summaryrefslogtreecommitdiffstats
path: root/libhb/common.c
blob: 50b596a987593934aa46e30f75fc37a9d5b1fdc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
/* common.c

   Copyright (c) 2003-2016 HandBrake Team
   This file is part of the HandBrake source code
   Homepage: <http://handbrake.fr/>.
   It may be used under the terms of the GNU General Public License v2.
   For full terms see the file COPYING file or visit http://www.gnu.org/licenses/gpl-2.0.html
 */

#include <stdarg.h>
#include <time.h>
#include <ctype.h>
#include <sys/time.h>

#include "hb.h"
#include "x264.h"
#include "lang.h"
#include "common.h"
#include "h264_common.h"
#include "h265_common.h"
#include "encx264.h"
#ifdef USE_QSV
#include "qsv_common.h"
#endif

#ifdef USE_X265
#include "x265.h"
#endif

#ifdef SYS_MINGW
#include <windows.h>
#endif

static int mixdown_get_opus_coupled_stream_count(int mixdown);

/**********************************************************************
 * Global variables
 *********************************************************************/
static hb_error_handler_t *error_handler = NULL;

/* Generic IDs for encoders, containers, etc. */
enum
{
    HB_GID_NONE = -1, // encoders must NEVER use it
    HB_GID_VCODEC_H264,
    HB_GID_VCODEC_H265,
    HB_GID_VCODEC_MPEG2,
    HB_GID_VCODEC_MPEG4,
    HB_GID_VCODEC_THEORA,
    HB_GID_VCODEC_VP8,
    HB_GID_VCODEC_VP9,
    HB_GID_ACODEC_AAC,
    HB_GID_ACODEC_AAC_HE,
    HB_GID_ACODEC_AAC_PASS,
    HB_GID_ACODEC_AC3,
    HB_GID_ACODEC_AC3_PASS,
    HB_GID_ACODEC_AUTO_PASS,
    HB_GID_ACODEC_DTS_PASS,
    HB_GID_ACODEC_DTSHD_PASS,
    HB_GID_ACODEC_EAC3,
    HB_GID_ACODEC_EAC3_PASS,
    HB_GID_ACODEC_FLAC,
    HB_GID_ACODEC_FLAC_PASS,
    HB_GID_ACODEC_MP3,
    HB_GID_ACODEC_MP3_PASS,
    HB_GID_ACODEC_TRUEHD_PASS,
    HB_GID_ACODEC_VORBIS,
    HB_GID_ACODEC_OPUS,
    HB_GID_MUX_MKV,
    HB_GID_MUX_MP4,
};

#define HB_VIDEO_CLOCK    27000000 // 27MHz clock
#define HB_VIDEO_FPS_MIN  1
#define HB_VIDEO_FPS_MAX  1000
int hb_video_rate_clock = HB_VIDEO_CLOCK;
int hb_video_rate_min   = HB_VIDEO_CLOCK / HB_VIDEO_FPS_MAX; // Min clock rate from *max* frame rate
int hb_video_rate_max   = HB_VIDEO_CLOCK / HB_VIDEO_FPS_MIN; // Max clock rate from *min* frame rate

typedef struct
{
    hb_rate_t  item;
    hb_rate_t *next;
    int enabled;
} hb_rate_internal_t;
hb_rate_t *hb_video_rates_first_item = NULL;
hb_rate_t *hb_video_rates_last_item  = NULL;
hb_rate_internal_t hb_video_rates[]  =
{
    // legacy framerates (disabled)
    { { "23.976 (NTSC Film)",  1126125, }, NULL, 0, },
    { { "25 (PAL Film/Video)", 1080000, }, NULL, 0, },
    { { "29.97 (NTSC Video)",   900900, }, NULL, 0, },
    // actual framerates
    { {  "5",                  5400000, }, NULL, 1, },
    { { "10",                  2700000, }, NULL, 1, },
    { { "12",                  2250000, }, NULL, 1, },
    { { "15",                  1800000, }, NULL, 1, },
    { { "20",                  1350000, }, NULL, 1, },
    { { "23.976",              1126125, }, NULL, 1, },
    { { "24",                  1125000, }, NULL, 1, },
    { { "25",                  1080000, }, NULL, 1, },
    { { "29.97",                900900, }, NULL, 1, },
    { { "30",                   900000, }, NULL, 1, },
    { { "48",                   562500, }, NULL, 1, },
    { { "50",                   540000, }, NULL, 1, },
    { { "59.94",                450450, }, NULL, 1, },
    { { "60",                   450000, }, NULL, 1, },
    { { "72",                   375000, }, NULL, 1, },
    { { "75",                   360000, }, NULL, 1, },
    { { "90",                   300000, }, NULL, 1, },
    { { "100",                  270000, }, NULL, 1, },
    { { "120",                  225000, }, NULL, 1, },
};
int hb_video_rates_count = sizeof(hb_video_rates) / sizeof(hb_video_rates[0]);

hb_rate_t *hb_audio_rates_first_item = NULL;
hb_rate_t *hb_audio_rates_last_item  = NULL;
hb_rate_internal_t hb_audio_rates[]  =
{
    { {  "8",      8000, }, NULL, 1, },
    { { "11.025", 11025, }, NULL, 1, },
    { { "12",     12000, }, NULL, 1, },
    { { "16",     16000, }, NULL, 1, },
    { { "22.05",  22050, }, NULL, 1, },
    { { "24",     24000, }, NULL, 1, },
    { { "32",     32000, }, NULL, 1, },
    { { "44.1",   44100, }, NULL, 1, },
    { { "48",     48000, }, NULL, 1, },
};
int hb_audio_rates_count = sizeof(hb_audio_rates) / sizeof(hb_audio_rates[0]);

hb_rate_t *hb_audio_bitrates_first_item = NULL;
hb_rate_t *hb_audio_bitrates_last_item  = NULL;
hb_rate_internal_t hb_audio_bitrates[]  =
{
    // AC3-compatible bitrates
    { {   "32",   32, }, NULL, 1, },
    { {   "40",   40, }, NULL, 1, },
    { {   "48",   48, }, NULL, 1, },
    { {   "56",   56, }, NULL, 1, },
    { {   "64",   64, }, NULL, 1, },
    { {   "80",   80, }, NULL, 1, },
    { {   "96",   96, }, NULL, 1, },
    { {  "112",  112, }, NULL, 1, },
    { {  "128",  128, }, NULL, 1, },
    { {  "160",  160, }, NULL, 1, },
    { {  "192",  192, }, NULL, 1, },
    { {  "224",  224, }, NULL, 1, },
    { {  "256",  256, }, NULL, 1, },
    { {  "320",  320, }, NULL, 1, },
    { {  "384",  384, }, NULL, 1, },
    { {  "448",  448, }, NULL, 1, },
    { {  "512",  512, }, NULL, 1, },
    { {  "576",  576, }, NULL, 1, },
    { {  "640",  640, }, NULL, 1, },
    // additional bitrates
    { {  "768",  768, }, NULL, 1, },
    { {  "960",  960, }, NULL, 1, },
    { { "1152", 1152, }, NULL, 1, },
    { { "1344", 1344, }, NULL, 1, },
    { { "1536", 1536, }, NULL, 1, },
    { { "2304", 2304, }, NULL, 1, },
    { { "3072", 3072, }, NULL, 1, },
    { { "4608", 4608, }, NULL, 1, },
    { { "6144", 6144, }, NULL, 1, },
};
int hb_audio_bitrates_count = sizeof(hb_audio_bitrates) / sizeof(hb_audio_bitrates[0]);

typedef struct
{
    hb_dither_t  item;
    hb_dither_t *next;
    int enabled;
} hb_dither_internal_t;
hb_dither_t *hb_audio_dithers_first_item = NULL;
hb_dither_t *hb_audio_dithers_last_item  = NULL;
hb_dither_internal_t hb_audio_dithers[]  =
{
    { { "default",                       "auto",          AV_RESAMPLE_DITHER_NONE - 1,      }, NULL, 1, },
    { { "none",                          "none",          AV_RESAMPLE_DITHER_NONE,          }, NULL, 1, },
    { { "rectangular",                   "rectangular",   AV_RESAMPLE_DITHER_RECTANGULAR,   }, NULL, 1, },
    { { "triangular",                    "triangular",    AV_RESAMPLE_DITHER_TRIANGULAR,    }, NULL, 1, },
    { { "triangular with high pass",     "triangular_hp", AV_RESAMPLE_DITHER_TRIANGULAR_HP, }, NULL, 1, },
    { { "triangular with noise shaping", "triangular_ns", AV_RESAMPLE_DITHER_TRIANGULAR_NS, }, NULL, 1, },
};
int hb_audio_dithers_count = sizeof(hb_audio_dithers) / sizeof(hb_audio_dithers[0]);

typedef struct
{
    hb_mixdown_t  item;
    hb_mixdown_t *next;
    int enabled;
} hb_mixdown_internal_t;
hb_mixdown_t *hb_audio_mixdowns_first_item = NULL;
hb_mixdown_t *hb_audio_mixdowns_last_item  = NULL;
hb_mixdown_internal_t hb_audio_mixdowns[]  =
{
    // legacy mixdowns, back to HB 0.9.4 whenever possible (disabled)
    { { "AC3 Passthru",       "",           HB_AMIXDOWN_NONE,      }, NULL, 0, },
    { { "DTS Passthru",       "",           HB_AMIXDOWN_NONE,      }, NULL, 0, },
    { { "DTS-HD Passthru",    "",           HB_AMIXDOWN_NONE,      }, NULL, 0, },
    { { "6-channel discrete", "6ch",        HB_AMIXDOWN_5POINT1,   }, NULL, 0, },
    // actual mixdowns
    { { "None",               "none",       HB_AMIXDOWN_NONE,      }, NULL, 1, },
    { { "Mono",               "mono",       HB_AMIXDOWN_MONO,      }, NULL, 1, },
    { { "Mono (Left Only)",   "left_only",  HB_AMIXDOWN_LEFT,      }, NULL, 1, },
    { { "Mono (Right Only)",  "right_only", HB_AMIXDOWN_RIGHT,     }, NULL, 1, },
    { { "Stereo",             "stereo",     HB_AMIXDOWN_STEREO,    }, NULL, 1, },
    { { "Dolby Surround",     "dpl1",       HB_AMIXDOWN_DOLBY,     }, NULL, 1, },
    { { "Dolby Pro Logic II", "dpl2",       HB_AMIXDOWN_DOLBYPLII, }, NULL, 1, },
    { { "5.1 Channels",       "5point1",    HB_AMIXDOWN_5POINT1,   }, NULL, 1, },
    { { "6.1 Channels",       "6point1",    HB_AMIXDOWN_6POINT1,   }, NULL, 1, },
    { { "7.1 Channels",       "7point1",    HB_AMIXDOWN_7POINT1,   }, NULL, 1, },
    { { "7.1 (5F/2R/LFE)",    "5_2_lfe",    HB_AMIXDOWN_5_2_LFE,   }, NULL, 1, },
};
int hb_audio_mixdowns_count = sizeof(hb_audio_mixdowns) / sizeof(hb_audio_mixdowns[0]);

typedef struct
{
    hb_encoder_t  item;
    hb_encoder_t *next;
    int enabled;
    int gid;
} hb_encoder_internal_t;
hb_encoder_t *hb_video_encoders_first_item = NULL;
hb_encoder_t *hb_video_encoders_last_item  = NULL;
hb_encoder_internal_t hb_video_encoders[]  =
{
    // legacy encoders, back to HB 0.9.4 whenever possible (disabled)
    { { "FFmpeg",              "ffmpeg",     NULL,                      HB_VCODEC_FFMPEG_MPEG4, HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_VCODEC_MPEG4,  },
    { { "MPEG-4 (FFmpeg)",     "ffmpeg4",    NULL,                      HB_VCODEC_FFMPEG_MPEG4, HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_VCODEC_MPEG4,  },
    { { "MPEG-2 (FFmpeg)",     "ffmpeg2",    NULL,                      HB_VCODEC_FFMPEG_MPEG2, HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_VCODEC_MPEG2,  },
    { { "VP3 (Theora)",        "libtheora",  NULL,                      HB_VCODEC_THEORA,                       HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_VCODEC_THEORA, },
    // actual encoders
    { { "H.264 (x264)",        "x264",       "H.264 (libx264)",         HB_VCODEC_X264_8BIT,         HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_H264,   },
    { { "H.264 10-bit (x264)", "x264_10bit", "H.264 10-bit (libx264)",  HB_VCODEC_X264_10BIT,   HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_H264,   },
    { { "H.264 (Intel QSV)",   "qsv_h264",   "H.264 (Intel Media SDK)", HB_VCODEC_QSV_H264,     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_H264,   },
    { { "H.265 (x265)",        "x265",       "H.265 (libx265)",         HB_VCODEC_X265_8BIT,      HB_MUX_AV_MP4|HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_VCODEC_H265,   },
    { { "H.265 10-bit (x265)", "x265_10bit", "H.265 10-bit (libx265)",  HB_VCODEC_X265_10BIT,     HB_MUX_AV_MP4|HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_VCODEC_H265,   },
    { { "H.265 12-bit (x265)", "x265_12bit", "H.265 12-bit (libx265)",  HB_VCODEC_X265_12BIT,     HB_MUX_AV_MP4|HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_VCODEC_H265,   },
    { { "H.265 16-bit (x265)", "x265_16bit", "H.265 16-bit (libx265)",  HB_VCODEC_X265_16BIT,     HB_MUX_AV_MP4|HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_VCODEC_H265,   },
    { { "H.265 (Intel QSV)",   "qsv_h265",   "H.265 (Intel Media SDK)", HB_VCODEC_QSV_H265,     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_H265,   },
    { { "MPEG-4",              "mpeg4",      "MPEG-4 (libavcodec)",     HB_VCODEC_FFMPEG_MPEG4, HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_MPEG4,  },
    { { "MPEG-2",              "mpeg2",      "MPEG-2 (libavcodec)",     HB_VCODEC_FFMPEG_MPEG2, HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_MPEG2,  },
    { { "VP8",                 "VP8",        "VP8 (libvpx)",            HB_VCODEC_FFMPEG_VP8,                   HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_VP8,    },
    { { "VP9",                 "VP9",        "VP9 (libvpx)",            HB_VCODEC_FFMPEG_VP9,                   HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_VP9,    },
    { { "Theora",              "theora",     "Theora (libtheora)",      HB_VCODEC_THEORA,                       HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_VCODEC_THEORA, },
};
int hb_video_encoders_count = sizeof(hb_video_encoders) / sizeof(hb_video_encoders[0]);
static int hb_video_encoder_is_enabled(int encoder)
{
#ifdef USE_QSV
    if (encoder & HB_VCODEC_QSV_MASK)
    {
        return hb_qsv_video_encoder_is_enabled(encoder);
    }
#endif
    switch (encoder)
    {
        // the following encoders are always enabled
        case HB_VCODEC_THEORA:
        case HB_VCODEC_FFMPEG_MPEG4:
        case HB_VCODEC_FFMPEG_MPEG2:
        case HB_VCODEC_FFMPEG_VP8:
        case HB_VCODEC_FFMPEG_VP9:
            return 1;

#ifdef USE_X265
        case HB_VCODEC_X265_8BIT:
        case HB_VCODEC_X265_10BIT:
        case HB_VCODEC_X265_12BIT:
        case HB_VCODEC_X265_16BIT:
        {
            const x265_api *api;
            api = x265_api_query(hb_video_encoder_get_depth(encoder), X265_BUILD, NULL);
            return (api != NULL);
        };
#endif

        case HB_VCODEC_X264_8BIT:
        case HB_VCODEC_X264_10BIT:
        {
            const x264_api_t *api;
            api = hb_x264_api_get(hb_video_encoder_get_depth(encoder));
            return (api != NULL);
        }

        default:
            return 0;
    }
}

hb_encoder_t *hb_audio_encoders_first_item = NULL;
hb_encoder_t *hb_audio_encoders_last_item  = NULL;
hb_encoder_internal_t hb_audio_encoders[]  =
{
    // legacy encoders, back to HB 0.9.4 whenever possible (disabled)
    { { "",                   "dts",        NULL,                          HB_ACODEC_DCA_PASS,    HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_DTS_PASS,   },
    { { "AAC (faac)",         "faac",       NULL,                          0,                     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_AAC,        },
    { { "AAC (ffmpeg)",       "ffaac",      NULL,                          HB_ACODEC_FFAAC,       HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_AAC,        },
    { { "AC3 (ffmpeg)",       "ffac3",      NULL,                          HB_ACODEC_AC3,         HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_AC3,        },
    { { "MP3 (lame)",         "lame",       NULL,                          HB_ACODEC_LAME,        HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_MP3,        },
    { { "Vorbis (vorbis)",    "libvorbis",  NULL,                          HB_ACODEC_VORBIS,                      HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_VORBIS,     },
    { { "FLAC (ffmpeg)",      "ffflac",     NULL,                          HB_ACODEC_FFFLAC,                      HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_FLAC,       },
    { { "FLAC (24-bit)",      "ffflac24",   NULL,                          HB_ACODEC_FFFLAC24,                    HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_FLAC,       },
    // generic names
    { { "AAC",                "aac",        NULL,                          0,                     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_AAC,        },
    { { "HE-AAC",             "haac",       NULL,                          0,                     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 0, HB_GID_ACODEC_AAC_HE,     },
    // actual encoders
    { { "AAC (CoreAudio)",    "ca_aac",     "AAC (Apple AudioToolbox)",    HB_ACODEC_CA_AAC,      HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AAC,        },
    { { "HE-AAC (CoreAudio)", "ca_haac",    "HE-AAC (Apple AudioToolbox)", HB_ACODEC_CA_HAAC,     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AAC_HE,     },
    { { "AAC (FDK)",          "fdk_aac",    "AAC (libfdk_aac)",            HB_ACODEC_FDK_AAC,     HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AAC,        },
    { { "HE-AAC (FDK)",       "fdk_haac",   "HE-AAC (libfdk_aac)",         HB_ACODEC_FDK_HAAC,    HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AAC_HE,     },
    { { "AAC (avcodec)",      "av_aac",     "AAC (libavcodec)",            HB_ACODEC_FFAAC,       HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AAC,        },
    { { "AAC Passthru",       "copy:aac",   "AAC Passthru",                HB_ACODEC_AAC_PASS,    HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AAC_PASS,   },
    { { "AC3",                "ac3",        "AC3 (libavcodec)",            HB_ACODEC_AC3,         HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AC3,        },
    { { "AC3 Passthru",       "copy:ac3",   "AC3 Passthru",                HB_ACODEC_AC3_PASS,    HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AC3_PASS,   },
    { { "E-AC3",              "eac3",       "E-AC3 (libavcodec)",          HB_ACODEC_FFEAC3,                      HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_ACODEC_EAC3,       },
    { { "E-AC3 Passthru",     "copy:eac3",  "E-AC3 Passthru",              HB_ACODEC_EAC3_PASS,                   HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_ACODEC_EAC3_PASS,  },
    { { "TrueHD Passthru",    "copy:truehd","TrueHD Passthru",             HB_ACODEC_TRUEHD_PASS,                 HB_MUX_AV_MKV,   }, NULL, 1, HB_GID_ACODEC_TRUEHD_PASS,},
    { { "DTS Passthru",       "copy:dts",   "DTS Passthru",                HB_ACODEC_DCA_PASS,    HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_DTS_PASS,   },
    { { "DTS-HD Passthru",    "copy:dtshd", "DTS-HD Passthru",             HB_ACODEC_DCA_HD_PASS, HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_DTSHD_PASS, },
    { { "MP3",                "mp3",        "MP3 (libmp3lame)",            HB_ACODEC_LAME,        HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_MP3,        },
    { { "MP3 Passthru",       "copy:mp3",   "MP3 Passthru",                HB_ACODEC_MP3_PASS,    HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_MP3_PASS,   },
    { { "Vorbis",             "vorbis",     "Vorbis (libvorbis)",          HB_ACODEC_VORBIS,                      HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_VORBIS,     },
    { { "FLAC 16-bit",        "flac16",     "FLAC 16-bit (libavcodec)",    HB_ACODEC_FFFLAC,                      HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_FLAC,       },
    { { "FLAC 24-bit",        "flac24",     "FLAC 24-bit (libavcodec)",    HB_ACODEC_FFFLAC24,                    HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_FLAC,       },
    { { "FLAC Passthru",      "copy:flac",  "FLAC Passthru",               HB_ACODEC_FLAC_PASS,                   HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_FLAC_PASS,  },
    { { "Opus",               "opus",     "Opus (libopus)",                HB_ACODEC_OPUS,                        HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_OPUS,     },
    { { "Auto Passthru",      "copy",       "Auto Passthru",               HB_ACODEC_AUTO_PASS,   HB_MUX_MASK_MP4|HB_MUX_MASK_MKV, }, NULL, 1, HB_GID_ACODEC_AUTO_PASS,  },
};
int hb_audio_encoders_count = sizeof(hb_audio_encoders) / sizeof(hb_audio_encoders[0]);
static int hb_audio_encoder_is_enabled(int encoder)
{
    if (encoder & HB_ACODEC_PASS_FLAG)
    {
        // Passthru encoders are always enabled
        return 1;
    }
    switch (encoder)
    {
#ifdef __APPLE__
        case HB_ACODEC_CA_AAC:
        case HB_ACODEC_CA_HAAC:
            return 1;
#endif

#ifdef USE_LIBAV_AAC
        case HB_ACODEC_FFAAC:
            return avcodec_find_encoder_by_name("aac") != NULL;
#endif

        case HB_ACODEC_FDK_AAC:
        case HB_ACODEC_FDK_HAAC:
            return avcodec_find_encoder_by_name("libfdk_aac") != NULL;

        case HB_ACODEC_AC3:
            return avcodec_find_encoder(AV_CODEC_ID_AC3) != NULL;

        case HB_ACODEC_FFEAC3:
            return avcodec_find_encoder(AV_CODEC_ID_EAC3) != NULL;

        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
            return avcodec_find_encoder(AV_CODEC_ID_FLAC) != NULL;

        case HB_ACODEC_OPUS:
            return avcodec_find_encoder(AV_CODEC_ID_OPUS) != NULL;

        // the following encoders are always enabled
        case HB_ACODEC_LAME:
        case HB_ACODEC_VORBIS:
            return 1;

        default:
            return 0;
    }
}

typedef struct
{
    hb_container_t  item;
    hb_container_t *next;
    int enabled;
    int gid;
} hb_container_internal_t;
hb_container_t *hb_containers_first_item = NULL;
hb_container_t *hb_containers_last_item  = NULL;
hb_container_internal_t hb_containers[]  =
{
    // legacy muxers, back to HB 0.9.4 whenever possible (disabled)
    { { "M4V file",            "m4v",    NULL,                     "m4v",  0,             }, NULL, 0, HB_GID_MUX_MP4, },
    { { "MP4 file",            "mp4",    NULL,                     "mp4",  0,             }, NULL, 0, HB_GID_MUX_MP4, },
    { { "MKV file",            "mkv",    NULL,                     "mkv",  0,             }, NULL, 0, HB_GID_MUX_MKV, },
    // actual muxers
    { { "MPEG-4 (avformat)",   "av_mp4", "MPEG-4 (libavformat)",   "mp4",  HB_MUX_AV_MP4, }, NULL, 1, HB_GID_MUX_MP4, },
    { { "MPEG-4 (mp4v2)",      "mp4v2",  "MPEG-4 (libmp4v2)",      "mp4",  HB_MUX_MP4V2,  }, NULL, 1, HB_GID_MUX_MP4, },
    { { "Matroska (avformat)", "av_mkv", "Matroska (libavformat)", "mkv",  HB_MUX_AV_MKV, }, NULL, 1, HB_GID_MUX_MKV, },
    { { "Matroska (libmkv)",   "libmkv", "Matroska (libmkv)",      "mkv",  HB_MUX_LIBMKV, }, NULL, 1, HB_GID_MUX_MKV, },
};
int hb_containers_count = sizeof(hb_containers) / sizeof(hb_containers[0]);
static int hb_container_is_enabled(int format)
{
    switch (format)
    {
        case HB_MUX_AV_MP4:
        case HB_MUX_AV_MKV:
            return 1;

        default:
            return 0;
    }
}

void hb_common_global_init()
{
    static int common_init_done = 0;
    if (common_init_done)
        return;

    int i, j;

    // video framerates
    for (i = 0; i < hb_video_rates_count; i++)
    {
        if (hb_video_rates[i].enabled)
        {
            if (hb_video_rates_first_item == NULL)
            {
                hb_video_rates_first_item = &hb_video_rates[i].item;
            }
            else
            {
                ((hb_rate_internal_t*)hb_video_rates_last_item)->next =
                    &hb_video_rates[i].item;
            }
            hb_video_rates_last_item = &hb_video_rates[i].item;
        }
    }
    // fallbacks are static for now (no setup required)

    // audio samplerates
    for (i = 0; i < hb_audio_rates_count; i++)
    {
        if (hb_audio_rates[i].enabled)
        {
            if (hb_audio_rates_first_item == NULL)
            {
                hb_audio_rates_first_item = &hb_audio_rates[i].item;
            }
            else
            {
                ((hb_rate_internal_t*)hb_audio_rates_last_item)->next =
                    &hb_audio_rates[i].item;
            }
            hb_audio_rates_last_item = &hb_audio_rates[i].item;
        }
    }
    // fallbacks are static for now (no setup required)

    // audio bitrates
    for (i = 0; i < hb_audio_bitrates_count; i++)
    {
        if (hb_audio_bitrates[i].enabled)
        {
            if (hb_audio_bitrates_first_item == NULL)
            {
                hb_audio_bitrates_first_item = &hb_audio_bitrates[i].item;
            }
            else
            {
                ((hb_rate_internal_t*)hb_audio_bitrates_last_item)->next =
                    &hb_audio_bitrates[i].item;
            }
            hb_audio_bitrates_last_item = &hb_audio_bitrates[i].item;
        }
    }
    // fallbacks are static for now (no setup required)

    // audio dithers
    for (i = 0; i < hb_audio_dithers_count; i++)
    {
        if (hb_audio_dithers[i].enabled)
        {
            if (hb_audio_dithers_first_item == NULL)
            {
                hb_audio_dithers_first_item = &hb_audio_dithers[i].item;
            }
            else
            {
                ((hb_dither_internal_t*)hb_audio_dithers_last_item)->next =
                    &hb_audio_dithers[i].item;
            }
            hb_audio_dithers_last_item = &hb_audio_dithers[i].item;
        }
    }
    // fallbacks are static for now (no setup required)

    // audio mixdowns
    for (i = 0; i < hb_audio_mixdowns_count; i++)
    {
        if (hb_audio_mixdowns[i].enabled)
        {
            if (hb_audio_mixdowns_first_item == NULL)
            {
                hb_audio_mixdowns_first_item = &hb_audio_mixdowns[i].item;
            }
            else
            {
                ((hb_mixdown_internal_t*)hb_audio_mixdowns_last_item)->next =
                    &hb_audio_mixdowns[i].item;
            }
            hb_audio_mixdowns_last_item = &hb_audio_mixdowns[i].item;
        }
    }
    // fallbacks are static for now (no setup required)

    // video encoders
    for (i = 0; i < hb_video_encoders_count; i++)
    {
        if (hb_video_encoders[i].enabled)
        {
            // we still need to check
            hb_video_encoders[i].enabled =
                hb_video_encoder_is_enabled(hb_video_encoders[i].item.codec);
        }
        if (hb_video_encoders[i].enabled)
        {
            if (hb_video_encoders_first_item == NULL)
            {
                hb_video_encoders_first_item = &hb_video_encoders[i].item;
            }
            else
            {
                ((hb_encoder_internal_t*)hb_video_encoders_last_item)->next =
                    &hb_video_encoders[i].item;
            }
            hb_video_encoders_last_item = &hb_video_encoders[i].item;
        }
    }
    // setup fallbacks
    for (i = 0; i < hb_video_encoders_count; i++)
    {
        if (!hb_video_encoders[i].enabled)
        {
            if ((hb_video_encoders[i].item.codec & HB_VCODEC_MASK) &&
                (hb_video_encoder_is_enabled(hb_video_encoders[i].item.codec)))
            {
                // we have a specific fallback and it's enabled
                continue;
            }
            for (j = 0; j < hb_video_encoders_count; j++)
            {
                if (hb_video_encoders[j].enabled &&
                    hb_video_encoders[j].gid == hb_video_encoders[i].gid)
                {
                    hb_video_encoders[i].item.codec = hb_video_encoders[j].item.codec;
                    break;
                }
            }
        }
    }

    // audio encoders
    for (i = 0; i < hb_audio_encoders_count; i++)
    {
        if (hb_audio_encoders[i].enabled)
        {
            // we still need to check
            hb_audio_encoders[i].enabled =
                hb_audio_encoder_is_enabled(hb_audio_encoders[i].item.codec);
        }
        if (hb_audio_encoders[i].enabled)
        {
            if (hb_audio_encoders_first_item == NULL)
            {
                hb_audio_encoders_first_item = &hb_audio_encoders[i].item;
            }
            else
            {
                ((hb_encoder_internal_t*)hb_audio_encoders_last_item)->next =
                    &hb_audio_encoders[i].item;
            }
            hb_audio_encoders_last_item = &hb_audio_encoders[i].item;
        }
    }
    // setup fallbacks
    for (i = 0; i < hb_audio_encoders_count; i++)
    {
        if (!hb_audio_encoders[i].enabled)
        {
            if ((hb_audio_encoders[i].item.codec & HB_ACODEC_MASK) &&
                (hb_audio_encoder_is_enabled(hb_audio_encoders[i].item.codec)))
            {
                // we have a specific fallback and it's enabled
                continue;
            }
            for (j = 0; j < hb_audio_encoders_count; j++)
            {
                if (hb_audio_encoders[j].enabled &&
                    hb_audio_encoders[j].gid == hb_audio_encoders[i].gid)
                {
                    hb_audio_encoders[i].item.codec = hb_audio_encoders[j].item.codec;
                    break;
                }
            }
            if (hb_audio_encoders[i].gid == HB_GID_ACODEC_AAC_HE)
            {
                // try to find an AAC fallback if no HE-AAC encoder is available
                for (j = 0; j < hb_audio_encoders_count; j++)
                {
                    if (hb_audio_encoders[j].enabled &&
                        hb_audio_encoders[j].gid == HB_GID_ACODEC_AAC)
                    {
                        hb_audio_encoders[i].item.codec = hb_audio_encoders[j].item.codec;
                        break;
                    }
                }
            }
        }
    }

    // video containers
    for (i = 0; i < hb_containers_count; i++)
    {
        if (hb_containers[i].enabled)
        {
            // we still need to check
            hb_containers[i].enabled =
                hb_container_is_enabled(hb_containers[i].item.format);
        }
        if (hb_containers[i].enabled)
        {
            if (hb_containers_first_item == NULL)
            {
                hb_containers_first_item = &hb_containers[i].item;
            }
            else
            {
                ((hb_container_internal_t*)hb_containers_last_item)->next =
                    &hb_containers[i].item;
            }
            hb_containers_last_item = &hb_containers[i].item;
        }
    }
    // setup fallbacks
    for (i = 0; i < hb_containers_count; i++)
    {
        if (!hb_containers[i].enabled)
        {
            if ((hb_containers[i].item.format & HB_MUX_MASK) &&
                (hb_container_is_enabled(hb_containers[i].item.format)))
            {
                // we have a specific fallback and it's enabled
                continue;
            }
            for (j = 0; j < hb_containers_count; j++)
            {
                if (hb_containers[j].enabled &&
                    hb_containers[j].gid == hb_containers[i].gid)
                {
                    hb_containers[i].item.format = hb_containers[j].item.format;
                    break;
                }
            }
        }
    }

    // we're done, yay!
    common_init_done = 1;
}

int hb_video_framerate_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_video_rates_count; i++)
    {
        if (!strcasecmp(hb_video_rates[i].item.name, name))
        {
            return hb_video_rates[i].item.rate;
        }
    }

fail:
    return -1;
}

const char* hb_video_framerate_get_name(int framerate)
{
    if (framerate > hb_video_rates_first_item->rate ||
        framerate < hb_video_rates_last_item ->rate)
        goto fail;

    const hb_rate_t *video_framerate = NULL;
    while ((video_framerate = hb_video_framerate_get_next(video_framerate)) != NULL)
    {
        if (video_framerate->rate == framerate)
        {
            return video_framerate->name;
        }
    }

fail:
    return NULL;
}

const char* hb_video_framerate_sanitize_name(const char *name)
{
    return hb_video_framerate_get_name(hb_video_framerate_get_from_name(name));
}

void hb_video_framerate_get_limits(int *low, int *high, int *clock)
{
    *low   = hb_video_rate_min;
    *high  = hb_video_rate_max;
    *clock = hb_video_rate_clock;
}

const hb_rate_t* hb_video_framerate_get_next(const hb_rate_t *last)
{
    if (last == NULL)
    {
        return hb_video_rates_first_item;
    }
    return ((hb_rate_internal_t*)last)->next;
}

int hb_video_framerate_get_close(hb_rational_t *framerate, double thresh)
{
    double            fps_in;
    const hb_rate_t * rate = NULL;
    int               result = -1;
    double            closest = thresh;

    fps_in = (double)framerate->num / framerate->den;
    while ((rate = hb_video_framerate_get_next(rate)) != NULL)
    {
        double fps = (double)hb_video_rate_clock / rate->rate;
        if (ABS(fps - fps_in) < closest)
        {
            result = rate->rate;
            closest = ABS(fps - fps_in);
        }
    }
    return result;
}

int hb_audio_samplerate_is_supported(int samplerate, uint32_t codec)
{
    switch (codec)
    {
        case HB_ACODEC_AC3:
        case HB_ACODEC_FFEAC3:
        case HB_ACODEC_CA_HAAC:
            // ca_haac can't do samplerates < 32 kHz
            // libav's E-AC-3 encoder can't do samplerates < 32 kHz
            // AC-3 < 32 kHz suffers from poor hardware compatibility
            if (samplerate < 32000)
                return 0;
            else
                return 1;
        case HB_ACODEC_FDK_HAAC:
            // fdk_haac can't do samplerates < 16 kHz
            if (samplerate < 16000)
                return 0;
             else
                return 1;
        case HB_ACODEC_OPUS:
            switch (samplerate)
            {
                // Opus only supports samplerates 8kHz, 12kHz, 16kHz,
                // 24kHz, 48kHz
                case 8000:
                case 12000:
                case 16000:
                case 24000:
                case 48000:
                    return 1;
                default:
                    return 0;
            }
        default:
            return 1;
    }
}

int hb_audio_samplerate_get_sr_shift(int samplerate)
{
    /* sr_shift: 0 -> 48000, 44100, 32000 Hz
     *           1 -> 24000, 22050, 16000 Hz
     *           2 -> 12000, 11025,  8000 Hz
     *
     * also, since samplerates are sanitized downwards:
     *
     * (samplerate < 32000) implies (samplerate <= 24000)
     */
    return ((samplerate < 16000) ? 2 : (samplerate < 32000) ? 1 : 0);
}

int hb_audio_samplerate_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_audio_rates_count; i++)
    {
        if (!strcasecmp(hb_audio_rates[i].item.name, name))
        {
            return hb_audio_rates[i].item.rate;
        }
    }

    // maybe the samplerate was specified in Hz
    i = atoi(name);
    if (i >= hb_audio_rates_first_item->rate &&
        i <= hb_audio_rates_last_item ->rate)
    {
        return hb_audio_samplerate_find_closest(i, HB_ACODEC_INVALID);
    }

fail:
    return -1;
}

const char* hb_audio_samplerate_get_name(int samplerate)
{
    if (samplerate < hb_audio_rates_first_item->rate ||
        samplerate > hb_audio_rates_last_item ->rate)
        goto fail;

    const hb_rate_t *audio_samplerate = NULL;
    while ((audio_samplerate = hb_audio_samplerate_get_next(audio_samplerate)) != NULL)
    {
        if (audio_samplerate->rate == samplerate)
        {
            return audio_samplerate->name;
        }
    }

fail:
    return NULL;
}

const hb_rate_t* hb_audio_samplerate_get_next(const hb_rate_t *last)
{
    if (last == NULL)
    {
        return hb_audio_rates_first_item;
    }
    return ((hb_rate_internal_t*)last)->next;
}

const hb_rate_t* hb_audio_samplerate_get_next_for_codec(const hb_rate_t *last,
                                                        uint32_t codec)
{
    while ((last = hb_audio_samplerate_get_next(last)) != NULL)
        if (hb_audio_samplerate_is_supported(last->rate, codec))
            return last;

    // None found or end of list
    return NULL;
}

int hb_audio_samplerate_find_closest(int samplerate, uint32_t codec)
{
    const hb_rate_t * rate, * prev, * next;

    rate = prev = next = hb_audio_samplerate_get_next_for_codec(NULL, codec);
    while (rate != NULL && next->rate < samplerate)
    {
        rate = hb_audio_samplerate_get_next_for_codec(rate, codec);
        if (rate != NULL)
        {
            prev = next;
            next = rate;
        }
    }

    int delta_prev = samplerate - prev->rate;
    int delta_next = next->rate - samplerate;
    if (delta_prev <= delta_next)
    {
        return prev->rate;
    }
    else
    {
        return next->rate;
    }
}

// Given an input bitrate, find closest match in the set of allowed bitrates
static int hb_audio_bitrate_find_closest(int bitrate)
{
    // Check if bitrate mode was disabled
    if (bitrate <= 0)
        return bitrate;

    int closest_bitrate            = hb_audio_bitrates_first_item->rate;
    const hb_rate_t *audio_bitrate = NULL;
    while ((audio_bitrate = hb_audio_bitrate_get_next(audio_bitrate)) != NULL)
    {
        if (bitrate == audio_bitrate->rate)
        {
            // valid bitrate
            closest_bitrate = audio_bitrate->rate;
            break;
        }
        if (bitrate > audio_bitrate->rate)
        {
            // bitrates are sanitized downwards
            closest_bitrate = audio_bitrate->rate;
        }
    }
    return closest_bitrate;
}

// Given an input bitrate, sanitize it.
// Check low and high limits and make sure it is in the set of allowed bitrates.
int hb_audio_bitrate_get_best(uint32_t codec, int bitrate, int samplerate,
                              int mixdown)
{
    int low, high;
    hb_audio_bitrate_get_limits(codec, samplerate, mixdown, &low, &high);
    if (bitrate > high)
        bitrate = high;
    if (bitrate < low)
        bitrate = low;
    return hb_audio_bitrate_find_closest(bitrate);
}

// Get the default bitrate for a given codec/samplerate/mixdown triplet.
int hb_audio_bitrate_get_default(uint32_t codec, int samplerate, int mixdown)
{
    if ((codec & HB_ACODEC_PASS_FLAG) || !(codec & HB_ACODEC_MASK))
        goto fail;

    int bitrate, nchannels, nlfe, sr_shift;
    /* full-bandwidth channels, sr_shift */
    nlfe      = hb_mixdown_get_low_freq_channel_count(mixdown);
    nchannels = hb_mixdown_get_discrete_channel_count(mixdown) - nlfe;
    sr_shift  = hb_audio_samplerate_get_sr_shift(samplerate);

    switch (codec)
    {
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
            goto fail;

        // 96, 224, 640 Kbps
        case HB_ACODEC_AC3:
            bitrate = (nchannels * 128) - (32 * (nchannels < 5));
            break;

        // Our E-AC-3 encoder is pretty similar to our AC-3 encoder but it does
        // allow for higher bitrates, should some users want a bit more quality
        // at the expense of compression efficiency - still, let's remain
        // compatible with passthru over S/PDIF by default: 384, 768, 1536 Kbps
        case HB_ACODEC_FFEAC3:
            bitrate = (nchannels * 384) - (128 * (nchannels - 2) * (nchannels > 2));
            break;

        case HB_ACODEC_CA_HAAC:
        case HB_ACODEC_FDK_HAAC:
            bitrate = nchannels * 32;
            break;

        case HB_ACODEC_OPUS:
        {
            int coupled = mixdown_get_opus_coupled_stream_count(mixdown);
            int uncoupled = nchannels + nlfe - 2 * coupled;

            bitrate = coupled * 96 + uncoupled * 64;
        } break;

        default:
            bitrate = nchannels * 80;
            break;
    }
    // sample_rate adjustment
    bitrate >>= sr_shift;
    return hb_audio_bitrate_get_best(codec, bitrate, samplerate, mixdown);

fail:
    return -1;
}

/* Get the bitrate low and high limits for a codec/samplerate/mixdown triplet.
 *
 * Encoder    1.0 channel    2.0 channels    5.1 channels    6.1 channels    7.1 channels
 * --------------------------------------------------------------------------------------
 *
 * ffaac
 * -----
 * supported samplerates: 8 - 48 kHz
 * libavcodec/aacenc.c defines a maximum bitrate:
 * -> 6144 * samplerate / 1024 bps (per channel, incl. LFE).
 * But output bitrates don't go as high as the theoretical maximums:
 * 12 kHz        61  (72)       123 (144)
 * 24 kHz       121 (144)       242 (288)
 * 48 kHz       236 (288)       472 (576)
 * Also, ffaac isn't a great encoder, so you don't want to allow too low a bitrate.
 * Limits: minimum of  32 Kbps per channel
 *         maximum of 192 Kbps per channel at 32 kHz, adjusted for sr_shift
 *         maximum of 256 Kbps per channel at 44.1-48 kHz, adjusted for sr_shift
 *
 * vorbis
 * ------
 * supported samplerates: 8 - 48 kHz
 * lib/modes/setup_*.h provides a range of allowed bitrates for various configurations.
 * for each samplerate, the highest minimums and lowest maximums are:
 *  8 kHz        Minimum  8 Kbps, maximum  32 Kbps (per channel, incl. LFE).
 * 12 kHz        Minimum 14 Kbps, maximum  44 Kbps (per channel, incl. LFE).
 * 16 kHz        Minimum 16 Kbps, maximum  86 Kbps (per channel, incl. LFE).
 * 24 kHz        Minimum 22 Kbps, maximum  86 Kbps (per channel, incl. LFE).
 * 32 kHz        Minimum 26 Kbps, maximum 190 Kbps (per channel, incl. LFE).
 * 48 kHz        Minimum 28 Kbps, maximum 240 Kbps (per channel, incl. LFE).
 * Limits: minimum of 14/22/28 Kbps per channel (8-12, 16-24, 32-48 kHz)
 *         maximum of 32/86/190/240 Kbps per channel (8-12, 16-24, 32, 44.1-48 kHz)
 *
 * lame
 * ----
 * supported samplerates: 8 - 48 kHz
 * lame_init_params() allows the following bitrates:
 * 12 kHz        Minimum  8 Kbps, maximum  64 Kbps
 * 24 kHz        Minimum  8 Kbps, maximum 160 Kbps
 * 48 kHz        Minimum 32 Kbps, maximum 320 Kbps
 * Limits: minimum of 8/8/32 Kbps (8-12, 16-24, 32-48 kHz)
 *         maximum of 64/160/320 Kbps (8-12, 16-24, 32-48 kHz)
 *
 * ffac3
 * -----
 * supported samplerates: 32 - 48 kHz (< 32 kHz disabled for compatibility reasons)
 * Dolby's encoder has a min. of 224 Kbps for 5 full-bandwidth channels (5.0, 5.1)
 * The maximum AC3 bitrate is 640 Kbps
 * Limits: minimum of 224/5 Kbps per full-bandwidth channel, maximum of 640 Kbps
 *
 * ffeac3
 * ------
 * supported samplerates: 32 - 48 kHz (< 32 kHz not supported by libav encoder)
 * Dolby's encoder has a min. of 224 Kbps for 5 full-bandwidth channels (5.0, 5.1)
 * The maximum bitrate is 128 bits per sample per second
 * Limits: minimum of 224/5 Kbps per full-bandwidth channel
 *         maximum of 128/1000 * samplerate Kbps
 *
 * ca_aac
 * ------
 * supported samplerates: 8 - 48 kHz
 * Core Audio API provides a range of allowed bitrates:
 *  8 kHz         8 -  24        16 -  48        40 - 112        48 - 144        56 - 160
 * 12 kHz        12 -  32        24 -  64        64 - 160        72 - 192        96 - 224
 * 16 kHz        12 -  48        24 -  96        64 - 224        72 - 288        96 - 320
 * 24 kHz        16 -  64        32 - 128        80 - 320        96 - 384       112 - 448
 * 32 kHz        24 -  96        48 - 192       128 - 448       144 - 576       192 - 640
 * 48 kHz        32 - 256        64 - 320       160 - 768       192 - 960       224 - 960
 * Limits:
 *  8 kHz -> minimum of  8 Kbps and maximum of  24 Kbps per full-bandwidth channel
 * 12 kHz -> minimum of 12 Kbps and maximum of  32 Kbps per full-bandwidth channel
 * 16 kHz -> minimum of 12 Kbps and maximum of  48 Kbps per full-bandwidth channel
 * 24 kHz -> minimum of 16 Kbps and maximum of  64 Kbps per full-bandwidth channel
 * 32 kHz -> minimum of 24 Kbps and maximum of  96 Kbps per full-bandwidth channel
 * 48 kHz -> minimum of 32 Kbps and maximum of 160 Kbps per full-bandwidth channel
 * 48 kHz ->                        maximum of +96 Kbps for Mono
 * Note: encCoreAudioInit() will sanitize any mistake made here.
 *
 * ca_haac
 * -------
 * supported samplerates: 32 - 48 kHz
 * Core Audio API provides a range of allowed bitrates:
 * 32 kHz         12 - 40         24 - 80        64 - 192          N/A           96 - 256
 * 48 kHz         16 - 40         32 - 80        80 - 192          N/A          112 - 256
 * Limits: minimum of 12 Kbps per full-bandwidth channel (<= 32 kHz)
 *         minimum of 16 Kbps per full-bandwidth channel ( > 32 kHz)
 *         maximum of 40 Kbps per full-bandwidth channel
 * Note: encCoreAudioInit() will sanitize any mistake made here.
 *
 * fdk_aac
 * -------
 * supported samplerates: 8 - 48 kHz
 * libfdk limits the bitrate to the following values:
 *  8 kHz              48              96             240
 * 12 kHz              72             144             360
 * 16 kHz              96             192             480
 * 24 kHz             144             288             720
 * 32 kHz             192             384             960
 * 48 kHz             288             576            1440
 * Limits: minimum of samplerate * 2/3 Kbps per full-bandwidth channel (see ca_aac)
 *         maximum of samplerate * 6.0 Kbps per full-bandwidth channel
 *
 * fdk_haac
 * --------
 * supported samplerates: 16 - 48 kHz
 * libfdk limits the bitrate to the following values:
 * 16 kHz         8 -  48        16 -  96        45 - 199
 * 24 kHz         8 -  63        16 - 127        45 - 266
 * 32 kHz         8 -  63        16 - 127        45 - 266
 * 48 kHz        12 -  63        16 - 127        50 - 266
 * Limits: minimum of 12 Kbps per full-bandwidth channel  (<= 32 kHz) (see ca_haac)
 *         minimum of 16 Kbps per full-bandwidth channel  ( > 32 kHz) (see ca_haac)
 *         maximum of 48,  96 or 192 Kbps (1.0, 2.0, 5.1) (<= 16 kHz)
 *         maximum of 64, 128 or 256 Kbps (1.0, 2.0, 5.1) ( > 16 kHz)
 */
void hb_audio_bitrate_get_limits(uint32_t codec, int samplerate, int mixdown,
                                 int *low, int *high)
{
    /*
     * samplerate == 0 means "auto" (same as source) and the UIs know the source
     * samplerate -- except where there isn't a source (audio defaults panel);
     * but we have enough info to return the global bitrate limits for this
     * mixdown, since the first/last samplerate are known to us and non-zero.
     */
    if (samplerate == 0)
    {
        int dummy;
        hb_audio_bitrate_get_limits(codec, hb_audio_rates_first_item->rate, mixdown, low, &dummy);
        hb_audio_bitrate_get_limits(codec, hb_audio_rates_last_item->rate, mixdown, &dummy, high);
        return;
    }

    /* samplerate, sr_shift */
    int sr_shift;
    samplerate = hb_audio_samplerate_find_closest(samplerate, codec);
    sr_shift = hb_audio_samplerate_get_sr_shift(samplerate);

    /* LFE, full-bandwidth channels */
    int lfe_count, nchannels;
    lfe_count = hb_mixdown_get_low_freq_channel_count(mixdown);
    nchannels = hb_mixdown_get_discrete_channel_count(mixdown) - lfe_count;

    switch (codec)
    {
        // Bitrates don't apply to "lossless" audio
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
            *low = *high = -1;
            return;

        case HB_ACODEC_AC3:
            *low  = 224 * nchannels / 5;
            *high = 640;
            break;

        case HB_ACODEC_FFEAC3:
            *low  = 224 * nchannels  /    5;
            *high = 128 * samplerate / 1000;
            break;

        case HB_ACODEC_CA_AAC:
        {
            switch (samplerate)
            {
                case 8000:
                    *low  = nchannels *  8;
                    *high = nchannels * 24;
                    break;

                case 11025:
                case 12000:
                    *low  = nchannels * 12;
                    *high = nchannels * 32;
                    break;

                case 16000:
                    *low  = nchannels * 12;
                    *high = nchannels * 48;
                    break;

                case 22050:
                case 24000:
                    *low  = nchannels * 16;
                    *high = nchannels * 64;
                    break;

                case 32000:
                    *low  = nchannels * 24;
                    *high = nchannels * 96;
                    break;

                case 44100:
                case 48000:
                default:
                    *low  = nchannels * 32;
                    *high = nchannels * (160 + (96 * (nchannels == 1)));
                    break;
            } break;
        }

        case HB_ACODEC_CA_HAAC:
            *low  = nchannels * (12 + (4 * (samplerate >= 44100)));
            *high = nchannels * 40;
            break;

        case HB_ACODEC_FDK_AAC:
            *low  = nchannels * samplerate * 2 / 3000;
            *high = nchannels * samplerate * 6 / 1000;
            break;

        case HB_ACODEC_FDK_HAAC:
            *low  = (nchannels * (12 + (4 * (samplerate >= 44100))));
            *high = (nchannels - (nchannels > 2)) * (48 +
                                                     (16 *
                                                      (samplerate >= 22050)));
            break;

        case HB_ACODEC_FFAAC:
            *low  = ((nchannels + lfe_count) * 32);
            *high = ((nchannels + lfe_count) *
                     ((192 + (64 * ((samplerate << sr_shift) >= 44100)))
                      >> sr_shift));
            break;

        case HB_ACODEC_LAME:
            *low  =  8 + (24 * (sr_shift < 1));
            *high = 64 + (96 * (sr_shift < 2)) + (160 * (sr_shift < 1));
            break;

        case HB_ACODEC_VORBIS:
            *low  = (nchannels + lfe_count) * (14 +
                                               (8 * (sr_shift < 2)) +
                                               (6 * (sr_shift < 1)));
            *high = (nchannels + lfe_count) * (32 +
                                               ( 54 * (sr_shift < 2)) +
                                               (104 * (sr_shift < 1)) +
                                               ( 50 * (samplerate >= 44100)));
            break;

        case HB_ACODEC_OPUS:
            *low  = (nchannels + lfe_count) * 6;
            *high = (nchannels + lfe_count) * 256;
            break;

        // Bitrates don't apply to passthrough audio, but may apply if we
        // fall back to an encoder when the source can't be passed through.
        default:
            *low  = hb_audio_bitrates_first_item->rate;
            *high = hb_audio_bitrates_last_item ->rate;
            break;
    }

    // sanitize max. bitrate
    if (*high < hb_audio_bitrates_first_item->rate)
        *high = hb_audio_bitrates_first_item->rate;
    if (*high > hb_audio_bitrates_last_item ->rate)
        *high = hb_audio_bitrates_last_item ->rate;
}

const hb_rate_t* hb_audio_bitrate_get_next(const hb_rate_t *last)
{
    if (last == NULL)
    {
        return hb_audio_bitrates_first_item;
    }
    return ((hb_rate_internal_t*)last)->next;
}

// Get limits and hints for the UIs.
//
// granularity sets the minimum step increments that should be used
// (it's ok to round up to some nice multiple if you like)
//
// direction says whether 'low' limit is highest or lowest
// quality (direction 0 == lowest value is worst quality)
void hb_video_quality_get_limits(uint32_t codec, float *low, float *high,
                                 float *granularity, int *direction)
{
#ifdef USE_QSV
    if (codec & HB_VCODEC_QSV_MASK)
    {
        return hb_qsv_video_quality_get_limits(codec, low, high, granularity,
                                               direction);
    }
#endif

    switch (codec)
    {
        /*
         * H.264/H.265: *low
         * = 51 - (QP_MAX_SPEC)
         * = 51 - (51 + QP_BD_OFFSET)
         * =  0 - (QP_BD_OFFSET)
         * =  0 - (6*(BIT_DEPTH-8))     (libx264)
         * =  0 - (6*(X265_DEPTH-8))    (libx265)
         */
        case HB_VCODEC_X264_8BIT:
        case HB_VCODEC_X265_8BIT:
            *direction   = 1;
            *granularity = 0.1;
            *low         = 0.;
            *high        = 51.;
            break;
        case HB_VCODEC_X264_10BIT:
        case HB_VCODEC_X265_10BIT:
            *direction   = 1;
            *granularity = 0.1;
            *low         = -12.;
            *high        = 51.;
            break;
        case HB_VCODEC_X265_12BIT:
            *direction   = 1;
            *granularity = 0.1;
            *low         = -24.;
            *high        = 51.;
            break;
        case HB_VCODEC_X265_16BIT:
            *direction   = 1;
            *granularity = 0.1;
            *low         = -48.;
            *high        = 51.;
            break;

        case HB_VCODEC_THEORA:
            *direction   = 0;
            *granularity = 1.;
            *low         = 0.;
            *high        = 63.;
            break;

        case HB_VCODEC_FFMPEG_VP8:
        case HB_VCODEC_FFMPEG_VP9:
            *direction   = 1;
            *granularity = 1.;
            *low         = 0.;
            *high        = 63.;
            break;

        case HB_VCODEC_FFMPEG_MPEG2:
        case HB_VCODEC_FFMPEG_MPEG4:
        default:
            *direction   = 1;
            *granularity = 1.;
            *low         = 1.;
            *high        = 31.;
            break;
    }
}

const char* hb_video_quality_get_name(uint32_t codec)
{
#ifdef USE_QSV
    if (codec & HB_VCODEC_QSV_MASK)
    {
        return hb_qsv_video_quality_get_name(codec);
    }
#endif

    switch (codec)
    {
        case HB_VCODEC_X264_8BIT:
        case HB_VCODEC_X264_10BIT:
        case HB_VCODEC_X265_8BIT:
        case HB_VCODEC_X265_10BIT:
        case HB_VCODEC_X265_12BIT:
        case HB_VCODEC_X265_16BIT:
            return "RF";

        case HB_VCODEC_FFMPEG_VP8:
        case HB_VCODEC_FFMPEG_VP9:
            return "CQ";

        default:
            return "QP";
    }
}

int hb_video_encoder_get_depth(int encoder)
{
    switch (encoder)
    {
        case HB_VCODEC_X264_10BIT:
        case HB_VCODEC_X265_10BIT:
            return 10;
        case HB_VCODEC_X265_12BIT:
            return 12;
        case HB_VCODEC_X265_16BIT:
            return 16;
        default:
            return 8;
    }
}

const char* const* hb_video_encoder_get_presets(int encoder)
{
#ifdef USE_QSV
    if (encoder & HB_VCODEC_QSV_MASK)
    {
        return hb_qsv_preset_get_names();
    }
#endif

    if (encoder & HB_VCODEC_FFMPEG_MASK)
    {
        return hb_av_preset_get_names(encoder);
    }

    switch (encoder)
    {
        case HB_VCODEC_X264_8BIT:
        case HB_VCODEC_X264_10BIT:
            return x264_preset_names;

#ifdef USE_X265
        case HB_VCODEC_X265_8BIT:
        case HB_VCODEC_X265_10BIT:
        case HB_VCODEC_X265_12BIT:
        case HB_VCODEC_X265_16BIT:
            return x265_preset_names;
#endif
        default:
            return NULL;
    }
}

const char* const* hb_video_encoder_get_tunes(int encoder)
{
    switch (encoder)
    {
        case HB_VCODEC_X264_8BIT:
        case HB_VCODEC_X264_10BIT:
            return x264_tune_names;

#ifdef USE_X265
        case HB_VCODEC_X265_8BIT:
        case HB_VCODEC_X265_10BIT:
        case HB_VCODEC_X265_12BIT:
        case HB_VCODEC_X265_16BIT:
            return x265_tune_names;
#endif
        default:
            return NULL;
    }
}

const char* const* hb_video_encoder_get_profiles(int encoder)
{
#ifdef USE_QSV
    if (encoder & HB_VCODEC_QSV_MASK)
    {
        return hb_qsv_profile_get_names(encoder);
    }
#endif

    switch (encoder)
    {
        case HB_VCODEC_X264_8BIT:
            return hb_h264_profile_names_8bit;
        case HB_VCODEC_X264_10BIT:
            return hb_h264_profile_names_10bit;

        case HB_VCODEC_X265_8BIT:
            return hb_h265_profile_names_8bit;
        case HB_VCODEC_X265_10BIT:
            return hb_h265_profile_names_10bit;
        case HB_VCODEC_X265_12BIT:
            return hb_h265_profile_names_12bit;
        case HB_VCODEC_X265_16BIT:
            return hb_h265_profile_names_16bit;

        default:
            return NULL;
    }
}

const char* const* hb_video_encoder_get_levels(int encoder)
{
#ifdef USE_QSV
    if (encoder & HB_VCODEC_QSV_MASK)
    {
        return hb_qsv_level_get_names(encoder);
    }
#endif

    switch (encoder)
    {
        case HB_VCODEC_X264_8BIT:
        case HB_VCODEC_X264_10BIT:
            return hb_h264_level_names;

        default:
            return NULL;
    }
}

// Get limits and hints for the UIs.
//
// granularity sets the minimum step increments that should be used
// (it's ok to round up to some nice multiple if you like)
//
// direction says whether 'low' limit is highest or lowest
// quality (direction 0 == lowest value is worst quality)
void hb_audio_quality_get_limits(uint32_t codec, float *low, float *high,
                                 float *granularity, int *direction)
{
    switch (codec)
    {
        case HB_ACODEC_FFAAC:
            *direction   = 0;
            *granularity = 1.;
            *low         = 1.;
            *high        = 10.;
            break;

        case HB_ACODEC_FDK_HAAC:
        case HB_ACODEC_FDK_AAC:
            *direction   = 0;
            *granularity = 1.;
            *low         = 1.;
            *high        = 5.;
            break;

        case HB_ACODEC_LAME:
            *direction   = 1;
            *granularity = 0.5;
            *low         = 0.;
            *high        = 10.;
            break;

        case HB_ACODEC_VORBIS:
            *direction   = 0;
            *granularity = 0.5;
            *low         = -2.;
            *high        = 10.;
            break;

        case HB_ACODEC_CA_AAC:
            *direction   = 0;
            *granularity = 9.;
            *low         = 1.;
            *high        = 127.;
            break;

        case HB_ACODEC_OPUS:
            *direction   = 0;
            *granularity = 1.;
            *low         = 0.;
            *high        = 10.;
            break;

        default:
            *direction   = 0;
            *granularity = 1.;
            *low = *high = HB_INVALID_AUDIO_QUALITY;
            break;
    }
}

float hb_audio_quality_get_best(uint32_t codec, float quality)
{
    int direction;
    float low, high, granularity;
    hb_audio_quality_get_limits(codec, &low, &high, &granularity, &direction);
    if (quality > high)
        quality = high;
    if (quality < low)
        quality = low;
    return quality;
}

float hb_audio_quality_get_default(uint32_t codec)
{
    switch (codec)
    {
        case HB_ACODEC_FFAAC:
            return 5.;

        case HB_ACODEC_FDK_HAAC:
        case HB_ACODEC_FDK_AAC:
            return 3.;

        case HB_ACODEC_LAME:
            return 2.;

        case HB_ACODEC_VORBIS:
            return 5.;

        case HB_ACODEC_CA_AAC:
            return 91.;

        case HB_ACODEC_OPUS:
            return 10.;

        default:
            return HB_INVALID_AUDIO_QUALITY;
    }
}

// Get limits and hints for the UIs.
//
// granularity sets the minimum step increments that should be used
// (it's ok to round up to some nice multiple if you like)
//
// direction says whether 'low' limit is highest or lowest
// compression level (direction 0 == lowest value is worst compression level)
void hb_audio_compression_get_limits(uint32_t codec, float *low, float *high,
                                     float *granularity, int *direction)
{
    switch (codec)
    {
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
            *direction   = 0;
            *granularity = 1.;
            *high        = 12.;
            *low         = 0.;
            break;

        case HB_ACODEC_LAME:
            *direction   = 1;
            *granularity = 1.;
            *high        = 9.;
            *low         = 0.;
            break;

        default:
            *direction   = 0;
            *granularity = 1.;
            *low = *high = -1.;
            break;
    }
}

float hb_audio_compression_get_best(uint32_t codec, float compression)
{
    int direction;
    float low, high, granularity;
    hb_audio_compression_get_limits(codec, &low, &high, &granularity, &direction);
    if( compression > high )
        compression = high;
    if( compression < low )
        compression = low;
    return compression;
}

float hb_audio_compression_get_default(uint32_t codec)
{
    switch (codec)
    {
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
            return 5.;

        case HB_ACODEC_LAME:
            return 2.;

        default:
            return -1.;
    }
}

int hb_audio_dither_get_default()
{
    // "auto"
    return hb_audio_dithers_first_item->method;
}

int hb_audio_dither_get_default_method()
{
    /*
     * input could be s16 (possibly already dithered) converted to flt, so
     * let's use a "low-risk" dither algorithm (standard triangular).
     */
    return AV_RESAMPLE_DITHER_TRIANGULAR;
}

int hb_audio_dither_is_supported(uint32_t codec)
{
    // encoder's input sample format must be s16(p)
    switch (codec)
    {
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FDK_AAC:
        case HB_ACODEC_FDK_HAAC:
            return 1;

        default:
            return 0;
    }
}

int hb_audio_dither_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for ( i = 0; i < hb_audio_dithers_count; i++)
    {
        if (!strcasecmp(hb_audio_dithers[i].item.short_name,  name) ||
            !strcasecmp(hb_audio_dithers[i].item.description, name))
        {
            return hb_audio_dithers[i].item.method;
        }
    }

fail:
    return hb_audio_dither_get_default();
}

const char* hb_audio_dither_get_description(int method)
{
    if (method < hb_audio_dithers_first_item->method ||
        method > hb_audio_dithers_last_item ->method)
        goto fail;

    const hb_dither_t *audio_dither = NULL;
    while ((audio_dither = hb_audio_dither_get_next(audio_dither)) != NULL)
    {
        if (audio_dither->method == method)
        {
            return audio_dither->description;
        }
    }

fail:
    return NULL;
}

const hb_dither_t* hb_audio_dither_get_next(const hb_dither_t *last)
{
    if (last == NULL)
    {
        return hb_audio_dithers_first_item;
    }
    return ((hb_dither_internal_t*)last)->next;
}

static int mixdown_get_opus_coupled_stream_count(int mixdown)
{
    switch (mixdown)
    {
        case HB_AMIXDOWN_7POINT1:
        case HB_AMIXDOWN_6POINT1:
            return 3;

        case HB_AMIXDOWN_5POINT1:
            return 2;

        case HB_AMIXDOWN_MONO:
        case HB_AMIXDOWN_LEFT:
        case HB_AMIXDOWN_RIGHT:
            return 0;

        case HB_AMIXDOWN_NONE:
        case HB_INVALID_AMIXDOWN:
        case HB_AMIXDOWN_5_2_LFE:
            // The 5F/2R/LFE configuration is currently not supported by Opus,
            // so don't set coupled streams.
            return 0;

        default:
            return 1;
    }
}

int hb_mixdown_is_supported(int mixdown, uint32_t codec, uint64_t layout)
{
    return (hb_mixdown_has_codec_support(mixdown, codec) &&
            hb_mixdown_has_remix_support(mixdown, layout));
}

int hb_mixdown_has_codec_support(int mixdown, uint32_t codec)
{
    // Passthru, only "None" mixdown is supported
    if (codec & HB_ACODEC_PASS_FLAG)
        return (mixdown == HB_AMIXDOWN_NONE);

    // Not passthru, "None" mixdown never supported
    if (mixdown == HB_AMIXDOWN_NONE)
        return 0;

    switch (codec)
    {
        case HB_ACODEC_VORBIS:
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
        case HB_ACODEC_OPUS:
            return (mixdown <= HB_AMIXDOWN_7POINT1);

        case HB_ACODEC_LAME:
            return (mixdown <= HB_AMIXDOWN_DOLBYPLII);

        case HB_ACODEC_CA_AAC:
        case HB_ACODEC_CA_HAAC:
            return ((mixdown <= HB_AMIXDOWN_5POINT1) ||
                    (mixdown == HB_AMIXDOWN_5_2_LFE));

        default:
            return (mixdown <= HB_AMIXDOWN_5POINT1);
    }
}

int hb_mixdown_has_remix_support(int mixdown, uint64_t layout)
{
    /*
     * Where there isn't a source (e.g. audio defaults panel), we have no input
     * layout; assume remix support, as the mixdown will be sanitized later on.
     */
    if (!layout)
    {
        return 1;
    }
    switch (mixdown)
    {
        // stereo + front left/right of center
        case HB_AMIXDOWN_5_2_LFE:
            return ((layout & AV_CH_FRONT_LEFT_OF_CENTER) &&
                    (layout & AV_CH_FRONT_RIGHT_OF_CENTER) &&
                    (layout & AV_CH_LAYOUT_STEREO) == AV_CH_LAYOUT_STEREO);

        // 7.0 or better
        case HB_AMIXDOWN_7POINT1:
            return ((layout & AV_CH_LAYOUT_7POINT0) == AV_CH_LAYOUT_7POINT0);

        // 6.0 or better
        case HB_AMIXDOWN_6POINT1:
            return ((layout & AV_CH_LAYOUT_7POINT0) == AV_CH_LAYOUT_7POINT0 ||
                    (layout & AV_CH_LAYOUT_6POINT0) == AV_CH_LAYOUT_6POINT0 ||
                    (layout & AV_CH_LAYOUT_HEXAGONAL) == AV_CH_LAYOUT_HEXAGONAL);

        // stereo + either of front center, side or back left/right, back center
        case HB_AMIXDOWN_5POINT1:
            return ((layout & AV_CH_LAYOUT_2_1) == AV_CH_LAYOUT_2_1 ||
                    (layout & AV_CH_LAYOUT_2_2) == AV_CH_LAYOUT_2_2 ||
                    (layout & AV_CH_LAYOUT_QUAD) == AV_CH_LAYOUT_QUAD ||
                    (layout & AV_CH_LAYOUT_SURROUND) == AV_CH_LAYOUT_SURROUND);

        // stereo + either of side or back left/right, back center
        // also, allow Dolby Surrounbd output if the input is already Dolby
        case HB_AMIXDOWN_DOLBY:
        case HB_AMIXDOWN_DOLBYPLII:
            return ((layout & AV_CH_LAYOUT_2_1) == AV_CH_LAYOUT_2_1 ||
                    (layout & AV_CH_LAYOUT_2_2) == AV_CH_LAYOUT_2_2 ||
                    (layout & AV_CH_LAYOUT_QUAD) == AV_CH_LAYOUT_QUAD ||
                    (layout == AV_CH_LAYOUT_STEREO_DOWNMIX &&
                     mixdown == HB_AMIXDOWN_DOLBY));

        // more than 1 channel
        case HB_AMIXDOWN_STEREO:
            return (av_get_channel_layout_nb_channels(layout) > 1);

        // regular stereo (not Dolby)
        case HB_AMIXDOWN_LEFT:
        case HB_AMIXDOWN_RIGHT:
            return (layout == AV_CH_LAYOUT_STEREO);

        // mono remix always supported
        // HB_AMIXDOWN_NONE always supported (for Passthru)
        case HB_AMIXDOWN_MONO:
        case HB_AMIXDOWN_NONE:
            return 1;

        // unknown mixdown, should never happen
        default:
            return 0;
    }
}

int hb_mixdown_get_discrete_channel_count(int amixdown)
{
    switch (amixdown)
    {
        case HB_AMIXDOWN_5_2_LFE:
        case HB_AMIXDOWN_7POINT1:
            return 8;

        case HB_AMIXDOWN_6POINT1:
            return 7;

        case HB_AMIXDOWN_5POINT1:
            return 6;

        case HB_AMIXDOWN_MONO:
        case HB_AMIXDOWN_LEFT:
        case HB_AMIXDOWN_RIGHT:
            return 1;

        case HB_AMIXDOWN_NONE:
            return 0;

        default:
            return 2;
    }
}

int hb_mixdown_get_low_freq_channel_count(int amixdown)
{
    switch (amixdown)
    {
        case HB_AMIXDOWN_5POINT1:
        case HB_AMIXDOWN_6POINT1:
        case HB_AMIXDOWN_7POINT1:
        case HB_AMIXDOWN_5_2_LFE:
            return 1;

        default:
            return 0;
    }
}

int hb_mixdown_get_best(uint32_t codec, uint64_t layout, int mixdown)
{
    // Passthru, only "None" mixdown is supported
    if (codec & HB_ACODEC_PASS_FLAG)
        return HB_AMIXDOWN_NONE;

    int best_mixdown                  = HB_INVALID_AMIXDOWN;
    const hb_mixdown_t *audio_mixdown = hb_mixdown_get_next(NULL);
    // test all non-None mixdowns while the value is <= the requested mixdown
    // HB_INVALID_AMIXDOWN means the highest supported mixdown was requested
    while ((audio_mixdown = hb_mixdown_get_next(audio_mixdown)) != NULL)
    {
        if ((mixdown == HB_INVALID_AMIXDOWN || audio_mixdown->amixdown <= mixdown) &&
            (hb_mixdown_is_supported(audio_mixdown->amixdown, codec, layout)))
        {
            best_mixdown = audio_mixdown->amixdown;
        }
    }
    return best_mixdown;
}

int hb_mixdown_get_default(uint32_t codec, uint64_t layout)
{
    int mixdown;
    switch (codec)
    {
        // the FLAC encoder defaults to the best mixdown up to 7.1
        case HB_ACODEC_FFFLAC:
        case HB_ACODEC_FFFLAC24:
        case HB_ACODEC_OPUS:
            mixdown = HB_AMIXDOWN_7POINT1;
            break;

        // the (E-)AC-3 encoder defaults to the best mixdown up to 5.1
        case HB_ACODEC_AC3:
        case HB_ACODEC_FFEAC3:
            mixdown = HB_AMIXDOWN_5POINT1;
            break;

        // other encoders default to the best mixdown up to DPLII
        default:
            mixdown = HB_AMIXDOWN_DOLBYPLII;
            break;
    }

    // return the best available mixdown up to the selected default
    return hb_mixdown_get_best(codec, layout, mixdown);
}

hb_mixdown_t* hb_mixdown_get_from_mixdown(int mixdown)
{
    int i;
    for (i = 0; i < hb_audio_mixdowns_count; i++)
    {
        if (hb_audio_mixdowns[i].item.amixdown == mixdown)
        {
            return &hb_audio_mixdowns[i].item;
        }
    }

    return NULL;
}

int hb_mixdown_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_audio_mixdowns_count; i++)
    {
        if (!strcasecmp(hb_audio_mixdowns[i].item.name,       name) ||
            !strcasecmp(hb_audio_mixdowns[i].item.short_name, name))
        {
            return hb_audio_mixdowns[i].item.amixdown;
        }
    }

fail:
    return HB_INVALID_AMIXDOWN;
}

const char* hb_mixdown_get_name(int mixdown)
{
    if (mixdown < hb_audio_mixdowns_first_item->amixdown ||
        mixdown > hb_audio_mixdowns_last_item ->amixdown)
        goto fail;

    const hb_mixdown_t *audio_mixdown = NULL;
    while ((audio_mixdown = hb_mixdown_get_next(audio_mixdown)) != NULL)
    {
        if (audio_mixdown->amixdown == mixdown)
        {
            return audio_mixdown->name;
        }
    }

fail:
    return NULL;
}

const char* hb_mixdown_get_short_name(int mixdown)
{
    if (mixdown < hb_audio_mixdowns_first_item->amixdown ||
        mixdown > hb_audio_mixdowns_last_item ->amixdown)
        goto fail;

    const hb_mixdown_t *audio_mixdown = NULL;
    while ((audio_mixdown = hb_mixdown_get_next(audio_mixdown)) != NULL)
    {
        if (audio_mixdown->amixdown == mixdown)
        {
            return audio_mixdown->short_name;
        }
    }

fail:
    return NULL;
}

const char* hb_mixdown_sanitize_name(const char *name)
{
    return hb_mixdown_get_name(hb_mixdown_get_from_name(name));
}

const hb_mixdown_t* hb_mixdown_get_next(const hb_mixdown_t *last)
{
    if (last == NULL)
    {
        return hb_audio_mixdowns_first_item;
    }
    return ((hb_mixdown_internal_t*)last)->next;
}

int hb_video_encoder_get_default(int muxer)
{
    if (!(muxer & HB_MUX_MASK))
        goto fail;

    const hb_encoder_t *video_encoder = NULL;
    while ((video_encoder = hb_video_encoder_get_next(video_encoder)) != NULL)
    {
        if (video_encoder->muxers & muxer)
        {
            return video_encoder->codec;
        }
    }

fail:
    return HB_VCODEC_INVALID;
}

hb_encoder_t * hb_video_encoder_get_from_codec(int codec)
{
    int i;
    for (i = 0; i < hb_video_encoders_count; i++)
    {
        if (hb_video_encoders[i].item.codec == codec)
        {
            return &hb_video_encoders[i].item;
        }
    }

    return NULL;
}

int hb_video_encoder_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_video_encoders_count; i++)
    {
        if (!strcasecmp(hb_video_encoders[i].item.name,       name) ||
            !strcasecmp(hb_video_encoders[i].item.short_name, name))
        {
            return hb_video_encoders[i].item.codec;
        }
    }

fail:
    return HB_VCODEC_INVALID;
}

const char* hb_video_encoder_get_name(int encoder)
{
    if (!(encoder & HB_VCODEC_MASK))
        goto fail;

    const hb_encoder_t *video_encoder = NULL;
    while ((video_encoder = hb_video_encoder_get_next(video_encoder)) != NULL)
    {
        if (video_encoder->codec == encoder)
        {
            return video_encoder->name;
        }
    }

fail:
    return NULL;
}

const char* hb_video_encoder_get_short_name(int encoder)
{
    if (!(encoder & HB_VCODEC_MASK))
        goto fail;

    const hb_encoder_t *video_encoder = NULL;
    while ((video_encoder = hb_video_encoder_get_next(video_encoder)) != NULL)
    {
        if (video_encoder->codec == encoder)
        {
            return video_encoder->short_name;
        }
    }

fail:
    return NULL;
}

const char* hb_video_encoder_get_long_name(int encoder)
{
    if (!(encoder & HB_VCODEC_MASK))
        goto fail;

    const hb_encoder_t *video_encoder = NULL;
    while ((video_encoder = hb_video_encoder_get_next(video_encoder)) != NULL)
    {
        if (video_encoder->codec == encoder)
        {
            return video_encoder->long_name;
        }
    }

fail:
    return NULL;
}

const char* hb_video_encoder_sanitize_name(const char *name)
{
    return hb_video_encoder_get_name(hb_video_encoder_get_from_name(name));
}

const hb_encoder_t* hb_video_encoder_get_next(const hb_encoder_t *last)
{
    if (last == NULL)
    {
        return hb_video_encoders_first_item;
    }
    return ((hb_encoder_internal_t*)last)->next;
}

// for a valid passthru, return the matching encoder for that codec (if any),
// else return -1 (i.e. drop the track)
int hb_audio_encoder_get_fallback_for_passthru(int passthru)
{
    int gid;
    const hb_encoder_t *audio_encoder = NULL;
    switch (passthru)
    {
        case HB_ACODEC_AAC_PASS:
            gid = HB_GID_ACODEC_AAC;
            break;

        case HB_ACODEC_AC3_PASS:
            gid = HB_GID_ACODEC_AC3;
            break;

        case HB_ACODEC_EAC3_PASS:
            gid = HB_GID_ACODEC_EAC3;
            break;

        case HB_ACODEC_FLAC_PASS:
            gid = HB_GID_ACODEC_FLAC;
            break;

        case HB_ACODEC_MP3_PASS:
            gid = HB_GID_ACODEC_MP3;
            break;

        default:
            gid = HB_GID_NONE; // will never match an enabled encoder
            break;
    }
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        if (((hb_encoder_internal_t*)audio_encoder)->gid == gid)
        {
            return audio_encoder->codec;
        }
    }

    // passthru tracks are often the second audio from the same source track
    // if we don't have an encoder matching the passthru codec, return INVALID
    // dropping the track, as well as ensuring that there is at least one
    // audio track in the output is then up to the UIs
    return HB_ACODEC_INVALID;
}

int hb_audio_encoder_get_default(int muxer)
{
    if (!(muxer & HB_MUX_MASK))
        goto fail;

    int codec                         = 0;
    const hb_encoder_t *audio_encoder = NULL;
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        // default encoder should not be passthru
        if ((audio_encoder->muxers & muxer) &&
            (audio_encoder->codec  & HB_ACODEC_PASS_FLAG) == 0)
        {
            codec = audio_encoder->codec;
            break;
        }
    }

    // Lame is better than our low-end AAC encoders
    // if the container is MKV, use the former
    // AAC is still used when the container is MP4 (for better compatibility)
    if (codec == HB_ACODEC_FFAAC && (muxer & HB_MUX_MASK_MKV) == muxer)
    {
        return HB_ACODEC_LAME;
    }
    else
    {
        return codec;
    }

fail:
    return HB_ACODEC_INVALID;
}

hb_encoder_t* hb_audio_encoder_get_from_codec(int codec)
{
    int i;
    for (i = 0; i < hb_audio_encoders_count; i++)
    {
        if (hb_audio_encoders[i].item.codec == codec)
        {
            return &hb_audio_encoders[i].item;
        }
    }

    return NULL;
}

int hb_audio_encoder_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_audio_encoders_count; i++)
    {
        if (!strcasecmp(hb_audio_encoders[i].item.name,       name) ||
            !strcasecmp(hb_audio_encoders[i].item.short_name, name))
        {
            return hb_audio_encoders[i].item.codec;
        }
    }

fail:
    return HB_ACODEC_INVALID;
}

const char* hb_audio_encoder_get_name(int encoder)
{
    if (!(encoder & HB_ACODEC_ANY))
        goto fail;

    const hb_encoder_t *audio_encoder = NULL;
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        if (audio_encoder->codec == encoder)
        {
            return audio_encoder->name;
        }
    }

fail:
    return NULL;
}

const char* hb_audio_encoder_get_short_name(int encoder)
{
    if (!(encoder & HB_ACODEC_ANY))
        goto fail;

    const hb_encoder_t *audio_encoder = NULL;
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        if (audio_encoder->codec == encoder)
        {
            return audio_encoder->short_name;
        }
    }

fail:
    return NULL;
}

const char* hb_audio_encoder_get_long_name(int encoder)
{
    if (!(encoder & HB_ACODEC_ANY))
        goto fail;

    const hb_encoder_t *audio_encoder = NULL;
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        if (audio_encoder->codec == encoder)
        {
            return audio_encoder->long_name;
        }
    }

fail:
    return NULL;
}

const char* hb_audio_encoder_sanitize_name(const char *name)
{
    return hb_audio_encoder_get_name(hb_audio_encoder_get_from_name(name));
}

const hb_encoder_t* hb_audio_encoder_get_next(const hb_encoder_t *last)
{
    if (last == NULL)
    {
        return  hb_audio_encoders_first_item;
    }
    return ((hb_encoder_internal_t*)last)->next;
}

void hb_autopassthru_apply_settings(hb_job_t *job)
{
    hb_audio_t *audio;
    int i, already_printed;
    for (i = already_printed = 0; i < hb_list_count(job->list_audio);)
    {
        audio = hb_list_item(job->list_audio, i);
        if (audio->config.out.codec == HB_ACODEC_AUTO_PASS)
        {
            if (!already_printed)
                hb_autopassthru_print_settings(job);
            already_printed = 1;
            audio->config.out.codec = hb_autopassthru_get_encoder(audio->config.in.codec,
                                                                  job->acodec_copy_mask,
                                                                  job->acodec_fallback,
                                                                  job->mux);
            if (!(audio->config.out.codec & HB_ACODEC_PASS_FLAG) &&
                !(audio->config.out.codec & HB_ACODEC_MASK))
            {
                hb_log("Auto Passthru: passthru not possible and no valid fallback specified, dropping track %d",
                       audio->config.out.track );
                hb_list_rem(job->list_audio, audio);
                hb_audio_close(&audio);
                continue;
            }
            if (!(audio->config.out.codec & HB_ACODEC_PASS_FLAG))
            {
                if (audio->config.out.codec == job->acodec_fallback)
                {
                    hb_log("Auto Passthru: passthru not possible for track %d, using fallback",
                           audio->config.out.track);
                }
                else
                {
                    hb_log("Auto Passthru: passthru and fallback not possible for track %d, using default encoder",
                           audio->config.out.track);
                }
                if (audio->config.out.mixdown <= 0)
                {
                    audio->config.out.mixdown =
                        hb_mixdown_get_default(audio->config.out.codec,
                                               audio->config.in.channel_layout);
                }
                else
                {
                    audio->config.out.mixdown =
                        hb_mixdown_get_best(audio->config.out.codec,
                                            audio->config.in.channel_layout,
                                            audio->config.out.mixdown);
                }
                if (audio->config.out.samplerate <= 0)
                    audio->config.out.samplerate = audio->config.in.samplerate;
                audio->config.out.samplerate =
                    hb_audio_samplerate_find_closest(
                        audio->config.out.samplerate, audio->config.out.codec);
                int quality_not_allowed =
                    hb_audio_quality_get_default(audio->config.out.codec)
                            == HB_INVALID_AUDIO_QUALITY;
                if (audio->config.out.bitrate > 0)
                {
                    // Use best bitrate
                    audio->config.out.bitrate =
                        hb_audio_bitrate_get_best(audio->config.out.codec,
                                                  audio->config.out.bitrate,
                                                  audio->config.out.samplerate,
                                                  audio->config.out.mixdown);
                }
                else if (quality_not_allowed ||
                         audio->config.out.quality != HB_INVALID_AUDIO_QUALITY)
                {
                    // Use default bitrate
                    audio->config.out.bitrate =
                        hb_audio_bitrate_get_default(audio->config.out.codec,
                                                 audio->config.out.samplerate,
                                                 audio->config.out.mixdown);
                }
                else
                {
                    // Use best quality
                    audio->config.out.quality =
                        hb_audio_quality_get_best(audio->config.out.codec,
                                                  audio->config.out.quality);
                }
                if (audio->config.out.compression_level < 0)
                {
                    audio->config.out.compression_level =
                        hb_audio_compression_get_default(
                                        audio->config.out.codec);
                }
                else
                {
                    audio->config.out.compression_level =
                        hb_audio_compression_get_best(audio->config.out.codec,
                                        audio->config.out.compression_level);
                }
            }
            else
            {
                const hb_encoder_t *audio_encoder = NULL;
                while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
                {
                    if (audio_encoder->codec == audio->config.out.codec)
                    {
                        hb_log("Auto Passthru: using %s for track %d",
                               audio_encoder->name,
                               audio->config.out.track);
                        break;
                    }
                }
            }
        }
        /* Adjust output track number, in case we removed one.
         * Output tracks sadly still need to be in sequential order.
         * Note: out.track starts at 1, i starts at 0 */
        audio->config.out.track = ++i;
    }
}

void hb_autopassthru_print_settings(hb_job_t *job)
{
    char *mask = NULL, *tmp;
    const char *fallback = NULL;
    const hb_encoder_t *audio_encoder = NULL;
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        if ((audio_encoder->codec &  HB_ACODEC_PASS_FLAG) &&
            (audio_encoder->codec != HB_ACODEC_AUTO_PASS) &&
            (audio_encoder->codec & (job->acodec_copy_mask &
                                     HB_ACODEC_PASS_MASK)))
        {
            if (mask != NULL)
            {
                tmp = hb_strncat_dup(mask, ", ", 2);
                if (tmp != NULL)
                {
                    free(mask);
                    mask = tmp;
                }
            }
            // passthru name without " Passthru"
            tmp = hb_strncat_dup(mask,  audio_encoder->name,
                                 strlen(audio_encoder->name) - 9);
            if (tmp != NULL)
            {
                free(mask);
                mask = tmp;
            }
        }
        else if ((audio_encoder->codec & HB_ACODEC_PASS_FLAG) == 0 &&
                 (audio_encoder->codec == job->acodec_fallback))
        {
            fallback = audio_encoder->name;
        }
    }
    if (mask == NULL)
        hb_log("Auto Passthru: no codecs allowed");
    else
        hb_log("Auto Passthru: allowed codecs are %s", mask);
    if (fallback == NULL)
        hb_log("Auto Passthru: no valid fallback specified");
    else
        hb_log("Auto Passthru: fallback is %s", fallback);
}

int hb_autopassthru_get_encoder(int in_codec, int copy_mask, int fallback,
                                int muxer)
{
    int i = 0;
    const hb_encoder_t *audio_encoder = NULL;
    int out_codec = (copy_mask & in_codec) | HB_ACODEC_PASS_FLAG;
    // sanitize fallback encoder and selected passthru
    // note: invalid fallbacks are caught in hb_autopassthru_apply_settings
    while ((audio_encoder = hb_audio_encoder_get_next(audio_encoder)) != NULL)
    {
        if (audio_encoder->codec == out_codec)
        {
            i++;
            if (!(audio_encoder->muxers & muxer))
                out_codec = 0;
        }
        else if (audio_encoder->codec == fallback)
        {
            i++;
            if (!(audio_encoder->muxers & muxer))
                fallback = hb_audio_encoder_get_default(muxer);
        }
        if (i > 1)
        {
            break;
        }
    }
    return (out_codec & HB_ACODEC_PASS_MASK) ? out_codec : fallback;
}

hb_container_t* hb_container_get_from_format(int format)
{
    int i;
    for (i = 0; i < hb_containers_count; i++)
    {
        if (hb_containers[i].item.format == format)
        {
            return &hb_containers[i].item;
        }
    }

    return NULL;
}

int hb_container_get_from_name(const char *name)
{
    if (name == NULL || *name == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_containers_count; i++)
    {
        if (!strcasecmp(hb_containers[i].item.name,       name) ||
            !strcasecmp(hb_containers[i].item.short_name, name))
        {
            return hb_containers[i].item.format;
        }
    }

fail:
    return HB_MUX_INVALID;
}

int hb_container_get_from_extension(const char *extension)
{
    if (extension == NULL || *extension == '\0')
        goto fail;

    int i;
    for (i = 0; i < hb_containers_count; i++)
    {
        if (!strcasecmp(hb_containers[i].item.default_extension, extension))
        {
            return hb_containers[i].item.format;
        }
    }

fail:
    return HB_MUX_INVALID;
}

const char* hb_container_get_name(int format)
{
    if (!(format & HB_MUX_MASK))
        goto fail;

    const hb_container_t *container = NULL;
    while ((container = hb_container_get_next(container)) != NULL)
    {
        if (container->format == format)
        {
            return container->name;
        }
    }

fail:
    return NULL;
}

const char* hb_container_get_short_name(int format)
{
    if (!(format & HB_MUX_MASK))
        goto fail;

    const hb_container_t *container = NULL;
    while ((container = hb_container_get_next(container)) != NULL)
    {
        if (container->format == format)
        {
            return container->short_name;
        }
    }

fail:
    return NULL;
}

const char* hb_container_get_long_name(int format)
{
    if (!(format & HB_MUX_MASK))
        goto fail;

    const hb_container_t *container = NULL;
    while ((container = hb_container_get_next(container)) != NULL)
    {
        if (container->format == format)
        {
            return container->long_name;
        }
    }

fail:
    return NULL;
}

const char* hb_container_get_default_extension(int format)
{
    if (!(format & HB_MUX_MASK))
        goto fail;

    const hb_container_t *container = NULL;
    while ((container = hb_container_get_next(container)) != NULL)
    {
        if (container->format == format)
        {
            return container->default_extension;
        }
    }

fail:
    return NULL;
}

const char* hb_container_sanitize_name(const char *name)
{
    return hb_container_get_name(hb_container_get_from_name(name));
}

const hb_container_t* hb_container_get_next(const hb_container_t *last)
{
    if (last == NULL)
    {
        return  hb_containers_first_item;
    }
    return ((hb_container_internal_t*)last)->next;
}

/**********************************************************************
 * hb_reduce
 **********************************************************************
 * Given a numerator (num) and a denominator (den), reduce them to an
 * equivalent fraction and store the result in x and y.
 *********************************************************************/
void hb_reduce( int *x, int *y, int num, int den )
{
    // find the greatest common divisor of num & den by Euclid's algorithm
    int n = num, d = den;
    while ( d )
    {
        int t = d;
        d = n % d;
        n = t;
    }

    // at this point n is the gcd. if it's non-zero remove it from num
    // and den. Otherwise just return the original values.
    if ( n )
    {
        *x = num / n;
        *y = den / n;
    }
    else
    {
        *x = num;
        *y = den;
    }
}

void hb_limit_rational( int *x, int *y, int num, int den, int limit )
{
    hb_reduce( &num, &den, num, den );
    if ( num < limit && den < limit )
    {
        *x = num;
        *y = den;
        return;
    }

    if ( num > den )
    {
        double div = (double)limit / num;
        num = limit;
        den *= div;
    }
    else
    {
        double div = (double)limit / den;
        den = limit;
        num *= div;
    }
    *x = num;
    *y = den;
}

/**********************************************************************
 * hb_reduce64
 **********************************************************************
 * Given a numerator (num) and a denominator (den), reduce them to an
 * equivalent fraction and store the result in x and y.
 *********************************************************************/
void hb_reduce64( int64_t *x, int64_t *y, int64_t num, int64_t den )
{
    // find the greatest common divisor of num & den by Euclid's algorithm
    int64_t n = num, d = den;
    while ( d )
    {
        int64_t t = d;
        d = n % d;
        n = t;
    }

    // at this point n is the gcd. if it's non-zero remove it from num
    // and den. Otherwise just return the original values.
    if ( n )
    {
        num /= n;
        den /= n;
    }

    *x = num;
    *y = den;

}

void hb_limit_rational64( int64_t *x, int64_t *y, int64_t num, int64_t den, int64_t limit )
{
    hb_reduce64( &num, &den, num, den );
    if ( num < limit && den < limit )
    {
        *x = num;
        *y = den;
        return;
    }

    if ( num > den )
    {
        double div = (double)limit / num;
        num = limit;
        den *= div;
    }
    else
    {
        double div = (double)limit / den;
        den = limit;
        num *= div;
    }
    *x = num;
    *y = den;
}

/**********************************************************************
 * hb_buffer_list implementation
 *********************************************************************/
void hb_buffer_list_append(hb_buffer_list_t *list, hb_buffer_t *buf)
{
    int count = 1;
    int size = 0;
    hb_buffer_t *end = buf;

    if (buf == NULL)
    {
        return;
    }

    // Input buffer may be a list of buffers, find the end.
    size += buf->size;
    while (end != NULL && end->next != NULL)
    {
        end = end->next;
        size += end->size;
        count++;
    }
    if (list->tail == NULL)
    {
        list->head = buf;
        list->tail = end;
    }
    else
    {
        list->tail->next = buf;
        list->tail = end;
    }
    list->count += count;
    list->size += size;
}

void hb_buffer_list_prepend(hb_buffer_list_t *list, hb_buffer_t *buf)
{
    int count = 1;
    int size = 0;
    hb_buffer_t *end = buf;

    if (buf == NULL)
    {
        return;
    }

    // Input buffer may be a list of buffers, find the end.
    size += buf->size;
    while (end != NULL && end->next != NULL)
    {
        end = end->next;
        size += end->size;
        count++;
    }
    if (list->tail == NULL)
    {
        list->head = buf;
        list->tail = end;
    }
    else
    {
        end->next = list->head;
        list->head = buf;
    }
    list->count += count;
    list->size += size;
}

hb_buffer_t* hb_buffer_list_rem_head(hb_buffer_list_t *list)
{
    if (list == NULL)
    {
        return NULL;
    }
    hb_buffer_t *head = list->head;
    if (list->head != NULL)
    {
        if (list->head == list->tail)
        {
            list->tail = NULL;
        }
        list->head = list->head->next;
        list->count--;
        list->size -= head->size;
    }
    if (head != NULL)
    {
        head->next = NULL;
    }
    return head;
}

hb_buffer_t* hb_buffer_list_rem_tail(hb_buffer_list_t *list)
{
    if (list == NULL)
    {
        return NULL;
    }
    hb_buffer_t *tail = list->tail;

    if (list->head == list->tail)
    {
        list->head = list->tail = NULL;
        list->count = 0;
        list->size = 0;
    }
    else if (list->tail != NULL)
    {
        hb_buffer_t *end = list->head;
        while (end != NULL && end->next != list->tail)
        {
            end = end->next;
        }
        end->next = NULL;
        list->tail = end;
        list->count--;
        list->size -= tail->size;
    }
    if (tail != NULL)
    {
        tail->next = NULL;
    }
    return tail;
}

hb_buffer_t* hb_buffer_list_rem(hb_buffer_list_t *list, hb_buffer_t * b)
{
    hb_buffer_t * a;

    if (list == NULL)
    {
        return NULL;
    }
    if (b == list->head)
    {
        return hb_buffer_list_rem_head(list);
    }
    a = list->head;
    while (a != NULL && a->next != b)
    {
        a = a->next;
    }
    if (a == NULL)
    {
        // Buffer is not in the list
        return NULL;
    }
    list->count--;
    list->size -= b->size;
    a->next = b->next;
    if (list->tail == b)
    {
        list->tail = a;
    }
    b->next = NULL;

    return b;
}

hb_buffer_t* hb_buffer_list_head(hb_buffer_list_t *list)
{
    if (list == NULL)
    {
        return NULL;
    }
    return list->head;
}

hb_buffer_t* hb_buffer_list_tail(hb_buffer_list_t *list)
{
    if (list == NULL)
    {
        return NULL;
    }
    return list->tail;
}

hb_buffer_t* hb_buffer_list_set(hb_buffer_list_t *list, hb_buffer_t *buf)
{
    int count = 0;
    int size = 0;

    if (list == NULL)
    {
        return NULL;
    }

    hb_buffer_t *head = list->head;
    hb_buffer_t *end = buf;
    if (end != NULL)
    {
        count++;
        size += end->size;
        while (end->next != NULL)
        {
            end = end->next;
            count++;
            size += end->size;
        }
    }
    list->head = buf;
    list->tail = end;
    list->count = count;
    list->size = size;
    return head;
}

hb_buffer_t* hb_buffer_list_clear(hb_buffer_list_t *list)
{
    if (list == NULL)
    {
        return NULL;
    }
    hb_buffer_t *head = list->head;
    list->head = list->tail = NULL;
    list->count = 0;
    list->size = 0;
    return head;
}

void hb_buffer_list_close(hb_buffer_list_t *list)
{
    hb_buffer_t *buf = hb_buffer_list_clear(list);
    hb_buffer_close(&buf);
}

int hb_buffer_list_count(hb_buffer_list_t *list)
{
    if (list == NULL) return 0;
    return list->count;
}

int hb_buffer_list_size(hb_buffer_list_t *list)
{
    return list->size;
}

/**********************************************************************
 * hb_list implementation
 **********************************************************************
 * Basic and slow, but enough for what we need
 *********************************************************************/

#define HB_LIST_DEFAULT_SIZE 20

struct hb_list_s
{
    /* Pointers to items in the list */
    void ** items;

    /* How many (void *) allocated in 'items' */
    int     items_alloc;

    /* How many valid pointers in 'items' */
    int     items_count;
};

/**********************************************************************
 * hb_list_init
 **********************************************************************
 * Allocates an empty list ready for HB_LIST_DEFAULT_SIZE items
 *********************************************************************/
hb_list_t * hb_list_init()
{
    hb_list_t * l;

    l              = calloc( sizeof( hb_list_t ), 1 );
    l->items       = calloc( HB_LIST_DEFAULT_SIZE * sizeof( void * ), 1 );
    l->items_alloc = HB_LIST_DEFAULT_SIZE;

    return l;
}

/**********************************************************************
 * hb_list_count
 **********************************************************************
 * Returns the number of items currently in the list
 *********************************************************************/
int hb_list_count( const hb_list_t * l )
{
    if (l == NULL) return 0;
    return l->items_count;
}

/**********************************************************************
 * hb_list_add
 **********************************************************************
 * Adds an item at the end of the list, making it bigger if necessary.
 * Can safely be called with a NULL pointer to add, it will be ignored.
 *********************************************************************/
void hb_list_add( hb_list_t * l, void * p )
{
    if( !p )
    {
        return;
    }

    if( l->items_count == l->items_alloc )
    {
        /* We need a bigger boat */
        l->items_alloc += HB_LIST_DEFAULT_SIZE;
        l->items        = realloc( l->items,
                                   l->items_alloc * sizeof( void * ) );
    }

    l->items[l->items_count] = p;
    (l->items_count)++;
}

/**********************************************************************
 * hb_list_insert
 **********************************************************************
 * Adds an item at the specifiec position in the list, making it bigger
 * if necessary.
 * Can safely be called with a NULL pointer to add, it will be ignored.
 *********************************************************************/
void hb_list_insert( hb_list_t * l, int pos, void * p )
{
    if( !p )
    {
        return;
    }

    if( l->items_count == l->items_alloc )
    {
        /* We need a bigger boat */
        l->items_alloc += HB_LIST_DEFAULT_SIZE;
        l->items        = realloc( l->items,
                                   l->items_alloc * sizeof( void * ) );
    }

    if ( l->items_count != pos )
    {
        /* Shift all items after it sizeof( void * ) bytes earlier */
        memmove( &l->items[pos+1], &l->items[pos],
                 ( l->items_count - pos ) * sizeof( void * ) );
    }


    l->items[pos] = p;
    (l->items_count)++;
}

/**********************************************************************
 * hb_list_rem
 **********************************************************************
 * Remove an item from the list. Bad things will happen if called
 * with a NULL pointer or if the item is not in the list.
 *********************************************************************/
void hb_list_rem( hb_list_t * l, void * p )
{
    int i;

    /* Find the item in the list */
    for( i = 0; i < l->items_count; i++ )
    {
        if( l->items[i] == p )
        {
            /* Shift all items after it sizeof( void * ) bytes earlier */
            memmove( &l->items[i], &l->items[i+1],
                     ( l->items_count - i - 1 ) * sizeof( void * ) );

            (l->items_count)--;
            break;
        }
    }
}

/**********************************************************************
 * hb_list_item
 **********************************************************************
 * Returns item at position i, or NULL if there are not that many
 * items in the list
 *********************************************************************/
void * hb_list_item( const hb_list_t * l, int i )
{
    if( l == NULL || i < 0 || i >= l->items_count )
    {
        return NULL;
    }

    return l->items[i];
}

/**********************************************************************
 * hb_list_bytes
 **********************************************************************
 * Assuming all items are of type hb_buffer_t, returns the total
 * number of bytes in the list
 *********************************************************************/
int hb_list_bytes( hb_list_t * l )
{
    hb_buffer_t * buf;
    int           ret;
    int           i;

    ret = 0;
    for( i = 0; i < hb_list_count( l ); i++ )
    {
        buf  = hb_list_item( l, i );
        ret += buf->size - buf->offset;
    }

    return ret;
}

/**********************************************************************
 * hb_list_seebytes
 **********************************************************************
 * Assuming all items are of type hb_buffer_t, copy <size> bytes from
 * the list to <dst>, keeping the list unmodified.
 *********************************************************************/
void hb_list_seebytes( hb_list_t * l, uint8_t * dst, int size )
{
    hb_buffer_t * buf;
    int           copied;
    int           copying;
    int           i;

    for( i = 0, copied = 0; copied < size; i++ )
    {
        buf     = hb_list_item( l, i );
        copying = MIN( buf->size - buf->offset, size - copied );
        memcpy( &dst[copied], &buf->data[buf->offset], copying );
        copied += copying;
    }
}

/**********************************************************************
 * hb_list_getbytes
 **********************************************************************
 * Assuming all items are of type hb_buffer_t, copy <size> bytes from
 * the list to <dst>. What's copied is removed from the list.
 * The variable pointed by <pts> is set to the PTS of the buffer the
 * first byte has been got from.
 * The variable pointed by <pos> is set to the position of that byte
 * in that buffer.
 *********************************************************************/
void hb_list_getbytes( hb_list_t * l, uint8_t * dst, int size,
                       uint64_t * pts, uint64_t * pos )
{
    hb_buffer_t * buf;
    int           copied;
    int           copying;
    uint8_t       has_pts;

    /* So we won't have to deal with NULL pointers */
     uint64_t dummy1, dummy2;

    if( !pts ) pts = &dummy1;
    if( !pos ) pos = &dummy2;

    for( copied = 0, has_pts = 0; copied < size;  )
    {
        buf     = hb_list_item( l, 0 );
        copying = MIN( buf->size - buf->offset, size - copied );
        memcpy( &dst[copied], &buf->data[buf->offset], copying );

        if( !has_pts )
        {
            *pts    = buf->s.start;
            *pos    = buf->offset;
            has_pts = 1;
        }

        buf->offset += copying;
        if( buf->offset >= buf->size )
        {
            hb_list_rem( l, buf );
            hb_buffer_close( &buf );
        }

        copied += copying;
    }
}

/**********************************************************************
 * hb_list_empty
 **********************************************************************
 * Assuming all items are of type hb_buffer_t, close them all and
 * close the list.
 *********************************************************************/
void hb_list_empty( hb_list_t ** _l )
{
    hb_list_t * l = *_l;
    hb_buffer_t * b;

    while( ( b = hb_list_item( l, 0 ) ) )
    {
        hb_list_rem( l, b );
        hb_buffer_close( &b );
    }

    hb_list_close( _l );
}

/**********************************************************************
 * hb_list_close
 **********************************************************************
 * Free memory allocated by hb_list_init. Does NOT free contents of
 * items still in the list.
 *********************************************************************/
void hb_list_close( hb_list_t ** _l )
{
    hb_list_t * l = *_l;

    if (l == NULL)
    {
        return;
    }

    free( l->items );
    free( l );

    *_l = NULL;
}

int global_verbosity_level; //Necessary for hb_deep_log
/**********************************************************************
 * hb_valog
 **********************************************************************
 * If verbose mode is one, print message with timestamp. Messages
 * longer than 180 characters are stripped ;p
 *********************************************************************/
void hb_valog( hb_debug_level_t level, const char * prefix, const char * log, va_list args)
{
    char      * string;
    time_t      _now;
    struct tm * now;
    char        preamble[362];

    if( global_verbosity_level < level )
    {
        /* Hiding message */
        return;
    }

    /* Get the time */
    _now = time( NULL );
    now  = localtime( &_now );
    if ( prefix && *prefix )
    {
        // limit the prefix length
        snprintf( preamble, 361, "[%02d:%02d:%02d] %s %s\n",
                 now->tm_hour, now->tm_min, now->tm_sec, prefix, log );
    }
    else
    {
        snprintf( preamble, 361, "[%02d:%02d:%02d] %s\n",
                  now->tm_hour, now->tm_min, now->tm_sec, log );
    }

    string = hb_strdup_vaprintf(preamble, args);

#ifdef SYS_MINGW
    wchar_t     *wstring; /* 360 chars + \n + \0 */
    int          len;

    len = strlen(string) + 1;
    wstring = malloc(2 * len);

    // Convert internal utf8 to "console output code page".
    //
    // This is just bizarre windows behavior.  You would expect that
    // printf would automatically convert a wide character string to
    // the current "console output code page" when using the "%ls" format
    // specifier.  But it doesn't... so we must do it.
    if (!MultiByteToWideChar(CP_UTF8, 0, string, -1, wstring, len))
    {
        free(string);
        free(wstring);
        return;
    }
    free(string);
    string = malloc(2 * len);
    if (!WideCharToMultiByte(GetConsoleOutputCP(), 0, wstring, -1, string, len,
                             NULL, NULL))
    {
        free(string);
        free(wstring);
        return;
    }
    free(wstring);
#endif

    /* Print it */
    fprintf( stderr, "%s", string );
    free(string);
}

/**********************************************************************
 * hb_log
 **********************************************************************
 * If verbose mode is one, print message with timestamp. Messages
 * longer than 180 characters are stripped ;p
 *********************************************************************/
void hb_log( char * log, ... )
{
    va_list     args;

    va_start( args, log );
    hb_valog( 0, NULL, log, args );
    va_end( args );
}

/**********************************************************************
 * hb_deep_log
 **********************************************************************
 * If verbose mode is >= level, print message with timestamp. Messages
 * longer than 360 characters are stripped ;p
 *********************************************************************/
void hb_deep_log( hb_debug_level_t level, char * log, ... )
{
    va_list     args;

    va_start( args, log );
    hb_valog( level, NULL, log, args );
    va_end( args );
}

/**********************************************************************
 * hb_error
 **********************************************************************
 * Using whatever output is available display this error.
 *********************************************************************/
void hb_error( char * log, ... )
{
    char        string[181]; /* 180 chars + \0 */
    char        rep_string[181];
    static char last_string[181];
    static int  last_error_count = 0;
    static uint64_t last_series_error_time = 0;
    static hb_lock_t *mutex = 0;
    va_list     args;
    uint64_t time_now;

    /* Convert the message to a string */
    va_start( args, log );
    vsnprintf( string, 180, log, args );
    va_end( args );

    if( !mutex )
    {
        mutex = hb_lock_init();
    }

    hb_lock( mutex );

    time_now = hb_get_date();

    if( strcmp( string, last_string) == 0 )
    {
        /*
         * The last error and this one are the same, don't log it
         * just count it instead, unless it was more than one second
         * ago.
         */
        last_error_count++;
        if( last_series_error_time + ( 1000 * 1 ) > time_now )
        {
            hb_unlock( mutex );
            return;
        }
    }

    /*
     * A new error, or the same one more than 10sec since the last one
     * did we have any of the same counted up?
     */
    if( last_error_count > 0 )
    {
        /*
         * Print out the last error to ensure context for the last
         * repeated message.
         */
        if( error_handler )
        {
            error_handler( last_string );
        } else {
            hb_log( "%s", last_string );
        }

        if( last_error_count > 1 )
        {
            /*
             * Only print out the repeat message for more than 2 of the
             * same, since we just printed out two of them already.
             */
            snprintf( rep_string, 180, "Last error repeated %d times",
                      last_error_count - 1 );

            if( error_handler )
            {
                error_handler( rep_string );
            } else {
                hb_log( "%s", rep_string );
            }
        }

        last_error_count = 0;
    }

    last_series_error_time = time_now;

    strcpy( last_string, string );

    /*
     * Got the error in a single string, send it off to be dispatched.
     */
    if( error_handler )
    {
        error_handler( string );
    } else {
        hb_log( "%s", string );
    }

    hb_unlock( mutex );
}

void hb_register_error_handler( hb_error_handler_t * handler )
{
    error_handler = handler;
}

static void hb_update_str( char **dst, const char *src )
{
    if ( dst )
    {
        free( *dst );
        *dst = NULL;
        if ( src )
        {
            *dst = strdup( src );
        }
    }
}

/**********************************************************************
 * hb_title_init
 **********************************************************************
 *
 *********************************************************************/
hb_title_t * hb_title_init( char * path, int index )
{
    hb_title_t * t;

    t = calloc( sizeof( hb_title_t ), 1 );

    t->index         = index;
    t->playlist      = -1;
    t->list_audio    = hb_list_init();
    t->list_chapter  = hb_list_init();
    t->list_subtitle = hb_list_init();
    t->list_attachment = hb_list_init();
    t->metadata      = hb_metadata_init();
    strncat(t->path, path, sizeof(t->path) - 1);
    // default to decoding mpeg2
    t->video_id      = 0xE0;
    t->video_codec   = WORK_DECAVCODECV;
    t->video_codec_param = AV_CODEC_ID_MPEG2VIDEO;
    t->angle_count   = 1;
    t->geometry.par.num = 1;
    t->geometry.par.den = 1;

    return t;
}

/**********************************************************************
 * hb_title_close
 **********************************************************************
 *
 *********************************************************************/
void hb_title_close( hb_title_t ** _t )
{
    hb_title_t * t = *_t;
    hb_audio_t * audio;
    hb_chapter_t * chapter;
    hb_subtitle_t * subtitle;
    hb_attachment_t * attachment;

    while( ( chapter = hb_list_item( t->list_chapter, 0 ) ) )
    {
        hb_list_rem( t->list_chapter, chapter );
        hb_chapter_close( &chapter );
    }
    hb_list_close( &t->list_chapter );

    while( ( audio = hb_list_item( t->list_audio, 0 ) ) )
    {
        hb_list_rem( t->list_audio, audio );
        hb_audio_close( &audio );
    }
    hb_list_close( &t->list_audio );

    while( ( subtitle = hb_list_item( t->list_subtitle, 0 ) ) )
    {
        hb_list_rem( t->list_subtitle, subtitle );
        hb_subtitle_close( &subtitle );
    }
    hb_list_close( &t->list_subtitle );

    while( ( attachment = hb_list_item( t->list_attachment, 0 ) ) )
    {
        hb_list_rem( t->list_attachment, attachment );
        hb_attachment_close( &attachment );
    }
    hb_list_close( &t->list_attachment );

    hb_metadata_close( &t->metadata );

    free( t->video_codec_name );
    free(t->container_name);

    free( t );
    *_t = NULL;
}

static void job_setup(hb_job_t * job, hb_title_t * title)
{
    if ( job == NULL || title == NULL )
        return;

    job->title = title;

    /* Set defaults settings */
    job->chapter_start = 1;
    job->chapter_end   = hb_list_count( title->list_chapter );
    job->list_chapter = hb_chapter_list_copy( title->list_chapter );

    /* Autocrop by default. Gnark gnark */
    memcpy( job->crop, title->crop, 4 * sizeof( int ) );


    hb_geometry_t resultGeo, srcGeo;
    hb_geometry_settings_t uiGeo;

    srcGeo = title->geometry;

    memset(&uiGeo, 0, sizeof(uiGeo));
    memcpy(uiGeo.crop, title->crop, 4 * sizeof( int ));
    uiGeo.geometry.width = srcGeo.width - uiGeo.crop[2] - uiGeo.crop[3];
    uiGeo.geometry.height = srcGeo.height - uiGeo.crop[0] - uiGeo.crop[1];
    uiGeo.mode = HB_ANAMORPHIC_NONE;
    uiGeo.keep = HB_KEEP_DISPLAY_ASPECT;

    hb_set_anamorphic_size2(&srcGeo, &uiGeo, &resultGeo);
    job->width = resultGeo.width;
    job->height = resultGeo.height;
    job->par = resultGeo.par;

    job->vcodec     = HB_VCODEC_FFMPEG_MPEG4;
    job->vquality   = HB_INVALID_VIDEO_QUALITY;
    job->vbitrate   = 1000;
    job->twopass    = 0;
    job->pass_id    = HB_PASS_ENCODE;
    job->vrate      = title->vrate;

    job->mux = HB_MUX_MP4;

    job->list_audio = hb_list_init();
    job->list_subtitle = hb_list_init();
    job->list_filter = hb_list_init();

    job->list_attachment = hb_attachment_list_copy( title->list_attachment );
    job->metadata = hb_metadata_copy( title->metadata );

#ifdef USE_QSV
    job->qsv.enc_info.is_init_done = 0;
    job->qsv.async_depth           = AV_QSV_ASYNC_DEPTH_DEFAULT;
    job->qsv.decode                = !!(title->video_decode_support &
                                        HB_DECODE_SUPPORT_QSV);
#endif
}

static void job_clean( hb_job_t * job )
{
    if (job)
    {
        hb_chapter_t *chapter;
        hb_audio_t *audio;
        hb_subtitle_t *subtitle;
        hb_filter_object_t *filter;
        hb_attachment_t *attachment;

        free((void*)job->json);
        job->json = NULL;
        free(job->encoder_preset);
        job->encoder_preset = NULL;
        free(job->encoder_tune);
        job->encoder_tune = NULL;
        free(job->encoder_options);
        job->encoder_options = NULL;
        free(job->encoder_profile);
        job->encoder_profile = NULL;
        free(job->encoder_level);
        job->encoder_level = NULL;
        free(job->file);
        job->file = NULL;

        // clean up chapter list
        while( ( chapter = hb_list_item( job->list_chapter, 0 ) ) )
        {
            hb_list_rem( job->list_chapter, chapter );
            hb_chapter_close( &chapter );
        }
        hb_list_close( &job->list_chapter );

        // clean up audio list
        while( ( audio = hb_list_item( job->list_audio, 0 ) ) )
        {
            hb_list_rem( job->list_audio, audio );
            hb_audio_close( &audio );
        }
        hb_list_close( &job->list_audio );

        // clean up subtitle list
        while( ( subtitle = hb_list_item( job->list_subtitle, 0 ) ) )
        {
            hb_list_rem( job->list_subtitle, subtitle );
            hb_subtitle_close( &subtitle );
        }
        hb_list_close( &job->list_subtitle );

        // clean up filter list
        while( ( filter = hb_list_item( job->list_filter, 0 ) ) )
        {
            hb_list_rem( job->list_filter, filter );
            hb_filter_close( &filter );
        }
        hb_list_close( &job->list_filter );

        // clean up attachment list
        while( ( attachment = hb_list_item( job->list_attachment, 0 ) ) )
        {
            hb_list_rem( job->list_attachment, attachment );
            hb_attachment_close( &attachment );
        }
        hb_list_close( &job->list_attachment );

        // clean up metadata
        hb_metadata_close( &job->metadata );
    }
}

hb_title_t * hb_find_title_by_index( hb_handle_t *h, int title_index )
{
    hb_title_set_t *title_set = hb_get_title_set( h );
    int ii;

    for (ii = 0; ii < hb_list_count(title_set->list_title); ii++)
    {
        hb_title_t *title = hb_list_item(title_set->list_title, ii);
        if (title_index == title->index)
        {
            return title;
        }
    }
    return NULL;
}

/*
 * Create a pristine job structure from a title
 * title_index is 1 based
 */
hb_job_t * hb_job_init_by_index( hb_handle_t * h, int title_index )
{
    hb_title_t * title = hb_find_title_by_index(h, title_index);
    if (title == NULL)
        return NULL;
    return hb_job_init(title);
}

hb_job_t * hb_job_init( hb_title_t * title )
{
    hb_job_t * job;

    if ( title == NULL )
        return NULL;

    job = calloc( sizeof( hb_job_t ), 1 );
    job_setup(job, title);

    return job;
}

/**********************************************************************
 * hb_job_close
 **********************************************************************
 *
 *********************************************************************/
void hb_job_close( hb_job_t ** _j )
{
    if (_j && *_j)
    {
        job_clean(*_j);
        free( *_j );
        _j = NULL;
    }
}

void hb_job_set_encoder_preset(hb_job_t *job, const char *preset)
{
    if (job != NULL)
    {
        if (preset == NULL || preset[0] == 0)
        {
            preset = NULL;
        }
        hb_update_str(&job->encoder_preset, preset);
    }
}

void hb_job_set_encoder_tune(hb_job_t *job, const char *tune)
{
    if (job != NULL)
    {
        if (tune == NULL || tune[0] == 0)
        {
            tune = NULL;
        }
        hb_update_str(&job->encoder_tune, tune);
    }
}

void hb_job_set_encoder_options(hb_job_t *job, const char *options)
{
    if (job != NULL)
    {
        if (options == NULL || options[0] == 0)
        {
            options = NULL;
        }
        hb_update_str(&job->encoder_options, options);
    }
}

void hb_job_set_encoder_profile(hb_job_t *job, const char *profile)
{
    if (job != NULL)
    {
        if (profile == NULL || profile[0] == 0)
        {
            profile = NULL;
        }
        hb_update_str(&job->encoder_profile, profile);
    }
}

void hb_job_set_encoder_level(hb_job_t *job, const char *level)
{
    if (job != NULL)
    {
        if (level == NULL || level[0] == 0)
        {
            level = NULL;
        }
        hb_update_str(&job->encoder_level, level);
    }
}

void hb_job_set_file(hb_job_t *job, const char *file)
{
    if (job != NULL)
    {
        hb_update_str(&job->file, file);
    }
}

hb_filter_object_t * hb_filter_copy( hb_filter_object_t * filter )
{
    if( filter == NULL )
        return NULL;

    hb_filter_object_t * filter_copy = malloc( sizeof( hb_filter_object_t ) );
    memcpy( filter_copy, filter, sizeof( hb_filter_object_t ) );
    if( filter->settings )
        filter_copy->settings = hb_value_dup(filter->settings);
    return filter_copy;
}

/**********************************************************************
 * hb_filter_list_copy
 **********************************************************************
 *
 *********************************************************************/
hb_list_t *hb_filter_list_copy(const hb_list_t *src)
{
    hb_list_t *list = hb_list_init();
    hb_filter_object_t *filter = NULL;
    int i;

    if( src )
    {
        for( i = 0; i < hb_list_count(src); i++ )
        {
            if( ( filter = hb_list_item( src, i ) ) )
            {
                hb_list_add( list, hb_filter_copy(filter) );
            }
        }
    }
    return list;
}

hb_filter_object_t * hb_filter_find(const hb_list_t *list, int filter_id)
{
    hb_filter_object_t *filter = NULL;
    int ii;

    if (list == NULL)
    {
        return NULL;
    }
    for (ii = 0; ii < hb_list_count(list); ii++)
    {
        filter = hb_list_item(list, ii);
        if (filter->id == filter_id)
        {
            return filter;
        }
    }

    return NULL;
}

/**
 * Gets a filter object with the given type
 * @param filter_id The type of filter to get.
 * @returns The requested filter object.
 */
hb_filter_object_t * hb_filter_get( int filter_id )
{
    hb_filter_object_t * filter;
    switch( filter_id )
    {
        case HB_FILTER_DETELECINE:
            filter = &hb_filter_detelecine;
            break;

        case HB_FILTER_COMB_DETECT:
            filter = &hb_filter_comb_detect;
            break;

        case HB_FILTER_DECOMB:
            filter = &hb_filter_decomb;
            break;

        case HB_FILTER_DEINTERLACE:
            filter = &hb_filter_deinterlace;
            break;

        case HB_FILTER_VFR:
            filter = &hb_filter_vfr;
            break;

        case HB_FILTER_DEBLOCK:
            filter = &hb_filter_deblock;
            break;

        case HB_FILTER_DENOISE:
            filter = &hb_filter_denoise;
            break;

        case HB_FILTER_NLMEANS:
            filter = &hb_filter_nlmeans;
            break;

        case HB_FILTER_RENDER_SUB:
            filter = &hb_filter_render_sub;
            break;

        case HB_FILTER_CROP_SCALE:
            filter = &hb_filter_crop_scale;
            break;

        case HB_FILTER_AVFILTER:
            filter = &hb_filter_avfilter;
            break;

        case HB_FILTER_PAD:
            filter = &hb_filter_pad;
            break;

        case HB_FILTER_ROTATE:
            filter = &hb_filter_rotate;
            break;

        case HB_FILTER_GRAYSCALE:
            filter = &hb_filter_grayscale;
            break;

#ifdef USE_QSV
        case HB_FILTER_QSV:
            filter = &hb_filter_qsv;
            break;

        case HB_FILTER_QSV_PRE:
            filter = &hb_filter_qsv_pre;
            break;

        case HB_FILTER_QSV_POST:
            filter = &hb_filter_qsv_post;
            break;
#endif

        default:
            filter = NULL;
            break;
    }
    return filter;
}

hb_filter_object_t * hb_filter_init( int filter_id )
{
    return hb_filter_copy(hb_filter_get(filter_id));
}

/**********************************************************************
 * hb_filter_close
 **********************************************************************
 *
 *********************************************************************/
void hb_filter_close( hb_filter_object_t ** _f )
{
    hb_filter_object_t * f = *_f;

    hb_value_free(&f->settings);

    free( f );
    *_f = NULL;
}

/**********************************************************************
 * hb_filter_info_close
 **********************************************************************
 *
 *********************************************************************/
void hb_filter_info_close( hb_filter_info_t ** _fi )
{
    hb_filter_info_t * fi = *_fi;

    if (fi != NULL)
    {
        free(fi->human_readable_desc);
    }

    free( fi );
    *_fi = NULL;
}

static char * append_string(char * dst, const char * src)
{
    int dst_len = 0, src_len, len;

    if (src == NULL)
    {
        return dst;
    }

    src_len = len = strlen(src) + 1;
    if (dst != NULL)
    {
        dst_len = strlen(dst);
        len += dst_len;
    }
    char * tmp = realloc(dst, len);
    if (tmp == NULL)
    {
        // Failed to allocate required space
        return dst;
    }
    dst = tmp;
    memcpy(dst + dst_len, src, src_len);
    return dst;
}

static char * stringify_array(int filter_id, hb_value_array_t * array)
{
    char * result = strdup("");
    int    ii;
    int    len = hb_value_array_len(array);
    int    first = 1;

    if (hb_value_array_len(array) == 0)
    {
        return result;
    }
    for (ii = 0; ii < len; ii++)
    {
        hb_value_t * val = hb_value_array_get(array, ii);
        char       * str = hb_filter_settings_string(filter_id, val);
        if (str != NULL)
        {
            if (!first)
            {
                result = append_string(result, ",");
            }
            first = 0;
            if (hb_value_type(val) == HB_VALUE_TYPE_DICT)
            {
                result = append_string(result, str);
            }
            else if (hb_value_type(val) == HB_VALUE_TYPE_ARRAY)
            {
                result = append_string(result, "[");
                result = append_string(result, str);
                result = append_string(result, "]");
            }
            else
            {
                result = append_string(result, str);
            }
            free(str);
        }
    }

    return result;
}

static char * stringify_dict(int filter_id, hb_dict_t * dict)
{
    char            * result = strdup("");
    const char      * key;
    char           ** keys = NULL;
    hb_value_t      * val;
    hb_dict_iter_t    iter;
    int               first = 1;

    if (hb_dict_elements(dict) == 0)
    {
        return result;
    }
    // Check for dict containing rational value
    if (hb_dict_elements(dict) == 2)
    {
        hb_value_t *num_val = hb_dict_get(dict, "Num");
        hb_value_t *den_val = hb_dict_get(dict, "Den");
        if (num_val != NULL && den_val != NULL &&
            hb_value_type(num_val) == HB_VALUE_TYPE_INT &&
            hb_value_type(den_val) == HB_VALUE_TYPE_INT)
        {
            int num = hb_value_get_int(num_val);
            int den = hb_value_get_int(den_val);
            char * str = hb_strdup_printf("%d/%d", num, den);
            result = append_string(result, str);
            free(str);
            return result;
        }
    }
    hb_filter_object_t * filter = hb_filter_get(filter_id);
    if (filter != NULL)
    {
        keys = hb_filter_get_keys(filter_id);
        if (keys != NULL && keys[0] == NULL)
        {
            hb_str_vfree(keys);
            keys = NULL;
        }
    }

    int done, ii = 0;
    iter = hb_dict_iter_init(dict);
    if (keys == NULL)
    {
        done = !hb_dict_iter_next_ex(dict, &iter, &key, NULL);
    }
    else
    {
        done = (key = keys[ii]) == NULL;
    }
    while (!done)
    {
        val = hb_dict_get(dict, key);
        if (val != NULL)
        {
            if (!first)
            {
                result = append_string(result, ":");
            }
            first = 0;
            result = append_string(result, key);
            int elements = 1;

            if (hb_value_type(val) == HB_VALUE_TYPE_NULL)
            {
                elements = 0;
            }
            else if (hb_value_type(val) == HB_VALUE_TYPE_DICT)
            {
                elements = hb_dict_elements(val);
            }
            else if (hb_value_type(val) == HB_VALUE_TYPE_ARRAY)
            {
                elements = hb_value_array_len(val);
            }
            if (elements != 0)
            {
                char * str = hb_filter_settings_string(filter_id, val);
                if (str != NULL)
                {
                    result = append_string(result, "=");
                    if (hb_value_type(val) == HB_VALUE_TYPE_DICT)
                    {
                        result = append_string(result, "'");
                        result = append_string(result, str);
                        result = append_string(result, "'");
                    }
                    else if (hb_value_type(val) == HB_VALUE_TYPE_ARRAY)
                    {
                        result = append_string(result, "[");
                        result = append_string(result, str);
                        result = append_string(result, "]");
                    }
                    else
                    {
                        result = append_string(result, str);
                    }
                    free(str);
                }
            }
        }
        ii++;
        if (keys == NULL)
        {
            done = !hb_dict_iter_next_ex(dict, &iter, &key, NULL);
        }
        else
        {
            done = (key = keys[ii]) == NULL;
        }
    }
    hb_str_vfree(keys);

    return result;
}

char * hb_filter_settings_string(int filter_id, hb_value_t * value)
{
    if (value == NULL || hb_value_type(value) == HB_VALUE_TYPE_NULL)
    {
        return strdup("");
    }
    if (hb_value_type(value) == HB_VALUE_TYPE_DICT)
    {
        return stringify_dict(filter_id, value);
    }
    if (hb_value_type(value) == HB_VALUE_TYPE_ARRAY)
    {
        return stringify_array(filter_id, value);
    }
    return hb_value_get_string_xform(value);
}

char * hb_filter_settings_string_json(int filter_id, const char * json)
{
    hb_value_t * value  = hb_value_json(json);
    char       * result = hb_filter_settings_string(filter_id, value);
    hb_value_free(&value);

    return result;
}

hb_dict_t * hb_parse_filter_settings(const char * settings_str)
{
    hb_dict_t  * dict = hb_dict_init();
    char      ** settings_list = hb_str_vsplit(settings_str, ':');
    int          ii;

    for (ii = 0; settings_list[ii] != NULL; ii++)
    {
        char * key, * value;
        char ** settings_pair = hb_str_vsplit(settings_list[ii], '=');
        if (settings_pair[0] == NULL || settings_pair[1] == NULL)
        {
            // Parse error. Not key=value pair.
            hb_str_vfree(settings_list);
            hb_str_vfree(settings_pair);
            hb_value_free(&dict);
            hb_log("hb_parse_filter_settings: Error parsing (%s)",
                   settings_str);
            return NULL;
        }
        key   = settings_pair[0];
        value = settings_pair[1];

        int last = strlen(value) - 1;
        // Check if value was quoted dictionary and remove quotes
        // and parse the sub-dictionary.  This should only happen
        // for avfilter settings.
        if (last > 0 && value[0] == '\'' && value[last] == '\'')
        {
            char * str = strdup(value + 1);
            str[last - 1] = 0;
            hb_dict_t * sub_dict = hb_parse_filter_settings(str);
            free(str);
            if (sub_dict == NULL)
            {
                // Parse error. Not key=value pair.
                hb_str_vfree(settings_list);
                hb_str_vfree(settings_pair);
                hb_value_free(&dict);
                hb_log("hb_parse_filter_settings: Error parsing (%s)",
                       settings_str);
                return NULL;
            }
            hb_dict_case_set(dict, key, sub_dict);
        }
        // Check if value was quoted string and remove quotes
        else if (last > 0 && value[0] == '"' && value[last] == '"')
        {
            char * str = strdup(value + 1);
            str[last - 1] = 0;
            hb_dict_case_set(dict, key, hb_value_string(str));
            free(str);
        }
        else
        {
            hb_dict_case_set(dict, key, hb_value_string(value));
        }

        hb_str_vfree(settings_pair);
    }
    hb_str_vfree(settings_list);

    return dict;
}

char * hb_parse_filter_settings_json(const char * settings_str)
{
    hb_dict_t * dict = hb_parse_filter_settings(settings_str);
    char      * result = hb_value_get_json(dict);
    hb_value_free(&dict);

    return result;
}

/**********************************************************************
 * hb_chapter_copy
 **********************************************************************
 *
 *********************************************************************/
hb_chapter_t *hb_chapter_copy(const hb_chapter_t *src)
{
    hb_chapter_t *chap = NULL;

    if ( src )
    {
        chap = calloc( 1, sizeof(*chap) );
        memcpy( chap, src, sizeof(*chap) );
        if ( src->title )
        {
            chap->title = strdup( src->title );
        }
    }
    return chap;
}

/**********************************************************************
 * hb_chapter_list_copy
 **********************************************************************
 *
 *********************************************************************/
hb_list_t *hb_chapter_list_copy(const hb_list_t *src)
{
    hb_list_t *list = hb_list_init();
    hb_chapter_t *chapter = NULL;
    int i;

    if( src )
    {
        for( i = 0; i < hb_list_count(src); i++ )
        {
            if( ( chapter = hb_list_item( src, i ) ) )
            {
                hb_list_add( list, hb_chapter_copy(chapter) );
            }
        }
    }
    return list;
}

/**********************************************************************
 * hb_chapter_close
 **********************************************************************
 *
 *********************************************************************/
void hb_chapter_close(hb_chapter_t **chap)
{
    if ( chap && *chap )
    {
        free((*chap)->title);
        free(*chap);
        *chap = NULL;
    }
}

/**********************************************************************
 * hb_chapter_set_title
 **********************************************************************
 *
 *********************************************************************/
void hb_chapter_set_title( hb_chapter_t *chapter, const char *title )
{
    if ( chapter )
    {
        hb_update_str( &chapter->title, title );
    }
}

/**********************************************************************
 * hb_chapter_set_title_by_index
 **********************************************************************
 * Applies information from the given job to the official job instance.
 * @param job Handle to hb_job_t.
 * @param chapter The chapter to apply the name to (1-based).
 * @param titel to apply.
 *********************************************************************/
void hb_chapter_set_title_by_index( hb_job_t * job, int chapter_index, const char * title )
{
    hb_chapter_t * chapter = hb_list_item( job->list_chapter, chapter_index - 1 );
    hb_chapter_set_title( chapter, title );
}

/**********************************************************************
 * hb_audio_copy
 **********************************************************************
 *
 *********************************************************************/
hb_audio_t *hb_audio_copy(const hb_audio_t *src)
{
    hb_audio_t *audio = NULL;

    if( src )
    {
        audio = calloc(1, sizeof(*audio));
        memcpy(audio, src, sizeof(*audio));
        if ( src->config.out.name )
        {
            audio->config.out.name = strdup(src->config.out.name);
        }
    }
    return audio;
}

/**********************************************************************
 * hb_audio_list_copy
 **********************************************************************
 *
 *********************************************************************/
hb_list_t *hb_audio_list_copy(const hb_list_t *src)
{
    hb_list_t *list = hb_list_init();
    hb_audio_t *audio = NULL;
    int i;

    if( src )
    {
        for( i = 0; i < hb_list_count(src); i++ )
        {
            if( ( audio = hb_list_item( src, i ) ) )
            {
                hb_list_add( list, hb_audio_copy(audio) );
            }
        }
    }
    return list;
}

/**********************************************************************
 * hb_audio_close
 **********************************************************************
 *
 *********************************************************************/
void hb_audio_close( hb_audio_t **audio )
{
    if ( audio && *audio )
    {
        free((*audio)->config.out.name);
        free(*audio);
        *audio = NULL;
    }
}

/**********************************************************************
 * hb_audio_new
 **********************************************************************
 *
 *********************************************************************/
void hb_audio_config_init(hb_audio_config_t * audiocfg)
{
    /* Set read-only paramaters to invalid values */
    audiocfg->in.codec = 0;
    audiocfg->in.codec_param = 0;
    audiocfg->in.reg_desc = 0;
    audiocfg->in.stream_type = 0;
    audiocfg->in.substream_type = 0;
    audiocfg->in.version = 0;
    audiocfg->in.flags = 0;
    audiocfg->in.mode = 0;
    audiocfg->in.samplerate = -1;
    audiocfg->in.sample_bit_depth = 0;
    audiocfg->in.samples_per_frame = -1;
    audiocfg->in.bitrate = -1;
    audiocfg->in.matrix_encoding = AV_MATRIX_ENCODING_NONE;
    audiocfg->in.channel_layout = 0;
    audiocfg->in.channel_map = NULL;
    audiocfg->lang.description[0] = 0;
    audiocfg->lang.simple[0] = 0;
    audiocfg->lang.iso639_2[0] = 0;

    /* Initalize some sensible defaults */
    audiocfg->in.track = audiocfg->out.track = 0;
    audiocfg->out.codec = hb_audio_encoder_get_default(HB_MUX_MP4); // default container
    audiocfg->out.samplerate = -1;
    audiocfg->out.samples_per_frame = -1;
    audiocfg->out.bitrate = -1;
    audiocfg->out.quality = HB_INVALID_AUDIO_QUALITY;
    audiocfg->out.compression_level = -1;
    audiocfg->out.mixdown = HB_INVALID_AMIXDOWN;
    audiocfg->out.dynamic_range_compression = 0;
    audiocfg->out.gain = 0;
    audiocfg->out.normalize_mix_level = 0;
    audiocfg->out.dither_method = hb_audio_dither_get_default();
    audiocfg->out.name = NULL;
}

/**********************************************************************
 * hb_audio_add
 **********************************************************************
 *
 *********************************************************************/
int hb_audio_add(const hb_job_t * job, const hb_audio_config_t * audiocfg)
{
    hb_title_t *title = job->title;
    hb_audio_t *audio;

    audio = hb_audio_copy( hb_list_item( title->list_audio, audiocfg->in.track ) );
    if( audio == NULL )
    {
        /* We fail! */
        return 0;
    }

    if( (audiocfg->in.bitrate != -1) && (audiocfg->in.codec != 0xDEADBEEF) )
    {
        /* This most likely means the client didn't call hb_audio_config_init
         * so bail. */
        return 0;
    }

    /* Set the job's "in track" to the value passed in audiocfg.
     * HandBrakeCLI assumes this value is preserved in the jobs
     * audio list, but in.track in the title's audio list is not
     * required to be the same. */
    // "track" in title->list_audio is an index into the source's tracks.
    // "track" in job->list_audio is an index into title->list_audio
    audio->config.in.track = audiocfg->in.track;

    /* Really shouldn't ignore the passed out track, but there is currently no
     * way to handle duplicates or out-of-order track numbers. */
    audio->config.out.track = hb_list_count(job->list_audio) + 1;
    int codec = audiocfg->out.codec;
    if(!(codec & HB_ACODEC_PASS_FLAG) ||
       ((codec & HB_ACODEC_PASS_FLAG) &&
        !(codec & audio->config.in.codec) &&
        hb_audio_encoder_is_enabled(codec & ~HB_ACODEC_PASS_FLAG)))
    {
        audio->config.out.codec = codec & ~HB_ACODEC_PASS_FLAG;
        audio->config.out.samplerate = audiocfg->out.samplerate;
        audio->config.out.bitrate = audiocfg->out.bitrate;
        audio->config.out.compression_level = audiocfg->out.compression_level;
        audio->config.out.quality = audiocfg->out.quality;
        audio->config.out.dynamic_range_compression = audiocfg->out.dynamic_range_compression;
        audio->config.out.mixdown = audiocfg->out.mixdown;
        audio->config.out.gain = audiocfg->out.gain;
        audio->config.out.normalize_mix_level = audiocfg->out.normalize_mix_level;
        audio->config.out.dither_method = audiocfg->out.dither_method;
    }
    else
    {
        /* Pass-through, copy from input. */
        audio->config.out.codec = codec;
        audio->config.out.samplerate = audio->config.in.samplerate;
        audio->config.out.bitrate = audio->config.in.bitrate;
        audio->config.out.mixdown = HB_AMIXDOWN_NONE;
        audio->config.out.dynamic_range_compression = 0;
        audio->config.out.gain = 0;
        audio->config.out.normalize_mix_level = 0;
        audio->config.out.compression_level = -1;
        audio->config.out.quality = HB_INVALID_AUDIO_QUALITY;
        audio->config.out.dither_method = hb_audio_dither_get_default();
    }
    if (audiocfg->out.name && *audiocfg->out.name)
    {
        audio->config.out.name = strdup(audiocfg->out.name);
    }

    hb_list_add(job->list_audio, audio);
    return 1;
}

hb_audio_config_t * hb_list_audio_config_item(hb_list_t * list, int i)
{
    hb_audio_t *audio = NULL;

    if( (audio = hb_list_item(list, i)) )
        return &(audio->config);

    return NULL;
}

/**********************************************************************
 * hb_subtitle_copy
 **********************************************************************
 *
 *********************************************************************/
hb_subtitle_t *hb_subtitle_copy(const hb_subtitle_t *src)
{
    hb_subtitle_t *subtitle = NULL;

    if( src )
    {
        subtitle = calloc(1, sizeof(*subtitle));
        memcpy(subtitle, src, sizeof(*subtitle));
        if ( src->extradata )
        {
            subtitle->extradata = malloc( src->extradata_size );
            memcpy( subtitle->extradata, src->extradata, src->extradata_size );
        }
    }
    return subtitle;
}

/**********************************************************************
 * hb_subtitle_list_copy
 **********************************************************************
 *
 *********************************************************************/
hb_list_t *hb_subtitle_list_copy(const hb_list_t *src)
{
    hb_list_t *list = hb_list_init();
    hb_subtitle_t *subtitle = NULL;
    int i;

    if( src )
    {
        for( i = 0; i < hb_list_count(src); i++ )
        {
            if( ( subtitle = hb_list_item( src, i ) ) )
            {
                hb_list_add( list, hb_subtitle_copy(subtitle) );
            }
        }
    }
    return list;
}

/**********************************************************************
 * hb_subtitle_close
 **********************************************************************
 *
 *********************************************************************/
void hb_subtitle_close( hb_subtitle_t **sub )
{
    if ( sub && *sub )
    {
        free ((*sub)->extradata);
        free(*sub);
        *sub = NULL;
    }
}

/**********************************************************************
 * hb_subtitle_add
 **********************************************************************
 *
 *********************************************************************/
int hb_subtitle_add_ssa_header(hb_subtitle_t *subtitle, const char *font,
                               int fs, int w, int h)
{
    // Free any pre-existing extradata
    free(subtitle->extradata);

    // SRT subtitles are represented internally as SSA
    // Create an SSA header
    const char * ssa_header =
        "[Script Info]\r\n"
        "ScriptType: v4.00+\r\n"
        "Collisions: Normal\r\n"
        "PlayResX: %d\r\n"
        "PlayResY: %d\r\n"
        "Timer: 100.0\r\n"
        "WrapStyle: 0\r\n"
        "\r\n"
        "[V4+ Styles]\r\n"
        "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\r\n"
        "Style: Default,%s,%d,&H00FFFFFF,&H00FFFFFF,&H000F0F0F,&H000F0F0F,0,0,0,0,100,100,0,0.00,1,2,3,2,20,20,20,0\r\n";

    subtitle->extradata = (uint8_t*)hb_strdup_printf(ssa_header, w, h, font, fs);
    if (subtitle->extradata == NULL)
    {
        hb_error("hb_subtitle_add_ssa_header: malloc failed");
        return 0;
    }
    subtitle->extradata_size = strlen((char*)subtitle->extradata) + 1;

    return 1;
}

int hb_subtitle_add(const hb_job_t * job, const hb_subtitle_config_t * subtitlecfg, int track)
{
    hb_title_t *title = job->title;
    hb_subtitle_t *subtitle;

    subtitle = hb_subtitle_copy( hb_list_item( title->list_subtitle, track ) );
    if( subtitle == NULL )
    {
        /* We fail! */
        return 0;
    }

    // "track" in title->list_audio is an index into the source's tracks.
    // "track" in job->list_audio is an index into title->list_audio
    subtitle->track = track;
    subtitle->config = *subtitlecfg;
    subtitle->out_track = hb_list_count(job->list_subtitle) + 1;
    hb_list_add(job->list_subtitle, subtitle);
    return 1;
}

int hb_srt_add( const hb_job_t * job,
                const hb_subtitle_config_t * subtitlecfg,
                const char *lang )
{
    hb_subtitle_t *subtitle;
    iso639_lang_t *language = NULL;

    subtitle = calloc( 1, sizeof( *subtitle ) );
    if (subtitle == NULL)
    {
        hb_error("hb_srt_add: malloc failed");
        return 0;
    }

    subtitle->id = (hb_list_count(job->list_subtitle) << 8) | 0xFF;
    subtitle->format = TEXTSUB;
    subtitle->source = SRTSUB;
    subtitle->codec = WORK_DECSRTSUB;

    language = lang_for_code2(lang);
    if (language == NULL)
    {
        hb_log("hb_srt_add: unknown language code (%s)", lang);
        language = lang_for_code2("und");
    }
    strcpy(subtitle->lang, language->eng_name);
    strcpy(subtitle->iso639_2, language->iso639_2);

    subtitle->config = *subtitlecfg;
    hb_list_add(job->list_subtitle, subtitle);

    return 1;
}

int hb_subtitle_can_force( int source )
{
    return source == VOBSUB || source == PGSSUB;
}

int hb_subtitle_can_burn( int source )
{
    return source == VOBSUB  || source == PGSSUB   || source == SSASUB  ||
           source == SRTSUB  || source == CC608SUB || source == UTF8SUB ||
           source == TX3GSUB;
}

int hb_subtitle_can_pass( int source, int mux )
{
    switch (mux)
    {
        case HB_MUX_AV_MKV:
            switch( source )
            {
                case PGSSUB:
                case VOBSUB:
                case SSASUB:
                case SRTSUB:
                case UTF8SUB:
                case TX3GSUB:
                case CC608SUB:
                case CC708SUB:
                    return 1;

                default:
                    return 0;
            } break;

        case HB_MUX_AV_MP4:
            switch( source )
            {
                case VOBSUB:
                case SSASUB:
                case SRTSUB:
                case UTF8SUB:
                case TX3GSUB:
                case CC608SUB:
                case CC708SUB:
                    return 1;

                default:
                    return 0;
            } break;

        default:
            // Internal error. Should never get here.
            hb_error("internel error.  Bad mux %d\n", mux);
            return 0;
    }
}

int hb_audio_can_apply_drc(uint32_t codec, uint32_t codec_param, int encoder)
{
    if (encoder & HB_ACODEC_PASS_FLAG)
    {
        // can't apply DRC to passthrough audio
        return 0;
    }
    else if (codec & HB_ACODEC_FF_MASK)
    {
        return (codec_param == AV_CODEC_ID_AC3 ||
                codec_param == AV_CODEC_ID_EAC3);
    }
    else if (codec == HB_ACODEC_AC3)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int hb_audio_can_apply_drc2(hb_handle_t *h, int title_idx, int audio_idx, int encoder)
{
    hb_title_t *title = hb_find_title_by_index(h, title_idx);
    if (title == NULL)
        return 0;

    hb_audio_t *audio = hb_list_item(title->list_audio, audio_idx);
    if (audio == NULL)
        return 0;

    return hb_audio_can_apply_drc(audio->config.in.codec,
                                  audio->config.in.codec_param, encoder);
}

/**********************************************************************
 * hb_metadata_init
 **********************************************************************
 *
 *********************************************************************/
hb_metadata_t *hb_metadata_init()
{
    hb_metadata_t *metadata = calloc( 1, sizeof(*metadata) );
    return metadata;
}

/**********************************************************************
 * hb_metadata_copy
 **********************************************************************
 *
 *********************************************************************/
hb_metadata_t *hb_metadata_copy( const hb_metadata_t *src )
{
    hb_metadata_t *metadata = NULL;

    if ( src )
    {
        metadata = calloc( 1, sizeof(*metadata) );
        if ( src->name )
        {
            metadata->name = strdup(src->name);
        }
        if ( src->artist )
        {
            metadata->artist = strdup(src->artist);
        }
        if ( src->album_artist )
        {
            metadata->album_artist = strdup(src->album_artist);
        }
        if ( src->composer )
        {
            metadata->composer = strdup(src->composer);
        }
        if ( src->release_date )
        {
            metadata->release_date = strdup(src->release_date);
        }
        if ( src->comment )
        {
            metadata->comment = strdup(src->comment);
        }
        if ( src->album )
        {
            metadata->album = strdup(src->album);
        }
        if ( src->genre )
        {
            metadata->genre = strdup(src->genre);
        }
        if ( src->description )
        {
            metadata->description = strdup(src->description);
        }
        if ( src->long_description )
        {
            metadata->long_description = strdup(src->long_description);
        }
        if ( src->list_coverart )
        {
            int ii;
            for ( ii = 0; ii < hb_list_count( src->list_coverart ); ii++ )
            {
                hb_coverart_t *art = hb_list_item( src->list_coverart, ii );
                hb_metadata_add_coverart(
                        metadata, art->data, art->size, art->type );
            }
        }
    }
    return metadata;
}

/**********************************************************************
 * hb_metadata_close
 **********************************************************************
 *
 *********************************************************************/
void hb_metadata_close( hb_metadata_t **_m )
{
    if ( _m && *_m )
    {
        hb_metadata_t *m = *_m;
        hb_coverart_t *art;

        free( m->name );
        free( m->artist );
        free( m->composer );
        free( m->release_date );
        free( m->comment );
        free( m->album );
        free( m->album_artist );
        free( m->genre );
        free( m->description );
        free( m->long_description );

        if ( m->list_coverart )
        {
            while( ( art = hb_list_item( m->list_coverart, 0 ) ) )
            {
                hb_list_rem( m->list_coverart, art );
                free( art->data );
                free( art );
            }
            hb_list_close( &m->list_coverart );
        }

        free( m );
        *_m = NULL;
    }
}

/**********************************************************************
 * hb_metadata_set_*
 **********************************************************************
 *
 *********************************************************************/
void hb_metadata_set_name( hb_metadata_t *metadata, const char *name )
{
    if ( metadata )
    {
        hb_update_str( &metadata->name, name );
    }
}

void hb_metadata_set_artist( hb_metadata_t *metadata, const char *artist )
{
    if ( metadata )
    {
        hb_update_str( &metadata->artist, artist );
    }
}

void hb_metadata_set_composer( hb_metadata_t *metadata, const char *composer )
{
    if ( metadata )
    {
        hb_update_str( &metadata->composer, composer );
    }
}

void hb_metadata_set_release_date( hb_metadata_t *metadata, const char *release_date )
{
    if ( metadata )
    {
        hb_update_str( &metadata->release_date, release_date );
    }
}

void hb_metadata_set_comment( hb_metadata_t *metadata, const char *comment )
{
    if ( metadata )
    {
        hb_update_str( &metadata->comment, comment );
    }
}

void hb_metadata_set_genre( hb_metadata_t *metadata, const char *genre )
{
    if ( metadata )
    {
        hb_update_str( &metadata->genre, genre );
    }
}

void hb_metadata_set_album( hb_metadata_t *metadata, const char *album )
{
    if ( metadata )
    {
        hb_update_str( &metadata->album, album );
    }
}

void hb_metadata_set_album_artist( hb_metadata_t *metadata, const char *album_artist )
{
    if ( metadata )
    {
        hb_update_str( &metadata->album_artist, album_artist );
    }
}

void hb_metadata_set_description( hb_metadata_t *metadata, const char *description )
{
    if ( metadata )
    {
        hb_update_str( &metadata->description, description );
    }
}

void hb_metadata_set_long_description( hb_metadata_t *metadata, const char *long_description )
{
    if ( metadata )
    {
        hb_update_str( &metadata->long_description, long_description );
    }
}

void hb_metadata_add_coverart( hb_metadata_t *metadata, const uint8_t *data, int size, int type )
{
    if ( metadata )
    {
        if ( metadata->list_coverart == NULL )
        {
            metadata->list_coverart = hb_list_init();
        }
        hb_coverart_t *art = calloc( 1, sizeof(hb_coverart_t) );
        art->data = malloc( size );
        memcpy( art->data, data, size );
        art->size = size;
        art->type = type;
        hb_list_add( metadata->list_coverart, art );
    }
}

void hb_metadata_rem_coverart( hb_metadata_t *metadata, int idx )
{
    if ( metadata )
    {
        hb_coverart_t *art = hb_list_item( metadata->list_coverart, idx );
        if ( art )
        {
            hb_list_rem( metadata->list_coverart, art );
            free( art->data );
            free( art );
        }
    }
}

char * hb_strdup_vaprintf( const char * fmt, va_list args )
{
    int       len;
    int       size = 256;
    char    * str;
    char    * tmp;
    va_list   copy;

    str = malloc( size );
    if ( str == NULL )
        return NULL;

    while (1)
    {
        // vsnprintf modifies it's va_list.  Since we may need to do this
        // more than once, use a copy of the va_list.
        va_copy(copy, args);

        /* Try to print in the allocated space. */
        len = vsnprintf( str, size, fmt, copy );

        /* If that worked, return the string. */
        if ( len > -1 && len < size )
        {
            return str;
        }

        /* Else try again with more space. */
        if ( len > -1 )     /* glibc 2.1 */
            size = len + 1; /* precisely what is needed */
        else                /* glibc 2.0 */
            size *= 2;      /* twice the old size */
        tmp = realloc( str, size );
        if ( tmp == NULL )
        {
            free( str );
            return NULL;
        }
        else
            str = tmp;
    }

    return str;
}

char * hb_strdup_printf( const char * fmt, ... )
{
    char    * str;
    va_list   args;

    va_start( args, fmt );
    str = hb_strdup_vaprintf( fmt, args );
    va_end( args );

    return str;
}

char * hb_strncat_dup( const char * s1, const char * s2, size_t n )
{
    size_t len;
    char * str;

    len = 0;
    if( s1 )
        len += strlen( s1 );
    if( s2 )
        len += MAX( strlen( s2 ), n );
    if( !len )
        return NULL;

    str = malloc( len + 1 );
    if( !str )
        return NULL;

    if( s1 )
        strcpy( str, s1 );
    else
        strcpy( str, "" );
    strncat( str, s2, n );
    return str;
}

/**********************************************************************
 * hb_attachment_copy
 **********************************************************************
 *
 *********************************************************************/
hb_attachment_t *hb_attachment_copy(const hb_attachment_t *src)
{
    hb_attachment_t *attachment = NULL;

    if( src )
    {
        attachment = calloc(1, sizeof(*attachment));
        memcpy(attachment, src, sizeof(*attachment));
        if ( src->name )
        {
            attachment->name = strdup( src->name );
        }
        if ( src->data )
        {
            attachment->data = malloc( src->size );
            memcpy( attachment->data, src->data, src->size );
        }
    }
    return attachment;
}

/**********************************************************************
 * hb_attachment_list_copy
 **********************************************************************
 *
 *********************************************************************/
hb_list_t *hb_attachment_list_copy(const hb_list_t *src)
{
    hb_list_t *list = hb_list_init();
    hb_attachment_t *attachment = NULL;
    int i;

    if( src )
    {
        for( i = 0; i < hb_list_count(src); i++ )
        {
            if( ( attachment = hb_list_item( src, i ) ) )
            {
                hb_list_add( list, hb_attachment_copy(attachment) );
            }
        }
    }
    return list;
}

/**********************************************************************
 * hb_attachment_close
 **********************************************************************
 *
 *********************************************************************/
void hb_attachment_close( hb_attachment_t **attachment )
{
    if ( attachment && *attachment )
    {
        free((*attachment)->data);
        free((*attachment)->name);
        free(*attachment);
        *attachment = NULL;
    }
}

/**********************************************************************
 * hb_yuv2rgb
 **********************************************************************
 * Converts a YCrCb pixel to an RGB pixel.
 *
 * This conversion is lossy (due to rounding and clamping).
 *
 * Algorithm:
 *   http://en.wikipedia.org/w/index.php?title=YCbCr&oldid=361987695#Technical_details
 *********************************************************************/
int hb_yuv2rgb(int yuv)
{
    double y, Cr, Cb;
    int r, g, b;

    y  = (yuv >> 16) & 0xff;
    Cr = (yuv >>  8) & 0xff;
    Cb = (yuv      ) & 0xff;

    r = 1.164 * (y - 16)                      + 1.596 * (Cr - 128);
    g = 1.164 * (y - 16) - 0.392 * (Cb - 128) - 0.813 * (Cr - 128);
    b = 1.164 * (y - 16) + 2.017 * (Cb - 128);

    r = (r < 0) ? 0 : r;
    g = (g < 0) ? 0 : g;
    b = (b < 0) ? 0 : b;

    r = (r > 255) ? 255 : r;
    g = (g > 255) ? 255 : g;
    b = (b > 255) ? 255 : b;

    return (r << 16) | (g << 8) | b;
}

/**********************************************************************
 * hb_rgb2yuv
 **********************************************************************
 * Converts an RGB pixel to a YCrCb pixel.
 *
 * This conversion is lossy (due to rounding and clamping).
 *
 * Algorithm:
 *   http://en.wikipedia.org/w/index.php?title=YCbCr&oldid=361987695#Technical_details
 *********************************************************************/
int hb_rgb2yuv(int rgb)
{
    double r, g, b;
    int y, Cr, Cb;

    r = (rgb >> 16) & 0xff;
    g = (rgb >>  8) & 0xff;
    b = (rgb      ) & 0xff;

    y  =  16. + ( 0.257 * r) + (0.504 * g) + (0.098 * b);
    Cb = 128. + (-0.148 * r) - (0.291 * g) + (0.439 * b);
    Cr = 128. + ( 0.439 * r) - (0.368 * g) - (0.071 * b);

    y = (y < 0) ? 0 : y;
    Cb = (Cb < 0) ? 0 : Cb;
    Cr = (Cr < 0) ? 0 : Cr;

    y = (y > 255) ? 255 : y;
    Cb = (Cb > 255) ? 255 : Cb;
    Cr = (Cr > 255) ? 255 : Cr;

    return (y << 16) | (Cr << 8) | Cb;
}

const char * hb_subsource_name( int source )
{
    switch (source)
    {
        case VOBSUB:
            return "VOBSUB";
        case SRTSUB:
            return "SRT";
        case CC608SUB:
            return "CC";
        case CC708SUB:
            return "CC";
        case UTF8SUB:
            return "UTF-8";
        case TX3GSUB:
            return "TX3G";
        case SSASUB:
            return "SSA";
        case PGSSUB:
            return "PGS";
        default:
            return "Unknown";
    }
}

void hb_hexdump( hb_debug_level_t level, const char * label, const uint8_t * data, int len )
{
    int ii;
    char line[80], ascii[19], *p;

    ascii[18] = 0;
    ascii[0] = '|';
    ascii[17] = '|';
    memset(&ascii[1], '.', 16);
    p = line;
    if( label )
        hb_deep_log(level, "++++ %s ++++", label);
    else
        hb_deep_log(level, "++++++++++++");
    for( ii = 0; ii < len; ii++ )
    {
        if( ( ii & 0x0f ) == 0x0f )
        {
            p += sprintf( p, "%02x", data[ii] );
            hb_deep_log( level, "    %-50s%20s", line, ascii );
            memset(&ascii[1], '.', 16);
            p = line;
        }
        else if( ( ii & 0x07 ) == 0x07 )
        {
            p += sprintf( p, "%02x  ", data[ii] );
        }
        else
        {
            p += sprintf( p, "%02x ", data[ii] );
        }
        if( isgraph( data[ii] ) )
            ascii[(ii & 0x0f) + 1] = data[ii];
        else
            ascii[(ii & 0x0f) + 1] = '.';
    }
    if( p != line )
    {
        hb_deep_log( level, "    %-50s%20s", line, ascii );
    }
}

int hb_str_vlen(char **strv)
{
    int i;
    if (strv == NULL)
        return 0;
    for (i = 0; strv[i]; i++);
    return i;
}

static const char* strchr_quote(const char *pos, char c, char q)
{
    if (pos == NULL)
        return NULL;

    while (*pos != 0 && *pos != c)
    {
        if (*pos == q)
        {
            pos = strchr_quote(pos+1, q, 0);
            if (pos == NULL)
                return NULL;
            pos++;
        }
        else if (*pos == '\\' && *(pos+1) != 0)
            pos += 2;
        else
            pos++;
    }
    if (*pos != c)
        return NULL;
    return pos;
}

static char *strndup_quote(const char *str, char q, int len)
{
    if (str == NULL)
        return NULL;

    char * res;
    int str_len = strlen( str );
    int src = 0, dst = 0;
    res = malloc( len > str_len ? str_len + 1 : len + 1 );
    if ( res == NULL ) return res;

    while (str[src] != 0 && src < len)
    {
        if (str[src] == q)
            src++;
        else if (str[src] == '\\' && str[src+1] != 0)
        {
            res[dst++] = str[src+1];
            src += 2;
        }
        else
            res[dst++] = str[src++];
    }
    res[dst] = '\0';
    return res;
}

char** hb_str_vsplit( const char *str, char delem )
{
    const char *  pos;
    const char *  end;
    char       ** ret;
    int           count, i;
    char          quote = '"';

    if (delem == '"')
    {
        quote = '\'';
    }
    if ( str == NULL || str[0] == 0 )
    {
        ret = malloc( sizeof(char*) );
        if ( ret == NULL ) return ret;
        *ret = NULL;
        return ret;
    }

    // Find number of elements in the string
    count = 1;
    pos = str;
    while ( ( pos = strchr_quote( pos, delem, quote ) ) != NULL )
    {
        count++;
        pos++;
    }

    ret = calloc( ( count + 1 ), sizeof(char*) );
    if ( ret == NULL ) return ret;

    pos = str;
    for ( i = 0; i < count - 1; i++ )
    {
        end = strchr_quote( pos, delem, quote );
        ret[i] = strndup_quote(pos, quote, end - pos);
        pos = end + 1;
    }
    ret[i] = strndup_quote(pos, quote, strlen(pos));

    return ret;
}

void hb_str_vfree( char **strv )
{
    int i;

    if (strv == NULL)
        return;

    for ( i = 0; strv[i]; i++ )
    {
        free( strv[i] );
    }
    free( strv );
}

hb_chapter_queue_t * hb_chapter_queue_init(void)
{
    hb_chapter_queue_t * q;

    q = calloc(1, sizeof(*q));
    if (q != NULL)
    {
        q->list_chapter = hb_list_init();
        if (q->list_chapter == NULL)
        {
            free(q);
            q = NULL;
        }
    }
    return q;
}

void hb_chapter_queue_close(hb_chapter_queue_t **_q)
{
    hb_chapter_queue_t      * q = *_q;
    hb_chapter_queue_item_t * item;

    if (q == NULL)
    {
        return;
    }
    while ((item = hb_list_item(q->list_chapter, 0)) != NULL)
    {
        hb_list_rem(q->list_chapter, item);
        free(item);
    }
    hb_list_close(&q->list_chapter);
    free(q);
    *_q = NULL;
}

void hb_chapter_enqueue(hb_chapter_queue_t *q, hb_buffer_t *buf)
{
    /*
     * Chapter markers are sometimes so close we can get a new
     * one before the previous goes through the encoding queue.
     *
     * Dropping markers can cause weird side-effects downstream,
     * including but not limited to missing chapters in the
     * output, so we need to save it somehow.
     */
    hb_chapter_queue_item_t *item = malloc(sizeof(hb_chapter_queue_item_t));
    if (item != NULL)
    {
        item->start = buf->s.start;
        item->new_chap = buf->s.new_chap;
        // Make sure work_loop doesn't also copy the chapter mark
        buf->s.new_chap = 0;
        hb_list_add(q->list_chapter, item);
    }
}

void hb_chapter_dequeue(hb_chapter_queue_t *q, hb_buffer_t *buf)
{
    hb_chapter_queue_item_t *item = hb_list_item(q->list_chapter, 0);
    if (item != NULL)
    {
        if (buf->s.start < item->start)
        {
            // Have not reached the next chapter yet.
            return;
        }

        // we're done with this chapter
        hb_list_rem(q->list_chapter, item);
        buf->s.new_chap = item->new_chap;
        free(item);
    }
}