summaryrefslogtreecommitdiff
path: root/Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_jpeg.c
blob: 1b4ff3e7b68acef19cc5b9d82b5de63fb6799ee0 (plain) (blame)
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
/**
  ******************************************************************************
  * @file    stm32h7xx_hal_jpeg.c
  * @author  MCD Application Team
  * @brief   JPEG HAL module driver.
  *          This file provides firmware functions to manage the following
  *          functionalities of the JPEG encoder/decoder peripheral:
  *           + Initialization and de-initialization functions
  *           + JPEG processing functions encoding and decoding
  *           + JPEG decoding Getting Info and encoding configuration setting
  *           + JPEG enable/disable header parsing functions (for decoding)
  *           + JPEG Input/Output Buffer configuration.
  *           + JPEG callback functions
  *           + JPEG Abort/Pause/Resume functions
  *           + JPEG custom quantization tables setting functions
  *           + IRQ handler management
  *           + Peripheral State and Error functions
  *
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2017 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  @verbatim
  ==============================================================================
                     ##### How to use this driver #####
  ==============================================================================
    [..]
     (#) Initialize the JPEG peripheral using HAL_JPEG_Init : No initialization parameters are required.
         Only the call to HAL_JPEG_Init is necessary to initialize the JPEG peripheral.

     (#) If operation is JPEG encoding use function HAL_JPEG_ConfigEncoding to set
         the encoding parameters (mandatory before calling the encoding function).
         the application can change the encoding parameter ImageQuality from
         1 to 100 to obtain a more or less quality (visual quality vs the original row image),
         and inversely more or less jpg file size.

     (#) Note that for decoding operation the JPEG peripheral output data are organized in
         YCbCr blocks called MCU (Minimum Coded Unit) as defioned in the JPEG specification
         ISO/IEC 10918-1 standard.
         It is up to the application to transform these YCbCr blocks to RGB data that can be display.

         Respectively, for Encoding operation the JPEG peripheral input should be organized
         in YCbCr MCU blocks. It is up to the application to perform the necessary RGB to YCbCr
         MCU blocks transformation before feeding the JPEG peripheral with data.

     (#) Use functions HAL_JPEG_Encode and HAL_JPEG_Decode to start respectively
         a JPEG encoding/decoding operation in polling method (blocking).

     (#) Use functions HAL_JPEG_Encode_IT and HAL_JPEG_Decode_IT to start respectively
         a JPEG encoding/decoding operation with Interrupt method (not blocking).

     (#) Use functions HAL_JPEG_Encode_DMA and HAL_JPEG_Decode_DMA to start respectively
         a JPEG encoding/decoding operation with DMA method (not blocking).

     (#) Callback HAL_JPEG_InfoReadyCallback is asserted if the current operation
         is a JPEG decoding to provide the application with JPEG image  parameters.
         This callback is asserted when the JPEG peripheral successfully parse the
         JPEG header.

     (#) Callback HAL_JPEG_GetDataCallback is asserted for both encoding and decoding
         operations to inform the application that the input buffer has been
         consumed by the peripheral and to ask for a new data chunk if the operation
         (encoding/decoding) has not been complete yet.

        (++) This CallBack should be implemented in the application side. It should
             call the function HAL_JPEG_ConfigInputBuffer if new input data are available,
             or call HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_INPUT
             to inform the JPEG HAL driver that the ongoing operation shall pause waiting for the
             application to provide a new input data chunk.
             Once the application succeed getting new data and if the input has been paused,
             the application can call the function HAL_JPEG_ConfigInputBuffer to set the new
             input buffer and size, then resume the JPEG HAL input by calling new function HAL_JPEG_Resume.
             If the application has ended feeding the HAL JPEG with input data (no more input data), the application
             Should call the function HAL_JPEG_ConfigInputBuffer (within the callback HAL_JPEG_GetDataCallback)
             with the parameter InDataLength set to zero.

         (++) The mechanism of HAL_JPEG_ConfigInputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows
              to the application to provide the input data (for encoding or decoding) by chunks.
              If the new input data chunk is not available (because data should be read from an input file
              for example) the application can pause the JPEG input (using function HAL_JPEG_Pause)
              Once the new input data chunk is available ( read from a file for example), the application
              can call the function HAL_JPEG_ConfigInputBuffer to provide the HAL with the new chunk
              then resume the JPEG HAL input by calling function HAL_JPEG_Resume.

         (++) The application can call functions HAL_JPEG_ConfigInputBuffer then HAL_JPEG_Resume.
              any time (outside the HAL_JPEG_GetDataCallback)  Once the new input chunk data available.
              However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called
              (if necessary) within the callback HAL_JPEG_GetDataCallback, i.e when the HAL JPEG has ended
              Transferring the previous chunk buffer to the JPEG peripheral.

     (#) Callback HAL_JPEG_DataReadyCallback is asserted when the HAL JPEG driver
         has filled the given output buffer with the given size.

         (++) This CallBack should be implemented in the application side. It should
              call the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver
              with the new output buffer location and size to be used  to store next data chunk.
              if the application is not ready to provide the output chunk location then it can
              call the function HAL_JPEG_Pause with parameter XferSelection set to JPEG_PAUSE_RESUME_OUTPUT
              to inform the JPEG HAL driver that it shall pause output data. Once the application
              is ready to receive the new data chunk (output buffer location free or available) it should call
              the function HAL_JPEG_ConfigOutputBuffer to provide the HAL JPEG driver
              with the new output chunk buffer location and size, then call HAL_JPEG_Resume
              to inform the HAL that it shall resume outputting data in the given output buffer.

         (++) The mechanism of HAL_JPEG_ConfigOutputBuffer/HAL_JPEG_Pause/HAL_JPEG_Resume allows
              the application to receive data from the JPEG peripheral by chunks. when a chunk
              is received, the application can pause the HAL JPEG output data to be able to process
              these received data (YCbCr to RGB conversion in case of decoding or data storage in case
              of encoding).

         (++) The application can call  functions HAL_JPEG_ ConfigOutputBuffer then HAL_JPEG_Resume.
              any time (outside the HAL_JPEG_DataReadyCallback) Once the output data buffer is free to use.
              However, to keep data coherency, the function HAL_JPEG_Pause must be imperatively called
              (if necessary) within the callback HAL_JPEG_ DataReadyCallback, i.e when the HAL JPEG has ended
              Transferring the previous chunk buffer from the JPEG peripheral to the application.

     (#) Callback HAL_JPEG_EncodeCpltCallback is asserted when the HAL JPEG driver has
         ended the current JPEG encoding operation, and all output data has been transmitted
         to the application.

     (#) Callback HAL_JPEG_DecodeCpltCallback is asserted when the HAL JPEG driver has
         ended the current JPEG decoding operation. and all output data has been transmitted
         to the application.

     (#) Callback HAL_JPEG_ErrorCallback is asserted when an error occurred during
         the current operation. the application can call the function HAL_JPEG_GetError()
         to retrieve the error codes.

     (#) By default the HAL JPEG driver uses the default quantization tables
         as provide in the JPEG specification (ISO/IEC 10918-1 standard) for encoding.
         User can change these default tables if necessary using the function HAL_JPEG_SetUserQuantTables
         Note that for decoding the quantization tables are automatically extracted from
         the JPEG header.

      (#) To control JPEG state you can use the following function: HAL_JPEG_GetState()

     *** JPEG HAL driver macros list ***
     =============================================
     [..]
       Below the list of most used macros in JPEG HAL driver.

      (+) __HAL_JPEG_RESET_HANDLE_STATE : Reset JPEG handle state.
      (+) __HAL_JPEG_ENABLE             : Enable the JPEG peripheral.
      (+) __HAL_JPEG_DISABLE            : Disable the JPEG peripheral.
      (+) __HAL_JPEG_GET_FLAG           : Check the specified JPEG status flag.
      (+) __HAL_JPEG_CLEAR_FLAG         : Clear the specified JPEG status flag.
      (+) __HAL_JPEG_ENABLE_IT          : Enable the specified JPEG Interrupt.
      (+) __HAL_JPEG_DISABLE_IT         : Disable the specified JPEG Interrupt.
      (+) __HAL_JPEG_GET_IT_SOURCE      : returns the state of the specified JPEG Interrupt (Enabled or disabled).

  *** Callback registration ***
  =============================================

  The compilation define  USE_HAL_JPEG_REGISTER_CALLBACKS when set to 1
  allows the user to configure dynamically the driver callbacks.
  Use Functions HAL_JPEG_RegisterCallback() or HAL_JPEG_RegisterXXXCallback()
  to register an interrupt callback.

  Function HAL_JPEG_RegisterCallback() allows to register following callbacks:
    (+) EncodeCpltCallback : callback for end of encoding operation.
    (+) DecodeCpltCallback : callback for end of decoding operation.
    (+) ErrorCallback      : callback for error detection.
    (+) MspInitCallback    : JPEG MspInit.
    (+) MspDeInitCallback  : JPEG MspDeInit.
  This function takes as parameters the HAL peripheral handle, the Callback ID
  and a pointer to the user callback function.

  For specific callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated
  register callbacks : respectively HAL_JPEG_RegisterInfoReadyCallback(),
  HAL_JPEG_RegisterGetDataCallback() and HAL_JPEG_RegisterDataReadyCallback().

  Use function HAL_JPEG_UnRegisterCallback() to reset a callback to the default
  weak function.
  HAL_JPEG_UnRegisterCallback() takes as parameters the HAL peripheral handle,
  and the Callback ID.
  This function allows to reset following callbacks:
    (+) EncodeCpltCallback : callback for end of encoding operation.
    (+) DecodeCpltCallback : callback for end of decoding operation.
    (+) ErrorCallback      : callback for error detection.
    (+) MspInitCallback    : JPEG MspInit.
    (+) MspDeInitCallback  : JPEG MspDeInit.

  For callbacks InfoReadyCallback, GetDataCallback and DataReadyCallback use dedicated
  unregister callbacks : respectively HAL_JPEG_UnRegisterInfoReadyCallback(),
  HAL_JPEG_UnRegisterGetDataCallback() and HAL_JPEG_UnRegisterDataReadyCallback().

  By default, after the HAL_JPEG_Init() and when the state is HAL_JPEG_STATE_RESET
  all callbacks are set to the corresponding weak functions :
  examples HAL_JPEG_DecodeCpltCallback() , HAL_JPEG_GetDataCallback().
  Exception done for MspInit and MspDeInit functions that are
  reset to the legacy weak function in the HAL_JPEG_Init()/ HAL_JPEG_DeInit() only when
  these callbacks are null (not registered beforehand).
  if not, MspInit or MspDeInit are not null, the HAL_JPEG_Init() / HAL_JPEG_DeInit()
  keep and use the user MspInit/MspDeInit functions (registered beforehand)

  Callbacks can be registered/unregistered in HAL_JPEG_STATE_READY state only.
  Exception done MspInit/MspDeInit callbacks that can be registered/unregistered
  in HAL_JPEG_STATE_READY or HAL_JPEG_STATE_RESET state,
  thus registered (user) MspInit/DeInit callbacks can be used during the Init/DeInit.
  In that case first register the MspInit/MspDeInit user callbacks
  using HAL_JPEG_RegisterCallback() before calling HAL_JPEG_DeInit()
  or HAL_JPEG_Init() function.

  When The compilation define USE_HAL_JPEG_REGISTER_CALLBACKS is set to 0 or
  not defined, the callback registration feature is not available and all callbacks
  are set to the corresponding weak functions.

  @endverbatim
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_hal.h"

/** @addtogroup STM32H7xx_HAL_Driver
  * @{
  */

#ifdef HAL_JPEG_MODULE_ENABLED

#if defined (JPEG)

/** @defgroup JPEG JPEG
  * @brief JPEG HAL module driver.
  * @{
  */

/* Private define ------------------------------------------------------------*/
/** @addtogroup JPEG_Private_Constants
  * @{
  */
#define JPEG_TIMEOUT_VALUE  ((uint32_t)1000)     /* 1s */
#define JPEG_AC_HUFF_TABLE_SIZE  ((uint32_t)162) /* Huffman AC table size : 162 codes*/
#define JPEG_DC_HUFF_TABLE_SIZE  ((uint32_t)12)  /* Huffman AC table size : 12 codes*/

#define JPEG_FIFO_SIZE ((uint32_t)16U)             /* JPEG Input/Output HW FIFO size in words*/

#define JPEG_FIFO_TH_SIZE ((uint32_t)8U)              /* JPEG Input/Output HW FIFO Threshold in words*/

#define JPEG_INTERRUPT_MASK  ((uint32_t)0x0000007EU) /* JPEG Interrupt Mask*/

#define JPEG_CONTEXT_ENCODE          ((uint32_t)0x00000001) /* JPEG context : operation is encoding*/
#define JPEG_CONTEXT_DECODE          ((uint32_t)0x00000002) /* JPEG context : operation is decoding*/
#define JPEG_CONTEXT_OPERATION_MASK  ((uint32_t)0x00000003) /* JPEG context : operation Mask */

#define JPEG_CONTEXT_POLLING        ((uint32_t)0x00000004)  /* JPEG context : Transfer use Polling */
#define JPEG_CONTEXT_IT             ((uint32_t)0x00000008)  /* JPEG context : Transfer use Interrupt */
#define JPEG_CONTEXT_DMA            ((uint32_t)0x0000000C)  /* JPEG context : Transfer use DMA */
#define JPEG_CONTEXT_METHOD_MASK    ((uint32_t)0x0000000C)  /* JPEG context : Transfer Mask */


#define JPEG_CONTEXT_CONF_ENCODING  ((uint32_t)0x00000100)  /* JPEG context : encoding config done */

#define JPEG_CONTEXT_PAUSE_INPUT    ((uint32_t)0x00001000)  /* JPEG context : Pause Input */
#define JPEG_CONTEXT_PAUSE_OUTPUT   ((uint32_t)0x00002000)  /* JPEG context : Pause Output */

#define JPEG_CONTEXT_CUSTOM_TABLES  ((uint32_t)0x00004000)  /* JPEG context : Use custom quantization tables */

#define JPEG_CONTEXT_ENDING_DMA     ((uint32_t)0x00008000)  /* JPEG context : ending with DMA in progress */

#define JPEG_PROCESS_ONGOING        ((uint32_t)0x00000000)  /* Process is on going */
#define JPEG_PROCESS_DONE           ((uint32_t)0x00000001)  /* Process is done (ends) */
/**
  * @}
  */

/* Private typedef -----------------------------------------------------------*/
/** @addtogroup JPEG_Private_Types
  * @{
  */

/*
 JPEG Huffman Table Structure definition :
 This implementation of Huffman table structure is compliant with ISO/IEC 10918-1 standard , Annex C Huffman Table specification
 */
typedef struct
{
  /* These two fields directly represent the contents of a JPEG DHT marker */
  uint8_t Bits[16];        /*!< bits[k] = # of symbols with codes of length k bits, this parameter corresponds to BITS list in the Annex C */

  uint8_t HuffVal[162];    /*!< The symbols, in order of incremented code length, this parameter corresponds to HUFFVAL list in the Annex C */


} JPEG_ACHuffTableTypeDef;

typedef struct
{
  /* These two fields directly represent the contents of a JPEG DHT marker */
  uint8_t Bits[16];        /*!< bits[k] = # of symbols with codes of length k bits, this parameter corresponds to BITS list in the Annex C */

  uint8_t HuffVal[12];    /*!< The symbols, in order of incremented code length, this parameter corresponds to HUFFVAL list in the Annex C */


} JPEG_DCHuffTableTypeDef;

typedef struct
{
  uint8_t CodeLength[JPEG_AC_HUFF_TABLE_SIZE];      /*!< Code length  */

  uint32_t HuffmanCode[JPEG_AC_HUFF_TABLE_SIZE];    /*!< HuffmanCode */

} JPEG_AC_HuffCodeTableTypeDef;

typedef struct
{
  uint8_t CodeLength[JPEG_DC_HUFF_TABLE_SIZE];        /*!< Code length  */

  uint32_t HuffmanCode[JPEG_DC_HUFF_TABLE_SIZE];    /*!< HuffmanCode */

} JPEG_DC_HuffCodeTableTypeDef;
/**
  * @}
  */

/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
/** @addtogroup JPEG_Private_Variables
  * @{
  */

static const JPEG_DCHuffTableTypeDef JPEG_DCLUM_HuffTable =
{
  { 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 },   /*Bits*/

  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb }           /*HUFFVAL */

};

static const JPEG_DCHuffTableTypeDef JPEG_DCCHROM_HuffTable =
{
  { 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 },  /*Bits*/

  { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb }          /*HUFFVAL */
};

static const JPEG_ACHuffTableTypeDef JPEG_ACLUM_HuffTable =
{
  { 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d },  /*Bits*/

  {
    0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,     /*HUFFVAL */
    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
  }
};

static const JPEG_ACHuffTableTypeDef JPEG_ACCHROM_HuffTable =
{
  { 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 },   /*Bits*/

  {
    0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,      /*HUFFVAL */
    0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
    0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
    0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
    0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
    0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
    0x27, 0x28, 0x29, 0x2a, 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, 0x82, 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,
    0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
    0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
    0xf9, 0xfa
  }
};

static const uint8_t JPEG_ZIGZAG_ORDER[JPEG_QUANT_TABLE_SIZE] =
{
  0,   1,   8,  16,   9,   2,   3,  10,
  17,  24,  32,  25,  18,  11,   4,   5,
  12,  19,  26,  33,  40,  48,  41,  34,
  27,  20,  13,   6,   7,  14,  21,  28,
  35,  42,  49,  56,  57,  50,  43,  36,
  29,  22,  15,  23,  30,  37,  44,  51,
  58,  59,  52,  45,  38,  31,  39,  46,
  53,  60,  61,  54,  47,  55,  62,  63
};
/**
  * @}
  */

/* Private function prototypes -----------------------------------------------*/
/** @addtogroup JPEG_Private_Functions_Prototypes
  * @{
  */

static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode, uint32_t *LastK);
static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable,
                                                           JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable);
static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable,
                                                           JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable);
static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC,
                                             const __IO uint32_t *DCTableAddress);
static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC,
                                             const __IO uint32_t *ACTableAddress);
static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg);
static void JPEG_Set_Huff_DHTMem(JPEG_HandleTypeDef *hjpeg);
static uint32_t  JPEG_Set_Quantization_Mem(JPEG_HandleTypeDef *hjpeg, uint8_t *QTable,
                                                    __IO uint32_t *QTableAddress);
static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg);
static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg);
static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg);

static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg);
static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg);
static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords);
static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords);
static uint32_t JPEG_GetQuality(JPEG_HandleTypeDef *hjpeg);

static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg);
static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg);
static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg);
static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg);
static void JPEG_MDMAOutCpltCallback(MDMA_HandleTypeDef *hmdma);
static void JPEG_MDMAInCpltCallback(MDMA_HandleTypeDef *hmdma);
static void JPEG_MDMAErrorCallback(MDMA_HandleTypeDef *hmdma);
static void JPEG_MDMAOutAbortCallback(MDMA_HandleTypeDef *hmdma);

/**
  * @}
  */

/** @defgroup JPEG_Exported_Functions JPEG Exported Functions
  * @{
  */

/** @defgroup JPEG_Exported_Functions_Group1 Initialization and de-initialization functions
  *  @brief    Initialization and de-initialization functions.
  *
@verbatim
  ==============================================================================
              ##### Initialization and de-initialization functions #####
  ==============================================================================
    [..]  This section provides functions allowing to:
      (+) Initialize the JPEG peripheral and creates the associated handle
      (+) DeInitialize the JPEG peripheral

@endverbatim
  * @{
  */

/**
  * @brief  Initializes the JPEG according to the specified
  *         parameters in the JPEG_InitTypeDef and creates the associated handle.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_Init(JPEG_HandleTypeDef *hjpeg)
{
  /* These are the sample quantization tables given in JPEG spec ISO/IEC 10918-1 standard , section K.1. */
  static const uint8_t JPEG_LUM_QuantTable[JPEG_QUANT_TABLE_SIZE] =
  {
    16,  11,  10,  16,  24,  40,  51,  61,
    12,  12,  14,  19,  26,  58,  60,  55,
    14,  13,  16,  24,  40,  57,  69,  56,
    14,  17,  22,  29,  51,  87,  80,  62,
    18,  22,  37,  56,  68, 109, 103,  77,
    24,  35,  55,  64,  81, 104, 113,  92,
    49,  64,  78,  87, 103, 121, 120, 101,
    72,  92,  95,  98, 112, 100, 103,  99
  };
  static const uint8_t JPEG_CHROM_QuantTable[JPEG_QUANT_TABLE_SIZE] =
  {
    17,  18,  24,  47,  99,  99,  99,  99,
    18,  21,  26,  66,  99,  99,  99,  99,
    24,  26,  56,  99,  99,  99,  99,  99,
    47,  66,  99,  99,  99,  99,  99,  99,
    99,  99,  99,  99,  99,  99,  99,  99,
    99,  99,  99,  99,  99,  99,  99,  99,
    99,  99,  99,  99,  99,  99,  99,  99,
    99,  99,  99,  99,  99,  99,  99,  99
  };

  /* Check the JPEG handle allocation */
  if (hjpeg == NULL)
  {
    return HAL_ERROR;
  }

#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
  if (hjpeg->State == HAL_JPEG_STATE_RESET)
  {
    /* Allocate lock resource and initialize it */
    hjpeg->Lock = HAL_UNLOCKED;

    hjpeg->InfoReadyCallback  = HAL_JPEG_InfoReadyCallback;  /* Legacy weak InfoReadyCallback  */
    hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback */
    hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback */
    hjpeg->ErrorCallback      = HAL_JPEG_ErrorCallback;      /* Legacy weak ErrorCallback      */
    hjpeg->GetDataCallback    = HAL_JPEG_GetDataCallback;    /* Legacy weak GetDataCallback    */
    hjpeg->DataReadyCallback  = HAL_JPEG_DataReadyCallback;  /* Legacy weak DataReadyCallback  */

    if (hjpeg->MspInitCallback == NULL)
    {
      hjpeg->MspInitCallback = HAL_JPEG_MspInit; /* Legacy weak MspInit  */
    }

    /* Init the low level hardware */
    hjpeg->MspInitCallback(hjpeg);
  }
#else
  if (hjpeg->State == HAL_JPEG_STATE_RESET)
  {
    /* Allocate lock resource and initialize it */
    hjpeg->Lock = HAL_UNLOCKED;

    /* Init the low level hardware : GPIO, CLOCK */
    HAL_JPEG_MspInit(hjpeg);
  }
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

  /* Change the JPEG state */
  hjpeg->State = HAL_JPEG_STATE_BUSY;

  /* Start the JPEG Core*/
  __HAL_JPEG_ENABLE(hjpeg);

  /* Stop the JPEG encoding/decoding process*/
  hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

  /* Disable All Interrupts */
  __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);


  /* Flush input and output FIFOs*/
  hjpeg->Instance->CR |= JPEG_CR_IFF;
  hjpeg->Instance->CR |= JPEG_CR_OFF;

  /* Clear all flags */
  __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);

  /* init default quantization tables*/
  hjpeg->QuantTable0 = (uint8_t *)((uint32_t)JPEG_LUM_QuantTable);
  hjpeg->QuantTable1 = (uint8_t *)((uint32_t)JPEG_CHROM_QuantTable);
  hjpeg->QuantTable2 = NULL;
  hjpeg->QuantTable3 = NULL;

  /* init the default Huffman tables*/
  if (JPEG_Set_HuffEnc_Mem(hjpeg) != HAL_OK)
  {
    hjpeg->ErrorCode = HAL_JPEG_ERROR_HUFF_TABLE;

    return HAL_ERROR;
  }

  /* Enable header processing*/
  hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR;

  /* Reset JpegInCount and JpegOutCount */
  hjpeg->JpegInCount = 0;
  hjpeg->JpegOutCount = 0;

  /* Change the JPEG state */
  hjpeg->State = HAL_JPEG_STATE_READY;

  /* Reset the JPEG ErrorCode */
  hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE;

  /*Clear the context filelds*/
  hjpeg->Context = 0;

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  DeInitializes the JPEG peripheral.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_DeInit(JPEG_HandleTypeDef *hjpeg)
{
  /* Check the JPEG handle allocation */
  if (hjpeg == NULL)
  {
    return HAL_ERROR;
  }

#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
  if (hjpeg->MspDeInitCallback == NULL)
  {
    hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit; /* Legacy weak MspDeInit  */
  }

  /* DeInit the low level hardware */
  hjpeg->MspDeInitCallback(hjpeg);

#else
  /* DeInit the low level hardware: CLOCK, NVIC.*/
  HAL_JPEG_MspDeInit(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

  /* Change the JPEG state */
  hjpeg->State = HAL_JPEG_STATE_BUSY;

  /* Reset the JPEG ErrorCode */
  hjpeg->ErrorCode = HAL_JPEG_ERROR_NONE;

  /* Reset JpegInCount and JpegOutCount */
  hjpeg->JpegInCount = 0;
  hjpeg->JpegOutCount = 0;

  /* Change the JPEG state */
  hjpeg->State = HAL_JPEG_STATE_RESET;

  /*Clear the context fields*/
  hjpeg->Context = 0;

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Initializes the JPEG MSP.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
__weak void HAL_JPEG_MspInit(JPEG_HandleTypeDef *hjpeg)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_MspInit could be implemented in the user file
   */
}

/**
  * @brief  DeInitializes JPEG MSP.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
__weak void HAL_JPEG_MspDeInit(JPEG_HandleTypeDef *hjpeg)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_MspDeInit could be implemented in the user file
   */
}

#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
/**
  * @brief  Register a User JPEG Callback
  *         To be used instead of the weak predefined callback
  * @param  hjpeg JPEG handle
  * @param  CallbackID ID of the callback to be registered
  *         This parameter can be one of the following values:
  *          @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID
  *          @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID
  *          @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID
  *          @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID
  *          @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID
  * @param  pCallback pointer to the Callback function
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_RegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID,
                                            pJPEG_CallbackTypeDef pCallback)
{
  HAL_StatusTypeDef status = HAL_OK;

  if (pCallback == NULL)
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    return HAL_ERROR;
  }
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    switch (CallbackID)
    {
      case HAL_JPEG_ENCODE_CPLT_CB_ID :
        hjpeg->EncodeCpltCallback = pCallback;
        break;

      case HAL_JPEG_DECODE_CPLT_CB_ID :
        hjpeg->DecodeCpltCallback = pCallback;
        break;

      case HAL_JPEG_ERROR_CB_ID :
        hjpeg->ErrorCallback = pCallback;
        break;

      case HAL_JPEG_MSPINIT_CB_ID :
        hjpeg->MspInitCallback = pCallback;
        break;

      case HAL_JPEG_MSPDEINIT_CB_ID :
        hjpeg->MspDeInitCallback = pCallback;
        break;

      default :
        /* Update the error code */
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
        /* Return error status */
        status =  HAL_ERROR;
        break;
    }
  }
  else if (HAL_JPEG_STATE_RESET == hjpeg->State)
  {
    switch (CallbackID)
    {
      case HAL_JPEG_MSPINIT_CB_ID :
        hjpeg->MspInitCallback = pCallback;
        break;

      case HAL_JPEG_MSPDEINIT_CB_ID :
        hjpeg->MspDeInitCallback = pCallback;
        break;

      default :
        /* Update the error code */
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
        /* Return error status */
        status =  HAL_ERROR;
        break;
    }
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  Unregister a JPEG Callback
  *         JPEG callabck is redirected to the weak predefined callback
  * @param  hjpeg JPEG handle
  * @param  CallbackID ID of the callback to be unregistered
  *         This parameter can be one of the following values:
  *         This parameter can be one of the following values:
  *          @arg @ref HAL_JPEG_ENCODE_CPLT_CB_ID Encode Complete callback ID
  *          @arg @ref HAL_JPEG_DECODE_CPLT_CB_ID Decode Complete callback ID
  *          @arg @ref HAL_JPEG_ERROR_CB_ID Error callback ID
  *          @arg @ref HAL_JPEG_MSPINIT_CB_ID MspInit callback ID
  *          @arg @ref HAL_JPEG_MSPDEINIT_CB_ID MspDeInit callback ID
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_UnRegisterCallback(JPEG_HandleTypeDef *hjpeg, HAL_JPEG_CallbackIDTypeDef CallbackID)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    switch (CallbackID)
    {
      case HAL_JPEG_ENCODE_CPLT_CB_ID :
        hjpeg->EncodeCpltCallback = HAL_JPEG_EncodeCpltCallback; /* Legacy weak EncodeCpltCallback  */
        break;

      case HAL_JPEG_DECODE_CPLT_CB_ID :
        hjpeg->DecodeCpltCallback = HAL_JPEG_DecodeCpltCallback; /* Legacy weak DecodeCpltCallback  */
        break;

      case HAL_JPEG_ERROR_CB_ID :
        hjpeg->ErrorCallback = HAL_JPEG_ErrorCallback;           /* Legacy weak ErrorCallback  */
        break;

      case HAL_JPEG_MSPINIT_CB_ID :
        hjpeg->MspInitCallback = HAL_JPEG_MspInit;              /* Legacy weak MspInit  */
        break;

      case HAL_JPEG_MSPDEINIT_CB_ID :
        hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit;          /* Legacy weak MspDeInit  */
        break;

      default :
        /* Update the error code */
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
        /* Return error status */
        status =  HAL_ERROR;
        break;
    }
  }
  else if (HAL_JPEG_STATE_RESET == hjpeg->State)
  {
    switch (CallbackID)
    {
      case HAL_JPEG_MSPINIT_CB_ID :
        hjpeg->MspInitCallback = HAL_JPEG_MspInit;           /* Legacy weak MspInit  */
        break;

      case HAL_JPEG_MSPDEINIT_CB_ID :
        hjpeg->MspDeInitCallback = HAL_JPEG_MspDeInit;       /* Legacy weak MspInit  */
        break;

      default :
        /* Update the error code */
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
        /* Return error status */
        status =  HAL_ERROR;
        break;
    }
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  Register Info Ready JPEG Callback
  *         To be used instead of the weak HAL_JPEG_InfoReadyCallback() predefined callback
  * @param  hjpeg JPEG handle
  * @param  pCallback pointer to the Info Ready Callback function
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_RegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg,
                                                     pJPEG_InfoReadyCallbackTypeDef pCallback)
{
  HAL_StatusTypeDef status = HAL_OK;

  if (pCallback == NULL)
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    return HAL_ERROR;
  }
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    hjpeg->InfoReadyCallback = pCallback;
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  UnRegister the Info Ready JPEG Callback
  *         Info Ready JPEG Callback is redirected to the weak HAL_JPEG_InfoReadyCallback() predefined callback
  * @param  hjpeg JPEG handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_UnRegisterInfoReadyCallback(JPEG_HandleTypeDef *hjpeg)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    hjpeg->InfoReadyCallback = HAL_JPEG_InfoReadyCallback; /* Legacy weak InfoReadyCallback  */
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  Register Get Data JPEG Callback
  *         To be used instead of the weak HAL_JPEG_GetDataCallback() predefined callback
  * @param  hjpeg JPEG handle
  * @param  pCallback pointer to the Get Data Callback function
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_RegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg, pJPEG_GetDataCallbackTypeDef pCallback)
{
  HAL_StatusTypeDef status = HAL_OK;

  if (pCallback == NULL)
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    return HAL_ERROR;
  }
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    hjpeg->GetDataCallback = pCallback;
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  UnRegister the Get Data JPEG Callback
  *         Get Data JPEG Callback is redirected to the weak HAL_JPEG_GetDataCallback() predefined callback
  * @param  hjpeg JPEG handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_UnRegisterGetDataCallback(JPEG_HandleTypeDef *hjpeg)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    hjpeg->GetDataCallback = HAL_JPEG_GetDataCallback;  /* Legacy weak GetDataCallback  */
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  Register Data Ready JPEG Callback
  *         To be used instead of the weak HAL_JPEG_DataReadyCallback() predefined callback
  * @param  hjpeg JPEG handle
  * @param  pCallback pointer to the Get Data Callback function
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_RegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg,
                                                     pJPEG_DataReadyCallbackTypeDef pCallback)
{
  HAL_StatusTypeDef status = HAL_OK;

  if (pCallback == NULL)
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    return HAL_ERROR;
  }
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    hjpeg->DataReadyCallback = pCallback;
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

/**
  * @brief  UnRegister the Data Ready JPEG Callback
  *         Get Data Ready Callback is redirected to the weak HAL_JPEG_DataReadyCallback() predefined callback
  * @param  hjpeg JPEG handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_UnRegisterDataReadyCallback(JPEG_HandleTypeDef *hjpeg)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (HAL_JPEG_STATE_READY == hjpeg->State)
  {
    hjpeg->DataReadyCallback = HAL_JPEG_DataReadyCallback;  /* Legacy weak DataReadyCallback  */
  }
  else
  {
    /* Update the error code */
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_INVALID_CALLBACK;
    /* Return error status */
    status =  HAL_ERROR;
  }

  /* Release Lock */
  __HAL_UNLOCK(hjpeg);
  return status;
}

#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

/**
  * @}
  */

/** @defgroup JPEG_Exported_Functions_Group2 Configuration functions
  *  @brief    JPEG Configuration functions.
  *
@verbatim
  ==============================================================================
              ##### Configuration functions #####
  ==============================================================================
    [..]  This section provides functions allowing to:
      (+) HAL_JPEG_ConfigEncoding() : JPEG encoding configuration
      (+) HAL_JPEG_GetInfo() :  Extract the image configuration from the JPEG header during the decoding
      (+) HAL_JPEG_EnableHeaderParsing() :  Enable JPEG Header parsing for decoding
      (+) HAL_JPEG_DisableHeaderParsing() : Disable JPEG Header parsing for decoding
      (+) HAL_JPEG_SetUserQuantTables : Modify the default Quantization tables used for JPEG encoding.

@endverbatim
  * @{
  */

/**
  * @brief  Set the JPEG encoding configuration.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pConf pointer to a JPEG_ConfTypeDef structure that contains
  *         the encoding configuration
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_ConfigEncoding(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pConf)
{
  uint32_t error;
  uint32_t numberMCU;
  uint32_t hfactor;
  uint32_t vfactor;
  uint32_t hMCU;
  uint32_t vMCU;

  /* Check the JPEG handle allocation */
  if ((hjpeg == NULL) || (pConf == NULL))
  {
    return HAL_ERROR;
  }
  else
  {
    /* Check the parameters */
    assert_param(IS_JPEG_COLORSPACE(pConf->ColorSpace));
    assert_param(IS_JPEG_CHROMASUBSAMPLING(pConf->ChromaSubsampling));
    assert_param(IS_JPEG_IMAGE_QUALITY(pConf->ImageQuality));

    /* Process Locked */
    __HAL_LOCK(hjpeg);

    if (hjpeg->State == HAL_JPEG_STATE_READY)
    {
      hjpeg->State = HAL_JPEG_STATE_BUSY;

      hjpeg->Conf.ColorSpace          =  pConf->ColorSpace;
      hjpeg->Conf.ChromaSubsampling   =  pConf->ChromaSubsampling;
      hjpeg->Conf.ImageHeight         =  pConf->ImageHeight;
      hjpeg->Conf.ImageWidth          =  pConf->ImageWidth;
      hjpeg->Conf.ImageQuality        =  pConf->ImageQuality;

      /* Reset the Color Space : by default only one quantization table is used*/
      hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_COLORSPACE;

      /* Set Number of color components*/
      if (hjpeg->Conf.ColorSpace == JPEG_GRAYSCALE_COLORSPACE)
      {
        /*Gray Scale is only one component 8x8 blocks i.e 4:4:4*/
        hjpeg->Conf.ChromaSubsampling = JPEG_444_SUBSAMPLING;

        JPEG_SetColorGrayScale(hjpeg);
        /* Set quantization table 0*/
        error = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0));
      }
      else if (hjpeg->Conf.ColorSpace == JPEG_YCBCR_COLORSPACE)
      {
        /*
           Set the Color Space for YCbCr : 2 quantization tables are used
           one for Luminance(Y) and one for both Chrominances (Cb & Cr)
          */
        hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_0;

        JPEG_SetColorYCBCR(hjpeg);

        /* Set quantization table 0*/
        error  = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0));
        /*By default quantization table 0 for component 0 and quantization table 1 for both components 1 and 2*/
        error |= JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1));

        if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL)
        {
          /*Use user customized quantization tables , 1 table per component*/
          /* use 3 quantization tables , one for each component*/
          hjpeg->Instance->CONFR1 &= (~JPEG_CONFR1_COLORSPACE);
          hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE_1;

          error |= JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2));

          /*Use Quantization 1 table for component 1*/
          hjpeg->Instance->CONFR5 &= (~JPEG_CONFR5_QT);
          hjpeg->Instance->CONFR5 |=  JPEG_CONFR5_QT_0;

          /*Use Quantization 2 table for component 2*/
          hjpeg->Instance->CONFR6 &= (~JPEG_CONFR6_QT);
          hjpeg->Instance->CONFR6 |=  JPEG_CONFR6_QT_1;
        }
      }
      else /* ColorSpace == JPEG_CMYK_COLORSPACE */
      {
        JPEG_SetColorCMYK(hjpeg);

        /* Set quantization table 0*/
        error  = JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable0, (hjpeg->Instance->QMEM0));
        /*By default quantization table 0 for All components*/

        if ((hjpeg->Context & JPEG_CONTEXT_CUSTOM_TABLES) != 0UL)
        {
          /*Use user customized quantization tables , 1 table per component*/
          /* use 4 quantization tables , one for each component*/
          hjpeg->Instance->CONFR1 |= JPEG_CONFR1_COLORSPACE;

          error |= JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable1, (hjpeg->Instance->QMEM1));
          error |= JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable2, (hjpeg->Instance->QMEM2));
          error |= JPEG_Set_Quantization_Mem(hjpeg, hjpeg->QuantTable3, (hjpeg->Instance->QMEM3));

          /*Use Quantization 1 table for component 1*/
          hjpeg->Instance->CONFR5 |=  JPEG_CONFR5_QT_0;

          /*Use Quantization 2 table for component 2*/
          hjpeg->Instance->CONFR6 |=  JPEG_CONFR6_QT_1;

          /*Use Quantization 3 table for component 3*/
          hjpeg->Instance->CONFR7 |=  JPEG_CONFR7_QT;
        }
      }

      if (error != 0UL)
      {
        hjpeg->ErrorCode = HAL_JPEG_ERROR_QUANT_TABLE;

        /* Process Unlocked */
        __HAL_UNLOCK(hjpeg);

        /* Set the JPEG State to ready */
        hjpeg->State = HAL_JPEG_STATE_READY;

        return  HAL_ERROR;
      }
      /* Set the image size*/
      /* set the number of lines*/
      MODIFY_REG(hjpeg->Instance->CONFR1, JPEG_CONFR1_YSIZE, ((hjpeg->Conf.ImageHeight & 0x0000FFFFUL) << 16));
      /* set the number of pixels per line*/
      MODIFY_REG(hjpeg->Instance->CONFR3, JPEG_CONFR3_XSIZE, ((hjpeg->Conf.ImageWidth & 0x0000FFFFUL) << 16));


      if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING) /* 4:2:0*/
      {
        hfactor = 16;
        vfactor = 16;
      }
      else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING) /* 4:2:2*/
      {
        hfactor = 16;
        vfactor = 8;
      }
      else /* Default is 8x8 MCU,  4:4:4*/
      {
        hfactor = 8;
        vfactor = 8;
      }

      hMCU = (hjpeg->Conf.ImageWidth / hfactor);
      if ((hjpeg->Conf.ImageWidth % hfactor) != 0UL)
      {
        hMCU++; /*+1 for horizontal incomplete MCU */
      }

      vMCU = (hjpeg->Conf.ImageHeight / vfactor);
      if ((hjpeg->Conf.ImageHeight % vfactor) != 0UL)
      {
        vMCU++; /*+1 for vertical incomplete MCU */
      }

      numberMCU = (hMCU * vMCU) - 1UL; /* Bit Field JPEG_CONFR2_NMCU shall be set to NB_MCU - 1*/
      /* Set the number of MCU*/
      hjpeg->Instance->CONFR2 = (numberMCU & JPEG_CONFR2_NMCU);

      hjpeg->Context |= JPEG_CONTEXT_CONF_ENCODING;

      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      /* Set the JPEG State to ready */
      hjpeg->State = HAL_JPEG_STATE_READY;

      /* Return function status */
      return HAL_OK;
    }
    else
    {
      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      /* Return function status */
      return HAL_BUSY;
    }
  }
}

/**
  * @brief  Extract the image configuration from the JPEG header during the decoding
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pInfo pointer to a JPEG_ConfTypeDef structure that contains
  *         The JPEG decoded header information
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_GetInfo(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo)
{
  uint32_t yblockNb;
  uint32_t cBblockNb;
  uint32_t cRblockNb;

  /* Check the JPEG handle allocation */
  if ((hjpeg == NULL) || (pInfo == NULL))
  {
    return HAL_ERROR;
  }

  /*Read the conf parameters */
  if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF_1)
  {
    pInfo->ColorSpace = JPEG_YCBCR_COLORSPACE;
  }
  else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == 0UL)
  {
    pInfo->ColorSpace = JPEG_GRAYSCALE_COLORSPACE;
  }
  else if ((hjpeg->Instance->CONFR1 & JPEG_CONFR1_NF) == JPEG_CONFR1_NF)
  {
    pInfo->ColorSpace = JPEG_CMYK_COLORSPACE;
  }
  else
  {
    return HAL_ERROR;
  }

  pInfo->ImageHeight = (hjpeg->Instance->CONFR1 & 0xFFFF0000UL) >> 16;
  pInfo->ImageWidth  = (hjpeg->Instance->CONFR3 & 0xFFFF0000UL) >> 16;

  if ((pInfo->ColorSpace == JPEG_YCBCR_COLORSPACE) || (pInfo->ColorSpace == JPEG_CMYK_COLORSPACE))
  {
    yblockNb  = (hjpeg->Instance->CONFR4 & JPEG_CONFR4_NB) >> 4;
    cBblockNb = (hjpeg->Instance->CONFR5 & JPEG_CONFR5_NB) >> 4;
    cRblockNb = (hjpeg->Instance->CONFR6 & JPEG_CONFR6_NB) >> 4;

    if ((yblockNb == 1UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL))
    {
      pInfo->ChromaSubsampling = JPEG_422_SUBSAMPLING; /*16x8 block*/
    }
    else if ((yblockNb == 0UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL))
    {
      pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING;
    }
    else if ((yblockNb == 3UL) && (cBblockNb == 0UL) && (cRblockNb == 0UL))
    {
      pInfo->ChromaSubsampling = JPEG_420_SUBSAMPLING;
    }
    else /*Default is 4:4:4*/
    {
      pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING;
    }
  }
  else
  {
    pInfo->ChromaSubsampling = JPEG_444_SUBSAMPLING;
  }

  pInfo->ImageQuality = JPEG_GetQuality(hjpeg);

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Enable JPEG Header parsing for decoding
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *               the configuration information for the JPEG.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_EnableHeaderParsing(JPEG_HandleTypeDef *hjpeg)
{
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_BUSY;

    /* Enable header processing*/
    hjpeg->Instance->CONFR1 |= JPEG_CONFR1_HDR;

    /* Process unlocked */
    __HAL_UNLOCK(hjpeg);

    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_READY;

    return HAL_OK;
  }
  else
  {
    /* Process unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
}

/**
  * @brief  Disable JPEG Header parsing for decoding
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *               the configuration information for the JPEG.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_DisableHeaderParsing(JPEG_HandleTypeDef *hjpeg)
{
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_BUSY;

    /* Disable header processing*/
    hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_HDR;

    /* Process unlocked */
    __HAL_UNLOCK(hjpeg);

    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_READY;

    return HAL_OK;
  }
  else
  {
    /* Process unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
}

/**
  * @brief  Modify the default Quantization tables used for JPEG encoding.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  QTable0  pointer to uint8_t , define the user quantification table for color component 1.
  *                  If NULL assume no need to update  the table and no error return
  * @param  QTable1  pointer to uint8_t , define the user quantification table for color component 2.
  *                  If NULL assume no need to update  the table and no error return.
  * @param  QTable2  pointer to uint8_t , define the user quantification table for color component 3,
  *                  If NULL assume no need to update  the table and no error return.
  * @param  QTable3  pointer to uint8_t , define the user quantification table for color component 4.
  *                  If NULL assume no need to update  the table and no error return.
  *
  * @retval HAL status
  */


HAL_StatusTypeDef  HAL_JPEG_SetUserQuantTables(JPEG_HandleTypeDef *hjpeg, uint8_t *QTable0, uint8_t *QTable1,
                                               uint8_t *QTable2, uint8_t *QTable3)
{
  /* Process Locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    /* Change the DMA state */
    hjpeg->State = HAL_JPEG_STATE_BUSY;

    hjpeg->Context |= JPEG_CONTEXT_CUSTOM_TABLES;

    hjpeg->QuantTable0 = QTable0;
    hjpeg->QuantTable1 = QTable1;
    hjpeg->QuantTable2 = QTable2;
    hjpeg->QuantTable3 = QTable3;

    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    /* Change the DMA state */
    hjpeg->State = HAL_JPEG_STATE_READY;

    /* Return function status */
    return HAL_OK;
  }
  else
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
}

/**
  * @}
  */

/** @defgroup JPEG_Exported_Functions_Group3 encoding/decoding processing functions
  *  @brief   processing functions.
  *
@verbatim
  ==============================================================================
                      ##### JPEG processing functions #####
  ==============================================================================
    [..]  This section provides functions allowing to:
      (+) HAL_JPEG_Encode()     : JPEG encoding with polling process
      (+) HAL_JPEG_Decode()     : JPEG decoding with polling process
      (+) HAL_JPEG_Encode_IT()  : JPEG encoding with interrupt process
      (+) HAL_JPEG_Decode_IT()  : JPEG decoding with interrupt process
      (+) HAL_JPEG_Encode_DMA() : JPEG encoding with DMA process
      (+) HAL_JPEG_Decode_DMA() : JPEG decoding with DMA process
      (+) HAL_JPEG_Pause()      :   Pause the Input/Output processing
      (+) HAL_JPEG_Resume()     :  Resume the JPEG Input/Output processing
      (+) HAL_JPEG_ConfigInputBuffer()  : Config Encoding/Decoding Input Buffer
      (+) HAL_JPEG_ConfigOutputBuffer() : Config Encoding/Decoding Output Buffer
      (+) HAL_JPEG_Abort()              : Aborts the JPEG Encoding/Decoding

@endverbatim
  * @{
  */

/**
  * @brief  Starts JPEG encoding with polling processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataInMCU Pointer to the Input buffer
  * @param  InDataLength size in bytes Input buffer
  * @param  pDataOut Pointer to the jpeg output data buffer
  * @param  OutDataLength size in bytes of the Output buffer
  * @param  Timeout Specify Timeout value
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Encode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength,
                                   uint8_t *pDataOut, uint32_t OutDataLength, uint32_t Timeout)
{
  uint32_t tickstart;

  /* Check the parameters */
  assert_param((InDataLength >= 4UL));
  assert_param((OutDataLength >= 4UL));

  /* Check In/out buffer allocation and size */
  if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL))
  {
    return HAL_ERROR;
  }
  /* Process locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State != HAL_JPEG_STATE_READY)
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING)
    {
      /*Change JPEG state*/
      hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING;

      /*Set the Context to Encode with Polling*/
      hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
      hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_POLLING);

      /* Get tick */
      tickstart = HAL_GetTick();

      /*Store In/out buffers pointers and size*/
      hjpeg->pJpegInBuffPtr = pDataInMCU;
      hjpeg->pJpegOutBuffPtr = pDataOut;
      hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /* In Data length must be multiple of 4 Bytes (1 word)*/
      hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /* Out Data length must be multiple of 4 Bytes (1 word)*/

      /*Reset In/out data counter */
      hjpeg->JpegInCount = 0;
      hjpeg->JpegOutCount = 0;

      /*Init decoding process*/
      JPEG_Init_Process(hjpeg);

      /*JPEG data processing : In/Out FIFO transfer*/
      while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING))
      {
        if (Timeout != HAL_MAX_DELAY)
        {
          if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
          {

            /* Update error code */
            hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT;

            /* Process Unlocked */
            __HAL_UNLOCK(hjpeg);

            /*Change JPEG state*/
            hjpeg->State = HAL_JPEG_STATE_READY;

            return HAL_TIMEOUT;
          }
        }
      }

      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      /*Change JPEG state*/
      hjpeg->State = HAL_JPEG_STATE_READY;

    }
    else
    {
      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      return HAL_ERROR;
    }
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Starts JPEG decoding with polling processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataIn Pointer to the input data buffer
  * @param  InDataLength size in bytes Input buffer
  * @param  pDataOutMCU Pointer to the Output data buffer
  * @param  OutDataLength size in bytes of the Output buffer
  * @param  Timeout Specify Timeout value
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Decode(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength,
                                   uint8_t *pDataOutMCU, uint32_t OutDataLength, uint32_t Timeout)
{
  uint32_t tickstart;

  /* Check the parameters */
  assert_param((InDataLength >= 4UL));
  assert_param((OutDataLength >= 4UL));

  /* Check In/out buffer allocation and size */
  if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL))
  {
    return HAL_ERROR;
  }

  /* Process Locked */
  __HAL_LOCK(hjpeg);

  /* Get tick */
  tickstart = HAL_GetTick();

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    /*Change JPEG state*/
    hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING;

    /*Set the Context to Decode with Polling*/
    /*Set the Context to Encode with Polling*/
    hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
    hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_POLLING);

    /*Store In/out buffers pointers and size*/
    hjpeg->pJpegInBuffPtr = pDataIn;
    hjpeg->pJpegOutBuffPtr = pDataOutMCU;
    hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /*In Data length must be multiple of 4 Bytes (1 word)*/
    hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple of 4 Bytes (1 word)*/

    /*Reset In/out data counter */
    hjpeg->JpegInCount = 0;
    hjpeg->JpegOutCount = 0;

    /*Init decoding process*/
    JPEG_Init_Process(hjpeg);

    /*JPEG data processing : In/Out FIFO transfer*/
    while ((JPEG_Process(hjpeg) == JPEG_PROCESS_ONGOING))
    {
      if (Timeout != HAL_MAX_DELAY)
      {
        if (((HAL_GetTick() - tickstart) > Timeout) || (Timeout == 0UL))
        {

          /* Update error code */
          hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT;

          /* Process Unlocked */
          __HAL_UNLOCK(hjpeg);

          /*Change JPEG state*/
          hjpeg->State = HAL_JPEG_STATE_READY;

          return HAL_TIMEOUT;
        }
      }
    }

    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    /*Change JPEG state*/
    hjpeg->State = HAL_JPEG_STATE_READY;

  }
  else
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Starts JPEG encoding with interrupt processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataInMCU Pointer to the Input buffer
  * @param  InDataLength size in bytes Input buffer
  * @param  pDataOut Pointer to the jpeg output data buffer
  * @param  OutDataLength size in bytes of the Output buffer
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Encode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength,
                                      uint8_t *pDataOut, uint32_t OutDataLength)
{
  /* Check the parameters */
  assert_param((InDataLength >= 4UL));
  assert_param((OutDataLength >= 4UL));

  /* Check In/out buffer allocation and size */
  if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL))
  {
    return HAL_ERROR;
  }

  /* Process Locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State != HAL_JPEG_STATE_READY)
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
  else
  {
    if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING)
    {
      /*Change JPEG state*/
      hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING;

      /*Set the Context to Encode with IT*/
      hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
      hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_IT);

      /*Store In/out buffers pointers and size*/
      hjpeg->pJpegInBuffPtr = pDataInMCU;
      hjpeg->pJpegOutBuffPtr = pDataOut;
      hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /*In Data length must be multiple of 4 Bytes (1 word)*/
      hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple of 4 Bytes (1 word)*/

      /*Reset In/out data counter */
      hjpeg->JpegInCount = 0;
      hjpeg->JpegOutCount = 0;

      /*Init decoding process*/
      JPEG_Init_Process(hjpeg);

    }
    else
    {
      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      return HAL_ERROR;
    }
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Starts JPEG decoding with interrupt processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataIn Pointer to the input data buffer
  * @param  InDataLength size in bytes Input buffer
  * @param  pDataOutMCU Pointer to the Output data buffer
  * @param  OutDataLength size in bytes of the Output buffer
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Decode_IT(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength,
                                      uint8_t *pDataOutMCU, uint32_t OutDataLength)
{
  /* Check the parameters */
  assert_param((InDataLength >= 4UL));
  assert_param((OutDataLength >= 4UL));

  /* Check In/out buffer allocation and size */
  if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL))
  {
    return HAL_ERROR;
  }

  /* Process Locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    /*Change JPEG state*/
    hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING;

    /*Set the Context to Decode with IT*/
    hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
    hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_IT);

    /*Store In/out buffers pointers and size*/
    hjpeg->pJpegInBuffPtr = pDataIn;
    hjpeg->pJpegOutBuffPtr = pDataOutMCU;
    hjpeg->InDataLength = InDataLength - (InDataLength % 4UL);    /*In Data length must be multiple of 4 Bytes (1 word)*/
    hjpeg->OutDataLength = OutDataLength - (OutDataLength % 4UL); /*Out Data length must be multiple of 4 Bytes (1 word)*/

    /*Reset In/out data counter */
    hjpeg->JpegInCount = 0;
    hjpeg->JpegOutCount = 0;

    /*Init decoding process*/
    JPEG_Init_Process(hjpeg);

  }
  else
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Starts JPEG encoding with DMA processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataInMCU Pointer to the Input buffer
  * @param  InDataLength size in bytes Input buffer
  * @param  pDataOut Pointer to the jpeg output data buffer
  * @param  OutDataLength size in bytes of the Output buffer
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Encode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataInMCU, uint32_t InDataLength,
                                       uint8_t *pDataOut, uint32_t OutDataLength)
{
  /* Check the parameters */
  assert_param((InDataLength >= 4UL));
  assert_param((OutDataLength >= 4UL));

  /* Check In/out buffer allocation and size */
  if ((hjpeg == NULL) || (pDataInMCU == NULL) || (pDataOut == NULL))
  {
    return HAL_ERROR;
  }

  /* Process Locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State != HAL_JPEG_STATE_READY)
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
  else
  {
    if ((hjpeg->Context & JPEG_CONTEXT_CONF_ENCODING) == JPEG_CONTEXT_CONF_ENCODING)
    {
      /*Change JPEG state*/
      hjpeg->State = HAL_JPEG_STATE_BUSY_ENCODING;

      /*Set the Context to Encode with DMA*/
      hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
      hjpeg->Context |= (JPEG_CONTEXT_ENCODE | JPEG_CONTEXT_DMA);

      /*Store In/out buffers pointers and size*/
      hjpeg->pJpegInBuffPtr = pDataInMCU;
      hjpeg->pJpegOutBuffPtr = pDataOut;
      hjpeg->InDataLength = InDataLength;
      hjpeg->OutDataLength = OutDataLength;

      /*Reset In/out data counter */
      hjpeg->JpegInCount = 0;
      hjpeg->JpegOutCount = 0;

      /*Init decoding process*/
      JPEG_Init_Process(hjpeg);

      /* JPEG encoding process using DMA */
      if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK)
      {
        /* Update State */
        hjpeg->State = HAL_JPEG_STATE_ERROR;
        /* Process Unlocked */
        __HAL_UNLOCK(hjpeg);

        return HAL_ERROR;
      }

    }
    else
    {
      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      return HAL_ERROR;
    }
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Starts JPEG decoding with DMA processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataIn Pointer to the input data buffer
  * @param  InDataLength size in bytes Input buffer
  * @param  pDataOutMCU Pointer to the Output data buffer
  * @param  OutDataLength size in bytes of the Output buffer
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Decode_DMA(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataIn, uint32_t InDataLength,
                                       uint8_t *pDataOutMCU, uint32_t OutDataLength)
{
  /* Check the parameters */
  assert_param((InDataLength >= 4UL));
  assert_param((OutDataLength >= 4UL));

  /* Check In/out buffer allocation and size */
  if ((hjpeg == NULL) || (pDataIn == NULL) || (pDataOutMCU == NULL))
  {
    return HAL_ERROR;
  }

  /* Process Locked */
  __HAL_LOCK(hjpeg);

  if (hjpeg->State == HAL_JPEG_STATE_READY)
  {
    /*Change JPEG state*/
    hjpeg->State = HAL_JPEG_STATE_BUSY_DECODING;

    /*Set the Context to Decode with DMA*/
    hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK);
    hjpeg->Context |= (JPEG_CONTEXT_DECODE | JPEG_CONTEXT_DMA);

    /*Store In/out buffers pointers and size*/
    hjpeg->pJpegInBuffPtr = pDataIn;
    hjpeg->pJpegOutBuffPtr = pDataOutMCU;
    hjpeg->InDataLength = InDataLength;
    hjpeg->OutDataLength = OutDataLength;

    /*Reset In/out data counter */
    hjpeg->JpegInCount = 0;
    hjpeg->JpegOutCount = 0;

    /*Init decoding process*/
    JPEG_Init_Process(hjpeg);

    /* JPEG decoding process using DMA */
    if (JPEG_DMA_StartProcess(hjpeg) != HAL_OK)
    {
      /* Update State */
      hjpeg->State = HAL_JPEG_STATE_ERROR;
      /* Process Unlocked */
      __HAL_UNLOCK(hjpeg);

      return HAL_ERROR;
    }
  }
  else
  {
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    return HAL_BUSY;
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Pause the JPEG Input/Output processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  XferSelection This parameter can be one of the following values :
  *                           JPEG_PAUSE_RESUME_INPUT : Pause Input processing
  *                           JPEG_PAUSE_RESUME_OUTPUT: Pause Output processing
  *                           JPEG_PAUSE_RESUME_INPUT_OUTPUT: Pause Input and Output processing
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Pause(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection)
{
  uint32_t mask = 0;

  assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection));

  if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
  {
    if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
    {
      hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT;
    }
    if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
    {
      hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT;
    }

  }
  else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
  {

    if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
    {
      hjpeg->Context |= JPEG_CONTEXT_PAUSE_INPUT;
      mask |= (JPEG_IT_IFT | JPEG_IT_IFNF);
    }
    if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
    {
      hjpeg->Context |= JPEG_CONTEXT_PAUSE_OUTPUT;
      mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC);
    }
    __HAL_JPEG_DISABLE_IT(hjpeg, mask);

  }
  else
  {
    /* Nothing to do */
  }

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Resume the JPEG Input/Output processing
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  XferSelection This parameter can be one of the following values :
  *                           JPEG_PAUSE_RESUME_INPUT : Resume Input processing
  *                           JPEG_PAUSE_RESUME_OUTPUT: Resume Output processing
  *                           JPEG_PAUSE_RESUME_INPUT_OUTPUT: Resume Input and Output processing
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_JPEG_Resume(JPEG_HandleTypeDef *hjpeg, uint32_t XferSelection)
{
  uint32_t mask = 0;
  uint32_t xfrSize;

  assert_param(IS_JPEG_PAUSE_RESUME_STATE(XferSelection));

  if ((hjpeg->Context & (JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT)) == 0UL)
  {
    /* if nothing paused to resume return error*/
    return HAL_ERROR;
  }

  if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
  {

    if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
    {
      hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT);
      /*if the MDMA In is triggred with JPEG In FIFO Threshold flag
        then MDMA In buffer size is 32 bytes

        else (MDMA In is triggred with JPEG In FIFO not full flag)
        then MDMA In buffer size is 4 bytes
        */
      xfrSize = hjpeg->hdmain->Init.BufferTransferLength;

      if (xfrSize == 0UL)
      {
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
        hjpeg->State = HAL_JPEG_STATE_ERROR;
        return HAL_ERROR;
      }
      /*MDMA transfer size (BNDTR) must be a multiple of MDMA buffer size (TLEN)*/
      hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % xfrSize);


      if (hjpeg->InDataLength > 0UL)
      {
        /* Start DMA FIFO In transfer */
        if (HAL_MDMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR,
                              hjpeg->InDataLength, 1) != HAL_OK)
        {
          hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
          hjpeg->State = HAL_JPEG_STATE_ERROR;
          return HAL_ERROR;
        }
      }
    }
    if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
    {
      hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT);

      if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL)
      {
        JPEG_DMA_PollResidualData(hjpeg);
      }
      else
      {
        /*if the MDMA Out is triggred with JPEG Out FIFO Threshold flag
          then MDMA out buffer size is 32 bytes
          else (MDMA Out is triggred with JPEG Out FIFO not empty flag)
          then MDMA buffer size is 4 bytes
          */
        xfrSize = hjpeg->hdmaout->Init.BufferTransferLength;

        if (xfrSize == 0UL)
        {
          hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
          hjpeg->State = HAL_JPEG_STATE_ERROR;
          return HAL_ERROR;
        }
        /*MDMA transfer size (BNDTR) must be a multiple of MDMA buffer size (TLEN)*/
        hjpeg->OutDataLength = hjpeg->OutDataLength - (hjpeg->OutDataLength % xfrSize);

        /* Start DMA FIFO Out transfer */
        if (HAL_MDMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr,
                              hjpeg->OutDataLength, 1) != HAL_OK)
        {
          hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
          hjpeg->State = HAL_JPEG_STATE_ERROR;
          return HAL_ERROR;
        }
      }

    }

  }
  else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
  {
    if ((XferSelection & JPEG_PAUSE_RESUME_INPUT) == JPEG_PAUSE_RESUME_INPUT)
    {
      hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_INPUT);
      mask |= (JPEG_IT_IFT | JPEG_IT_IFNF);
    }
    if ((XferSelection & JPEG_PAUSE_RESUME_OUTPUT) == JPEG_PAUSE_RESUME_OUTPUT)
    {
      hjpeg->Context &= (~JPEG_CONTEXT_PAUSE_OUTPUT);
      mask |= (JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC);
    }
    __HAL_JPEG_ENABLE_IT(hjpeg, mask);

  }
  else
  {
    /* Nothing to do */
  }

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Config Encoding/Decoding Input Buffer.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module.
  * @param  pNewInputBuffer Pointer to the new input data buffer
  * @param  InDataLength Size in bytes of the new Input data buffer
  * @retval HAL status
  */
void HAL_JPEG_ConfigInputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewInputBuffer, uint32_t InDataLength)
{
  hjpeg->pJpegInBuffPtr =  pNewInputBuffer;
  hjpeg->InDataLength = InDataLength;
}

/**
  * @brief  Config Encoding/Decoding Output Buffer.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module.
  * @param  pNewOutputBuffer Pointer to the new output data buffer
  * @param  OutDataLength Size in bytes of the new Output data buffer
  * @retval HAL status
  */
void HAL_JPEG_ConfigOutputBuffer(JPEG_HandleTypeDef *hjpeg, uint8_t *pNewOutputBuffer, uint32_t OutDataLength)
{
  hjpeg->pJpegOutBuffPtr = pNewOutputBuffer;
  hjpeg->OutDataLength = OutDataLength;
}

/**
  * @brief  Aborts the JPEG Encoding/Decoding.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_JPEG_Abort(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t tickstart;
  uint32_t tmpContext;
  tmpContext = hjpeg->Context;

  /*Reset the Context operation and method*/
  hjpeg->Context &= ~(JPEG_CONTEXT_OPERATION_MASK | JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA);

  if ((tmpContext & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
  {
    /* Stop the DMA In/out Xfer*/
    if (HAL_MDMA_Abort(hjpeg->hdmaout) != HAL_OK)
    {
      if (hjpeg->hdmaout->ErrorCode == HAL_MDMA_ERROR_TIMEOUT)
      {
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
      }
    }
    if (HAL_MDMA_Abort(hjpeg->hdmain) != HAL_OK)
    {
      if (hjpeg->hdmain->ErrorCode == HAL_MDMA_ERROR_TIMEOUT)
      {
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
      }
    }

  }

  /* Stop the JPEG encoding/decoding process*/
  hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

  /* Get tick */
  tickstart = HAL_GetTick();

  /* Check if the JPEG Codec is effectively disabled */
  while (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_COF) != 0UL)
  {
    /* Check for the Timeout */
    if ((HAL_GetTick() - tickstart) > JPEG_TIMEOUT_VALUE)
    {
      /* Update error code */
      hjpeg->ErrorCode |= HAL_JPEG_ERROR_TIMEOUT;

      /* Change the DMA state */
      hjpeg->State = HAL_JPEG_STATE_ERROR;
      break;
    }
  }

  /* Disable All Interrupts */
  __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);


  /* Flush input and output FIFOs*/
  hjpeg->Instance->CR |= JPEG_CR_IFF;
  hjpeg->Instance->CR |= JPEG_CR_OFF;

  /* Clear all flags */
  __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);

  /* Reset JpegInCount and JpegOutCount */
  hjpeg->JpegInCount = 0;
  hjpeg->JpegOutCount = 0;

  /*Reset the Context Pause*/
  hjpeg->Context &= ~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT);

  /* Change the DMA state*/
  if (hjpeg->ErrorCode != HAL_JPEG_ERROR_NONE)
  {
    hjpeg->State = HAL_JPEG_STATE_ERROR;
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);
    /* Return function status */
    return HAL_ERROR;
  }
  else
  {
    hjpeg->State = HAL_JPEG_STATE_READY;
    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);
    /* Return function status */
    return HAL_OK;
  }

}


/**
  * @}
  */

/** @defgroup JPEG_Exported_Functions_Group4 JPEG Decode/Encode callback functions
  *  @brief   JPEG process callback functions.
  *
@verbatim
  ==============================================================================
              #####  JPEG Decode and Encode callback functions  #####
  ==============================================================================
    [..]  This section provides callback functions:
      (+) HAL_JPEG_InfoReadyCallback()  : Decoding JPEG Info ready callback
      (+) HAL_JPEG_EncodeCpltCallback() : Encoding complete callback.
      (+) HAL_JPEG_DecodeCpltCallback() : Decoding complete callback.
      (+) HAL_JPEG_ErrorCallback()      : JPEG error callback.
      (+) HAL_JPEG_GetDataCallback()    : Get New Data chunk callback.
      (+) HAL_JPEG_DataReadyCallback()  : Decoded/Encoded Data ready  callback.

@endverbatim
  * @{
  */

/**
  * @brief  Decoding JPEG Info ready callback.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pInfo pointer to a JPEG_ConfTypeDef structure that contains
  *         The JPEG decoded header information
  * @retval None
  */
__weak void HAL_JPEG_InfoReadyCallback(JPEG_HandleTypeDef *hjpeg, JPEG_ConfTypeDef *pInfo)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);
  UNUSED(pInfo);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_HeaderParsingCpltCallback could be implemented in the user file
   */
}

/**
  * @brief  Encoding complete callback.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
__weak void HAL_JPEG_EncodeCpltCallback(JPEG_HandleTypeDef *hjpeg)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_EncodeCpltCallback could be implemented in the user file
   */
}

/**
  * @brief  Decoding complete callback.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
__weak void HAL_JPEG_DecodeCpltCallback(JPEG_HandleTypeDef *hjpeg)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_EncodeCpltCallback could be implemented in the user file
   */
}

/**
  * @brief  JPEG error callback.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
__weak void HAL_JPEG_ErrorCallback(JPEG_HandleTypeDef *hjpeg)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_ErrorCallback could be implemented in the user file
   */
}

/**
  * @brief  Get New Data chunk callback.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  NbDecodedData Number of consummed data in the previous chunk in bytes
  * @retval None
  */
__weak void HAL_JPEG_GetDataCallback(JPEG_HandleTypeDef *hjpeg, uint32_t NbDecodedData)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);
  UNUSED(NbDecodedData);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_GetDataCallback could be implemented in the user file
   */
}

/**
  * @brief  Decoded/Encoded Data ready  callback.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  pDataOut pointer to the output data buffer
  * @param  OutDataLength number in bytes of data available in the specified output buffer
  * @retval None
  */
__weak void HAL_JPEG_DataReadyCallback(JPEG_HandleTypeDef *hjpeg, uint8_t *pDataOut, uint32_t OutDataLength)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hjpeg);
  UNUSED(pDataOut);
  UNUSED(OutDataLength);

  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_JPEG_DataReadyCallback could be implemented in the user file
   */
}

/**
  * @}
  */


/** @defgroup JPEG_Exported_Functions_Group5 JPEG IRQ handler management
  *  @brief   JPEG IRQ handler.
  *
@verbatim
  ==============================================================================
                ##### JPEG IRQ handler management #####
  ==============================================================================
    [..]  This section provides JPEG IRQ handler function.
      (+) HAL_JPEG_IRQHandler()  : handles JPEG interrupt request

@endverbatim
  * @{
  */

/**
  * @brief  This function handles JPEG interrupt request.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
void HAL_JPEG_IRQHandler(JPEG_HandleTypeDef *hjpeg)
{
  switch (hjpeg->State)
  {
    case HAL_JPEG_STATE_BUSY_ENCODING:
    case HAL_JPEG_STATE_BUSY_DECODING:
      /* continue JPEG data encoding/Decoding*/
      /* JPEG data processing : In/Out FIFO transfer*/
      if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
      {
        (void) JPEG_Process(hjpeg);
      }
      else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
      {
        JPEG_DMA_ContinueProcess(hjpeg);
      }
      else
      {
        /* Nothing to do */
      }
      break;

    default:
      break;
  }
}

/**
  * @}
  */

/** @defgroup JPEG_Exported_Functions_Group6 Peripheral State functions
  *  @brief   Peripheral State functions.
  *
@verbatim
  ==============================================================================
                    ##### Peripheral State and Error functions #####
  ==============================================================================
    [..]  This section provides JPEG State and Errors function.
      (+) HAL_JPEG_GetState()  : permits to get in run-time the JPEG state.
      (+) HAL_JPEG_GetError()  : Returns the JPEG error code if any.

@endverbatim
  * @{
  */

/**
  * @brief  Returns the JPEG state.
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval JPEG state
  */
HAL_JPEG_STATETypeDef HAL_JPEG_GetState(JPEG_HandleTypeDef *hjpeg)
{
  return hjpeg->State;
}

/**
  * @brief  Return the JPEG error code
  * @param  hjpeg  pointer to a JPEG_HandleTypeDef structure that contains
  *              the configuration information for the specified JPEG.
  * @retval JPEG Error Code
  */
uint32_t HAL_JPEG_GetError(JPEG_HandleTypeDef *hjpeg)
{
  return hjpeg->ErrorCode;
}

/**
  * @}
  */

/**
  * @}
  */


/** @addtogroup JPEG_Private_Functions
  * @{
  */

/**
  * @brief  Generates Huffman sizes/Codes Table from Bits/vals Table
  * @param  Bits pointer to bits table
  * @param  Huffsize pointer to sizes table
  * @param  Huffcode pointer to codes table
  * @param  LastK pointer to last Coeff (table dimension)
  * @retval HAL status
  */
static HAL_StatusTypeDef JPEG_Bits_To_SizeCodes(uint8_t *Bits, uint8_t *Huffsize, uint32_t *Huffcode, uint32_t *LastK)
{
  uint32_t i;
  uint32_t p;
  uint32_t l;
  uint32_t code;
  uint32_t si;

  /* Figure C.1: Generation of table of Huffman code sizes */
  p = 0;
  for (l = 0; l < 16UL; l++)
  {
    i = (uint32_t)Bits[l];
    if ((p + i) > 256UL)
    {
      /* check for table overflow */
      return HAL_ERROR;
    }
    while (i != 0UL)
    {
      Huffsize[p] = (uint8_t) l + 1U;
      p++;
      i--;
    }
  }
  Huffsize[p] = 0;
  *LastK = p;

  /* Figure C.2: Generation of table of Huffman codes */
  code = 0;
  si = Huffsize[0];
  p = 0;
  while (Huffsize[p] != 0U)
  {
    while (((uint32_t) Huffsize[p]) == si)
    {
      Huffcode[p] = code;
      p++;
      code++;
    }
    /* code must fit in "size" bits (si), no code is allowed to be all ones*/
    if(si > 31UL)
    {
      return HAL_ERROR;
    }
    if (((uint32_t) code) >= (((uint32_t) 1) << si))
    {
      return HAL_ERROR;
    }
    code <<= 1;
    si++;
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Transform a Bits/Vals AC Huffman table to sizes/Codes huffman Table
  *         that can programmed to the JPEG encoder registers
  * @param  AC_BitsValsTable pointer to AC huffman bits/vals table
  * @param  AC_SizeCodesTable pointer to AC huffman Sizes/Codes table
  * @retval HAL status
  */
static HAL_StatusTypeDef JPEG_ACHuff_BitsVals_To_SizeCodes(JPEG_ACHuffTableTypeDef *AC_BitsValsTable,
                                                           JPEG_AC_HuffCodeTableTypeDef *AC_SizeCodesTable)
{
  HAL_StatusTypeDef error;
  uint8_t huffsize[257];
  uint32_t huffcode[257];
  uint32_t k;
  uint32_t l, lsb, msb;
  uint32_t lastK;

  error = JPEG_Bits_To_SizeCodes(AC_BitsValsTable->Bits, huffsize, huffcode, &lastK);
  if (error != HAL_OK)
  {
    return  error;
  }

  /* Figure C.3: Ordering procedure for encoding procedure code tables */
  k = 0;

  while (k < lastK)
  {
    l = AC_BitsValsTable->HuffVal[k];
    if (l == 0UL)
    {
      l = 160; /*l = 0x00 EOB code*/
    }
    else if (l == 0xF0UL) /* l = 0xF0 ZRL code*/
    {
      l = 161;
    }
    else
    {
      msb = (l & 0xF0UL) >> 4;
      lsb = (l & 0x0FUL);
      l = (msb * 10UL) + lsb - 1UL;
    }
    if (l >= JPEG_AC_HUFF_TABLE_SIZE)
    {
      return HAL_ERROR; /* Huffman Table overflow error*/
    }
    else
    {
      AC_SizeCodesTable->HuffmanCode[l] = huffcode[k];
      AC_SizeCodesTable->CodeLength[l] = huffsize[k] - 1U;
      k++;
    }
  }

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Transform a Bits/Vals DC Huffman table to sizes/Codes huffman Table
  *         that can programmed to the JPEG encoder registers
  * @param  DC_BitsValsTable pointer to DC huffman bits/vals table
  * @param  DC_SizeCodesTable pointer to DC huffman Sizes/Codes table
  * @retval HAL status
  */
static HAL_StatusTypeDef JPEG_DCHuff_BitsVals_To_SizeCodes(JPEG_DCHuffTableTypeDef *DC_BitsValsTable,
                                                           JPEG_DC_HuffCodeTableTypeDef *DC_SizeCodesTable)
{
  HAL_StatusTypeDef error;

  uint32_t k;
  uint32_t l;
  uint32_t lastK;
  uint8_t huffsize[257];
  uint32_t huffcode[257];
  error = JPEG_Bits_To_SizeCodes(DC_BitsValsTable->Bits, huffsize, huffcode, &lastK);
  if (error != HAL_OK)
  {
    return  error;
  }
  /* Figure C.3: ordering procedure for encoding procedure code tables */
  k = 0;

  while (k < lastK)
  {
    l = DC_BitsValsTable->HuffVal[k];
    if (l >= JPEG_DC_HUFF_TABLE_SIZE)
    {
      return HAL_ERROR; /* Huffman Table overflow error*/
    }
    else
    {
      DC_SizeCodesTable->HuffmanCode[l] = huffcode[k];
      DC_SizeCodesTable->CodeLength[l] = huffsize[k] - 1U;
      k++;
    }
  }

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Set the JPEG register with an DC huffman table at the given DC table address
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  HuffTableDC pointer to DC huffman table
  * @param  DCTableAddress Encoder DC huffman table address it could be HUFFENC_DC0 or HUFFENC_DC1.
  * @retval HAL status
  */
static HAL_StatusTypeDef JPEG_Set_HuffDC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_DCHuffTableTypeDef *HuffTableDC,
                                             const __IO uint32_t *DCTableAddress)
{
  HAL_StatusTypeDef error;
  JPEG_DC_HuffCodeTableTypeDef dcSizeCodesTable;
  uint32_t i;
  uint32_t lsb;
  uint32_t msb;
  __IO uint32_t *address, *addressDef;

  if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC0))
  {
    address = (hjpeg->Instance->HUFFENC_DC0 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL));
  }
  else if (DCTableAddress == (hjpeg->Instance->HUFFENC_DC1))
  {
    address = (hjpeg->Instance->HUFFENC_DC1 + (JPEG_DC_HUFF_TABLE_SIZE / 2UL));
  }
  else
  {
    return HAL_ERROR;
  }

  if (HuffTableDC != NULL)
  {
    error = JPEG_DCHuff_BitsVals_To_SizeCodes(HuffTableDC, &dcSizeCodesTable);
    if (error != HAL_OK)
    {
      return  error;
    }
    addressDef = address;
    *addressDef = 0x0FFF0FFF;
    addressDef++;
    *addressDef = 0x0FFF0FFF;

    i = JPEG_DC_HUFF_TABLE_SIZE;
    while (i > 1UL)
    {
      i--;
      address --;
      msb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | ((uint32_t)dcSizeCodesTable.HuffmanCode[i] &
                                                                                   0xFFUL);
      i--;
      lsb = ((uint32_t)(((uint32_t)dcSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | ((uint32_t)dcSizeCodesTable.HuffmanCode[i] &
                                                                                   0xFFUL);

      *address = lsb | (msb << 16);
    }
  }

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Set the JPEG register with an AC huffman table at the given AC table address
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  HuffTableAC pointer to AC huffman table
  * @param  ACTableAddress Encoder AC huffman table address it could be HUFFENC_AC0 or HUFFENC_AC1.
  * @retval HAL status
  */
static HAL_StatusTypeDef JPEG_Set_HuffAC_Mem(JPEG_HandleTypeDef *hjpeg, JPEG_ACHuffTableTypeDef *HuffTableAC,
                                             const __IO uint32_t *ACTableAddress)
{
  HAL_StatusTypeDef error;
  JPEG_AC_HuffCodeTableTypeDef acSizeCodesTable;
  uint32_t i, lsb, msb;
  __IO uint32_t *address, *addressDef;

  if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC0))
  {
    address = (hjpeg->Instance->HUFFENC_AC0 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL));
  }
  else if (ACTableAddress == (hjpeg->Instance->HUFFENC_AC1))
  {
    address = (hjpeg->Instance->HUFFENC_AC1 + (JPEG_AC_HUFF_TABLE_SIZE / 2UL));
  }
  else
  {
    return HAL_ERROR;
  }

  if (HuffTableAC != NULL)
  {
    error = JPEG_ACHuff_BitsVals_To_SizeCodes(HuffTableAC, &acSizeCodesTable);
    if (error != HAL_OK)
    {
      return  error;
    }
    /* Default values settings: 162:167 FFFh , 168:175 FD0h_FD7h */
    /* Locations 162:175 of each AC table contain information used internally by the core */

    addressDef = address;
    for (i = 0; i < 3UL; i++)
    {
      *addressDef = 0x0FFF0FFF;
      addressDef++;
    }
    *addressDef = 0x0FD10FD0;
    addressDef++;
    *addressDef = 0x0FD30FD2;
    addressDef++;
    *addressDef = 0x0FD50FD4;
    addressDef++;
    *addressDef = 0x0FD70FD6;
    /* end of Locations 162:175  */


    i = JPEG_AC_HUFF_TABLE_SIZE;
    while (i > 1UL)
    {
      i--;
      address--;
      msb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | ((uint32_t)acSizeCodesTable.HuffmanCode[i] &
                                                                                   0xFFUL);
      i--;
      lsb = ((uint32_t)(((uint32_t)acSizeCodesTable.CodeLength[i] & 0xFU) << 8)) | ((uint32_t)acSizeCodesTable.HuffmanCode[i] &
                                                                                   0xFFUL);

      *address = lsb | (msb << 16);
    }
  }

  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Configure the JPEG encoder register huffman tables to used during
  *         the encdoing operation
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
static HAL_StatusTypeDef JPEG_Set_HuffEnc_Mem(JPEG_HandleTypeDef *hjpeg)
{
  HAL_StatusTypeDef error;

  JPEG_Set_Huff_DHTMem(hjpeg);
  error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable,
                              (hjpeg->Instance->HUFFENC_AC0));
  if (error != HAL_OK)
  {
    return  error;
  }

  error = JPEG_Set_HuffAC_Mem(hjpeg, (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable,
                              (hjpeg->Instance->HUFFENC_AC1));
  if (error != HAL_OK)
  {
    return  error;
  }

  error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable,
                              hjpeg->Instance->HUFFENC_DC0);
  if (error != HAL_OK)
  {
    return  error;
  }

  error = JPEG_Set_HuffDC_Mem(hjpeg, (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable,
                              hjpeg->Instance->HUFFENC_DC1);
  if (error != HAL_OK)
  {
    return  error;
  }
  /* Return function status */
  return HAL_OK;
}

/**
  * @brief  Configure the JPEG register huffman tables to be included in the JPEG
  *         file header (used for encoding only)
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
static void JPEG_Set_Huff_DHTMem(JPEG_HandleTypeDef *hjpeg)
{
  JPEG_ACHuffTableTypeDef *HuffTableAC0 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACLUM_HuffTable;
  JPEG_ACHuffTableTypeDef *HuffTableAC1 = (JPEG_ACHuffTableTypeDef *)(uint32_t)&JPEG_ACCHROM_HuffTable;
  JPEG_DCHuffTableTypeDef *HuffTableDC0 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCLUM_HuffTable;
  JPEG_DCHuffTableTypeDef *HuffTableDC1 = (JPEG_DCHuffTableTypeDef *)(uint32_t)&JPEG_DCCHROM_HuffTable;
  uint32_t value, index;
  __IO uint32_t *address;

  /* DC0 Huffman Table : BITS*/
  /* DC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address to DHTMEM + 3*/
  address = (hjpeg->Instance->DHTMEM + 3);
  index = 16;
  while (index > 3UL)
  {

    *address = (((uint32_t)HuffTableDC0->Bits[index - 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableDC0->Bits[index - 2UL] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableDC0->Bits[index - 3UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableDC0->Bits[index - 4UL] & 0xFFUL);
    address--;
    index -= 4UL;

  }
  /* DC0 Huffman Table : Val*/
  /* DC0 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +4 to DHTMEM + 6 */
  address = (hjpeg->Instance->DHTMEM + 6);
  index = 12;
  while (index > 3UL)
  {
    *address = (((uint32_t)HuffTableDC0->HuffVal[index - 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableDC0->HuffVal[index - 2UL] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableDC0->HuffVal[index - 3UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableDC0->HuffVal[index - 4UL] & 0xFFUL);
    address--;
    index -= 4UL;
  }

  /* AC0 Huffman Table : BITS*/
  /* AC0 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 7 to DHTMEM + 10*/
  address = (hjpeg->Instance->DHTMEM + 10UL);
  index = 16;
  while (index > 3UL)
  {

    *address = (((uint32_t)HuffTableAC0->Bits[index - 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableAC0->Bits[index - 2UL] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableAC0->Bits[index - 3UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableAC0->Bits[index - 4UL] & 0xFFUL);
    address--;
    index -= 4UL;

  }
  /* AC0 Huffman Table : Val*/
  /* AC0 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 11 to DHTMEM + 51 */
  /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 51) belong to AC0 VALS table */
  address = (hjpeg->Instance->DHTMEM + 51);
  value = *address & 0xFFFF0000U;
  value = value | (((uint32_t)HuffTableAC0->HuffVal[161] & 0xFFUL) << 8) | ((uint32_t)HuffTableAC0->HuffVal[160] & 0xFFUL);
  *address = value;

  /*continue setting 160 AC0 huffman values */
  address--; /* address = hjpeg->Instance->DHTMEM + 50*/
  index = 160;
  while (index > 3UL)
  {
    *address = (((uint32_t)HuffTableAC0->HuffVal[index - 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableAC0->HuffVal[index - 2UL] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableAC0->HuffVal[index - 3UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableAC0->HuffVal[index - 4UL] & 0xFFUL);
    address--;
    index -= 4UL;
  }

  /* DC1 Huffman Table : BITS*/
  /* DC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM + 51 base address to DHTMEM + 55*/
  /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 51) belong to DC1 Bits table */
  address = (hjpeg->Instance->DHTMEM + 51);
  value = *address & 0x0000FFFFU;
  value = value | (((uint32_t)HuffTableDC1->Bits[1] & 0xFFUL) << 24) | (((uint32_t)HuffTableDC1->Bits[0] & 0xFFUL) << 16);
  *address = value;

  /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 55) belong to DC1 Bits table */
  address = (hjpeg->Instance->DHTMEM + 55);
  value = *address & 0xFFFF0000U;
  value = value | (((uint32_t)HuffTableDC1->Bits[15] & 0xFFUL) << 8) | ((uint32_t)HuffTableDC1->Bits[14] & 0xFFUL);
  *address = value;

  /*continue setting 12 DC1 huffman Bits from DHTMEM + 54 down to DHTMEM + 52*/
  address--;
  index = 12;
  while (index > 3UL)
  {

    *address = (((uint32_t)HuffTableDC1->Bits[index + 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableDC1->Bits[index] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableDC1->Bits[index - 1UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableDC1->Bits[index - 2UL] & 0xFFUL);
    address--;
    index -= 4UL;

  }
  /* DC1 Huffman Table : Val*/
  /* DC1 VALS is a 12 Bytes table i.e 3x32bits words from DHTMEM base address +55 to DHTMEM + 58 */
  /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 55) belong to DC1 Val table */
  address = (hjpeg->Instance->DHTMEM + 55);
  value = *address & 0x0000FFFFUL;
  value = value | (((uint32_t)HuffTableDC1->HuffVal[1] & 0xFFUL) << 24) | (((uint32_t)HuffTableDC1->HuffVal[0] & 0xFFUL) <<
                                                                         16);
  *address = value;

  /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 58) belong to DC1 Val table */
  address = (hjpeg->Instance->DHTMEM + 58);
  value = *address & 0xFFFF0000UL;
  value = value | (((uint32_t)HuffTableDC1->HuffVal[11] & 0xFFUL) << 8) | ((uint32_t)HuffTableDC1->HuffVal[10] & 0xFFUL);
  *address = value;

  /*continue setting 8 DC1 huffman val from DHTMEM + 57 down to DHTMEM + 56*/
  address--;
  index = 8;
  while (index > 3UL)
  {
    *address = (((uint32_t)HuffTableDC1->HuffVal[index + 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableDC1->HuffVal[index] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableDC1->HuffVal[index - 1UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableDC1->HuffVal[index - 2UL] & 0xFFUL);
    address--;
    index -= 4UL;
  }

  /* AC1 Huffman Table : BITS*/
  /* AC1 BITS is a 16 Bytes table i.e 4x32bits words from DHTMEM base address + 58 to DHTMEM + 62*/
  /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 58) belong to AC1 Bits table */
  address = (hjpeg->Instance->DHTMEM + 58);
  value = *address & 0x0000FFFFU;
  value = value | (((uint32_t)HuffTableAC1->Bits[1] & 0xFFUL) << 24) | (((uint32_t)HuffTableAC1->Bits[0] & 0xFFUL) << 16);
  *address = value;

  /* only Byte 0 and Byte 1 of the last word (@ DHTMEM + 62) belong to Bits Val table */
  address = (hjpeg->Instance->DHTMEM + 62);
  value = *address & 0xFFFF0000U;
  value = value | (((uint32_t)HuffTableAC1->Bits[15] & 0xFFUL) << 8) | ((uint32_t)HuffTableAC1->Bits[14] & 0xFFUL);
  *address = value;

  /*continue setting 12 AC1 huffman Bits from DHTMEM + 61 down to DHTMEM + 59*/
  address--;
  index = 12;
  while (index > 3UL)
  {

    *address = (((uint32_t)HuffTableAC1->Bits[index + 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableAC1->Bits[index] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableAC1->Bits[index - 1UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableAC1->Bits[index - 2UL] & 0xFFUL);
    address--;
    index -= 4UL;

  }
  /* AC1 Huffman Table : Val*/
  /* AC1 VALS is a 162 Bytes table i.e 41x32bits words from DHTMEM base address + 62 to DHTMEM + 102 */
  /* only Byte 2 and Byte 3 of the first word (@ DHTMEM + 62) belong to AC1 VALS table */
  address = (hjpeg->Instance->DHTMEM + 62);
  value = *address & 0x0000FFFFUL;
  value = value | (((uint32_t)HuffTableAC1->HuffVal[1] & 0xFFUL) << 24) | (((uint32_t)HuffTableAC1->HuffVal[0] & 0xFFUL) <<
                                                                         16);
  *address = value;

  /*continue setting 160 AC1 huffman values from DHTMEM + 63 to DHTMEM+102 */
  address = (hjpeg->Instance->DHTMEM + 102);
  index = 160;
  while (index > 3UL)
  {
    *address = (((uint32_t)HuffTableAC1->HuffVal[index + 1UL] & 0xFFUL) << 24) |
               (((uint32_t)HuffTableAC1->HuffVal[index] & 0xFFUL) << 16) |
               (((uint32_t)HuffTableAC1->HuffVal[index - 1UL] & 0xFFUL) << 8) |
               ((uint32_t)HuffTableAC1->HuffVal[index - 2UL] & 0xFFUL);
    address--;
    index -= 4UL;
  }

}

/**
  * @brief  Configure the JPEG registers with a given quantization table
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  QTable pointer to an array of 64 bytes giving the quantization table
  * @param  QTableAddress destination quantization address in the JPEG peripheral
  *         it could be QMEM0, QMEM1, QMEM2 or QMEM3
  * @retval 0 if no error, 1 if error
  */
static uint32_t JPEG_Set_Quantization_Mem(JPEG_HandleTypeDef *hjpeg, uint8_t *QTable,
                                                    __IO uint32_t *QTableAddress)
{
  uint32_t i;
  uint32_t j;
  uint32_t quantRow;
  uint32_t quantVal;
  uint32_t ScaleFactor;
  __IO uint32_t *tableAddress;

  tableAddress = QTableAddress;

  if ((hjpeg->Conf.ImageQuality >= 50UL) && (hjpeg->Conf.ImageQuality <= 100UL))
  {
    ScaleFactor = 200UL - (hjpeg->Conf.ImageQuality * 2UL);
  }
  else if (hjpeg->Conf.ImageQuality > 0UL)
  {
    ScaleFactor = ((uint32_t) 5000) / ((uint32_t) hjpeg->Conf.ImageQuality);
  }
  else
  {
    return 1UL;
  }

  /*Quantization_table = (Standard_quanization_table * ScaleFactor + 50) / 100*/
  i = 0;
  while (i < (JPEG_QUANT_TABLE_SIZE - 3UL))
  {
    quantRow = 0;
    for (j = 0; j < 4UL; j++)
    {
      /* Note that the quantization coefficients must be specified in the table in zigzag order */
      quantVal = ((((uint32_t) QTable[JPEG_ZIGZAG_ORDER[i + j]]) * ScaleFactor) + 50UL) / 100UL;

      if (quantVal == 0UL)
      {
        quantVal = 1UL;
      }
      else if (quantVal > 255UL)
      {
        quantVal = 255UL;
      }
      else
      {
        /* Nothing to do, keep same value of quantVal */
      }

      quantRow |= ((quantVal & 0xFFUL) << (8UL * j));
    }

    i += 4UL;
    *tableAddress = quantRow;
    tableAddress ++;
  }

  /* Return function status */
  return 0UL;
}

/**
  * @brief  Configure the JPEG registers for YCbCr color space
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
static void JPEG_SetColorYCBCR(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t ySamplingH;
  uint32_t ySamplingV;
  uint32_t yblockNb;

  /*Set Number of color components to 3*/
  hjpeg->Instance->CONFR1 &=  ~JPEG_CONFR1_NF;
  hjpeg->Instance->CONFR1 |=  JPEG_CONFR1_NF_1;

  /* compute MCU block size and Y, Cb ,Cr sampling factors*/
  if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING)
  {
    ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
    ySamplingV  = JPEG_CONFR4_VSF_1;   /* Vs = 2*/

    yblockNb  = 0x30; /* 4 blocks of 8x8*/
  }
  else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING)
  {
    ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
    ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/

    yblockNb  = 0x10; /* 2 blocks of 8x8*/
  }
  else /*JPEG_444_SUBSAMPLING and default*/
  {
    ySamplingH  = JPEG_CONFR4_HSF_0;   /* Hs = 1*/
    ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/

    yblockNb  = 0; /* 1 block of 8x8*/
  }

  hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS);
  hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF_1 | JPEG_CONFR1_NS_1);

  /*Reset CONFR4 register*/
  hjpeg->Instance->CONFR4 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 0*/
  hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB));

  /*Reset CONFR5 register*/
  hjpeg->Instance->CONFR5 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 1*/
  hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0 | JPEG_CONFR5_QT_0 | JPEG_CONFR5_HA | JPEG_CONFR5_HD);

  /*Reset CONFR6 register*/
  hjpeg->Instance->CONFR6 =  0;
  /*Set Horizental and Vertical  sampling factor and number of blocks for component 2*/
  /* In YCBCR , by default, both chrominance components (component 1 and component 2) use the same Quantization table (table 1) */
  /* In YCBCR , both chrominance components (component 1 and component 2) use the same Huffman tables (table 1) */
  hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0 | JPEG_CONFR6_QT_0 | JPEG_CONFR6_HA | JPEG_CONFR6_HD);

}

/**
  * @brief  Configure the JPEG registers for GrayScale color space
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
static void JPEG_SetColorGrayScale(JPEG_HandleTypeDef *hjpeg)
{
  /*Set Number of color components to 1*/
  hjpeg->Instance->CONFR1 &= ~(JPEG_CONFR1_NF | JPEG_CONFR1_NS);

  /*in GrayScale use 1 single Quantization table (Table 0)*/
  /*in GrayScale use only one couple of AC/DC huffman table (table 0)*/

  /*Reset CONFR4 register*/
  hjpeg->Instance->CONFR4 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 0*/
  hjpeg->Instance->CONFR4 |=  JPEG_CONFR4_HSF_0 | JPEG_CONFR4_VSF_0 ;
}

/**
  * @brief  Configure the JPEG registers for CMYK color space
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
static void JPEG_SetColorCMYK(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t ySamplingH;
  uint32_t ySamplingV;
  uint32_t yblockNb;

  /*Set Number of color components to 4*/
  hjpeg->Instance->CONFR1 |= (JPEG_CONFR1_NF | JPEG_CONFR1_NS);

  /* compute MCU block size and Y, Cb ,Cr sampling factors*/
  if (hjpeg->Conf.ChromaSubsampling == JPEG_420_SUBSAMPLING)
  {
    ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
    ySamplingV  = JPEG_CONFR4_VSF_1;   /* Vs = 2*/

    yblockNb  = 0x30; /* 4 blocks of 8x8*/
  }
  else if (hjpeg->Conf.ChromaSubsampling == JPEG_422_SUBSAMPLING)
  {
    ySamplingH  = JPEG_CONFR4_HSF_1;   /* Hs = 2*/
    ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/

    yblockNb  = 0x10; /* 2 blocks of 8x8*/
  }
  else /*JPEG_444_SUBSAMPLING and default*/
  {
    ySamplingH  = JPEG_CONFR4_HSF_0;   /* Hs = 1*/
    ySamplingV  = JPEG_CONFR4_VSF_0;   /* Vs = 1*/

    yblockNb  = 0; /* 1 block of 8x8*/
  }

  /*Reset CONFR4 register*/
  hjpeg->Instance->CONFR4 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 0*/
  hjpeg->Instance->CONFR4 |= (ySamplingH | ySamplingV | (yblockNb & JPEG_CONFR4_NB));

  /*Reset CONFR5 register*/
  hjpeg->Instance->CONFR5 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 1*/
  hjpeg->Instance->CONFR5 |= (JPEG_CONFR5_HSF_0 | JPEG_CONFR5_VSF_0);

  /*Reset CONFR6 register*/
  hjpeg->Instance->CONFR6 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 2*/
  hjpeg->Instance->CONFR6 |= (JPEG_CONFR6_HSF_0 | JPEG_CONFR6_VSF_0);

  /*Reset CONFR7 register*/
  hjpeg->Instance->CONFR7 =  0;
  /*Set Horizental and Vertical  sampling factor , number of blocks , Quantization table and Huffman AC/DC tables for component 3*/
  hjpeg->Instance->CONFR7 |= (JPEG_CONFR7_HSF_0 | JPEG_CONFR7_VSF_0);
}

/**
  * @brief  Init the JPEG encoding/decoding process in case of Polling or Interrupt and DMA
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None
  */
static void JPEG_Init_Process(JPEG_HandleTypeDef *hjpeg)
{
  /*Reset pause*/
  hjpeg->Context &= (~(JPEG_CONTEXT_PAUSE_INPUT | JPEG_CONTEXT_PAUSE_OUTPUT));

  if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
  {
    /*Set JPEG Codec to Decoding mode */
    hjpeg->Instance->CONFR1 |= JPEG_CONFR1_DE;
  }
  else /* JPEG_CONTEXT_ENCODE */
  {
    /*Set JPEG Codec to Encoding mode */
    hjpeg->Instance->CONFR1 &= ~JPEG_CONFR1_DE;
  }

  /*Stop JPEG processing */
  hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

  /* Disable All Interrupts */
  __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);

  /* Flush input and output FIFOs*/
  hjpeg->Instance->CR |= JPEG_CR_IFF;
  hjpeg->Instance->CR |= JPEG_CR_OFF;

  /* Clear all flags */
  __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);

  /*Start Encoding/Decoding*/
  hjpeg->Instance->CONFR0 |=  JPEG_CONFR0_START;

  if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
  {
    /*Enable IN/OUT, end of Conversation, and end of header parsing interruptions*/
    __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_IFT | JPEG_IT_IFNF | JPEG_IT_OFT | JPEG_IT_OFNE | JPEG_IT_EOC | JPEG_IT_HPD);
  }
  else if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_DMA)
  {
    /*Enable End Of Conversation, and End Of Header parsing interruptions*/
    __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD);

  }
  else
  {
    /* Nothing to do */
  }
}

/**
  * @brief  JPEG encoding/decoding process in case of Polling or Interrupt
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval JPEG_PROCESS_DONE if the process has ends else JPEG_PROCESS_ONGOING
  */
static uint32_t JPEG_Process(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t tmpContext;

  /*End of header processing flag */
  if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
  {
    if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL)
    {
      /*Call Header parsing complete callback */
      (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf);
      /* Reset the ImageQuality */
      hjpeg->Conf.ImageQuality = 0;
      /* Note : the image quality is only available at the end of the decoding operation */
      /* at the current stage the calculated image quality is not correct so reset it */

      /*Call Info Ready callback */
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf);
#else
      HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD);

      /* Clear header processing done flag */
      __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF);
    }
  }

  /*Input FIFO status handling*/
  if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_INPUT) == 0UL)
  {
    if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFTF) != 0UL)
    {
      /*Input FIFO threshold flag */
      /*JPEG_FIFO_TH_SIZE words can be written in */
      JPEG_ReadInputData(hjpeg, JPEG_FIFO_TH_SIZE);
    }
    else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_IFNFF) != 0UL)
    {
      /*Input FIFO Not Full flag */
      /*32-bit value can be written in */
      JPEG_ReadInputData(hjpeg, 1);
    }
    else
    {
      /* Nothing to do */
    }
  }


  /*Output FIFO flag handling*/
  if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
  {
    if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFTF) != 0UL)
    {
      /*Output FIFO threshold flag */
      /*JPEG_FIFO_TH_SIZE words can be read out */
      JPEG_StoreOutputData(hjpeg, JPEG_FIFO_TH_SIZE);
    }
    else if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL)
    {
      /*Output FIFO Not Empty flag */
      /*32-bit value can be read out */
      JPEG_StoreOutputData(hjpeg, 1);
    }
    else
    {
      /* Nothing to do */
    }
  }

  /*End of Conversion handling :i.e EOC flag is high and OFTF low and OFNEF low*/
  if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF | JPEG_FLAG_OFTF | JPEG_FLAG_OFNEF) == JPEG_FLAG_EOCF)
  {
    /*Stop Encoding/Decoding*/
    hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

    if ((hjpeg->Context & JPEG_CONTEXT_METHOD_MASK) == JPEG_CONTEXT_IT)
    {
      /* Disable All Interrupts */
      __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);
    }

    /* Clear all flags */
    __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);

    /*Call End of conversion callback */
    if (hjpeg->JpegOutCount > 0UL)
    {
      /*Output Buffer is not empty, call DecodedDataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      hjpeg->JpegOutCount = 0;
    }

    /*Reset Context Operation*/
    tmpContext = hjpeg->Context;
    /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/
    hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES);

    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_READY;

    /*Call End of Encoding/Decoding callback */
    if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
    {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DecodeCpltCallback(hjpeg);
#else
      HAL_JPEG_DecodeCpltCallback(hjpeg);
#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/
    }
    else /* JPEG_CONTEXT_ENCODE */
    {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->EncodeCpltCallback(hjpeg);
#else
      HAL_JPEG_EncodeCpltCallback(hjpeg);
#endif
    }

    return JPEG_PROCESS_DONE;
  }


  return JPEG_PROCESS_ONGOING;
}

/**
  * @brief  Store some output data from the JPEG peripheral to the output buffer.
  *         This function is used when the JPEG peripheral has new data to output
  *         in case of Polling or Interrupt process
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  nbOutputWords Number of output words (of 32 bits) ready from the JPEG peripheral
  * @retval None
  */
static void JPEG_StoreOutputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbOutputWords)
{
  uint32_t index;
  uint32_t nb_words;
  uint32_t nb_bytes;
  uint32_t dataword;

  if (hjpeg->OutDataLength >= (hjpeg->JpegOutCount + (nbOutputWords * 4UL)))
  {
    for (index = 0; index < nbOutputWords; index++)
    {
      /*Transfer 32 bits from the JPEG output FIFO*/
      dataword = hjpeg->Instance->DOR;
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL);
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8);
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16);
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24);
      hjpeg->JpegOutCount += 4UL;
    }
    if (hjpeg->OutDataLength == hjpeg->JpegOutCount)
    {
      /*Output Buffer is full, call DecodedDataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/
      hjpeg->JpegOutCount = 0;
    }
  }
  else if (hjpeg->OutDataLength > hjpeg->JpegOutCount)
  {
    nb_words = (hjpeg->OutDataLength - hjpeg->JpegOutCount) / 4UL;
    for (index = 0; index < nb_words; index++)
    {
      /*Transfer 32 bits from the JPEG output FIFO*/
      dataword = hjpeg->Instance->DOR;
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataword & 0x000000FFUL);
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataword & 0x0000FF00UL) >> 8);
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataword & 0x00FF0000UL) >> 16);
      hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataword & 0xFF000000UL) >> 24);
      hjpeg->JpegOutCount += 4UL;
    }
    if (hjpeg->OutDataLength == hjpeg->JpegOutCount)
    {
      /*Output Buffer is full, call DecodedDataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
      hjpeg->JpegOutCount = 0;
    }
    else
    {
      nb_bytes = hjpeg->OutDataLength - hjpeg->JpegOutCount;
      dataword = hjpeg->Instance->DOR;
      for (index = 0; index < nb_bytes; index++)
      {
        hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * (index & 0x3UL))) & 0xFFUL);
        hjpeg->JpegOutCount++;
      }
      /*Output Buffer is full, call DecodedDataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      hjpeg->JpegOutCount = 0;

      nb_bytes = 4UL - nb_bytes;
      for (index = nb_bytes; index < 4UL; index++)
      {
        hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)((dataword >> (8UL * index)) & 0xFFUL);
        hjpeg->JpegOutCount++;
      }
    }
  }
  else
  {
    /* Nothing to do */
  }
}

/**
  * @brief  Read some input Data from the input buffer.
  *         This function is used when the JPEG peripheral needs new data
  *         in case of Polling or Interrupt process
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @param  nbRequestWords Number of input words (of 32 bits) that the JPE peripheral request
  * @retval None
  */
static void JPEG_ReadInputData(JPEG_HandleTypeDef *hjpeg, uint32_t nbRequestWords)
{
  uint32_t nb_bytes = 0;
  uint32_t nb_words;
  uint32_t index;
  uint32_t dataword;
  uint32_t input_count;

  if ((hjpeg->InDataLength == 0UL) || (nbRequestWords == 0UL))
  {
    /* No more Input data : nothing to do*/
    (void) HAL_JPEG_Pause(hjpeg, JPEG_PAUSE_RESUME_INPUT);
  }
  else if (hjpeg->InDataLength > hjpeg->JpegInCount)
  {
    nb_bytes = hjpeg->InDataLength - hjpeg->JpegInCount;
  }
  else if (hjpeg->InDataLength == hjpeg->JpegInCount)
  {
    /*Call HAL_JPEG_GetDataCallback to get new data */
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
    hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount);
#else
    HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount);
#endif /*USE_HAL_JPEG_REGISTER_CALLBACKS*/

    if (hjpeg->InDataLength > 4UL)
    {
      hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % 4UL);
    }
    hjpeg->JpegInCount = 0;
    nb_bytes = hjpeg->InDataLength;
  }
  else
  {
    /* Nothing to do */
  }
  if (((hjpeg->Context &  JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (nb_bytes > 0UL))
  {
    nb_words = nb_bytes / 4UL;
    if (nb_words >= nbRequestWords)
    {
      for (index = 0; index < nbRequestWords; index++)
      {
        input_count = hjpeg->JpegInCount;
        hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \
                                (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \
                                (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \
                                (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24));

        hjpeg->JpegInCount += 4UL;
      }
    }
    else /*nb_words < nbRequestWords*/
    {
      if (nb_words > 0UL)
      {
        for (index = 0; index < nb_words; index++)
        {
          input_count = hjpeg->JpegInCount;
          hjpeg->Instance->DIR = (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count])) | \
                                  (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 1UL])) << 8) | \
                                  (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 2UL])) << 16) | \
                                  (((uint32_t)(hjpeg->pJpegInBuffPtr[input_count + 3UL])) << 24));

          hjpeg->JpegInCount += 4UL;
        }
      }
      else
      {
        /* end of file*/
        dataword = 0;
        for (index = 0; index < nb_bytes; index++)
        {
          dataword |= (uint32_t)hjpeg->pJpegInBuffPtr[hjpeg->JpegInCount] << (8UL * (index & 0x03UL));
          hjpeg->JpegInCount++;
        }
        hjpeg->Instance->DIR = dataword;
      }
    }
  }
}

/**
  * @brief  Start the JPEG DMA process (encoding/decoding)
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING
  */
static HAL_StatusTypeDef JPEG_DMA_StartProcess(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t inXfrSize, outXfrSize;

  /*if the MDMA In is triggred with JPEG In FIFO Threshold flag
      then MDMA In buffer size is 32 bytes
    else (MDMA In is triggred with JPEG In FIFO not full flag)
      then MDMA In buffer size is 4 bytes
    */
  inXfrSize = hjpeg->hdmain->Init.BufferTransferLength;

  /*if the MDMA Out is triggred with JPEG Out FIFO Threshold flag
      then MDMA out buffer size is 32 bytes
    else (MDMA Out is triggred with JPEG Out FIFO not empty flag)
      then MDMA buffer size is 4 bytes
    */
  outXfrSize = hjpeg->hdmaout->Init.BufferTransferLength;

  if ((hjpeg->InDataLength < inXfrSize) || (hjpeg->OutDataLength < outXfrSize))
  {
    return HAL_ERROR;
  }
  /* Set the JPEG MDMA In transfer complete callback */
  hjpeg->hdmain->XferCpltCallback = JPEG_MDMAInCpltCallback;
  /* Set the MDMA In error callback */
  hjpeg->hdmain->XferErrorCallback = JPEG_MDMAErrorCallback;

  /* Set the JPEG MDMA Out transfer complete callback */
  hjpeg->hdmaout->XferCpltCallback = JPEG_MDMAOutCpltCallback;
  /* Set the MDMA In error callback */
  hjpeg->hdmaout->XferErrorCallback = JPEG_MDMAErrorCallback;
  /* Set the MDMA Out Abort callback */
  hjpeg->hdmaout->XferAbortCallback = JPEG_MDMAOutAbortCallback;

  if ((inXfrSize == 0UL) || (outXfrSize == 0UL))
  {
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
    return HAL_ERROR;
  }
  /*MDMA transfer size (BNDTR) must be a multiple of MDMA buffer size (TLEN)*/
  hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % inXfrSize);

  /*MDMA transfer size (BNDTR) must be a multiple of MDMA buffer size (TLEN)*/
  hjpeg->OutDataLength = hjpeg->OutDataLength - (hjpeg->OutDataLength % outXfrSize);


  /* Start MDMA FIFO Out transfer */
  if (HAL_MDMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr,
                        hjpeg->OutDataLength, 1) != HAL_OK)
  {
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
    return HAL_ERROR;
  }
  /* Start DMA FIFO In transfer */
  if (HAL_MDMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR,
                        hjpeg->InDataLength, 1) != HAL_OK)
  {
    hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
    return HAL_ERROR;
  }

  return HAL_OK;
}

/**
  * @brief  Continue the current JPEG DMA process (encoding/decoding)
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval JPEG_PROCESS_DONE if process ends else JPEG_PROCESS_ONGOING
  */
static void JPEG_DMA_ContinueProcess(JPEG_HandleTypeDef *hjpeg)
{
  /*End of header processing flag rises*/
  if ((hjpeg->Context & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
  {
    if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_HPDF) != 0UL)
    {
      /*Call Header parsing complete callback */
      (void) HAL_JPEG_GetInfo(hjpeg, &hjpeg->Conf);

      /* Reset the ImageQuality */
      hjpeg->Conf.ImageQuality = 0;
      /* Note : the image quality is only available at the end of the decoding operation */
      /* at the current stage the calculated image quality is not correct so reset it */

      /*Call Info Ready callback */
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->InfoReadyCallback(hjpeg, &hjpeg->Conf);
#else
      HAL_JPEG_InfoReadyCallback(hjpeg, &hjpeg->Conf);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_IT_HPD);

      /* Clear header processing done flag */
      __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_HPDF);
    }
  }

  /*End of Conversion handling*/
  if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) != 0UL)
  {

    hjpeg->Context |= JPEG_CONTEXT_ENDING_DMA;

    /*Stop Encoding/Decoding*/
    hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

    __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);

    /* Clear all flags */
    __HAL_JPEG_CLEAR_FLAG(hjpeg, JPEG_FLAG_ALL);

    if (hjpeg->hdmain->State == HAL_MDMA_STATE_BUSY)
    {
      /* Stop the MDMA In Xfer*/
      (void) HAL_MDMA_Abort_IT(hjpeg->hdmain);
    }

    if (hjpeg->hdmaout->State == HAL_MDMA_STATE_BUSY)
    {
      /* Stop the MDMA out Xfer*/
      (void) HAL_MDMA_Abort_IT(hjpeg->hdmaout);
    }
    else
    {
      JPEG_DMA_EndProcess(hjpeg);
    }
  }


}

/**
  * @brief  Finalize the current JPEG DMA process (encoding/decoding)
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval JPEG_PROCESS_DONE
  */
static void JPEG_DMA_EndProcess(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t tmpContext;
  hjpeg->JpegOutCount = hjpeg->OutDataLength - (hjpeg->hdmaout->Instance->CBNDTR & MDMA_CBNDTR_BNDT);

  /*if Output Buffer is full, call HAL_JPEG_DataReadyCallback*/
  if (hjpeg->JpegOutCount == hjpeg->OutDataLength)
  {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
    hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
    HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

    hjpeg->JpegOutCount = 0;
  }

  /*Check if remaining data in the output FIFO*/
  if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL)
  {
    if (hjpeg->JpegOutCount > 0UL)
    {
      /*Output Buffer is not empty, call DecodedDataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      hjpeg->JpegOutCount = 0;
    }

    /*Stop Encoding/Decoding*/
    hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

    tmpContext = hjpeg->Context;
    /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/
    hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES);

    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_READY;

    /*Call End of Encoding/Decoding callback */
    if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
    {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DecodeCpltCallback(hjpeg);
#else
      HAL_JPEG_DecodeCpltCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
    }
    else /* JPEG_CONTEXT_ENCODE */
    {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->EncodeCpltCallback(hjpeg);
#else
      HAL_JPEG_EncodeCpltCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
    }
  }
  else if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
  {
    JPEG_DMA_PollResidualData(hjpeg);
  }
  else
  {
    /* Nothing to do */
  }

}

/**
  * @brief  Poll residual output data when DMA process (encoding/decoding)
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval None.
  */
static void JPEG_DMA_PollResidualData(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t tmpContext;
  uint32_t count;
  uint32_t dataOut;

  for (count = JPEG_FIFO_SIZE; count > 0UL; count--)
  {
    if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
    {
      if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) != 0UL)
      {
        dataOut = hjpeg->Instance->DOR;
        hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount] = (uint8_t)(dataOut & 0x000000FFUL);
        hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 1UL] = (uint8_t)((dataOut & 0x0000FF00UL) >> 8);
        hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 2UL] = (uint8_t)((dataOut & 0x00FF0000UL) >> 16);
        hjpeg->pJpegOutBuffPtr[hjpeg->JpegOutCount + 3UL] = (uint8_t)((dataOut & 0xFF000000UL) >> 24);
        hjpeg->JpegOutCount += 4UL;

        if (hjpeg->JpegOutCount == hjpeg->OutDataLength)
        {
          /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
          hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
          HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

          hjpeg->JpegOutCount = 0;
        }

      }
    }
  }

  tmpContext = hjpeg->Context;

  if ((__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_OFNEF) == 0UL) || ((tmpContext & JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL))
  {
    /*Stop Encoding/Decoding*/
    hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

    if (hjpeg->JpegOutCount > 0UL)
    {
      /*Output Buffer is not empty, call DecodedDataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      hjpeg->JpegOutCount = 0;
    }

    tmpContext = hjpeg->Context;
    /*Clear all context fields execpt JPEG_CONTEXT_CONF_ENCODING and JPEG_CONTEXT_CUSTOM_TABLES*/
    hjpeg->Context &= (JPEG_CONTEXT_CONF_ENCODING | JPEG_CONTEXT_CUSTOM_TABLES);

    /* Process Unlocked */
    __HAL_UNLOCK(hjpeg);

    /* Change the JPEG state */
    hjpeg->State = HAL_JPEG_STATE_READY;

    /*Call End of Encoding/Decoding callback */
    if ((tmpContext & JPEG_CONTEXT_OPERATION_MASK) == JPEG_CONTEXT_DECODE)
    {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DecodeCpltCallback(hjpeg);
#else
      HAL_JPEG_DecodeCpltCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
    }
    else /* JPEG_CONTEXT_ENCODE */
    {
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->EncodeCpltCallback(hjpeg);
#else
      HAL_JPEG_EncodeCpltCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
    }
  }
}

/**
  * @brief  MDMA input transfer complete callback
  * @param  hmdma pointer to a MDMA_HandleTypeDef structure.
  * @retval None
  */
static void JPEG_MDMAInCpltCallback(MDMA_HandleTypeDef *hmdma)
{
  uint32_t inXfrSize;

  JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((MDMA_HandleTypeDef *)hmdma)->Parent;

  /* Disable The JPEG IT so the MDMA Input Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */
  __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);

  /* Check if context method is DMA and we are not in ending DMA stage */
  if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) == JPEG_CONTEXT_DMA)
  {

    /*if the MDMA In is triggred with JPEG In FIFO Threshold flag
      then MDMA In buffer size is 32 bytes
      else (MDMA In is triggred with JPEG In FIFO not full flag)
      then MDMA In buffer size is 4 bytes
      */
    inXfrSize = hjpeg->hdmain->Init.BufferTransferLength;

    hjpeg->JpegInCount = hjpeg->InDataLength - (hmdma->Instance->CBNDTR & MDMA_CBNDTR_BNDT);

    /*Call HAL_JPEG_GetDataCallback to get new data */
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
    hjpeg->GetDataCallback(hjpeg, hjpeg->JpegInCount);
#else
    HAL_JPEG_GetDataCallback(hjpeg, hjpeg->JpegInCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */


    if (hjpeg->InDataLength >= inXfrSize)
    {
      if (inXfrSize == 0UL)
      {
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
        hjpeg->State = HAL_JPEG_STATE_ERROR;
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
        hjpeg->ErrorCallback(hjpeg);
#else
        HAL_JPEG_ErrorCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
        return;
      }
      /*JPEG Input MDMA transfer data number must be multiple of MDMA buffer size
        as the destination is a 32 bits register */
      hjpeg->InDataLength = hjpeg->InDataLength - (hjpeg->InDataLength % inXfrSize);

    }
    else if (hjpeg->InDataLength > 0UL)
    {
      /* Transfer the remaining Data, must be multiple of source data size (byte) and destination data size (word) */
      if ((hjpeg->InDataLength % 4UL) != 0UL)
      {
        hjpeg->InDataLength = ((hjpeg->InDataLength / 4UL) + 1UL) * 4UL;
      }
    }
    else
    {
      /* Nothing to do */
    }

    if (((hjpeg->Context &  JPEG_CONTEXT_PAUSE_INPUT) == 0UL) && (hjpeg->InDataLength > 0UL))
    {
      /* Start MDMA FIFO In transfer */
      if (HAL_MDMA_Start_IT(hjpeg->hdmain, (uint32_t)hjpeg->pJpegInBuffPtr, (uint32_t)&hjpeg->Instance->DIR,
                            hjpeg->InDataLength, 1) != HAL_OK)
      {
        hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
        hjpeg->State = HAL_JPEG_STATE_ERROR;
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
        hjpeg->ErrorCallback(hjpeg);
#else
        HAL_JPEG_ErrorCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
        return;
      }
    }

    /* JPEG Conversion still on going : Enable the JPEG IT */
    __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD);
  }
}

/**
  * @brief  MDMA output transfer complete callback
  * @param  hmdma pointer to a MDMA_HandleTypeDef structure.
  * @retval None
  */
static void JPEG_MDMAOutCpltCallback(MDMA_HandleTypeDef *hmdma)
{
  JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((MDMA_HandleTypeDef *)hmdma)->Parent;


  /* Disable The JPEG IT so the MDMA Output Callback can not be interrupted by the JPEG EOC IT or JPEG HPD IT */
  __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);

  if ((hjpeg->Context & (JPEG_CONTEXT_METHOD_MASK | JPEG_CONTEXT_ENDING_DMA)) ==
      JPEG_CONTEXT_DMA) /* Check if context method is DMA and we are not in ending DMA stage */
  {
    if (__HAL_JPEG_GET_FLAG(hjpeg, JPEG_FLAG_EOCF) == 0UL)
    {
      hjpeg->JpegOutCount = hjpeg->OutDataLength - (hmdma->Instance->CBNDTR & MDMA_CBNDTR_BNDT);

      /*Output Buffer is full, call HAL_JPEG_DataReadyCallback*/
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
      hjpeg->DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#else
      HAL_JPEG_DataReadyCallback(hjpeg, hjpeg->pJpegOutBuffPtr, hjpeg->JpegOutCount);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */

      if ((hjpeg->Context &  JPEG_CONTEXT_PAUSE_OUTPUT) == 0UL)
      {
        /* Start MDMA FIFO Out transfer */
        if (HAL_MDMA_Start_IT(hjpeg->hdmaout, (uint32_t)&hjpeg->Instance->DOR, (uint32_t)hjpeg->pJpegOutBuffPtr,
                              hjpeg->OutDataLength, 1) != HAL_OK)
        {
          hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;
          hjpeg->State = HAL_JPEG_STATE_ERROR;
#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
          hjpeg->ErrorCallback(hjpeg);
#else
          HAL_JPEG_ErrorCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
          return;
        }
      }
    }

    /* JPEG Conversion still on going : Enable the JPEG IT */
    __HAL_JPEG_ENABLE_IT(hjpeg, JPEG_IT_EOC | JPEG_IT_HPD);
  }

}

/**
  * @brief  MDMA Transfer error callback
  * @param  hmdma pointer to a MDMA_HandleTypeDef structure.
  * @retval None
  */
static void JPEG_MDMAErrorCallback(MDMA_HandleTypeDef *hmdma)
{
  JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((MDMA_HandleTypeDef *)hmdma)->Parent;

  /*Stop Encoding/Decoding*/
  hjpeg->Instance->CONFR0 &=  ~JPEG_CONFR0_START;

  /* Disable All Interrupts */
  __HAL_JPEG_DISABLE_IT(hjpeg, JPEG_INTERRUPT_MASK);

  hjpeg->State = HAL_JPEG_STATE_READY;
  hjpeg->ErrorCode |= HAL_JPEG_ERROR_DMA;

#if (USE_HAL_JPEG_REGISTER_CALLBACKS == 1)
  hjpeg->ErrorCallback(hjpeg);
#else
  HAL_JPEG_ErrorCallback(hjpeg);
#endif /* USE_HAL_JPEG_REGISTER_CALLBACKS */
}

/**
  * @brief  MDMA output Abort callback
  * @param  hmdma pointer to a MDMA_HandleTypeDef structure.
  * @retval None
  */
static void JPEG_MDMAOutAbortCallback(MDMA_HandleTypeDef *hmdma)
{
  JPEG_HandleTypeDef *hjpeg = (JPEG_HandleTypeDef *)((MDMA_HandleTypeDef *)hmdma)->Parent;

  if ((hjpeg->Context & JPEG_CONTEXT_ENDING_DMA) != 0UL)
  {
    JPEG_DMA_EndProcess(hjpeg);
  }
}


/**
  * @brief  Calculate the decoded image quality (from 1 to 100)
  * @param  hjpeg pointer to a JPEG_HandleTypeDef structure that contains
  *         the configuration information for JPEG module
  * @retval JPEG image quality from 1 to 100.
  */
static uint32_t JPEG_GetQuality(JPEG_HandleTypeDef *hjpeg)
{
  uint32_t quality = 0;
  uint32_t quantRow, quantVal, scale, i, j;
  __IO uint32_t *tableAddress = hjpeg->Instance->QMEM0;

  i = 0;
  while (i < (JPEG_QUANT_TABLE_SIZE - 3UL))
  {
    quantRow = *tableAddress;
    for (j = 0; j < 4UL; j++)
    {
      quantVal = (quantRow >> (8UL * j)) & 0xFFUL;
      if (quantVal == 1UL)
      {
        /* if Quantization value = 1 then quality is 100%*/
        quality += 100UL;
      }
      else
      {
        /* Note that the quantization coefficients must be specified in the table in zigzag order */
        scale = (quantVal * 100UL) / ((uint32_t) hjpeg->QuantTable0[JPEG_ZIGZAG_ORDER[i + j]]);

        if (scale <= 100UL)
        {
          quality += (200UL - scale) / 2UL;
        }
        else
        {
          quality += 5000UL / scale;
        }
      }
    }

    i += 4UL;
    tableAddress ++;
  }

  return (quality / 64UL);
}
/**
  * @}
  */

/**
  * @}
  */
#endif /* JPEG */
#endif /* HAL_JPEG_MODULE_ENABLED */


/**
  * @}
  */