aboutsummaryrefslogtreecommitdiffstats
path: root/libavcodec/mediacodec_wrapper.c
blob: 0880ddd3efb489db574013f44ffe2739f80f7a2b (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
/*
 * Android MediaCodec Wrapper
 *
 * Copyright (c) 2015-2016 Matthieu Bouron <matthieu.bouron stupeflix.com>
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <dlfcn.h>
#include <jni.h>
#include <stdbool.h>
#include <media/NdkMediaFormat.h>
#include <media/NdkMediaCodec.h>
#include <android/native_window_jni.h>

#include "libavutil/avassert.h"
#include "libavutil/mem.h"
#include "libavutil/avstring.h"

#include "avcodec.h"
#include "ffjni.h"
#include "mediacodec_wrapper.h"

struct JNIAMediaCodecListFields {

    jclass mediacodec_list_class;
    jmethodID init_id;
    jmethodID find_decoder_for_format_id;

    jmethodID get_codec_count_id;
    jmethodID get_codec_info_at_id;

    jclass mediacodec_info_class;
    jmethodID get_name_id;
    jmethodID get_codec_capabilities_id;
    jmethodID get_supported_types_id;
    jmethodID is_encoder_id;
    jmethodID is_software_only_id;

    jclass codec_capabilities_class;
    jfieldID color_formats_id;
    jfieldID profile_levels_id;

    jclass codec_profile_level_class;
    jfieldID profile_id;
    jfieldID level_id;
};

static const struct FFJniField jni_amediacodeclist_mapping[] = {
    { "android/media/MediaCodecList", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaCodecListFields, mediacodec_list_class), 1 },
        { "android/media/MediaCodecList", "<init>", "(I)V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, init_id), 0 },
        { "android/media/MediaCodecList", "findDecoderForFormat", "(Landroid/media/MediaFormat;)Ljava/lang/String;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, find_decoder_for_format_id), 0 },

        { "android/media/MediaCodecList", "getCodecCount", "()I", FF_JNI_STATIC_METHOD, offsetof(struct JNIAMediaCodecListFields, get_codec_count_id), 1 },
        { "android/media/MediaCodecList", "getCodecInfoAt", "(I)Landroid/media/MediaCodecInfo;", FF_JNI_STATIC_METHOD, offsetof(struct JNIAMediaCodecListFields, get_codec_info_at_id), 1 },

    { "android/media/MediaCodecInfo", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaCodecListFields, mediacodec_info_class), 1 },
        { "android/media/MediaCodecInfo", "getName", "()Ljava/lang/String;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, get_name_id), 1 },
        { "android/media/MediaCodecInfo", "getCapabilitiesForType", "(Ljava/lang/String;)Landroid/media/MediaCodecInfo$CodecCapabilities;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, get_codec_capabilities_id), 1 },
        { "android/media/MediaCodecInfo", "getSupportedTypes", "()[Ljava/lang/String;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, get_supported_types_id), 1 },
        { "android/media/MediaCodecInfo", "isEncoder", "()Z", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, is_encoder_id), 1 },
        { "android/media/MediaCodecInfo", "isSoftwareOnly", "()Z", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecListFields, is_software_only_id), 0 },

    { "android/media/MediaCodecInfo$CodecCapabilities", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaCodecListFields, codec_capabilities_class), 1 },
        { "android/media/MediaCodecInfo$CodecCapabilities", "colorFormats", "[I", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecListFields, color_formats_id), 1 },
        { "android/media/MediaCodecInfo$CodecCapabilities", "profileLevels", "[Landroid/media/MediaCodecInfo$CodecProfileLevel;", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecListFields, profile_levels_id), 1 },

    { "android/media/MediaCodecInfo$CodecProfileLevel", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaCodecListFields, codec_profile_level_class), 1 },
        { "android/media/MediaCodecInfo$CodecProfileLevel", "profile", "I", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecListFields, profile_id), 1 },
        { "android/media/MediaCodecInfo$CodecProfileLevel", "level", "I", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecListFields, level_id), 1 },

    { NULL }
};

struct JNIAMediaFormatFields {

    jclass mediaformat_class;

    jmethodID init_id;

    jmethodID contains_key_id;

    jmethodID get_integer_id;
    jmethodID get_long_id;
    jmethodID get_float_id;
    jmethodID get_bytebuffer_id;
    jmethodID get_string_id;

    jmethodID set_integer_id;
    jmethodID set_long_id;
    jmethodID set_float_id;
    jmethodID set_bytebuffer_id;
    jmethodID set_string_id;

    jmethodID to_string_id;

};

static const struct FFJniField jni_amediaformat_mapping[] = {
    { "android/media/MediaFormat", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaFormatFields, mediaformat_class), 1 },

        { "android/media/MediaFormat", "<init>", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, init_id), 1 },

        { "android/media/MediaFormat", "containsKey", "(Ljava/lang/String;)Z", FF_JNI_METHOD,offsetof(struct JNIAMediaFormatFields, contains_key_id), 1 },

        { "android/media/MediaFormat", "getInteger", "(Ljava/lang/String;)I", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, get_integer_id), 1 },
        { "android/media/MediaFormat", "getLong", "(Ljava/lang/String;)J", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, get_long_id), 1 },
        { "android/media/MediaFormat", "getFloat", "(Ljava/lang/String;)F", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, get_float_id), 1 },
        { "android/media/MediaFormat", "getByteBuffer", "(Ljava/lang/String;)Ljava/nio/ByteBuffer;", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, get_bytebuffer_id), 1 },
        { "android/media/MediaFormat", "getString", "(Ljava/lang/String;)Ljava/lang/String;", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, get_string_id), 1 },

        { "android/media/MediaFormat", "setInteger", "(Ljava/lang/String;I)V", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, set_integer_id), 1 },
        { "android/media/MediaFormat", "setLong", "(Ljava/lang/String;J)V", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, set_long_id), 1 },
        { "android/media/MediaFormat", "setFloat", "(Ljava/lang/String;F)V", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, set_float_id), 1 },
        { "android/media/MediaFormat", "setByteBuffer", "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, set_bytebuffer_id), 1 },
        { "android/media/MediaFormat", "setString", "(Ljava/lang/String;Ljava/lang/String;)V", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, set_string_id), 1 },

        { "android/media/MediaFormat", "toString", "()Ljava/lang/String;", FF_JNI_METHOD, offsetof(struct JNIAMediaFormatFields, to_string_id), 1 },

    { NULL }
};

static const AVClass amediaformat_class = {
    .class_name = "amediaformat",
    .item_name  = av_default_item_name,
    .version    = LIBAVUTIL_VERSION_INT,
};

typedef struct FFAMediaFormatJni {
    FFAMediaFormat api;

    struct JNIAMediaFormatFields jfields;
    jobject object;
} FFAMediaFormatJni;

static const FFAMediaFormat media_format_jni;

struct JNIAMediaCodecFields {

    jclass mediacodec_class;

    jfieldID info_try_again_later_id;
    jfieldID info_output_buffers_changed_id;
    jfieldID info_output_format_changed_id;

    jfieldID buffer_flag_codec_config_id;
    jfieldID buffer_flag_end_of_stream_id;
    jfieldID buffer_flag_key_frame_id;

    jfieldID configure_flag_encode_id;

    jmethodID create_by_codec_name_id;
    jmethodID create_decoder_by_type_id;
    jmethodID create_encoder_by_type_id;

    jmethodID get_name_id;

    jmethodID configure_id;
    jmethodID start_id;
    jmethodID flush_id;
    jmethodID stop_id;
    jmethodID release_id;

    jmethodID get_output_format_id;

    jmethodID dequeue_input_buffer_id;
    jmethodID queue_input_buffer_id;
    jmethodID get_input_buffer_id;
    jmethodID get_input_buffers_id;

    jmethodID dequeue_output_buffer_id;
    jmethodID get_output_buffer_id;
    jmethodID get_output_buffers_id;
    jmethodID release_output_buffer_id;
    jmethodID release_output_buffer_at_time_id;

    jmethodID set_input_surface_id;
    jmethodID signal_end_of_input_stream_id;

    jclass mediainfo_class;

    jmethodID init_id;

    jfieldID flags_id;
    jfieldID offset_id;
    jfieldID presentation_time_us_id;
    jfieldID size_id;

};

static const struct FFJniField jni_amediacodec_mapping[] = {
    { "android/media/MediaCodec", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaCodecFields, mediacodec_class), 1 },

        { "android/media/MediaCodec", "INFO_TRY_AGAIN_LATER", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, info_try_again_later_id), 1 },
        { "android/media/MediaCodec", "INFO_OUTPUT_BUFFERS_CHANGED", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, info_output_buffers_changed_id), 1 },
        { "android/media/MediaCodec", "INFO_OUTPUT_FORMAT_CHANGED", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, info_output_format_changed_id), 1 },

        { "android/media/MediaCodec", "BUFFER_FLAG_CODEC_CONFIG", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, buffer_flag_codec_config_id), 1 },
        { "android/media/MediaCodec", "BUFFER_FLAG_END_OF_STREAM", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, buffer_flag_end_of_stream_id), 1 },
        { "android/media/MediaCodec", "BUFFER_FLAG_KEY_FRAME", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, buffer_flag_key_frame_id), 0 },

        { "android/media/MediaCodec", "CONFIGURE_FLAG_ENCODE", "I", FF_JNI_STATIC_FIELD, offsetof(struct JNIAMediaCodecFields, configure_flag_encode_id), 1 },

        { "android/media/MediaCodec", "createByCodecName", "(Ljava/lang/String;)Landroid/media/MediaCodec;", FF_JNI_STATIC_METHOD, offsetof(struct JNIAMediaCodecFields, create_by_codec_name_id), 1 },
        { "android/media/MediaCodec", "createDecoderByType", "(Ljava/lang/String;)Landroid/media/MediaCodec;", FF_JNI_STATIC_METHOD, offsetof(struct JNIAMediaCodecFields, create_decoder_by_type_id), 1 },
        { "android/media/MediaCodec", "createEncoderByType", "(Ljava/lang/String;)Landroid/media/MediaCodec;", FF_JNI_STATIC_METHOD, offsetof(struct JNIAMediaCodecFields, create_encoder_by_type_id), 1 },

        { "android/media/MediaCodec", "getName", "()Ljava/lang/String;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, get_name_id), 1 },

        { "android/media/MediaCodec", "configure", "(Landroid/media/MediaFormat;Landroid/view/Surface;Landroid/media/MediaCrypto;I)V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, configure_id), 1 },
        { "android/media/MediaCodec", "start", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, start_id), 1 },
        { "android/media/MediaCodec", "flush", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, flush_id), 1 },
        { "android/media/MediaCodec", "stop", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, stop_id), 1 },
        { "android/media/MediaCodec", "release", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, release_id), 1 },

        { "android/media/MediaCodec", "getOutputFormat", "()Landroid/media/MediaFormat;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, get_output_format_id), 1 },

        { "android/media/MediaCodec", "dequeueInputBuffer", "(J)I", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, dequeue_input_buffer_id), 1 },
        { "android/media/MediaCodec", "queueInputBuffer", "(IIIJI)V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, queue_input_buffer_id), 1 },
        { "android/media/MediaCodec", "getInputBuffer", "(I)Ljava/nio/ByteBuffer;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, get_input_buffer_id), 0 },
        { "android/media/MediaCodec", "getInputBuffers", "()[Ljava/nio/ByteBuffer;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, get_input_buffers_id), 1 },

        { "android/media/MediaCodec", "dequeueOutputBuffer", "(Landroid/media/MediaCodec$BufferInfo;J)I", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, dequeue_output_buffer_id), 1 },
        { "android/media/MediaCodec", "getOutputBuffer", "(I)Ljava/nio/ByteBuffer;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, get_output_buffer_id), 0 },
        { "android/media/MediaCodec", "getOutputBuffers", "()[Ljava/nio/ByteBuffer;", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, get_output_buffers_id), 1 },
        { "android/media/MediaCodec", "releaseOutputBuffer", "(IZ)V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, release_output_buffer_id), 1 },
        { "android/media/MediaCodec", "releaseOutputBuffer", "(IJ)V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, release_output_buffer_at_time_id), 0 },

        { "android/media/MediaCodec", "setInputSurface", "(Landroid/view/Surface;)V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, set_input_surface_id), 0 },
        { "android/media/MediaCodec", "signalEndOfInputStream", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, signal_end_of_input_stream_id), 0 },

    { "android/media/MediaCodec$BufferInfo", NULL, NULL, FF_JNI_CLASS, offsetof(struct JNIAMediaCodecFields, mediainfo_class), 1 },

        { "android/media/MediaCodec.BufferInfo", "<init>", "()V", FF_JNI_METHOD, offsetof(struct JNIAMediaCodecFields, init_id), 1 },
        { "android/media/MediaCodec.BufferInfo", "flags", "I", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecFields, flags_id), 1 },
        { "android/media/MediaCodec.BufferInfo", "offset", "I", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecFields, offset_id), 1 },
        { "android/media/MediaCodec.BufferInfo", "presentationTimeUs", "J", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecFields, presentation_time_us_id), 1 },
        { "android/media/MediaCodec.BufferInfo", "size", "I", FF_JNI_FIELD, offsetof(struct JNIAMediaCodecFields, size_id), 1 },

    { NULL }
};

static const AVClass amediacodec_class = {
    .class_name = "amediacodec",
    .item_name  = av_default_item_name,
    .version    = LIBAVUTIL_VERSION_INT,
};

typedef struct FFAMediaCodecJni {
    FFAMediaCodec api;

    struct JNIAMediaCodecFields jfields;

    jobject object;
    jobject buffer_info;

    jobject input_buffers;
    jobject output_buffers;

    int INFO_TRY_AGAIN_LATER;
    int INFO_OUTPUT_BUFFERS_CHANGED;
    int INFO_OUTPUT_FORMAT_CHANGED;

    int BUFFER_FLAG_CODEC_CONFIG;
    int BUFFER_FLAG_END_OF_STREAM;
    int BUFFER_FLAG_KEY_FRAME;

    int CONFIGURE_FLAG_ENCODE;

    int has_get_i_o_buffer;
} FFAMediaCodecJni;

static const FFAMediaCodec media_codec_jni;

#define JNI_GET_ENV_OR_RETURN(env, log_ctx, ret) do {              \
    (env) = ff_jni_get_env(log_ctx);                               \
    if (!(env)) {                                                  \
        return ret;                                                \
    }                                                              \
} while (0)

#define JNI_GET_ENV_OR_RETURN_VOID(env, log_ctx) do {              \
    (env) = ff_jni_get_env(log_ctx);                               \
    if (!(env)) {                                                  \
        return;                                                    \
    }                                                              \
} while (0)

int ff_AMediaCodecProfile_getProfileFromAVCodecContext(AVCodecContext *avctx)
{
    // Copy and modified from MediaCodecInfo.java
    static const int AVCProfileBaseline = 0x01;
    static const int AVCProfileMain     = 0x02;
    static const int AVCProfileExtended = 0x04;
    static const int AVCProfileHigh     = 0x08;
    static const int AVCProfileHigh10   = 0x10;
    static const int AVCProfileHigh422  = 0x20;
    static const int AVCProfileHigh444  = 0x40;
    static const int AVCProfileConstrainedBaseline = 0x10000;
    static const int AVCProfileConstrainedHigh     = 0x80000;

    static const int HEVCProfileMain        = 0x01;
    static const int HEVCProfileMain10      = 0x02;
    static const int HEVCProfileMainStill   = 0x04;
    static const int HEVCProfileMain10HDR10 = 0x1000;
    static const int HEVCProfileMain10HDR10Plus = 0x2000;

    static const int VP9Profile0 = 0x01;
    static const int VP9Profile1 = 0x02;
    static const int VP9Profile2 = 0x04;
    static const int VP9Profile3 = 0x08;
    static const int VP9Profile2HDR = 0x1000;
    static const int VP9Profile3HDR = 0x2000;
    static const int VP9Profile2HDR10Plus = 0x4000;
    static const int VP9Profile3HDR10Plus = 0x8000;

    static const int MPEG4ProfileSimple           = 0x01;
    static const int MPEG4ProfileSimpleScalable   = 0x02;
    static const int MPEG4ProfileCore             = 0x04;
    static const int MPEG4ProfileMain             = 0x08;
    static const int MPEG4ProfileNbit             = 0x10;
    static const int MPEG4ProfileScalableTexture  = 0x20;
    static const int MPEG4ProfileSimpleFBA        = 0x80;
    static const int MPEG4ProfileSimpleFace       = 0x40;
    static const int MPEG4ProfileBasicAnimated    = 0x100;
    static const int MPEG4ProfileHybrid           = 0x200;
    static const int MPEG4ProfileAdvancedRealTime = 0x400;
    static const int MPEG4ProfileCoreScalable     = 0x800;
    static const int MPEG4ProfileAdvancedCoding   = 0x1000;
    static const int MPEG4ProfileAdvancedCore     = 0x2000;
    static const int MPEG4ProfileAdvancedScalable = 0x4000;
    static const int MPEG4ProfileAdvancedSimple   = 0x8000;


    static const int AV1ProfileMain8  = 0x1;
    static const int AV1ProfileMain10 = 0x2;
    static const int AV1ProfileMain10HDR10     = 0x1000;
    static const int AV1ProfileMain10HDR10Plus = 0x2000;

    // Unused yet.
    (void)AVCProfileConstrainedHigh;
    (void)HEVCProfileMain10HDR10;
    (void)HEVCProfileMain10HDR10Plus;
    (void)VP9Profile2HDR;
    (void)VP9Profile3HDR;
    (void)VP9Profile2HDR10Plus;
    (void)VP9Profile3HDR10Plus;
    (void)AV1ProfileMain10;
    (void)AV1ProfileMain10HDR10;
    (void)AV1ProfileMain10HDR10Plus;

    if (avctx->codec_id == AV_CODEC_ID_H264) {
        switch(avctx->profile) {
        case AV_PROFILE_H264_BASELINE:
            return AVCProfileBaseline;
        case AV_PROFILE_H264_CONSTRAINED_BASELINE:
            return AVCProfileConstrainedBaseline;
        case AV_PROFILE_H264_MAIN:
            return AVCProfileMain;
            break;
        case AV_PROFILE_H264_EXTENDED:
            return AVCProfileExtended;
        case AV_PROFILE_H264_HIGH:
            return AVCProfileHigh;
        case AV_PROFILE_H264_HIGH_10:
        case AV_PROFILE_H264_HIGH_10_INTRA:
            return AVCProfileHigh10;
        case AV_PROFILE_H264_HIGH_422:
        case AV_PROFILE_H264_HIGH_422_INTRA:
            return AVCProfileHigh422;
        case AV_PROFILE_H264_HIGH_444:
        case AV_PROFILE_H264_HIGH_444_INTRA:
        case AV_PROFILE_H264_HIGH_444_PREDICTIVE:
            return AVCProfileHigh444;
        }
    } else if (avctx->codec_id == AV_CODEC_ID_HEVC) {
        switch (avctx->profile) {
        case AV_PROFILE_HEVC_MAIN:
            return HEVCProfileMain;
        case AV_PROFILE_HEVC_MAIN_STILL_PICTURE:
            return HEVCProfileMainStill;
        case AV_PROFILE_HEVC_MAIN_10:
            return HEVCProfileMain10;
        }
    } else if (avctx->codec_id == AV_CODEC_ID_VP9) {
        switch (avctx->profile) {
        case AV_PROFILE_VP9_0:
            return VP9Profile0;
        case AV_PROFILE_VP9_1:
            return VP9Profile1;
        case AV_PROFILE_VP9_2:
            return VP9Profile2;
         case AV_PROFILE_VP9_3:
            return VP9Profile3;
        }
    } else if(avctx->codec_id == AV_CODEC_ID_MPEG4) {
        switch (avctx->profile)
        {
        case AV_PROFILE_MPEG4_SIMPLE:
            return MPEG4ProfileSimple;
        case AV_PROFILE_MPEG4_SIMPLE_SCALABLE:
            return MPEG4ProfileSimpleScalable;
        case AV_PROFILE_MPEG4_CORE:
            return MPEG4ProfileCore;
        case AV_PROFILE_MPEG4_MAIN:
            return MPEG4ProfileMain;
        case AV_PROFILE_MPEG4_N_BIT:
            return MPEG4ProfileNbit;
        case AV_PROFILE_MPEG4_SCALABLE_TEXTURE:
            return MPEG4ProfileScalableTexture;
        case AV_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION:
            return MPEG4ProfileSimpleFBA;
        case AV_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE:
            return MPEG4ProfileBasicAnimated;
        case AV_PROFILE_MPEG4_HYBRID:
            return MPEG4ProfileHybrid;
        case AV_PROFILE_MPEG4_ADVANCED_REAL_TIME:
            return MPEG4ProfileAdvancedRealTime;
        case AV_PROFILE_MPEG4_CORE_SCALABLE:
            return MPEG4ProfileCoreScalable;
        case AV_PROFILE_MPEG4_ADVANCED_CODING:
            return MPEG4ProfileAdvancedCoding;
        case AV_PROFILE_MPEG4_ADVANCED_CORE:
            return MPEG4ProfileAdvancedCore;
        case AV_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE:
            return MPEG4ProfileAdvancedScalable;
        case AV_PROFILE_MPEG4_ADVANCED_SIMPLE:
            return MPEG4ProfileAdvancedSimple;
        case AV_PROFILE_MPEG4_SIMPLE_STUDIO:
            // Studio profiles are not supported by mediacodec.
        default:
            break;
        }
    } else if(avctx->codec_id == AV_CODEC_ID_AV1) {
        switch (avctx->profile)
        {
        case AV_PROFILE_AV1_MAIN:
            return AV1ProfileMain8;
        case AV_PROFILE_AV1_HIGH:
        case AV_PROFILE_AV1_PROFESSIONAL:
        default:
            break;
        }
    }

    return -1;
}

char *ff_AMediaCodecList_getCodecNameByType(const char *mime, int profile, int encoder, void *log_ctx)
{
    int ret;
    int i;
    int codec_count;
    int found_codec = 0;
    char *name = NULL;
    char *supported_type = NULL;

    JNIEnv *env = NULL;
    struct JNIAMediaCodecListFields jfields = { 0 };
    struct JNIAMediaFormatFields mediaformat_jfields = { 0 };

    jobject codec_name = NULL;

    jobject info = NULL;
    jobject type = NULL;
    jobjectArray types = NULL;

    jobject capabilities = NULL;
    jobject profile_level = NULL;
    jobjectArray profile_levels = NULL;

    JNI_GET_ENV_OR_RETURN(env, log_ctx, NULL);

    if ((ret = ff_jni_init_jfields(env, &jfields, jni_amediacodeclist_mapping, 0, log_ctx)) < 0) {
        goto done;
    }

    if ((ret = ff_jni_init_jfields(env, &mediaformat_jfields, jni_amediaformat_mapping, 0, log_ctx)) < 0) {
        goto done;
    }

    codec_count = (*env)->CallStaticIntMethod(env, jfields.mediacodec_list_class, jfields.get_codec_count_id);
    if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
        goto done;
    }

    for(i = 0; i < codec_count; i++) {
        int j;
        int type_count;
        int is_encoder;

        info = (*env)->CallStaticObjectMethod(env, jfields.mediacodec_list_class, jfields.get_codec_info_at_id, i);
        if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
            goto done;
        }

        types = (*env)->CallObjectMethod(env, info, jfields.get_supported_types_id);
        if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
            goto done;
        }

        is_encoder = (*env)->CallBooleanMethod(env, info, jfields.is_encoder_id);
        if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
            goto done;
        }

        if (is_encoder != encoder) {
            goto done_with_info;
        }

        if (jfields.is_software_only_id) {
            int is_software_only = (*env)->CallBooleanMethod(env, info, jfields.is_software_only_id);
            if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
                goto done;
            }

            if (is_software_only) {
                goto done_with_info;
            }
        }

        codec_name = (*env)->CallObjectMethod(env, info, jfields.get_name_id);
        if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
            goto done;
        }

        name = ff_jni_jstring_to_utf_chars(env, codec_name, log_ctx);
        if (!name) {
            goto done;
        }

        if (codec_name) {
            (*env)->DeleteLocalRef(env, codec_name);
            codec_name = NULL;
        }

        /* Skip software decoders */
        if (
            strstr(name, "OMX.google") ||
            strstr(name, "OMX.ffmpeg") ||
            (strstr(name, "OMX.SEC") && strstr(name, ".sw.")) ||
            !strcmp(name, "OMX.qcom.video.decoder.hevcswvdec")) {
            goto done_with_info;
        }

        type_count = (*env)->GetArrayLength(env, types);
        for (j = 0; j < type_count; j++) {
            int k;
            int profile_count;

            type = (*env)->GetObjectArrayElement(env, types, j);
            if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
                goto done;
            }

            supported_type = ff_jni_jstring_to_utf_chars(env, type, log_ctx);
            if (!supported_type) {
                goto done;
            }

            if (av_strcasecmp(supported_type, mime)) {
                goto done_with_type;
            }

            capabilities = (*env)->CallObjectMethod(env, info, jfields.get_codec_capabilities_id, type);
            if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
                goto done;
            }

            profile_levels = (*env)->GetObjectField(env, capabilities, jfields.profile_levels_id);
            if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
                goto done;
            }

            profile_count = (*env)->GetArrayLength(env, profile_levels);
            if (!profile_count) {
                found_codec = 1;
            }
            for (k = 0; k < profile_count; k++) {
                int supported_profile = 0;

                if (profile < 0) {
                    found_codec = 1;
                    break;
                }

                profile_level = (*env)->GetObjectArrayElement(env, profile_levels, k);
                if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
                    goto done;
                }

                supported_profile = (*env)->GetIntField(env, profile_level, jfields.profile_id);
                if (ff_jni_exception_check(env, 1, log_ctx) < 0) {
                    goto done;
                }

                found_codec = profile == supported_profile;

                if (profile_level) {
                    (*env)->DeleteLocalRef(env, profile_level);
                    profile_level = NULL;
                }

                if (found_codec) {
                    break;
                }
            }

done_with_type:
            if (profile_levels) {
                (*env)->DeleteLocalRef(env, profile_levels);
                profile_levels = NULL;
            }

            if (capabilities) {
                (*env)->DeleteLocalRef(env, capabilities);
                capabilities = NULL;
            }

            if (type) {
                (*env)->DeleteLocalRef(env, type);
                type = NULL;
            }

            av_freep(&supported_type);

            if (found_codec) {
                break;
            }
        }

done_with_info:
        if (info) {
            (*env)->DeleteLocalRef(env, info);
            info = NULL;
        }

        if (types) {
            (*env)->DeleteLocalRef(env, types);
            types = NULL;
        }

        if (found_codec) {
            break;
        }

        av_freep(&name);
    }

done:
    if (codec_name) {
        (*env)->DeleteLocalRef(env, codec_name);
    }

    if (info) {
        (*env)->DeleteLocalRef(env, info);
    }

    if (type) {
        (*env)->DeleteLocalRef(env, type);
    }

    if (types) {
        (*env)->DeleteLocalRef(env, types);
    }

    if (capabilities) {
        (*env)->DeleteLocalRef(env, capabilities);
    }

    if (profile_level) {
        (*env)->DeleteLocalRef(env, profile_level);
    }

    if (profile_levels) {
        (*env)->DeleteLocalRef(env, profile_levels);
    }

    av_freep(&supported_type);

    ff_jni_reset_jfields(env, &jfields, jni_amediacodeclist_mapping, 0, log_ctx);
    ff_jni_reset_jfields(env, &mediaformat_jfields, jni_amediaformat_mapping, 0, log_ctx);

    if (!found_codec) {
        av_freep(&name);
    }

    return name;
}

static FFAMediaFormat *mediaformat_jni_new(void)
{
    JNIEnv *env = NULL;
    FFAMediaFormatJni *format = NULL;
    jobject object = NULL;

    format = av_mallocz(sizeof(*format));
    if (!format) {
        return NULL;
    }
    format->api = media_format_jni;

    env = ff_jni_get_env(format);
    if (!env) {
        av_freep(&format);
        return NULL;
    }

    if (ff_jni_init_jfields(env, &format->jfields, jni_amediaformat_mapping, 1, format) < 0) {
        goto fail;
    }

    object = (*env)->NewObject(env, format->jfields.mediaformat_class, format->jfields.init_id);
    if (!object) {
        goto fail;
    }

    format->object = (*env)->NewGlobalRef(env, object);
    if (!format->object) {
        goto fail;
    }

fail:
    if (object) {
        (*env)->DeleteLocalRef(env, object);
    }

    if (!format->object) {
        ff_jni_reset_jfields(env, &format->jfields, jni_amediaformat_mapping, 1, format);
        av_freep(&format);
    }

    return (FFAMediaFormat *)format;
}

static FFAMediaFormat *mediaformat_jni_newFromObject(void *object)
{
    JNIEnv *env = NULL;
    FFAMediaFormatJni *format = NULL;

    format = av_mallocz(sizeof(*format));
    if (!format) {
        return NULL;
    }
    format->api = media_format_jni;

    env = ff_jni_get_env(format);
    if (!env) {
        av_freep(&format);
        return NULL;
    }

    if (ff_jni_init_jfields(env, &format->jfields, jni_amediaformat_mapping, 1, format) < 0) {
        goto fail;
    }

    format->object = (*env)->NewGlobalRef(env, object);
    if (!format->object) {
        goto fail;
    }

    return (FFAMediaFormat *)format;
fail:
    ff_jni_reset_jfields(env, &format->jfields, jni_amediaformat_mapping, 1, format);

    av_freep(&format);

    return NULL;
}

static int mediaformat_jni_delete(FFAMediaFormat* ctx)
{
    int ret = 0;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;

    if (!format) {
        return 0;
    }

    JNI_GET_ENV_OR_RETURN(env, format, AVERROR_EXTERNAL);

    (*env)->DeleteGlobalRef(env, format->object);
    format->object = NULL;

    ff_jni_reset_jfields(env, &format->jfields, jni_amediaformat_mapping, 1, format);

    av_freep(&format);

    return ret;
}

static char* mediaformat_jni_toString(FFAMediaFormat* ctx)
{
    char *ret = NULL;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;
    jstring description = NULL;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN(env, format, NULL);

    description = (*env)->CallObjectMethod(env, format->object, format->jfields.to_string_id);
    if (ff_jni_exception_check(env, 1, NULL) < 0) {
        goto fail;
    }

    ret = ff_jni_jstring_to_utf_chars(env, description, format);
fail:
    if (description) {
        (*env)->DeleteLocalRef(env, description);
    }

    return ret;
}

static int mediaformat_jni_getInt32(FFAMediaFormat* ctx, const char *name, int32_t *out)
{
    int ret = 1;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;
    jstring key = NULL;
    jboolean contains_key;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN(env, format, 0);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        ret = 0;
        goto fail;
    }

    contains_key = (*env)->CallBooleanMethod(env, format->object, format->jfields.contains_key_id, key);
    if (!contains_key || (ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    *out = (*env)->CallIntMethod(env, format->object, format->jfields.get_integer_id, key);
    if ((ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    ret = 1;
fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    return ret;
}

static int mediaformat_jni_getInt64(FFAMediaFormat* ctx, const char *name, int64_t *out)
{
    int ret = 1;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;
    jstring key = NULL;
    jboolean contains_key;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN(env, format, 0);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        ret = 0;
        goto fail;
    }

    contains_key = (*env)->CallBooleanMethod(env, format->object, format->jfields.contains_key_id, key);
    if (!contains_key || (ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    *out = (*env)->CallLongMethod(env, format->object, format->jfields.get_long_id, key);
    if ((ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    ret = 1;
fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    return ret;
}

static int mediaformat_jni_getFloat(FFAMediaFormat* ctx, const char *name, float *out)
{
    int ret = 1;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;
    jstring key = NULL;
    jboolean contains_key;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN(env, format, 0);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        ret = 0;
        goto fail;
    }

    contains_key = (*env)->CallBooleanMethod(env, format->object, format->jfields.contains_key_id, key);
    if (!contains_key || (ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    *out = (*env)->CallFloatMethod(env, format->object, format->jfields.get_float_id, key);
    if ((ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    ret = 1;
fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    return ret;
}

static int mediaformat_jni_getBuffer(FFAMediaFormat* ctx, const char *name, void** data, size_t *size)
{
    int ret = 1;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;
    jstring key = NULL;
    jboolean contains_key;
    jobject result = NULL;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN(env, format, 0);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        ret = 0;
        goto fail;
    }

    contains_key = (*env)->CallBooleanMethod(env, format->object, format->jfields.contains_key_id, key);
    if (!contains_key || (ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    result = (*env)->CallObjectMethod(env, format->object, format->jfields.get_bytebuffer_id, key);
    if ((ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    *data = (*env)->GetDirectBufferAddress(env, result);
    *size = (*env)->GetDirectBufferCapacity(env, result);

    if (*data && *size) {
        void *src = *data;
        *data = av_malloc(*size);
        if (!*data) {
            ret = 0;
            goto fail;
        }

        memcpy(*data, src, *size);
    }

    ret = 1;
fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    if (result) {
        (*env)->DeleteLocalRef(env, result);
    }

    return ret;
}

static int mediaformat_jni_getString(FFAMediaFormat* ctx, const char *name, const char **out)
{
    int ret = 1;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;
    JNIEnv *env = NULL;
    jstring key = NULL;
    jboolean contains_key;
    jstring result = NULL;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN(env, format, 0);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        ret = 0;
        goto fail;
    }

    contains_key = (*env)->CallBooleanMethod(env, format->object, format->jfields.contains_key_id, key);
    if (!contains_key || (ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    result = (*env)->CallObjectMethod(env, format->object, format->jfields.get_string_id, key);
    if ((ret = ff_jni_exception_check(env, 1, format)) < 0) {
        ret = 0;
        goto fail;
    }

    *out = ff_jni_jstring_to_utf_chars(env, result, format);
    if (!*out) {
        ret = 0;
        goto fail;
    }

    ret = 1;
fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    if (result) {
        (*env)->DeleteLocalRef(env, result);
    }

    return ret;
}

static void mediaformat_jni_setInt32(FFAMediaFormat* ctx, const char* name, int32_t value)
{
    JNIEnv *env = NULL;
    jstring key = NULL;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN_VOID(env, format);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        goto fail;
    }

    (*env)->CallVoidMethod(env, format->object, format->jfields.set_integer_id, key, value);
    if (ff_jni_exception_check(env, 1, format) < 0) {
        goto fail;
    }

fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }
}

static void mediaformat_jni_setInt64(FFAMediaFormat* ctx, const char* name, int64_t value)
{
    JNIEnv *env = NULL;
    jstring key = NULL;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN_VOID(env, format);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        goto fail;
    }

    (*env)->CallVoidMethod(env, format->object, format->jfields.set_long_id, key, value);
    if (ff_jni_exception_check(env, 1, format) < 0) {
        goto fail;
    }

fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }
}

static void mediaformat_jni_setFloat(FFAMediaFormat* ctx, const char* name, float value)
{
    JNIEnv *env = NULL;
    jstring key = NULL;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN_VOID(env, format);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        goto fail;
    }

    (*env)->CallVoidMethod(env, format->object, format->jfields.set_float_id, key, value);
    if (ff_jni_exception_check(env, 1, format) < 0) {
        goto fail;
    }

fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }
}

static void mediaformat_jni_setString(FFAMediaFormat* ctx, const char* name, const char* value)
{
    JNIEnv *env = NULL;
    jstring key = NULL;
    jstring string = NULL;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN_VOID(env, format);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        goto fail;
    }

    string = ff_jni_utf_chars_to_jstring(env, value, format);
    if (!string) {
        goto fail;
    }

    (*env)->CallVoidMethod(env, format->object, format->jfields.set_string_id, key, string);
    if (ff_jni_exception_check(env, 1, format) < 0) {
        goto fail;
    }

fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    if (string) {
        (*env)->DeleteLocalRef(env, string);
    }
}

static void mediaformat_jni_setBuffer(FFAMediaFormat* ctx, const char* name, void* data, size_t size)
{
    JNIEnv *env = NULL;
    jstring key = NULL;
    jobject buffer = NULL;
    void *buffer_data = NULL;
    FFAMediaFormatJni *format = (FFAMediaFormatJni *)ctx;

    av_assert0(format != NULL);

    JNI_GET_ENV_OR_RETURN_VOID(env, format);

    key = ff_jni_utf_chars_to_jstring(env, name, format);
    if (!key) {
        goto fail;
    }

    if (!data || !size) {
        goto fail;
    }

    buffer_data = av_malloc(size);
    if (!buffer_data) {
        goto fail;
    }

    memcpy(buffer_data, data, size);

    buffer = (*env)->NewDirectByteBuffer(env, buffer_data, size);
    if (!buffer) {
        goto fail;
    }

    (*env)->CallVoidMethod(env, format->object, format->jfields.set_bytebuffer_id, key, buffer);
    if (ff_jni_exception_check(env, 1, format) < 0) {
        goto fail;
    }

fail:
    if (key) {
        (*env)->DeleteLocalRef(env, key);
    }

    if (buffer) {
        (*env)->DeleteLocalRef(env, buffer);
    }
}

static int codec_init_static_fields(FFAMediaCodecJni *codec)
{
    int ret = 0;
    JNIEnv *env = NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    codec->INFO_TRY_AGAIN_LATER = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.info_try_again_later_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

    codec->BUFFER_FLAG_CODEC_CONFIG = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.buffer_flag_codec_config_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

    codec->BUFFER_FLAG_END_OF_STREAM = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.buffer_flag_end_of_stream_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

    if (codec->jfields.buffer_flag_key_frame_id) {
        codec->BUFFER_FLAG_KEY_FRAME = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.buffer_flag_key_frame_id);
        if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
            goto fail;
        }
    }

    codec->CONFIGURE_FLAG_ENCODE = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.configure_flag_encode_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

    codec->INFO_TRY_AGAIN_LATER = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.info_try_again_later_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

    codec->INFO_OUTPUT_BUFFERS_CHANGED = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.info_output_buffers_changed_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

    codec->INFO_OUTPUT_FORMAT_CHANGED = (*env)->GetStaticIntField(env, codec->jfields.mediacodec_class, codec->jfields.info_output_format_changed_id);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        goto fail;
    }

fail:

    return ret;
}

#define CREATE_CODEC_BY_NAME   0
#define CREATE_DECODER_BY_TYPE 1
#define CREATE_ENCODER_BY_TYPE 2

static inline FFAMediaCodec *codec_create(int method, const char *arg)
{
    int ret = -1;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = NULL;
    jstring jarg = NULL;
    jobject object = NULL;
    jobject buffer_info = NULL;
    jmethodID create_id = NULL;

    codec = av_mallocz(sizeof(*codec));
    if (!codec) {
        return NULL;
    }
    codec->api = media_codec_jni;

    env = ff_jni_get_env(codec);
    if (!env) {
        av_freep(&codec);
        return NULL;
    }

    if (ff_jni_init_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec) < 0) {
        goto fail;
    }

    jarg = ff_jni_utf_chars_to_jstring(env, arg, codec);
    if (!jarg) {
        goto fail;
    }

    switch (method) {
    case CREATE_CODEC_BY_NAME:   create_id = codec->jfields.create_by_codec_name_id;   break;
    case CREATE_DECODER_BY_TYPE: create_id = codec->jfields.create_decoder_by_type_id; break;
    case CREATE_ENCODER_BY_TYPE: create_id = codec->jfields.create_encoder_by_type_id; break;
    default:
        av_assert0(0);
    }

    object = (*env)->CallStaticObjectMethod(env,
                                            codec->jfields.mediacodec_class,
                                            create_id,
                                            jarg);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        goto fail;
    }

    codec->object = (*env)->NewGlobalRef(env, object);
    if (!codec->object) {
        goto fail;
    }

    if (codec_init_static_fields(codec) < 0) {
        goto fail;
    }

    if (codec->jfields.get_input_buffer_id && codec->jfields.get_output_buffer_id) {
        codec->has_get_i_o_buffer = 1;
    }

    buffer_info = (*env)->NewObject(env, codec->jfields.mediainfo_class, codec->jfields.init_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        goto fail;
    }

    codec->buffer_info = (*env)->NewGlobalRef(env, buffer_info);
    if (!codec->buffer_info) {
        goto fail;
    }

    ret = 0;
fail:
    if (jarg) {
        (*env)->DeleteLocalRef(env, jarg);
    }

    if (object) {
        (*env)->DeleteLocalRef(env, object);
    }

    if (buffer_info) {
        (*env)->DeleteLocalRef(env, buffer_info);
    }

    if (ret < 0) {
        if (codec->object) {
            (*env)->DeleteGlobalRef(env, codec->object);
        }

        if (codec->buffer_info) {
            (*env)->DeleteGlobalRef(env, codec->buffer_info);
        }

        ff_jni_reset_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec);
        av_freep(&codec);
    }

    return (FFAMediaCodec *)codec;
}

#define DECLARE_FF_AMEDIACODEC_CREATE_FUNC(name, method) \
static FFAMediaCodec *mediacodec_jni_##name(const char *arg)    \
{                                                        \
    return codec_create(method, arg);                    \
}                                                        \

DECLARE_FF_AMEDIACODEC_CREATE_FUNC(createCodecByName,   CREATE_CODEC_BY_NAME)
DECLARE_FF_AMEDIACODEC_CREATE_FUNC(createDecoderByType, CREATE_DECODER_BY_TYPE)
DECLARE_FF_AMEDIACODEC_CREATE_FUNC(createEncoderByType, CREATE_ENCODER_BY_TYPE)

static int mediacodec_jni_delete(FFAMediaCodec* ctx)
{
    int ret = 0;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    JNIEnv *env = NULL;

    if (!codec) {
        return 0;
    }

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.release_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
    }

    (*env)->DeleteGlobalRef(env, codec->input_buffers);
    codec->input_buffers = NULL;

    (*env)->DeleteGlobalRef(env, codec->output_buffers);
    codec->output_buffers = NULL;

    (*env)->DeleteGlobalRef(env, codec->object);
    codec->object = NULL;

    (*env)->DeleteGlobalRef(env, codec->buffer_info);
    codec->buffer_info = NULL;

    ff_jni_reset_jfields(env, &codec->jfields, jni_amediacodec_mapping, 1, codec);

    av_freep(&codec);

    return ret;
}

static char *mediacodec_jni_getName(FFAMediaCodec *ctx)
{
    char *ret = NULL;
    JNIEnv *env = NULL;
    jobject *name = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, NULL);

    name = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_name_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        goto fail;
    }

    ret = ff_jni_jstring_to_utf_chars(env, name, codec);

fail:
    if (name) {
        (*env)->DeleteLocalRef(env, name);
    }

    return ret;
}

static int mediacodec_jni_configure(FFAMediaCodec *ctx,
                                    const FFAMediaFormat* format_ctx,
                                    FFANativeWindow* window,
                                    void *crypto,
                                    uint32_t flags)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    const FFAMediaFormatJni *format = (FFAMediaFormatJni *)format_ctx;
    jobject *surface = window ? window->surface : NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    if (flags & codec->CONFIGURE_FLAG_ENCODE) {
        if (surface && !codec->jfields.set_input_surface_id) {
            av_log(ctx, AV_LOG_ERROR, "System doesn't support setInputSurface\n");
            return AVERROR_EXTERNAL;
        }

        (*env)->CallVoidMethod(env, codec->object, codec->jfields.configure_id, format->object, NULL, NULL, flags);
        if (ff_jni_exception_check(env, 1, codec) < 0)
            return AVERROR_EXTERNAL;

        if (!surface)
            return 0;

        (*env)->CallVoidMethod(env, codec->object, codec->jfields.set_input_surface_id, surface);
        if (ff_jni_exception_check(env, 1, codec) < 0)
            return AVERROR_EXTERNAL;
        return 0;
    } else {
        (*env)->CallVoidMethod(env, codec->object, codec->jfields.configure_id, format->object, surface, NULL, flags);
    }
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static int mediacodec_jni_start(FFAMediaCodec* ctx)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.start_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static int mediacodec_jni_stop(FFAMediaCodec* ctx)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.stop_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static int mediacodec_jni_flush(FFAMediaCodec* ctx)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.flush_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static int mediacodec_jni_releaseOutputBuffer(FFAMediaCodec* ctx, size_t idx, int render)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.release_output_buffer_id, (jint)idx, (jboolean)render);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static int mediacodec_jni_releaseOutputBufferAtTime(FFAMediaCodec *ctx, size_t idx, int64_t timestampNs)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.release_output_buffer_at_time_id, (jint)idx, (jlong)timestampNs);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static ssize_t mediacodec_jni_dequeueInputBuffer(FFAMediaCodec* ctx, int64_t timeoutUs)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    ret = (*env)->CallIntMethod(env, codec->object, codec->jfields.dequeue_input_buffer_id, timeoutUs);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static int mediacodec_jni_queueInputBuffer(FFAMediaCodec* ctx, size_t idx, off_t offset, size_t size, uint64_t time, uint32_t flags)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.queue_input_buffer_id, (jint)idx, (jint)offset, (jint)size, time, flags);
    if ((ret = ff_jni_exception_check(env, 1, codec)) < 0) {
        ret = AVERROR_EXTERNAL;
        goto fail;
    }

fail:
    return ret;
}

static ssize_t mediacodec_jni_dequeueOutputBuffer(FFAMediaCodec* ctx, FFAMediaCodecBufferInfo *info, int64_t timeoutUs)
{
    int ret = 0;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    ret = (*env)->CallIntMethod(env, codec->object, codec->jfields.dequeue_output_buffer_id, codec->buffer_info, timeoutUs);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        return AVERROR_EXTERNAL;
    }

    info->flags = (*env)->GetIntField(env, codec->buffer_info, codec->jfields.flags_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        return AVERROR_EXTERNAL;
    }

    info->offset = (*env)->GetIntField(env, codec->buffer_info, codec->jfields.offset_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        return AVERROR_EXTERNAL;
    }

    info->presentationTimeUs = (*env)->GetLongField(env, codec->buffer_info, codec->jfields.presentation_time_us_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        return AVERROR_EXTERNAL;
    }

    info->size = (*env)->GetIntField(env, codec->buffer_info, codec->jfields.size_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        return AVERROR_EXTERNAL;
    }

    return ret;
}

static uint8_t* mediacodec_jni_getInputBuffer(FFAMediaCodec* ctx, size_t idx, size_t *out_size)
{
    uint8_t *ret = NULL;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    jobject buffer = NULL;
    jobject input_buffers = NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, NULL);

    if (codec->has_get_i_o_buffer) {
        buffer = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_input_buffer_id, (jint)idx);
        if (ff_jni_exception_check(env, 1, codec) < 0) {
            goto fail;
        }
    } else {
        if (!codec->input_buffers) {
            input_buffers = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_input_buffers_id);
            if (ff_jni_exception_check(env, 1, codec) < 0) {
                goto fail;
            }

            codec->input_buffers = (*env)->NewGlobalRef(env, input_buffers);
            if (ff_jni_exception_check(env, 1, codec) < 0) {
                goto fail;
            }
        }

        buffer = (*env)->GetObjectArrayElement(env, codec->input_buffers, idx);
        if (ff_jni_exception_check(env, 1, codec) < 0) {
            goto fail;
        }
    }

    ret = (*env)->GetDirectBufferAddress(env, buffer);
    *out_size = (*env)->GetDirectBufferCapacity(env, buffer);
fail:
    if (buffer) {
        (*env)->DeleteLocalRef(env, buffer);
    }

    if (input_buffers) {
        (*env)->DeleteLocalRef(env, input_buffers);
    }

    return ret;
}

static uint8_t* mediacodec_jni_getOutputBuffer(FFAMediaCodec* ctx, size_t idx, size_t *out_size)
{
    uint8_t *ret = NULL;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    jobject buffer = NULL;
    jobject output_buffers = NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, NULL);

    if (codec->has_get_i_o_buffer) {
        buffer = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_output_buffer_id, (jint)idx);
        if (ff_jni_exception_check(env, 1, codec) < 0) {
            goto fail;
        }
    } else {
        if (!codec->output_buffers) {
            output_buffers = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_output_buffers_id);
            if (ff_jni_exception_check(env, 1, codec) < 0) {
                goto fail;
            }

            codec->output_buffers = (*env)->NewGlobalRef(env, output_buffers);
            if (ff_jni_exception_check(env, 1, codec) < 0) {
                goto fail;
            }
        }

        buffer = (*env)->GetObjectArrayElement(env, codec->output_buffers, idx);
        if (ff_jni_exception_check(env, 1, codec) < 0) {
            goto fail;
        }
    }

    ret = (*env)->GetDirectBufferAddress(env, buffer);
    *out_size = (*env)->GetDirectBufferCapacity(env, buffer);
fail:
    if (buffer) {
        (*env)->DeleteLocalRef(env, buffer);
    }

    if (output_buffers) {
        (*env)->DeleteLocalRef(env, output_buffers);
    }

    return ret;
}

static FFAMediaFormat* mediacodec_jni_getOutputFormat(FFAMediaCodec* ctx)
{
    FFAMediaFormat *ret = NULL;
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    jobject mediaformat = NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, NULL);

    mediaformat = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_output_format_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        goto fail;
    }

    ret = mediaformat_jni_newFromObject(mediaformat);
fail:
    if (mediaformat) {
        (*env)->DeleteLocalRef(env, mediaformat);
    }

    return ret;
}

static int mediacodec_jni_infoTryAgainLater(FFAMediaCodec *ctx, ssize_t idx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return idx == codec->INFO_TRY_AGAIN_LATER;
}

static int mediacodec_jni_infoOutputBuffersChanged(FFAMediaCodec *ctx, ssize_t idx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return idx == codec->INFO_OUTPUT_BUFFERS_CHANGED;
}

static int mediacodec_jni_infoOutputFormatChanged(FFAMediaCodec *ctx, ssize_t idx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return idx == codec->INFO_OUTPUT_FORMAT_CHANGED;
}

static int mediacodec_jni_getBufferFlagCodecConfig(FFAMediaCodec *ctx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return codec->BUFFER_FLAG_CODEC_CONFIG;
}

static int mediacodec_jni_getBufferFlagEndOfStream(FFAMediaCodec *ctx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return codec->BUFFER_FLAG_END_OF_STREAM;
}

static int mediacodec_jni_getBufferFlagKeyFrame(FFAMediaCodec *ctx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return codec->BUFFER_FLAG_KEY_FRAME;
}

static int mediacodec_jni_getConfigureFlagEncode(FFAMediaCodec *ctx)
{
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;
    return codec->CONFIGURE_FLAG_ENCODE;
}

static int mediacodec_jni_cleanOutputBuffers(FFAMediaCodec *ctx)
{
    int ret = 0;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    if (!codec->has_get_i_o_buffer) {
        if (codec->output_buffers) {
            JNIEnv *env = NULL;

            env = ff_jni_get_env(codec);
            if (!env) {
                ret = AVERROR_EXTERNAL;
                goto fail;
            }

            (*env)->DeleteGlobalRef(env, codec->output_buffers);
            codec->output_buffers = NULL;
        }
    }

fail:
    return ret;
}

static int mediacodec_jni_signalEndOfInputStream(FFAMediaCodec *ctx)
{
    JNIEnv *env = NULL;
    FFAMediaCodecJni *codec = (FFAMediaCodecJni *)ctx;

    JNI_GET_ENV_OR_RETURN(env, codec, AVERROR_EXTERNAL);

    (*env)->CallVoidMethod(env, codec->object, codec->jfields.signal_end_of_input_stream_id);
    if (ff_jni_exception_check(env, 1, codec) < 0) {
        return AVERROR_EXTERNAL;
    }

    return 0;
}

static const FFAMediaFormat media_format_jni = {
    .class = &amediaformat_class,

    .create = mediaformat_jni_new,
    .delete = mediaformat_jni_delete,

    .toString = mediaformat_jni_toString,

    .getInt32 = mediaformat_jni_getInt32,
    .getInt64 = mediaformat_jni_getInt64,
    .getFloat = mediaformat_jni_getFloat,
    .getBuffer = mediaformat_jni_getBuffer,
    .getString = mediaformat_jni_getString,

    .setInt32 = mediaformat_jni_setInt32,
    .setInt64 = mediaformat_jni_setInt64,
    .setFloat = mediaformat_jni_setFloat,
    .setString = mediaformat_jni_setString,
    .setBuffer = mediaformat_jni_setBuffer,
};

static const FFAMediaCodec media_codec_jni = {
    .class = &amediacodec_class,

    .getName = mediacodec_jni_getName,

    .createCodecByName = mediacodec_jni_createCodecByName,
    .createDecoderByType = mediacodec_jni_createDecoderByType,
    .createEncoderByType = mediacodec_jni_createEncoderByType,
    .delete = mediacodec_jni_delete,

    .configure = mediacodec_jni_configure,
    .start = mediacodec_jni_start,
    .stop = mediacodec_jni_stop,
    .flush = mediacodec_jni_flush,

    .getInputBuffer = mediacodec_jni_getInputBuffer,
    .getOutputBuffer = mediacodec_jni_getOutputBuffer,

    .dequeueInputBuffer = mediacodec_jni_dequeueInputBuffer,
    .queueInputBuffer = mediacodec_jni_queueInputBuffer,

    .dequeueOutputBuffer = mediacodec_jni_dequeueOutputBuffer,
    .getOutputFormat = mediacodec_jni_getOutputFormat,

    .releaseOutputBuffer = mediacodec_jni_releaseOutputBuffer,
    .releaseOutputBufferAtTime = mediacodec_jni_releaseOutputBufferAtTime,

    .infoTryAgainLater = mediacodec_jni_infoTryAgainLater,
    .infoOutputBuffersChanged = mediacodec_jni_infoOutputBuffersChanged,
    .infoOutputFormatChanged = mediacodec_jni_infoOutputFormatChanged,

    .getBufferFlagCodecConfig = mediacodec_jni_getBufferFlagCodecConfig,
    .getBufferFlagEndOfStream = mediacodec_jni_getBufferFlagEndOfStream,
    .getBufferFlagKeyFrame = mediacodec_jni_getBufferFlagKeyFrame,

    .getConfigureFlagEncode = mediacodec_jni_getConfigureFlagEncode,
    .cleanOutputBuffers = mediacodec_jni_cleanOutputBuffers,
    .signalEndOfInputStream = mediacodec_jni_signalEndOfInputStream,
};

typedef struct FFAMediaFormatNdk {
    FFAMediaFormat api;

    void *libmedia;
    AMediaFormat *impl;

    AMediaFormat *(*new)(void);
    media_status_t (*delete)(AMediaFormat*);

    const char* (*toString)(AMediaFormat*);

    bool (*getInt32)(AMediaFormat*, const char *name, int32_t *out);
    bool (*getInt64)(AMediaFormat*, const char *name, int64_t *out);
    bool (*getFloat)(AMediaFormat*, const char *name, float *out);
    bool (*getSize)(AMediaFormat*, const char *name, size_t *out);
    bool (*getBuffer)(AMediaFormat*, const char *name, void** data, size_t *size);
    bool (*getString)(AMediaFormat*, const char *name, const char **out);
    bool (*getRect)(AMediaFormat *, const char *name,
                    int32_t *left, int32_t *top, int32_t *right, int32_t *bottom);

    void (*setInt32)(AMediaFormat*, const char* name, int32_t value);
    void (*setInt64)(AMediaFormat*, const char* name, int64_t value);
    void (*setFloat)(AMediaFormat*, const char* name, float value);
    void (*setString)(AMediaFormat*, const char* name, const char* value);
    void (*setBuffer)(AMediaFormat*, const char* name, const void* data, size_t size);
    void (*setRect)(AMediaFormat *, const char *name,
                    int32_t left, int32_t top, int32_t right, int32_t bottom);
} FFAMediaFormatNdk;

typedef struct FFAMediaCodecNdk {
    FFAMediaCodec api;

    void *libmedia;
    AMediaCodec *impl;
    ANativeWindow *window;

    AMediaCodec* (*createCodecByName)(const char *name);
    AMediaCodec* (*createDecoderByType)(const char *mime_type);
    AMediaCodec* (*createEncoderByType)(const char *mime_type);
    media_status_t (*delete)(AMediaCodec*);

    media_status_t (*configure)(AMediaCodec *,
                                const AMediaFormat *format,
                                ANativeWindow *surface,
                                AMediaCrypto *crypto,
                                uint32_t flags);
    media_status_t (*start)(AMediaCodec*);
    media_status_t (*stop)(AMediaCodec*);
    media_status_t (*flush)(AMediaCodec*);

    uint8_t* (*getInputBuffer)(AMediaCodec*, size_t idx, size_t *out_size);
    uint8_t* (*getOutputBuffer)(AMediaCodec*, size_t idx, size_t *out_size);

    ssize_t (*dequeueInputBuffer)(AMediaCodec*, int64_t timeoutUs);
    media_status_t (*queueInputBuffer)(AMediaCodec*, size_t idx,
                                       long offset, size_t size,
                                       uint64_t time, uint32_t flags);

    ssize_t (*dequeueOutputBuffer)(AMediaCodec*, AMediaCodecBufferInfo *info, int64_t timeoutUs);
    AMediaFormat* (*getOutputFormat)(AMediaCodec*);

    media_status_t (*releaseOutputBuffer)(AMediaCodec*, size_t idx, bool render);
    media_status_t (*releaseOutputBufferAtTime)(AMediaCodec *mData, size_t idx, int64_t timestampNs);

    // Available since API level 28.
    media_status_t (*getName)(AMediaCodec*, char** out_name);
    void (*releaseName)(AMediaCodec*, char* name);

    // Available since API level 26.
    media_status_t (*setInputSurface)(AMediaCodec*, ANativeWindow *);
    media_status_t (*signalEndOfInputStream)(AMediaCodec *);
} FFAMediaCodecNdk;

static const FFAMediaFormat media_format_ndk;
static const FFAMediaCodec media_codec_ndk;

static const AVClass amediaformat_ndk_class = {
    .class_name = "amediaformat_ndk",
    .item_name  = av_default_item_name,
    .version    = LIBAVUTIL_VERSION_INT,
};

static const AVClass amediacodec_ndk_class = {
    .class_name = "amediacodec_ndk",
    .item_name  = av_default_item_name,
    .version    = LIBAVUTIL_VERSION_INT,
};

static FFAMediaFormat *mediaformat_ndk_create(AMediaFormat *impl)
{
    FFAMediaFormatNdk *format = av_mallocz(sizeof(*format));
    if (!format)
        return NULL;

    format->api = media_format_ndk;

    format->libmedia = dlopen("libmediandk.so", RTLD_NOW);
    if (!format->libmedia)
        goto error;

#define GET_OPTIONAL_SYMBOL(sym) \
    format->sym = dlsym(format->libmedia, "AMediaFormat_" #sym);

#define GET_SYMBOL(sym)         \
    GET_OPTIONAL_SYMBOL(sym)    \
    if (!format->sym)           \
        goto error;

    GET_SYMBOL(new)
    GET_SYMBOL(delete)

    GET_SYMBOL(toString)

    GET_SYMBOL(getInt32)
    GET_SYMBOL(getInt64)
    GET_SYMBOL(getFloat)
    GET_SYMBOL(getSize)
    GET_SYMBOL(getBuffer)
    GET_SYMBOL(getString)
    GET_OPTIONAL_SYMBOL(getRect)

    GET_SYMBOL(setInt32)
    GET_SYMBOL(setInt64)
    GET_SYMBOL(setFloat)
    GET_SYMBOL(setString)
    GET_SYMBOL(setBuffer)
    GET_OPTIONAL_SYMBOL(setRect)

#undef GET_SYMBOL
#undef GET_OPTIONAL_SYMBOL

    if (impl) {
        format->impl = impl;
    } else {
        format->impl = format->new();
        if (!format->impl)
            goto error;
    }

    return (FFAMediaFormat *)format;

error:
    if (format->libmedia)
        dlclose(format->libmedia);
    av_freep(&format);
    return NULL;
}

static FFAMediaFormat *mediaformat_ndk_new(void)
{
    return mediaformat_ndk_create(NULL);
}

static int mediaformat_ndk_delete(FFAMediaFormat* ctx)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    int ret = 0;
    if (!format)
        return 0;

    av_assert0(format->api.class == &amediaformat_ndk_class);

    if (format->impl && (format->delete(format->impl) != AMEDIA_OK))
            ret = AVERROR_EXTERNAL;
    if (format->libmedia)
        dlclose(format->libmedia);
    av_free(format);

    return ret;
}

static char* mediaformat_ndk_toString(FFAMediaFormat* ctx)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    const char *str = format->toString(format->impl);
    return av_strdup(str);
}

static int mediaformat_ndk_getInt32(FFAMediaFormat* ctx, const char *name, int32_t *out)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    return format->getInt32(format->impl, name, out);
}

static int mediaformat_ndk_getInt64(FFAMediaFormat* ctx, const char *name, int64_t *out)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    return format->getInt64(format->impl, name, out);
}

static int mediaformat_ndk_getFloat(FFAMediaFormat* ctx, const char *name, float *out)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    return format->getFloat(format->impl, name, out);
}

static int mediaformat_ndk_getBuffer(FFAMediaFormat* ctx, const char *name, void** data, size_t *size)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    return format->getBuffer(format->impl, name, data, size);
}

static int mediaformat_ndk_getString(FFAMediaFormat* ctx, const char *name, const char **out)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    const char *tmp = NULL;
    int ret = format->getString(format->impl, name, &tmp);

    if (tmp)
        *out = av_strdup(tmp);
    return ret;
}

static int mediaformat_ndk_getRect(FFAMediaFormat *ctx, const char *name,
                                   int32_t *left, int32_t *top, int32_t *right, int32_t *bottom)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    if (!format->getRect)
        return AVERROR_EXTERNAL;
    return format->getRect(format->impl, name, left, top, right, bottom);
}

static void mediaformat_ndk_setInt32(FFAMediaFormat* ctx, const char* name, int32_t value)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    format->setInt32(format->impl, name, value);
}

static void mediaformat_ndk_setInt64(FFAMediaFormat* ctx, const char* name, int64_t value)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    format->setInt64(format->impl, name, value);
}

static void mediaformat_ndk_setFloat(FFAMediaFormat* ctx, const char* name, float value)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    format->setFloat(format->impl, name, value);
}

static void mediaformat_ndk_setString(FFAMediaFormat* ctx, const char* name, const char* value)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    format->setString(format->impl, name, value);
}

static void mediaformat_ndk_setBuffer(FFAMediaFormat* ctx, const char* name, void* data, size_t size)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    format->setBuffer(format->impl, name, data, size);
}

static void mediaformat_ndk_setRect(FFAMediaFormat *ctx, const char *name,
                                     int32_t left, int32_t top, int32_t right, int32_t bottom)
{
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)ctx;
    if (!format->setRect) {
        av_log(ctx, AV_LOG_WARNING, "Doesn't support setRect\n");
        return;
    }
    format->setRect(format->impl, name, left, top, right, bottom);
}

static char *mediacodec_ndk_getName(FFAMediaCodec *ctx)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    char *ret = NULL;
    char *name = NULL;

    if (!codec->getName || !codec->releaseName) {
        av_log(ctx, AV_LOG_DEBUG, "getName() unavailable\n");
        return ret;
    }

    codec->getName(codec->impl, &name);
    if (name) {
        ret = av_strdup(name);
        codec->releaseName(codec->impl, name);
    }

    return ret;
}

static inline FFAMediaCodec *ndk_codec_create(int method, const char *arg) {
    FFAMediaCodecNdk *codec = av_mallocz(sizeof(*codec));
    const char *lib_name = "libmediandk.so";

    if (!codec)
        return NULL;

    codec->api = media_codec_ndk;
    codec->libmedia = dlopen(lib_name, RTLD_NOW);
    if (!codec->libmedia)
        goto error;

#define GET_SYMBOL(sym, required)                                   \
    codec->sym = dlsym(codec->libmedia, "AMediaCodec_" #sym);       \
    if (!codec->sym) {                                              \
        av_log(codec, required ? AV_LOG_ERROR : AV_LOG_INFO,        \
               #sym "() unavailable from %s\n", lib_name);          \
        if (required)                                               \
            goto error;                                             \
    }

    GET_SYMBOL(createCodecByName, 1)
    GET_SYMBOL(createDecoderByType, 1)
    GET_SYMBOL(createEncoderByType, 1)
    GET_SYMBOL(delete, 1)

    GET_SYMBOL(configure, 1)
    GET_SYMBOL(start, 1)
    GET_SYMBOL(stop, 1)
    GET_SYMBOL(flush, 1)

    GET_SYMBOL(getInputBuffer, 1)
    GET_SYMBOL(getOutputBuffer, 1)

    GET_SYMBOL(dequeueInputBuffer, 1)
    GET_SYMBOL(queueInputBuffer, 1)

    GET_SYMBOL(dequeueOutputBuffer, 1)
    GET_SYMBOL(getOutputFormat, 1)

    GET_SYMBOL(releaseOutputBuffer, 1)
    GET_SYMBOL(releaseOutputBufferAtTime, 1)

    GET_SYMBOL(getName, 0)
    GET_SYMBOL(releaseName, 0)

    GET_SYMBOL(setInputSurface, 0)
    GET_SYMBOL(signalEndOfInputStream, 0)

#undef GET_SYMBOL

    switch (method) {
    case CREATE_CODEC_BY_NAME:
        codec->impl = codec->createCodecByName(arg);
        break;
    case CREATE_DECODER_BY_TYPE:
        codec->impl = codec->createDecoderByType(arg);
        break;
    case CREATE_ENCODER_BY_TYPE:
        codec->impl = codec->createEncoderByType(arg);
        break;
    default:
        av_assert0(0);
    }
    if (!codec->impl)
        goto error;

    return (FFAMediaCodec *)codec;

error:
    if (codec->libmedia)
        dlclose(codec->libmedia);
    av_freep(&codec);
    return NULL;
}

#define DECLARE_NDK_AMEDIACODEC_CREATE_FUNC(name, method)       \
static FFAMediaCodec *mediacodec_ndk_##name(const char *arg)    \
{                                                               \
    return ndk_codec_create(method, arg);                       \
}                                                               \

DECLARE_NDK_AMEDIACODEC_CREATE_FUNC(createCodecByName,   CREATE_CODEC_BY_NAME)
DECLARE_NDK_AMEDIACODEC_CREATE_FUNC(createDecoderByType, CREATE_DECODER_BY_TYPE)
DECLARE_NDK_AMEDIACODEC_CREATE_FUNC(createEncoderByType, CREATE_ENCODER_BY_TYPE)

static int mediacodec_ndk_delete(FFAMediaCodec* ctx)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    int ret = 0;

    if (!codec)
        return 0;

    av_assert0(codec->api.class == &amediacodec_ndk_class);

    if (codec->impl && (codec->delete(codec->impl) != AMEDIA_OK))
        ret = AVERROR_EXTERNAL;
    if (codec->window)
        ANativeWindow_release(codec->window);
    if (codec->libmedia)
        dlclose(codec->libmedia);
    av_free(codec);

    return ret;
}

static int mediacodec_ndk_configure(FFAMediaCodec* ctx,
                                    const FFAMediaFormat* format_ctx,
                                    FFANativeWindow* window,
                                    void *crypto,
                                    uint32_t flags)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    FFAMediaFormatNdk *format = (FFAMediaFormatNdk *)format_ctx;
    media_status_t status;
    ANativeWindow *native_window = NULL;

    if (window) {
        if (window->surface) {
            JNIEnv *env = NULL;
            JNI_GET_ENV_OR_RETURN(env, ctx, -1);
            native_window = ANativeWindow_fromSurface(env, window->surface);
            // Save for release
            codec->window = native_window;
        } else if (window->native_window) {
            native_window = window->native_window;
        }
    }

    if (format_ctx->class != &amediaformat_ndk_class) {
        av_log(ctx, AV_LOG_ERROR, "invalid media format\n");
        return AVERROR(EINVAL);
    }

    if (flags & AMEDIACODEC_CONFIGURE_FLAG_ENCODE) {
        if (native_window && !codec->setInputSurface) {
            av_log(ctx, AV_LOG_ERROR, "System doesn't support setInputSurface\n");
            return AVERROR_EXTERNAL;
        }

        status = codec->configure(codec->impl, format->impl, NULL, NULL, flags);
        if (status != AMEDIA_OK) {
            av_log(codec, AV_LOG_ERROR, "Encoder configure failed, %d\n", status);
            return AVERROR_EXTERNAL;
        }

        if (!native_window)
            return 0;

        status = codec->setInputSurface(codec->impl, native_window);
        if (status != AMEDIA_OK) {
            av_log(codec, AV_LOG_ERROR, "Encoder set input surface failed, %d\n", status);
            return AVERROR_EXTERNAL;
        }
    } else {
        status = codec->configure(codec->impl, format->impl, native_window, NULL, flags);
        if (status != AMEDIA_OK) {
            av_log(codec, AV_LOG_ERROR, "Decoder configure failed, %d\n", status);
            return AVERROR_EXTERNAL;
        }
    }

    return 0;
}

#define MEDIACODEC_NDK_WRAPPER(method)                                   \
static int mediacodec_ndk_ ## method(FFAMediaCodec* ctx)                 \
{                                                                        \
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;                   \
    media_status_t status = codec->method(codec->impl);                  \
                                                                         \
    if (status != AMEDIA_OK) {                                           \
        av_log(codec, AV_LOG_ERROR, #method " failed, %d\n", status);    \
        return AVERROR_EXTERNAL;                                         \
    }                                                                    \
                                                                         \
    return 0;                                                            \
}                                                                        \

MEDIACODEC_NDK_WRAPPER(start)
MEDIACODEC_NDK_WRAPPER(stop)
MEDIACODEC_NDK_WRAPPER(flush)

static uint8_t* mediacodec_ndk_getInputBuffer(FFAMediaCodec* ctx, size_t idx, size_t *out_size)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    return codec->getInputBuffer(codec->impl, idx, out_size);
}

static uint8_t* mediacodec_ndk_getOutputBuffer(FFAMediaCodec* ctx, size_t idx, size_t *out_size)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    return codec->getOutputBuffer(codec->impl, idx, out_size);
}

static ssize_t mediacodec_ndk_dequeueInputBuffer(FFAMediaCodec* ctx, int64_t timeoutUs)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    return codec->dequeueInputBuffer(codec->impl, timeoutUs);
}

static int mediacodec_ndk_queueInputBuffer(FFAMediaCodec *ctx, size_t idx,
                                           off_t offset, size_t size,
                                           uint64_t time, uint32_t flags)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    return codec->queueInputBuffer(codec->impl, idx, offset, size, time, flags);
}

static ssize_t mediacodec_ndk_dequeueOutputBuffer(FFAMediaCodec* ctx, FFAMediaCodecBufferInfo *info, int64_t timeoutUs)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    AMediaCodecBufferInfo buf_info = {0};
    ssize_t ret;

    ret = codec->dequeueOutputBuffer(codec->impl, &buf_info, timeoutUs);
    info->offset = buf_info.offset;
    info->size = buf_info.size;
    info->presentationTimeUs = buf_info.presentationTimeUs;
    info->flags = buf_info.flags;

    return ret;
}

static FFAMediaFormat* mediacodec_ndk_getOutputFormat(FFAMediaCodec* ctx)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    AMediaFormat *format = codec->getOutputFormat(codec->impl);

    if (!format)
        return NULL;
    return mediaformat_ndk_create(format);
}

static int mediacodec_ndk_releaseOutputBuffer(FFAMediaCodec* ctx, size_t idx, int render)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    media_status_t status;

    status = codec->releaseOutputBuffer(codec->impl, idx, render);
    if (status != AMEDIA_OK) {
        av_log(codec, AV_LOG_ERROR, "release output buffer failed, %d\n", status);
        return AVERROR_EXTERNAL;
    }

    return 0;
}

static int mediacodec_ndk_releaseOutputBufferAtTime(FFAMediaCodec *ctx, size_t idx, int64_t timestampNs)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    media_status_t status;

    status = codec->releaseOutputBufferAtTime(codec->impl, idx, timestampNs);
    if (status != AMEDIA_OK) {
        av_log(codec, AV_LOG_ERROR, "releaseOutputBufferAtTime failed, %d\n", status);
        return AVERROR_EXTERNAL;
    }

    return 0;
}

static int mediacodec_ndk_infoTryAgainLater(FFAMediaCodec *ctx, ssize_t idx)
{
    return idx == AMEDIACODEC_INFO_TRY_AGAIN_LATER;
}

static int mediacodec_ndk_infoOutputBuffersChanged(FFAMediaCodec *ctx, ssize_t idx)
{
    return idx == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED;
}

static int mediacodec_ndk_infoOutputFormatChanged(FFAMediaCodec *ctx, ssize_t idx)
{
    return idx == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED;
}

static int mediacodec_ndk_getBufferFlagCodecConfig(FFAMediaCodec *ctx)
{
    return AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG;
}

static int mediacodec_ndk_getBufferFlagEndOfStream(FFAMediaCodec *ctx)
{
    return AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM;
}

static int mediacodec_ndk_getBufferFlagKeyFrame(FFAMediaCodec *ctx)
{
    return 1;
}

static int mediacodec_ndk_getConfigureFlagEncode(FFAMediaCodec *ctx)
{
    return AMEDIACODEC_CONFIGURE_FLAG_ENCODE;
}

static int mediacodec_ndk_cleanOutputBuffers(FFAMediaCodec *ctx)
{
    return 0;
}

static int mediacodec_ndk_signalEndOfInputStream(FFAMediaCodec *ctx)
{
    FFAMediaCodecNdk *codec = (FFAMediaCodecNdk *)ctx;
    media_status_t status;

    if (!codec->signalEndOfInputStream) {
        av_log(codec, AV_LOG_ERROR, "signalEndOfInputStream unavailable\n");
        return AVERROR_EXTERNAL;
    }

    status = codec->signalEndOfInputStream(codec->impl);
    if (status != AMEDIA_OK) {
        av_log(codec, AV_LOG_ERROR, "signalEndOfInputStream failed, %d\n", status);
        return AVERROR_EXTERNAL;
    }
    av_log(codec, AV_LOG_DEBUG, "signalEndOfInputStream success\n");

    return 0;
}

static const FFAMediaFormat media_format_ndk = {
    .class = &amediaformat_ndk_class,

    .create = mediaformat_ndk_new,
    .delete = mediaformat_ndk_delete,

    .toString = mediaformat_ndk_toString,

    .getInt32 = mediaformat_ndk_getInt32,
    .getInt64 = mediaformat_ndk_getInt64,
    .getFloat = mediaformat_ndk_getFloat,
    .getBuffer = mediaformat_ndk_getBuffer,
    .getString = mediaformat_ndk_getString,
    .getRect = mediaformat_ndk_getRect,

    .setInt32 = mediaformat_ndk_setInt32,
    .setInt64 = mediaformat_ndk_setInt64,
    .setFloat = mediaformat_ndk_setFloat,
    .setString = mediaformat_ndk_setString,
    .setBuffer = mediaformat_ndk_setBuffer,
    .setRect = mediaformat_ndk_setRect,
};

static const FFAMediaCodec media_codec_ndk = {
    .class = &amediacodec_ndk_class,

    .getName = mediacodec_ndk_getName,

    .createCodecByName = mediacodec_ndk_createCodecByName,
    .createDecoderByType = mediacodec_ndk_createDecoderByType,
    .createEncoderByType = mediacodec_ndk_createEncoderByType,
    .delete = mediacodec_ndk_delete,

    .configure = mediacodec_ndk_configure,
    .start = mediacodec_ndk_start,
    .stop = mediacodec_ndk_stop,
    .flush = mediacodec_ndk_flush,

    .getInputBuffer = mediacodec_ndk_getInputBuffer,
    .getOutputBuffer = mediacodec_ndk_getOutputBuffer,

    .dequeueInputBuffer = mediacodec_ndk_dequeueInputBuffer,
    .queueInputBuffer = mediacodec_ndk_queueInputBuffer,

    .dequeueOutputBuffer = mediacodec_ndk_dequeueOutputBuffer,
    .getOutputFormat = mediacodec_ndk_getOutputFormat,

    .releaseOutputBuffer = mediacodec_ndk_releaseOutputBuffer,
    .releaseOutputBufferAtTime = mediacodec_ndk_releaseOutputBufferAtTime,

    .infoTryAgainLater = mediacodec_ndk_infoTryAgainLater,
    .infoOutputBuffersChanged = mediacodec_ndk_infoOutputBuffersChanged,
    .infoOutputFormatChanged = mediacodec_ndk_infoOutputFormatChanged,

    .getBufferFlagCodecConfig = mediacodec_ndk_getBufferFlagCodecConfig,
    .getBufferFlagEndOfStream = mediacodec_ndk_getBufferFlagEndOfStream,
    .getBufferFlagKeyFrame = mediacodec_ndk_getBufferFlagKeyFrame,

    .getConfigureFlagEncode = mediacodec_ndk_getConfigureFlagEncode,
    .cleanOutputBuffers = mediacodec_ndk_cleanOutputBuffers,
    .signalEndOfInputStream = mediacodec_ndk_signalEndOfInputStream,
};

FFAMediaFormat *ff_AMediaFormat_new(int ndk)
{
    if (ndk)
        return media_format_ndk.create();
    return media_format_jni.create();
}

FFAMediaCodec* ff_AMediaCodec_createCodecByName(const char *name, int ndk)
{
    if (ndk)
        return media_codec_ndk.createCodecByName(name);
    return media_codec_jni.createCodecByName(name);
}

FFAMediaCodec* ff_AMediaCodec_createDecoderByType(const char *mime_type, int ndk)
{
   if (ndk)
        return media_codec_ndk.createDecoderByType(mime_type);
    return media_codec_jni.createDecoderByType(mime_type);
}

FFAMediaCodec* ff_AMediaCodec_createEncoderByType(const char *mime_type, int ndk)
{
    if (ndk)
        return media_codec_ndk.createEncoderByType(mime_type);
    return media_codec_jni.createEncoderByType(mime_type);
}

int ff_Build_SDK_INT(AVCodecContext *avctx)
{
    int ret = -1;

#if __ANDROID_API__ >= 24
    // android_get_device_api_level() is a static inline before API level 29.
    // dlsym() might doesn't work.
    //
    // We can implement android_get_device_api_level() by
    // __system_property_get(), but __system_property_get() has created a lot of
    // troubles and is deprecated. So avoid using __system_property_get() for
    // now.
    //
    // Hopy we can remove the conditional compilation finally by bumping the
    // required API level.
    //
    ret = android_get_device_api_level();
#else
    JNIEnv *env = NULL;
    jclass versionClass;
    jfieldID sdkIntFieldID;
    JNI_GET_ENV_OR_RETURN(env, avctx, -1);

    versionClass = (*env)->FindClass(env, "android/os/Build$VERSION");
    sdkIntFieldID = (*env)->GetStaticFieldID(env, versionClass, "SDK_INT", "I");
    ret = (*env)->GetStaticIntField(env, versionClass, sdkIntFieldID);
    (*env)->DeleteLocalRef(env, versionClass);
#endif
    av_log(avctx, AV_LOG_DEBUG, "device api level %d\n", ret);

    return ret;
}

static struct {
    enum FFAMediaFormatColorRange mf_range;
    enum AVColorRange range;
} color_range_map[] = {
    { COLOR_RANGE_FULL,     AVCOL_RANGE_JPEG },
    { COLOR_RANGE_LIMITED,  AVCOL_RANGE_MPEG },
};

static struct {
    enum FFAMediaFormatColorStandard mf_standard;
    enum AVColorSpace space;
} color_space_map[] = {
    { COLOR_STANDARD_BT709,         AVCOL_SPC_BT709         },
    { COLOR_STANDARD_BT601_PAL,     AVCOL_SPC_BT470BG       },
    { COLOR_STANDARD_BT601_NTSC,    AVCOL_SPC_SMPTE170M     },
    { COLOR_STANDARD_BT2020,        AVCOL_SPC_BT2020_NCL    },
};

static struct {
    enum FFAMediaFormatColorStandard mf_standard;
    enum AVColorPrimaries primaries;
} color_primaries_map[] = {
    { COLOR_STANDARD_BT709,         AVCOL_PRI_BT709     },
    { COLOR_STANDARD_BT601_PAL,     AVCOL_PRI_BT470BG   },
    { COLOR_STANDARD_BT601_NTSC,    AVCOL_PRI_SMPTE170M },
    { COLOR_STANDARD_BT2020,        AVCOL_PRI_BT2020    },
};

static struct {
    enum FFAMediaFormatColorTransfer mf_transfer;
    enum AVColorTransferCharacteristic transfer;
} color_transfer_map[] = {
    { COLOR_TRANSFER_LINEAR,        AVCOL_TRC_LINEAR        },
    { COLOR_TRANSFER_SDR_VIDEO,     AVCOL_TRC_SMPTE170M     },
    { COLOR_TRANSFER_ST2084,        AVCOL_TRC_SMPTEST2084   },
    { COLOR_TRANSFER_HLG,           AVCOL_TRC_ARIB_STD_B67  },
};

enum AVColorRange ff_AMediaFormatColorRange_to_AVColorRange(int color_range)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_range_map); i++)
        if (color_range_map[i].mf_range == color_range)
            return color_range_map[i].range;

    return AVCOL_RANGE_UNSPECIFIED;
}

int ff_AMediaFormatColorRange_from_AVColorRange(enum AVColorRange color_range)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_range_map); i++)
        if (color_range_map[i].range == color_range)
            return color_range_map[i].mf_range;
    return COLOR_RANGE_UNSPECIFIED;
}

enum AVColorSpace ff_AMediaFormatColorStandard_to_AVColorSpace(int color_standard)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_space_map); i++)
        if (color_space_map[i].mf_standard == color_standard)
            return color_space_map[i].space;

    return AVCOL_SPC_UNSPECIFIED;
}

int ff_AMediaFormatColorStandard_from_AVColorSpace(enum AVColorSpace color_space)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_space_map); i++)
        if (color_space_map[i].space == color_space)
            return color_space_map[i].mf_standard;

    return COLOR_STANDARD_UNSPECIFIED;
}

enum AVColorPrimaries ff_AMediaFormatColorStandard_to_AVColorPrimaries(int color_standard)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_primaries_map); i++)
        if (color_primaries_map[i].mf_standard == color_standard)
            return color_primaries_map[i].primaries;

    return AVCOL_PRI_UNSPECIFIED;
}

enum AVColorTransferCharacteristic
ff_AMediaFormatColorTransfer_to_AVColorTransfer(int color_transfer)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_transfer_map); i++)
        if (color_transfer_map[i].mf_transfer == color_transfer)
            return color_transfer_map[i].transfer;

    return AVCOL_TRC_UNSPECIFIED;
}

int ff_AMediaFormatColorTransfer_from_AVColorTransfer(
    enum AVColorTransferCharacteristic color_transfer)
{
    for (int i = 0; i < FF_ARRAY_ELEMS(color_transfer_map); i++)
        if (color_transfer_map[i].transfer == color_transfer)
            return color_transfer_map[i].mf_transfer;

    return COLOR_TRANSFER_UNSPECIFIED;
}