1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
|
/*
% Copyright (C) 2003-2023 GraphicsMagick Group
% Copyright (C) 2002 ImageMagick Studio
% Copyright 1991-1999 E. I. du Pont de Nemours and Company
%
% This program is covered by multiple licenses, which are described in
% Copyright.txt. You should have received a copy of Copyright.txt with this
% package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% JJJJJ PPPP EEEEE GGGG %
% J P P E G %
% J PPPP EEE G GG %
% J J P E G G %
% JJJ P EEEEE GGG %
% %
% %
% Read/Write JPEG Image Format. %
% %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This software is based in part on the work of the Independent JPEG Group.
% See ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz for copyright and
% licensing restrictions. Blob support contributed by Glenn Randers-Pehrson.
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/analyze.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/colormap.h"
#include "magick/enum_strings.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/monitor.h"
#include "magick/pixel_cache.h"
#include "magick/profile.h"
#include "magick/resource.h"
#include "magick/utility.h"
/*
Forward declarations.
*/
static unsigned int
WriteJPEGImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J P E G %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method IsJPEG returns True if the image format type, identified by the
% magick string, is JPEG.
%
% The format of the IsJPEG method is:
%
% unsigned int IsJPEG(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o status: Method IsJPEG returns True if the image format type is JPEG.
%
% o magick: This string is generally the first few bytes of an image file
% or blob.
%
% o length: Specifies the length of the magick string.
%
%
*/
static unsigned int IsJPEG(const unsigned char *magick,const size_t length)
{
if (length < 3)
return(False);
if (memcmp(magick,"\377\330\377",3) == 0)
return(True);
return(False);
}
#if defined(HasJPEG)
#define JPEG_INTERNAL_OPTIONS
/*
Avoid conflicting typedef for INT32
*/
#if defined(__MINGW32__)
# define XMD_H 1
#endif
/*
The JPEG headers have the annoying problem that they define
HAVE_STDLIB_H and we do too. The define isn't actually used
so just undef it.
*/
#undef HAVE_STDLIB_H
#include <setjmp.h>
#include "jpeglib.h"
#include "jerror.h"
/*
Define declarations.
*/
#define ICC_MARKER (JPEG_APP0+2)
#define IPTC_MARKER (JPEG_APP0+13)
#define XML_MARKER (JPEG_APP0+1)
#define MaxBufferExtent 8192
#define JPEG_MARKER_MAX_SIZE 65533
#define MaxWarningCount 3
/*
Set to 1 to use libjpeg callback for progress indication. This is
not enabled by default since it outputs multiple progress
indications, which may be confusing for the user. However, the
libjpeg method provides more detailed progress.
*/
#define USE_LIBJPEG_PROGRESS 0 /* Use libjpeg callback for progress */
static const char xmp_std_header[]="http://ns.adobe.com/xap/1.0/";
typedef struct _DestinationManager
{
struct jpeg_destination_mgr
manager;
Image
*image;
JOCTET
*buffer;
} DestinationManager;
typedef struct _MagickClientData
{
Image
*image;
MagickBool
ping;
MagickBool
completed;
jmp_buf
error_recovery;
unsigned int
max_warning_count;
magick_uint16_t
warning_counts[JMSG_LASTMSGCODE];
int
max_scan_number;
ProfileInfo
profiles[16];
unsigned char
buffer[65537+200];
} MagickClientData;
typedef struct _SourceManager
{
struct jpeg_source_mgr
manager;
Image
*image;
JOCTET
*buffer;
boolean
start_of_blob;
} SourceManager;
static MagickClientData *AllocateMagickClientData(void)
{
MagickClientData
*client_data;
client_data = MagickAllocateClearedMemory(MagickClientData *, sizeof(MagickClientData));
return client_data;
}
static MagickClientData *FreeMagickClientData(MagickClientData *client_data)
{
unsigned int
i;
/* Free profiles data */
if (client_data != (MagickClientData *) NULL)
{
for (i=0 ; i < ArraySize(client_data->profiles); i++)
{
MagickFreeMemory(client_data->profiles[i].name);
MagickFreeResourceLimitedMemory(client_data->profiles[i].info);
}
MagickFreeMemory(client_data);
}
return client_data;
}
/* Append named profile to profiles in client data. */
static MagickPassFail
AppendProfile(MagickClientData *client_data,
const char *name,
const unsigned char *profile_chunk,
const size_t chunk_length)
{
unsigned int
i;
/*
If entry with matching name is found, then add/append data to
profile 'info' and update profile length
*/
for (i=0 ; i < ArraySize(client_data->profiles); i++)
{
ProfileInfo *profile=&client_data->profiles[i];
if (!profile->name)
break;
if (strcmp(profile->name,name) == 0)
{
const size_t new_length = profile->length+chunk_length;
unsigned char *info = MagickReallocateResourceLimitedMemory(unsigned char *,
profile->info,new_length);
if (info != (unsigned char *) NULL)
{
profile->info = info;
(void) memcpy(profile->info+profile->length,profile_chunk,chunk_length);
profile->length=new_length;
return MagickPass;
}
}
}
/*
If no matching entry, then find unallocated entry, add data to
profile 'info' and update profile length
*/
for (i=0 ; i < ArraySize(client_data->profiles); i++)
{
ProfileInfo *profile=&client_data->profiles[i];
if (profile->name)
continue;
profile->name=AcquireString(name);
profile->info=MagickAllocateResourceLimitedMemory(unsigned char*,chunk_length);
if (!profile->name || !profile->info)
{
MagickFreeMemory(profile->name);
MagickFreeResourceLimitedMemory(profile->info);
break;
}
(void) memcpy(profile->info,profile_chunk,chunk_length);
profile->length=chunk_length;
return MagickPass;
}
return MagickFail;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method ReadJPEGImage reads a JPEG image file and returns it. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadJPEGImage method is:
%
% Image *ReadJPEGImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Method ReadJPEGImage returns a pointer to the image after
% reading. A null image is returned if there is a memory shortage or
% if the image cannot be read.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
%
*/
/*
Format a libjpeg warning or trace event while decoding. Warnings
are converted to GraphicsMagick warning exceptions while traces are
optionally logged.
JPEG message codes range from 0 to JMSG_LASTMSGCODE
*/
static void JPEGDecodeMessageHandler(j_common_ptr jpeg_info,int msg_level)
{
char
message[JMSG_LENGTH_MAX];
struct jpeg_error_mgr
*err;
MagickClientData
*client_data;
Image
*image;
message[0]='\0';
err=jpeg_info->err;
client_data=(MagickClientData *) jpeg_info->client_data;
image=client_data->image;
/* msg_level is -1 for warnings, 0 and up for trace messages. */
if (msg_level < 0)
{
unsigned int strikes = 0;
/* A warning */
(err->format_message)(jpeg_info,message);
if ((err->msg_code >= 0) &&
((size_t) err->msg_code < ArraySize(client_data->warning_counts)))
{
client_data->warning_counts[err->msg_code]++;
strikes=client_data->warning_counts[err->msg_code];
}
if (image->logging)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Warning[%u]: \"%s\""
" (code=%d "
"parms=0x%02x,0x%02x,"
"0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x)",
image->filename,
strikes,
message,err->msg_code,
err->msg_parm.i[0], err->msg_parm.i[1],
err->msg_parm.i[2], err->msg_parm.i[3],
err->msg_parm.i[4], err->msg_parm.i[5],
err->msg_parm.i[6], err->msg_parm.i[7]);
}
if (strikes > client_data->max_warning_count)
{
ThrowException2(&image->exception,CorruptImageError,(char *) message,
image->filename);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Longjmp error recovery");
longjmp(client_data->error_recovery,1);
SignalHandlerExit(EXIT_FAILURE);
}
if ((err->num_warnings == 0) ||
(err->trace_level >= 3))
ThrowException2(&image->exception,CorruptImageWarning,message,
image->filename);
/* JWRN_JPEG_EOF - "Premature end of JPEG file" */
err->num_warnings++;
return /* False */;
}
else
{
/* A trace message */
if ((image->logging) && (msg_level >= err->trace_level))
{
(err->format_message)(jpeg_info,message);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Trace: \"%s\"",image->filename,
message);
}
}
return /* True */;
}
static void JPEGDecodeProgressMonitor(j_common_ptr cinfo)
{
MagickClientData *client_data = (MagickClientData *) cinfo->client_data;
Image *image = client_data->image;
const int max_scan_number = client_data->max_scan_number;
#if USE_LIBJPEG_PROGRESS
{
struct jpeg_progress_mgr *p = cinfo->progress;
#if 0
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Progress: pass_counter=%ld, pass_limit=%ld,"
" completed_passes=%d, total_passes=%d, filename=%s",
p->pass_counter, p->pass_limit,
p->completed_passes, p->total_passes, image->filename);
#endif
if (QuantumTick(p->pass_counter,p->pass_limit))
if (!MagickMonitorFormatted(p->pass_counter,p->pass_limit,&image->exception,
"[%s] Loading image: %lux%lu (pass %d of %d)... ",
image->filename,
image->columns,image->rows,
p->completed_passes+1, p->total_passes))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quitting (longjmp) due to progress monitor");
longjmp(client_data->error_recovery,1);
SignalHandlerExit(EXIT_FAILURE);
}
}
#endif /* USE_LIBJPEG_PROGRESS */
if (cinfo->is_decompressor)
{
int scan_no = ((j_decompress_ptr) cinfo)->input_scan_number;
if (scan_no > max_scan_number)
{
char message[MaxTextExtent];
FormatString(message,"Scan number %d exceeds maximum scans (%d)",
scan_no, max_scan_number);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s", message);
ThrowException2(&image->exception,CorruptImageError,(char *) message,
image->filename);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Longjmp error recovery");
longjmp(client_data->error_recovery,1);
SignalHandlerExit(EXIT_FAILURE);
}
}
}
static boolean FillInputBuffer(j_decompress_ptr cinfo)
{
SourceManager
*source;
source=(SourceManager *) cinfo->src;
source->manager.bytes_in_buffer=
ReadBlob(source->image,MaxBufferExtent,(char *) source->buffer);
if (source->manager.bytes_in_buffer == 0)
{
if (source->start_of_blob)
ERREXIT(cinfo,JERR_INPUT_EMPTY);
WARNMS(cinfo,JWRN_JPEG_EOF);
source->buffer[0]=(JOCTET) 0xff;
source->buffer[1]=(JOCTET) JPEG_EOI;
source->manager.bytes_in_buffer=2;
}
source->manager.next_input_byte=source->buffer;
source->start_of_blob=FALSE;
return(TRUE);
}
static int GetCharacter(j_decompress_ptr jpeg_info)
{
if (jpeg_info->src->bytes_in_buffer == 0)
if ((!((*jpeg_info->src->fill_input_buffer)(jpeg_info))) ||
(jpeg_info->src->bytes_in_buffer == 0))
return EOF;
jpeg_info->src->bytes_in_buffer--;
return(GETJOCTET(*jpeg_info->src->next_input_byte++));
}
static void InitializeSource(j_decompress_ptr cinfo)
{
SourceManager
*source;
source=(SourceManager *) cinfo->src;
source->start_of_blob=TRUE;
}
/*
Format and report a libjpeg error event. Errors are reported via a
GraphicsMagick error exception. The function terminates with
longjmp() so it never returns to the caller.
*/
static void JPEGErrorHandler(j_common_ptr jpeg_info) MAGICK_FUNC_NORETURN;
static void JPEGErrorHandler(j_common_ptr jpeg_info)
{
char
message[JMSG_LENGTH_MAX];
struct jpeg_error_mgr
*err;
MagickClientData
*client_data;
Image
*image;
message[0]='\0';
err=jpeg_info->err;
client_data=(MagickClientData *) jpeg_info->client_data;
image=client_data->image;
(err->format_message)(jpeg_info,message);
if (image->logging)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Error: \"%s\" (code=%d, "
"parms=0x%02x,0x%02x,"
"0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x)",
image->filename,message,err->msg_code,
err->msg_parm.i[0], err->msg_parm.i[1],
err->msg_parm.i[2], err->msg_parm.i[3],
err->msg_parm.i[4], err->msg_parm.i[5],
err->msg_parm.i[6], err->msg_parm.i[7]);
}
if (client_data->completed)
ThrowException2(&image->exception,CoderWarning,(char *) message,
image->filename);
else
ThrowException2(&image->exception,CoderError,(char *) message,
image->filename);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Longjmp error recovery");
longjmp(client_data->error_recovery,1);
SignalHandlerExit(EXIT_FAILURE);
}
#define GetProfileLength(jpeg_info, length) \
do { \
int \
_c; \
\
if (((_c = GetCharacter(jpeg_info)) != EOF) && (_c >= 0)) \
{ \
length=_c*256; \
if (((_c = GetCharacter(jpeg_info)) != EOF) && (_c >= 0)) \
length+=_c; \
else \
length=0; \
} \
else \
{ \
length=0; \
} \
} while(0)
static boolean ReadComment(j_decompress_ptr jpeg_info)
{
char
*comment;
MagickClientData
*client_data;
Image
*image;
register char
*p;
size_t
i,
length;
int
c;
/*
Determine length of comment.
*/
client_data=(MagickClientData *) jpeg_info->client_data;
image=client_data->image;
GetProfileLength(jpeg_info, length);
if (length <= 2)
return(True);
length-=2;
comment=(char *) client_data->buffer;
/*
Read comment.
*/
p=comment;
for (i=0; i < length; i++)
{
if ((c=GetCharacter(jpeg_info)) == EOF)
break;
*p=c;
p++;
}
*p='\0';
(void) SetImageAttribute(image,"comment",comment);
return(True);
}
static boolean ReadGenericProfile(j_decompress_ptr jpeg_info)
{
MagickClientData
*client_data;
size_t
header_length=0,
length;
register size_t
i;
char
profile_name[MaxTextExtent];
unsigned char
*profile;
int
c,
marker;
/*
Determine length of generic profile.
*/
GetProfileLength(jpeg_info, length);
if (length <= 2)
return(True);
length-=2;
/*
jpeg_info->unread_marker ('int') is either zero or the code of a
JPEG marker that has been read from the data source, but has not
yet been processed. The underlying type for a marker appears to
be UINT8 (JPEG_COM, or JPEG_APP0+n).
Unexpected markers are prevented due to registering for specific
markers we are interested in via jpeg_set_marker_processor().
#define JPEG_APP0 0xE0
#define JPEG_COM 0xFE
#define ICC_MARKER (JPEG_APP0+2)
#define IPTC_MARKER (JPEG_APP0+13)
#define XML_MARKER (JPEG_APP0+1)
*/
marker=jpeg_info->unread_marker-JPEG_APP0;
/*
Compute generic profile name.
*/
FormatString(profile_name,"APP%d",marker);
/*
Obtain Image.
*/
client_data=(MagickClientData *) jpeg_info->client_data;
/*
Copy profile from JPEG to allocated memory.
*/
profile=client_data->buffer;
for (i=0 ; i < length ; i++)
{
if ((c=GetCharacter(jpeg_info)) != EOF)
profile[i]=c;
else
break;
}
if (i != length)
return True;
/*
Detect EXIF and XMP profiles.
*/
if ((marker == 1) && (length > 4) &&
(strncmp((char *) profile,"Exif",4) == 0))
{
FormatString(profile_name,"EXIF");
}
else if (((marker == 1) && (length > strlen(xmp_std_header)+1)) &&
(memcmp(profile, xmp_std_header, strlen(xmp_std_header)+1) == 0))
{
/*
XMP is required to fit in one 64KB chunk. Strip off its JPEG
namespace header.
*/
header_length=strlen(xmp_std_header)+1;
FormatString((char *) profile_name,"XMP");
}
/*
Store profile in Image.
*/
(void) AppendProfile(client_data,profile_name,profile+header_length,
length-header_length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: %s, header %" MAGICK_SIZE_T_F "u bytes, "
"data %" MAGICK_SIZE_T_F "u bytes",
profile_name, (MAGICK_SIZE_T) header_length,
(MAGICK_SIZE_T) length-header_length);
return (True);
}
static boolean ReadICCProfile(j_decompress_ptr jpeg_info)
{
char
magick[12];
MagickClientData
*client_data;
unsigned char
*profile;
long
length;
register long
i;
int
c;
/*
Determine length of color profile.
*/
GetProfileLength(jpeg_info, length);
length-=2;
if (length <= 14)
{
while (--length >= 0)
(void) GetCharacter(jpeg_info);
return(True);
}
for (i=0; i < 12; i++)
magick[i]=GetCharacter(jpeg_info);
if (LocaleCompare(magick,"ICC_PROFILE") != 0)
{
/*
Not a ICC profile, return.
*/
for (i=0; i < length-12; i++)
(void) GetCharacter(jpeg_info);
return(True);
}
(void) GetCharacter(jpeg_info); /* id */
(void) GetCharacter(jpeg_info); /* markers */
length-=14;
client_data=(MagickClientData *) jpeg_info->client_data;
/*
Read color profile.
*/
profile=client_data->buffer;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"ICC profile chunk: %ld bytes",
length);
for (i=0 ; i < length; i++)
{
if ((c=GetCharacter(jpeg_info)) != EOF)
profile[i]=c;
else
break;
}
if (i == length)
(void) AppendProfile(client_data,"ICM",profile,length);
return(True);
}
static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)
{
MagickClientData
*client_data;
Image
*image;
long
length,
tag_length;
unsigned char
*profile;
register long
i;
#ifdef GET_ONLY_IPTC_DATA
unsigned char
tag[MaxTextExtent];
#endif
int
c;
/*
Determine length of binary data stored here.
*/
GetProfileLength(jpeg_info, length);
length-=2;
if (length <= 0)
return(True);
tag_length=0;
#ifdef GET_ONLY_IPTC_DATA
*tag='\0';
#endif
client_data=(MagickClientData *) jpeg_info->client_data;
image=client_data->image;
#ifdef GET_ONLY_IPTC_DATA
/*
Find the beginning of the IPTC portion of the binary data.
*/
for (*tag='\0'; length > 0; )
{
*tag=GetCharacter(jpeg_info);
*(tag+1)=GetCharacter(jpeg_info);
length-=2;
if ((*tag == 0x1c) && (*(tag+1) == 0x02))
break;
}
tag_length=2;
#else
/*
Validate that this was written as a Photoshop resource format slug.
*/
{
char
magick[MaxTextExtent];
for (i=0; i < 10 && i < length; i++)
magick[i]=GetCharacter(jpeg_info);
magick[i]='\0';
length-=i;
if (LocaleCompare(magick,"Photoshop ") != 0)
{
/*
Not a ICC profile, return.
*/
for (i=0; i < length; i++)
(void) GetCharacter(jpeg_info);
return(True);
}
}
/*
Remove the version number.
*/
for (i=0; i < 4 && i < length; i++)
(void) GetCharacter(jpeg_info);
length-=i;
tag_length=0;
#endif
if (length <= 0)
return(True);
if ((size_t) length+tag_length > sizeof(client_data->buffer))
ThrowBinaryException(ResourceLimitError,MemoryAllocationFailed,
(char *) NULL);
profile=client_data->buffer;
/*
Read the payload of this binary data.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: IPTC, %ld bytes",
length);
for (i=0; i < length; i++)
{
if ((c=GetCharacter(jpeg_info)) != EOF)
profile[i]=c;
else
break;
}
if (i == length)
(void) AppendProfile(client_data,"IPTC",profile,length);
return(True);
}
static void SkipInputData(j_decompress_ptr cinfo,long number_bytes)
{
SourceManager
*source;
if (number_bytes <= 0)
return;
source=(SourceManager *) cinfo->src;
while (number_bytes > (long) source->manager.bytes_in_buffer)
{
number_bytes-=(long) source->manager.bytes_in_buffer;
(void) FillInputBuffer(cinfo);
}
source->manager.next_input_byte+=(size_t) number_bytes;
source->manager.bytes_in_buffer-=(size_t) number_bytes;
}
static void TerminateSource(j_decompress_ptr cinfo)
{
(void) cinfo;
}
static void JPEGSourceManager(j_decompress_ptr cinfo,Image *image)
{
SourceManager
*source;
cinfo->src=(struct jpeg_source_mgr *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,sizeof(SourceManager));
source=(SourceManager *) cinfo->src;
source->buffer=(JOCTET *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,MaxBufferExtent*sizeof(JOCTET));
source=(SourceManager *) cinfo->src;
source->manager.init_source=InitializeSource;
source->manager.fill_input_buffer=FillInputBuffer;
source->manager.skip_input_data=SkipInputData;
source->manager.resync_to_restart=jpeg_resync_to_restart;
source->manager.term_source=TerminateSource;
source->manager.bytes_in_buffer=0;
source->manager.next_input_byte=NULL;
source->image=image;
}
/*
Estimate the IJG quality factor used when saving the file.
*/
static int
EstimateJPEGQuality(const struct jpeg_decompress_struct *jpeg_info,
Image *image)
{
int
save_quality;
register long
i;
save_quality=0;
#if !defined(LIBJPEG_TURBO_VERSION_NUMBER) && defined(D_LOSSLESS_SUPPORTED)
if (image->compression==LosslessJPEGCompression)
{
save_quality=100;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: 100 (lossless)");
}
else
#endif
{
int
hashval,
sum;
/*
Log the JPEG quality that was used for compression.
*/
sum=0;
for (i=0; i < NUM_QUANT_TBLS; i++)
{
int
j;
if (jpeg_info->quant_tbl_ptrs[i] != NULL)
for (j=0; j < DCTSIZE2; j++)
{
UINT16 *c;
c=jpeg_info->quant_tbl_ptrs[i]->quantval;
sum+=c[j];
}
}
if ((jpeg_info->quant_tbl_ptrs[0] != NULL) &&
(jpeg_info->quant_tbl_ptrs[1] != NULL))
{
int
hash[] =
{
1020, 1015, 932, 848, 780, 735, 702, 679, 660, 645,
632, 623, 613, 607, 600, 594, 589, 585, 581, 571,
555, 542, 529, 514, 494, 474, 457, 439, 424, 410,
397, 386, 373, 364, 351, 341, 334, 324, 317, 309,
299, 294, 287, 279, 274, 267, 262, 257, 251, 247,
243, 237, 232, 227, 222, 217, 213, 207, 202, 198,
192, 188, 183, 177, 173, 168, 163, 157, 153, 148,
143, 139, 132, 128, 125, 119, 115, 108, 104, 99,
94, 90, 84, 79, 74, 70, 64, 59, 55, 49,
45, 40, 34, 30, 25, 20, 15, 11, 6, 4,
0
};
int
sums[] =
{
32640,32635,32266,31495,30665,29804,29146,28599,28104,27670,
27225,26725,26210,25716,25240,24789,24373,23946,23572,22846,
21801,20842,19949,19121,18386,17651,16998,16349,15800,15247,
14783,14321,13859,13535,13081,12702,12423,12056,11779,11513,
11135,10955,10676,10392,10208, 9928, 9747, 9564, 9369, 9193,
9017, 8822, 8639, 8458, 8270, 8084, 7896, 7710, 7527, 7347,
7156, 6977, 6788, 6607, 6422, 6236, 6054, 5867, 5684, 5495,
5305, 5128, 4945, 4751, 4638, 4442, 4248, 4065, 3888, 3698,
3509, 3326, 3139, 2957, 2775, 2586, 2405, 2216, 2037, 1846,
1666, 1483, 1297, 1109, 927, 735, 554, 375, 201, 128,
0
};
hashval=(jpeg_info->quant_tbl_ptrs[0]->quantval[2]+
jpeg_info->quant_tbl_ptrs[0]->quantval[53]+
jpeg_info->quant_tbl_ptrs[1]->quantval[0]+
jpeg_info->quant_tbl_ptrs[1]->quantval[DCTSIZE2-1]);
for (i=0; i < 100; i++)
{
if ((hashval >= hash[i]) || (sum >= sums[i]))
{
save_quality=i+1;
if (image->logging)
{
if ((hashval > hash[i]) || (sum > sums[i]))
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: %d (approximate)",
save_quality);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: %d",save_quality);
}
break;
}
}
}
else
if (jpeg_info->quant_tbl_ptrs[0] != NULL)
{
int
bwhash[] =
{
510, 505, 422, 380, 355, 338, 326, 318, 311, 305,
300, 297, 293, 291, 288, 286, 284, 283, 281, 280,
279, 278, 277, 273, 262, 251, 243, 233, 225, 218,
211, 205, 198, 193, 186, 181, 177, 172, 168, 164,
158, 156, 152, 148, 145, 142, 139, 136, 133, 131,
129, 126, 123, 120, 118, 115, 113, 110, 107, 105,
102, 100, 97, 94, 92, 89, 87, 83, 81, 79,
76, 74, 70, 68, 66, 63, 61, 57, 55, 52,
50, 48, 44, 42, 39, 37, 34, 31, 29, 26,
24, 21, 18, 16, 13, 11, 8, 6, 3, 2,
0
};
int
bwsum[] =
{
16320,16315,15946,15277,14655,14073,13623,13230,12859,12560,
12240,11861,11456,11081,10714,10360,10027, 9679, 9368, 9056,
8680, 8331, 7995, 7668, 7376, 7084, 6823, 6562, 6345, 6125,
5939, 5756, 5571, 5421, 5240, 5086, 4976, 4829, 4719, 4616,
4463, 4393, 4280, 4166, 4092, 3980, 3909, 3835, 3755, 3688,
3621, 3541, 3467, 3396, 3323, 3247, 3170, 3096, 3021, 2952,
2874, 2804, 2727, 2657, 2583, 2509, 2437, 2362, 2290, 2211,
2136, 2068, 1996, 1915, 1858, 1773, 1692, 1620, 1552, 1477,
1398, 1326, 1251, 1179, 1109, 1031, 961, 884, 814, 736,
667, 592, 518, 441, 369, 292, 221, 151, 86, 64,
0
};
hashval=(jpeg_info->quant_tbl_ptrs[0]->quantval[2]+
jpeg_info->quant_tbl_ptrs[0]->quantval[53]);
for (i=0; i < 100; i++)
{
if ((hashval >= bwhash[i]) || (sum >= bwsum[i]))
{
save_quality=i+1;
if (image->logging)
{
if ((hashval > bwhash[i]) || (sum > bwsum[i]))
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: %ld (approximate)",
i+1);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quality: %ld",i+1);
}
break;
}
}
}
}
return save_quality;
}
/*
Format JPEG color space to a string.
*/
static void
FormatJPEGColorSpace(const J_COLOR_SPACE colorspace,
char *colorspace_name)
{
const char
*s = NULL;
switch (colorspace)
{
default:
case JCS_UNKNOWN:
s = "UNKNOWN";
break;
case JCS_GRAYSCALE:
s = "GRAYSCALE";
break;
case JCS_RGB:
s = "RGB";
break;
case JCS_YCbCr:
s = "YCbCr";
break;
case JCS_CMYK:
s = "CMYK";
break;
case JCS_YCCK:
s = "YCCK";
break;
}
(void) strlcpy(colorspace_name,s,MaxTextExtent);
}
/*
Format JPEG sampling factors to a string.
*/
static void
FormatJPEGSamplingFactors(const struct jpeg_decompress_struct *jpeg_info,
char *sampling_factors)
{
switch (jpeg_info->out_color_space)
{
case JCS_CMYK:
{
(void) FormatString(sampling_factors,"%dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor,
jpeg_info->comp_info[3].h_samp_factor,
jpeg_info->comp_info[3].v_samp_factor);
break;
}
case JCS_GRAYSCALE:
{
(void) FormatString(sampling_factors,"%dx%d",
jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor);
break;
}
case JCS_RGB:
{
(void) FormatString(sampling_factors,"%dx%d,%dx%d,%dx%d",
jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor);
break;
}
default:
{
(void) FormatString(sampling_factors,"%dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info->comp_info[0].h_samp_factor,
jpeg_info->comp_info[0].v_samp_factor,
jpeg_info->comp_info[1].h_samp_factor,
jpeg_info->comp_info[1].v_samp_factor,
jpeg_info->comp_info[2].h_samp_factor,
jpeg_info->comp_info[2].v_samp_factor,
jpeg_info->comp_info[3].h_samp_factor,
jpeg_info->comp_info[3].v_samp_factor);
break;
}
}
}
static MagickBool
IsITUFax(const Image* image)
{
size_t
profile_length;
const unsigned char
*profile;
MagickBool
status;
status=MagickFalse;
if ((profile=GetImageProfile(image,"APP1",&profile_length)) &&
(profile_length >= 5))
{
if (profile[0] == 0x47 &&
profile[1] == 0x33 &&
profile[2] == 0x46 &&
profile[3] == 0x41 &&
profile[4] == 0x58)
status=MagickTrue;
}
return status;
}
#define ThrowJPEGReaderException(code_,reason_,image_) \
{ \
client_data=FreeMagickClientData(client_data); \
ThrowReaderException(code_,reason_,image_); \
}
static Image *ReadJPEGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickClientData
*client_data = (MagickClientData *) NULL;
IndexPacket
index;
long
y;
JSAMPLE
*jpeg_pixels;
JSAMPROW
scanline[1];
const char
*value;
register unsigned long
i;
struct jpeg_error_mgr
jpeg_error;
struct jpeg_progress_mgr
jpeg_progress;
struct jpeg_decompress_struct
jpeg_info;
register JSAMPLE
*p;
MagickPassFail
status;
unsigned long
number_pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AllocateImage(image_info);
if (image == (Image *) NULL)
ThrowJPEGReaderException(ResourceLimitError,MemoryAllocationFailed,image);
client_data=AllocateMagickClientData();
if (client_data == (MagickClientData *) NULL)
ThrowJPEGReaderException(ResourceLimitError,MemoryAllocationFailed,image);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFail)
ThrowJPEGReaderException(FileOpenError,UnableToOpenFile,image);
if (BlobIsSeekable(image) && GetBlobSize(image) < 107)
ThrowJPEGReaderException(CorruptImageError,InsufficientImageDataInFile,image);
/*
Initialize structures.
*/
(void) memset(&jpeg_progress,0,sizeof(jpeg_progress));
(void) memset(&jpeg_info,0,sizeof(jpeg_info));
(void) memset(&jpeg_error,0,sizeof(jpeg_error));
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=/*(void (*)(j_common_ptr,int))*/ JPEGDecodeMessageHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
jpeg_pixels=(JSAMPLE *) NULL;
client_data->image=image;
client_data->ping=image_info->ping;
client_data->max_scan_number=100;
client_data->max_warning_count=MaxWarningCount;
/*
Allow the user to set how many warnings of any given type are
allowed before promotion of the warning to a hard error.
*/
if ((value=AccessDefinition(image_info,"jpeg","max-warnings")))
client_data->max_warning_count=strtol(value,(char **) NULL, 10);
/*
Set initial longjmp based error handler.
*/
if (setjmp(client_data->error_recovery) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Setjmp return from longjmp!");
jpeg_destroy_decompress(&jpeg_info);
GetImageException(image,exception);
client_data=FreeMagickClientData(client_data);
CloseBlob(image);
if (exception->severity < ErrorException)
return(image);
DestroyImage(image);
return((Image *) NULL);
}
jpeg_info.client_data=(void *) client_data;
jpeg_create_decompress(&jpeg_info);
/*
Specify a memory limit for libjpeg which is 1/5th the absolute
limit. Don't actually consume the resource since we don't know
how much libjpeg will actually consume.
*/
jpeg_info.mem->max_memory_to_use=(long) (GetMagickResourceLimit(MemoryResource) -
GetMagickResource(MemoryResource))/5U;
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Memory capped to %ld bytes", jpeg_info.mem->max_memory_to_use);
/*
Register our progress monitor
*/
jpeg_progress.progress_monitor=(void (*)(j_common_ptr)) JPEGDecodeProgressMonitor;
jpeg_info.progress=&jpeg_progress;
JPEGSourceManager(&jpeg_info,image);
jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment);
jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile);
jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile);
for (i=1; i < 16; i++)
if ((i != 2) && (i != 13) && (i != 14))
jpeg_set_marker_processor(&jpeg_info,JPEG_APP0+i,ReadGenericProfile);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Reading JPEG header...");
i=jpeg_read_header(&jpeg_info,True);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Done with reading JPEG header");
if (IsITUFax(image))
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image colorspace set to LAB");
image->colorspace=LABColorspace;
jpeg_info.out_color_space = JCS_YCbCr;
}
else if (jpeg_info.out_color_space == JCS_CMYK)
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image colorspace set to CMYK");
image->colorspace=CMYKColorspace;
}
if (jpeg_info.saw_JFIF_marker)
{
if ((jpeg_info.X_density != 1U) && (jpeg_info.Y_density != 1U))
{
/*
Set image resolution.
*/
image->x_resolution=jpeg_info.X_density;
image->y_resolution=jpeg_info.Y_density;
if (jpeg_info.density_unit == 1)
image->units=PixelsPerInchResolution;
if (jpeg_info.density_unit == 2)
image->units=PixelsPerCentimeterResolution;
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image resolution set to %gx%g %s",
image->x_resolution,
image->y_resolution,
ResolutionTypeToString(image->units));
}
}
/*
If the desired image size is pre-set (e.g. by using -size), then
let the JPEG library subsample for us.
*/
number_pixels=image->columns*image->rows;
if (number_pixels != 0)
{
double
scale_factor;
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Requested Geometry: %lux%lu",
image->columns,image->rows);
jpeg_calc_output_dimensions(&jpeg_info);
image->magick_columns=jpeg_info.output_width;
image->magick_rows=jpeg_info.output_height;
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"magick_geometry=%lux%lu",
image->magick_columns, image->magick_rows);
scale_factor=(double) jpeg_info.output_width/image->columns;
if (scale_factor > ((double) jpeg_info.output_height/image->rows))
scale_factor=(double) jpeg_info.output_height/image->rows;
jpeg_info.scale_denom *=(unsigned int) scale_factor;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Original Geometry: %lux%lu,"
" Scale_factor: %ld (scale_num=%d,"
" scale_denom=%d)",
image->magick_columns, image->magick_rows,
(long) scale_factor,
jpeg_info.scale_num,jpeg_info.scale_denom);
}
#if 0
/*
The subrange parameter is set by the filename array syntax similar
to the way an image is requested from a list (e.g. myfile.jpg[2]).
Argument values other than zero are used to scale the image down
by that factor. IJG JPEG 62 (6b) supports values of 1,2,4, or 8
while IJG JPEG 70 supports all values in the range 1-16. This
feature is useful in case you want to view all of the images with
a consistent ratio. Unfortunately, it uses the same syntax as
list member access.
*/
else if (image_info->subrange != 0)
{
jpeg_info.scale_denom *=(int) image_info->subrange;
jpeg_calc_output_dimensions(&jpeg_info);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Requested Scaling Denominator: %d "
"(scale_num=%d, scale_denom=%d)",
(int) image_info->subrange,
jpeg_info.scale_num,jpeg_info.scale_denom);
}
#endif
#if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED)
#if !defined(LIBJPEG_TURBO_VERSION_NUMBER) && defined(D_LOSSLESS_SUPPORTED)
/* This code is based on a patch to IJG JPEG 6b, or somesuch. Standard
library does not have a 'process' member. */
image->interlace=
jpeg_info.process == JPROC_PROGRESSIVE ? LineInterlace : NoInterlace;
image->compression=jpeg_info.process == JPROC_LOSSLESS ?
LosslessJPEGCompression : JPEGCompression;
if (jpeg_info.data_precision > 8)
MagickError2(OptionError,
"12-bit JPEG not supported. Reducing pixel data to 8 bits",
(char *) NULL);
#else
image->interlace=jpeg_info.progressive_mode ? LineInterlace : NoInterlace;
image->compression=JPEGCompression;
#endif
#else
image->compression=JPEGCompression;
image->interlace=LineInterlace;
#endif
/*
Allow the user to enable/disable block smoothing.
*/
if ((value=AccessDefinition(image_info,"jpeg","block-smoothing")))
{
if (LocaleCompare(value,"FALSE") == 0)
jpeg_info.do_block_smoothing=False;
else
jpeg_info.do_block_smoothing=True;
}
/*
Allow the user to select the DCT decoding algorithm.
*/
if ((value=AccessDefinition(image_info,"jpeg","dct-method")))
{
if (LocaleCompare(value,"ISLOW") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
else if (LocaleCompare(value,"IFAST") == 0)
jpeg_info.dct_method=JDCT_IFAST;
else if (LocaleCompare(value,"FLOAT") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
else if (LocaleCompare(value,"DEFAULT") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
else if (LocaleCompare(value,"FASTEST") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
}
/*
Allow the user to enable/disable fancy upsampling.
*/
if ((value=AccessDefinition(image_info,"jpeg","fancy-upsampling")))
{
if (LocaleCompare(value,"FALSE") == 0)
jpeg_info.do_fancy_upsampling=False;
else
jpeg_info.do_fancy_upsampling=True;
}
/*
Allow the user to adjust the maximum JPEG scan number
*/
if ((value=AccessDefinition(image_info,"jpeg","max-scan-number")))
{
client_data->max_scan_number=strtol(value,(char **) NULL, 10);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"JPEG max-scan-number set to %d",
client_data->max_scan_number);
}
jpeg_calc_output_dimensions(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
image->depth=Min(jpeg_info.data_precision,Min(16,QuantumDepth));
if (image->logging)
{
if (image->interlace == LineInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d",
(int) jpeg_info.data_precision);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Components: %d",
(int) jpeg_info.output_components);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d",
(int) jpeg_info.output_width,
(int) jpeg_info.output_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"DCT Method: %d",
jpeg_info.dct_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Fancy Upsampling: %s",
(jpeg_info.do_fancy_upsampling ? "true" : "false"));
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Block Smoothing: %s",
(jpeg_info.do_block_smoothing ? "true" : "false"));
}
if (CheckImagePixelLimits(image, exception) != MagickPass)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowJPEGReaderException(ResourceLimitError,ImagePixelLimitExceeded,image);
}
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Starting JPEG decompression...");
(void) jpeg_start_decompress(&jpeg_info);
image->columns=jpeg_info.output_width;
image->rows=jpeg_info.output_height;
{
char
attribute[MaxTextExtent];
/*
Estimate and retain JPEG properties as attributes.
*/
FormatString(attribute,"%d",EstimateJPEGQuality(&jpeg_info,image));
(void) SetImageAttribute(image,"JPEG-Quality",attribute);
FormatString(attribute,"%ld",(long)jpeg_info.out_color_space);
(void) SetImageAttribute(image,"JPEG-Colorspace",attribute);
FormatJPEGColorSpace(jpeg_info.out_color_space,attribute);
(void) SetImageAttribute(image,"JPEG-Colorspace-Name",attribute);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: %s (%d)", attribute,
jpeg_info.out_color_space);
FormatJPEGSamplingFactors(&jpeg_info,attribute);
(void) SetImageAttribute(image,"JPEG-Sampling-factors",attribute);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s", attribute);
}
image->depth=Min(jpeg_info.data_precision,Min(16,QuantumDepth));
if (jpeg_info.out_color_space == JCS_GRAYSCALE)
{
/*
Build colormap if we can
*/
unsigned long max_index = MaxValueGivenBits(image->depth);
if (max_index <= MaxMap)
if (!AllocateImageColormap(image,max_index+1LU))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowJPEGReaderException(ResourceLimitError,MemoryAllocationFailed,image);
}
}
/*
Store profiles in image.
*/
for (i=0 ; i < ArraySize(client_data->profiles); i++)
{
ProfileInfo *profile=&client_data->profiles[i];
if (!profile->name)
continue;
if (!profile->length)
continue;
if (!profile->info)
continue;
(void) SetImageProfile(image,profile->name,profile->info,profile->length);
}
if (image_info->ping)
{
jpeg_destroy_decompress(&jpeg_info);
client_data=FreeMagickClientData(client_data);
CloseBlob(image);
return(image);
}
if (CheckImagePixelLimits(image, exception) != MagickPass)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowJPEGReaderException(ResourceLimitError,ImagePixelLimitExceeded,image);
}
/*
Verify that we support the number of output components.
*/
if ((jpeg_info.output_components != 1) &&
(jpeg_info.output_components != 3) &&
(jpeg_info.output_components != 4))
{
jpeg_destroy_decompress(&jpeg_info);
ThrowJPEGReaderException(CoderError,ImageTypeNotSupported,image);
}
/*
Verify that file size is reasonable (if we can)
*/
if (BlobIsSeekable(image))
{
magick_off_t
blob_size;
double
ratio = 0;
blob_size = GetBlobSize(image);
if (blob_size != 0)
{
/* magick columns/rows are only set if size was specified! */
if (image->magick_columns && image->magick_rows)
ratio = ((double) image->magick_columns*image->magick_rows*
jpeg_info.output_components/blob_size);
else
ratio = ((double) image->columns*image->rows*
jpeg_info.output_components/blob_size);
}
/* All-black JPEG can produce tremendous compression ratios.
Allow for it. */
if ((blob_size == 0) || (ratio > 2500.0))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Unreasonable dimensions: "
"geometry=%lux%lu,"
" magick_geometry=%lux%lu,"
" components=%d, "
"blob size=%" MAGICK_OFF_F "d bytes, "
"compression ratio %g",
image->columns, image->rows,
image->magick_columns, image->magick_rows,
jpeg_info.output_components, blob_size, ratio);
jpeg_destroy_decompress(&jpeg_info);
ThrowJPEGReaderException(CorruptImageError,InsufficientImageDataInFile,image);
}
}
jpeg_pixels=MagickAllocateResourceLimitedClearedArray(JSAMPLE *,
jpeg_info.output_components,
MagickArraySize(image->columns,
sizeof(JSAMPLE)));
if (jpeg_pixels == (JSAMPLE *) NULL)
{
jpeg_destroy_decompress(&jpeg_info);
ThrowJPEGReaderException(ResourceLimitError,MemoryAllocationFailed,image);
}
/*
Extended longjmp-based error handler (with jpeg_pixels)
*/
if (setjmp(client_data->error_recovery) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Setjmp return from longjmp!");
/* Error handling code executed if longjmp was invoked */
MagickFreeResourceLimitedMemory(jpeg_pixels);
jpeg_destroy_decompress(&jpeg_info);
if (image->exception.severity > exception->severity)
CopyException(exception,&image->exception);
client_data=FreeMagickClientData(client_data);
CloseBlob(image);
number_pixels=image->columns*image->rows;
if (number_pixels != 0)
return(image);
DestroyImage(image);
return((Image *) NULL);
}
/*
Convert JPEG pixels to pixel packets.
*/
scanline[0]=(JSAMPROW) jpeg_pixels;
for (y=0; y < (long) image->rows; y++)
{
register IndexPacket
*indexes;
register long
x;
register PixelPacket
*q;
/*
Read scanlines. Stop at first serious error.
*/
if ((jpeg_read_scanlines(&jpeg_info,scanline,1) != 1) ||
(image->exception.severity >= ErrorException))
{
status=MagickFail;
break;
}
q=SetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
{
status=MagickFail;
break;
}
indexes=AccessMutableIndexes(image);
p=jpeg_pixels;
if (jpeg_info.output_components == 1)
{
if (image->storage_class == PseudoClass)
{
for (x=0; x < (long) image->columns; x++)
{
index=(IndexPacket) (GETJSAMPLE(*p++));
VerifyColormapIndex(image,index);
indexes[x]=index;
*q++=image->colormap[index];
}
}
else
{
if (jpeg_info.data_precision > 8)
{
unsigned int
scale_short;
scale_short=65535U/MaxValueGivenBits(jpeg_info.data_precision);
for (x=0; x < (long) image->columns; x++)
{
q->red=q->green=q->blue=ScaleShortToQuantum(scale_short*GETJSAMPLE(*p++));
q->opacity=OpaqueOpacity;
q++;
}
}
else
{
for (x=0; x < (long) image->columns; x++)
{
q->red=q->green=q->blue=ScaleCharToQuantum(GETJSAMPLE(*p++));
q->opacity=OpaqueOpacity;
q++;
}
}
}
}
else if ((jpeg_info.output_components == 3) ||
(jpeg_info.output_components == 4))
{
if (jpeg_info.data_precision > 8)
{
unsigned int
scale_short;
scale_short=65535U/MaxValueGivenBits(jpeg_info.data_precision);
for (x=0; x < (long) image->columns; x++)
{
q->red=ScaleShortToQuantum(scale_short*GETJSAMPLE(*p++));
q->green=ScaleShortToQuantum(scale_short*GETJSAMPLE(*p++));
q->blue=ScaleShortToQuantum(scale_short*GETJSAMPLE(*p++));
if (jpeg_info.output_components > 3)
q->opacity=ScaleShortToQuantum(scale_short*GETJSAMPLE(*p++));
else
q->opacity=OpaqueOpacity;
q++;
}
}
else
{
for (x=0; x < (long) image->columns; x++)
{
q->red=ScaleCharToQuantum(GETJSAMPLE(*p++));
q->green=ScaleCharToQuantum(GETJSAMPLE(*p++));
q->blue=ScaleCharToQuantum(GETJSAMPLE(*p++));
if (jpeg_info.output_components > 3)
q->opacity=ScaleCharToQuantum(GETJSAMPLE(*p++));
else
q->opacity=OpaqueOpacity;
q++;
}
}
if (image->colorspace == CMYKColorspace)
{
/*
CMYK pixels are inverted.
*/
q=AccessMutablePixels(image);
for (x=0; x < (long) image->columns; x++)
{
q->red=MaxRGB-q->red;
q->green=MaxRGB-q->green;
q->blue=MaxRGB-q->blue;
q->opacity=MaxRGB-q->opacity;
q++;
}
}
}
if (!SyncImagePixels(image))
{
status=MagickFail;
break;
}
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,exception,LoadImageText,
image->filename,
image->columns,image->rows))
{
status=MagickFail;
jpeg_abort_decompress(&jpeg_info);
break;
}
#endif /* !USE_LIBJPEG_PROGRESS */
}
/*
Free jpeg resources.
*/
if (status == MagickPass)
{
/*
jpeg_finish_decompress() may throw an exception while it is
finishing the remainder of the JPEG file. At this point we
have already decoded the image so we handle exceptions from
jpeg_finish_decompress() specially, mapping reported
exceptions as warnings rather than errors. We try using
jpeg_finish_decompress() and if it results in a longjmp(),
then we skip over it again.
*/
client_data->completed=MagickTrue;
if (setjmp(client_data->error_recovery) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Setjmp return from longjmp!");
}
else
{
(void) jpeg_finish_decompress(&jpeg_info);
}
}
jpeg_destroy_decompress(&jpeg_info);
MagickFreeResourceLimitedMemory(jpeg_pixels);
client_data=FreeMagickClientData(client_data);
CloseBlob(image);
/*
Retrieve image orientation from EXIF (if present) and store in
image.
EXIF orienation enumerations match TIFF enumerations, which happen
to match the enumeration values used by GraphicsMagick.
*/
if (status == MagickPass)
{
const ImageAttribute
*attribute;
attribute = GetImageAttribute(image,"EXIF:Orientation");
if ((attribute != (const ImageAttribute *) NULL) &&
(attribute->value != (char *) NULL))
{
int
orientation;
orientation=MagickAtoI(attribute->value);
if ((orientation > UndefinedOrientation) &&
(orientation <= LeftBottomOrientation))
image->orientation=(OrientationType) orientation;
}
}
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"return");
GetImageException(image,exception);
StopTimer(&image->timer);
return(image);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method RegisterJPEGImage adds attributes for the JPEG image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterJPEGImage method is:
%
% RegisterJPEGImage(void)
%
*/
ModuleExport void RegisterJPEGImage(void)
{
static const char
description[]="Joint Photographic Experts Group JFIF format";
#if defined(HasJPEG) && defined(JPEG_LIB_VERSION)
static const char
version[] = "IJG JPEG " DefineValueToString(JPEG_LIB_VERSION);
#define HAVE_JPEG_VERSION
#endif
MagickInfo
*entry;
MagickBool
thread_support;
#if defined(SETJMP_IS_THREAD_SAFE) && (SETJMP_IS_THREAD_SAFE)
thread_support=MagickTrue; /* libjpeg is thread safe */
#else
thread_support=MagickFalse; /* libjpeg is not thread safe */
#endif
entry=SetMagickInfo("JPEG");
entry->thread_support=thread_support;
#if defined(HasJPEG)
entry->decoder=(DecoderHandler) ReadJPEGImage;
entry->encoder=(EncoderHandler) WriteJPEGImage;
#endif
entry->magick=(MagickHandler) IsJPEG;
entry->adjoin=False;
entry->description=description;
#if defined(HAVE_JPEG_VERSION)
entry->version=version;
#endif
entry->module="JPEG";
entry->coder_class=PrimaryCoderClass;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPG");
entry->thread_support=thread_support;
#if defined(HasJPEG)
entry->decoder=(DecoderHandler) ReadJPEGImage;
entry->encoder=(EncoderHandler) WriteJPEGImage;
#endif
entry->adjoin=False;
entry->description=description;
#if defined(HAVE_JPEG_VERSION)
entry->version=version;
#endif
entry->module="JPEG";
entry->coder_class=PrimaryCoderClass;
(void) RegisterMagickInfo(entry);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method UnregisterJPEGImage removes format registrations made by the
% JPEG module from the list of supported formats.
%
% The format of the UnregisterJPEGImage method is:
%
% UnregisterJPEGImage(void)
%
*/
ModuleExport void UnregisterJPEGImage(void)
{
(void) UnregisterMagickInfo("JPEG");
(void) UnregisterMagickInfo("JPG");
}
#if defined(HasJPEG)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J P E G I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method WriteJPEGImage writes a JPEG image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the WriteJPEGImage method is:
%
% unsigned int WriteJPEGImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o status: Method WriteJPEGImage return True if the image is written.
% False is returned is there is of a memory shortage or if the image
% file cannot be opened for writing.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o jpeg_image: A pointer to an Image structure.
%
%
*/
static boolean EmptyOutputBuffer(j_compress_ptr cinfo)
{
DestinationManager
*destination;
destination=(DestinationManager *) cinfo->dest;
destination->manager.free_in_buffer=WriteBlob(destination->image,
MaxBufferExtent,(char *) destination->buffer);
if (destination->manager.free_in_buffer != MaxBufferExtent)
ERREXIT(cinfo,JERR_FILE_WRITE);
destination->manager.next_output_byte=destination->buffer;
return(TRUE);
}
static void InitializeDestination(j_compress_ptr cinfo)
{
DestinationManager
*destination;
destination=(DestinationManager *) cinfo->dest;
destination->buffer=(JOCTET *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,MaxBufferExtent*sizeof(JOCTET));
destination->manager.next_output_byte=destination->buffer;
destination->manager.free_in_buffer=MaxBufferExtent;
}
static void TerminateDestination(j_compress_ptr cinfo)
{
DestinationManager
*destination;
destination=(DestinationManager *) cinfo->dest;
if ((MaxBufferExtent-(int) destination->manager.free_in_buffer) > 0)
{
size_t
number_bytes;
number_bytes=WriteBlob(destination->image,MaxBufferExtent-
destination->manager.free_in_buffer,(char *) destination->buffer);
if (number_bytes != (MaxBufferExtent-destination->manager.free_in_buffer))
ERREXIT(cinfo,JERR_FILE_WRITE);
}
}
/*
Output generic APPN profile
*/
static void WriteAPPNProfile(j_compress_ptr jpeg_info,
const unsigned char *profile,
const size_t profile_length,
const char * profile_name)
{
size_t
j;
int
marker_id;
marker_id=JPEG_APP0+(int) MagickAtoL(profile_name+3);
for (j=0; j < profile_length; j+=65533L)
jpeg_write_marker(jpeg_info,marker_id,
profile+j,(int)
Min(profile_length-j,65533L));
}
/*
Output EXIF profile
*/
static void WriteEXIFProfile(j_compress_ptr jpeg_info,
const unsigned char *profile,
const size_t profile_length)
{
size_t
j;
for (j=0; j < profile_length; j+=65533L)
jpeg_write_marker(jpeg_info,JPEG_APP0+1,
profile+j,(int)
Min(profile_length-j,65533L));
}
/*
Output ICC color profile as a APP marker.
*/
static void WriteICCProfile(j_compress_ptr jpeg_info,
const unsigned char *color_profile,
const size_t profile_length)
{
register long
i,
j;
for (i=0; i < (long) profile_length; i+=65519)
{
unsigned char
*profile;
size_t
alloc_length,
length=0;
length=Min(profile_length-i,65519);
alloc_length=length+14;
profile=MagickAllocateResourceLimitedMemory(unsigned char *,alloc_length);
if (profile == (unsigned char *) NULL)
break;
(void) strlcpy((char *) profile,"ICC_PROFILE",alloc_length);
profile[12]=(unsigned char) ((i/65519)+1);
profile[13]=(unsigned char) ((profile_length/65519)+1);
for (j=0; j < (long) length; j++)
profile[j+14]=color_profile[i+j];
jpeg_write_marker(jpeg_info,ICC_MARKER,profile,(unsigned int) alloc_length);
MagickFreeResourceLimitedMemory(profile);
}
}
/*
Output binary Photoshop resource data using an APP marker.
*/
static void WriteIPTCProfile(j_compress_ptr jpeg_info,
const unsigned char *iptc_profile,
const size_t profile_length)
{
register long
i;
unsigned long
roundup,
tag_length;
#ifdef GET_ONLY_IPTC_DATA
tag_length=26;
#else
tag_length=14;
#endif
for (i=0; i < (long) profile_length; i+=65500)
{
size_t
length;
unsigned char
*profile;
length=Min(profile_length-i,65500);
roundup=(length & 0x01); /* round up for Photoshop */
profile=MagickAllocateResourceLimitedMemory(unsigned char *,length+roundup+tag_length);
if (profile == (unsigned char *) NULL)
break;
#ifdef GET_ONLY_IPTC_DATA
(void) memcpy(profile,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24);
profile[13]=0x00;
profile[24]=length >> 8;
profile[25]=length & 0xff;
#else
(void) memcpy(profile,"Photoshop 3.0 ",14);
profile[13]=0x00;
#endif
(void) memcpy(&(profile[tag_length]),&(iptc_profile[i]),length);
if (roundup)
profile[length+tag_length]=0;
jpeg_write_marker(jpeg_info,IPTC_MARKER,profile,(unsigned int)
(length+roundup+tag_length));
MagickFreeResourceLimitedMemory(profile);
}
}
/*
Output Adobe XMP XML profile.
*/
static void WriteXMPProfile(j_compress_ptr jpeg_info,
const unsigned char *profile,
const size_t profile_length)
{
size_t
count,
index,
header_length,
total_length;
unsigned int
marker_length,
remaining;
header_length=strlen(xmp_std_header)+1; /* Include terminating null */
total_length=header_length+profile_length;
/* XMP profile must be no larger than range of 'unsigned int' */
remaining=(unsigned int) Min(UINT_MAX,total_length);
marker_length=Min(remaining,JPEG_MARKER_MAX_SIZE);
jpeg_write_m_header(jpeg_info,XML_MARKER,marker_length);
count=marker_length;
{
for (index=0 ; index < header_length; index++)
{
jpeg_write_m_byte(jpeg_info,xmp_std_header[index]);
--remaining;
--count;
}
}
for (index=0; remaining > 0; --remaining)
{
if (count == 0)
{
marker_length=Min(remaining,JPEG_MARKER_MAX_SIZE);
jpeg_write_m_header(jpeg_info,XML_MARKER,marker_length);
count=marker_length;
}
jpeg_write_m_byte(jpeg_info,profile[index]);
index++;
count--;
}
}
/*
Output profiles to JPEG stream.
*/
static void WriteProfiles(j_compress_ptr jpeg_info,Image *image)
{
const char
*profile_name;
const unsigned char *
profile;
ImageProfileIterator
profile_iterator;
size_t
profile_length=0;
profile_iterator=AllocateImageProfileIterator(image);
while(NextImageProfile(profile_iterator,&profile_name,&profile,
&profile_length) != MagickFail)
{
if (LocaleNCompare(profile_name,"APP",3) == 0)
{
WriteAPPNProfile(jpeg_info, profile, profile_length, profile_name);
}
else if (LocaleCompare(profile_name,"EXIF") == 0)
{
WriteEXIFProfile(jpeg_info, profile, profile_length);
}
else if ((LocaleCompare(profile_name,"ICM") == 0) ||
(LocaleCompare(profile_name,"ICC") == 0))
{
WriteICCProfile(jpeg_info, profile, profile_length);
}
else if ((LocaleCompare(profile_name,"IPTC") == 0) ||
(LocaleCompare(profile_name,"8BIM") == 0))
{
WriteIPTCProfile(jpeg_info, profile, profile_length);
}
else if (LocaleCompare(profile_name,"XMP") == 0)
{
WriteXMPProfile(jpeg_info, profile, profile_length);
}
else
{
/*
Skip unknown profile type
*/
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Skipped Profile: %s, %"
MAGICK_SIZE_T_F "u bytes",
profile_name,
(MAGICK_SIZE_T) profile_length);
continue;
}
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Wrote Profile: %s, %"
MAGICK_SIZE_T_F "u bytes",profile_name,
(MAGICK_SIZE_T) profile_length);
}
DeallocateImageProfileIterator(profile_iterator);
}
static void JPEGDestinationManager(j_compress_ptr cinfo,Image * image)
{
DestinationManager
*destination;
cinfo->dest=(struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo,JPOOL_IMAGE,sizeof(DestinationManager));
destination=(DestinationManager *) cinfo->dest;
destination->manager.init_destination=InitializeDestination;
destination->manager.empty_output_buffer=EmptyOutputBuffer;
destination->manager.term_destination=TerminateDestination;
destination->image=image;
}
/*
Format a libjpeg warning or trace event while encoding. Warnings
are converted to GraphicsMagick warning exceptions while traces are
optionally logged.
JPEG message codes range from 0 to JMSG_LASTMSGCODE
*/
static void JPEGEncodeMessageHandler(j_common_ptr jpeg_info,int msg_level)
{
char
message[JMSG_LENGTH_MAX];
struct jpeg_error_mgr
*err;
MagickClientData
*client_data;
Image
*image;
message[0]='\0';
err=jpeg_info->err;
client_data=(MagickClientData *) jpeg_info->client_data;
image=client_data->image;
/* msg_level is -1 for warnings, 0 and up for trace messages. */
if (msg_level < 0)
{
unsigned int strikes = 0;
/* A warning */
(err->format_message)(jpeg_info,message);
if ((err->msg_code >= 0) &&
((size_t) err->msg_code < ArraySize(client_data->warning_counts)))
{
client_data->warning_counts[err->msg_code]++;
strikes=client_data->warning_counts[err->msg_code];
}
if (image->logging)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Warning[%u]: \"%s\""
" (code=%d "
"parms=0x%02x,0x%02x,"
"0x%02x,0x%02x,0x%02x,0x%02x,0x%02x,0x%02x)",
image->filename,
strikes,
message,err->msg_code,
err->msg_parm.i[0], err->msg_parm.i[1],
err->msg_parm.i[2], err->msg_parm.i[3],
err->msg_parm.i[4], err->msg_parm.i[5],
err->msg_parm.i[6], err->msg_parm.i[7]);
}
/*
if (strikes > client_data->max_warning_count)
{
ThrowException2(&image->exception,CorruptImageError,(char *) message,
image->filename);
longjmp(client_data->error_recovery,1);
}
if ((err->num_warnings == 0) ||
(err->trace_level >= 3))
ThrowException2(&image->exception,CorruptImageWarning,message,
image->filename);
*/
/* JWRN_JPEG_EOF - "Premature end of JPEG file" */
err->num_warnings++;
return /* False */;
}
else
{
/* A trace message */
if ((image->logging) && (msg_level >= err->trace_level))
{
(err->format_message)(jpeg_info,message);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"[%s] JPEG Trace: \"%s\"",image->filename,
message);
}
}
return /* True */;
}
static void JPEGEncodeProgressMonitor(j_common_ptr cinfo)
{
#if USE_LIBJPEG_PROGRESS
struct jpeg_progress_mgr *p = cinfo->progress;
MagickClientData *client_data = (MagickClientData *) cinfo->client_data;
Image *image = client_data->image;
#if 0
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Progress: pass_counter=%ld, pass_limit=%ld,"
" completed_passes=%d, total_passes=%d, filename=%s",
p->pass_counter, p->pass_limit,
p->completed_passes, p->total_passes, image->filename);
#endif
if (QuantumTick(p->pass_counter,p->pass_limit))
if (!MagickMonitorFormatted(p->pass_counter,p->pass_limit,&image->exception,
"[%s] Saving image: %lux%lu (pass %d of %d)... ",
image->filename,
image->columns,image->rows,
p->completed_passes+1, p->total_passes))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Quitting due to progress monitor");
longjmp(client_data->error_recovery,1);
}
#else
(void) cinfo;
#endif /* USE_LIBJPEG_PROGRESS */
}
#define ThrowJPEGWriterException(code_,reason_,image_) \
{ \
client_data=FreeMagickClientData(client_data); \
ThrowWriterException(code_,reason_,image_); \
}
static MagickPassFail WriteJPEGImage(const ImageInfo *image_info,Image *imagep)
{
Image
* volatile image = imagep; /* volatile to avoid "clobber" */
MagickClientData
*client_data = (MagickClientData *) NULL;
const ImageAttribute
*attribute;
JSAMPLE
*jpeg_pixels;
JSAMPROW
scanline[1];
char
*sampling_factors,
*preserve_settings;
const char
*value;
long
y;
register const PixelPacket
*p;
register JSAMPLE
*q;
register long
i,
x;
struct jpeg_error_mgr
jpeg_error;
struct jpeg_progress_mgr
jpeg_progress;
struct jpeg_compress_struct
jpeg_info;
MagickPassFail
status;
unsigned long
input_colorspace;
unsigned long
quality;
magick_int64_t
huffman_memory;
ImageCharacteristics
characteristics;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(imagep != (Image *) NULL);
assert(imagep->signature == MagickSignature);
client_data=AllocateMagickClientData();
if (client_data == (MagickClientData *) NULL)
ThrowJPEGWriterException(ResourceLimitError,MemoryAllocationFailed,image);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == False)
ThrowJPEGWriterException(FileOpenError,UnableToOpenFile,image);
(void) memset(&jpeg_progress,0,sizeof(jpeg_progress));
(void) memset(&jpeg_info,0,sizeof(jpeg_info));
(void) memset(&jpeg_error,0,sizeof(jpeg_error));
/*
Set initial longjmp based error handler.
*/
jpeg_info.client_data=(void *) image;
jpeg_info.err=jpeg_std_error(&jpeg_error);
jpeg_info.err->emit_message=/*(void (*)(j_common_ptr,int))*/ JPEGEncodeMessageHandler;
jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler;
client_data->image=image;
client_data->max_warning_count=MaxWarningCount;
/*
Allow the user to set how many warnings of any given type are
allowed before promotion of the warning to a hard error.
*/
if ((value=AccessDefinition(image_info,"jpeg","max-warnings")))
client_data->max_warning_count=strtol(value,(char **) NULL, 10);
jpeg_info.client_data=(void *) client_data;
if (setjmp(client_data->error_recovery) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Setjmp return from longjmp!");
jpeg_destroy_compress(&jpeg_info);
client_data=FreeMagickClientData(client_data);
CloseBlob(image);
return MagickFail ;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Write JPEG Image: image->orientation = %d",image->orientation);
/*
Transform image to user-requested colorspace.
*/
if (UndefinedColorspace != image_info->colorspace)
{
(void) TransformColorspace(image,image_info->colorspace);
}
/*
Convert RGB-compatible colorspaces (e.g. CineonLog) to RGB by
default. User can still override it by explicitly specifying the
desired colorspace.
*/
else if (IsRGBCompatibleColorspace(image->colorspace) &&
!IsRGBColorspace(image->colorspace))
{
(void) TransformColorspace(image,RGBColorspace);
}
/*
Analyze image to be written.
*/
if (!GetImageCharacteristics(image,&characteristics,
(OptimizeType == image_info->type),
&image->exception))
{
client_data=FreeMagickClientData(client_data);
CloseBlob(image);
return MagickFail;
}
jpeg_create_compress(&jpeg_info);
JPEGDestinationManager(&jpeg_info,image);
jpeg_info.image_width=(unsigned int) image->columns;
jpeg_info.image_height=(unsigned int) image->rows;
jpeg_info.input_components=3;
jpeg_info.in_color_space=JCS_RGB;
/*
Register our progress monitor
*/
jpeg_progress.progress_monitor=(void (*)(j_common_ptr)) JPEGEncodeProgressMonitor;
jpeg_info.progress=&jpeg_progress;
/*
Set JPEG colorspace as per user request.
*/
{
MagickBool
colorspace_set=MagickFalse;
if (IsCMYKColorspace(image_info->colorspace))
{
jpeg_info.input_components=4;
jpeg_info.in_color_space=JCS_CMYK;
colorspace_set=MagickTrue;
}
else if (IsYCbCrColorspace(image_info->colorspace))
{
jpeg_info.input_components=3;
jpeg_info.in_color_space=JCS_YCbCr;
colorspace_set=MagickTrue;
}
else if (IsGrayColorspace(image_info->colorspace))
{
jpeg_info.input_components=1;
jpeg_info.in_color_space=JCS_GRAYSCALE;
colorspace_set=MagickTrue;
}
if (!colorspace_set)
{
if (IsCMYKColorspace(image->colorspace))
{
jpeg_info.input_components=4;
jpeg_info.in_color_space=JCS_CMYK;
}
else if (IsYCbCrColorspace(image->colorspace))
{
jpeg_info.input_components=3;
jpeg_info.in_color_space=JCS_YCbCr;
}
else if ((IsGrayColorspace(image->colorspace) ||
(characteristics.grayscale)))
{
jpeg_info.input_components=1;
jpeg_info.in_color_space=JCS_GRAYSCALE;
}
else
{
jpeg_info.input_components=3;
jpeg_info.in_color_space=JCS_RGB;
}
}
}
input_colorspace=UndefinedColorspace;
quality=image_info->quality;
/* Check for -define jpeg:preserve-settings */
/* ImageMagick:
GetImageOption();
*/
/* GraphicsMagick */
preserve_settings=(char *) AccessDefinition(image_info,"jpeg",
"preserve-settings");
sampling_factors=image_info->sampling_factor;
if (preserve_settings)
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" JPEG:preserve-settings flag is defined.");
/* Retrieve input file quality */
attribute=GetImageAttribute(image,"JPEG-Quality");
if ((attribute != (const ImageAttribute *) NULL) &&
(attribute->value != (char *) NULL))
{
(void) sscanf(attribute->value,"%lu",&quality);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input quality=%lu",quality);
}
/* Retrieve input file colorspace */
attribute=GetImageAttribute(image,"JPEG-Colorspace");
if ((attribute != (const ImageAttribute *) NULL) &&
(attribute->value != (char *) NULL))
{
(void) sscanf(attribute->value,"%lu",&input_colorspace);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input colorspace=%lu",input_colorspace);
}
if (input_colorspace == (unsigned long) jpeg_info.in_color_space)
{
/* Retrieve input sampling factors */
attribute=GetImageAttribute(image,"JPEG-Sampling-factors");
if ((attribute != (const ImageAttribute *) NULL) &&
(attribute->value != (char *) NULL))
{
sampling_factors=attribute->value;
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factors);
}
}
else
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input colorspace (%lu) != Output colorspace (%d)",
input_colorspace,jpeg_info.in_color_space);
}
}
jpeg_set_defaults(&jpeg_info);
/*
Determine bit depth (valid range in 8-16).
*/
{
int
sample_size;
sample_size=sizeof(JSAMPLE)*8;
if (sample_size > 8)
sample_size=12;
if ((jpeg_info.data_precision != 12) &&
(image->depth <= 8))
sample_size=8;
jpeg_info.data_precision=sample_size;
}
if ((image->x_resolution == 0) || (image->y_resolution == 0))
{
image->x_resolution=72.0;
image->y_resolution=72.0;
image->units=PixelsPerInchResolution;
}
if (image_info->density != (char *) NULL)
{
int
count;
/* FIXME: density should not be set via image_info->density
but removing this support may break some applications. */
count=GetMagickDimension(image_info->density,&image->x_resolution,
&image->y_resolution,NULL,NULL);
if (count == 1 )
image->y_resolution=image->x_resolution;
}
jpeg_info.density_unit=1; /* default to DPI */
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Image resolution: %ld,%ld",(long) image->x_resolution,
(long) image->y_resolution);
if ((image->x_resolution >= 0) && (image->x_resolution < (double) SHRT_MAX) &&
(image->y_resolution >= 0) && (image->y_resolution < (double) SHRT_MAX))
{
/*
Set image resolution.
*/
jpeg_info.write_JFIF_header=True;
jpeg_info.X_density=(short) image->x_resolution;
jpeg_info.Y_density=(short) image->y_resolution;
if (image->units == PixelsPerInchResolution)
jpeg_info.density_unit=1;
if (image->units == PixelsPerCentimeterResolution)
jpeg_info.density_unit=2;
}
{
const char
*value;
/*
Allow the user to select the DCT encoding algorithm.
*/
if ((value=AccessDefinition(image_info,"jpeg","dct-method")))
{
if (LocaleCompare(value,"ISLOW") == 0)
jpeg_info.dct_method=JDCT_ISLOW;
else if (LocaleCompare(value,"IFAST") == 0)
jpeg_info.dct_method=JDCT_IFAST;
else if (LocaleCompare(value,"FLOAT") == 0)
jpeg_info.dct_method=JDCT_FLOAT;
else if (LocaleCompare(value,"DEFAULT") == 0)
jpeg_info.dct_method=JDCT_DEFAULT;
else if (LocaleCompare(value,"FASTEST") == 0)
jpeg_info.dct_method=JDCT_FASTEST;
}
}
{
const char
*value;
huffman_memory = 0;
#ifdef C_ARITH_CODING_SUPPORTED
/*
Allow the user to turn on/off arithmetic coder.
*/
if ((value=AccessDefinition(image_info,"jpeg","arithmetic-coding")))
{
if (LocaleCompare(value,"FALSE") == 0)
jpeg_info.arith_code = False;
else
jpeg_info.arith_code = True;
}
if (!jpeg_info.arith_code) /* jpeg_info.optimize_coding must not be set to enable arithmetic. */
#endif
{
if ((value=AccessDefinition(image_info,"jpeg","optimize-coding")))
{
if (LocaleCompare(value,"FALSE") == 0)
jpeg_info.optimize_coding=MagickFalse;
else
jpeg_info.optimize_coding=MagickTrue;
}
else
{
/*
Huffman optimization requires that the whole image be buffered in
memory. Since this is such a large consumer, obtain a memory
resource for the memory to be consumed. If the memory resource
fails to be acquired, then don't enable huffman optimization.
*/
huffman_memory=(magick_int64_t) jpeg_info.input_components*
image->columns*image->rows*sizeof(JSAMPLE);
jpeg_info.optimize_coding=AcquireMagickResource(MemoryResource,
huffman_memory);
}
if (!jpeg_info.optimize_coding)
huffman_memory=0;
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Huffman optimization is %s",
(jpeg_info.optimize_coding ? "enabled" : "disabled"));
}
}
#if (JPEG_LIB_VERSION >= 61) && defined(C_PROGRESSIVE_SUPPORTED)
if (image_info->interlace == LineInterlace)
jpeg_simple_progression(&jpeg_info);
if (image->logging)
{
if (image_info->interlace == LineInterlace)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: progressive");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
}
#else
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Interlace: nonprogressive");
#endif
if ((image->compression == LosslessJPEGCompression) ||
(quality > 100))
{
#if !defined(LIBJPEG_TURBO_VERSION_NUMBER) && defined(C_LOSSLESS_SUPPORTED)
if (quality < 100)
ThrowException(&image->exception,CoderWarning,
LosslessToLossyJPEGConversion,(char *) NULL);
else
{
int
point_transform,
predictor;
predictor=quality/100; /* range 1-7 */
point_transform=quality % 20; /* range 0-15 */
jpeg_simple_lossless(&jpeg_info,predictor,point_transform);
if (image->logging)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Compression: lossless");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Predictor: %d",predictor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Point Transform: %d",point_transform);
}
}
#else
{
jpeg_set_quality(&jpeg_info,100,True);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: 100");
}
#endif
}
else
{
jpeg_set_quality(&jpeg_info,(int) quality,True);
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: %lu",
quality);
}
if (sampling_factors != (char *) NULL)
{
double
hs[4]={1.0, 1.0, 1.0, 1.0},
vs[4]={1.0, 1.0, 1.0, 1.0};
long
count;
/*
Set sampling factors.
*/
count=sscanf(sampling_factors,"%lfx%lf,%lfx%lf,%lfx%lf,%lfx%lf",
&hs[0],&vs[0],&hs[1],&vs[1],&hs[2],&vs[2],&hs[3],&vs[3]);
if (count%2 == 1)
vs[count/2]=hs[count/2];
for (i=0; i < 4; i++)
{
jpeg_info.comp_info[i].h_samp_factor=(int) hs[i];
jpeg_info.comp_info[i].v_samp_factor=(int) vs[i];
}
for (; i < MAX_COMPONENTS; i++)
{
jpeg_info.comp_info[i].h_samp_factor=1;
jpeg_info.comp_info[i].v_samp_factor=1;
}
}
else
{
if (quality >= 90)
for (i=0; i < MAX_COMPONENTS; i++)
{
jpeg_info.comp_info[i].h_samp_factor=1;
jpeg_info.comp_info[i].v_samp_factor=1;
}
}
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Starting JPEG compression");
jpeg_start_compress(&jpeg_info,True);
if (image->logging)
{
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: PseudoClass");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: DirectClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Depth: %u",
image->depth);
if (image->colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Number of colors: %u",image->colors);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Number of colors: unspecified");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"JPEG data precision: %d",(int) jpeg_info.data_precision);
if (IsCMYKColorspace(image_info->colorspace))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Storage class: DirectClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: CMYK");
}
else if (IsYCbCrColorspace(image_info->colorspace))
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: YCbCr");
}
if (IsCMYKColorspace(image->colorspace))
{
/* A CMYK space */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: CMYK");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor,
jpeg_info.comp_info[3].h_samp_factor,
jpeg_info.comp_info[3].v_samp_factor);
}
else if (IsGrayColorspace(image->colorspace))
{
/* A gray space */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: GRAY");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor);
}
else if (IsRGBCompatibleColorspace(image->colorspace))
{
/* An RGB space */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colorspace is RGB");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor);
}
else if (IsYCbCrColorspace(image->colorspace))
{
/* A YCbCr space */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Colorspace: YCbCr");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor);
}
else
{
/* Some other color space */
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d",
image->colorspace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d",
jpeg_info.comp_info[0].h_samp_factor,
jpeg_info.comp_info[0].v_samp_factor,
jpeg_info.comp_info[1].h_samp_factor,
jpeg_info.comp_info[1].v_samp_factor,
jpeg_info.comp_info[2].h_samp_factor,
jpeg_info.comp_info[2].v_samp_factor,
jpeg_info.comp_info[3].h_samp_factor,
jpeg_info.comp_info[3].v_samp_factor);
}
}
/*
Write JPEG profiles.
*/
attribute=GetImageAttribute(image,"comment");
if ((attribute != (const ImageAttribute *) NULL) &&
(attribute->value != (char *) NULL))
for (i=0; i < (long) strlen(attribute->value); i+=65533L)
jpeg_write_marker(&jpeg_info,JPEG_COM,(unsigned char *) attribute->value+
i,(int) Min(strlen(attribute->value+i),65533L));
#if 0
WriteICCProfile(&jpeg_info,image);
WriteIPTCProfile(&jpeg_info,image);
WriteXMPProfile(&jpeg_info,image);
#endif
WriteProfiles(&jpeg_info,image);
/*
Convert MIFF to JPEG raster pixels.
*/
jpeg_pixels=MagickAllocateResourceLimitedArray(JSAMPLE *,
jpeg_info.input_components*image->columns,sizeof(JSAMPLE));
if (jpeg_pixels == (JSAMPLE *) NULL)
{
if (huffman_memory)
LiberateMagickResource(MemoryResource,huffman_memory);
ThrowJPEGWriterException(ResourceLimitError,MemoryAllocationFailed,image);
}
scanline[0]=(JSAMPROW) jpeg_pixels;
if (jpeg_info.data_precision > 8 && jpeg_info.data_precision <= 16)
{
unsigned int
scale_short;
scale_short=65535U/MaxValueGivenBits(jpeg_info.data_precision);
if (jpeg_info.in_color_space == JCS_GRAYSCALE)
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Writing %d bit JCS_GRAYSCALE samples",
jpeg_info.data_precision);
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
if (image->is_grayscale)
{
for (x=0; x < (long) image->columns; x++)
{
*q++=(JSAMPLE) (ScaleQuantumToShort(GetGraySample(p))/
scale_short);
p++;
}
}
else
{
for (x=0; x < (long) image->columns; x++)
{
*q++=(JSAMPLE)
(ScaleQuantumToShort(PixelIntensityToQuantum(p))/scale_short);
p++;
}
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
SaveImageText,image->filename,
image->columns,image->rows))
break;
#endif /* !USE_LIBJPEG_PROGRESS */
}
}
else
if ((jpeg_info.in_color_space == JCS_RGB) ||
(jpeg_info.in_color_space == JCS_YCbCr))
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Writing %d bit JCS_RGB or "
"JCS_YCbCr samples",
jpeg_info.data_precision);
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (long) image->columns; x++)
{
*q++=(JSAMPLE) (ScaleQuantumToShort(p->red)/16);
*q++=(JSAMPLE) (ScaleQuantumToShort(p->green)/16);
*q++=(JSAMPLE) (ScaleQuantumToShort(p->blue)/16);
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
SaveImageText,image->filename,
image->columns,image->rows))
break;
#endif /* !USE_LIBJPEG_PROGRESS */
}
}
else
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Writing %d bit JCS_CMYK samples",
jpeg_info.data_precision);
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (long) image->columns; x++)
{
/*
Convert DirectClass packets to contiguous CMYK scanlines.
*/
*q++=(JSAMPLE) (4095-ScaleQuantumToShort(p->red)/16);
*q++=(JSAMPLE) (4095-ScaleQuantumToShort(p->green)/16);
*q++=(JSAMPLE) (4095-ScaleQuantumToShort(p->blue)/16);
*q++=(JSAMPLE) (4095-ScaleQuantumToShort(p->opacity)/16);
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
SaveImageText,image->filename,
image->columns,image->rows))
break;
#endif /* !USE_LIBJPEG_PROGRESS */
}
}
}
else
if (jpeg_info.in_color_space == JCS_GRAYSCALE)
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Writing %d bit JCS_GRAYSCALE samples",
jpeg_info.data_precision);
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
if (image->is_grayscale)
{
for (x=0; x < (long) image->columns; x++)
{
*q++=(JSAMPLE) ScaleQuantumToChar(GetGraySample(p));
p++;
}
}
else
{
for (x=0; x < (long) image->columns; x++)
{
*q++=(JSAMPLE)
ScaleQuantumToChar(PixelIntensityToQuantum(p));
p++;
}
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
SaveImageText,image->filename,
image->columns,image->rows))
break;
#endif /* !USE_LIBJPEG_PROGRESS */
}
}
else
if ((jpeg_info.in_color_space == JCS_RGB) ||
(jpeg_info.in_color_space == JCS_YCbCr))
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Writing %d bit JCS_RGB or JCS_YCbCr samples",
jpeg_info.data_precision);
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (long) image->columns; x++)
{
*q++=(JSAMPLE) ScaleQuantumToChar(p->red);
*q++=(JSAMPLE) ScaleQuantumToChar(p->green);
*q++=(JSAMPLE) ScaleQuantumToChar(p->blue);
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
SaveImageText,image->filename,
image->columns,image->rows))
break;
#endif /* !USE_LIBJPEG_PROGRESS */
}
}
else
{
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Writing %d bit JCS_CMYK samples",
jpeg_info.data_precision);
for (y=0; y < (long) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=jpeg_pixels;
for (x=0; x < (long) image->columns; x++)
{
/*
Convert DirectClass packets to contiguous CMYK scanlines.
*/
*q++=(JSAMPLE) (ScaleQuantumToChar(MaxRGB-p->red));
*q++=(JSAMPLE) (ScaleQuantumToChar(MaxRGB-p->green));
*q++=(JSAMPLE) (ScaleQuantumToChar(MaxRGB-p->blue));
*q++=(JSAMPLE) (ScaleQuantumToChar(MaxRGB-p->opacity));
p++;
}
(void) jpeg_write_scanlines(&jpeg_info,scanline,1);
#if !USE_LIBJPEG_PROGRESS
if (QuantumTick(y,image->rows))
if (!MagickMonitorFormatted(y,image->rows,&image->exception,
SaveImageText,image->filename,
image->columns,image->rows))
break;
#endif /* !USE_LIBJPEG_PROGRESS */
}
}
if (image->logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Finishing JPEG compression");
jpeg_finish_compress(&jpeg_info);
/*
Free memory.
*/
if (huffman_memory)
LiberateMagickResource(MemoryResource,huffman_memory);
client_data=FreeMagickClientData(client_data);
jpeg_destroy_compress(&jpeg_info);
MagickFreeResourceLimitedMemory(jpeg_pixels);
CloseBlob(image);
return(True);
}
#endif
|