File: jpgdataset.cpp

package info (click to toggle)
gdal 3.6.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 89,664 kB
  • sloc: cpp: 1,136,033; ansic: 197,355; python: 35,910; java: 5,511; xml: 4,011; sh: 3,950; cs: 2,443; yacc: 1,047; makefile: 288
file content (4277 lines) | stat: -rw-r--r-- 148,241 bytes parent folder | download
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
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
/******************************************************************************
 *
 * Project:  JPEG JFIF Driver
 * Purpose:  Implement GDAL JPEG Support based on IJG libjpeg.
 * Author:   Frank Warmerdam, warmerdam@pobox.com
 *
 ******************************************************************************
 * Copyright (c) 2000, Frank Warmerdam
 * Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
 *
 * Portions Copyright (c) Her majesty the Queen in right of Canada as
 * represented by the Minister of National Defence, 2006.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ****************************************************************************/

#include "cpl_port.h"
#include "jpgdataset.h"

#include <cerrno>
#include <climits>
#include <cstddef>
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <limits>
#include <setjmp.h>

#include <algorithm>
#include <string>

#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "cpl_time.h"
#include "cpl_vsi.h"
#include "gdal.h"
#include "gdal_frmts.h"
#include "gdal_pam.h"
#include "gdal_priv.h"
#include "gdalexif.h"
CPL_C_START
#ifdef LIBJPEG_12_PATH
#include LIBJPEG_12_PATH
#else
#include "jpeglib.h"
#endif
CPL_C_END
#include "memdataset.h"
#include "rawdataset.h"
#include "vsidataio.h"

#if defined(EXPECTED_JPEG_LIB_VERSION) && !defined(LIBJPEG_12_PATH)
#if EXPECTED_JPEG_LIB_VERSION != JPEG_LIB_VERSION
#error EXPECTED_JPEG_LIB_VERSION != JPEG_LIB_VERSION
#endif
#endif

constexpr int TIFF_VERSION = 42;

constexpr int TIFF_BIGENDIAN = 0x4d4d;
constexpr int TIFF_LITTLEENDIAN = 0x4949;

constexpr int JPEG_TIFF_IMAGEWIDTH = 0x100;
constexpr int JPEG_TIFF_IMAGEHEIGHT = 0x101;
constexpr int JPEG_TIFF_COMPRESSION = 0x103;
constexpr int JPEG_EXIF_JPEGIFOFSET = 0x201;
constexpr int JPEG_EXIF_JPEGIFBYTECOUNT = 0x202;

// Ok to use setjmp().
#ifdef _MSC_VER
#pragma warning(disable : 4611)
#endif

// Do we want to do special processing suitable for when JSAMPLE is a
// 16bit value?
#if defined(JPEG_LIB_MK1)
#define JPEG_LIB_MK1_OR_12BIT 1
#elif BITS_IN_JSAMPLE == 12
#define JPEG_LIB_MK1_OR_12BIT 1
#endif

/************************************************************************/
/*                     SetMaxMemoryToUse()                              */
/************************************************************************/

static void SetMaxMemoryToUse(struct jpeg_decompress_struct *psDInfo)
{
    // This is to address bug related in ticket #1795.
    if (CPLGetConfigOption("JPEGMEM", nullptr) == nullptr)
    {
        // If the user doesn't provide a value for JPEGMEM, we want to be sure
        // that at least 500 MB will be used before creating the temporary file.
        const long nMinMemory = 500 * 1024 * 1024;
        psDInfo->mem->max_memory_to_use =
            std::max(psDInfo->mem->max_memory_to_use, nMinMemory);
    }
}

#if !defined(JPGDataset)

/************************************************************************/
/*                       ReadEXIFMetadata()                             */
/************************************************************************/
void JPGDatasetCommon::ReadEXIFMetadata()
{
    if (bHasReadEXIFMetadata)
        return;

    CPLAssert(papszMetadata == nullptr);

    // Save current position to avoid disturbing JPEG stream decoding.
    const vsi_l_offset nCurOffset = VSIFTellL(m_fpImage);

    if (EXIFInit(m_fpImage))
    {
        EXIFExtractMetadata(papszMetadata, m_fpImage, nTiffDirStart, bSwabflag,
                            nTIFFHEADER, nExifOffset, nInterOffset, nGPSOffset);

        if (nExifOffset > 0)
        {
            EXIFExtractMetadata(papszMetadata, m_fpImage, nExifOffset,
                                bSwabflag, nTIFFHEADER, nExifOffset,
                                nInterOffset, nGPSOffset);
        }
        if (nInterOffset > 0)
        {
            EXIFExtractMetadata(papszMetadata, m_fpImage, nInterOffset,
                                bSwabflag, nTIFFHEADER, nExifOffset,
                                nInterOffset, nGPSOffset);
        }
        if (nGPSOffset > 0)
        {
            EXIFExtractMetadata(papszMetadata, m_fpImage, nGPSOffset, bSwabflag,
                                nTIFFHEADER, nExifOffset, nInterOffset,
                                nGPSOffset);
        }

        // Avoid setting the PAM dirty bit just for that.
        const int nOldPamFlags = nPamFlags;

        // Append metadata from PAM after EXIF metadata.
        papszMetadata = CSLMerge(papszMetadata, GDALPamDataset::GetMetadata());

        // Expose XMP in EXIF in xml:XMP metadata domain
        if (GDALDataset::GetMetadata("xml:XMP") == nullptr)
        {
            const char *pszXMP =
                CSLFetchNameValue(papszMetadata, "EXIF_XmlPacket");
            if (pszXMP)
            {
                CPLDebug("JPEG", "Read XMP metadata from EXIF tag");
                const char *const apszMDList[2] = {pszXMP, nullptr};
                SetMetadata(const_cast<char **>(apszMDList), "xml:XMP");

                papszMetadata =
                    CSLSetNameValue(papszMetadata, "EXIF_XmlPacket", nullptr);
            }
        }

        SetMetadata(papszMetadata);

        nPamFlags = nOldPamFlags;
    }

    VSIFSeekL(m_fpImage, nCurOffset, SEEK_SET);

    bHasReadEXIFMetadata = true;
}

/************************************************************************/
/*                        ReadXMPMetadata()                             */
/************************************************************************/

// See §2.1.3 of
// http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/xmp/pdfs/XMPSpecificationPart3.pdf

void JPGDatasetCommon::ReadXMPMetadata()
{
    if (bHasReadXMPMetadata)
        return;

    // Save current position to avoid disturbing JPEG stream decoding.
    const vsi_l_offset nCurOffset = VSIFTellL(m_fpImage);

    // Search for APP1 chunk.
    constexpr int APP1_BYTE = 0xe1;
    constexpr int JFIF_MARKER_SIZE = 2 + 2;  // ID + size
    constexpr const char APP1_XMP_SIGNATURE[] = "http://ns.adobe.com/xap/1.0/";
    constexpr int APP1_XMP_SIGNATURE_LEN =
        static_cast<int>(sizeof(APP1_XMP_SIGNATURE));
    GByte abyChunkHeader[JFIF_MARKER_SIZE + APP1_XMP_SIGNATURE_LEN] = {};
    int nChunkLoc = 2;
    bool bFoundXMP = false;

    while (true)
    {
        if (VSIFSeekL(m_fpImage, nChunkLoc, SEEK_SET) != 0)
            break;

        if (VSIFReadL(abyChunkHeader, sizeof(abyChunkHeader), 1, m_fpImage) !=
            1)
            break;

        nChunkLoc += 2 + abyChunkHeader[2] * 256 + abyChunkHeader[3];
        // COM marker.
        if (abyChunkHeader[0] == 0xFF && abyChunkHeader[1] == 0xFE)
            continue;

        if (abyChunkHeader[0] != 0xFF || (abyChunkHeader[1] & 0xf0) != 0xe0)
            break;  // Not an APP chunk.

        if (abyChunkHeader[1] == APP1_BYTE &&
            memcmp(reinterpret_cast<char *>(abyChunkHeader) + JFIF_MARKER_SIZE,
                   APP1_XMP_SIGNATURE, APP1_XMP_SIGNATURE_LEN) == 0)
        {
            bFoundXMP = true;
            break;  // APP1 - XMP.
        }
    }

    if (bFoundXMP)
    {
        const int nXMPLength = abyChunkHeader[2] * 256 + abyChunkHeader[3] - 2 -
                               APP1_XMP_SIGNATURE_LEN;
        if (nXMPLength > 0)
        {
            char *pszXMP = static_cast<char *>(VSIMalloc(nXMPLength + 1));
            if (pszXMP)
            {
                if (VSIFReadL(pszXMP, nXMPLength, 1, m_fpImage) == 1)
                {
                    pszXMP[nXMPLength] = '\0';

                    // Avoid setting the PAM dirty bit just for that.
                    const int nOldPamFlags = nPamFlags;

                    char *apszMDList[2] = {pszXMP, nullptr};
                    SetMetadata(apszMDList, "xml:XMP");

                    nPamFlags = nOldPamFlags;
                }
                VSIFree(pszXMP);
            }
        }
    }

    VSIFSeekL(m_fpImage, nCurOffset, SEEK_SET);

    bHasReadXMPMetadata = true;
}

/************************************************************************/
/*                        ReadFLIRMetadata()                            */
/************************************************************************/

// See https://exiftool.org/TagNames/FLIR.html

void JPGDatasetCommon::ReadFLIRMetadata()
{
    if (bHasReadFLIRMetadata)
        return;
    bHasReadFLIRMetadata = true;

    // Save current position to avoid disturbing JPEG stream decoding.
    const vsi_l_offset nCurOffset = VSIFTellL(m_fpImage);

    int nChunkLoc = 2;
    // size of APP1 segment marker + size of "FLIR\0"
    GByte abyChunkHeader[4 + 5];
    std::vector<GByte> abyFLIR;

    while (true)
    {
        if (VSIFSeekL(m_fpImage, nChunkLoc, SEEK_SET) != 0)
            break;

        if (VSIFReadL(abyChunkHeader, sizeof(abyChunkHeader), 1, m_fpImage) !=
            1)
            break;

        int nMarkerLength = abyChunkHeader[2] * 256 + abyChunkHeader[3] - 2;
        nChunkLoc += 4 + nMarkerLength;

        if (abyChunkHeader[1] == 0xe1 &&
            memcmp(abyChunkHeader + 4, "FLIR\0", 5) == 0)
        {
            // Somewhat arbitrary limit
            if (abyFLIR.size() > 10 * 1024 * 1024)
            {
                CPLError(CE_Warning, CPLE_AppDefined,
                         "Too large FLIR data compared to hardcoded limit");
                abyFLIR.clear();
                break;
            }

            // 8 = sizeof("FLIR\0") + '\1' + chunk_idx + chunk_count
            if (nMarkerLength < 8)
            {
                abyFLIR.clear();
                break;
            }
            size_t nOldSize = abyFLIR.size();
            abyFLIR.resize(nOldSize + nMarkerLength - 8);
            GByte abyIgnored[3];  // skip '\1' + chunk_idx + chunk_count
            if (VSIFReadL(abyIgnored, 3, 1, m_fpImage) != 1 ||
                VSIFReadL(&abyFLIR[nOldSize], nMarkerLength - 8, 1,
                          m_fpImage) != 1)
            {
                abyFLIR.clear();
                break;
            }
        }
    }
    // Restore file pointer
    VSIFSeekL(m_fpImage, nCurOffset, SEEK_SET);

    constexpr size_t FLIR_HEADER_SIZE = 64;
    if (abyFLIR.size() < FLIR_HEADER_SIZE)
        return;
    if (memcmp(&abyFLIR[0], "FFF\0", 4) != 0)
        return;

    const auto ReadString = [&abyFLIR](size_t nOffset, size_t nLen)
    {
        std::string osStr(
            reinterpret_cast<const char *>(abyFLIR.data()) + nOffset, nLen);
        osStr.resize(strlen(osStr.c_str()));
        return osStr;
    };

    bool bLittleEndian = false;

    const auto ReadUInt16 = [&abyFLIR, &bLittleEndian](size_t nOffset)
    {
        std::uint16_t nVal;
        memcpy(&nVal, &abyFLIR[nOffset], sizeof(nVal));
        if (bLittleEndian)
            CPL_LSBPTR16(&nVal);
        else
            CPL_MSBPTR16(&nVal);
        return nVal;
    };

    const auto ReadInt16 = [&abyFLIR, &bLittleEndian](size_t nOffset)
    {
        std::int16_t nVal;
        memcpy(&nVal, &abyFLIR[nOffset], sizeof(nVal));
        if (bLittleEndian)
            CPL_LSBPTR16(&nVal);
        else
            CPL_MSBPTR16(&nVal);
        return nVal;
    };

    const auto ReadUInt32 = [&abyFLIR, &bLittleEndian](size_t nOffset)
    {
        std::uint32_t nVal;
        memcpy(&nVal, &abyFLIR[nOffset], sizeof(nVal));
        if (bLittleEndian)
            CPL_LSBPTR32(&nVal);
        else
            CPL_MSBPTR32(&nVal);
        return nVal;
    };

    const auto ReadInt32 = [&abyFLIR, &bLittleEndian](size_t nOffset)
    {
        std::int32_t nVal;
        memcpy(&nVal, &abyFLIR[nOffset], sizeof(nVal));
        if (bLittleEndian)
            CPL_LSBPTR32(&nVal);
        else
            CPL_MSBPTR32(&nVal);
        return nVal;
    };

    const auto ReadFloat32 = [&abyFLIR, &bLittleEndian](size_t nOffset)
    {
        float fVal;
        memcpy(&fVal, &abyFLIR[nOffset], sizeof(fVal));
        if (bLittleEndian)
            CPL_LSBPTR32(&fVal);
        else
            CPL_MSBPTR32(&fVal);
        return fVal;
    };

    const auto ReadFloat64 = [&abyFLIR, &bLittleEndian](size_t nOffset)
    {
        double fVal;
        memcpy(&fVal, &abyFLIR[nOffset], sizeof(fVal));
        if (bLittleEndian)
            CPL_LSBPTR64(&fVal);
        else
            CPL_MSBPTR64(&fVal);
        return fVal;
    };

    // Avoid setting the PAM dirty bit just for that.
    struct PamFlagKeeper
    {
        int &m_nPamFlagsRef;
        int m_nOldPamFlags;
        explicit PamFlagKeeper(int &nPamFlagsRef)
            : m_nPamFlagsRef(nPamFlagsRef), m_nOldPamFlags(nPamFlagsRef)
        {
        }
        ~PamFlagKeeper()
        {
            m_nPamFlagsRef = m_nOldPamFlags;
        }
    };
    PamFlagKeeper oKeeper(nPamFlags);

    const auto SetStringIfNotEmpty =
        [&](const char *pszItemName, int nOffset, int nLength)
    {
        const auto str = ReadString(nOffset, nLength);
        if (!str.empty())
            SetMetadataItem(pszItemName, str.c_str(), "FLIR");
    };
    SetStringIfNotEmpty("CreatorSoftware", 4, 16);

    // Check file format version (big endian most of the time)
    const auto nFileFormatVersion = ReadUInt32(20);
    if (!(nFileFormatVersion >= 100 && nFileFormatVersion < 200))
    {
        bLittleEndian = true;  // retry with little-endian
        const auto nFileFormatVersionOtherEndianness = ReadUInt32(20);
        if (!(nFileFormatVersionOtherEndianness >= 100 &&
              nFileFormatVersionOtherEndianness < 200))
        {
            CPLDebug("JPEG", "FLIR: Unknown file format version: %u",
                     nFileFormatVersion);
            return;
        }
    }

    const auto nOffsetRecordDirectory = ReadUInt32(24);
    const auto nEntryCountRecordDirectory = ReadUInt32(28);

    CPLDebugOnly("JPEG", "FLIR: record offset %u, entry count %u",
                 nOffsetRecordDirectory, nEntryCountRecordDirectory);
    constexpr size_t SIZE_RECORD_DIRECTORY = 32;
    if (nOffsetRecordDirectory < FLIR_HEADER_SIZE ||
        nOffsetRecordDirectory +
                SIZE_RECORD_DIRECTORY * nEntryCountRecordDirectory >
            abyFLIR.size())
    {
        CPLDebug("JPEG", "Invalid FLIR FFF directory");
        return;
    }

    // Read the RawData record
    const auto ReadRawData =
        [&](std::uint32_t nRecOffset, std::uint32_t nRecLength)
    {
        if (!(nRecLength >= 32 && nRecOffset + nRecLength <= abyFLIR.size()))
            return;

        const int nByteOrder = ReadUInt16(nRecOffset);
        if (nByteOrder == 512)
            bLittleEndian = !bLittleEndian;
        else if (nByteOrder != 2)
            return;
        const auto nImageWidth = ReadUInt16(nRecOffset + 2);
        SetMetadataItem("RawThermalImageWidth", CPLSPrintf("%d", nImageWidth),
                        "FLIR");
        const auto nImageHeight = ReadUInt16(nRecOffset + 4);
        SetMetadataItem("RawThermalImageHeight", CPLSPrintf("%d", nImageHeight),
                        "FLIR");
        m_bRawThermalLittleEndian = bLittleEndian;
        m_nRawThermalImageWidth = nImageWidth;
        m_nRawThermalImageHeight = nImageHeight;
        m_abyRawThermalImage.clear();
        m_abyRawThermalImage.insert(m_abyRawThermalImage.end(),
                                    abyFLIR.begin() + nRecOffset + 32,
                                    abyFLIR.begin() + nRecOffset + nRecLength);

        if (!STARTS_WITH(GetDescription(), "JPEG:"))
        {
            m_nSubdatasetCount++;
            SetMetadataItem(
                CPLSPrintf("SUBDATASET_%d_NAME", m_nSubdatasetCount),
                CPLSPrintf("JPEG:\"%s\":FLIR_RAW_THERMAL_IMAGE",
                           GetDescription()),
                "SUBDATASETS");
            SetMetadataItem(
                CPLSPrintf("SUBDATASET_%d_DESC", m_nSubdatasetCount),
                "FLIR raw thermal image", "SUBDATASETS");
        }
    };

    // Read the Camera Info record
    const auto ReadCameraInfo =
        [&](std::uint32_t nRecOffset, std::uint32_t nRecLength)
    {
        if (!(nRecLength >= 1126 && nRecOffset + nRecLength <= abyFLIR.size()))
            return;

        const int nByteOrder = ReadUInt16(nRecOffset);
        if (nByteOrder == 512)
            bLittleEndian = !bLittleEndian;
        else if (nByteOrder != 2)
            return;

        const auto ReadFloat32FromKelvin = [=](std::uint32_t nOffset)
        {
            constexpr float ZERO_CELCIUS_IN_KELVIN = 273.15f;
            return ReadFloat32(nOffset) - ZERO_CELCIUS_IN_KELVIN;
        };
        SetMetadataItem("Emissivity",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 32)), "FLIR");
        SetMetadataItem("ObjectDistance",
                        CPLSPrintf("%f m", ReadFloat32(nRecOffset + 36)),
                        "FLIR");
        SetMetadataItem(
            "ReflectedApparentTemperature",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 40)), "FLIR");
        SetMetadataItem(
            "AtmosphericTemperature",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 44)), "FLIR");
        SetMetadataItem(
            "IRWindowTemperature",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 48)), "FLIR");
        SetMetadataItem("IRWindowTemperature",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 52)), "FLIR");
        auto fRelativeHumidity = ReadFloat32(nRecOffset + 60);
        if (fRelativeHumidity > 2)
            fRelativeHumidity /= 100.0f;  // Sometimes expressed in percentage
        SetMetadataItem("RelativeHumidity",
                        CPLSPrintf("%f %%", 100.0f * fRelativeHumidity));
        SetMetadataItem("PlanckR1",
                        CPLSPrintf("%.8g", ReadFloat32(nRecOffset + 88)),
                        "FLIR");
        SetMetadataItem("PlanckB",
                        CPLSPrintf("%.8g", ReadFloat32(nRecOffset + 92)),
                        "FLIR");
        SetMetadataItem("PlanckF",
                        CPLSPrintf("%.8g", ReadFloat32(nRecOffset + 96)),
                        "FLIR");
        SetMetadataItem("AtmosphericTransAlpha1",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 112)),
                        "FLIR");
        SetMetadataItem("AtmosphericTransAlpha2",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 116)),
                        "FLIR");
        SetMetadataItem("AtmosphericTransBeta1",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 120)),
                        "FLIR");
        SetMetadataItem("AtmosphericTransBeta2",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 124)),
                        "FLIR");
        SetMetadataItem("AtmosphericTransX",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 128)),
                        "FLIR");
        SetMetadataItem(
            "CameraTemperatureRangeMax",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 144)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureRangeMin",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 148)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureMaxClip",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 152)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureMinClip",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 156)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureMaxWarn",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 160)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureMinWarn",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 164)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureMaxSaturated",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 168)),
            "FLIR");
        SetMetadataItem(
            "CameraTemperatureMinSaturated",
            CPLSPrintf("%f C", ReadFloat32FromKelvin(nRecOffset + 172)),
            "FLIR");

        SetStringIfNotEmpty("CameraModel", nRecOffset + 212, 32);
        SetStringIfNotEmpty("CameraPartNumber", nRecOffset + 244, 16);
        SetStringIfNotEmpty("CameraSerialNumber", nRecOffset + 260, 16);
        SetStringIfNotEmpty("CameraSoftware", nRecOffset + 276, 16);
        SetStringIfNotEmpty("LensModel", nRecOffset + 368, 32);
        SetStringIfNotEmpty("LensPartNumber", nRecOffset + 400, 16);
        SetStringIfNotEmpty("LensSerialNumber", nRecOffset + 416, 16);
        SetMetadataItem("FieldOfView",
                        CPLSPrintf("%f deg", ReadFloat32(nRecOffset + 436)),
                        "FLIR");
        SetStringIfNotEmpty("FilterModel", nRecOffset + 492, 16);
        SetStringIfNotEmpty("FilterPartNumber", nRecOffset + 508, 32);
        SetStringIfNotEmpty("FilterSerialNumber", nRecOffset + 540, 32);
        SetMetadataItem("PlanckO",
                        CPLSPrintf("%d", ReadInt32(nRecOffset + 776)), "FLIR");
        SetMetadataItem("PlanckR2",
                        CPLSPrintf("%.8g", ReadFloat32(nRecOffset + 780)),
                        "FLIR");
        SetMetadataItem("RawValueRangeMin",
                        CPLSPrintf("%d", ReadUInt16(nRecOffset + 784)), "FLIR");
        SetMetadataItem("RawValueRangeMax",
                        CPLSPrintf("%d", ReadUInt16(nRecOffset + 786)), "FLIR");
        SetMetadataItem("RawValueMedian",
                        CPLSPrintf("%d", ReadUInt16(nRecOffset + 824)), "FLIR");
        SetMetadataItem("RawValueRange",
                        CPLSPrintf("%d", ReadUInt16(nRecOffset + 828)), "FLIR");
        const auto nUnixTime = ReadUInt32(nRecOffset + 900);
        const auto nSS = ReadUInt32(nRecOffset + 904) & 0xffff;
        const auto nTZ = ReadInt16(nRecOffset + 908);
        struct tm brokenDown;
        CPLUnixTimeToYMDHMS(static_cast<GIntBig>(nUnixTime) - nTZ * 60,
                            &brokenDown);
        std::string osDateTime(CPLSPrintf(
            "%04d-%02d-%02dT%02d:%02d:%02d.%03d", brokenDown.tm_year + 1900,
            brokenDown.tm_mon + 1, brokenDown.tm_mday, brokenDown.tm_hour,
            brokenDown.tm_min, brokenDown.tm_sec, nSS));
        if (nTZ <= 0)
            osDateTime += CPLSPrintf("+%02d:%02d", (-nTZ) / 60, (-nTZ) % 60);
        else
            osDateTime += CPLSPrintf("-%02d:%02d", nTZ / 60, nTZ % 60);
        SetMetadataItem("DateTimeOriginal", osDateTime.c_str(), "FLIR");
        SetMetadataItem("FocusStepCount",
                        CPLSPrintf("%d", ReadUInt16(nRecOffset + 912)), "FLIR");
        SetMetadataItem("FocusDistance",
                        CPLSPrintf("%f m", ReadFloat32(nRecOffset + 1116)),
                        "FLIR");
        SetMetadataItem("FrameRate",
                        CPLSPrintf("%d", ReadUInt16(nRecOffset + 1124)),
                        "FLIR");
    };

    // Read the Palette Info record
    const auto ReadPaletteInfo =
        [&](std::uint32_t nRecOffset, std::uint32_t nRecLength)
    {
        if (!(nRecLength >= 112 && nRecOffset + nRecLength <= abyFLIR.size()))
            return;
        const int nPaletteColors = abyFLIR[nRecOffset];
        SetMetadataItem("PaletteColors", CPLSPrintf("%d", nPaletteColors),
                        "FLIR");

        const auto SetColorItem =
            [this, &abyFLIR](const char *pszItem, std::uint32_t nOffset)
        {
            SetMetadataItem(pszItem,
                            CPLSPrintf("%d %d %d", abyFLIR[nOffset],
                                       abyFLIR[nOffset + 1],
                                       abyFLIR[nOffset + 2]),
                            "FLIR");
        };
        SetColorItem("AboveColor", nRecOffset + 6);
        SetColorItem("BelowColor", nRecOffset + 9);
        SetColorItem("OverflowColor", nRecOffset + 12);
        SetColorItem("UnderflowColor", nRecOffset + 15);
        SetColorItem("Isotherm1Color", nRecOffset + 18);
        SetColorItem("Isotherm2Color", nRecOffset + 21);
        SetMetadataItem("PaletteMethod",
                        CPLSPrintf("%d", abyFLIR[nRecOffset + 26]), "FLIR");
        SetMetadataItem("PaletteStretch",
                        CPLSPrintf("%d", abyFLIR[nRecOffset + 27]), "FLIR");
        SetStringIfNotEmpty("PaletteFileName", nRecOffset + 48, 32);
        SetStringIfNotEmpty("PaletteName", nRecOffset + 80, 32);
        if (nRecLength < static_cast<std::uint32_t>(112 + nPaletteColors * 3))
            return;
        std::string osPalette;
        for (int i = 0; i < nPaletteColors; i++)
        {
            if (!osPalette.empty())
                osPalette += ", ";
            osPalette +=
                CPLSPrintf("(%d %d %d)", abyFLIR[nRecOffset + 112 + 3 * i + 0],
                           abyFLIR[nRecOffset + 112 + 3 * i + 1],
                           abyFLIR[nRecOffset + 112 + 3 * i + 2]);
        }
        SetMetadataItem("Palette", osPalette.c_str(), "FLIR");
    };

    // Read the GPS Info record
    const auto ReadGPSInfo =
        [&](std::uint32_t nRecOffset, std::uint32_t nRecLength)
    {
        if (!(nRecLength >= 104 && nRecOffset + nRecLength <= abyFLIR.size()))
            return;
        auto nGPSValid = ReadUInt32(nRecOffset);
        if (nGPSValid == 0x01000000)
        {
            bLittleEndian = !bLittleEndian;
            nGPSValid = 1;
        }
        if (nGPSValid != 1)
            return;
        SetMetadataItem("GPSVersionID",
                        CPLSPrintf("%c%c%c%c", abyFLIR[nRecOffset + 4],
                                   abyFLIR[nRecOffset + 5],
                                   abyFLIR[nRecOffset + 6],
                                   abyFLIR[nRecOffset + 7]),
                        "FLIR");
        SetStringIfNotEmpty("GPSLatitudeRef", nRecOffset + 8, 1);
        SetStringIfNotEmpty("GPSLongitudeRef", nRecOffset + 10, 1);
        SetMetadataItem("GPSLatitude",
                        CPLSPrintf("%.10f", ReadFloat64(nRecOffset + 16)),
                        "FLIR");
        SetMetadataItem("GPSLongitude",
                        CPLSPrintf("%.10f", ReadFloat64(nRecOffset + 24)),
                        "FLIR");
        SetMetadataItem("GPSAltitude",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 32)), "FLIR");
        SetMetadataItem("GPSDOP",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 64)), "FLIR");
        SetStringIfNotEmpty("GPSSpeedRef", nRecOffset + 68, 1);
        SetStringIfNotEmpty("GPSTrackRef", nRecOffset + 70, 1);
        SetMetadataItem("GPSSpeed",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 76)), "FLIR");
        SetMetadataItem("GPSTrack",
                        CPLSPrintf("%f", ReadFloat32(nRecOffset + 80)), "FLIR");
        SetStringIfNotEmpty("GPSMapDatum", nRecOffset + 88, 16);
    };

    size_t nOffsetDirEntry = nOffsetRecordDirectory;
    enum FLIRRecordType
    {
        FLIR_REC_FREE = 0,
        FLIR_REC_RAWDATA = 1,
        FLIR_REC_CAMERA_INFO = 32,
        FLIR_REC_PALETTE_INFO = 34,
        FLIR_REC_GPS_INFO = 43,
    };
    // Iterate over records
    for (std::uint32_t iRec = 0; iRec < nEntryCountRecordDirectory; iRec++)
    {
        const auto nRecType = ReadUInt16(nOffsetDirEntry);
        const auto nRecOffset = ReadUInt32(nOffsetDirEntry + 12);
        const auto nRecLength = ReadUInt32(nOffsetDirEntry + 16);
        if (nRecType == FLIR_REC_FREE && nRecLength == 0)
            continue;  // silently keep empty records of type 0
        CPLDebugOnly("JPEG", "FLIR: record %u, type %u, offset %u, length %u",
                     iRec, nRecType, nRecOffset, nRecLength);
        if (nRecOffset + nRecLength > abyFLIR.size())
        {
            CPLDebug("JPEG",
                     "Invalid record %u, type %u, offset %u, length %u "
                     "w.r.t total FLIR segment size (%u)",
                     iRec, nRecType, nRecOffset, nRecLength,
                     static_cast<unsigned>(abyFLIR.size()));
            continue;
        }
        switch (nRecType)
        {
            case FLIR_REC_RAWDATA:
            {
                const auto bLittleEndianBackup = bLittleEndian;
                ReadRawData(nRecOffset, nRecLength);
                bLittleEndian = bLittleEndianBackup;
                break;
            }
            case FLIR_REC_CAMERA_INFO:
            {
                const auto bLittleEndianBackup = bLittleEndian;
                ReadCameraInfo(nRecOffset, nRecLength);
                bLittleEndian = bLittleEndianBackup;
                break;
            }
            case FLIR_REC_PALETTE_INFO:
            {
                ReadPaletteInfo(nRecOffset, nRecLength);
                break;
            }
            case FLIR_REC_GPS_INFO:
            {
                const auto bLittleEndianBackup = bLittleEndian;
                ReadGPSInfo(nRecOffset, nRecLength);
                bLittleEndian = bLittleEndianBackup;
                break;
            }
            default:
            {
                CPLDebugOnly("JPEG", "FLIR record ignored");
                break;
            }
        }
        nOffsetDirEntry += SIZE_RECORD_DIRECTORY;
    }

    CPLDebug("JPEG", "FLIR metadata read");
}

/************************************************************************/
/*                      GetMetadataDomainList()                         */
/************************************************************************/

char **JPGDatasetCommon::GetMetadataDomainList()
{
    ReadFLIRMetadata();
    return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
                                   TRUE, "xml:XMP", "COLOR_PROFILE", "FLIR",
                                   nullptr);
}

/************************************************************************/
/*                        LoadForMetadataDomain()                       */
/************************************************************************/
void JPGDatasetCommon::LoadForMetadataDomain(const char *pszDomain)
{
    if (m_fpImage == nullptr)
        return;
    if (eAccess == GA_ReadOnly && !bHasReadEXIFMetadata &&
        (pszDomain == nullptr || EQUAL(pszDomain, "")))
        ReadEXIFMetadata();
    if (eAccess == GA_ReadOnly && pszDomain != nullptr &&
        EQUAL(pszDomain, "xml:XMP"))
    {
        if (!bHasReadXMPMetadata)
        {
            ReadXMPMetadata();
        }
        if (!bHasReadEXIFMetadata &&
            GDALPamDataset::GetMetadata("xml:XMP") == nullptr)
        {
            // XMP can sometimes be embedded in a EXIF TIFF tag
            ReadEXIFMetadata();
        }
    }
    if (eAccess == GA_ReadOnly && !bHasReadICCMetadata &&
        pszDomain != nullptr && EQUAL(pszDomain, "COLOR_PROFILE"))
        ReadICCProfile();
    if (eAccess == GA_ReadOnly && !bHasReadFLIRMetadata &&
        pszDomain != nullptr && EQUAL(pszDomain, "FLIR"))
        ReadFLIRMetadata();
    if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
        ReadFLIRMetadata();
}

/************************************************************************/
/*                           GetMetadata()                              */
/************************************************************************/
char **JPGDatasetCommon::GetMetadata(const char *pszDomain)
{
    LoadForMetadataDomain(pszDomain);
    return GDALPamDataset::GetMetadata(pszDomain);
}

/************************************************************************/
/*                       GetMetadataItem()                              */
/************************************************************************/
const char *JPGDatasetCommon::GetMetadataItem(const char *pszName,
                                              const char *pszDomain)
{
    LoadForMetadataDomain(pszDomain);
    return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
}

/************************************************************************/
/*                        ReadICCProfile()                              */
/*                                                                      */
/*                 Read ICC Profile from APP2 data                      */
/************************************************************************/
void JPGDatasetCommon::ReadICCProfile()
{
    if (bHasReadICCMetadata)
        return;
    bHasReadICCMetadata = true;

    const vsi_l_offset nCurOffset = VSIFTellL(m_fpImage);

    int nChunkCount = -1;
    int anChunkSize[256] = {};
    char *apChunk[256] = {};

    // Search for APP2 chunk.
    GByte abyChunkHeader[18] = {};
    int nChunkLoc = 2;
    bool bOk = true;

    while (true)
    {
        if (VSIFSeekL(m_fpImage, nChunkLoc, SEEK_SET) != 0)
            break;

        if (VSIFReadL(abyChunkHeader, sizeof(abyChunkHeader), 1, m_fpImage) !=
            1)
            break;

        if (abyChunkHeader[0] != 0xFF)
            break;  // Not a valid tag

        if (abyChunkHeader[1] == 0xD9)
            break;  // End of image

        if ((abyChunkHeader[1] >= 0xD0) && (abyChunkHeader[1] <= 0xD8))
        {
            // Restart tags have no length
            nChunkLoc += 2;
            continue;
        }

        const int nChunkLength = abyChunkHeader[2] * 256 + abyChunkHeader[3];

        if (abyChunkHeader[1] == 0xe2 &&
            memcmp(reinterpret_cast<char *>(abyChunkHeader) + 4,
                   "ICC_PROFILE\0", 12) == 0)
        {
            // Get length and segment ID
            // Header:
            // APP2 tag: 2 bytes
            // App Length: 2 bytes
            // ICC_PROFILE\0 tag: 12 bytes
            // Segment index: 1 bytes
            // Total segments: 1 bytes
            const int nICCChunkLength = nChunkLength - 16;
            if (nICCChunkLength < 0)
            {
                CPLError(CE_Failure, CPLE_FileIO,
                         "nICCChunkLength unreasonable: %d", nICCChunkLength);
                bOk = false;
                break;
            }
            const int nICCChunkID = abyChunkHeader[16];
            const int nICCMaxChunkID = abyChunkHeader[17];

            if (nChunkCount == -1)
                nChunkCount = nICCMaxChunkID;

            // Check that all max segment counts are the same.
            if (nICCMaxChunkID != nChunkCount)
            {
                bOk = false;
                break;
            }

            // Check that no segment ID is larger than the total segment count.
            if ((nICCChunkID > nChunkCount) || (nICCChunkID == 0) ||
                (nChunkCount == 0))
            {
                bOk = false;
                break;
            }

            // Check if ICC segment already loaded.
            if (apChunk[nICCChunkID - 1] != nullptr)
            {
                bOk = false;
                break;
            }

            // Load it.
            apChunk[nICCChunkID - 1] =
                static_cast<char *>(VSIMalloc(nICCChunkLength));
            if (apChunk[nICCChunkID - 1] == nullptr)
            {
                bOk = false;
                break;
            }
            anChunkSize[nICCChunkID - 1] = nICCChunkLength;

            if (VSIFReadL(apChunk[nICCChunkID - 1], nICCChunkLength, 1,
                          m_fpImage) != 1)
            {
                bOk = false;
                break;
            }
        }

        nChunkLoc += 2 + nChunkLength;
    }

    int nTotalSize = 0;

    // Get total size and verify that there are no missing segments.
    if (bOk)
    {
        for (int i = 0; i < nChunkCount; i++)
        {
            if (apChunk[i] == nullptr)
            {
                // Missing segment - abort.
                bOk = false;
                break;
            }
            const int nSize = anChunkSize[i];
            if (nSize < 0 ||
                nTotalSize > std::numeric_limits<int>::max() - nSize)
            {
                CPLError(CE_Failure, CPLE_FileIO, "nTotalSize nonsensical");
                bOk = false;
                break;
            }
            nTotalSize += anChunkSize[i];
        }
    }

    // TODO(schwehr): Can we know what the maximum reasonable size is?
    if (nTotalSize > 2 << 28)
    {
        CPLError(CE_Failure, CPLE_FileIO, "nTotalSize unreasonable: %d",
                 nTotalSize);
        bOk = false;
    }

    // Merge all segments together and set metadata.
    if (bOk && nChunkCount > 0)
    {
        char *pBuffer = static_cast<char *>(VSIMalloc(nTotalSize));
        if (pBuffer == nullptr)
        {
            CPLError(CE_Failure, CPLE_OutOfMemory,
                     "ICCProfile too large.  nTotalSize: %d", nTotalSize);
        }
        else
        {
            char *pBufferPtr = pBuffer;
            for (int i = 0; i < nChunkCount; i++)
            {
                memcpy(pBufferPtr, apChunk[i], anChunkSize[i]);
                pBufferPtr += anChunkSize[i];
            }

            // Escape the profile.
            char *pszBase64Profile =
                CPLBase64Encode(nTotalSize, reinterpret_cast<GByte *>(pBuffer));

            // Avoid setting the PAM dirty bit just for that.
            const int nOldPamFlags = nPamFlags;

            // Set ICC profile metadata.
            SetMetadataItem("SOURCE_ICC_PROFILE", pszBase64Profile,
                            "COLOR_PROFILE");

            nPamFlags = nOldPamFlags;

            VSIFree(pBuffer);
            CPLFree(pszBase64Profile);
        }
    }

    for (int i = 0; i < nChunkCount; i++)
    {
        if (apChunk[i] != nullptr)
            VSIFree(apChunk[i]);
    }

    VSIFSeekL(m_fpImage, nCurOffset, SEEK_SET);
}

/************************************************************************/
/*                        EXIFInit()                                    */
/*                                                                      */
/*           Create Metadata from Information file directory APP1       */
/************************************************************************/
bool JPGDatasetCommon::EXIFInit(VSILFILE *fp)
{
    if (nTiffDirStart == 0)
        return false;
    if (nTiffDirStart > 0)
        return true;
    nTiffDirStart = 0;

#ifdef CPL_MSB
    constexpr bool bigendian = true;
#else
    constexpr bool bigendian = false;
#endif

    // Search for APP1 chunk.
    GByte abyChunkHeader[10] = {};
    int nChunkLoc = 2;

    while (true)
    {
        if (VSIFSeekL(fp, nChunkLoc, SEEK_SET) != 0)
            return false;

        if (VSIFReadL(abyChunkHeader, sizeof(abyChunkHeader), 1, fp) != 1)
            return false;

        const int nChunkLength = abyChunkHeader[2] * 256 + abyChunkHeader[3];
        // COM marker
        if (abyChunkHeader[0] == 0xFF && abyChunkHeader[1] == 0xFE &&
            nChunkLength >= 2)
        {
            char *pszComment =
                static_cast<char *>(CPLMalloc(nChunkLength - 2 + 1));
            if (nChunkLength > 2 &&
                VSIFSeekL(fp, nChunkLoc + 4, SEEK_SET) == 0 &&
                VSIFReadL(pszComment, nChunkLength - 2, 1, fp) == 1)
            {
                pszComment[nChunkLength - 2] = 0;
                // Avoid setting the PAM dirty bit just for that.
                const int nOldPamFlags = nPamFlags;
                // Set ICC profile metadata.
                SetMetadataItem("COMMENT", pszComment);
                nPamFlags = nOldPamFlags;
            }
            CPLFree(pszComment);
        }
        else
        {
            if (abyChunkHeader[0] != 0xFF || (abyChunkHeader[1] & 0xf0) != 0xe0)
                break;  // Not an APP chunk.

            if (abyChunkHeader[1] == 0xe1 &&
                STARTS_WITH(reinterpret_cast<char *>(abyChunkHeader) + 4,
                            "Exif"))
            {
                nTIFFHEADER = nChunkLoc + 10;
            }
        }

        nChunkLoc += 2 + nChunkLength;
    }

    if (nTIFFHEADER < 0)
        return false;

    // Read TIFF header.
    TIFFHeader hdr = {0, 0, 0};

    VSIFSeekL(fp, nTIFFHEADER, SEEK_SET);
    if (VSIFReadL(&hdr, 1, sizeof(hdr), fp) != sizeof(hdr))
    {
        CPLError(CE_Failure, CPLE_FileIO,
                 "Failed to read %d byte from image header.",
                 static_cast<int>(sizeof(hdr)));
        return false;
    }

    if (hdr.tiff_magic != TIFF_BIGENDIAN && hdr.tiff_magic != TIFF_LITTLEENDIAN)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Not a TIFF file, bad magic number %u (%#x)", hdr.tiff_magic,
                 hdr.tiff_magic);
        return false;
    }

    if (hdr.tiff_magic == TIFF_BIGENDIAN)
        bSwabflag = !bigendian;
    if (hdr.tiff_magic == TIFF_LITTLEENDIAN)
        bSwabflag = bigendian;

    if (bSwabflag)
    {
        CPL_SWAP16PTR(&hdr.tiff_version);
        CPL_SWAP32PTR(&hdr.tiff_diroff);
    }

    if (hdr.tiff_version != TIFF_VERSION)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Not a TIFF file, bad version number %u (%#x)",
                 hdr.tiff_version, hdr.tiff_version);
        return false;
    }
    nTiffDirStart = hdr.tiff_diroff;

    CPLDebug("JPEG", "Magic: %#x <%s-endian> Version: %#x\n", hdr.tiff_magic,
             hdr.tiff_magic == TIFF_BIGENDIAN ? "big" : "little",
             hdr.tiff_version);

    return true;
}

/************************************************************************/
/*                            JPGMaskBand()                             */
/************************************************************************/

JPGMaskBand::JPGMaskBand(JPGDatasetCommon *poDSIn)

{
    poDS = poDSIn;
    nBand = 0;

    nRasterXSize = poDS->GetRasterXSize();
    nRasterYSize = poDS->GetRasterYSize();

    eDataType = GDT_Byte;
    nBlockXSize = nRasterXSize;
    nBlockYSize = 1;
}

/************************************************************************/
/*                             IReadBlock()                             */
/************************************************************************/

CPLErr JPGMaskBand::IReadBlock(int /* nBlockX */, int nBlockY, void *pImage)
{
    JPGDatasetCommon *poJDS = cpl::down_cast<JPGDatasetCommon *>(poDS);

    // Make sure the mask is loaded and decompressed.
    poJDS->DecompressMask();
    if (poJDS->pabyBitMask == nullptr)
        return CE_Failure;

    // Set mask based on bitmask for this scanline.
    GUInt32 iBit =
        static_cast<GUInt32>(nBlockY) * static_cast<GUInt32>(nBlockXSize);

    GByte *const pbyImage = static_cast<GByte *>(pImage);
    if (poJDS->bMaskLSBOrder)
    {
        for (int iX = 0; iX < nBlockXSize; iX++)
        {
            if (poJDS->pabyBitMask[iBit >> 3] & (0x1 << (iBit & 7)))
                pbyImage[iX] = 255;
            else
                pbyImage[iX] = 0;
            iBit++;
        }
    }
    else
    {
        for (int iX = 0; iX < nBlockXSize; iX++)
        {
            if (poJDS->pabyBitMask[iBit >> 3] & (0x1 << (7 - (iBit & 7))))
                pbyImage[iX] = 255;
            else
                pbyImage[iX] = 0;
            iBit++;
        }
    }

    return CE_None;
}

/************************************************************************/
/*                           JPGRasterBand()                            */
/************************************************************************/

JPGRasterBand::JPGRasterBand(JPGDatasetCommon *poDSIn, int nBandIn)
    : poGDS(poDSIn)
{
    poDS = poDSIn;

    nBand = nBandIn;
    if (poDSIn->GetDataPrecision() == 12)
        eDataType = GDT_UInt16;
    else
        eDataType = GDT_Byte;

    nBlockXSize = poDSIn->nRasterXSize;
    nBlockYSize = 1;

    GDALMajorObject::SetMetadataItem("COMPRESSION", "JPEG", "IMAGE_STRUCTURE");
}

/************************************************************************/
/*                           JPGCreateBand()                            */
/************************************************************************/

GDALRasterBand *JPGCreateBand(JPGDatasetCommon *poDS, int nBand)
{
    return new JPGRasterBand(poDS, nBand);
}

/************************************************************************/
/*                             IReadBlock()                             */
/************************************************************************/

CPLErr JPGRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)

{
    CPLAssert(nBlockXOff == 0);

    const int nXSize = GetXSize();
    const int nWordSize = GDALGetDataTypeSizeBytes(eDataType);
    if (poGDS->m_fpImage == nullptr)
    {
        memset(pImage, 0, nXSize * nWordSize);
        return CE_None;
    }

    // Load the desired scanline into the working buffer.
    CPLErr eErr = poGDS->LoadScanline(nBlockYOff);
    if (eErr != CE_None)
        return eErr;

    // Transfer between the working buffer the callers buffer.
    if (poGDS->GetRasterCount() == 1)
    {
#ifdef JPEG_LIB_MK1
        GDALCopyWords(poGDS->m_pabyScanline, GDT_UInt16, 2, pImage, eDataType,
                      nWordSize, nXSize);
#else
        memcpy(pImage, poGDS->m_pabyScanline, nXSize * nWordSize);
#endif
    }
    else
    {
#ifdef JPEG_LIB_MK1
        GDALCopyWords(poGDS->m_pabyScanline + (nBand - 1) * 2, GDT_UInt16, 6,
                      pImage, eDataType, nWordSize, nXSize);
#else
        if (poGDS->eGDALColorSpace == JCS_RGB &&
            poGDS->GetOutColorSpace() == JCS_CMYK && eDataType == GDT_Byte)
        {
            GByte *const pbyImage = static_cast<GByte *>(pImage);
            if (nBand == 1)
            {
                for (int i = 0; i < nXSize; i++)
                {
                    const int C = poGDS->m_pabyScanline[i * 4 + 0];
                    const int K = poGDS->m_pabyScanline[i * 4 + 3];
                    pbyImage[i] = static_cast<GByte>((C * K) / 255);
                }
            }
            else if (nBand == 2)
            {
                for (int i = 0; i < nXSize; i++)
                {
                    const int M = poGDS->m_pabyScanline[i * 4 + 1];
                    const int K = poGDS->m_pabyScanline[i * 4 + 3];
                    pbyImage[i] = static_cast<GByte>((M * K) / 255);
                }
            }
            else if (nBand == 3)
            {
                for (int i = 0; i < nXSize; i++)
                {
                    const int Y = poGDS->m_pabyScanline[i * 4 + 2];
                    const int K = poGDS->m_pabyScanline[i * 4 + 3];
                    pbyImage[i] = static_cast<GByte>((Y * K) / 255);
                }
            }
        }
        else
        {
            GDALCopyWords(poGDS->m_pabyScanline + (nBand - 1) * nWordSize,
                          eDataType, nWordSize * poGDS->GetRasterCount(),
                          pImage, eDataType, nWordSize, nXSize);
        }
#endif
    }

    // Forcibly load the other bands associated with this scanline.
    if (nBand == 1)
    {
        for (int iBand = 2; iBand <= poGDS->GetRasterCount(); iBand++)
        {
            GDALRasterBlock *const poBlock =
                poGDS->GetRasterBand(iBand)->GetLockedBlockRef(nBlockXOff,
                                                               nBlockYOff);
            if (poBlock != nullptr)
                poBlock->DropLock();
        }
    }

    return CE_None;
}

/************************************************************************/
/*                       GetColorInterpretation()                       */
/************************************************************************/

GDALColorInterp JPGRasterBand::GetColorInterpretation()

{
    if (poGDS->eGDALColorSpace == JCS_GRAYSCALE)
        return GCI_GrayIndex;

    else if (poGDS->eGDALColorSpace == JCS_RGB)
    {
        if (nBand == 1)
            return GCI_RedBand;
        else if (nBand == 2)
            return GCI_GreenBand;
        else
            return GCI_BlueBand;
    }
    else if (poGDS->eGDALColorSpace == JCS_CMYK)
    {
        if (nBand == 1)
            return GCI_CyanBand;
        else if (nBand == 2)
            return GCI_MagentaBand;
        else if (nBand == 3)
            return GCI_YellowBand;
        else
            return GCI_BlackBand;
    }
    else if (poGDS->eGDALColorSpace == JCS_YCbCr ||
             poGDS->eGDALColorSpace == JCS_YCCK)
    {
        if (nBand == 1)
            return GCI_YCbCr_YBand;
        else if (nBand == 2)
            return GCI_YCbCr_CbBand;
        else if (nBand == 3)
            return GCI_YCbCr_CrBand;
        else
            return GCI_BlackBand;
    }

    CPLAssert(false);
    return GCI_Undefined;
}

/************************************************************************/
/*                            GetMaskBand()                             */
/************************************************************************/

GDALRasterBand *JPGRasterBand::GetMaskBand()

{
    if (poGDS->nScaleFactor > 1)
        return GDALPamRasterBand::GetMaskBand();

    if (poGDS->m_fpImage == nullptr)
        return nullptr;

    if (!poGDS->bHasCheckedForMask)
    {
        if (CPLTestBool(CPLGetConfigOption("JPEG_READ_MASK", "YES")))
            poGDS->CheckForMask();
        poGDS->bHasCheckedForMask = true;
    }
    if (poGDS->pabyCMask)
    {
        if (poGDS->poMaskBand == nullptr)
            poGDS->poMaskBand = new JPGMaskBand(poGDS);

        return poGDS->poMaskBand;
    }

    return GDALPamRasterBand::GetMaskBand();
}

/************************************************************************/
/*                            GetMaskFlags()                            */
/************************************************************************/

int JPGRasterBand::GetMaskFlags()

{
    if (poGDS->nScaleFactor > 1)
        return GDALPamRasterBand::GetMaskFlags();

    if (poGDS->m_fpImage == nullptr)
        return 0;

    GetMaskBand();
    if (poGDS->poMaskBand != nullptr)
        return GMF_PER_DATASET;

    return GDALPamRasterBand::GetMaskFlags();
}

/************************************************************************/
/*                            GetOverview()                             */
/************************************************************************/

GDALRasterBand *JPGRasterBand::GetOverview(int i)
{
    if (i < 0 || i >= GetOverviewCount())
        return nullptr;

    if (poGDS->nInternalOverviewsCurrent == 0)
        return GDALPamRasterBand::GetOverview(i);

    return poGDS->papoInternalOverviews[i]->GetRasterBand(nBand);
}

/************************************************************************/
/*                         GetOverviewCount()                           */
/************************************************************************/

int JPGRasterBand::GetOverviewCount()
{
    if (!poGDS->AreOverviewsEnabled())
        return 0;

    poGDS->InitInternalOverviews();

    if (poGDS->nInternalOverviewsCurrent == 0)
        return GDALPamRasterBand::GetOverviewCount();

    return poGDS->nInternalOverviewsCurrent;
}

/************************************************************************/
/* ==================================================================== */
/*                             JPGDataset                               */
/* ==================================================================== */
/************************************************************************/

JPGDatasetCommon::JPGDatasetCommon()
    : nScaleFactor(1), bHasInitInternalOverviews(false),
      nInternalOverviewsCurrent(0), nInternalOverviewsToFree(0),
      papoInternalOverviews(nullptr), bGeoTransformValid(false), nGCPCount(0),
      pasGCPList(nullptr), m_fpImage(nullptr), nSubfileOffset(0),
      nLoadedScanline(-1), m_pabyScanline(nullptr), bHasReadEXIFMetadata(false),
      bHasReadXMPMetadata(false), bHasReadICCMetadata(false),
      papszMetadata(nullptr), nExifOffset(-1), nInterOffset(-1), nGPSOffset(-1),
      bSwabflag(false), nTiffDirStart(-1), nTIFFHEADER(-1),
      bHasDoneJpegCreateDecompress(false), bHasDoneJpegStartDecompress(false),
      bHasCheckedForMask(false), poMaskBand(nullptr), pabyBitMask(nullptr),
      bMaskLSBOrder(true), pabyCMask(nullptr), nCMaskSize(0),
      eGDALColorSpace(JCS_UNKNOWN), bIsSubfile(false),
      bHasTriedLoadWorldFileOrTab(false)
{
    adfGeoTransform[0] = 0.0;
    adfGeoTransform[1] = 1.0;
    adfGeoTransform[2] = 0.0;
    adfGeoTransform[3] = 0.0;
    adfGeoTransform[4] = 0.0;
    adfGeoTransform[5] = 1.0;
}

/************************************************************************/
/*                           ~JPGDataset()                              */
/************************************************************************/

JPGDatasetCommon::~JPGDatasetCommon()

{
    if (m_fpImage != nullptr)
        VSIFCloseL(m_fpImage);

    if (m_pabyScanline != nullptr)
        CPLFree(m_pabyScanline);
    if (papszMetadata != nullptr)
        CSLDestroy(papszMetadata);

    if (nGCPCount > 0)
    {
        GDALDeinitGCPs(nGCPCount, pasGCPList);
        CPLFree(pasGCPList);
    }

    CPLFree(pabyBitMask);
    CPLFree(pabyCMask);
    delete poMaskBand;

    JPGDatasetCommon::CloseDependentDatasets();
}

/************************************************************************/
/*                       CloseDependentDatasets()                       */
/************************************************************************/

int JPGDatasetCommon::CloseDependentDatasets()
{
    int bRet = GDALPamDataset::CloseDependentDatasets();
    if (nInternalOverviewsToFree)
    {
        bRet = TRUE;
        for (int i = 0; i < nInternalOverviewsToFree; i++)
            delete papoInternalOverviews[i];
        nInternalOverviewsToFree = 0;
    }
    CPLFree(papoInternalOverviews);
    papoInternalOverviews = nullptr;

    return bRet;
}

/************************************************************************/
/*                          InitEXIFOverview()                          */
/************************************************************************/

GDALDataset *JPGDatasetCommon::InitEXIFOverview()
{
    if (!EXIFInit(m_fpImage))
        return nullptr;

    // Read number of entry in directory.
    GUInt16 nEntryCount = 0;
    if (nTiffDirStart > (INT_MAX - nTIFFHEADER) ||
        VSIFSeekL(m_fpImage, nTiffDirStart + nTIFFHEADER, SEEK_SET) != 0 ||
        VSIFReadL(&nEntryCount, 1, sizeof(GUInt16), m_fpImage) !=
            sizeof(GUInt16))
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Error reading EXIF Directory count at " CPL_FRMT_GUIB,
                 static_cast<vsi_l_offset>(nTiffDirStart) + nTIFFHEADER);
        return nullptr;
    }

    if (bSwabflag)
        CPL_SWAP16PTR(&nEntryCount);

    // Some files are corrupt, a large entry count is a sign of this.
    if (nEntryCount > 125)
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                 "Ignoring EXIF directory with unlikely entry count (%d).",
                 nEntryCount);
        return nullptr;
    }

    // Skip EXIF entries.
    VSIFSeekL(m_fpImage, nEntryCount * sizeof(GDALEXIFTIFFDirEntry), SEEK_CUR);

    // Read offset of next directory (IFD1).
    GUInt32 nNextDirOff = 0;
    if (VSIFReadL(&nNextDirOff, 1, sizeof(GUInt32), m_fpImage) !=
        sizeof(GUInt32))
        return nullptr;
    if (bSwabflag)
        CPL_SWAP32PTR(&nNextDirOff);
    if (nNextDirOff == 0 || nNextDirOff > UINT_MAX - nTIFFHEADER)
        return nullptr;

    // Seek to IFD1.
    if (VSIFSeekL(m_fpImage, nTIFFHEADER + nNextDirOff, SEEK_SET) != 0 ||
        VSIFReadL(&nEntryCount, 1, sizeof(GUInt16), m_fpImage) !=
            sizeof(GUInt16))
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Error reading IFD1 Directory count at %d.",
                 nTIFFHEADER + nNextDirOff);
        return nullptr;
    }

    if (bSwabflag)
        CPL_SWAP16PTR(&nEntryCount);
    if (nEntryCount > 125)
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                 "Ignoring IFD1 directory with unlikely entry count (%d).",
                 nEntryCount);
        return nullptr;
    }
#if DEBUG_VERBOSE
    CPLDebug("JPEG", "IFD1 entry count = %d", nEntryCount);
#endif

    int nImageWidth = 0;
    int nImageHeight = 0;
    int nCompression = 6;
    GUInt32 nJpegIFOffset = 0;
    GUInt32 nJpegIFByteCount = 0;
    for (int i = 0; i < nEntryCount; i++)
    {
        GDALEXIFTIFFDirEntry sEntry;
        if (VSIFReadL(&sEntry, 1, sizeof(sEntry), m_fpImage) != sizeof(sEntry))
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Cannot read entry %d of IFD1", i);
            return nullptr;
        }
        if (bSwabflag)
        {
            CPL_SWAP16PTR(&sEntry.tdir_tag);
            CPL_SWAP16PTR(&sEntry.tdir_type);
            CPL_SWAP32PTR(&sEntry.tdir_count);
            CPL_SWAP32PTR(&sEntry.tdir_offset);
        }

#ifdef DEBUG_VERBOSE
        CPLDebug("JPEG", "tag = %d (0x%4X), type = %d, count = %d, offset = %d",
                 sEntry.tdir_tag, sEntry.tdir_tag, sEntry.tdir_type,
                 sEntry.tdir_count, sEntry.tdir_offset);
#endif

        if ((sEntry.tdir_type == TIFF_SHORT || sEntry.tdir_type == TIFF_LONG) &&
            sEntry.tdir_count == 1)
        {
            switch (sEntry.tdir_tag)
            {
                case JPEG_TIFF_IMAGEWIDTH:
                    nImageWidth = sEntry.tdir_offset;
                    break;
                case JPEG_TIFF_IMAGEHEIGHT:
                    nImageHeight = sEntry.tdir_offset;
                    break;
                case JPEG_TIFF_COMPRESSION:
                    nCompression = sEntry.tdir_offset;
                    break;
                case JPEG_EXIF_JPEGIFOFSET:
                    nJpegIFOffset = sEntry.tdir_offset;
                    break;
                case JPEG_EXIF_JPEGIFBYTECOUNT:
                    nJpegIFByteCount = sEntry.tdir_offset;
                    break;
                default:
                    break;
            }
        }
    }
    if (nCompression != 6 || nImageWidth >= nRasterXSize ||
        nImageHeight >= nRasterYSize || nJpegIFOffset == 0 ||
        nJpegIFOffset > UINT_MAX - nTIFFHEADER ||
        static_cast<int>(nJpegIFByteCount) <= 0)
    {
        return nullptr;
    }

    const char *pszSubfile =
        CPLSPrintf("JPEG_SUBFILE:%u,%d,%s", nTIFFHEADER + nJpegIFOffset,
                   nJpegIFByteCount, GetDescription());
    JPGDatasetOpenArgs sArgs;
    sArgs.pszFilename = pszSubfile;
    sArgs.fpLin = nullptr;
    sArgs.papszSiblingFiles = nullptr;
    sArgs.nScaleFactor = 1;
    sArgs.bDoPAMInitialize = false;
    sArgs.bUseInternalOverviews = false;
    return JPGDataset::Open(&sArgs);
}

/************************************************************************/
/*                       InitInternalOverviews()                        */
/************************************************************************/

void JPGDatasetCommon::InitInternalOverviews()
{
    if (bHasInitInternalOverviews)
        return;
    bHasInitInternalOverviews = true;

    // Instantiate on-the-fly overviews (if no external ones).
    if (nScaleFactor == 1 && GetRasterBand(1)->GetOverviewCount() == 0)
    {
        // EXIF overview.
        GDALDataset *poEXIFOverview = nullptr;
        if (nRasterXSize > 512 || nRasterYSize > 512)
        {
            const vsi_l_offset nCurOffset = VSIFTellL(m_fpImage);
            poEXIFOverview = InitEXIFOverview();
            if (poEXIFOverview != nullptr)
            {
                if (poEXIFOverview->GetRasterCount() != nBands ||
                    poEXIFOverview->GetRasterXSize() >= nRasterXSize ||
                    poEXIFOverview->GetRasterYSize() >= nRasterYSize)
                {
                    GDALClose(poEXIFOverview);
                    poEXIFOverview = nullptr;
                }
                else
                {
                    CPLDebug("JPEG", "EXIF overview (%d x %d) detected",
                             poEXIFOverview->GetRasterXSize(),
                             poEXIFOverview->GetRasterYSize());
                }
            }
            VSIFSeekL(m_fpImage, nCurOffset, SEEK_SET);
        }

        // libjpeg-6b only supports 2, 4 and 8 scale denominators.
        // TODO: Later versions support more.

        int nImplicitOverviews = 0;

        // For the needs of the implicit JPEG-in-TIFF overview mechanism.
        if (CPLTestBool(
                CPLGetConfigOption("JPEG_FORCE_INTERNAL_OVERVIEWS", "NO")))
        {
            nImplicitOverviews = 3;
        }
        else
        {
            for (int i = 2; i >= 0; i--)
            {
                if (nRasterXSize >= (256 << i) || nRasterYSize >= (256 << i))
                {
                    nImplicitOverviews = i + 1;
                    break;
                }
            }
        }

        if (nImplicitOverviews > 0)
        {
            ppoActiveDS = &poActiveDS;
            papoInternalOverviews = static_cast<GDALDataset **>(
                CPLMalloc((nImplicitOverviews + (poEXIFOverview ? 1 : 0)) *
                          sizeof(GDALDataset *)));
            for (int i = 0; i < nImplicitOverviews; i++)
            {
                if (poEXIFOverview != nullptr &&
                    poEXIFOverview->GetRasterXSize() >= nRasterXSize >> (i + 1))
                {
                    break;
                }
                JPGDatasetOpenArgs sArgs;
                sArgs.pszFilename = GetDescription();
                sArgs.fpLin = nullptr;
                sArgs.papszSiblingFiles = nullptr;
                sArgs.nScaleFactor = 1 << (i + 1);
                sArgs.bDoPAMInitialize = false;
                sArgs.bUseInternalOverviews = false;
                JPGDatasetCommon *poImplicitOverview = JPGDataset::Open(&sArgs);
                if (poImplicitOverview == nullptr)
                    break;
                poImplicitOverview->ppoActiveDS = &poActiveDS;
                papoInternalOverviews[nInternalOverviewsCurrent] =
                    poImplicitOverview;
                nInternalOverviewsCurrent++;
                nInternalOverviewsToFree++;
            }
            if (poEXIFOverview != nullptr)
            {
                papoInternalOverviews[nInternalOverviewsCurrent] =
                    poEXIFOverview;
                nInternalOverviewsCurrent++;
                nInternalOverviewsToFree++;
            }
        }
        else if (poEXIFOverview)
        {
            papoInternalOverviews =
                static_cast<GDALDataset **>(CPLMalloc(sizeof(GDALDataset *)));
            papoInternalOverviews[0] = poEXIFOverview;
            nInternalOverviewsCurrent++;
            nInternalOverviewsToFree++;
        }
    }
}

/************************************************************************/
/*                          IBuildOverviews()                           */
/************************************************************************/

CPLErr JPGDatasetCommon::IBuildOverviews(const char *pszResampling,
                                         int nOverviewsListCount,
                                         const int *panOverviewList,
                                         int nListBands, const int *panBandList,
                                         GDALProgressFunc pfnProgress,
                                         void *pProgressData,
                                         CSLConstList papszOptions)
{
    bHasInitInternalOverviews = true;
    nInternalOverviewsCurrent = 0;

    return GDALPamDataset::IBuildOverviews(
        pszResampling, nOverviewsListCount, panOverviewList, nListBands,
        panBandList, pfnProgress, pProgressData, papszOptions);
}

/************************************************************************/
/*                           FlushCache(bool bAtClosing) */
/************************************************************************/

void JPGDatasetCommon::FlushCache(bool bAtClosing)

{
    GDALPamDataset::FlushCache(bAtClosing);

    if (bHasDoneJpegStartDecompress)
    {
        Restart();
    }

    // For the needs of the implicit JPEG-in-TIFF overview mechanism.
    for (int i = 0; i < nInternalOverviewsCurrent; i++)
        papoInternalOverviews[i]->FlushCache(bAtClosing);
}

#endif  // !defined(JPGDataset)

/************************************************************************/
/*                            JPGDataset()                              */
/************************************************************************/

JPGDataset::JPGDataset() : nQLevel(0)
{
    memset(&sDInfo, 0, sizeof(sDInfo));
    sDInfo.data_precision = 8;

    memset(&sJErr, 0, sizeof(sJErr));
    memset(&sJProgress, 0, sizeof(sJProgress));
}

/************************************************************************/
/*                           ~JPGDataset()                            */
/************************************************************************/

JPGDataset::~JPGDataset()

{
    GDALPamDataset::FlushCache(true);
    JPGDataset::StopDecompress();
}

/************************************************************************/
/*                           StopDecompress()                           */
/************************************************************************/

void JPGDataset::StopDecompress()
{
    if (bHasDoneJpegStartDecompress)
    {
        jpeg_abort_decompress(&sDInfo);
        bHasDoneJpegStartDecompress = false;
    }
    if (bHasDoneJpegCreateDecompress)
    {
        jpeg_destroy_decompress(&sDInfo);
        bHasDoneJpegCreateDecompress = false;
    }
    nLoadedScanline = INT_MAX;
    if (ppoActiveDS)
        *ppoActiveDS = nullptr;
}

/************************************************************************/
/*                      ErrorOutOnNonFatalError()                       */
/************************************************************************/

bool JPGDataset::ErrorOutOnNonFatalError()
{
    if (sUserData.bNonFatalErrorEncountered)
    {
        sUserData.bNonFatalErrorEncountered = false;
        return true;
    }
    return false;
}

/************************************************************************/
/*                          StartDecompress()                           */
/************************************************************************/

CPLErr JPGDataset::StartDecompress()
{
    /* In some cases, libjpeg needs to allocate a lot of memory */
    /* http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
     */
    if (jpeg_has_multiple_scans(&(sDInfo)))
    {
        /* In this case libjpeg will need to allocate memory or backing */
        /* store for all coefficients */
        /* See call to jinit_d_coef_controller() from master_selection() */
        /* in libjpeg */

        // 1 MB for regular libjpeg usage
        vsi_l_offset nRequiredMemory = 1024 * 1024;

        for (int ci = 0; ci < sDInfo.num_components; ci++)
        {
            const jpeg_component_info *compptr = &(sDInfo.comp_info[ci]);
            if (compptr->h_samp_factor <= 0 || compptr->v_samp_factor <= 0)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Invalid sampling factor(s)");
                return CE_Failure;
            }
            nRequiredMemory +=
                static_cast<vsi_l_offset>(DIV_ROUND_UP(
                    compptr->width_in_blocks, compptr->h_samp_factor)) *
                DIV_ROUND_UP(compptr->height_in_blocks,
                             compptr->v_samp_factor) *
                sizeof(JBLOCK);
        }

        if (nRequiredMemory > 10 * 1024 * 1024 && ppoActiveDS &&
            *ppoActiveDS != this)
        {
            // If another overview was active, stop it to limit memory
            // consumption
            if (*ppoActiveDS)
                (*ppoActiveDS)->StopDecompress();
            *ppoActiveDS = this;
        }

        if (sDInfo.mem->max_memory_to_use > 0 &&
            nRequiredMemory >
                static_cast<vsi_l_offset>(sDInfo.mem->max_memory_to_use) &&
            CPLGetConfigOption("GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC", nullptr) ==
                nullptr)
        {
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Reading this image would require libjpeg to allocate "
                     "at least " CPL_FRMT_GUIB " bytes. "
                     "This is disabled since above the " CPL_FRMT_GUIB
                     " threshold. "
                     "You may override this restriction by defining the "
                     "GDAL_ALLOW_LARGE_LIBJPEG_MEM_ALLOC environment variable, "
                     "or setting the JPEGMEM environment variable to a value "
                     "greater "
                     "or equal to '" CPL_FRMT_GUIB "M'",
                     static_cast<GUIntBig>(nRequiredMemory),
                     static_cast<GUIntBig>(sDInfo.mem->max_memory_to_use),
                     static_cast<GUIntBig>((nRequiredMemory + 1000000 - 1) /
                                           1000000));
            return CE_Failure;
        }
    }

    sDInfo.progress = &sJProgress;
    sJProgress.progress_monitor = JPGDataset::ProgressMonitor;
    jpeg_start_decompress(&sDInfo);
    bHasDoneJpegStartDecompress = true;

    return CE_None;
}

/************************************************************************/
/*                            LoadScanline()                            */
/************************************************************************/

CPLErr JPGDataset::LoadScanline(int iLine, GByte *outBuffer)

{
    if (nLoadedScanline == iLine)
        return CE_None;

    // code path triggered when an active reader has been stopped by another
    // one, in case of multiple scans datasets and overviews
    if (!bHasDoneJpegCreateDecompress && Restart() != CE_None)
        return CE_Failure;

    // setup to trap a fatal error.
    if (setjmp(sUserData.setjmp_buffer))
        return CE_Failure;

    if (!bHasDoneJpegStartDecompress && StartDecompress() != CE_None)
        return CE_Failure;

    if (outBuffer == nullptr && m_pabyScanline == nullptr)
    {
        int nJPEGBands = 0;
        switch (sDInfo.out_color_space)
        {
            case JCS_GRAYSCALE:
                nJPEGBands = 1;
                break;
            case JCS_RGB:
            case JCS_YCbCr:
                nJPEGBands = 3;
                break;
            case JCS_CMYK:
            case JCS_YCCK:
                nJPEGBands = 4;
                break;

            default:
                CPLAssert(false);
        }

        m_pabyScanline =
            static_cast<GByte *>(CPLMalloc(nJPEGBands * GetRasterXSize() * 2));
    }

    if (iLine < nLoadedScanline)
    {
        if (Restart() != CE_None)
            return CE_Failure;
    }

    while (nLoadedScanline < iLine)
    {
        JSAMPLE *ppSamples =
            reinterpret_cast<JSAMPLE *>(outBuffer ? outBuffer : m_pabyScanline);
        jpeg_read_scanlines(&sDInfo, &ppSamples, 1);
        if (ErrorOutOnNonFatalError())
            return CE_Failure;
        nLoadedScanline++;
    }

    return CE_None;
}

/************************************************************************/
/*                         LoadDefaultTables()                          */
/************************************************************************/

#if !defined(JPGDataset)

#define Q1table GDALJPEG_Q1table
#define Q2table GDALJPEG_Q2table
#define Q3table GDALJPEG_Q3table
#define Q4table GDALJPEG_Q4table
#define Q5table GDALJPEG_Q5table
#define AC_BITS GDALJPEG_AC_BITS
#define AC_HUFFVAL GDALJPEG_AC_HUFFVAL
#define DC_BITS GDALJPEG_DC_BITS
#define DC_HUFFVAL GDALJPEG_DC_HUFFVAL

constexpr GByte Q1table[64] = {
    8,   72,  72,  72,  72,  72,  72,  72,   // 0 - 7
    72,  72,  78,  74,  76,  74,  78,  89,   // 8 - 15
    81,  84,  84,  81,  89,  106, 93,  94,   // 16 - 23
    99,  94,  93,  106, 129, 111, 108, 116,  // 24 - 31
    116, 108, 111, 129, 135, 128, 136, 145,  // 32 - 39
    136, 128, 135, 155, 160, 177, 177, 160,  // 40 - 47
    155, 193, 213, 228, 213, 193, 255, 255,  // 48 - 55
    255, 255, 255, 255, 255, 255, 255, 255   // 56 - 63
};

constexpr GByte Q2table[64] = {
    8,   36, 36,  36,  36,  36,  36,  36,  36,  36,  39,  37,  38,
    37,  39, 45,  41,  42,  42,  41,  45,  53,  47,  47,  50,  47,
    47,  53, 65,  56,  54,  59,  59,  54,  56,  65,  68,  64,  69,
    73,  69, 64,  68,  78,  81,  89,  89,  81,  78,  98,  108, 115,
    108, 98, 130, 144, 144, 130, 178, 190, 178, 243, 243, 255};

constexpr GByte Q3table[64] = {
    8,  10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 10, 11, 10, 11, 13,
    11, 12, 12, 11, 13, 15, 13, 13, 14, 13, 13, 15, 18, 16, 15, 16,
    16, 15, 16, 18, 19, 18, 19, 21, 19, 18, 19, 22, 23, 25, 25, 23,
    22, 27, 30, 32, 30, 27, 36, 40, 40, 36, 50, 53, 50, 68, 68, 91};

constexpr GByte Q4table[64] = {
    8,  7,  7,  7,  7,  7,  7,  7,  7,  7,  8,  7,  8,  7,  8,  9,
    8,  8,  8,  8,  9,  11, 9,  9,  10, 9,  9,  11, 13, 11, 11, 12,
    12, 11, 11, 13, 14, 13, 14, 15, 14, 13, 14, 16, 16, 18, 18, 16,
    16, 20, 22, 23, 22, 20, 26, 29, 29, 26, 36, 38, 36, 49, 49, 65};

constexpr GByte Q5table[64] = {
    4, 4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  4,  5,
    5, 5,  5,  5,  5,  6,  5,  5,  6,  5,  5,  6,  7,  6,  6,  6,
    6, 6,  6,  7,  8,  7,  8,  8,  8,  7,  8,  9,  9,  10, 10, 9,
    9, 11, 12, 13, 12, 11, 14, 16, 16, 14, 20, 21, 20, 27, 27, 36};

constexpr GByte AC_BITS[16] = {0, 2, 1, 3, 3, 2, 4, 3,
                               5, 5, 4, 4, 0, 0, 1, 125};

constexpr GByte AC_HUFFVAL[256] = {
    0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
    0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08,
    0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, 0x24, 0x33, 0x62, 0x72,
    0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28,
    0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45,
    0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
    0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74, 0x75,
    0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
    0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3,
    0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6,
    0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9,
    0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2,
    0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4,
    0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

constexpr GByte DC_BITS[16] = {0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0};

constexpr GByte DC_HUFFVAL[256] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
                                   0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B};

void JPGDataset::LoadDefaultTables(int n)
{
    if (nQLevel < 1)
        return;

    // Load quantization table.
    JQUANT_TBL *quant_ptr = nullptr;
    const GByte *pabyQTable = nullptr;

    if (nQLevel == 1)
        pabyQTable = Q1table;
    else if (nQLevel == 2)
        pabyQTable = Q2table;
    else if (nQLevel == 3)
        pabyQTable = Q3table;
    else if (nQLevel == 4)
        pabyQTable = Q4table;
    else if (nQLevel == 5)
        pabyQTable = Q5table;
    else
        return;

    if (sDInfo.quant_tbl_ptrs[n] == nullptr)
        sDInfo.quant_tbl_ptrs[n] =
            jpeg_alloc_quant_table(reinterpret_cast<j_common_ptr>(&sDInfo));

    quant_ptr = sDInfo.quant_tbl_ptrs[n];  // quant_ptr is JQUANT_TBL.
    for (int i = 0; i < 64; i++)
    {
        // Qtable[] is desired quantization table, in natural array order.
        quant_ptr->quantval[i] = pabyQTable[i];
    }

    // Load AC huffman table.
    if (sDInfo.ac_huff_tbl_ptrs[n] == nullptr)
        sDInfo.ac_huff_tbl_ptrs[n] =
            jpeg_alloc_huff_table(reinterpret_cast<j_common_ptr>(&sDInfo));

    // huff_ptr is JHUFF_TBL*.
    JHUFF_TBL *huff_ptr = sDInfo.ac_huff_tbl_ptrs[n];

    for (int i = 1; i <= 16; i++)
    {
        // counts[i] is number of Huffman codes of length i bits, i=1..16
        huff_ptr->bits[i] = AC_BITS[i - 1];
    }

    for (int i = 0; i < 256; i++)
    {
        // symbols[] is the list of Huffman symbols, in code-length order.
        huff_ptr->huffval[i] = AC_HUFFVAL[i];
    }

    // Load DC huffman table.
    // TODO(schwehr): Revisit this "sideways" cast.
    if (sDInfo.dc_huff_tbl_ptrs[n] == nullptr)
        sDInfo.dc_huff_tbl_ptrs[n] =
            jpeg_alloc_huff_table(reinterpret_cast<j_common_ptr>(&sDInfo));

    huff_ptr = sDInfo.dc_huff_tbl_ptrs[n];  // huff_ptr is JHUFF_TBL*

    for (int i = 1; i <= 16; i++)
    {
        // counts[i] is number of Huffman codes of length i bits, i=1..16
        huff_ptr->bits[i] = DC_BITS[i - 1];
    }

    for (int i = 0; i < 256; i++)
    {
        // symbols[] is the list of Huffman symbols, in code-length order.
        huff_ptr->huffval[i] = DC_HUFFVAL[i];
    }
}
#endif  // !defined(JPGDataset)

/************************************************************************/
/*                       SetScaleNumAndDenom()                          */
/************************************************************************/

void JPGDataset::SetScaleNumAndDenom()
{
#if JPEG_LIB_VERSION > 62
    sDInfo.scale_num = 8 / nScaleFactor;
    sDInfo.scale_denom = 8;
#else
    sDInfo.scale_num = 1;
    sDInfo.scale_denom = nScaleFactor;
#endif
}

/************************************************************************/
/*                              Restart()                               */
/*                                                                      */
/*      Restart compressor at the beginning of the file.                */
/************************************************************************/

CPLErr JPGDataset::Restart()

{
    if (ppoActiveDS && *ppoActiveDS != this && *ppoActiveDS != nullptr)
    {
        (*ppoActiveDS)->StopDecompress();
    }

    // Setup to trap a fatal error.
    if (setjmp(sUserData.setjmp_buffer))
        return CE_Failure;

    J_COLOR_SPACE colorSpace = sDInfo.out_color_space;
    J_COLOR_SPACE jpegColorSpace = sDInfo.jpeg_color_space;

    StopDecompress();
    jpeg_create_decompress(&sDInfo);
    bHasDoneJpegCreateDecompress = true;

    SetMaxMemoryToUse(&sDInfo);

#if !defined(JPGDataset)
    LoadDefaultTables(0);
    LoadDefaultTables(1);
    LoadDefaultTables(2);
    LoadDefaultTables(3);
#endif  // !defined(JPGDataset)

    // Restart IO.
    VSIFSeekL(m_fpImage, nSubfileOffset, SEEK_SET);

    jpeg_vsiio_src(&sDInfo, m_fpImage);
    jpeg_read_header(&sDInfo, TRUE);

    sDInfo.out_color_space = colorSpace;
    nLoadedScanline = -1;
    SetScaleNumAndDenom();

    // The following errors could happen when "recycling" an existing dataset
    // particularly when triggered by the implicit overviews of JPEG-in-TIFF
    // with a corrupted TIFF file.
    if (nRasterXSize !=
            static_cast<int>(sDInfo.image_width + nScaleFactor - 1) /
                nScaleFactor ||
        nRasterYSize !=
            static_cast<int>(sDInfo.image_height + nScaleFactor - 1) /
                nScaleFactor)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Unexpected image dimension (%d x %d), "
                 "where as (%d x %d) was expected",
                 static_cast<int>(sDInfo.image_width + nScaleFactor - 1) /
                     nScaleFactor,
                 static_cast<int>(sDInfo.image_height + nScaleFactor - 1) /
                     nScaleFactor,
                 nRasterXSize, nRasterYSize);
        bHasDoneJpegStartDecompress = false;
    }
    else if (jpegColorSpace != sDInfo.jpeg_color_space)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Unexpected jpeg color space : %d", sDInfo.jpeg_color_space);
        bHasDoneJpegStartDecompress = false;
    }
    else
    {
        if (StartDecompress() != CE_None)
            return CE_Failure;
        if (ppoActiveDS)
            *ppoActiveDS = this;
    }

    return CE_None;
}

#if !defined(JPGDataset)

/************************************************************************/
/*                          GetGeoTransform()                           */
/************************************************************************/

CPLErr JPGDatasetCommon::GetGeoTransform(double *padfTransform)

{
    CPLErr eErr = GDALPamDataset::GetGeoTransform(padfTransform);
    if (eErr != CE_Failure)
        return eErr;

    LoadWorldFileOrTab();

    if (bGeoTransformValid)
    {
        memcpy(padfTransform, adfGeoTransform, sizeof(double) * 6);

        return CE_None;
    }

    return eErr;
}

/************************************************************************/
/*                            GetGCPCount()                             */
/************************************************************************/

int JPGDatasetCommon::GetGCPCount()

{
    const int nPAMGCPCount = GDALPamDataset::GetGCPCount();
    if (nPAMGCPCount != 0)
        return nPAMGCPCount;

    LoadWorldFileOrTab();

    return nGCPCount;
}

/************************************************************************/
/*                          GetGCPSpatialRef()                          */
/************************************************************************/

const OGRSpatialReference *JPGDatasetCommon::GetGCPSpatialRef() const

{
    const int nPAMGCPCount =
        const_cast<JPGDatasetCommon *>(this)->GDALPamDataset::GetGCPCount();
    if (nPAMGCPCount != 0)
        return GDALPamDataset::GetGCPSpatialRef();

    const_cast<JPGDatasetCommon *>(this)->LoadWorldFileOrTab();

    if (!m_oSRS.IsEmpty() && nGCPCount > 0)
        return &m_oSRS;

    return nullptr;
}

/************************************************************************/
/*                               GetGCPs()                              */
/************************************************************************/

const GDAL_GCP *JPGDatasetCommon::GetGCPs()

{
    const int nPAMGCPCount = GDALPamDataset::GetGCPCount();
    if (nPAMGCPCount != 0)
        return GDALPamDataset::GetGCPs();

    LoadWorldFileOrTab();

    return pasGCPList;
}

/************************************************************************/
/*                             IRasterIO()                              */
/*                                                                      */
/*      Checks for what might be the most common read case              */
/*      (reading an entire 8bit, RGB JPEG), and                         */
/*      optimizes for that case                                         */
/************************************************************************/

CPLErr JPGDatasetCommon::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
                                   int nXSize, int nYSize, void *pData,
                                   int nBufXSize, int nBufYSize,
                                   GDALDataType eBufType, int nBandCount,
                                   int *panBandMap, GSpacing nPixelSpace,
                                   GSpacing nLineSpace, GSpacing nBandSpace,
                                   GDALRasterIOExtraArg *psExtraArg)

{
    // Coverity says that we cannot pass a nullptr to IRasterIO.
    if (panBandMap == nullptr)
    {
        return CE_Failure;
    }

#ifndef JPEG_LIB_MK1
    if ((eRWFlag == GF_Read) && (nBandCount == 3) && (nBands == 3) &&
        (nXOff == 0) && (nYOff == 0) && (nXSize == nBufXSize) &&
        (nXSize == nRasterXSize) && (nYSize == nBufYSize) &&
        (nYSize == nRasterYSize) && (eBufType == GDT_Byte) &&
        (GetDataPrecision() != 12) && (pData != nullptr) &&
        (panBandMap[0] == 1) && (panBandMap[1] == 2) && (panBandMap[2] == 3) &&
        // These color spaces need to be transformed to RGB.
        GetOutColorSpace() != JCS_YCCK && GetOutColorSpace() != JCS_CMYK)
    {
        Restart();

        // Pixel interleaved case.
        if (nBandSpace == 1)
        {
            for (int y = 0; y < nYSize; ++y)
            {
                if (nPixelSpace == 3)
                {
                    CPLErr tmpError =
                        LoadScanline(y, &(((GByte *)pData)[(y * nLineSpace)]));
                    if (tmpError != CE_None)
                        return tmpError;
                }
                else
                {
                    CPLErr tmpError = LoadScanline(y);
                    if (tmpError != CE_None)
                        return tmpError;

                    for (int x = 0; x < nXSize; ++x)
                    {
                        memcpy(&(((GByte *)pData)[(y * nLineSpace) +
                                                  (x * nPixelSpace)]),
                               (const GByte *)&(m_pabyScanline[x * 3]), 3);
                    }
                }
            }
            nLoadedScanline = nRasterYSize;
        }
        else
        {
            for (int y = 0; y < nYSize; ++y)
            {
                CPLErr tmpError = LoadScanline(y);
                if (tmpError != CE_None)
                    return tmpError;
                for (int x = 0; x < nXSize; ++x)
                {
                    static_cast<GByte *>(
                        pData)[(y * nLineSpace) + (x * nPixelSpace)] =
                        m_pabyScanline[x * 3];
                    ((GByte *)pData)[(y * nLineSpace) + (x * nPixelSpace) +
                                     nBandSpace] = m_pabyScanline[x * 3 + 1];
                    ((GByte *)pData)[(y * nLineSpace) + (x * nPixelSpace) +
                                     2 * nBandSpace] =
                        m_pabyScanline[x * 3 + 2];
                }
            }
        }

        return CE_None;
    }
#endif

    return GDALPamDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
                                     pData, nBufXSize, nBufYSize, eBufType,
                                     nBandCount, panBandMap, nPixelSpace,
                                     nLineSpace, nBandSpace, psExtraArg);
}

#if JPEG_LIB_VERSION_MAJOR < 9
/************************************************************************/
/*                    JPEGDatasetIsJPEGLS()                             */
/************************************************************************/

static int JPEGDatasetIsJPEGLS(GDALOpenInfo *poOpenInfo)

{
    GByte *pabyHeader = poOpenInfo->pabyHeader;
    int nHeaderBytes = poOpenInfo->nHeaderBytes;

    if (nHeaderBytes < 10)
        return FALSE;

    if (pabyHeader[0] != 0xff || pabyHeader[1] != 0xd8)
        return FALSE;

    for (int nOffset = 2; nOffset + 4 < nHeaderBytes;)
    {
        if (pabyHeader[nOffset] != 0xFF)
            return FALSE;

        int nMarker = pabyHeader[nOffset + 1];
        if (nMarker == 0xF7)  // JPEG Extension 7, JPEG-LS.
            return TRUE;
        if (nMarker == 0xF8)  // JPEG Extension 8, JPEG-LS Extension.
            return TRUE;
        if (nMarker == 0xC3)  // Start of Frame 3.
            return TRUE;
        if (nMarker == 0xC7)  // Start of Frame 7.
            return TRUE;
        if (nMarker == 0xCB)  // Start of Frame 11.
            return TRUE;
        if (nMarker == 0xCF)  // Start of Frame 15.
            return TRUE;

        nOffset += 2 + pabyHeader[nOffset + 2] * 256 + pabyHeader[nOffset + 3];
    }

    return FALSE;
}
#endif

/************************************************************************/
/*                              Identify()                              */
/************************************************************************/

int JPGDatasetCommon::Identify(GDALOpenInfo *poOpenInfo)

{
    // If it is a subfile, read the JPEG header.
    if (STARTS_WITH_CI(poOpenInfo->pszFilename, "JPEG_SUBFILE:"))
        return TRUE;
    if (STARTS_WITH(poOpenInfo->pszFilename, "JPEG:"))
        return TRUE;

    // First we check to see if the file has the expected header bytes.
    const int nHeaderBytes = poOpenInfo->nHeaderBytes;

    if (nHeaderBytes < 10)
        return FALSE;

    GByte *const pabyHeader = poOpenInfo->pabyHeader;
    if (pabyHeader[0] != 0xff || pabyHeader[1] != 0xd8 || pabyHeader[2] != 0xff)
        return FALSE;

#if JPEG_LIB_VERSION_MAJOR < 9
    if (JPEGDatasetIsJPEGLS(poOpenInfo))
    {
        return FALSE;
    }
#endif

    // Some files like
    // http://dionecanali.hd.free.fr/~mdione/mapzen/N65E039.hgt.gz could be
    // mis-identfied as JPEG
    CPLString osFilenameLower = CPLString(poOpenInfo->pszFilename).tolower();
    if (osFilenameLower.endsWith(".hgt") ||
        osFilenameLower.endsWith(".hgt.gz") ||
        osFilenameLower.endsWith(".hgt.zip"))
    {
        return FALSE;
    }

    return TRUE;
}

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

GDALDataset *JPGDatasetCommon::Open(GDALOpenInfo *poOpenInfo)

{
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    // During fuzzing, do not use Identify to reject crazy content.
    if (!Identify(poOpenInfo))
        return nullptr;
#endif

    if (poOpenInfo->eAccess == GA_Update)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "The JPEG driver does not support update access to existing"
                 " datasets.");
        return nullptr;
    }

    CPLString osFilename(poOpenInfo->pszFilename);
    bool bFLIRRawThermalImage = false;
    if (STARTS_WITH(poOpenInfo->pszFilename, "JPEG:"))
    {
        CPLStringList aosTokens(CSLTokenizeString2(poOpenInfo->pszFilename, ":",
                                                   CSLT_HONOURSTRINGS));
        if (aosTokens.size() != 3)
            return nullptr;

        osFilename = aosTokens[1];
        if (std::string(aosTokens[2]) != "FLIR_RAW_THERMAL_IMAGE")
            return nullptr;
        bFLIRRawThermalImage = true;
    }

    VSILFILE *fpL = poOpenInfo->fpL;
    poOpenInfo->fpL = nullptr;

    JPGDatasetOpenArgs sArgs;
    sArgs.pszFilename = osFilename.c_str();
    sArgs.fpLin = fpL;
    sArgs.papszSiblingFiles = poOpenInfo->GetSiblingFiles();
    sArgs.nScaleFactor = 1;
    sArgs.bDoPAMInitialize = true;
    sArgs.bUseInternalOverviews = CPLFetchBool(poOpenInfo->papszOpenOptions,
                                               "USE_INTERNAL_OVERVIEWS", true);

    auto poDS = std::unique_ptr<JPGDatasetCommon>(JPGDataset::Open(&sArgs));
    if (poDS == nullptr)
    {
        return nullptr;
    }
    if (bFLIRRawThermalImage)
    {
        return poDS->OpenFLIRRawThermalImage();
    }
    return poDS.release();
}

/************************************************************************/
/*                       OpenFLIRRawThermalImage()                      */
/************************************************************************/

GDALDataset *JPGDatasetCommon::OpenFLIRRawThermalImage()
{
    ReadFLIRMetadata();
    if (m_abyRawThermalImage.empty())
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Cannot find FLIR raw thermal image");
        return nullptr;
    }

    GByte *pabyData =
        static_cast<GByte *>(CPLMalloc(m_abyRawThermalImage.size()));
    const std::string osTmpFilename(CPLSPrintf("/vsimem/jpeg/%p", pabyData));
    memcpy(pabyData, m_abyRawThermalImage.data(), m_abyRawThermalImage.size());
    VSILFILE *fpRaw = VSIFileFromMemBuffer(osTmpFilename.c_str(), pabyData,
                                           m_abyRawThermalImage.size(), true);

    // Termal image as uncompressed data
    if (m_nRawThermalImageWidth * m_nRawThermalImageHeight * 2 ==
        static_cast<int>(m_abyRawThermalImage.size()))
    {
        CPLDebug("JPEG", "Raw thermal image");

        class JPEGRawDataset : public RawDataset
        {
          public:
            JPEGRawDataset(int nXSizeIn, int nYSizeIn)
            {
                nRasterXSize = nXSizeIn;
                nRasterYSize = nYSizeIn;
            }
            ~JPEGRawDataset() = default;

            void SetBand(int nBand, GDALRasterBand *poBand)
            {
                RawDataset::SetBand(nBand, poBand);
            }
        };

        auto poBand = new RawRasterBand(
            fpRaw,
            0,                            // image offset
            2,                            // pixel offset
            2 * m_nRawThermalImageWidth,  // line offset
            GDT_UInt16,
            m_bRawThermalLittleEndian
                ? RawRasterBand::ByteOrder::ORDER_LITTLE_ENDIAN
                : RawRasterBand::ByteOrder::ORDER_BIG_ENDIAN,
            m_nRawThermalImageWidth, m_nRawThermalImageHeight,
            RawRasterBand::OwnFP::YES);

        auto poRawDS = new JPEGRawDataset(m_nRawThermalImageWidth,
                                          m_nRawThermalImageHeight);
        poRawDS->SetDescription(osTmpFilename.c_str());
        poRawDS->SetBand(1, poBand);
        poRawDS->MarkSuppressOnClose();
        return poRawDS;
    }

    VSIFCloseL(fpRaw);

    // Termal image as PNG
    if (m_abyRawThermalImage.size() > 4 &&
        memcmp(m_abyRawThermalImage.data(), "\x89PNG", 4) == 0)
    {
        auto poRawDS = GDALDataset::Open(osTmpFilename.c_str());
        if (poRawDS == nullptr)
        {
            CPLError(CE_Failure, CPLE_AppDefined, "Invalid raw thermal image");
            VSIUnlink(osTmpFilename.c_str());
            return nullptr;
        }
        poRawDS->MarkSuppressOnClose();
        return poRawDS;
    }

    CPLError(CE_Failure, CPLE_AppDefined,
             "Unrecognized format for raw thermal image");
    VSIUnlink(osTmpFilename.c_str());
    return nullptr;
}

#endif  // !defined(JPGDataset)

/************************************************************************/
/*                                Open()                                */
/************************************************************************/

JPGDatasetCommon *JPGDataset::Open(JPGDatasetOpenArgs *psArgs)

{
    JPGDataset *poDS = new JPGDataset();
    return OpenStage2(psArgs, poDS);
}

JPGDatasetCommon *JPGDataset::OpenStage2(JPGDatasetOpenArgs *psArgs,
                                         JPGDataset *&poDS)
{
    // Will detect mismatch between compile-time and run-time libjpeg versions.
    if (setjmp(poDS->sUserData.setjmp_buffer))
    {
#if defined(JPEG_DUAL_MODE_8_12) && !defined(JPGDataset)
        if (poDS->sDInfo.data_precision == 12 && poDS->m_fpImage != nullptr)
        {
            VSILFILE *fpImage = poDS->m_fpImage;
            poDS->m_fpImage = nullptr;
            delete poDS;
            psArgs->fpLin = fpImage;
            return JPEGDataset12Open(psArgs);
        }
#endif
        delete poDS;
        return nullptr;
    }

    const char *pszFilename = psArgs->pszFilename;
    VSILFILE *fpLin = psArgs->fpLin;
    char **papszSiblingFiles = psArgs->papszSiblingFiles;
    const int nScaleFactor = psArgs->nScaleFactor;
    const bool bDoPAMInitialize = psArgs->bDoPAMInitialize;
    const bool bUseInternalOverviews = psArgs->bUseInternalOverviews;

    // If it is a subfile, read the JPEG header.
    bool bIsSubfile = false;
    GUIntBig subfile_offset = 0;
    GUIntBig subfile_size = 0;
    const char *real_filename = pszFilename;
    int nQLevel = -1;

    if (STARTS_WITH_CI(pszFilename, "JPEG_SUBFILE:"))
    {
        bool bScan = false;

        if (STARTS_WITH_CI(pszFilename, "JPEG_SUBFILE:Q"))
        {
            char **papszTokens = CSLTokenizeString2(pszFilename + 14, ",", 0);
            if (CSLCount(papszTokens) >= 3)
            {
                nQLevel = atoi(papszTokens[0]);
                subfile_offset = CPLScanUIntBig(
                    papszTokens[1], static_cast<int>(strlen(papszTokens[1])));
                subfile_size = CPLScanUIntBig(
                    papszTokens[2], static_cast<int>(strlen(papszTokens[2])));
                bScan = true;
            }
            CSLDestroy(papszTokens);
        }
        else
        {
            char **papszTokens = CSLTokenizeString2(pszFilename + 13, ",", 0);
            if (CSLCount(papszTokens) >= 2)
            {
                subfile_offset = CPLScanUIntBig(
                    papszTokens[0], static_cast<int>(strlen(papszTokens[0])));
                subfile_size = CPLScanUIntBig(
                    papszTokens[1], static_cast<int>(strlen(papszTokens[1])));
                bScan = true;
            }
            CSLDestroy(papszTokens);
        }

        if (!bScan)
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Corrupt subfile definition: %s", pszFilename);
            delete poDS;
            return nullptr;
        }

        real_filename = strstr(pszFilename, ",");
        if (real_filename != nullptr)
            real_filename = strstr(real_filename + 1, ",");
        if (real_filename != nullptr && nQLevel != -1)
            real_filename = strstr(real_filename + 1, ",");
        if (real_filename != nullptr)
            real_filename++;
        else
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Could not find filename in subfile definition.");
            delete poDS;
            return nullptr;
        }

        CPLDebug("JPG",
                 "real_filename %s, offset=" CPL_FRMT_GUIB
                 ", size=" CPL_FRMT_GUIB "\n",
                 real_filename, subfile_offset, subfile_size);

        bIsSubfile = true;
    }

    // Open the file using the large file api if necessary.
    VSILFILE *fpImage = fpLin;

    if (fpImage == nullptr)
    {
        fpImage = VSIFOpenL(real_filename, "rb");

        if (fpImage == nullptr)
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "VSIFOpenL(%s) failed unexpectedly in jpgdataset.cpp",
                     real_filename);
            delete poDS;
            return nullptr;
        }
    }
    else
    {
        fpImage = fpLin;
    }

    // Create a corresponding GDALDataset.
    poDS->nQLevel = nQLevel;
    poDS->m_fpImage = fpImage;

    // Move to the start of jpeg data.
    poDS->nSubfileOffset = subfile_offset;
    VSIFSeekL(poDS->m_fpImage, poDS->nSubfileOffset, SEEK_SET);

    poDS->eAccess = GA_ReadOnly;

    poDS->sDInfo.err = jpeg_std_error(&poDS->sJErr);
    poDS->sJErr.error_exit = JPGDataset::ErrorExit;
    poDS->sUserData.p_previous_emit_message = poDS->sJErr.emit_message;
    poDS->sJErr.emit_message = JPGDataset::EmitMessage;
    poDS->sDInfo.client_data = &poDS->sUserData;

    jpeg_create_decompress(&poDS->sDInfo);
    poDS->bHasDoneJpegCreateDecompress = true;

    SetMaxMemoryToUse(&poDS->sDInfo);

#if !defined(JPGDataset)
    // Preload default NITF JPEG quantization tables.
    poDS->LoadDefaultTables(0);
    poDS->LoadDefaultTables(1);
    poDS->LoadDefaultTables(2);
    poDS->LoadDefaultTables(3);
#endif  // !defined(JPGDataset)

    // Read pre-image data after ensuring the file is rewound.
    VSIFSeekL(poDS->m_fpImage, poDS->nSubfileOffset, SEEK_SET);

    jpeg_vsiio_src(&poDS->sDInfo, poDS->m_fpImage);
    jpeg_read_header(&poDS->sDInfo, TRUE);

    if (poDS->sDInfo.data_precision != 8 && poDS->sDInfo.data_precision != 12)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "GDAL JPEG Driver doesn't support files with precision of "
                 "other than 8 or 12 bits.");
        delete poDS;
        return nullptr;
    }

#if defined(JPEG_DUAL_MODE_8_12) && !defined(JPGDataset)
    if (poDS->sDInfo.data_precision == 12 && poDS->m_fpImage != nullptr)
    {
        poDS->m_fpImage = nullptr;
        delete poDS;
        psArgs->fpLin = fpImage;
        return JPEGDataset12Open(psArgs);
    }
#endif

    // Capture some information from the file that is of interest.

    poDS->nScaleFactor = nScaleFactor;
    poDS->SetScaleNumAndDenom();
    poDS->nRasterXSize =
        (poDS->sDInfo.image_width + nScaleFactor - 1) / nScaleFactor;
    poDS->nRasterYSize =
        (poDS->sDInfo.image_height + nScaleFactor - 1) / nScaleFactor;

    poDS->sDInfo.out_color_space = poDS->sDInfo.jpeg_color_space;
    poDS->eGDALColorSpace = poDS->sDInfo.jpeg_color_space;

    if (poDS->sDInfo.jpeg_color_space == JCS_GRAYSCALE)
    {
        poDS->nBands = 1;
    }
    else if (poDS->sDInfo.jpeg_color_space == JCS_RGB)
    {
        poDS->nBands = 3;
    }
    else if (poDS->sDInfo.jpeg_color_space == JCS_YCbCr)
    {
        poDS->nBands = 3;
        if (CPLTestBool(CPLGetConfigOption("GDAL_JPEG_TO_RGB", "YES")))
        {
            poDS->sDInfo.out_color_space = JCS_RGB;
            poDS->eGDALColorSpace = JCS_RGB;
            poDS->SetMetadataItem("SOURCE_COLOR_SPACE", "YCbCr",
                                  "IMAGE_STRUCTURE");
        }
    }
    else if (poDS->sDInfo.jpeg_color_space == JCS_CMYK)
    {
        if (poDS->sDInfo.data_precision == 8 &&
            CPLTestBool(CPLGetConfigOption("GDAL_JPEG_TO_RGB", "YES")))
        {
            poDS->eGDALColorSpace = JCS_RGB;
            poDS->nBands = 3;
            poDS->SetMetadataItem("SOURCE_COLOR_SPACE", "CMYK",
                                  "IMAGE_STRUCTURE");
        }
        else
        {
            poDS->nBands = 4;
        }
    }
    else if (poDS->sDInfo.jpeg_color_space == JCS_YCCK)
    {
        if (poDS->sDInfo.data_precision == 8 &&
            CPLTestBool(CPLGetConfigOption("GDAL_JPEG_TO_RGB", "YES")))
        {
            poDS->eGDALColorSpace = JCS_RGB;
            poDS->nBands = 3;
            poDS->SetMetadataItem("SOURCE_COLOR_SPACE", "YCbCrK",
                                  "IMAGE_STRUCTURE");

            // libjpeg does the translation from YCrCbK -> CMYK internally
            // and we'll do the translation to RGB in IReadBlock().
            poDS->sDInfo.out_color_space = JCS_CMYK;
        }
        else
        {
            poDS->nBands = 4;
        }
    }
    else
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Unrecognized jpeg_color_space value of %d.\n",
                 poDS->sDInfo.jpeg_color_space);
        delete poDS;
        return nullptr;
    }

    // Create band information objects.
    for (int iBand = 0; iBand < poDS->nBands; iBand++)
        poDS->SetBand(iBand + 1, JPGCreateBand(poDS, iBand + 1));

    // More metadata.
    if (poDS->nBands > 1)
    {
        poDS->SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
        poDS->SetMetadataItem("COMPRESSION", "JPEG", "IMAGE_STRUCTURE");
    }

    // Initialize any PAM information.
    poDS->SetDescription(pszFilename);

    if (nScaleFactor == 1 && bDoPAMInitialize)
    {
        if (!bIsSubfile)
            poDS->TryLoadXML(papszSiblingFiles);
        else
            poDS->nPamFlags |= GPF_NOSAVE;

        // Open (external) overviews.
        poDS->oOvManager.Initialize(poDS, real_filename, papszSiblingFiles);

        if (!bUseInternalOverviews)
            poDS->bHasInitInternalOverviews = true;

        // In the case of a file downloaded through the HTTP driver, this one
        // will unlink the temporary /vsimem file just after GDALOpen(), so
        // later VSIFOpenL() when reading internal overviews would fail.
        // Initialize them now.
        if (STARTS_WITH(real_filename, "/vsimem/http_"))
        {
            poDS->InitInternalOverviews();
        }
    }
    else
    {
        poDS->nPamFlags |= GPF_NOSAVE;
    }

    poDS->bIsSubfile = bIsSubfile;

    return poDS;
}

#if !defined(JPGDataset)

/************************************************************************/
/*                       LoadWorldFileOrTab()                           */
/************************************************************************/

void JPGDatasetCommon::LoadWorldFileOrTab()
{
    if (bIsSubfile)
        return;
    if (bHasTriedLoadWorldFileOrTab)
        return;
    bHasTriedLoadWorldFileOrTab = true;

    char *pszWldFilename = nullptr;

    // TIROS3 JPEG files have a .wld extension, so don't look for .wld as
    // as worldfile.
    const bool bEndsWithWld =
        strlen(GetDescription()) > 4 &&
        EQUAL(GetDescription() + strlen(GetDescription()) - 4, ".wld");
    bGeoTransformValid =
        GDALReadWorldFile2(GetDescription(), nullptr, adfGeoTransform,
                           oOvManager.GetSiblingFiles(), &pszWldFilename) ||
        GDALReadWorldFile2(GetDescription(), ".jpw", adfGeoTransform,
                           oOvManager.GetSiblingFiles(), &pszWldFilename) ||
        (!bEndsWithWld &&
         GDALReadWorldFile2(GetDescription(), ".wld", adfGeoTransform,
                            oOvManager.GetSiblingFiles(), &pszWldFilename));

    if (!bGeoTransformValid)
    {
        char *pszProjection = nullptr;
        const bool bTabFileOK = CPL_TO_BOOL(GDALReadTabFile2(
            GetDescription(), adfGeoTransform, &pszProjection, &nGCPCount,
            &pasGCPList, oOvManager.GetSiblingFiles(), &pszWldFilename));
        if (pszProjection)
            m_oSRS.importFromWkt(pszProjection);
        CPLFree(pszProjection);

        if (bTabFileOK && nGCPCount == 0)
            bGeoTransformValid = true;
    }

    if (pszWldFilename)
    {
        osWldFilename = pszWldFilename;
        CPLFree(pszWldFilename);
    }
}

/************************************************************************/
/*                            GetFileList()                             */
/************************************************************************/

char **JPGDatasetCommon::GetFileList()

{
    char **papszFileList = GDALPamDataset::GetFileList();

    LoadWorldFileOrTab();

    if (!osWldFilename.empty() &&
        CSLFindString(papszFileList, osWldFilename) == -1)
    {
        papszFileList = CSLAddString(papszFileList, osWldFilename);
    }

    return papszFileList;
}

/************************************************************************/
/*                            CheckForMask()                            */
/************************************************************************/

void JPGDatasetCommon::CheckForMask()

{
    // Save current position to avoid disturbing JPEG stream decoding.
    const vsi_l_offset nCurOffset = VSIFTellL(m_fpImage);

    // Go to the end of the file, pull off four bytes, and see if
    // it is plausibly the size of the real image data.
    VSIFSeekL(m_fpImage, 0, SEEK_END);
    GIntBig nFileSize = VSIFTellL(m_fpImage);
    VSIFSeekL(m_fpImage, nFileSize - 4, SEEK_SET);

    GUInt32 nImageSize = 0;
    VSIFReadL(&nImageSize, 4, 1, m_fpImage);
    CPL_LSBPTR32(&nImageSize);

    GByte abyEOD[2] = {0, 0};

    if (nImageSize < nFileSize / 2 || nImageSize > nFileSize - 4)
        goto end;

    // If that seems okay, seek back, and verify that just preceding
    // the bitmask is an apparent end-of-jpeg-data marker.
    VSIFSeekL(m_fpImage, nImageSize - 2, SEEK_SET);
    VSIFReadL(abyEOD, 2, 1, m_fpImage);
    if (abyEOD[0] != 0xff || abyEOD[1] != 0xd9)
        goto end;

    // We seem to have a mask.  Read it in.
    nCMaskSize = static_cast<int>(nFileSize - nImageSize - 4);
    pabyCMask = static_cast<GByte *>(VSI_MALLOC_VERBOSE(nCMaskSize));
    if (pabyCMask == nullptr)
    {
        goto end;
    }
    VSIFReadL(pabyCMask, nCMaskSize, 1, m_fpImage);

    CPLDebug("JPEG", "Got %d byte compressed bitmask.", nCMaskSize);

    // TODO(schwehr): Refactor to not use goto.
end:
    VSIFSeekL(m_fpImage, nCurOffset, SEEK_SET);
}

/************************************************************************/
/*                           DecompressMask()                           */
/************************************************************************/

void JPGDatasetCommon::DecompressMask()

{
    if (pabyCMask == nullptr || pabyBitMask != nullptr)
        return;

    // Allocate 1bit buffer - may be slightly larger than needed.
    const int nBufSize = nRasterYSize * ((nRasterXSize + 7) / 8);
    pabyBitMask = static_cast<GByte *>(VSI_MALLOC_VERBOSE(nBufSize));
    if (pabyBitMask == nullptr)
    {
        CPLFree(pabyCMask);
        pabyCMask = nullptr;
        return;
    }

    // Decompress.
    void *pOut =
        CPLZLibInflate(pabyCMask, nCMaskSize, pabyBitMask, nBufSize, nullptr);

    // Cleanup if an error occurs.
    if (pOut == nullptr)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Failure decoding JPEG validity bitmask.");
        CPLFree(pabyCMask);
        pabyCMask = nullptr;

        CPLFree(pabyBitMask);
        pabyBitMask = nullptr;

        return;
    }

    const char *pszJPEGMaskBitOrder =
        CPLGetConfigOption("JPEG_MASK_BIT_ORDER", "AUTO");
    if (EQUAL(pszJPEGMaskBitOrder, "LSB"))
        bMaskLSBOrder = true;
    else if (EQUAL(pszJPEGMaskBitOrder, "MSB"))
        bMaskLSBOrder = false;
    else if (nRasterXSize > 8 && nRasterYSize > 1)
    {
        // Test MSB ordering hypothesis in a very restrictive case where it is
        // *obviously* ordered as MSB ! (unless someone coded something
        // specifically to defeat the below logic)
        // The case considered here is dop_465_6100.jpg from #5102.
        // The mask is identical for each line, starting with 1's and ending
        // with 0's (or starting with 0's and ending with 1's), and no other
        // intermediate change.
        // We can detect the MSB ordering since the lsb bits at the end of the
        // first line will be set with the 1's of the beginning of the second
        // line.
        // We can only be sure of this heuristics if the change of value occurs
        // in the middle of a byte, or if the raster width is not a multiple of
        // 8.
        //
        // TODO(schwehr): Check logic in this section that was added in r26063.
        int nPrevValBit = 0;
        int nChangedValBit = 0;
        int iX = 0;  // Used after for.
        for (; iX < nRasterXSize; iX++)
        {
            const int nValBit =
                (pabyBitMask[iX >> 3] & (0x1 << (7 - (iX & 7)))) != 0;
            if (iX == 0)
                nPrevValBit = nValBit;
            else if (nValBit != nPrevValBit)
            {
                nPrevValBit = nValBit;
                nChangedValBit++;
                if (nChangedValBit == 1)
                {
                    const bool bValChangedOnByteBoundary = (iX % 8) == 0;
                    if (bValChangedOnByteBoundary && (nRasterXSize % 8) == 0)
                        break;
                }
                else
                {
                    break;
                }
            }
            const int iNextLineX = iX + nRasterXSize;
            const int nNextLineValBit = (pabyBitMask[iNextLineX >> 3] &
                                         (0x1 << (7 - (iNextLineX & 7)))) != 0;
            if (nValBit != nNextLineValBit)
                break;
        }

        if (iX == nRasterXSize && nChangedValBit == 1)
        {
            CPLDebug("JPEG",
                     "Bit ordering in mask is guessed to be msb (unusual)");
            bMaskLSBOrder = false;
        }
        else
        {
            bMaskLSBOrder = true;
        }
    }
    else
    {
        bMaskLSBOrder = true;
    }
}

#endif  // !defined(JPGDataset)

/************************************************************************/
/*                             ErrorExit()                              */
/************************************************************************/

void JPGDataset::ErrorExit(j_common_ptr cinfo)
{
    GDALJPEGUserData *psUserData =
        static_cast<GDALJPEGUserData *>(cinfo->client_data);
    char buffer[JMSG_LENGTH_MAX] = {};

    // Create the message.
    (*cinfo->err->format_message)(cinfo, buffer);

    // Avoid error for a 12bit JPEG if reading from the 8bit JPEG driver and
    // we have JPEG_DUAL_MODE_8_12 support, as we'll try again with 12bit JPEG
    // driver.
#if defined(JPEG_DUAL_MODE_8_12) && !defined(JPGDataset)
    if (strstr(buffer, "Unsupported JPEG data precision 12") == nullptr)
#endif
        CPLError(CE_Failure, CPLE_AppDefined, "libjpeg: %s", buffer);

    // Return control to the setjmp point.
    longjmp(psUserData->setjmp_buffer, 1);
}

/************************************************************************/
/*                             EmitMessage()                            */
/************************************************************************/

void JPGDataset::EmitMessage(j_common_ptr cinfo, int msg_level)
{
    GDALJPEGUserData *psUserData =
        static_cast<GDALJPEGUserData *>(cinfo->client_data);
    if (msg_level >= 0)  // Trace message.
    {
        if (psUserData->p_previous_emit_message != nullptr)
            psUserData->p_previous_emit_message(cinfo, msg_level);
    }
    else
    {
        // Warning : libjpeg will try to recover but the image will be likely
        // corrupted.

        struct jpeg_error_mgr *err = cinfo->err;

        // It's a warning message.  Since corrupt files may generate many
        // warnings, the policy implemented here is to show only the first
        // warning, unless trace_level >= 3.
        if (err->num_warnings == 0 || err->trace_level >= 3)
        {
            char buffer[JMSG_LENGTH_MAX] = {};

            // Create the message.
            (*cinfo->err->format_message)(cinfo, buffer);

            if (CPLTestBool(
                    CPLGetConfigOption("GDAL_ERROR_ON_LIBJPEG_WARNING", "NO")))
            {
                psUserData->bNonFatalErrorEncountered = true;
                CPLError(CE_Failure, CPLE_AppDefined, "libjpeg: %s", buffer);
            }
            else
            {
                CPLError(CE_Warning, CPLE_AppDefined,
                         "libjpeg: %s (this warning can be turned as an error "
                         "by setting GDAL_ERROR_ON_LIBJPEG_WARNING to TRUE)",
                         buffer);
            }
        }

        // Always count warnings in num_warnings.
        err->num_warnings++;
    }
}

/************************************************************************/
/*                          ProgressMonitor()                           */
/************************************************************************/

/* Avoid the risk of denial-of-service on crafted JPEGs with an insane */
/* number of scans. */
/* See
 * http://www.libjpeg-turbo.org/pmwiki/uploads/About/TwoIssueswiththeJPEGStandard.pdf
 */
void JPGDataset::ProgressMonitor(j_common_ptr cinfo)
{
    if (cinfo->is_decompressor)
    {
        GDALJPEGUserData *psUserData =
            static_cast<GDALJPEGUserData *>(cinfo->client_data);
        const int scan_no =
            reinterpret_cast<j_decompress_ptr>(cinfo)->input_scan_number;
        if (scan_no >= psUserData->nMaxScans)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Scan number %d exceeds maximum scans (%d)", scan_no,
                     psUserData->nMaxScans);

            // Return control to the setjmp point.
            longjmp(psUserData->setjmp_buffer, 1);
        }
    }
}

#if !defined(JPGDataset)

/************************************************************************/
/*                           JPGAddICCProfile()                         */
/*                                                                      */
/*      This function adds an ICC profile to a JPEG file.               */
/************************************************************************/

void JPGAddICCProfile(void *pInfo, const char *pszICCProfile,
                      my_jpeg_write_m_header p_jpeg_write_m_header,
                      my_jpeg_write_m_byte p_jpeg_write_m_byte)
{
    if (pszICCProfile == nullptr)
        return;

    // Write out each segment of the ICC profile.
    char *pEmbedBuffer = CPLStrdup(pszICCProfile);
    GInt32 nEmbedLen = CPLBase64DecodeInPlace((GByte *)pEmbedBuffer);
    char *pEmbedPtr = pEmbedBuffer;
    char const *const paHeader = "ICC_PROFILE";
    int nSegments = (nEmbedLen + 65518) / 65519;
    int nSegmentID = 1;

    while (nEmbedLen != 0)
    {
        // 65535 - 16 bytes for header = 65519
        const int nChunkLen = (nEmbedLen > 65519) ? 65519 : nEmbedLen;
        nEmbedLen -= nChunkLen;

        // Write marker and length.
        p_jpeg_write_m_header(pInfo, JPEG_APP0 + 2,
                              static_cast<unsigned int>(nChunkLen + 14));

        // Write identifier.
        for (int i = 0; i < 12; i++)
            p_jpeg_write_m_byte(pInfo, paHeader[i]);

        // Write ID and max ID.
        p_jpeg_write_m_byte(pInfo, nSegmentID);
        p_jpeg_write_m_byte(pInfo, nSegments);

        // Write ICC Profile.
        for (int i = 0; i < nChunkLen; i++)
            p_jpeg_write_m_byte(pInfo, pEmbedPtr[i]);

        nSegmentID++;

        pEmbedPtr += nChunkLen;
    }

    CPLFree(pEmbedBuffer);
}

/************************************************************************/
/*                           JPGAppendMask()                            */
/*                                                                      */
/*      This function appends a zlib compressed bitmask to a JPEG       */
/*      file (or really any file) pulled from an existing mask band.    */
/************************************************************************/

// MSVC does not know that memset() has initialized sStream.
#ifdef _MSC_VER
#pragma warning(disable : 4701)
#endif

CPLErr JPGAppendMask(const char *pszJPGFilename, GDALRasterBand *poMask,
                     GDALProgressFunc pfnProgress, void *pProgressData)

{
    const int nXSize = poMask->GetXSize();
    const int nYSize = poMask->GetYSize();
    const int nBitBufSize = nYSize * ((nXSize + 7) / 8);
    CPLErr eErr = CE_None;

    // Allocate uncompressed bit buffer.
    GByte *pabyBitBuf =
        static_cast<GByte *>(VSI_CALLOC_VERBOSE(1, nBitBufSize));

    GByte *pabyMaskLine = static_cast<GByte *>(VSI_MALLOC_VERBOSE(nXSize));
    if (pabyBitBuf == nullptr || pabyMaskLine == nullptr)
    {
        eErr = CE_Failure;
    }

    // No reason to set it to MSB, unless for debugging purposes
    // to be able to generate a unusual LSB ordered mask (#5102).
    const char *pszJPEGMaskBitOrder =
        CPLGetConfigOption("JPEG_WRITE_MASK_BIT_ORDER", "LSB");
    const bool bMaskLSBOrder = EQUAL(pszJPEGMaskBitOrder, "LSB");

    // Set bit buffer from mask band, scanline by scanline.
    GUInt32 iBit = 0;
    for (int iY = 0; eErr == CE_None && iY < nYSize; iY++)
    {
        eErr = poMask->RasterIO(GF_Read, 0, iY, nXSize, 1, pabyMaskLine, nXSize,
                                1, GDT_Byte, 0, 0, nullptr);
        if (eErr != CE_None)
            break;

        if (bMaskLSBOrder)
        {
            for (int iX = 0; iX < nXSize; iX++)
            {
                if (pabyMaskLine[iX] != 0)
                    pabyBitBuf[iBit >> 3] |= (0x1 << (iBit & 7));

                iBit++;
            }
        }
        else
        {
            for (int iX = 0; iX < nXSize; iX++)
            {
                if (pabyMaskLine[iX] != 0)
                    pabyBitBuf[iBit >> 3] |= (0x1 << (7 - (iBit & 7)));

                iBit++;
            }
        }

        if (!pfnProgress((iY + 1) / static_cast<double>(nYSize), nullptr,
                         pProgressData))
        {
            eErr = CE_Failure;
            CPLError(CE_Failure, CPLE_UserInterrupt,
                     "User terminated JPGAppendMask()");
        }
    }

    CPLFree(pabyMaskLine);

    // Compress.
    GByte *pabyCMask = nullptr;

    if (eErr == CE_None)
    {
        pabyCMask = static_cast<GByte *>(VSI_MALLOC_VERBOSE(nBitBufSize + 30));
        if (pabyCMask == nullptr)
        {
            eErr = CE_Failure;
        }
    }

    size_t nTotalOut = 0;
    if (eErr == CE_None)
    {
        if (CPLZLibDeflate(pabyBitBuf, nBitBufSize, -1, pabyCMask,
                           nBitBufSize + 30, &nTotalOut) == nullptr)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Deflate compression of jpeg bit mask failed.");
            eErr = CE_Failure;
        }
    }

    // Write to disk, along with image file size.
    if (eErr == CE_None)
    {
        VSILFILE *fpOut = VSIFOpenL(pszJPGFilename, "r+");
        if (fpOut == nullptr)
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "Failed to open jpeg to append bitmask.");
            eErr = CE_Failure;
        }
        else
        {
            VSIFSeekL(fpOut, 0, SEEK_END);

            GUInt32 nImageSize = static_cast<GUInt32>(VSIFTellL(fpOut));
            CPL_LSBPTR32(&nImageSize);

            if (VSIFWriteL(pabyCMask, 1, nTotalOut, fpOut) != nTotalOut)
            {
                CPLError(CE_Failure, CPLE_FileIO,
                         "Failure writing compressed bitmask.\n%s",
                         VSIStrerror(errno));
                eErr = CE_Failure;
            }
            else
            {
                VSIFWriteL(&nImageSize, 4, 1, fpOut);
            }

            VSIFCloseL(fpOut);
        }
    }

    CPLFree(pabyBitBuf);
    CPLFree(pabyCMask);

    return eErr;
}

/************************************************************************/
/*                             JPGAddEXIF()                             */
/************************************************************************/

void JPGAddEXIF(GDALDataType eWorkDT, GDALDataset *poSrcDS, char **papszOptions,
                void *cinfo, my_jpeg_write_m_header p_jpeg_write_m_header,
                my_jpeg_write_m_byte p_jpeg_write_m_byte,
                GDALDataset *(pCreateCopy)(const char *, GDALDataset *, int,
                                           char **,
                                           GDALProgressFunc pfnProgress,
                                           void *pProgressData))
{
    const int nBands = poSrcDS->GetRasterCount();
    const int nXSize = poSrcDS->GetRasterXSize();
    const int nYSize = poSrcDS->GetRasterYSize();

    bool bGenerateEXIFThumbnail =
        CPLTestBool(CSLFetchNameValueDef(papszOptions, "EXIF_THUMBNAIL", "NO"));
    const char *pszThumbnailWidth =
        CSLFetchNameValue(papszOptions, "THUMBNAIL_WIDTH");
    const char *pszThumbnailHeight =
        CSLFetchNameValue(papszOptions, "THUMBNAIL_HEIGHT");
    int nOvrWidth = 0;
    int nOvrHeight = 0;
    if (pszThumbnailWidth == nullptr && pszThumbnailHeight == nullptr)
    {
        if (nXSize >= nYSize)
        {
            nOvrWidth = 128;
        }
        else
        {
            nOvrHeight = 128;
        }
    }
    if (pszThumbnailWidth != nullptr)
    {
        nOvrWidth = atoi(pszThumbnailWidth);
        if (nOvrWidth < 32)
            nOvrWidth = 32;
        if (nOvrWidth > 1024)
            nOvrWidth = 1024;
    }
    if (pszThumbnailHeight != nullptr)
    {
        nOvrHeight = atoi(pszThumbnailHeight);
        if (nOvrHeight < 32)
            nOvrHeight = 32;
        if (nOvrHeight > 1024)
            nOvrHeight = 1024;
    }
    if (nOvrWidth == 0)
    {
        nOvrWidth = static_cast<int>(static_cast<GIntBig>(nOvrHeight) * nXSize /
                                     nYSize);
        if (nOvrWidth == 0)
            nOvrWidth = 1;
    }
    else if (nOvrHeight == 0)
    {
        nOvrHeight =
            static_cast<int>(static_cast<GIntBig>(nOvrWidth) * nYSize / nXSize);
        if (nOvrHeight == 0)
            nOvrHeight = 1;
    }

    vsi_l_offset nJPEGIfByteCount = 0;
    GByte *pabyOvr = nullptr;

    if (bGenerateEXIFThumbnail && nXSize > nOvrWidth && nYSize > nOvrHeight)
    {
        GDALDataset *poMemDS = MEMDataset::Create("", nOvrWidth, nOvrHeight,
                                                  nBands, eWorkDT, nullptr);
        GDALRasterBand **papoSrcBands = static_cast<GDALRasterBand **>(
            CPLMalloc(nBands * sizeof(GDALRasterBand *)));
        GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
            CPLMalloc(nBands * sizeof(GDALRasterBand **)));
        for (int i = 0; i < nBands; i++)
        {
            papoSrcBands[i] = poSrcDS->GetRasterBand(i + 1);
            papapoOverviewBands[i] = static_cast<GDALRasterBand **>(
                CPLMalloc(sizeof(GDALRasterBand *)));
            papapoOverviewBands[i][0] = poMemDS->GetRasterBand(i + 1);
        }
        CPLErr eErr = GDALRegenerateOverviewsMultiBand(
            nBands, papoSrcBands, 1, papapoOverviewBands, "AVERAGE", nullptr,
            nullptr,
            /* papszOptions = */ nullptr);
        CPLFree(papoSrcBands);
        for (int i = 0; i < nBands; i++)
        {
            CPLFree(papapoOverviewBands[i]);
        }
        CPLFree(papapoOverviewBands);

        if (eErr != CE_None)
        {
            GDALClose(poMemDS);
            return;
        }

        CPLString osTmpFile(CPLSPrintf("/vsimem/ovrjpg%p", poMemDS));
        GDALDataset *poOutDS = pCreateCopy(osTmpFile, poMemDS, 0, nullptr,
                                           GDALDummyProgress, nullptr);
        const bool bExifOverviewSuccess = poOutDS != nullptr;
        delete poOutDS;
        poOutDS = nullptr;
        GDALClose(poMemDS);
        if (bExifOverviewSuccess)
            pabyOvr = VSIGetMemFileBuffer(osTmpFile, &nJPEGIfByteCount, TRUE);
        VSIUnlink(osTmpFile);

        // cppcheck-suppress knownConditionTrueFalse
        if (pabyOvr == nullptr)
        {
            nJPEGIfByteCount = 0;
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Could not generate EXIF overview");
        }
    }

    GUInt32 nMarkerSize;
    const bool bWriteExifMetadata =
        CPLFetchBool(papszOptions, "WRITE_EXIF_METADATA", true);

    GByte *pabyEXIF =
        EXIFCreate(bWriteExifMetadata ? poSrcDS->GetMetadata() : nullptr,
                   pabyOvr, static_cast<GUInt32>(nJPEGIfByteCount), nOvrWidth,
                   nOvrHeight, &nMarkerSize);
    if (pabyEXIF)
    {
        p_jpeg_write_m_header(cinfo, JPEG_APP0 + 1, nMarkerSize);
        for (GUInt32 i = 0; i < nMarkerSize; i++)
        {
            p_jpeg_write_m_byte(cinfo, pabyEXIF[i]);
        }
        VSIFree(pabyEXIF);
    }
    CPLFree(pabyOvr);
}

#endif  // !defined(JPGDataset)

/************************************************************************/
/*                              CreateCopy()                            */
/************************************************************************/

GDALDataset *JPGDataset::CreateCopy(const char *pszFilename,
                                    GDALDataset *poSrcDS, int bStrict,
                                    char **papszOptions,
                                    GDALProgressFunc pfnProgress,
                                    void *pProgressData)

{
    if (!pfnProgress(0.0, nullptr, pProgressData))
        return nullptr;

    // Some some rudimentary checks.
    const int nBands = poSrcDS->GetRasterCount();
    if (nBands != 1 && nBands != 3 && nBands != 4)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "JPEG driver doesn't support %d bands.  Must be 1 (grey), "
                 "3 (RGB) or 4 bands (CMYK).\n",
                 nBands);

        return nullptr;
    }

    if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    {
        CPLError(bStrict ? CE_Failure : CE_Warning, CPLE_NotSupported,
                 "JPEG driver ignores color table. "
                 "The source raster band will be considered as grey level.\n"
                 "Consider using color table expansion "
                 "(-expand option in gdal_translate)");
        if (bStrict)
            return nullptr;
    }

    if (nBands == 4 &&
        poSrcDS->GetRasterBand(1)->GetColorInterpretation() != GCI_CyanBand)
    {
        CPLError(CE_Warning, CPLE_AppDefined,
                 "4-band JPEGs will be interpreted on reading as in CMYK "
                 "colorspace");
    }

    VSILFILE *fpImage = nullptr;
    GDALJPEGUserData sUserData;
    sUserData.bNonFatalErrorEncountered = false;
    GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();

#if defined(JPEG_LIB_MK1_OR_12BIT) || defined(JPEG_DUAL_MODE_8_12)
    if (eDT != GDT_Byte && eDT != GDT_UInt16)
    {
        CPLError(bStrict ? CE_Failure : CE_Warning, CPLE_NotSupported,
                 "JPEG driver doesn't support data type %s. "
                 "Only eight and twelve bit bands supported (Mk1 libjpeg).\n",
                 GDALGetDataTypeName(
                     poSrcDS->GetRasterBand(1)->GetRasterDataType()));

        if (bStrict)
            return nullptr;
    }

    if (eDT == GDT_UInt16 || eDT == GDT_Int16)
    {
#if defined(JPEG_DUAL_MODE_8_12) && !defined(JPGDataset)
        return JPEGDataset12CreateCopy(pszFilename, poSrcDS, bStrict,
                                       papszOptions, pfnProgress,
                                       pProgressData);
#else
        eDT = GDT_UInt16;
#endif  // defined(JPEG_DUAL_MODE_8_12) && !defined(JPGDataset)
    }
    else
    {
        eDT = GDT_Byte;
    }

#else   // !(defined(JPEG_LIB_MK1_OR_12BIT) || defined(JPEG_DUAL_MODE_8_12))
    if (eDT != GDT_Byte)
    {
        CPLError(bStrict ? CE_Failure : CE_Warning, CPLE_NotSupported,
                 "JPEG driver doesn't support data type %s. "
                 "Only eight bit byte bands supported.\n",
                 GDALGetDataTypeName(
                     poSrcDS->GetRasterBand(1)->GetRasterDataType()));

        if (bStrict)
            return nullptr;
    }

    eDT = GDT_Byte;  // force to 8bit.
#endif  // !(defined(JPEG_LIB_MK1_OR_12BIT) || defined(JPEG_DUAL_MODE_8_12))

    // What options has the caller selected?
    int nQuality = 75;
    if (CSLFetchNameValue(papszOptions, "QUALITY") != nullptr)
    {
        nQuality = atoi(CSLFetchNameValue(papszOptions, "QUALITY"));
        if (nQuality < 10 || nQuality > 100)
        {
            CPLError(CE_Failure, CPLE_IllegalArg,
                     "QUALITY=%s is not a legal value in the range 10-100.",
                     CSLFetchNameValue(papszOptions, "QUALITY"));
            return nullptr;
        }
    }

    // Create the dataset.
    fpImage = VSIFOpenL(pszFilename, "wb");
    if (fpImage == nullptr)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Unable to create jpeg file %s.\n", pszFilename);
        return nullptr;
    }

    struct jpeg_compress_struct sCInfo;
    struct jpeg_error_mgr sJErr;
    GByte *pabyScanline;

    // Does the source have a mask?  If so, we will append it to the
    // jpeg file after the imagery.
    const int nMaskFlags = poSrcDS->GetRasterBand(1)->GetMaskFlags();
    const bool bAppendMask = !(nMaskFlags & GMF_ALL_VALID) &&
                             (nBands == 1 || (nMaskFlags & GMF_PER_DATASET)) &&
                             CPLFetchBool(papszOptions, "INTERNAL_MASK", true);

    // Nasty trick to avoid variable clobbering issues with setjmp/longjmp.
    return CreateCopyStage2(pszFilename, poSrcDS, papszOptions, pfnProgress,
                            pProgressData, fpImage, eDT, nQuality, bAppendMask,
                            sUserData, sCInfo, sJErr, pabyScanline);
}

GDALDataset *JPGDataset::CreateCopyStage2(
    const char *pszFilename, GDALDataset *poSrcDS, char **papszOptions,
    GDALProgressFunc pfnProgress, void *pProgressData, VSILFILE *fpImage,
    GDALDataType eDT, int nQuality, bool bAppendMask,
    GDALJPEGUserData &sUserData, struct jpeg_compress_struct &sCInfo,
    struct jpeg_error_mgr &sJErr, GByte *&pabyScanline)

{
    if (setjmp(sUserData.setjmp_buffer))
    {
        if (fpImage)
            VSIFCloseL(fpImage);
        return nullptr;
    }

    // Initialize JPG access to the file.
    sCInfo.err = jpeg_std_error(&sJErr);
    sJErr.error_exit = JPGDataset::ErrorExit;
    sUserData.p_previous_emit_message = sJErr.emit_message;
    sJErr.emit_message = JPGDataset::EmitMessage;
    sCInfo.client_data = &sUserData;

    jpeg_create_compress(&sCInfo);
    if (setjmp(sUserData.setjmp_buffer))
    {
        if (fpImage)
            VSIFCloseL(fpImage);
        jpeg_destroy_compress(&sCInfo);
        return nullptr;
    }

    jpeg_vsiio_dest(&sCInfo, fpImage);

    const int nXSize = poSrcDS->GetRasterXSize();
    const int nYSize = poSrcDS->GetRasterYSize();
    const int nBands = poSrcDS->GetRasterCount();
    sCInfo.image_width = nXSize;
    sCInfo.image_height = nYSize;
    sCInfo.input_components = nBands;

    if (nBands == 3)
        sCInfo.in_color_space = JCS_RGB;
    else if (nBands == 1)
        sCInfo.in_color_space = JCS_GRAYSCALE;
    else
        sCInfo.in_color_space = JCS_UNKNOWN;

    jpeg_set_defaults(&sCInfo);

    // libjpeg turbo 1.5.2 honours max_memory_to_use, but has no backing
    // store implementation, so better not set max_memory_to_use ourselves.
    // See https://github.com/libjpeg-turbo/libjpeg-turbo/issues/162
    if (sCInfo.mem->max_memory_to_use > 0)
    {
        // This is to address bug related in ticket #1795.
        if (CPLGetConfigOption("JPEGMEM", nullptr) == nullptr)
        {
            // If the user doesn't provide a value for JPEGMEM, we want to be
            // sure that at least 500 MB will be used before creating the
            // temporary file.
            const long nMinMemory = 500 * 1024 * 1024;
            sCInfo.mem->max_memory_to_use =
                std::max(sCInfo.mem->max_memory_to_use, nMinMemory);
        }
    }

    if (eDT == GDT_UInt16)
    {
        sCInfo.data_precision = 12;
    }
    else
    {
        sCInfo.data_precision = 8;
    }

    const char *pszVal = CSLFetchNameValue(papszOptions, "ARITHMETIC");
    if (pszVal)
        sCInfo.arith_code = CPLTestBool(pszVal);

    // Optimized Huffman coding. Supposedly slower according to libjpeg doc
    // but no longer significant with today computer standards.
    if (!sCInfo.arith_code)
        sCInfo.optimize_coding = TRUE;

#if JPEG_LIB_VERSION_MAJOR >= 8 &&                                             \
    (JPEG_LIB_VERSION_MAJOR > 8 || JPEG_LIB_VERSION_MINOR >= 3)
    pszVal = CSLFetchNameValue(papszOptions, "BLOCK");
    if (pszVal)
        sCInfo.block_size = atoi(pszVal);
#endif

#if JPEG_LIB_VERSION_MAJOR >= 9
    pszVal = CSLFetchNameValue(papszOptions, "COLOR_TRANSFORM");
    if (pszVal)
    {
        sCInfo.color_transform =
            EQUAL(pszVal, "RGB1") ? JCT_SUBTRACT_GREEN : JCT_NONE;
        jpeg_set_colorspace(&sCInfo, JCS_RGB);
    }
    else
#endif

        // Mostly for debugging purposes.
        if (nBands == 3 &&
            CPLTestBool(CPLGetConfigOption("JPEG_WRITE_RGB", "NO")))
        {
            jpeg_set_colorspace(&sCInfo, JCS_RGB);
        }

#ifdef JPEG_LIB_MK1
    sCInfo.bits_in_jsample = sCInfo.data_precision;
    // Always force to 16 bit for JPEG_LIB_MK1
    const GDALDataType eWorkDT = GDT_UInt16;
#else
    const GDALDataType eWorkDT = eDT;
#endif

    jpeg_set_quality(&sCInfo, nQuality, TRUE);

    const bool bProgressive = CPLFetchBool(papszOptions, "PROGRESSIVE", false);
    if (bProgressive)
        jpeg_simple_progression(&sCInfo);

    jpeg_start_compress(&sCInfo, TRUE);

    JPGAddEXIF(eWorkDT, poSrcDS, papszOptions, &sCInfo,
               (my_jpeg_write_m_header)jpeg_write_m_header,
               (my_jpeg_write_m_byte)jpeg_write_m_byte, CreateCopy);

    // Add comment if available.
    const char *pszComment = CSLFetchNameValue(papszOptions, "COMMENT");
    if (pszComment)
        jpeg_write_marker(&sCInfo, JPEG_COM,
                          reinterpret_cast<const JOCTET *>(pszComment),
                          static_cast<unsigned int>(strlen(pszComment)));

    // Save ICC profile if available.
    const char *pszICCProfile =
        CSLFetchNameValue(papszOptions, "SOURCE_ICC_PROFILE");
    if (pszICCProfile == nullptr)
        pszICCProfile =
            poSrcDS->GetMetadataItem("SOURCE_ICC_PROFILE", "COLOR_PROFILE");

    if (pszICCProfile != nullptr)
        JPGAddICCProfile(&sCInfo, pszICCProfile,
                         (my_jpeg_write_m_header)jpeg_write_m_header,
                         (my_jpeg_write_m_byte)jpeg_write_m_byte);

    // Loop over image, copying image data.
    const int nWorkDTSize = GDALGetDataTypeSizeBytes(eWorkDT);
    pabyScanline =
        static_cast<GByte *>(CPLMalloc(nBands * nXSize * nWorkDTSize));

    if (setjmp(sUserData.setjmp_buffer))
    {
        VSIFCloseL(fpImage);
        CPLFree(pabyScanline);
        jpeg_destroy_compress(&sCInfo);
        return nullptr;
    }

    CPLErr eErr = CE_None;
    bool bClipWarn = false;
    for (int iLine = 0; iLine < nYSize && eErr == CE_None; iLine++)
    {
        eErr = poSrcDS->RasterIO(
            GF_Read, 0, iLine, nXSize, 1, pabyScanline, nXSize, 1, eWorkDT,
            nBands, nullptr, nBands * nWorkDTSize,
            nBands * nXSize * nWorkDTSize, nWorkDTSize, nullptr);

        // Clamp 16bit values to 12bit.
        if (nWorkDTSize == 2)
        {
            GUInt16 *panScanline = reinterpret_cast<GUInt16 *>(pabyScanline);

            for (int iPixel = 0; iPixel < nXSize * nBands; iPixel++)
            {
                if (panScanline[iPixel] > 4095)
                {
                    panScanline[iPixel] = 4095;
                    if (!bClipWarn)
                    {
                        bClipWarn = true;
                        CPLError(CE_Warning, CPLE_AppDefined,
                                 "One or more pixels clipped to fit "
                                 "12bit domain for jpeg output.");
                    }
                }
            }
        }

        JSAMPLE *ppSamples = reinterpret_cast<JSAMPLE *>(pabyScanline);

        if (eErr == CE_None)
            jpeg_write_scanlines(&sCInfo, &ppSamples, 1);

        if (eErr == CE_None &&
            !pfnProgress((iLine + 1) / ((bAppendMask ? 2 : 1) *
                                        static_cast<double>(nYSize)),
                         nullptr, pProgressData))
        {
            eErr = CE_Failure;
            CPLError(CE_Failure, CPLE_UserInterrupt,
                     "User terminated CreateCopy()");
        }
    }

    // Cleanup and close.
    if (eErr == CE_None)
        jpeg_finish_compress(&sCInfo);
    jpeg_destroy_compress(&sCInfo);

    // Free scanline and image after jpeg_finish_compress since this could
    // cause a longjmp to occur.
    CPLFree(pabyScanline);

    VSIFCloseL(fpImage);

    if (eErr != CE_None)
    {
        VSIUnlink(pszFilename);
        return nullptr;
    }

    // Append masks to the jpeg file if necessary.
    int nCloneFlags = GCIF_PAM_DEFAULT;
    if (bAppendMask)
    {
        CPLDebug("JPEG", "Appending Mask Bitmap");

        void *pScaledData =
            GDALCreateScaledProgress(0.5, 1, pfnProgress, pProgressData);
        eErr =
            JPGAppendMask(pszFilename, poSrcDS->GetRasterBand(1)->GetMaskBand(),
                          GDALScaledProgress, pScaledData);
        GDALDestroyScaledProgress(pScaledData);
        nCloneFlags &= (~GCIF_MASK);

        if (eErr != CE_None)
        {
            VSIUnlink(pszFilename);
            return nullptr;
        }
    }

    // Do we need a world file?
    if (CPLFetchBool(papszOptions, "WORLDFILE", false))
    {
        double adfGeoTransform[6] = {};

        poSrcDS->GetGeoTransform(adfGeoTransform);
        GDALWriteWorldFile(pszFilename, "wld", adfGeoTransform);
    }

    // Re-open dataset, and copy any auxiliary pam information.

    // If writing to stdout, we can't reopen it, so return
    // a fake dataset to make the caller happy.
    if (CPLTestBool(CPLGetConfigOption("GDAL_OPEN_AFTER_COPY", "YES")))
    {
        CPLPushErrorHandler(CPLQuietErrorHandler);

        JPGDatasetOpenArgs sArgs;
        sArgs.pszFilename = pszFilename;
        sArgs.fpLin = nullptr;
        sArgs.papszSiblingFiles = nullptr;
        sArgs.nScaleFactor = 1;
        sArgs.bDoPAMInitialize = true;
        sArgs.bUseInternalOverviews = true;

        auto poDS = Open(&sArgs);
        CPLPopErrorHandler();
        if (poDS)
        {
            poDS->CloneInfo(poSrcDS, nCloneFlags);
            return poDS;
        }

        CPLErrorReset();
    }

    JPGDataset *poJPG_DS = new JPGDataset();
    poJPG_DS->nRasterXSize = nXSize;
    poJPG_DS->nRasterYSize = nYSize;
    for (int i = 0; i < nBands; i++)
        poJPG_DS->SetBand(i + 1, JPGCreateBand(poJPG_DS, i + 1));
    return poJPG_DS;
}

/************************************************************************/
/*                         GDALRegister_JPEG()                          */
/************************************************************************/

#if !defined(JPGDataset)

char **GDALJPGDriver::GetMetadata(const char *pszDomain)
{
    GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST);
    return GDALDriver::GetMetadata(pszDomain);
}

static void GDALJPEGIsArithmeticCodingAvailableErrorExit(j_common_ptr cinfo)
{
    jmp_buf *p_setjmp_buffer = static_cast<jmp_buf *>(cinfo->client_data);
    // Return control to the setjmp point.
    longjmp(*p_setjmp_buffer, 1);
}

// Runtime check if arithmetic coding is available.
static bool GDALJPEGIsArithmeticCodingAvailable()
{
    struct jpeg_compress_struct sCInfo;
    struct jpeg_error_mgr sJErr;
    jmp_buf setjmp_buffer;
    if (setjmp(setjmp_buffer))
    {
        jpeg_destroy_compress(&sCInfo);
        return false;
    }
    sCInfo.err = jpeg_std_error(&sJErr);
    sJErr.error_exit = GDALJPEGIsArithmeticCodingAvailableErrorExit;
    sCInfo.client_data = &setjmp_buffer;
    jpeg_create_compress(&sCInfo);
    // Hopefully nothing will be written.
    jpeg_stdio_dest(&sCInfo, stderr);
    sCInfo.image_width = 1;
    sCInfo.image_height = 1;
    sCInfo.input_components = 1;
    sCInfo.in_color_space = JCS_UNKNOWN;
    jpeg_set_defaults(&sCInfo);
    sCInfo.arith_code = TRUE;
    jpeg_start_compress(&sCInfo, FALSE);
    jpeg_abort_compress(&sCInfo);
    jpeg_destroy_compress(&sCInfo);

    return true;
}

const char *GDALJPGDriver::GetMetadataItem(const char *pszName,
                                           const char *pszDomain)
{
    if (pszName != nullptr && EQUAL(pszName, GDAL_DMD_CREATIONOPTIONLIST) &&
        (pszDomain == nullptr || EQUAL(pszDomain, "")) &&
        GDALDriver::GetMetadataItem(pszName, pszDomain) == nullptr)
    {
        CPLString osCreationOptions =
            "<CreationOptionList>\n"
            "   <Option name='PROGRESSIVE' type='boolean' description='whether "
            "to generate a progressive JPEG' default='NO'/>\n"
            "   <Option name='QUALITY' type='int' description='good=100, "
            "bad=0, default=75'/>\n"
            "   <Option name='WORLDFILE' type='boolean' description='whether "
            "to generate a worldfile' default='NO'/>\n"
            "   <Option name='INTERNAL_MASK' type='boolean' "
            "description='whether to generate a validity mask' "
            "default='YES'/>\n";
        if (GDALJPEGIsArithmeticCodingAvailable())
            osCreationOptions += "   <Option name='ARITHMETIC' type='boolean' "
                                 "description='whether to use arithmetic "
                                 "encoding' default='NO'/>\n";
        osCreationOptions +=
#if JPEG_LIB_VERSION_MAJOR >= 8 &&                                             \
    (JPEG_LIB_VERSION_MAJOR > 8 || JPEG_LIB_VERSION_MINOR >= 3)
            "   <Option name='BLOCK' type='int' description='between 1 and "
            "16'/>\n"
#endif
#if JPEG_LIB_VERSION_MAJOR >= 9
            "   <Option name='COLOR_TRANSFORM' type='string-select'>\n"
            "       <Value>RGB</Value>"
            "       <Value>RGB1</Value>"
            "   </Option>"
#endif
            "   <Option name='COMMENT' description='Comment' type='string'/>\n"
            "   <Option name='SOURCE_ICC_PROFILE' description='ICC profile "
            "encoded in Base64' type='string'/>\n"
            "   <Option name='EXIF_THUMBNAIL' type='boolean' "
            "description='whether to generate an EXIF thumbnail(overview). By "
            "default its max dimension will be 128' default='NO'/>\n"
            "   <Option name='THUMBNAIL_WIDTH' type='int' description='Forced "
            "thumbnail width' min='32' max='512'/>\n"
            "   <Option name='THUMBNAIL_HEIGHT' type='int' description='Forced "
            "thumbnail height' min='32' max='512'/>\n"
            "   <Option name='WRITE_EXIF_METADATA' type='boolean' "
            "description='whether to write EXIF_ metadata in a EXIF segment' "
            "default='YES'/>"
            "</CreationOptionList>\n";
        SetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST, osCreationOptions);
    }
    return GDALDriver::GetMetadataItem(pszName, pszDomain);
}

void GDALRegister_JPEG()

{
    if (GDALGetDriverByName("JPEG") != nullptr)
        return;

    GDALDriver *poDriver = new GDALJPGDriver();

    poDriver->SetDescription("JPEG");
    poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "JPEG JFIF");
    poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/jpeg.html");
    poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "jpg");
    poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "jpg jpeg");
    poDriver->SetMetadataItem(GDAL_DMD_MIMETYPE, "image/jpeg");

#if defined(JPEG_LIB_MK1_OR_12BIT) || defined(JPEG_DUAL_MODE_8_12)
    poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES, "Byte UInt16");
#else
    poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES, "Byte");
#endif
    poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");

    poDriver->SetMetadataItem(GDAL_DMD_OPENOPTIONLIST,
                              "<OpenOptionList>\n"
                              "   <Option name='USE_INTERNAL_OVERVIEWS' "
                              "type='boolean' description='whether to use "
                              "implicit internal overviews' default='YES'/>\n"
                              "</OpenOptionList>\n");

    poDriver->pfnIdentify = JPGDatasetCommon::Identify;
    poDriver->pfnOpen = JPGDatasetCommon::Open;
    poDriver->pfnCreateCopy = JPGDataset::CreateCopy;

    GetGDALDriverManager()->RegisterDriver(poDriver);
}
#endif