summaryrefslogtreecommitdiffstats
path: root/libhb/stream.c
blob: a48d339f1f0f8524a17ee4e9092248348c75cf2a (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
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
/* stream.c

   Copyright (c) 2003-2014 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 <string.h>
#include <ctype.h>
#include <errno.h>

#include "hb.h"
#include "hbffmpeg.h"
#include "lang.h"
#include "libbluray/bluray.h"
#include "vadxva2.h"

#define min(a, b) a < b ? a : b
#define HB_MAX_PROBE_SIZE (1*1024*1024)

/*
 * This table defines how ISO MPEG stream type codes map to HandBrake
 * codecs. It is indexed by the 8 bit stream type and contains the codec
 * worker object id and a parameter for that worker proc (ignored except
 * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
 *
 * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
 * doesn't handle the stream type.
 * N - Not used
 * U - Unknown (to be determined by further processing)
 * A - Audio
 * V - Video
 * S - Subtitle
 * P - PCR
 */
typedef enum { N, U, A, V, P, S } kind_t;
typedef struct {
    kind_t kind; /* not handled / unknown / audio / video */
    int codec;          /* HB worker object id of codec */
    int codec_param;    /* param for codec (usually ffmpeg codec id) */
    const char* name;   /* description of type */
} stream2codec_t;

#define st(id, kind, codec, codec_param, name) \
 [id] = { kind, codec, codec_param, name }

static const stream2codec_t st2codec[256] = {
    st(0x00, U, 0,                0,                      NULL),
    st(0x01, V, WORK_DECAVCODECV, AV_CODEC_ID_MPEG2VIDEO, "MPEG1"),
    st(0x02, V, WORK_DECAVCODECV, AV_CODEC_ID_MPEG2VIDEO, "MPEG2"),
    st(0x03, A, HB_ACODEC_FFMPEG, AV_CODEC_ID_MP2,        "MPEG1"),
    st(0x04, A, HB_ACODEC_FFMPEG, AV_CODEC_ID_MP2,        "MPEG2"),
    st(0x05, N, 0,                0,                      "ISO 13818-1 private section"),
    st(0x06, U, 0,                0,                      "ISO 13818-1 PES private data"),
    st(0x07, N, 0,                0,                      "ISO 13522 MHEG"),
    st(0x08, N, 0,                0,                      "ISO 13818-1 DSM-CC"),
    st(0x09, N, 0,                0,                      "ISO 13818-1 auxiliary"),
    st(0x0a, N, 0,                0,                      "ISO 13818-6 encap"),
    st(0x0b, N, 0,                0,                      "ISO 13818-6 DSM-CC U-N msgs"),
    st(0x0c, N, 0,                0,                      "ISO 13818-6 Stream descriptors"),
    st(0x0d, N, 0,                0,                      "ISO 13818-6 Sections"),
    st(0x0e, N, 0,                0,                      "ISO 13818-1 auxiliary"),
    st(0x0f, A, HB_ACODEC_FFAAC,  AV_CODEC_ID_AAC,        "AAC"),
    st(0x10, V, WORK_DECAVCODECV, AV_CODEC_ID_MPEG4,      "MPEG4"),
    st(0x11, A, HB_ACODEC_FFMPEG, AV_CODEC_ID_AAC_LATM,   "LATM AAC"),
    st(0x12, U, 0,                0,                      "MPEG4 generic"),

    st(0x14, N, 0,                0,                      "ISO 13818-6 DSM-CC download"),

    st(0x1b, V, WORK_DECAVCODECV, AV_CODEC_ID_H264,       "H.264"),

    st(0x80, U, HB_ACODEC_FFMPEG, AV_CODEC_ID_PCM_BLURAY, "Digicipher II Video"),
    st(0x81, A, HB_ACODEC_AC3,    AV_CODEC_ID_AC3,        "AC3"),
    st(0x82, A, HB_ACODEC_DCA,    AV_CODEC_ID_DTS,        "DTS"),
    // 0x83 can be LPCM or BD TrueHD.  Set to 'unknown' till we know more.
    st(0x83, U, HB_ACODEC_LPCM,   0,                      "LPCM"),
    // BD E-AC3 Primary audio
    st(0x84, U, 0,                0,                      "SDDS"),
    st(0x85, U, 0,                0,                      "ATSC Program ID"),
    // 0x86 can be BD DTS-HD/DTS. Set to 'unknown' till we know more.
    st(0x86, U, HB_ACODEC_DCA_HD, AV_CODEC_ID_DTS,        "DTS-HD MA"),
    st(0x87, A, HB_ACODEC_FFMPEG, AV_CODEC_ID_EAC3,       "E-AC3"),

    st(0x8a, A, HB_ACODEC_DCA,    AV_CODEC_ID_DTS,        "DTS"),

    st(0x90, S, WORK_DECPGSSUB,   0,                      "PGS Subtitle"),
    // 0x91 can be AC3 or BD Interactive Graphics Stream.
    st(0x91, U, 0,                0,                      "AC3/IGS"),
    st(0x92, N, 0,                0,                      "Subtitle"),

    st(0x94, U, 0,                0,                      "SDDS"),
    st(0xa0, V, 0,                0,                      "MSCODEC"),
    // BD E-AC3 Secondary audio
    st(0xa1, U, 0,                0,                      "E-AC3"),
    // BD DTS-HD Secondary audio
    st(0xa2, U, 0,                0,                      "DTS-HD LBR"),

    st(0xea, V, WORK_DECAVCODECV, AV_CODEC_ID_VC1,        "VC-1"),
};
#undef st

typedef enum {
    hb_stream_type_unknown = 0,
    transport,
    program,
    ffmpeg
} hb_stream_type_t;

#define MAX_PS_PROBE_SIZE (5*1024*1024)
#define kMaxNumberPMTStreams 32

typedef struct {
    hb_buffer_t *buf;
    hb_buffer_t *extra_buf;
    int8_t  skipbad;
    int8_t  continuity;
    uint8_t pkt_summary[8];
    int     pid;
    uint8_t is_pcr;
    int     pes_list;

} hb_ts_stream_t;

typedef struct {
    int      map_idx;
    int      stream_id;
    uint8_t  stream_id_ext;
    uint8_t  stream_type;
    kind_t   stream_kind;
    int      lang_code;
    uint32_t format_id;
#define TS_FORMAT_ID_AC3 (('A' << 24) | ('C' << 16) | ('-' << 8) | '3')
    int      codec;         // HB worker object id of codec
    int      codec_param;   // param for codec (usually ffmpeg codec id)
    char     codec_name[80];
    int      next;          // next pointer for list
                            // hb_ts_stream_t points to a list of
                            // hb_pes_stream_t
    hb_buffer_t  *probe_buf;
    int      probe_next_size;
} hb_pes_stream_t;

struct hb_stream_s
{
    int     scan;
    int     frames;             /* video frames so far */
    int     errors;             /* total errors so far */
    int     last_error_frame;   /* frame # at last error message */
    int     last_error_count;   /* # errors at last error message */
    int     packetsize;         /* Transport Stream packet size */

    int     need_keyframe;      // non-zero if want to start at a keyframe

    int      chapter;           /* Chapter that we are currently in */
    int64_t  chapter_end;       /* HB time that the current chapter ends */


    struct
    {
        uint8_t found_pcr;      // non-zero if we've found at least one pcr
        int     pcr_out;        // sequence number of most recent output pcr
        int     pcr_in;         // sequence number of most recent input pcr
        int     pcr_discontinuity; // sequence number of last discontinuity
        int     pcr_current;    // last discontinuity sent to reader
        int64_t pcr;            // most recent input pcr
        int64_t last_timestamp; // used for discontinuity detection when
                                // there are no PCRs

        uint8_t *packet;        // buffer for one TS packet
        hb_ts_stream_t *list;
        int count;
        int alloc;
    } ts;

    struct
    {
        uint8_t found_scr;      // non-zero if we've found at least one scr
        int64_t scr;            // most recent input scr
        hb_pes_stream_t *list;
        int count;
        int alloc;
    } pes;

    /*
     * Stuff before this point is dynamic state updated as we read the
     * stream. Stuff after this point is stream description state that
     * we learn during the initial scan but cache so it can be
     * reused during the conversion read.
     */
    uint8_t has_IDRs;           // # IDRs found during duration scan
    uint8_t ts_flags;           // stream characteristics:
#define         TS_HAS_PCR  (1 << 0)    // at least one PCR seen
#define         TS_HAS_RAP  (1 << 1)    // Random Access Point bit seen
#define         TS_HAS_RSEI (1 << 2)    // "Restart point" SEI seen

    char    *path;
    FILE    *file_handle;
    hb_stream_type_t hb_stream_type;
    hb_title_t *title;

    AVFormatContext *ffmpeg_ic;
    AVPacket *ffmpeg_pkt;
    uint8_t ffmpeg_video_id;

    uint32_t reg_desc;          // 4 byte registration code that identifies
                                // stream semantics

    struct
    {
        unsigned short program_number;
        unsigned short program_map_PID;
    } pat_info[kMaxNumberPMTStreams];
    int     ts_number_pat_entries;

    struct
    {
        int reading;
        unsigned char *tablebuf;
        unsigned int tablepos;
        unsigned char current_continuity_counter;

        unsigned int PCR_PID;
    } pmt_info;
};

typedef struct {
    uint8_t *buf;
    uint32_t val;
    int pos;
    int size;
} bitbuf_t;

typedef struct
{
    uint8_t has_stream_id_ext;
    uint8_t stream_id;
    uint8_t stream_id_ext;
    uint8_t bd_substream_id;
    int64_t pts;
    int64_t dts;
    int64_t scr;
    int     header_len;
    int     packet_len;
} hb_pes_info_t;


/***********************************************************************
 * Local prototypes
 **********************************************************************/
static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
static off_t align_to_next_packet(hb_stream_t *stream);
static int64_t pes_timestamp( const uint8_t *pes );

static int hb_ts_stream_init(hb_stream_t *stream);
static hb_buffer_t * hb_ts_stream_decode(hb_stream_t *stream);
static void hb_init_audio_list(hb_stream_t *stream, hb_title_t *title);
static void hb_init_subtitle_list(hb_stream_t *stream, hb_title_t *title);
static int hb_ts_stream_find_pids(hb_stream_t *stream);

static void hb_ps_stream_init(hb_stream_t *stream);
static hb_buffer_t * hb_ps_stream_decode(hb_stream_t *stream);
static void hb_ps_stream_find_streams(hb_stream_t *stream);
static int hb_ps_read_packet( hb_stream_t * stream, hb_buffer_t *b );
static int update_ps_streams( hb_stream_t * stream, int stream_id, int stream_id_ext, int stream_type, int in_kind );
static int update_ts_streams( hb_stream_t * stream, int pid, int stream_id_ext, int stream_type, int in_kind, int *pes_idx );
static void update_pes_kind( hb_stream_t * stream, int idx );

static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title, int scan );
static void ffmpeg_close( hb_stream_t *d );
static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream, hb_title_t *title );
hb_buffer_t *hb_ffmpeg_read( hb_stream_t *stream );
static int ffmpeg_seek( hb_stream_t *stream, float frac );
static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts );
static inline unsigned int bits_get(bitbuf_t *bb, int bits);
static inline void bits_init(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear);
static inline unsigned int bits_peek(bitbuf_t *bb, int bits);
static inline int bits_eob(bitbuf_t *bb);
static inline int bits_read_ue(bitbuf_t *bb );
static void pes_add_audio_to_title(hb_stream_t *s, int i, hb_title_t *t, int sort);
static int hb_parse_ps( hb_stream_t *stream, uint8_t *buf, int len, hb_pes_info_t *pes_info );
static void hb_ts_resolve_pid_types(hb_stream_t *stream);
static void hb_ps_resolve_stream_types(hb_stream_t *stream);
void hb_ts_stream_reset(hb_stream_t *stream);
void hb_ps_stream_reset(hb_stream_t *stream);

/*
 * logging routines.
 * these frontend hb_log because transport streams can have a lot of errors
 * so we want to rate limit messages. this routine limits the number of
 * messages to at most one per minute of video. other errors that occur
 * during the minute are counted & the count is output with the next
 * error msg we print.
 */
static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
{
    // limit error printing to at most one per minute of video (at 30fps)
    ++stream->errors;
    if ( stream->frames - stream->last_error_frame >= 30*60 )
    {
        char msg[256];

        vsnprintf( msg, sizeof(msg), log, args );

        if ( stream->errors - stream->last_error_count < 10 )
        {
            hb_log( "stream: error near frame %d: %s", stream->frames, msg );
        }
        else
        {
            int Edelta = stream->errors - stream->last_error_count;
            double Epcnt = (double)Edelta * 100. /
                            (stream->frames - stream->last_error_frame);
            hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
                    Edelta, Epcnt, stream->frames, msg );
        }
        stream->last_error_frame = stream->frames;
        stream->last_error_count = stream->errors;
    }
}

static void ts_warn( hb_stream_t*, char*, ... ) HB_WPRINTF(2,3);
static void ts_err( hb_stream_t*, int, char*, ... ) HB_WPRINTF(3,4);

static void ts_warn( hb_stream_t *stream, char *log, ... )
{
    va_list args;
    va_start( args, log );
    ts_warn_helper( stream, log, args );
    va_end( args );
}

static int get_id(hb_pes_stream_t *pes)
{
    return ( pes->stream_id_ext << 16 ) + pes->stream_id;
}

static int index_of_id(hb_stream_t *stream, int id)
{
    int i;

    for ( i = 0; i < stream->pes.count; ++i )
    {
        if ( id == get_id( &stream->pes.list[i] ) )
            return i;
    }

    return -1;
}

static int index_of_pid(hb_stream_t *stream, int pid)
{
    int i;

    for ( i = 0; i < stream->ts.count; ++i )
    {
        if ( pid == stream->ts.list[i].pid )
        {
            return i;
        }
    }

    return -1;
}

static int index_of_ps_stream(hb_stream_t *stream, int id, int sid)
{
    int i;

    for ( i = 0; i < stream->pes.count; ++i )
    {
        if ( id == stream->pes.list[i].stream_id &&
             sid == stream->pes.list[i].stream_id_ext )
        {
            return i;
        }
    }
    // If there is no match on the stream_id_ext, try matching 
    // on only the stream_id.
    for ( i = 0; i < stream->pes.count; ++i )
    {
        if ( id == stream->pes.list[i].stream_id &&
             0 == stream->pes.list[i].stream_id_ext )
        {
            return i;
        }
    }

    return -1;
}

static kind_t ts_stream_kind( hb_stream_t * stream, int idx )
{
    if ( stream->ts.list[idx].pes_list != -1 )
    {
        // Retuns kind for the first pes substream in the pes list
        // All substreams in a TS stream are the same kind.
        return stream->pes.list[stream->ts.list[idx].pes_list].stream_kind;
    }
    else
    {
        return U;
    }
}

static kind_t ts_stream_type( hb_stream_t * stream, int idx )
{
    if ( stream->ts.list[idx].pes_list != -1 )
    {
        // Retuns stream type for the first pes substream in the pes list
        // All substreams in a TS stream are the same stream type.
        return stream->pes.list[stream->ts.list[idx].pes_list].stream_type;
    }
    else
    {
        return 0x00;
    }
}

static int pes_index_of_video(hb_stream_t *stream)
{
    int i;

    for ( i = 0; i < stream->pes.count; ++i )
        if ( V == stream->pes.list[i].stream_kind )
            return i;

    return -1;
}

static int ts_index_of_video(hb_stream_t *stream)
{
    int i;

    for ( i = 0; i < stream->ts.count; ++i )
        if ( V == ts_stream_kind( stream, i ) )
            return i;

    return -1;
}

static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
{
    va_list args;
    va_start( args, log );
    ts_warn_helper( stream, log, args );
    va_end( args );

    stream->ts.list[curstream].skipbad = 1;
    stream->ts.list[curstream].continuity = -1;
}

static int check_ps_sync(const uint8_t *buf)
{
    // a legal MPEG program stream must start with a Pack header in the
    // first four bytes.
    return (buf[0] == 0x00) && (buf[1] == 0x00) &&
           (buf[2] == 0x01) && (buf[3] == 0xba);
}

static int check_ps_sc(const uint8_t *buf)
{
    // a legal MPEG program stream must start with a Pack followed by a
    // some other start code. If we've already verified the pack, this skip
    // it and checks for a start code prefix.
    int pos;
    int mark = buf[4] >> 4;
    if ( mark == 0x02 )
    {
        // Check other marker bits to make it less likely
        // that we are being spoofed.
        if( ( buf[4] & 0xf1 ) != 0x21 ||
            ( buf[6] & 0x01 ) != 0x01 ||
            ( buf[8] & 0x01 ) != 0x01 ||
            ( buf[9] & 0x80 ) != 0x80 ||
            ( buf[11] & 0x01 ) != 0x01 )
        {
            return 0;
        }
        // mpeg-1 pack header
        pos = 12;   // skip over the PACK
    }
    else
    {
        // Check other marker bits to make it less likely
        // that we are being spoofed.
        if( ( buf[4] & 0xC4 ) != 0x44 ||
            ( buf[6] & 0x04 ) != 0x04 ||
            ( buf[8] & 0x04 ) != 0x04 ||
            ( buf[9] & 0x01 ) != 0x01 ||
            ( buf[12] & 0x03 ) != 0x03 )
        {
            return 0;
        }
        // mpeg-2 pack header
        pos = 14 + ( buf[13] & 0x7 );   // skip over the PACK
    }
    return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) && (buf[pos+2] == 0x01);
}

static int check_ts_sync(const uint8_t *buf)
{
    // must have initial sync byte & a legal adaptation ctrl
    return (buf[0] == 0x47) && (((buf[3] & 0x30) >> 4) > 0);
}

static int have_ts_sync(const uint8_t *buf, int psize, int count)
{
    int ii;
    for ( ii = 0; ii < count; ii++ )
    {
        if ( !check_ts_sync(&buf[ii*psize]) )
            return 0;
    }
    return 1;
}

static int hb_stream_check_for_ts(const uint8_t *buf)
{
    // transport streams should have a sync byte every 188 bytes.
    // search the first 8KB of buf looking for at least 8 consecutive
    // correctly located sync patterns.
    int offset = 0;
    int count = 16;

    for ( offset = 0; offset < 8*1024-count*188; ++offset )
    {
        if ( have_ts_sync( &buf[offset], 188, count) )
            return 188 | (offset << 8);
        if ( have_ts_sync( &buf[offset], 192, count) )
            return 192 | (offset << 8);
        if ( have_ts_sync( &buf[offset], 204, count) )
            return 204 | (offset << 8);
        if ( have_ts_sync( &buf[offset], 208, count) )
            return 208 | (offset << 8);
    }
    return 0;
}

static int hb_stream_check_for_ps(hb_stream_t *stream)
{
    uint8_t buf[2048*4];
    uint8_t sc_buf[4];
    int pos = 0;

    fseek(stream->file_handle, 0, SEEK_SET);

    // program streams should start with a PACK then some other mpeg start
    // code (usually a SYS but that might be missing if we only have a clip).
    while (pos < 512 * 1024)
    {
        int offset;

        if ( fread(buf, 1, sizeof(buf), stream->file_handle) != sizeof(buf) )
            return 0;

        for ( offset = 0; offset < 8*1024-27; ++offset )
        {
            if ( check_ps_sync( &buf[offset] ) && check_ps_sc( &buf[offset] ) )
            {
                int pes_offset, prev, data_len;
                uint8_t sid;
                uint8_t *b = buf+offset;

                // Skip the pack header
                int mark = buf[4] >> 4;
                if ( mark == 0x02 )
                {
                    // mpeg-1 pack header
                    pes_offset = 12;
                }
                else
                {
                    // mpeg-2 pack header
                    pes_offset = 14 + ( buf[13] & 0x7 );
                }

                b +=  pes_offset;
                // Get the next stream id
                sid = b[3];
                data_len = (b[4] << 8) + b[5];
                if ( data_len && sid > 0xba && sid < 0xf9 )
                {
                    prev = ftell( stream->file_handle );
                    pos = prev - ( sizeof(buf) - offset );
                    pos += pes_offset + 6 + data_len;
                    fseek( stream->file_handle, pos, SEEK_SET );
                    if ( fread(sc_buf, 1, 4, stream->file_handle) != 4 )
                        return 0;
                    if (sc_buf[0] == 0x00 && sc_buf[1] == 0x00 &&
                        sc_buf[2] == 0x01)
                    {
                        return 1;
                    }
                    fseek( stream->file_handle, prev, SEEK_SET );
                }
            }
        }
        fseek( stream->file_handle, -27, SEEK_CUR );
        pos = ftell( stream->file_handle );
    }
    return 0;
}

static int hb_stream_get_type(hb_stream_t *stream)
{
    uint8_t buf[2048*4];

    if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
    {
#ifdef USE_HWD
        if ( hb_gui_use_hwd_flag == 1 )
            return 0;
#endif
        int psize;
        if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
        {
            int offset = psize >> 8;
            psize &= 0xff;
            hb_log("file is MPEG Transport Stream with %d byte packets"
                   " offset %d bytes", psize, offset);
            stream->packetsize = psize;
            stream->hb_stream_type = transport;
            if (hb_ts_stream_init(stream) == 0)
                return 1;
        }
        else if ( hb_stream_check_for_ps(stream) != 0 )
        {
            hb_log("file is MPEG Program Stream");
            stream->hb_stream_type = program;
            hb_ps_stream_init(stream);
            // We default to mpeg codec for ps streams if no
            // video found in program stream map
            return 1;
        }
    }
    return 0;
}

static void hb_stream_delete_dynamic( hb_stream_t *d )
{
    if( d->file_handle )
    {
        fclose( d->file_handle );
        d->file_handle = NULL;
    }

    int i=0;

    if ( d->ts.packet )
    {
        free( d->ts.packet );
        d->ts.packet = NULL;
    }
    if ( d->ts.list )
    {
        for (i = 0; i < d->ts.count; i++)
        {
            if (d->ts.list[i].buf)
            {
                hb_buffer_close(&(d->ts.list[i].buf));
                hb_buffer_close(&(d->ts.list[i].extra_buf));
                d->ts.list[i].buf = NULL;
                d->ts.list[i].extra_buf = NULL;
            }
        }
    }
}

static void hb_stream_delete( hb_stream_t *d )
{
    hb_stream_delete_dynamic( d );
    free( d->ts.list );
    free( d->pes.list );
    free( d->path );
    free( d );
}

static int audio_inactive( hb_stream_t *stream, int id, int stream_id_ext )
{
    if ( id < 0 )
    {
        // PID declared inactive by hb_stream_title_scan
        return 1;
    }
    if ( id == stream->pmt_info.PCR_PID )
    {
        // PCR PID is always active
        return 0;
    }

    int i;
    for ( i = 0; i < hb_list_count( stream->title->list_audio ); ++i )
    {
        hb_audio_t *audio = hb_list_item( stream->title->list_audio, i );
        if ( audio->id == ((stream_id_ext << 16) | id) )
        {
            return 0;
        }
    }
    return 1;
}

/* when the file was first opened we made entries for all the audio elementary
 * streams we found in it. Streams that were later found during the preview scan
 * now have an audio codec, type, rate, etc., associated with them. At the end
 * of the scan we delete all the audio entries that weren't found by the scan
 * or don't have a format we support. This routine deletes audio entry 'indx'
 * by setting its PID to an invalid value so no packet will match it. (We can't
 * move any of the entries since the index of the entry is used as the id
 * of the media stream for HB. */
static void hb_stream_delete_ts_entry(hb_stream_t *stream, int indx)
{
    if ( stream->ts.list[indx].pid > 0 )
    {
        stream->ts.list[indx].pid = -stream->ts.list[indx].pid;
    }
}

static int hb_stream_try_delete_ts_entry(hb_stream_t *stream, int indx)
{
    int ii;

    if ( stream->ts.list[indx].pid < 0 )
        return 1;

    for ( ii = stream->ts.list[indx].pes_list; ii != -1;
          ii = stream->pes.list[ii].next )
    {
        if ( stream->pes.list[ii].stream_id >= 0 )
            return 0;
    }
    stream->ts.list[indx].pid = -stream->ts.list[indx].pid;
    return 1;
}

static void hb_stream_delete_ps_entry(hb_stream_t *stream, int indx)
{
    if ( stream->pes.list[indx].stream_id > 0 )
    {
        stream->pes.list[indx].stream_id = -stream->pes.list[indx].stream_id;
    }
}

static void prune_streams(hb_stream_t *d)
{
    if ( d->hb_stream_type == transport )
    {
        int ii, jj;
        for ( ii = 0; ii < d->ts.count; ii++)
        {
            // If probing didn't find audio or video, and the pid
            // is not the PCR, remove the track
            if ( ts_stream_kind ( d, ii ) == U &&
                 !d->ts.list[ii].is_pcr )
            {
                hb_stream_delete_ts_entry(d, ii);
                continue;
            }

            if ( ts_stream_kind ( d, ii ) == A )
            {
                for ( jj = d->ts.list[ii].pes_list; jj != -1;
                      jj = d->pes.list[jj].next )
                {
                    if ( audio_inactive( d, d->pes.list[jj].stream_id,
                                         d->pes.list[jj].stream_id_ext ) )
                    {
                        hb_stream_delete_ps_entry(d, jj);
                    }
                }
                if ( !d->ts.list[ii].is_pcr &&
                     hb_stream_try_delete_ts_entry(d, ii) )
                {
                    continue;
                }
            }
        }
        // reset to beginning of file and reset some stream 
        // state information
        hb_stream_seek( d, 0. );
    }
    else if ( d->hb_stream_type == program )
    {
        int ii;
        for ( ii = 0; ii < d->pes.count; ii++)
        {
            // If probing didn't find audio or video, remove the track
            if ( d->pes.list[ii].stream_kind == U )
            {
                hb_stream_delete_ps_entry(d, ii);
            }

            if ( d->pes.list[ii].stream_kind == A &&
                 audio_inactive( d, d->pes.list[ii].stream_id,
                                 d->pes.list[ii].stream_id_ext ) )
            {
                // this PID isn't wanted (we don't have a codec for it
                // or scan didn't find audio parameters)
                hb_stream_delete_ps_entry(d, ii);
                continue;
            }
        }
        // reset to beginning of file and reset some stream 
        // state information
        hb_stream_seek( d, 0. );
    }
}

/***********************************************************************
 * hb_stream_open
 ***********************************************************************
 *
 **********************************************************************/
hb_stream_t * hb_stream_open( char *path, hb_title_t *title, int scan )
{
    FILE *f = hb_fopen(path, "rb");
    if ( f == NULL )
    {
        hb_log( "hb_stream_open: open %s failed", path );
        return NULL;
    }

    hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
    if ( d == NULL )
    {
        fclose( f );
        hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
        return NULL;
    }

    if( title && !( title->flags & HBTF_NO_IDR ) )
    {
        d->has_IDRs = 1;
    }

    /*
     * If it's something we can deal with (MPEG2 PS or TS) return a stream
     * reference structure & null otherwise.
     */
    d->file_handle = f;
    d->title = title;
    d->scan = scan;
    d->path = strdup( path );
    if (d->path != NULL )
    {
        if ( hb_stream_get_type( d ) != 0 )
        {
            if( !scan )
            {
                prune_streams( d );
            }
            // reset to beginning of file and reset some stream 
            // state information
            hb_stream_seek( d, 0. );
            return d;
        }
        fclose( d->file_handle );
        d->file_handle = NULL;
        if ( ffmpeg_open( d, title, scan ) )
        {
            return d;
        }
    }
    if ( d->file_handle )
    {
        fclose( d->file_handle );
    }
    if (d->path)
    {
        free( d->path );
    }
    hb_log( "hb_stream_open: open %s failed", path );
    free( d );
    return NULL;
}

static int new_pid( hb_stream_t * stream )
{
    int num = stream->ts.alloc;

    if ( stream->ts.count == stream->ts.alloc )
    {
        num = stream->ts.alloc ? stream->ts.alloc * 2 : 32;
        stream->ts.list = realloc( stream->ts.list,
                                   sizeof( hb_ts_stream_t ) * num );
    }
    int ii;
    for ( ii = stream->ts.alloc; ii < num; ii++ )
    {
        memset(&stream->ts.list[ii], 0, sizeof( hb_ts_stream_t ));
        stream->ts.list[ii].continuity = -1;
        stream->ts.list[ii].pid = -1;
        stream->ts.list[ii].pes_list = -1;
    }
    stream->ts.alloc = num;
    num = stream->ts.count;
    stream->ts.count++;

    return num;
}

static int new_pes( hb_stream_t * stream )
{
    int num = stream->pes.alloc;

    if ( stream->pes.count == stream->pes.alloc )
    {
        num = stream->pes.alloc ? stream->pes.alloc * 2 : 32;
        stream->pes.list = realloc( stream->pes.list,
                                    sizeof( hb_pes_stream_t ) * num );
    }
    int ii;
    for ( ii = stream->pes.alloc; ii < num; ii++ )
    {
        memset(&stream->pes.list[ii], 0, sizeof( hb_pes_stream_t ));
        stream->pes.list[ii].stream_id = -1;
        stream->pes.list[ii].next = -1;
    }
    stream->pes.alloc = num;
    num = stream->pes.count;
    stream->pes.count++;

    return num;
}

hb_stream_t * hb_bd_stream_open( hb_title_t *title )
{
    int ii;

    hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
    if ( d == NULL )
    {
        hb_error( "hb_bd_stream_open: can't allocate space for stream state" );
        return NULL;
    }

    d->file_handle = NULL;
    d->title = title;
    d->path = NULL;
    d->ts.packet = NULL;

    int pid = title->video_id;
    int stream_type = title->video_stream_type;
    update_ts_streams( d, pid, 0, stream_type, V, NULL );

    hb_audio_t * audio;
    for ( ii = 0; ( audio = hb_list_item( title->list_audio, ii ) ); ++ii )
    {
        int stream_id_ext = audio->config.in.substream_type;
        pid = audio->id & 0xFFFF;
        stream_type = audio->config.in.stream_type;

        update_ts_streams( d, pid, stream_id_ext, stream_type, A, NULL );
    }

    hb_subtitle_t * subtitle;
    for ( ii = 0; ( subtitle = hb_list_item( title->list_subtitle, ii ) ); ++ii )
    {
        // If the subtitle track is CC embedded in the video stream, then
        // it does not have an independent pid.  In this case, we assigned
        // the subtitle->id to 0.
        if (subtitle->id != 0)
        {
            pid = subtitle->id & 0xFFFF;
            stream_type = subtitle->stream_type;

            update_ts_streams( d, pid, 0, stream_type, S, NULL );
        }
    }

    // We don't need to wait for a PCR when scanning. In fact, it
    // trips us up on the first preview of every title since we would
    // have to read quite a lot of data before finding the PCR.
    if ( title->flags & HBTF_SCAN_COMPLETE )
    {
        /* BD has PCRs, but the BD index always points to a packet
         * after a PCR packet, so we will not see the initial PCR
         * after any seek.  So don't set the flag that causes us
         * to drop packets till we see a PCR. */
        //d->ts_flags = TS_HAS_RAP | TS_HAS_PCR;

        // BD PCR PID is specified to always be 0x1001
        update_ts_streams( d, 0x1001, 0, -1, P, NULL );
    }

    d->packetsize = 192;
    d->hb_stream_type = transport;

    for ( ii = 0; ii < d->ts.count; ii++ )
    {
        d->ts.list[ii].buf = hb_buffer_init(d->packetsize);
        d->ts.list[ii].extra_buf = hb_buffer_init(d->packetsize);
        d->ts.list[ii].buf->size = 0;
        d->ts.list[ii].extra_buf->size = 0;
    }

    return d;
}

/***********************************************************************
 * hb_stream_close
 ***********************************************************************
 * Closes and frees everything
 **********************************************************************/
void hb_stream_close( hb_stream_t ** _d )
{
    hb_stream_t *stream = * _d;

    if ( stream->hb_stream_type == ffmpeg )
    {
        ffmpeg_close( stream );
        hb_stream_delete( stream );
        *_d = NULL;
        return;
    }

    if ( stream->frames )
    {
        hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
                stream->errors, (double)stream->errors * 100. /
                (double)stream->frames );
    }

    hb_stream_delete( stream );
    *_d = NULL;
}

/***********************************************************************
 * hb_ps_stream_title_scan
 ***********************************************************************
 *
 **********************************************************************/
hb_title_t * hb_stream_title_scan(hb_stream_t *stream, hb_title_t * title)
{
    if ( stream->hb_stream_type == ffmpeg )
        return ffmpeg_title_scan( stream, title );

    // 'Barebones Title'
    title->type = HB_STREAM_TYPE;
    title->index = 1;

    // Copy part of the stream path to the title name
    char *sep = hb_strr_dir_sep(stream->path);
    if (sep)
        strcpy(title->name, sep+1);
    char *dot_term = strrchr(title->name, '.');
    if (dot_term)
        *dot_term = '\0';

    // Figure out how many audio streams we really have:
    // - For transport streams, for each PID listed in the PMT (whether
    //   or not it was an audio stream type) read the bitstream until we
    //   find an packet from that PID containing a PES header and see if
    //   the elementary stream is an audio type.
    // - For program streams read the first 4MB and take every unique
    //   audio stream we find.
    hb_init_audio_list(stream, title);
    hb_init_subtitle_list(stream, title);

    // set the video id, codec & muxer
    int idx = pes_index_of_video( stream );
    if ( idx < 0 )
    {
        hb_title_close( &title );
        return NULL;
    }

    title->video_id = get_id( &stream->pes.list[idx] );
    title->video_codec = stream->pes.list[idx].codec;
    title->video_codec_param = stream->pes.list[idx].codec_param;
    title->demuxer = HB_MPEG_DEMUXER;

    if (stream->hb_stream_type == transport)
    {

        // make sure we're grabbing the PCR PID
        update_ts_streams( stream, stream->pmt_info.PCR_PID, 0, -1, P, NULL );
    }

    // IDRs will be search for in hb_stream_duration
    stream->has_IDRs = 0;
    hb_stream_duration(stream, title);

    // One Chapter
    hb_chapter_t * chapter;
    chapter = calloc( sizeof( hb_chapter_t ), 1 );
    hb_chapter_set_title( chapter, "Chapter 1" );
    chapter->index = 1;
    chapter->duration = title->duration;
    chapter->hours = title->hours;
    chapter->minutes = title->minutes;
    chapter->seconds = title->seconds;
    hb_list_add( title->list_chapter, chapter );


    if ( stream->has_IDRs < 1 )
    {
        hb_log( "stream doesn't seem to have video IDR frames" );
        title->flags |= HBTF_NO_IDR;
    }

    if ( stream->hb_stream_type == transport && 
         ( stream->ts_flags & TS_HAS_PCR ) == 0 )
    {
        hb_log( "transport stream missing PCRs - using video DTS instead" );
    }
#ifdef USE_HWD
    hb_va_dxva2_t * dxva2 = NULL;
    dxva2 = hb_va_create_dxva2( dxva2, title->video_codec_param );
    if ( dxva2 )
    {
        title->hwd_support = 1;
        hb_va_close(dxva2);
        dxva2 = NULL;
    }
    else
        title->hwd_support = 0;
#else
    title->hwd_support = 0;
#endif

    // Height, width, rate and aspect ratio information is filled in
    // when the previews are built
    return title;
}

/*
 * read the next transport stream packet from 'stream'. Return NULL if
 * we hit eof & a pointer to the sync byte otherwise.
 */
static const uint8_t *next_packet( hb_stream_t *stream )
{
    uint8_t *buf = stream->ts.packet + stream->packetsize - 188;

    while ( 1 )
    {
        if ( fread(stream->ts.packet, 1, stream->packetsize, stream->file_handle) !=
             stream->packetsize )
        {
            return NULL;
        }
        if (buf[0] == 0x47)
        {
            return buf;
        }
        // lost sync - back up to where we started then try to re-establish.
        off_t pos = ftello(stream->file_handle) - stream->packetsize;
        off_t pos2 = align_to_next_packet(stream);
        if ( pos2 == 0 )
        {
            hb_log( "next_packet: eof while re-establishing sync @ %"PRId64, pos );
            return NULL;
        }
        ts_warn( stream, "next_packet: sync lost @ %"PRId64", regained after %"PRId64" bytes",
                 pos, pos2 );
    }
}

/*
 * skip to the start of the next PACK header in program stream src_stream.
 */
static void skip_to_next_pack( hb_stream_t *src_stream )
{
    // scan forward until we find the start of the next pack
    uint32_t strt_code = -1;
    int c;

    flockfile( src_stream->file_handle );
    while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
    {
        strt_code = ( strt_code << 8 ) | c;
        if ( strt_code == 0x000001ba )
            // we found the start of the next pack
            break;
    }
    funlockfile( src_stream->file_handle );

    // if we didn't terminate on an eof back up so the next read
    // starts on the pack boundary.
    if ( c != EOF )
    {
        fseeko( src_stream->file_handle, -4, SEEK_CUR );
    }
}

static void CreateDecodedNAL( uint8_t **dst, int *dst_len,
                              const uint8_t *src, int src_len )
{
    const uint8_t *end = &src[src_len];
    uint8_t *d = malloc( src_len );

    *dst = d;

    if( d )
    {
        while( src < end )
        {
            if( src < end - 3 && src[0] == 0x00 && src[1] == 0x00 &&
                src[2] == 0x01 )
            {
                // Next start code found
                break;
            }
            if( src < end - 3 && src[0] == 0x00 && src[1] == 0x00 &&
                src[2] == 0x03 )
            {
                *d++ = 0x00;
                *d++ = 0x00;

                src += 3;
                continue;
            }
            *d++ = *src++;
        }
    }
    *dst_len = d - *dst;
}

static int isRecoveryPoint( const uint8_t *buf, int len )
{
    uint8_t *nal;
    int nal_len;
    int ii, type, size;
    int recovery_frames = 0;

    CreateDecodedNAL( &nal, &nal_len, buf, len );

    for ( ii = 0; ii+1 < nal_len; )
    {
        type = 0;
        while ( ii+1 < nal_len )
        {
            type += nal[ii++];
            if ( nal[ii-1] != 0xff )
                break;
        }
        size = 0;
        while ( ii+1 < nal_len )
        {
            size += nal[ii++];
            if ( nal[ii-1] != 0xff )
                break;
        }

        if( type == 6 )
        {
            recovery_frames = 1;
            break;
        }
        ii += size;
    }

    free( nal );
    return recovery_frames;
}

static int isIframe( hb_stream_t *stream, const uint8_t *buf, int len )
{
    // For mpeg2: look for a gop start or i-frame picture start
    // for h.264: look for idr nal type or a slice header for an i-frame
    // for vc1:   look for a Sequence header
    int ii;
    uint32_t strid = 0;


    int vid = pes_index_of_video( stream );
    hb_pes_stream_t *pes = &stream->pes.list[vid];
    if ( pes->stream_type <= 2 ||
         pes->codec_param == AV_CODEC_ID_MPEG1VIDEO ||
         pes->codec_param == AV_CODEC_ID_MPEG2VIDEO )
    {
        // This section of the code handles MPEG-1 and MPEG-2 video streams
        for (ii = 0; ii < len; ii++)
        {
            strid = (strid << 8) | buf[ii];
            if ( ( strid >> 8 ) == 1 )
            {
                // we found a start code
                uint8_t id = strid;
                switch ( id )
                {
                    case 0xB8: // group_start_code (GOP header)
                    case 0xB3: // sequence_header code
                        return 1;

                    case 0x00: // picture_start_code
                        // picture_header, let's see if it's an I-frame
                        if (ii < len - 3)
                        {
                            // check if picture_coding_type == 1
                            if ((buf[ii+2] & (0x7 << 3)) == (1 << 3))
                            {
                                // found an I-frame picture
                                return 1;
                            }
                        }
                        break;
                }
            }
        }
        // didn't find an I-frame
        return 0;
    }
    if ( pes->stream_type == 0x1b || pes->codec_param == AV_CODEC_ID_H264 )
    {
        // we have an h.264 stream
        for (ii = 0; ii < len; ii++)
        {
            strid = (strid << 8) | buf[ii];
            if ( ( strid >> 8 ) == 1 )
            {
                // we found a start code - remove the ref_idc from the nal type
                uint8_t nal_type = strid & 0x1f;
                if ( nal_type == 0x01 )
                {
                    // Found slice and no recovery point
                    return 0;
                }
                if ( nal_type == 0x05 )
                {
                    // h.264 IDR picture start
                    return 1;
                }
                else if ( nal_type == 0x06 )
                {
                    int off = ii + 1;
                    int recovery_frames = isRecoveryPoint( buf+off, len-off );
                    if ( recovery_frames )
                    {
                        return recovery_frames;
                    }
                }
            }
        }
        // didn't find an I-frame
        return 0;
    }
    if ( pes->stream_type == 0xea || pes->codec_param == AV_CODEC_ID_VC1 )
    {
        // we have an vc1 stream
        for (ii = 0; ii < len; ii++)
        {
            strid = (strid << 8) | buf[ii];
            if ( strid == 0x10f )
            {
                // the ffmpeg vc1 decoder requires a seq hdr code in the first
                // frame.
                return 1;
            }
        }
        // didn't find an I-frame
        return 0;
    }

    // we don't understand the stream type so just say "yes" otherwise
    // we'll discard all the video.
    return 1;
}

static int ts_isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
{
    return isIframe( stream, buf + 13 + adapt_len, 188 - ( 13 + adapt_len ) );
}

/*
 * scan the next MB of 'stream' to find the next start packet for
 * the Packetized Elementary Stream associated with TS PID 'pid'.
 */
static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid, int *out_adapt_len)
{
    int npack = 300000; // max packets to read

    while (--npack >= 0)
    {
        const uint8_t *buf = next_packet( stream );
        if ( buf == NULL )
        {
            hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
            return 0;
        }

        // while we're reading the stream, check if it has valid PCRs
        // and/or random access points.
        uint32_t pack_pid = ( (buf[1] & 0x1f) << 8 ) | buf[2];
        if ( pack_pid == stream->pmt_info.PCR_PID )
        {
            if ( ( buf[5] & 0x10 ) &&
                 ( ( ( buf[3] & 0x30 ) == 0x20 ) ||
                   ( ( buf[3] & 0x30 ) == 0x30 && buf[4] > 6 ) ) )
            {
                stream->ts_flags |= TS_HAS_PCR;
            }
        }
        if ( buf[5] & 0x40 )
        {
            stream->ts_flags |= TS_HAS_RAP;
        }

        /*
         * The PES header is only in TS packets with 'start' set so we check
         * that first then check for the right PID.
         */
        if ((buf[1] & 0x40) == 0 || pack_pid != pid )
        {
            // not a start packet or not the pid we want
            continue;
        }

        int adapt_len = 0;
        /* skip over the TS hdr to return a pointer to the PES hdr */
        switch (buf[3] & 0x30)
        {
            case 0x00: // illegal
            case 0x20: // fill packet
                continue;

            case 0x30: // adaptation
                adapt_len = buf[4] + 1;
                if (adapt_len > 184)
                {
                    hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
                    continue;
                }
                break;
        }
        /* PES hdr has to begin with an mpeg start code */
        if (buf[adapt_len+4] == 0x00 && buf[adapt_len+5] == 0x00 && buf[adapt_len+6] == 0x01)
        {
            *out_adapt_len = adapt_len;
            return buf;
        }
    }

    /* didn't find it */
    return 0;
}

static hb_buffer_t * hb_ps_stream_getVideo(
    hb_stream_t *stream,
    hb_pes_info_t *pi)
{
    hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
    hb_pes_info_t pes_info;
    // how many blocks we read while searching for a video PES header
    int blksleft = 2048;

    while (--blksleft >= 0)
    {
        buf->size = 0;
        int len = hb_ps_read_packet( stream, buf );
        if ( len == 0 )
        {
            // EOF
            break;
        }
        if ( !hb_parse_ps( stream, buf->data, buf->size, &pes_info ) )
            continue;

        int idx;
        if ( pes_info.stream_id == 0xbd )
        {
            idx = index_of_ps_stream( stream, pes_info.stream_id,
                                      pes_info.bd_substream_id );
        }
        else
        {
            idx = index_of_ps_stream( stream, pes_info.stream_id,
                                      pes_info.stream_id_ext );
        }
        if ( stream->pes.list[idx].stream_kind == V )
        {
            if ( pes_info.pts != AV_NOPTS_VALUE )
            {
                *pi = pes_info;
                return buf;
            }
        }
    }
    hb_buffer_close( &buf );
    return NULL;
}

/***********************************************************************
 * hb_stream_duration
 ***********************************************************************
 *
 * Finding stream duration is difficult.  One issue is that the video file
 * may have chunks from several different program fragments (main feature,
 * commercials, station id, trailers, etc.) all with their own base pts
 * value.  We can't find the piece boundaries without reading the entire
 * file but if we compute a rate based on time stamps from two different
 * pieces the result will be meaningless.  The second issue is that the
 * data rate of compressed video normally varies by 5-10x over the length
 * of the video. This says that we want to compute the rate over relatively
 * long segments to get a representative average but long segments increase
 * the likelihood that we'll cross a piece boundary.
 *
 * What we do is take time stamp samples at several places in the file
 * (currently 16) then compute the average rate (i.e., ticks of video per
 * byte of the file) for all pairs of samples (N^2 rates computed for N
 * samples). Some of those rates will be absurd because the samples came
 * from different segments. Some will be way low or high because the
 * samples came from a low or high motion part of the segment. But given
 * that we're comparing *all* pairs the majority of the computed rates
 * should be near the overall average.  So we median filter the computed
 * rates to pick the most representative value.
 *
 **********************************************************************/
struct pts_pos {
    uint64_t pos;   /* file position of this PTS sample */
    uint64_t pts;   /* PTS from video stream */
};

#define NDURSAMPLES 128

// get one (position, timestamp) sampple from a transport or program
// stream.
static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
{
    struct pts_pos pp = { 0, 0 };

    if ( stream->hb_stream_type == transport )
    {
        const uint8_t *buf;
        int adapt_len;
        fseeko( stream->file_handle, fpos, SEEK_SET );
        align_to_next_packet( stream );
        int pid = stream->ts.list[ts_index_of_video(stream)].pid;
        buf = hb_ts_stream_getPEStype( stream, pid, &adapt_len );
        if ( buf == NULL )
        {
            hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
            return pp;
        }
        const uint8_t *pes = buf + 4 + adapt_len;
        if ( ( pes[7] >> 7 ) != 1 )
        {
            hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
            return pp;
        }
        pp.pts = ( ( (uint64_t)pes[9] >> 1 ) & 7 << 30 ) |
                 ( (uint64_t)pes[10] << 22 ) |
                 ( ( (uint64_t)pes[11] >> 1 ) << 15 ) |
                 ( (uint64_t)pes[12] << 7 ) |
                 ( (uint64_t)pes[13] >> 1 );

        if ( ts_isIframe( stream, buf, adapt_len ) )
        {
            if (  stream->has_IDRs < 255 )
            {
                ++stream->has_IDRs;
            }
        }
        pp.pos = ftello(stream->file_handle);
        if ( !stream->has_IDRs )
        {
            // Scan a little more to see if we will stumble upon one
            int ii;
            for ( ii = 0; ii < 10; ii++ )
            {
                buf = hb_ts_stream_getPEStype( stream, pid, &adapt_len );
                if ( buf == NULL )
                    break;
                if ( ts_isIframe( stream, buf, adapt_len ) )
                {
                    ++stream->has_IDRs;
                    break;
                }
            }
        }
    }
    else
    {
        hb_buffer_t *buf;
        hb_pes_info_t pes_info;

        // round address down to nearest dvd sector start
        fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
        fseeko( stream->file_handle, fpos, SEEK_SET );
        if ( stream->hb_stream_type == program )
        {
            skip_to_next_pack( stream );
        }
        buf = hb_ps_stream_getVideo( stream, &pes_info );
        if ( buf == NULL )
        {
            hb_log("hb_sample_pts: couldn't find video packet near %"PRIu64, fpos);
            return pp;
        }
        if ( pes_info.pts < 0 )
        {
            hb_log("hb_sample_pts: no PTS in video packet near %"PRIu64, fpos);
            hb_buffer_close( &buf );
            return pp;
        }
        if ( isIframe( stream, buf->data, buf->size ) )
        {
            if (  stream->has_IDRs < 255 )
            {
                ++stream->has_IDRs;
            }
        }
        hb_buffer_close( &buf );
        if ( !stream->has_IDRs )
        {
            // Scan a little more to see if we will stumble upon one
            int ii;
            for ( ii = 0; ii < 10; ii++ )
            {
                buf = hb_ps_stream_getVideo( stream, &pes_info );
                if ( buf == NULL )
                    break;
                if ( isIframe( stream, buf->data, buf->size ) )
                {
                    ++stream->has_IDRs;
                    hb_buffer_close( &buf );
                    break;
                }
                hb_buffer_close( &buf );
            }
        }

        pp.pts = pes_info.pts;
        pp.pos = ftello(stream->file_handle);
    }
    return pp;
}

static int dur_compare( const void *a, const void *b )
{
    const double *aval = a, *bval = b;
    return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
}

// given an array of (position, time) samples, compute a max-likelihood
// estimate of the average rate by computing the rate between all pairs
// of samples then taking the median of those rates.
static double compute_stream_rate( struct pts_pos *pp, int n )
{
    int i, j;
    double rates[NDURSAMPLES * NDURSAMPLES / 8];
    double *rp = rates;

    // the following nested loops compute the rates between all pairs.
    *rp = 0;
    for ( i = 0; i < n-1; ++i )
    {
        // Bias the median filter by not including pairs that are "far"
        // from one another. This is to handle cases where the file is
        // made of roughly equal size pieces where a symmetric choice of
        // pairs results in having the same number of intra-piece &
        // inter-piece rate estimates. This would mean that the median
        // could easily fall in the inter-piece part of the data which
        // would give a bogus estimate. The 'ns' index creates an
        // asymmetry that favors locality.
        int ns = i + ( n >> 3 );
        if ( ns > n )
            ns = n;
        for ( j = i+1; j < ns; ++j )
        {
            if ( (uint64_t)(pp[j].pts - pp[i].pts) > 90000LL*3600*6 )
                break;
            if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
            {
                *rp = ((double)( pp[j].pts - pp[i].pts )) /
                      ((double)( pp[j].pos - pp[i].pos ));
                ++rp;
            }
        }
    }
    // now compute and return the median of all the (n*n/2) rates we computed
    // above.
    int nrates = rp - rates;
    qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
    return rates[nrates >> 1];
}

static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
{
    struct pts_pos ptspos[NDURSAMPLES];
    struct pts_pos *pp = ptspos;
    int i;

    fseeko(stream->file_handle, 0, SEEK_END);
    uint64_t fsize = ftello(stream->file_handle);
    uint64_t fincr = fsize / NDURSAMPLES;
    uint64_t fpos = fincr / 2;
    for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
    {
        *pp++ = hb_sample_pts(stream, fpos);
    }
    uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
    inTitle->duration = dur;
    dur /= 90000;
    inTitle->hours    = dur / 3600;
    inTitle->minutes  = ( dur % 3600 ) / 60;
    inTitle->seconds  = dur % 60;

    rewind(stream->file_handle);
}

/***********************************************************************
 * hb_stream_read
 ***********************************************************************
 *
 **********************************************************************/
hb_buffer_t * hb_stream_read( hb_stream_t * src_stream )
{
    if ( src_stream->hb_stream_type == ffmpeg )
    {
        return hb_ffmpeg_read( src_stream );
    }
    if ( src_stream->hb_stream_type == program )
    {
        return hb_ps_stream_decode( src_stream );
    }
    return hb_ts_stream_decode( src_stream );
}

int64_t ffmpeg_initial_timestamp( hb_stream_t * stream )
{
    AVFormatContext *ic = stream->ffmpeg_ic;
    if ( ic->start_time != AV_NOPTS_VALUE && ic->start_time > 0 )
        return ic->start_time;
    else
        return 0;
}

int hb_stream_seek_chapter( hb_stream_t * stream, int chapter_num )
{

    if ( stream->hb_stream_type != ffmpeg )
    {
        // currently meaningliess for transport and program streams
        return 1;
    }
    if ( !stream || !stream->title ||
         chapter_num > hb_list_count( stream->title->list_chapter ) )
    {
        return 0;
    }

    int64_t sum_dur = 0;
    hb_chapter_t *chapter = NULL;
    int i;
    for ( i = 0; i < chapter_num; ++i)
    {
        chapter = hb_list_item( stream->title->list_chapter, i );
        sum_dur += chapter->duration;
    }
    stream->chapter = chapter_num - 1;
    stream->chapter_end = sum_dur;

    int64_t pos = ( ( ( sum_dur - chapter->duration ) * AV_TIME_BASE ) / 90000 ) + ffmpeg_initial_timestamp( stream );

    hb_deep_log( 2, "Seeking to chapter %d: starts %"PRId64", ends %"PRId64", AV pos %"PRId64,
                 chapter_num, sum_dur - chapter->duration, sum_dur, pos);

    if ( chapter_num > 1 && pos > 0 )
    {
        AVStream *st = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id];
        // timebase must be adjusted to match timebase of stream we are
        // using for seeking.
        pos = av_rescale(pos, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
        avformat_seek_file( stream->ffmpeg_ic, stream->ffmpeg_video_id, 0, pos, pos, AVSEEK_FLAG_BACKWARD);
    }
    return 1;
}

/***********************************************************************
 * hb_stream_chapter
 ***********************************************************************
 * Return the number of the chapter that we are currently in. We store
 * the chapter number starting from 0, so + 1 for the real chpater num.
 **********************************************************************/
int hb_stream_chapter( hb_stream_t * src_stream )
{
    return( src_stream->chapter + 1 );
}

/***********************************************************************
 * hb_stream_seek
 ***********************************************************************
 *
 **********************************************************************/
int hb_stream_seek( hb_stream_t * stream, float f )
{
    if ( stream->hb_stream_type == ffmpeg )
    {
        return ffmpeg_seek( stream, f );
    }
    off_t stream_size, cur_pos, new_pos;
    double pos_ratio = f;
    cur_pos = ftello( stream->file_handle );
    fseeko( stream->file_handle, 0, SEEK_END );
    stream_size = ftello( stream->file_handle );
    new_pos = (off_t) ((double) (stream_size) * pos_ratio);
    new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);

    int r = fseeko( stream->file_handle, new_pos, SEEK_SET );
    if (r == -1)
    {
        fseeko( stream->file_handle, cur_pos, SEEK_SET );
        return 0;
    }

    if ( stream->hb_stream_type == transport )
    {
        // We need to drop the current decoder output and move
        // forwards to the next transport stream packet.
        hb_ts_stream_reset(stream);
        align_to_next_packet(stream);
        if ( !stream->has_IDRs )
        {
            // the stream has no IDRs so don't look for one.
            stream->need_keyframe = 0;
        }
    }
    else if ( stream->hb_stream_type == program )
    {
        hb_ps_stream_reset(stream);
        skip_to_next_pack( stream );
        if ( !stream->has_IDRs )
        {
            // the stream has no IDRs so don't look for one.
            stream->need_keyframe = 0;
        }
    }

    return 1;
}

int hb_stream_seek_ts( hb_stream_t * stream, int64_t ts )
{
    if ( stream->hb_stream_type == ffmpeg )
    {
        return ffmpeg_seek_ts( stream, ts );
    }
    return -1;
}

static char* strncpyupper( char *dst, const char *src, int len )
{
    int ii;

    for ( ii = 0; ii < len-1 && src[ii]; ii++ )
    {
        dst[ii] = islower(src[ii]) ? toupper(src[ii]) : src[ii];
    }
    dst[ii] = '\0';
    return dst;
}

static const char *stream_type_name2(hb_stream_t *stream, hb_pes_stream_t *pes)
{
    static char codec_name_caps[80];

    if ( stream->reg_desc == STR4_TO_UINT32("HDMV") )
    {
        // Names for streams we know about.
        switch ( pes->stream_type )
        {
            case 0x80:
                return "BD LPCM";

            case 0x83:
                return "TrueHD";

            case 0x84:
                return "E-AC3";

            case 0x85:
                return "DTS-HD HRA";

            case 0x86:
                return "DTS-HD MA";

            default:
                break;
        }
    }
    if ( st2codec[pes->stream_type].name )
    {
        return st2codec[pes->stream_type].name;
    }
    if ( pes->codec_name[0] != 0 )
    {
        return pes->codec_name;
    }
    if ( pes->codec & HB_ACODEC_FF_MASK )
    {
        AVCodec * codec = avcodec_find_decoder( pes->codec_param );
        if ( codec && codec->name && codec->name[0] )
        {
            strncpyupper( codec_name_caps, codec->name, 80 );
            return codec_name_caps;
        }
    }
    return "Unknown";
}

static void set_audio_description(hb_audio_t *audio, iso639_lang_t *lang)
{
    snprintf( audio->config.lang.simple,
              sizeof( audio->config.lang.simple ), "%s",
              strlen( lang->native_name ) ? lang->native_name : lang->eng_name );
    snprintf( audio->config.lang.iso639_2,
              sizeof( audio->config.lang.iso639_2 ), "%s", lang->iso639_2 );
    audio->config.lang.type = 0;
}

// Sort specifies the index in the audio list where you would
// like sorted items to begin.
static void pes_add_subtitle_to_title(
    hb_stream_t *stream,
    int         idx,
    hb_title_t  *title,
    int         sort)
{
    hb_pes_stream_t *pes = &stream->pes.list[idx];

    // Sort by id when adding to the list
    // This assures that they are always displayed in the same order
    int id = get_id( pes );
    int i;
    hb_subtitle_t *tmp = NULL;

    int count = hb_list_count( title->list_subtitle );

    // Don't add the same audio twice.  Search for audio.
    for ( i = 0; i < count; i++ )
    {
        tmp = hb_list_item( title->list_subtitle, i );
        if ( id == tmp->id )
            return;
    }

    hb_subtitle_t *subtitle = calloc( sizeof( hb_subtitle_t ), 1 );
    iso639_lang_t * lang;

    subtitle->track = idx;
    subtitle->id = id;
    lang = lang_for_code( pes->lang_code );
    snprintf( subtitle->lang, sizeof( subtitle->lang ), "%s",
              strlen(lang->native_name) ? lang->native_name : lang->eng_name);
    snprintf( subtitle->iso639_2, sizeof( subtitle->iso639_2 ), "%s",
              lang->iso639_2);

    switch ( pes->codec )
    {
        case WORK_DECPGSSUB:
            subtitle->source = PGSSUB;
            subtitle->format = PICTURESUB;
            subtitle->config.dest = RENDERSUB;
            break;
        case WORK_DECVOBSUB:
            subtitle->source = VOBSUB;
            subtitle->format = PICTURESUB;
            subtitle->config.dest = RENDERSUB;
            break;
        default:
            // Unrecognized, don't add to list
            hb_log("unregonized subtitle!");
            free( subtitle );
            return;
    }
    subtitle->reg_desc = stream->reg_desc;
    subtitle->stream_type = pes->stream_type;
    subtitle->substream_type = pes->stream_id_ext;
    subtitle->codec = pes->codec;

    // Create a default palette since vob files do not include the
    // vobsub palette.
    if ( subtitle->source == VOBSUB )
    {
        subtitle->palette[0] = 0x108080;
        subtitle->palette[1] = 0x108080;
        subtitle->palette[2] = 0x108080;
        subtitle->palette[3] = 0xbff000;

        subtitle->palette[4] = 0xbff000;
        subtitle->palette[5] = 0x108080;
        subtitle->palette[6] = 0x108080;
        subtitle->palette[7] = 0x108080;

        subtitle->palette[8] = 0xbff000;
        subtitle->palette[9] = 0x108080;
        subtitle->palette[10] = 0x108080;
        subtitle->palette[11] = 0x108080;

        subtitle->palette[12] = 0x108080;
        subtitle->palette[13] = 0xbff000;
        subtitle->palette[14] = 0x108080;
        subtitle->palette[15] = 0x108080;
    }

    hb_log("stream id 0x%x (type 0x%x substream 0x%x) subtitle 0x%x",
           pes->stream_id, pes->stream_type, pes->stream_id_ext, subtitle->id);

    // Search for the sort position
    if ( sort >= 0 )
    {
        sort = sort < count ? sort : count;
        for ( i = sort; i < count; i++ )
        {
            tmp = hb_list_item( title->list_subtitle, i );
            int sid = tmp->id & 0xffff;
            int ssid = tmp->id >> 16;
            if ( pes->stream_id < sid )
                break;
            else if ( pes->stream_id <= sid &&
                      pes->stream_id_ext <= ssid )
            {
                break;
            }
        }
        hb_list_insert( title->list_subtitle, i, subtitle );
    }
    else
    {
        hb_list_add( title->list_subtitle, subtitle );
    }
}

// Sort specifies the index in the audio list where you would
// like sorted items to begin.
static void pes_add_audio_to_title(
    hb_stream_t *stream,
    int         idx,
    hb_title_t  *title,
    int         sort)
{
    hb_pes_stream_t *pes = &stream->pes.list[idx];

    // Sort by id when adding to the list
    // This assures that they are always displayed in the same order
    int id = get_id( pes );
    int i;
    hb_audio_t *tmp = NULL;

    int count = hb_list_count( title->list_audio );

    // Don't add the same audio twice.  Search for audio.
    for ( i = 0; i < count; i++ )
    {
        tmp = hb_list_item( title->list_audio, i );
        if ( id == tmp->id )
            return;
    }

    hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );

    audio->id = id;
    audio->config.in.reg_desc = stream->reg_desc;
    audio->config.in.stream_type = pes->stream_type;
    audio->config.in.substream_type = pes->stream_id_ext;

    audio->config.in.codec = pes->codec;
    audio->config.in.codec_param = pes->codec_param;

    set_audio_description(audio, lang_for_code(pes->lang_code));

    hb_log("stream id 0x%x (type 0x%x substream 0x%x) audio 0x%x",
           pes->stream_id, pes->stream_type, pes->stream_id_ext, audio->id);

    audio->config.in.track = idx;

    // Search for the sort position
    if ( sort >= 0 )
    {
        sort = sort < count ? sort : count;
        for ( i = sort; i < count; i++ )
        {
            tmp = hb_list_item( title->list_audio, i );
            int sid = tmp->id & 0xffff;
            int ssid = tmp->id >> 16;
            if ( pes->stream_id < sid )
                break;
            else if ( pes->stream_id <= sid &&
                      pes->stream_id_ext <= ssid )
            {
                break;
            }
        }
        hb_list_insert( title->list_audio, i, audio );
    }
    else
    {
        hb_list_add( title->list_audio, audio );
    }
}

static void hb_init_subtitle_list(hb_stream_t *stream, hb_title_t *title)
{
    int ii;
    int map_idx;
    int largest = -1;

    // First add all that were found in a map.
    for ( map_idx = 0; 1; map_idx++ )
    {
        for ( ii = 0; ii < stream->pes.count; ii++ )
        {
            if ( stream->pes.list[ii].stream_kind == S )
            {
                if ( stream->pes.list[ii].map_idx == map_idx )
                {
                    pes_add_subtitle_to_title( stream, ii, title, -1 );
                }
                if ( stream->pes.list[ii].map_idx > largest )
                    largest = stream->pes.list[ii].map_idx;
            }
        }
        if ( map_idx > largest )
            break;
    }

    int count = hb_list_count( title->list_audio );
    // Now add the reset.  Sort them by stream id.
    for ( ii = 0; ii < stream->pes.count; ii++ )
    {
        if ( stream->pes.list[ii].stream_kind == S )
        {
            pes_add_subtitle_to_title( stream, ii, title, count );
        }
    }
}

static void hb_init_audio_list(hb_stream_t *stream, hb_title_t *title)
{
    int ii;
    int map_idx;
    int largest = -1;

    // First add all that were found in a map.
    for ( map_idx = 0; 1; map_idx++ )
    {
        for ( ii = 0; ii < stream->pes.count; ii++ )
        {
            if ( stream->pes.list[ii].stream_kind == A )
            {
                if ( stream->pes.list[ii].map_idx == map_idx )
                {
                    pes_add_audio_to_title( stream, ii, title, -1 );
                }
                if ( stream->pes.list[ii].map_idx > largest )
                    largest = stream->pes.list[ii].map_idx;
            }
        }
        if ( map_idx > largest )
            break;
    }

    int count = hb_list_count( title->list_audio );
    // Now add the reset.  Sort them by stream id.
    for ( ii = 0; ii < stream->pes.count; ii++ )
    {
        if ( stream->pes.list[ii].stream_kind == A )
        {
            pes_add_audio_to_title( stream, ii, title, count );
        }
    }
}

/***********************************************************************
 * hb_ts_stream_init
 ***********************************************************************
 *
 **********************************************************************/

static int hb_ts_stream_init(hb_stream_t *stream)
{
    int i;

    if ( stream->ts.list )
    {
        for (i=0; i < stream->ts.alloc; i++)
        {
            stream->ts.list[i].continuity = -1;
            stream->ts.list[i].pid = -1;
            stream->ts.list[i].pes_list = -1;
        }
    }
    stream->ts.count = 0;

    if ( stream->pes.list )
    {
        for (i=0; i < stream->pes.alloc; i++)
        {
            stream->pes.list[i].stream_id = -1;
            stream->pes.list[i].next = -1;
        }
    }
    stream->pes.count = 0;

    stream->ts.packet = malloc( stream->packetsize );

    // Find the audio and video pids in the stream
    if (hb_ts_stream_find_pids(stream) < 0)
    {
        return -1;
    }

    // hb_ts_resolve_pid_types reads some data, so the TS buffers
    // are needed here.
    for (i = 0; i < stream->ts.count; i++)
    {
        // demuxing buffer for TS to PS conversion
        stream->ts.list[i].buf = hb_buffer_init(stream->packetsize);
        stream->ts.list[i].extra_buf = hb_buffer_init(stream->packetsize);
        stream->ts.list[i].buf->size = 0;
        stream->ts.list[i].extra_buf->size = 0;
    }
    hb_ts_resolve_pid_types(stream);

    if( stream->scan )
    {
        hb_log("Found the following PIDS");
        hb_log("    Video PIDS : ");
        for (i=0; i < stream->ts.count; i++)
        {
            if ( ts_stream_kind( stream, i ) == V )
            {
                hb_log( "      0x%x type %s (0x%x)%s",
                        stream->ts.list[i].pid,
                        stream_type_name2(stream, 
                                &stream->pes.list[stream->ts.list[i].pes_list]),
                        ts_stream_type( stream, i ),
                        stream->ts.list[i].is_pcr ? " (PCR)" : "");
            }
        }
        hb_log("    Audio PIDS : ");
        for (i = 0; i < stream->ts.count; i++)
        {
            if ( ts_stream_kind( stream, i ) == A )
            {
                hb_log( "      0x%x type %s (0x%x)%s",
                        stream->ts.list[i].pid,
                        stream_type_name2(stream,
                                &stream->pes.list[stream->ts.list[i].pes_list]),
                        ts_stream_type( stream, i ),
                        stream->ts.list[i].is_pcr ? " (PCR)" : "");
            }
        }
        hb_log("    Subtitle PIDS : ");
        for (i = 0; i < stream->ts.count; i++)
        {
            if ( ts_stream_kind( stream, i ) == S )
            {
                hb_log( "      0x%x type %s (0x%x)%s",
                        stream->ts.list[i].pid,
                        stream_type_name2(stream,
                                &stream->pes.list[stream->ts.list[i].pes_list]),
                        ts_stream_type( stream, i ),
                        stream->ts.list[i].is_pcr ? " (PCR)" : "");
            }
        }
        hb_log("    Other PIDS : ");
        for (i = 0; i < stream->ts.count; i++)
        {
            if ( ts_stream_kind( stream, i ) == N ||
                 ts_stream_kind( stream, i ) == P )
            {
                hb_log( "      0x%x type %s (0x%x)%s",
                        stream->ts.list[i].pid,
                        stream_type_name2(stream,
                                &stream->pes.list[stream->ts.list[i].pes_list]),
                        ts_stream_type( stream, i ),
                        stream->ts.list[i].is_pcr ? " (PCR)" : "");
            }
            if ( ts_stream_kind( stream, i ) == N )
                hb_stream_delete_ts_entry(stream, i);
        }
    }
    else
    {
        for (i = 0; i < stream->ts.count; i++)
        {
            if ( ts_stream_kind( stream, i ) == N )
                hb_stream_delete_ts_entry(stream, i);
        }
    }
    return 0;
}

static void hb_ps_stream_init(hb_stream_t *stream)
{
    int i;

    if ( stream->pes.list )
    {
        for (i=0; i < stream->pes.alloc; i++)
        {
            stream->pes.list[i].stream_id = -1;
            stream->pes.list[i].next = -1;
        }
    }
    stream->pes.count = 0;

    // Find the audio and video pids in the stream
    hb_ps_stream_find_streams(stream);
    hb_ps_resolve_stream_types(stream);

    if( stream->scan )
    {
        hb_log("Found the following streams");
        hb_log("    Video Streams : ");
        for (i=0; i < stream->pes.count; i++)
        {
            if ( stream->pes.list[i].stream_kind == V )
            {
                hb_log( "      0x%x-0x%x type %s (0x%x)",
                        stream->pes.list[i].stream_id,
                        stream->pes.list[i].stream_id_ext,
                        stream_type_name2(stream,
                                         &stream->pes.list[i]),
                        stream->pes.list[i].stream_type);
            }
        }
        hb_log("    Audio Streams : ");
        for (i = 0; i < stream->pes.count; i++)
        {
            if ( stream->pes.list[i].stream_kind == A )
            {
                hb_log( "      0x%x-0x%x type %s (0x%x)",
                        stream->pes.list[i].stream_id,
                        stream->pes.list[i].stream_id_ext,
                        stream_type_name2(stream,
                                         &stream->pes.list[i]),
                        stream->pes.list[i].stream_type );
            }
        }
        hb_log("    Subtitle Streams : ");
        for (i = 0; i < stream->pes.count; i++)
        {
            if ( stream->pes.list[i].stream_kind == S )
            {
                hb_log( "      0x%x-0x%x type %s (0x%x)",
                        stream->pes.list[i].stream_id,
                        stream->pes.list[i].stream_id_ext,
                        stream_type_name2(stream,
                                         &stream->pes.list[i]),
                        stream->pes.list[i].stream_type );
            }
        }
        hb_log("    Other Streams : ");
        for (i = 0; i < stream->pes.count; i++)
        {
            if ( stream->pes.list[i].stream_kind == N )
            {
                hb_log( "      0x%x-0x%x type %s (0x%x)",
                        stream->pes.list[i].stream_id,
                        stream->pes.list[i].stream_id_ext,
                        stream_type_name2(stream,
                                         &stream->pes.list[i]),
                        stream->pes.list[i].stream_type );
                hb_stream_delete_ps_entry(stream, i);
            }
        }
    }
    else
    {
        for (i = 0; i < stream->pes.count; i++)
        {
            if ( stream->pes.list[i].stream_kind == N )
                hb_stream_delete_ps_entry(stream, i);
        }
    }
}

#define MAX_HOLE 208*80

static off_t align_to_next_packet(hb_stream_t *stream)
{
    uint8_t buf[MAX_HOLE];
    off_t pos = 0;
    off_t start = ftello(stream->file_handle);
    off_t orig;

    if ( start >= stream->packetsize ) {
        start -= stream->packetsize;
        fseeko(stream->file_handle, start, SEEK_SET);
    }
    orig = start;

    while (1)
    {
        if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
        {
            const uint8_t *bp = buf;
            int i;

            for ( i = sizeof(buf) - 8 * stream->packetsize; --i >= 0; ++bp )
            {
                if ( have_ts_sync( bp, stream->packetsize, 8 ) )
                {
                    break;
                }
            }
            if ( i >= 0 )
            {
                pos = ( bp - buf ) - stream->packetsize + 188;
                break;
            }
            fseeko(stream->file_handle, -8 * stream->packetsize, SEEK_CUR);
            start = ftello(stream->file_handle);
        }
        else
        {
            return 0;
        }
    }
    fseeko(stream->file_handle, start+pos, SEEK_SET);
    return start - orig + pos;
}

static const unsigned int bitmask[] = {
    0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
    0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
    0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
    0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};

static inline void bits_init(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
{
    bb->pos = 0;
    bb->buf = buf;
    bb->size = bufsize;
    bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
              (bb->buf[2] << 8) | bb->buf[3];
    if (clear)
        memset(bb->buf, 0, bufsize);
    bb->size = bufsize;
}

static inline void bits_clone( bitbuf_t *dst, bitbuf_t *src, int bufsize )
{
    *dst = *src;
    dst->size = (dst->pos >> 3) + bufsize;
}

static inline int bits_bytes_left(bitbuf_t *bb)
{
    return bb->size - (bb->pos >> 3);
}

static inline int bits_eob(bitbuf_t *bb)
{
    return bb->pos >> 3 == bb->size;
}

static inline unsigned int bits_peek(bitbuf_t *bb, int bits)
{
    unsigned int val;
    int left = 32 - (bb->pos & 31);

    if (bits < left)
    {
        val = (bb->val >> (left - bits)) & bitmask[bits];
    }
    else
    {
        val = (bb->val & bitmask[left]) << (bits - left);
        int bpos = bb->pos + left;
        bits -= left;


        if (bits > 0)
        {
            int pos = bpos >> 3;
            int bval =  (bb->buf[pos]     << 24) | 
                        (bb->buf[pos + 1] << 16) | 
                        (bb->buf[pos + 2] <<  8) | 
                         bb->buf[pos + 3];
            val |= (bval >> (32 - bits)) & bitmask[bits];
        }
    }

    return val;
}

static inline unsigned int bits_get(bitbuf_t *bb, int bits)
{
    unsigned int val;
    int left = 32 - (bb->pos & 31);

    if (bits < left)
    {
        val = (bb->val >> (left - bits)) & bitmask[bits];
        bb->pos += bits;
    }
    else
    {
        val = (bb->val & bitmask[left]) << (bits - left);
        bb->pos += left;
        bits -= left;

        int pos = bb->pos >> 3;
        bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];

        if (bits > 0)
        {
            val |= (bb->val >> (32 - bits)) & bitmask[bits];
            bb->pos += bits;
        }
    }

    return val;
}

static inline int bits_read_ue(bitbuf_t *bb )
{
    int ii = 0;

    while( bits_get( bb, 1 ) == 0 && !bits_eob( bb ) && ii < 32 )
    {
        ii++;
    }
    return( ( 1 << ii) - 1 + bits_get( bb, ii ) );
}

static inline int bits_skip(bitbuf_t *bb, int bits)
{
    if (bits <= 0)
        return 0;
    while (bits > 32)
    {
        bits_get(bb, 32);
        bits -= 32;
    }
    bits_get(bb, bits);
    return 0;
}

// extract what useful information we can from the elementary stream
// descriptor list at 'dp' and add it to the stream at 'esindx'.
// Descriptors with info we don't currently use are ignored.
// The descriptor list & descriptor item formats are defined in
// ISO 13818-1 (2000E) section 2.6 (pg. 62).
static void decode_element_descriptors(
    hb_stream_t   *stream,
    int           pes_idx,
    bitbuf_t   *bb)
{
    int ii;

    while( bits_bytes_left( bb ) > 2 )
    {
        uint8_t tag = bits_get(bb, 8);
        uint8_t len = bits_get(bb, 8);
        switch ( tag )
        {
            case 5:    // Registration descriptor
                stream->pes.list[pes_idx].format_id = bits_get(bb, 32);
                bits_skip(bb, 8 * (len - 4));
                break;

            case 10:    // ISO_639_language descriptor
            {
                char code[3];
                for (ii = 0; ii < 3; ii++)
                {
                    code[ii] = bits_get(bb, 8);
                }
                stream->pes.list[pes_idx].lang_code =
                                    lang_to_code(lang_for_code2(code));
                bits_skip(bb, 8 * (len - 3));
            } break;

            case 0x56:  // DVB Teletext descriptor
            {
                // We don't currently process teletext from
                // TS or PS streams.  Set stream 'kind' to N
                stream->pes.list[pes_idx].stream_type = 0x00;
                stream->pes.list[pes_idx].stream_kind = N;
                strncpy(stream->pes.list[pes_idx].codec_name,
                        "DVB Teletext", 80);
                bits_skip(bb, 8 * len);
            } break;

            case 0x59:  // DVB Subtitleing descriptor
            {
                // We don't currently process subtitles from
                // TS or PS streams.  Set stream 'kind' to N
                stream->pes.list[pes_idx].stream_type = 0x00;
                stream->pes.list[pes_idx].stream_kind = N;
                strncpy(stream->pes.list[pes_idx].codec_name,
                        "DVB Subtitling", 80);
                bits_skip(bb, 8 * len);
            } break;

            case 0x6a:  // DVB AC-3 descriptor
            {
                stream->pes.list[pes_idx].stream_type = 0x81;
                update_pes_kind( stream, pes_idx );
                bits_skip(bb, 8 * len);
            } break;

            case 0x7a:  // DVB EAC-3 descriptor
            {
                stream->pes.list[pes_idx].stream_type = 0x87;
                update_pes_kind( stream, pes_idx );
                bits_skip(bb, 8 * len);
            } break;

            default:
                bits_skip(bb, 8 * len);
                break;
        }
    }
}

int decode_program_map(hb_stream_t* stream)
{
    bitbuf_t bb;
    bits_init(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);

    bits_get(&bb, 8);  // table_id
    bits_get(&bb, 4);
    unsigned int section_length = bits_get(&bb, 12);

    bits_get(&bb, 16); // program number
    bits_get(&bb, 2);
    bits_get(&bb, 5);  // version_number
    bits_get(&bb, 1);
    bits_get(&bb, 8);  // section_number
    bits_get(&bb, 8);  // last_section_number
    bits_get(&bb, 3);
    stream->pmt_info.PCR_PID = bits_get(&bb, 13);
    bits_get(&bb, 4);
    int program_info_length = bits_get(&bb, 12);
    int i;
    for (i = 0; i < program_info_length - 2; )
    {
        uint8_t tag, len;
        tag = bits_get(&bb, 8);
        len = bits_get(&bb, 8);
        i += 2;
        if ( i + len > program_info_length )
        {
            break;
        }
        if (tag == 0x05 && len >= 4)
        {
            // registration descriptor
            stream->reg_desc = bits_get(&bb, 32);
            i += 4;
            len -= 4;
        }
        int j;
        for ( j = 0; j < len; j++ )
        {
            bits_get(&bb, 8);
        }
        i += len;
    }
    for ( ; i < program_info_length; i++ )
    {
        bits_get(&bb, 8);
    }

    int cur_pos =  9 /* data after the section length field*/ + program_info_length;
    int done_reading_stream_types = 0;
    int ii = 0;
    while (!done_reading_stream_types)
    {
        unsigned char stream_type = bits_get(&bb, 8);
        bits_get(&bb, 3);
        unsigned int elementary_PID = bits_get(&bb, 13);
        bits_get(&bb, 4);
        unsigned int info_len = bits_get(&bb, 12);
        // Defined audio stream types are 0x81 for AC-3/A52 audio
        // and 0x03 for mpeg audio. But content producers seem to
        // use other values (0x04 and 0x06 have both been observed)
        // so at this point we say everything that isn't a video
        // pid is audio then at the end of hb_stream_title_scan
        // we'll figure out which are really audio by looking at
        // the PES headers.
        int pes_idx;
        update_ts_streams( stream, elementary_PID, 0,
                           stream_type, -1, &pes_idx );
        if ( pes_idx >= 0 )
            stream->pes.list[pes_idx].map_idx = ii;
        if (info_len > 0)
        {
            bitbuf_t bb_desc;
            bits_clone( &bb_desc, &bb, info_len );
            if ( pes_idx >= 0 )
                decode_element_descriptors( stream, pes_idx, &bb_desc );
            bits_skip(&bb, 8 * info_len);
        }

        cur_pos += 5 /* stream header */ + info_len;

        if (cur_pos >= section_length - 4 /* stop before the CRC */)
            done_reading_stream_types = 1;
        ii++;
    }

    return 1;
}

static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
{
    // Get adaption header info
    int adapt_len = 0;
    int adaption = (buf[3] & 0x30) >> 4;
    if (adaption == 0)
            return 0;
    else if (adaption == 0x2)
            adapt_len = 184;
    else if (adaption == 0x3)
            adapt_len = buf[4] + 1;
    if (adapt_len > 184)
            return 0;

    // Get payload start indicator
    int start;
    start = (buf[1] & 0x40) != 0;

    // Get pointer length - only valid in packets with a start flag
    int pointer_len = 0;

    if (start)
    {
        pointer_len = buf[4 + adapt_len] + 1;
        stream->pmt_info.tablepos = 0;
    }
    // Get Continuity Counter
    int continuity_counter = buf[3] & 0x0f;
    if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
    {
        hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
        return 0;
    }
    stream->pmt_info.current_continuity_counter = continuity_counter;
    stream->pmt_info.reading |= start;

    // Add the payload for this packet to the current buffer
    int amount_to_copy = 184 - adapt_len - pointer_len;
    if (stream->pmt_info.reading && (amount_to_copy > 0))
    {
            stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);

            memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
            stream->pmt_info.tablepos += amount_to_copy;
    }
    if (stream->pmt_info.tablepos > 3)
    {
        // We have enough to check the section length
        int length;
        length = ((stream->pmt_info.tablebuf[1] << 8) +
                  stream->pmt_info.tablebuf[2]) & 0xFFF;
        if (stream->pmt_info.tablepos > length + 1)
        {
            // We just finished a bunch of packets - parse the program map details
            int decode_ok = 0;
            if (stream->pmt_info.tablebuf[0] == 0x02)
                decode_ok = decode_program_map(stream);
            free(stream->pmt_info.tablebuf);
            stream->pmt_info.tablebuf = NULL;
            stream->pmt_info.tablepos = 0;
            stream->pmt_info.reading = 0;
            if (decode_ok)
                return decode_ok;
        }

    }

    return 0;
}

static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
{
    unsigned char tablebuf[1024];
    unsigned int tablepos = 0;

    int reading = 0;


    // Get adaption header info
    int adapt_len = 0;
    int adaption = (buf[3] & 0x30) >> 4;
    if (adaption == 0)
            return 0;
    else if (adaption == 0x2)
            adapt_len = 184;
    else if (adaption == 0x3)
            adapt_len = buf[4] + 1;
    if (adapt_len > 184)
            return 0;

    // Get pointer length
    int pointer_len = buf[4 + adapt_len] + 1;

    // Get payload start indicator
    int start;
    start = (buf[1] & 0x40) != 0;

    if (start)
            reading = 1;

    // Add the payload for this packet to the current buffer
    if (reading && (184 - adapt_len) > 0)
    {
            if (tablepos + 184 - adapt_len - pointer_len > 1024)
            {
                    hb_log("decode_PAT - Bad program section length (> 1024)");
                    return 0;
            }
            memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
            tablepos += 184 - adapt_len - pointer_len;
    }

    if (start && reading)
    {
            memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);


            unsigned int pos = 0;
            //while (pos < tablepos)
            {
                    bitbuf_t bb;
                    bits_init(&bb, tablebuf + pos, tablepos - pos, 0);

                    unsigned char section_id    = bits_get(&bb, 8);
                    bits_get(&bb, 4);
                    unsigned int section_len    = bits_get(&bb, 12);
                    bits_get(&bb, 16); // transport_id
                    bits_get(&bb, 2);
                    bits_get(&bb, 5);  // version_num
                    bits_get(&bb, 1);  // current_next
                    bits_get(&bb, 8);  // section_num
                    bits_get(&bb, 8);  // last_section

                    switch (section_id)
                    {
                      case 0x00:
                        {
                          // Program Association Section
                          section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
                          section_len -= 4;   // Ignore the CRC
                          int curr_pos = 0;
                          stream->ts_number_pat_entries = 0;
                          while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
                          {
                            unsigned int pkt_program_num = bits_get(&bb, 16);
                            stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;

                            bits_get(&bb, 3);  // Reserved
                            if (pkt_program_num == 0)
                            {
                              bits_get(&bb, 13); // pkt_network_id
                            }
                            else
                            {
                              unsigned int pkt_program_map_PID = bits_get(&bb, 13);
                                stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
                            }
                            curr_pos += 4;
                            stream->ts_number_pat_entries++;
                          }
                        }
                        break;
                      case 0xC7:
                            {
                                    break;
                            }
                      case 0xC8:
                            {
                                    break;
                            }
                    }

                    pos += 3 + section_len;
            }

            tablepos = 0;
    }
    return 1;
}

// convert a PES PTS or DTS to an int64
static int64_t parse_pes_timestamp( bitbuf_t *bb )
{
    int64_t ts;

    ts =  ( (uint64_t)   bits_get(bb,  3) << 30 ) +
                         bits_skip(bb, 1)         +
                       ( bits_get(bb, 15) << 15 ) +
                         bits_skip(bb, 1)         +
                         bits_get(bb, 15);
    bits_skip(bb, 1);
    return ts;
}

static int parse_pes_header(
    hb_stream_t   *stream,
    bitbuf_t      *bb,
    hb_pes_info_t *pes_info )
{
    if ( bits_bytes_left(bb) < 6 )
    {
        return 0;
    }

    bits_skip(bb, 8 * 4);
    pes_info->packet_len = bits_get(bb, 16);

    /*
     * This would normally be an error.  But the decoders can generally
     * recover well from missing data.  So let the packet pass.
    if ( bits_bytes_left(bb) < pes_info->packet_len )
    {
        return 0;
    }
    */

    int mark = bits_peek(bb, 2);
    if ( mark == 0x02 )
    {
        // mpeg2 pes
        if ( bits_bytes_left(bb) < 3 )
        {
            return 0;
        }

        /*
        bits_skip(bb, 2);
        bits_get(bb, 2);    // scrambling
        bits_get(bb, 1);    // priority
        bits_get(bb, 1);    // alignment
        bits_get(bb, 1);    // copyright
        bits_get(bb, 1);    // original
        */
        bits_get(bb, 8);    // skip all of the above

        int has_pts        = bits_get(bb, 2);
        int has_escr       = bits_get(bb, 1);
        int has_esrate     = bits_get(bb, 1);
        int has_dsm        = bits_get(bb, 1);
        int has_copy_info  = bits_get(bb, 1);
        int has_crc        = bits_get(bb, 1);
        int has_ext        = bits_get(bb, 1);
        int hdr_len = pes_info->header_len = bits_get(bb, 8);
        pes_info->header_len += bb->pos >> 3;

        bitbuf_t bb_hdr;
        bits_clone(&bb_hdr, bb, hdr_len);

        if ( bits_bytes_left(&bb_hdr) < hdr_len )
        {
            return 0;
        }

        int expect = (!!has_pts) * 5 + (has_pts & 0x01) * 5 + has_escr * 6 + 
                     has_esrate * 3 + has_dsm + has_copy_info + has_crc * 2 + 
                     has_ext;

        if ( bits_bytes_left(&bb_hdr) < expect )
        {
            return 0;
        }

        if( has_pts )
        {
            if ( bits_bytes_left(&bb_hdr) < 5 )
            {
                return 0;
            }
            bits_skip(&bb_hdr, 4);
            pes_info->pts = parse_pes_timestamp( &bb_hdr );
            if ( has_pts & 1 )
            {
                if ( bits_bytes_left(&bb_hdr) < 5 )
                {
                    return 0;
                }
                bits_skip(&bb_hdr, 4);
                pes_info->dts = parse_pes_timestamp( &bb_hdr );
            }
            else
            {
                pes_info->dts = pes_info->pts;
            }
        }
        // A user encountered a stream that has garbage DTS timestamps.
        // DTS should never be > PTS.  Such broken timestamps leads to
        // HandBrake computing negative buffer start times.
        if (pes_info->dts > pes_info->pts)
        {
            pes_info->dts = pes_info->pts;
        }

        if ( has_escr )
            bits_skip(&bb_hdr, 8 * 6);
        if ( has_esrate )
            bits_skip(&bb_hdr, 8 * 3);
        if ( has_dsm )
            bits_skip(&bb_hdr, 8);
        if ( has_copy_info )
            bits_skip(&bb_hdr, 8);
        if ( has_crc )
            bits_skip(&bb_hdr, 8 * 2);

        if ( has_ext )
        {
            int has_private = bits_get(&bb_hdr, 1);
            int has_pack = bits_get(&bb_hdr, 1);
            int has_counter = bits_get(&bb_hdr, 1);
            int has_pstd = bits_get(&bb_hdr, 1);
            bits_skip(&bb_hdr, 3);   // reserved bits
            int has_ext2 = bits_get(&bb_hdr, 1);

            expect = (has_private) * 16 + has_pack + has_counter * 2 + 
                     has_pstd * 2 + has_ext2 * 2;

            if ( bits_bytes_left(&bb_hdr) < expect )
            {
                return 0;
            }

            if ( has_private )
            {
                bits_skip(&bb_hdr, 8 * 16);
                expect -= 2;
            }
            if ( has_pack )
            {
                int len = bits_get(&bb_hdr, 8);
                expect -= 1;
                if ( bits_bytes_left(&bb_hdr) < len + expect )
                {
                    return 0;
                }
                bits_skip(&bb_hdr, 8 * len);
            }
            if ( has_counter )
                bits_skip(&bb_hdr, 8 * 2);
            if ( has_pstd )
                bits_skip(&bb_hdr, 8 * 2);

            if ( has_ext2 )
            {
                bits_skip(&bb_hdr, 1);   // marker
                bits_get(&bb_hdr, 7);    // extension length
                pes_info->has_stream_id_ext = !bits_get(&bb_hdr, 1);
                if ( pes_info->has_stream_id_ext )
                    pes_info->stream_id_ext = bits_get(&bb_hdr, 7);
            }
        }
        // eat header stuffing
        bits_skip(bb, 8 * hdr_len);
    }
    else
    {
        // mpeg1 pes

        // Skip stuffing
        while ( bits_peek(bb, 1) && bits_bytes_left(bb) )
            bits_get(bb, 8);

        if ( !bits_bytes_left(bb) )
            return 0;

        // Skip std buffer info
        int mark = bits_get(bb, 2);
        if ( mark == 0x01 )
        {
            if ( bits_bytes_left(bb) < 2 )
                return 0;
            bits_skip(bb, 8 * 2);
        }

        int has_pts = bits_get(bb, 2);
        if( has_pts == 0x02 )
        {
            pes_info->pts = parse_pes_timestamp( bb );
            pes_info->dts = pes_info->pts;
        }
        else if( has_pts == 0x03 )
        {
            pes_info->pts = parse_pes_timestamp( bb );
            bits_skip(bb, 4);
            pes_info->dts = parse_pes_timestamp( bb );
        }
        else
        {
            bits_skip(bb, 8); // 0x0f flag
        }
        if ( bits_bytes_left(bb) < 0 )
            return 0;
        pes_info->header_len = bb->pos >> 3;
    }
    if ( pes_info->stream_id == 0xbd && stream->hb_stream_type == program )
    {
        if ( bits_bytes_left(bb) < 4 )
        {
            return 0;
        }
        int ssid = bits_peek(bb, 8);
        if( ( ssid >= 0xa0 && ssid <= 0xaf ) ||
            ( ssid >= 0x20 && ssid <= 0x2f ) )
        {
            // DVD LPCM or DVD SPU (subtitles)
            pes_info->bd_substream_id = bits_get(bb, 8);
            pes_info->header_len += 1;
        }
        else if ( ssid >= 0xb0 && ssid <= 0xbf )
        {
            // HD-DVD TrueHD has a 4 byte header
            pes_info->bd_substream_id = bits_get(bb, 8);
            bits_skip(bb, 8 * 4);
            pes_info->header_len += 5;
        }
        else if( ( ssid >= 0x80 && ssid <= 0x9f ) ||
                 ( ssid >= 0xc0 && ssid <= 0xcf ) )
        {
            // AC3, E-AC3, DTS, and DTS-HD has 3 byte header
            pes_info->bd_substream_id = bits_get(bb, 8);
            bits_skip(bb, 8 * 3);
            pes_info->header_len += 4;
        }
    }
    return 1;
}

static int parse_pack_header(
    hb_stream_t   *stream,
    bitbuf_t      *bb,
    hb_pes_info_t *pes_info )
{
    if ( bits_bytes_left(bb) < 12)
    {
        return 0;
    }

    bits_skip(bb, 8 * 4);
    int mark = bits_get(bb, 2);

    if ( mark == 0x00 )
    {
        // mpeg1 pack
        bits_skip(bb, 2); // marker
    }
    pes_info->scr = parse_pes_timestamp( bb );

    if ( mark == 0x00 )
    {
        bits_skip(bb, 24);
        pes_info->header_len = (bb->pos >> 3);
    }
    else
    {
        bits_skip(bb, 39);
        int stuffing = bits_get(bb, 3);
        pes_info->header_len = stuffing;
        pes_info->header_len += (bb->pos >> 3);
    }
    return 1;
}

// Returns the length of the header
static int hb_parse_ps(
    hb_stream_t   *stream,
    uint8_t       *buf,
    int           len,
    hb_pes_info_t *pes_info )
{
    memset( pes_info, 0, sizeof( hb_pes_info_t ) );
    pes_info->pts = AV_NOPTS_VALUE;
    pes_info->dts = AV_NOPTS_VALUE;

    bitbuf_t bb, cc;
    bits_init(&bb, buf, len, 0);
    bits_clone(&cc, &bb, len);

    if ( bits_bytes_left(&bb) < 4 )
        return 0;

    // Validate start code
    if ( bits_get(&bb, 8 * 3) != 0x000001 )
    {
        return 0;
    }

    pes_info->stream_id = bits_get(&bb, 8);
    if ( pes_info->stream_id == 0xb9 )
    {
        // Program stream end code
        return 1;
    }
    else if ( pes_info->stream_id == 0xba )
    {
        return parse_pack_header( stream, &cc, pes_info );
    }
    else if ( pes_info->stream_id >= 0xbd &&
              pes_info->stream_id != 0xbe &&
              pes_info->stream_id != 0xbf &&
              pes_info->stream_id != 0xf0 &&
              pes_info->stream_id != 0xf1 &&
              pes_info->stream_id != 0xf2 &&
              pes_info->stream_id != 0xf8 &&
              pes_info->stream_id != 0xff )
    {
        return parse_pes_header( stream, &cc, pes_info );
    }
    else
    {
        if ( bits_bytes_left(&bb) < 2 )
        {
            return 0;
        }
        pes_info->packet_len = bits_get(&bb, 16);
        pes_info->header_len = bb.pos >> 3;
        return 1;
    }
}

static int hb_ps_read_packet( hb_stream_t * stream, hb_buffer_t *b )
{
    // Appends to buffer if size != 0
    int start_code = -1;
    int pos = b->size;
    int stream_id = -1;
    int c;

#define cp (b->data)
    flockfile( stream->file_handle );
    while ( ( c = getc_unlocked( stream->file_handle ) ) != EOF )
    {
        start_code = ( start_code << 8 ) | c;
        if ( ( start_code >> 8 )== 0x000001 )
            // we found the start of the next start
            break;
    }
    if ( c == EOF )
        goto done;

    if ( pos + 4 > b->alloc )
    {
        // need to expand the buffer
        hb_buffer_realloc( b, b->alloc * 2 );
    }
    cp[pos++] = ( start_code >> 24 ) & 0xff;
    cp[pos++] = ( start_code >> 16 ) & 0xff;
    cp[pos++] = ( start_code >>  8 ) & 0xff;
    cp[pos++] = ( start_code )       & 0xff;
    stream_id = start_code & 0xff;

    if ( stream_id == 0xba )
    {
        int start = pos - 4;
        // Read pack header
        if ( pos + 21 >= b->alloc )
        {
            // need to expand the buffer
            hb_buffer_realloc( b, b->alloc * 2 );
        }

        // There are at least 8 bytes.  More if this is mpeg2 pack.
        fread( cp+pos, 1, 8, stream->file_handle );
        int mark = cp[pos] >> 4;
        pos += 8;

        if ( mark != 0x02 )
        {
            // mpeg-2 pack,
            fread( cp+pos, 1, 2, stream->file_handle );
            pos += 2;
            int len = cp[start+13] & 0x7;
            fread( cp+pos, 1, len, stream->file_handle );
            pos += len;
        }
    }
    // Non-video streams can emulate start codes, so we need
    // to inspect PES packets and skip over their data
    // sections to avoid mis-detection of the next pack or pes start code
    else if ( stream_id >= 0xbb )
    {
        int len = 0;
        c = getc_unlocked( stream->file_handle );
        if ( c == EOF )
            goto done;
        len = c << 8;
        c = getc_unlocked( stream->file_handle );
        if ( c == EOF )
            goto done;
        len |= c;
        if ( pos + len + 2 > b->alloc )
        {
            if ( b->alloc * 2 > pos + len + 2 )
                hb_buffer_realloc( b, b->alloc * 2 );
            else
                hb_buffer_realloc( b, b->alloc * 2 + len + 2 );
        }
        cp[pos++] = len >> 8;
        cp[pos++] = len & 0xff;
        if ( len )
        {
            // Length is non-zero, read the packet all at once
            len = fread( cp+pos, 1, len, stream->file_handle );
            pos += len;
        }
        else
        {
            // Length is zero, read bytes till we find a start code.
            // Only video PES packets are allowed to have zero length.
            start_code = -1;
            while ( ( c = getc_unlocked( stream->file_handle ) ) != EOF )
            {
                start_code = ( start_code << 8 ) | c;
                if ( pos  >= b->alloc )
                {
                    // need to expand the buffer
                    hb_buffer_realloc( b, b->alloc * 2 );
                }
                cp[pos++] = c;
                if ( ( start_code >> 8   ) == 0x000001 &&
                     ( start_code & 0xff ) >= 0xb9 )
                {
                    // we found the start of the next start
                    break;
                }
            }
            if ( c == EOF )
                goto done;
            pos -= 4;
            fseeko( stream->file_handle, -4, SEEK_CUR );
        }
    }
    else
    {
        // Unknown, find next start code
        start_code = -1;
        while ( ( c = getc_unlocked( stream->file_handle ) ) != EOF )
        {
            start_code = ( start_code << 8 ) | c;
            if ( pos  >= b->alloc )
            {
                // need to expand the buffer
                hb_buffer_realloc( b, b->alloc * 2 );
            }
            cp[pos++] = c;
            if ( ( start_code >> 8 ) == 0x000001 &&
                 ( start_code & 0xff ) >= 0xb9 )
                // we found the start of the next start
                break;
        }
        if ( c == EOF )
            goto done;
        pos -= 4;
        fseeko( stream->file_handle, -4, SEEK_CUR );
    }
done:
    // Parse packet for information we might need
    funlockfile( stream->file_handle );
    int len = pos - b->size;
    b->size = pos;
#undef cp
    return len;
}

static hb_buffer_t * hb_ps_stream_decode( hb_stream_t *stream )
{
    hb_pes_info_t pes_info;
    hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);

    while (1)
    {
        buf->size = 0;
        int len = hb_ps_read_packet( stream, buf );
        if ( len == 0 )
        {
            // End of file
            hb_buffer_close( &buf );
            return buf;
        }
        if ( !hb_parse_ps( stream, buf->data, buf->size, &pes_info ) )
        {
            ++stream->errors;
            continue;
        }
        // pack header
        if ( pes_info.stream_id == 0xba )
        {
            stream->pes.found_scr = 1;
            stream->ts_flags |= TS_HAS_PCR;
            stream->pes.scr = pes_info.scr;
            continue;
        }

        // If we don't have a SCR yet but the stream has SCRs just loop
        // so we don't process anything until we have a clock reference.
        if ( !stream->pes.found_scr && ( stream->ts_flags & TS_HAS_PCR ) )
        {
            continue;
        }

        // system header
        if ( pes_info.stream_id == 0xbb )
            continue;

        int idx;
        if ( pes_info.stream_id == 0xbd )
        {
            idx = index_of_ps_stream( stream, pes_info.stream_id,
                                      pes_info.bd_substream_id );
        }
        else
        {
            idx = index_of_ps_stream( stream, pes_info.stream_id,
                                      pes_info.stream_id_ext );
        }

        // Is this a stream carrying data that we care about?
        if ( idx < 0 )
            continue;

        switch (stream->pes.list[idx].stream_kind)
        {
            case A:
                buf->s.type = AUDIO_BUF;
                break;

            case V:
                buf->s.type = VIDEO_BUF;
                break;

            default:
                buf->s.type = OTHER_BUF;
                break;
        }

        if ( stream->need_keyframe )
        {
            // we're looking for the first video frame because we're
            // doing random access during 'scan'
            if ( buf->s.type != VIDEO_BUF ||
                 !isIframe( stream, buf->data, buf->size ) )
            {
                // not the video stream or didn't find an I frame
                // but we'll only wait 255 video frames for an I frame.
                if ( buf->s.type != VIDEO_BUF || ++stream->need_keyframe < 512 )
                {
                    continue;
                }
            }
            stream->need_keyframe = 0;
        }
        if ( buf->s.type == VIDEO_BUF )
            ++stream->frames;

        buf->s.id = get_id( &stream->pes.list[idx] );
        buf->s.pcr = stream->pes.scr;
        buf->s.start = pes_info.pts;
        buf->s.renderOffset = pes_info.dts;
        memmove( buf->data, buf->data + pes_info.header_len,
                 buf->size - pes_info.header_len );
        buf->size -= pes_info.header_len;
        if ( buf->size == 0 )
            continue;
        stream->pes.scr = AV_NOPTS_VALUE;
        return buf;
    }
}

static int update_ps_streams( hb_stream_t * stream, int stream_id, int stream_id_ext, int stream_type, int in_kind )
{
    int ii;
    int same_stream = -1;
    kind_t kind = in_kind == -1 ? st2codec[stream_type].kind : in_kind;

    for ( ii = 0; ii < stream->pes.count; ii++ )
    {
        if ( stream->pes.list[ii].stream_id == stream_id )
            same_stream = ii;

        if ( stream->pes.list[ii].stream_id == stream_id &&
             stream->pes.list[ii].stream_id_ext == 0 &&
             stream->pes.list[ii].stream_kind == U )
        {
            // This is an unknown stream type that hasn't been
            // given a stream_id_ext.  So match only to stream_id
            //
            // is the stream_id_ext being updated?
            if ( stream_id_ext != 0 )
                break;

            // If stream is already in the list and the new 'kind' is
            // PCR, Unknown, or same as before, just return the index
            // to the entry found.
            if ( kind == P || kind == U || kind == stream->pes.list[ii].stream_kind )
                return ii;
            // Update stream_type and kind
            break;
        }
        if ( stream_id == stream->pes.list[ii].stream_id &&
             stream_id_ext == stream->pes.list[ii].stream_id_ext )
        {
            // If stream is already in the list and the new 'kind' is
            // PCR and the old 'kind' is unknown, set the new 'kind'
            if ( kind == P && stream->pes.list[ii].stream_kind == U )
                break;

            // If stream is already in the list and the new 'kind' is
            // PCR, Unknown, or same as before, just return the index
            // to the entry found.
            if ( kind == P || kind == U || kind == stream->pes.list[ii].stream_kind )
                return ii;
            // Replace unknown 'kind' with known 'kind'
            break;
        }
        // Resolve multiple videos
        if ( kind == V && stream->pes.list[ii].stream_kind == V )
        {
            if ( stream_id <= stream->pes.list[ii].stream_id &&
                 stream_id_ext <= stream->pes.list[ii].stream_id_ext )
            {
                // Assume primary video stream has the smallest stream id
                // and only use the primary. move the current item
                // to the end of the list.  we want to keep it for 
                // debug and informational purposes.
                int jj = new_pes( stream );
                memcpy( &stream->pes.list[jj], &stream->pes.list[ii],
                        sizeof( hb_pes_stream_t ) );
                break;
            }
        }
    }

    if ( ii == stream->pes.count )
    {
        ii = new_pes( stream );
        if ( same_stream >= 0 )
        {
            memcpy( &stream->pes.list[ii], &stream->pes.list[same_stream],
                    sizeof( hb_pes_stream_t ) );
        }
        else
        {
            stream->pes.list[ii].map_idx = -1;
        }
    }

    stream->pes.list[ii].stream_id = stream_id;
    stream->pes.list[ii].stream_id_ext = stream_id_ext;
    stream->pes.list[ii].stream_type = stream_type;
    stream->pes.list[ii].stream_kind = kind;
    return ii;
}

static void update_pes_kind( hb_stream_t * stream, int idx )
{
    kind_t kind = st2codec[stream->pes.list[idx].stream_type].kind;
    if ( kind != U && kind != N )
    {
        stream->pes.list[idx].stream_kind = kind;
    }
}

static void ts_pes_list_add( hb_stream_t *stream, int ts_idx, int pes_idx )
{
    int ii = stream->ts.list[ts_idx].pes_list;
    if ( ii == -1 )
    {
        stream->ts.list[ts_idx].pes_list = pes_idx;
        return;
    }

    int idx;
    while ( ii != -1 )
    {
        if ( ii == pes_idx ) // Already in list
            return;
        idx = ii;
        ii = stream->pes.list[ii].next;
    }
    stream->pes.list[idx].next = pes_idx;
}

static int update_ts_streams( hb_stream_t * stream, int pid, int stream_id_ext, int stream_type, int in_kind, int *out_pes_idx )
{
    int ii;
    int pes_idx = update_ps_streams( stream, pid, stream_id_ext,
                                     stream_type, in_kind );

    if ( out_pes_idx )
        *out_pes_idx = pes_idx;

    if ( pes_idx < 0 )
        return -1;

    kind_t kind = stream->pes.list[pes_idx].stream_kind;
    for ( ii = 0; ii < stream->ts.count; ii++ )
    {
        if ( pid == stream->ts.list[ii].pid )
        {
            break;
        }
        // Resolve multiple videos
        if ( kind == V && ts_stream_kind( stream, ii ) == V && 
             pes_idx < stream->ts.list[ii].pes_list )
        {
            // We have a new candidate for the primary video.  Move
            // the current video to the end of the list. And put the
            // new video in this slot
            int jj = new_pid( stream );
            memcpy( &stream->ts.list[jj], &stream->ts.list[ii], 
                    sizeof( hb_ts_stream_t ) );
            break;
        }
    }
    if ( ii == stream->ts.count )
        ii = new_pid( stream );

    stream->ts.list[ii].pid = pid;
    ts_pes_list_add( stream, ii, pes_idx );
    if ( in_kind == P )
        stream->ts.list[ii].is_pcr = 1;

    return ii;
}

static int decode_ps_map( hb_stream_t * stream, uint8_t *buf, int len )
{
    int retval = 1;
    bitbuf_t bb;
    bits_init(&bb, buf, len, 0);

    if ( bits_bytes_left(&bb) < 10 )
        return 0;

    // Skip stuff not needed
    bits_skip(&bb, 8 * 8);
    int info_len = bits_get(&bb, 16);
    if ( bits_bytes_left(&bb) < info_len )
        return 0;

    if ( info_len )
    {
        bitbuf_t cc;
        bits_clone( &cc, &bb, info_len );

        while ( bits_bytes_left(&cc) >= 2 )
        {
            uint8_t tag, len;

            tag = bits_get(&cc, 8);
            len = bits_get(&cc, 8);
            if ( bits_bytes_left(&cc) < len )
                return 0;

            if (tag == 0x05 && len >= 4)
            {
                // registration descriptor
                stream->reg_desc = bits_get(&cc, 32);
                bits_skip(&cc, 8 * (len - 4));
            }
            else
            {
                bits_skip(&cc, 8 * len);
            }
        }
        bits_skip(&bb, 8 * info_len);
    }

    int map_len = bits_get(&bb, 16);
    if ( bits_bytes_left(&bb) < map_len )
        return 0;

    // Process the map
    int ii = 0;
    while ( bits_bytes_left(&bb) >= 8 )
    {
        int pes_idx;
        int stream_type = bits_get(&bb, 8);
        int stream_id = bits_get(&bb, 8);
        info_len = bits_get(&bb, 16);
        if ( info_len > bits_bytes_left(&bb) )
            return 0;

        int substream_id = 0;
        switch ( stream_type )
        {
            case 0x81: // ac3
            case 0x82: // dts
            case 0x83: // lpcm
            case 0x87: // eac3
                // If the stream_id isn't one of the standard mpeg
                // stream ids, assume it is an private stream 1 substream id.
                // This is how most PS streams specify this type of audio.
                //
                // TiVo sets the stream id to 0xbd and does not
                // give a substream id.  This limits them to one audio 
                // stream and differs from how everyone else specifies
                // this type of audio.
                if ( stream_id < 0xb9 )
                {
                    substream_id = stream_id;
                    stream_id = 0xbd;
                }
                break;
            default:
                break;
        }

        pes_idx = update_ps_streams( stream, stream_id, substream_id,
                                     stream_type, -1 );
        if ( pes_idx >= 0 )
            stream->pes.list[pes_idx].map_idx = ii;

        if ( info_len > 0 )
        {
            bitbuf_t bb_desc;
            bits_clone( &bb_desc, &bb, info_len );
            if ( pes_idx >= 0 )
                decode_element_descriptors( stream, pes_idx, &bb_desc );
            bits_skip(&bb, 8 * info_len);
        }
        ii++;
    }
    // skip CRC 32
    return retval;
}

static void hb_ps_stream_find_streams(hb_stream_t *stream)
{
    int ii, jj;
    hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);

    fseeko( stream->file_handle, 0, SEEK_SET );
    // Scan beginning of file, then if no program stream map is found
    // seek to 20% and scan again since there's occasionally no
    // audio at the beginning (particularly for vobs).
    for ( ii = 0; ii < 2; ii++ )
    {
        for ( jj = 0; jj < MAX_PS_PROBE_SIZE; jj += buf->size )
        {
            int stream_type;
            int len;

            hb_pes_info_t pes_info;
            buf->size = 0;
            len = hb_ps_read_packet( stream, buf );
            if ( len == 0 )
            {
                // Must have reached EOF
                break;
            }
            if ( !hb_parse_ps( stream, buf->data, buf->size, &pes_info ) )
            {
                hb_deep_log( 2, "hb_ps_stream_find_streams: Error parsing PS packet");
                continue;
            }
            if ( pes_info.stream_id == 0xba )
            {
                stream->ts_flags |= TS_HAS_PCR;
            }
            else if ( pes_info.stream_id == 0xbc )
            {
                // program stream map
                // Note that if there is a program map, any
                // extrapolation that is made below based on 
                // stream id may be overridden by entry in the map.
                if ( decode_ps_map( stream, buf->data, buf->size ) )
                {
                    hb_log("Found program stream map");
                    // Normally, we could quit here since the program
                    // stream map *should* map all streams. But once
                    // again Tivo breaks things by not always creating
                    // complete maps.  So continue processing...
                }
                else
                {
                    hb_error("Error parsing program stream map");
                }
            }
            else if ( ( pes_info.stream_id & 0xe0 ) == 0xc0 )
            {
                // MPeg audio (c0 - df)
                stream_type = 0x04;
                update_ps_streams( stream, pes_info.stream_id,
                                   pes_info.stream_id_ext, stream_type, -1 );
            }
            else if ( pes_info.stream_id == 0xbd )
            {
                int ssid = pes_info.bd_substream_id;
                // Add a potentail audio stream
                // Check dvd substream id
                if ( ssid >= 0x20 && ssid <= 0x37 )
                {
                    int idx = update_ps_streams( stream, pes_info.stream_id,
                                            pes_info.bd_substream_id, 0, -1 );
                    stream->pes.list[idx].stream_kind = S;
                    stream->pes.list[idx].codec = WORK_DECVOBSUB;
                    strncpy(stream->pes.list[idx].codec_name, 
                            "DVD Subtitle", 80);
                    continue;
                }
                if ( ssid >= 0x80 && ssid <= 0x87 )
                {
                    stream_type = 0x81; // ac3
                }
                else if ( ( ssid >= 0x88 && ssid <= 0x8f ) ||
                          ( ssid >= 0x98 && ssid <= 0x9f ) )
                {
                    // Could be either dts or dts-hd
                    // will have to probe to resolve
                    int idx = update_ps_streams( stream, pes_info.stream_id,
                                            pes_info.bd_substream_id, 0, U );
                    stream->pes.list[idx].codec = HB_ACODEC_DCA_HD;
                    stream->pes.list[idx].codec_param = AV_CODEC_ID_DTS;
                    continue;
                }
                else if ( ssid >= 0xa0 && ssid <= 0xaf )
                {
                    stream_type = 0x83; // lpcm
                    // This is flagged as an unknown stream type in
                    // st2codec because it can be either LPCM or
                    // BD TrueHD. In this case it is LPCM.
                    update_ps_streams( stream, pes_info.stream_id,
                                   pes_info.bd_substream_id, stream_type, A );
                    continue;
                }
                else if ( ssid >= 0xb0 && ssid <= 0xbf )
                {
                    // HD-DVD TrueHD
                    int idx = update_ps_streams( stream, pes_info.stream_id,
                                            pes_info.bd_substream_id, 0, A );
                    stream->pes.list[idx].codec = HB_ACODEC_FFMPEG;
                    stream->pes.list[idx].codec_param = AV_CODEC_ID_TRUEHD;
                    continue;
                }
                else if ( ssid >= 0xc0 && ssid <= 0xcf )
                {
                    // HD-DVD uses this for both ac3 and eac3.
                    // Check ac3 bitstream_id to distinguish between them.
                    bitbuf_t bb;
                    bits_init(&bb, buf->data + pes_info.header_len, 
                              buf->size - pes_info.header_len, 0);
                    int sync = bits_get(&bb, 16);
                    if ( sync == 0x0b77 )
                    {
                        bits_skip(&bb, 24);
                        int bsid = bits_get(&bb, 5);
                        if ( bsid <= 10 )
                        {
                            // ac3
                            stream_type = 0x81; // ac3
                        }
                        else
                        {
                            // eac3
                            stream_type = 0x87; // eac3
                        }
                    }
                    else
                    {
                        // Doesn't look like an ac3 stream.  Probe it.
                        stream_type = 0x00;
                    }
                }
                else
                {
                    // Unknown. Probe it.
                    stream_type = 0x00;
                }
                update_ps_streams( stream, pes_info.stream_id,
                                   pes_info.bd_substream_id, stream_type, -1 );
            }
            else if ( ( pes_info.stream_id & 0xf0 ) == 0xe0 )
            {
                // Normally this is MPEG video, but MPEG-1 PS streams
                // (which do not have a program stream map)  may use 
                // this for other types of video.
                //
                // Also, the hddvd tards decided to use 0xe2 and 0xe3 for
                // h.264 video :( and the twits decided not to put a
                // program stream map in the stream :'(
                //
                // So set this to an unknown stream type and probe.
                stream_type = 0x00;
                update_ps_streams( stream, pes_info.stream_id,
                                   pes_info.stream_id_ext, stream_type, -1 );
            }
            else if ( pes_info.stream_id == 0xfd )
            {
                if ( pes_info.stream_id_ext == 0x55 ||
                     pes_info.stream_id_ext == 0x56 )
                {
                    // hddvd uses this for vc-1.
                    stream_type = 0xea;
                }
                else
                {  
                    // mark as unknown and probe.
                    stream_type = 0x00;
                }
                update_ps_streams( stream, pes_info.stream_id,
                                   pes_info.stream_id_ext, stream_type, -1 );
            }
        }
        hb_stream_seek( stream, 0.2 );
    }
    hb_buffer_close( &buf );
}

static int probe_dts_profile( hb_pes_stream_t *pes )
{
    hb_work_info_t info;
    hb_work_object_t *w = hb_codec_decoder( pes->codec );

    w->codec_param = pes->codec_param;
    int ret = w->bsinfo( w, pes->probe_buf, &info );
    if ( ret < 0 )
    {
        hb_log( "probe_dts_profile: no info type %d/0x%x for id 0x%x",
                pes->codec, pes->codec_param, pes->stream_id );

    }
    switch (info.profile)
    {
        case FF_PROFILE_DTS:
        case FF_PROFILE_DTS_ES:
        case FF_PROFILE_DTS_96_24:
            pes->codec = HB_ACODEC_DCA;
            pes->stream_type = 0x82;
            pes->stream_kind = A;
            break;

        case FF_PROFILE_DTS_HD_HRA:
        case FF_PROFILE_DTS_HD_MA:
            pes->stream_type = 0;
            pes->stream_kind = A;
            break;

        default:
            return 0;
    }
    const char *profile_name;
    AVCodec *codec = avcodec_find_decoder( pes->codec_param );
    profile_name = av_get_profile_name( codec, info.profile );
    if ( profile_name )
    {
        strncpy(pes->codec_name, profile_name, 80);
        pes->codec_name[79] = 0;
    }
    return 1;
}

static int do_probe( hb_pes_stream_t *pes, hb_buffer_t *buf )
{
    // Check upper limit of per stream data to probe
    if ( pes->probe_buf == NULL )
    {
        pes->probe_buf = hb_buffer_init( 0 );
    }
    if ( pes->probe_buf->size > HB_MAX_PROBE_SIZE )
    {
        pes->stream_kind = N;
        hb_buffer_close( &pes->probe_buf );
        return 1;
    }

    // Add this stream buffer to probe buffer and perform probe
    AVInputFormat *fmt = NULL;
    int score = 0;
    AVProbeData pd = {0,};
    int size = pes->probe_buf->size + buf->size;

    hb_buffer_realloc(pes->probe_buf, size + AVPROBE_PADDING_SIZE );
    memcpy( pes->probe_buf->data + pes->probe_buf->size, buf->data, buf->size );
    pes->probe_buf->size = size;

    if ( pes->codec == HB_ACODEC_DCA_HD )
    {
        // We need to probe for the profile of DTS audio in this stream.
        return probe_dts_profile( pes );
    }

    // Probing is slow, so we don't want to re-probe the probe
    // buffer for every packet we add to it.  Grow the buffer
    // by a factor of 2 before probing again.
    if ( pes->probe_buf->size < pes->probe_next_size )
        return 0;

    pes->probe_next_size = pes->probe_buf->size * 2;
    pd.buf = pes->probe_buf->data;
    pd.buf_size = pes->probe_buf->size;
    fmt = av_probe_input_format2( &pd, 1, &score );
    if ( fmt && score > AVPROBE_SCORE_MAX / 2 )
    {
        AVCodec *codec = avcodec_find_decoder_by_name( fmt->name );
        if( !codec )
        {
            int i;
            static const struct
            {
                const char *name;
                enum AVCodecID id;
            }
            fmt_id_type[] =
            {
                { "g722"     , AV_CODEC_ID_ADPCM_G722 },
                { "mlp"      , AV_CODEC_ID_MLP        },
                { "truehd"   , AV_CODEC_ID_TRUEHD     },
                { "shn"      , AV_CODEC_ID_SHORTEN    },
                { "aac"      , AV_CODEC_ID_AAC        },
                { "ac3"      , AV_CODEC_ID_AC3        },
                { "dts"      , AV_CODEC_ID_DTS        },
                { "eac3"     , AV_CODEC_ID_EAC3       },
                { "h264"     , AV_CODEC_ID_H264       },
                { "m4v"      , AV_CODEC_ID_MPEG4      },
                { "mp3"      , AV_CODEC_ID_MP3        },
                { "mpegvideo", AV_CODEC_ID_MPEG2VIDEO },
                { "cavsvideo", AV_CODEC_ID_CAVS       },
                { "dnxhd"    , AV_CODEC_ID_DNXHD      },
                { "h261"     , AV_CODEC_ID_H261       },
                { "h263"     , AV_CODEC_ID_H263       },
                { "mjpeg"    , AV_CODEC_ID_MJPEG      },
                { "vc1"      , AV_CODEC_ID_VC1        },
                { 0 },
            };
            for( i = 0; fmt_id_type[i].name; i++ )
            {
                if( !strcmp(fmt->name, fmt_id_type[i].name ) )
                {
                    codec = avcodec_find_decoder( fmt_id_type[i].id );
                    break;
                }
            }
        }
        if( codec )
        {
            pes->codec_param = codec->id;
            if ( codec->type == AVMEDIA_TYPE_VIDEO )
            {
                pes->stream_kind = V;
                switch ( codec->id )
                {
                    case AV_CODEC_ID_MPEG1VIDEO:
                        pes->codec = WORK_DECAVCODECV;
                        pes->stream_type = 0x01;
                        break;

                    case AV_CODEC_ID_MPEG2VIDEO:
                        pes->codec = WORK_DECAVCODECV;
                        pes->stream_type = 0x02;
                        break;

                    case AV_CODEC_ID_H264:
                        pes->codec = WORK_DECAVCODECV;
                        pes->stream_type = 0x1b;
                        break;

                    case AV_CODEC_ID_VC1:
                        pes->codec = WORK_DECAVCODECV;
                        pes->stream_type = 0xea;
                        break;

                    default:
                        pes->codec = WORK_DECAVCODECV;
                }
            }
            else if ( codec->type == AVMEDIA_TYPE_AUDIO )
            {
                pes->stream_kind = A;
                switch ( codec->id )
                {
                    case AV_CODEC_ID_AC3:
                        pes->codec = HB_ACODEC_AC3;
                        break;
                    default:
                        pes->codec = HB_ACODEC_FFMPEG;
                }
            }
            else
            {
                pes->stream_kind = N;
            }
            strncpy(pes->codec_name, codec->name, 79);
            pes->codec_name[79] = 0;
        }
        else
        {
            pes->stream_kind = N;
        }
        hb_buffer_close( &pes->probe_buf );
        return 1;
    }
    return 0;
}

static void hb_ts_resolve_pid_types(hb_stream_t *stream)
{
    int ii, probe = 0;

    for ( ii = 0; ii < stream->ts.count; ii++ )
    {
        int pid = stream->ts.list[ii].pid;
        int stype = ts_stream_type( stream, ii );
        int pes_idx;

        if ( stype == 0x80 &&
             stream->reg_desc == STR4_TO_UINT32("HDMV") )
        {
            // LPCM audio in bluray have an stype of 0x80
            // 0x80 is used for other DigiCipher normally
            // To distinguish, Bluray streams have a reg_desc of HDMV
            update_ts_streams( stream, pid, 0, stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_FFMPEG;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_PCM_BLURAY;
            continue;
        }

        // The blu ray consortium apparently forgot to read the portion
        // of the MPEG spec that says one PID should map to one media
        // stream and multiplexed multiple types of audio into one PID
        // using the extended stream identifier of the PES header to
        // distinguish them. So we have to check if that's happening and
        // if so tell the runtime what esid we want.
        if ( stype == 0x83 &&
             stream->reg_desc == STR4_TO_UINT32("HDMV") )
        {
            // This is an interleaved TrueHD/AC-3 stream and the esid of
            // the AC-3 is 0x76
            update_ts_streams( stream, pid, HB_SUBSTREAM_BD_AC3,
                               stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_AC3;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_AC3;

            update_ts_streams( stream, pid, HB_SUBSTREAM_BD_TRUEHD,
                               stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_FFMPEG;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_TRUEHD;
            continue;
        }
        if ( ( stype == 0x84 || stype == 0xa1 ) &&
             stream->reg_desc == STR4_TO_UINT32("HDMV") )
        {
            // EAC3 audio in bluray has an stype of 0x84
            // which conflicts with SDDS
            // To distinguish, Bluray streams have a reg_desc of HDMV
            update_ts_streams( stream, pid, 0, stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_FFMPEG;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_EAC3;
            continue;
        }
        // 0xa2 is DTS-HD LBR used in HD-DVD and bluray for
        // secondary audio streams. Libav can not decode yet.
        // Having it in the audio list causes delays during scan
        // while we try to get stream parameters. So skip 
        // this type for now.
        if ( stype == 0x85 &&
             stream->reg_desc == STR4_TO_UINT32("HDMV") )
        {
            // DTS-HD HRA audio in bluray has an stype of 0x85
            // which conflicts with ATSC Program ID
            // To distinguish, Bluray streams have a reg_desc of HDMV
            // This is an interleaved DTS-HD HRA/DTS stream and the
            // esid of the DTS is 0x71
            update_ts_streams( stream, pid, HB_SUBSTREAM_BD_DTS,
                               stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_DCA;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_DTS;

            update_ts_streams( stream, pid, 0, stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_DCA_HD;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_DTS;
            continue;
        }
        if ( stype == 0x86 &&
             stream->reg_desc == STR4_TO_UINT32("HDMV") )
        {
            // This is an interleaved DTS-HD MA/DTS stream and the
            // esid of the DTS is 0x71
            update_ts_streams( stream, pid, HB_SUBSTREAM_BD_DTS,
                               stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_DCA;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_DTS;

            update_ts_streams( stream, pid, 0, stype, A, &pes_idx );
            stream->pes.list[pes_idx].codec = HB_ACODEC_DCA_HD;
            stream->pes.list[pes_idx].codec_param = AV_CODEC_ID_DTS;
            continue;
        }

        // stype == 0 indicates a type not in st2codec table
        if ( stype != 0 &&
             ( ts_stream_kind( stream, ii ) == A ||
               ts_stream_kind( stream, ii ) == S ||
               ts_stream_kind( stream, ii ) == V ) )
        {
            // Assuming there are no substreams.
            // This should be true before probing.
            // This function is only called before
            // probing.
            pes_idx = stream->ts.list[ii].pes_list;
            stream->pes.list[pes_idx].codec = st2codec[stype].codec;
            stream->pes.list[pes_idx].codec_param = st2codec[stype].codec_param;
            continue;
        }

        if ( ts_stream_kind( stream, ii ) == U )
        {
            probe++;
        }
    }

    // Probe remaining unknown streams for stream types
    hb_stream_seek( stream, 0.0 );
    stream->need_keyframe = 0;

    int total_size = 0;
    hb_buffer_t *buf;

    if ( probe )
        hb_log("Probing %d unknown stream%s", probe, probe > 1 ? "s" : "" );

    while ( probe && ( buf = hb_ts_stream_decode( stream ) ) != NULL )
    {
        // Check upper limit of total data to probe
        total_size += buf->size;

        if ( total_size > HB_MAX_PROBE_SIZE * 2 )
        {
            hb_buffer_close(&buf);
            break;
        }

        int idx;
        idx = index_of_id( stream, buf->s.id );

        if (idx < 0 || stream->pes.list[idx].stream_kind != U )
        {
            hb_buffer_close(&buf);
            continue;
        }

        hb_pes_stream_t *pes = &stream->pes.list[idx];

        if ( do_probe( pes, buf ) )
        {
            probe--;
            if ( pes->stream_kind != N )
            {
                hb_log("    Probe: Found stream %s. stream id 0x%x-0x%x",
                        pes->codec_name, pes->stream_id, pes->stream_id_ext);
            }
            else
            {
                hb_log("    Probe: Unsupported stream %s. stream id 0x%x-0x%x",
                        pes->codec_name, pes->stream_id, pes->stream_id_ext);
            }
        }
        hb_buffer_close(&buf);
    }
    // Clean up any probe buffers and set all remaining unknown
    // streams to 'kind' N
    for ( ii = 0; ii < stream->pes.count; ii++ )
    {
        if ( stream->pes.list[ii].stream_kind == U )
            stream->pes.list[ii].stream_kind = N;
        hb_buffer_close( &stream->pes.list[ii].probe_buf );
        stream->pes.list[ii].probe_next_size = 0;
    }
}

static void hb_ps_resolve_stream_types(hb_stream_t *stream)
{
    int ii, probe = 0;

    for ( ii = 0; ii < stream->pes.count; ii++ )
    {
        int stype = stream->pes.list[ii].stream_type;

        // stype == 0 indicates a type not in st2codec table
        if ( stype != 0 &&
             ( stream->pes.list[ii].stream_kind == A ||
               stream->pes.list[ii].stream_kind == S ||
               stream->pes.list[ii].stream_kind == V ) )
        {
            stream->pes.list[ii].codec = st2codec[stype].codec;
            stream->pes.list[ii].codec_param = st2codec[stype].codec_param;
            continue;
        }

        if ( stream->pes.list[ii].stream_kind == U )
        {
            probe++;
        }
    }

    // Probe remaining unknown streams for stream types
    hb_stream_seek( stream, 0.0 );
    stream->need_keyframe = 0;

    int total_size = 0;
    hb_buffer_t *buf;

    if ( probe )
        hb_log("Probing %d unknown stream%s", probe, probe > 1 ? "s" : "" );

    while ( probe && ( buf = hb_ps_stream_decode( stream ) ) != NULL )
    {
        // Check upper limit of total data to probe
        total_size += buf->size;

        if ( total_size > HB_MAX_PROBE_SIZE * 2 )
            break;

        int idx;
        idx = index_of_id( stream, buf->s.id );

        if (idx < 0 || stream->pes.list[idx].stream_kind != U )
            continue;

        hb_pes_stream_t *pes = &stream->pes.list[idx];

        if ( do_probe( pes, buf ) )
        {
            probe--;
            if ( pes->stream_kind != N )
            {
                hb_log("    Probe: Found stream %s. stream id 0x%x-0x%x",
                        pes->codec_name, pes->stream_id, pes->stream_id_ext);
            }
            else
            {
                hb_log("    Probe: Unsupported stream %s. stream id 0x%x-0x%x",
                        pes->codec_name, pes->stream_id, pes->stream_id_ext);
            }
        }
    }
    // Clean up any probe buffers and set all remaining unknown
    // streams to 'kind' N
    for ( ii = 0; ii < stream->pes.count; ii++ )
    {
        if ( stream->pes.list[ii].stream_kind == U )
            stream->pes.list[ii].stream_kind = N;
        hb_buffer_close( &stream->pes.list[ii].probe_buf );
        stream->pes.list[ii].probe_next_size = 0;
    }
}


static int hb_ts_stream_find_pids(hb_stream_t *stream)
{
    // To be different from every other broadcaster in the world, New Zealand TV
    // changes PMTs (and thus video & audio PIDs) when 'programs' change. Since
    // we may have the tail of the previous program at the beginning of this
    // file, take our PMT from the middle of the file.
    fseeko(stream->file_handle, 0, SEEK_END);
    uint64_t fsize = ftello(stream->file_handle);
    fseeko(stream->file_handle, fsize >> 1, SEEK_SET);
    align_to_next_packet(stream);

    // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
    // to find the program map PID and then decode that to get the list of audio and video PIDs

    for (;;)
    {
        const uint8_t *buf = next_packet( stream );

        if ( buf == NULL )
        {
            hb_log("hb_ts_stream_find_pids - end of file");
            break;
        }

        // Get pid
        int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;

        if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
        {
            decode_PAT(buf, stream);
            continue;
        }

        int pat_index = 0;
        for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
        {
            // There are some streams where the PAT table has multiple
            // entries as if their are multiple programs in the same
            // transport stream, and yet there's actually only one
            // program really in the stream. This seems to be true for
            // transport streams that originate in the HDHomeRun but have
            // been output by EyeTV's export utility. What I think is
            // happening is that the HDHomeRun is sending the entire
            // transport stream as broadcast, but the EyeTV is only
            // recording a single (selected) program number and not
            // rewriting the PAT info on export to match what's actually
            // on the stream. Until we have a way of handling multiple
            // programs per transport stream elegantly we'll match on the
            // first pat entry for which we find a matching program map PID.
            // The ideal solution would be to build a title choice popup
            // from the PAT program number details and then select from
            // their - but right now the API's not capable of that.
            if (stream->pat_info[pat_index].program_number != 0 &&
                pid == stream->pat_info[pat_index].program_map_PID)
            {
                if (build_program_map(buf, stream) > 0)
                {
                    break;
                }
            }
        }
        // Keep going  until we have a complete set of PIDs
        if ( ts_index_of_video( stream ) >= 0 )
          break;
    }
    if ( ts_index_of_video( stream ) < 0 )
        return -1;
    update_ts_streams( stream, stream->pmt_info.PCR_PID, 0, -1, P, NULL );
    return 0;
}


// convert a PES PTS or DTS to an int64
static int64_t pes_timestamp( const uint8_t *buf )
{
    int64_t ts;

    ts = ( (uint64_t)  ( buf[0] & 0x0e ) << 29 ) +
                       ( buf[1] <<  22 )         +
                     ( ( buf[2] >>   1 ) << 15 ) +
                       ( buf[3] <<   7 )         +
                       ( buf[4] >>   1 );
    return ts;
}

static hb_buffer_t * generate_output_data(hb_stream_t *stream, int curstream)
{
    hb_buffer_t *buf = NULL, *first = NULL;
    hb_pes_info_t pes_info;

    hb_buffer_t * b = stream->ts.list[curstream].buf;
    if ( !hb_parse_ps( stream, b->data, b->size, &pes_info ) )
    {
        b->size = 0;
        return NULL;
    }

    uint8_t *tdat = b->data + pes_info.header_len;
    int size = b->size - pes_info.header_len;

    if ( size <= 0 )
    {
        b->size = 0;
        return NULL;
    }

    int pes_idx;
    pes_idx = stream->ts.list[curstream].pes_list;
    if( stream->need_keyframe )
    {
        // we're looking for the first video frame because we're
        // doing random access during 'scan'
        int kind = stream->pes.list[pes_idx].stream_kind;
        if( kind != V || !isIframe( stream, tdat, size ) )
        {
            // not the video stream or didn't find an I frame
            // but we'll only wait 255 video frames for an I frame.
            if ( kind != V || ++stream->need_keyframe < 512 )
            {
                b->size = 0;
                return NULL;
            }
        }
        stream->need_keyframe = 0;
    }

    // Check all substreams to see if this packet matches
    for ( pes_idx = stream->ts.list[curstream].pes_list; pes_idx != -1;
          pes_idx = stream->pes.list[pes_idx].next )
    {
        if ( stream->pes.list[pes_idx].stream_id_ext != pes_info.stream_id_ext &&
             stream->pes.list[pes_idx].stream_id_ext != 0 )
        {
            continue;
        }
        // The substreams match.
        // Note that when stream->pes.list[pes_idx].stream_id_ext == 0,
        // we want the whole TS stream including all substreams.
        // DTS-HD is an example of this.

        if ( first == NULL )
            first = buf = hb_buffer_init( size );
        else
        {
            hb_buffer_t *tmp = hb_buffer_init( size );
            buf->next = tmp;
            buf = tmp;
        }

        buf->s.id = get_id( &stream->pes.list[pes_idx] );
        switch (stream->pes.list[pes_idx].stream_kind)
        {
            case A:
                buf->s.type = AUDIO_BUF;
                break;

            case V:
                buf->s.type = VIDEO_BUF;
                break;

            default:
                buf->s.type = OTHER_BUF;
                break;
        }

        if( b->sequence > stream->ts.pcr_out )
        {
            // we have a new pcr
            stream->ts.pcr_out = b->sequence;
            buf->s.pcr = b->s.pcr;
            if( b->sequence >= stream->ts.pcr_discontinuity )
                stream->ts.pcr_current = stream->ts.pcr_discontinuity;
        }
        else
        {
            buf->s.pcr = AV_NOPTS_VALUE;
        }

        // check if this packet was referenced to an older pcr and if that
        // pcr was prior to a discontinuity.
        if( b->sequence < stream->ts.pcr_current )
        {
            // we've sent up a new pcr but have a packet referenced to an
            // old pcr and the difference was enough to trigger a discontinuity
            // correction. smash the timestamps or we'll mess up the correction.
            buf->s.start = AV_NOPTS_VALUE;
            buf->s.renderOffset = AV_NOPTS_VALUE;
            buf->s.stop = AV_NOPTS_VALUE;
            buf->s.pcr = AV_NOPTS_VALUE;
        }
        else
        {
            // put the PTS & possible DTS into 'start' & 'renderOffset'
            // then strip off the PES header.
            buf->s.start = pes_info.pts;
            buf->s.renderOffset = pes_info.dts;
        }
        memcpy( buf->data, tdat, size );
    }

    b->size = 0;
    return first;
}

static void hb_ts_stream_append_pkt(hb_stream_t *stream, int idx, const uint8_t *buf, int len)
{
    if (stream->ts.list[idx].buf->size + len > stream->ts.list[idx].buf->alloc)
    {
        int size;

        size = MAX( stream->ts.list[idx].buf->alloc * 2,
                    stream->ts.list[idx].buf->size + len);
        hb_buffer_realloc(stream->ts.list[idx].buf, size);
    }
    memcpy( stream->ts.list[idx].buf->data + stream->ts.list[idx].buf->size,
            buf, len);
    stream->ts.list[idx].buf->size += len;
}

/***********************************************************************
 * hb_ts_stream_decode
 ***********************************************************************
 *
 **********************************************************************/
hb_buffer_t * hb_ts_decode_pkt( hb_stream_t *stream, const uint8_t * pkt )
{
    /*
     * stash the output buffer pointer in our stream so we don't have to
     * pass it & its original value to everything we call.
     */
    int video_index = ts_index_of_video(stream);
    int curstream;
    hb_buffer_t *buf;

    /* This next section validates the packet */

    // Get pid and use it to find stream state.
    int pid = ((pkt[1] & 0x1F) << 8) | pkt[2];
    if ( ( curstream = index_of_pid( stream, pid ) ) < 0 )
    {
        return NULL;
    }

    // Get error
    int errorbit = (pkt[1] & 0x80) != 0;
    if (errorbit)
    {
        ts_err( stream, curstream,  "packet error bit set");
        return NULL;
    }

    // Get adaption header info
    int adaption = (pkt[3] & 0x30) >> 4;
    int adapt_len = 0;
    if (adaption == 0)
    {
        ts_err( stream, curstream,  "adaptation code 0");
        return NULL;
    }
    else if (adaption == 0x2)
        adapt_len = 184;
    else if (adaption == 0x3)
    {
        adapt_len = pkt[4] + 1;
        if (adapt_len > 184)
        {
            ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
            return NULL;
        }
    }

    if ( adapt_len > 0 )
    {
        if ( pkt[5] & 0x40 )
        {
            // found a random access point
        }
        // if there's an adaptation header & PCR_flag is set
        // get the PCR (Program Clock Reference)
        //
        // JAS: I have a badly mastered BD that does adaptation field
        // stuffing incorrectly which results in invalid PCRs.  Test
        // for all 0xff to guard against this.
        if ( adapt_len > 7 && ( pkt[5] & 0x10 ) != 0 &&
            !(pkt[5] == 0xff && pkt[6] == 0xff && pkt[7] == 0xff &&
              pkt[8] == 0xff && pkt[9] == 0xff && pkt[10] == 0xff))
        {
            int64_t pcr;
            pcr =    ( (uint64_t)pkt[6] << (33 - 8) ) |
                     ( (uint64_t)pkt[7] << (33 - 16) ) |
                     ( (uint64_t)pkt[8] << (33 - 24) ) |
                     ( (uint64_t)pkt[9] << (33 - 32) ) |
                     ( pkt[10] >> 7 );
            ++stream->ts.pcr_in;
            stream->ts.found_pcr = 1;
            stream->ts_flags |= TS_HAS_PCR;
            // Check for a pcr discontinuity.
            // The reason for the uint cast on the pcr difference is that the
            // difference is significant if it advanced by more than 200ms or
            // if it went backwards by any amount. The negative numbers look
            // like huge unsigned ints so the cast allows both conditions to
            // be checked at once.
            if ( (uint64_t)( pcr - stream->ts.pcr ) > 200*90LL )
            {
                stream->ts.pcr_discontinuity = stream->ts.pcr_in;
            }
            stream->ts.pcr = pcr;
        }
    }

    // If we don't have a PCR yet but the stream has PCRs just loop
    // so we don't process anything until we have a clock reference.
    // Unfortunately the HD Home Run appears to null out the PCR so if
    // we didn't detect a PCR during scan keep going and we'll use
    // the video stream DTS for the PCR.
    if ( !stream->ts.found_pcr && ( stream->ts_flags & TS_HAS_PCR ) )
    {
        return NULL;
    }

    // Get continuity
    // Continuity only increments for adaption values of 0x3 or 0x01
    // and is not checked for start packets.

    int start = (pkt[1] & 0x40) != 0;

    if ( (adaption & 0x01) != 0 )
    {
        int continuity = (pkt[3] & 0xF);
        if ( continuity == stream->ts.list[curstream].continuity )
        {
            // Spliced transport streams can have duplicate
            // continuity counts at the splice boundary.
            // Test to see if the packet is really a duplicate
            // by comparing packet summaries to see if they
            // match.
            uint8_t summary[8];

            summary[0] = adaption;
            summary[1] = adapt_len;
            if (adapt_len + 4 + 6 + 9 <= 188)
            {
                memcpy(&summary[2], pkt+4+adapt_len+9, 6);
            }
            else
            {
                memset(&summary[2], 0, 6);
            }
            if ( memcmp( summary, stream->ts.list[curstream].pkt_summary, 8 ) == 0 )
            {
                // we got a duplicate packet (usually used to introduce
                // a PCR when one is needed). The only thing that can
                // change in the dup is the PCR which we grabbed above
                // so ignore the rest.
                return NULL;
            }
        }
        if ( !start && (stream->ts.list[curstream].continuity != -1) &&
             !stream->ts.list[curstream].skipbad &&
             (continuity != ( (stream->ts.list[curstream].continuity + 1) & 0xf ) ) )
        {
            ts_err( stream, curstream, "continuity error: got %d expected %d",
                    (int)continuity,
                    (stream->ts.list[curstream].continuity + 1) & 0xf );
            stream->ts.list[curstream].continuity = continuity;
            return NULL;
        }
        stream->ts.list[curstream].continuity = continuity;

        // Save a summary of this packet for later duplicate
        // testing.  The summary includes some header information
        // and payload bytes.  Should be enough to detect
        // non-duplicates.
        stream->ts.list[curstream].pkt_summary[0] = adaption;
        stream->ts.list[curstream].pkt_summary[1] = adapt_len;
        if (adapt_len + 4 + 6 + 9 <= 188)
        {
            memcpy(&stream->ts.list[curstream].pkt_summary[2],
                    pkt+4+adapt_len+9, 6);
        }
        else
        {
            memset(&stream->ts.list[curstream].pkt_summary[2], 0, 6);
        }
    }

    if ( ts_stream_kind( stream, curstream ) == P )
    {
        // This is a stream that only contains PCRs.  No need to process
        // the remainder of the packet.
        //
        // I ran across a poorly mastered BD that does not properly pad
        // the adaptation field and causes parsing errors below if we
        // do not exit early here.
        return NULL;
    }

    /* If we get here the packet is valid - process its data */


    if ( start )
    {
        // Found a random access point or we have finished generating a PES
        // and must start a new one.

        // PES must begin with an mpeg start code
        const uint8_t *pes = pkt + adapt_len + 4;
        if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 )
        {
            ts_err( stream, curstream, "missing start code" );
            stream->ts.list[curstream].skipbad = 1;
            return NULL;
        }

        // If we were skipping a bad packet, start fresh on this new PES packet
        if (stream->ts.list[curstream].skipbad == 1)
        {
            stream->ts.list[curstream].skipbad = 0;
        }

        if ( curstream == video_index )
        {
            ++stream->frames;

            // if we don't have a pcr yet use the dts from this frame
            // to attempt to detect discontinuities
            if ( !stream->ts.found_pcr )
            {
                // PES must begin with an mpeg start code & contain
                // a DTS or PTS.
                const uint8_t *pes = pkt + adapt_len + 4;
                if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
                     ( pes[7] >> 6 ) == 0 )
                {
                    return NULL;
                }
                // if we have a dts use it otherwise use the pts
                int64_t timestamp;
                timestamp = pes_timestamp( pes + ( pes[7] & 0x40?14:9 ) );
                if( stream->ts.last_timestamp < 0 ||
                    timestamp - stream->ts.last_timestamp > 90 * 600 ||
                    stream->ts.last_timestamp - timestamp > 90 * 600 )
                {
                    stream->ts.pcr = timestamp;
                    ++stream->ts.pcr_in;
                    stream->ts.pcr_discontinuity = stream->ts.pcr_in;
                }
                stream->ts.last_timestamp = timestamp;
            }
        }

        // If we have some data already on this stream, turn it into
        // a program stream packet. Then add the payload for this
        // packet to the current pid's buffer.
        if ( stream->ts.list[curstream].buf->size )
        {
            // we have to ship the old packet before updating the pcr
            // since the packet we've been accumulating is referenced
            // to the old pcr.
            buf = generate_output_data(stream, curstream);

            if ( buf )
            {
                // Output data is ready.
                // remember the pcr that was in effect when we started
                // this packet.
                stream->ts.list[curstream].buf->sequence = stream->ts.pcr_in;
                stream->ts.list[curstream].buf->s.pcr = stream->ts.pcr;
                hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
                                        184 - adapt_len);
                return buf;
            }
        }
        // remember the pcr that was in effect when we started this packet.
        stream->ts.list[curstream].buf->sequence = stream->ts.pcr_in;
        stream->ts.list[curstream].buf->s.pcr = stream->ts.pcr;
    }

    // Add the payload for this packet to the current buffer
    if (!stream->ts.list[curstream].skipbad && (184 - adapt_len) > 0)
    {
        hb_ts_stream_append_pkt(stream, curstream, pkt + 4 + adapt_len,
                                184 - adapt_len);
        // see if we've hit the end of this PES packet
        const uint8_t *pes = stream->ts.list[curstream].buf->data;
        int len = ( pes[4] << 8 ) + pes[5] + 6;
        if ( len > 6 && stream->ts.list[curstream].buf->size == len &&
             pes[0] == 0x00 && pes[1] == 0x00 && pes[2] == 0x01 )
        {
            buf = generate_output_data(stream, curstream);
            if ( buf )
                return buf;
        }
    }
    return NULL;
}

static hb_buffer_t * hb_ts_stream_decode( hb_stream_t *stream )
{
    hb_buffer_t * b;

    // spin until we get a packet of data from some stream or hit eof
    while ( 1 )
    {
        const uint8_t *buf = next_packet(stream);
        if ( buf == NULL )
        {
            // end of file - we didn't finish filling our ps write buffer
            // so just discard the remainder (the partial buffer is useless)
            hb_log("hb_ts_stream_decode - eof");
            return NULL;
        }

        b = hb_ts_decode_pkt( stream, buf );
        if ( b )
        {
            return b;
        }
    }
    return NULL;
}

void hb_ts_stream_reset(hb_stream_t *stream)
{
    int i;

    for (i=0; i < stream->ts.count; i++)
    {
        if ( stream->ts.list[i].buf )
            stream->ts.list[i].buf->size = 0;
        if ( stream->ts.list[i].extra_buf )
            stream->ts.list[i].extra_buf->size = 0;
        stream->ts.list[i].skipbad = 1;
        stream->ts.list[i].continuity = -1;
    }

    stream->need_keyframe = 1;

    stream->ts.found_pcr = 0;
    stream->ts.pcr_out = 0;
    stream->ts.pcr_in = 0;
    stream->ts.pcr = AV_NOPTS_VALUE;
    stream->ts.pcr_current = -1;
    stream->ts.last_timestamp = AV_NOPTS_VALUE;

    stream->frames = 0;
    stream->errors = 0;
    stream->last_error_frame = -10000;
    stream->last_error_count = 0;
}

void hb_ps_stream_reset(hb_stream_t *stream)
{
    stream->need_keyframe = 1;

    stream->pes.found_scr = 0;
    stream->pes.scr = AV_NOPTS_VALUE;

    stream->frames = 0;
    stream->errors = 0;
}

// ------------------------------------------------------------------
// Support for reading media files via the ffmpeg libraries.

static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title, int scan )
{
    AVFormatContext *info_ic = NULL;

    av_log_set_level( AV_LOG_ERROR );

    // FFMpeg has issues with seeking.  After av_find_stream_info, the
    // streams are left in an indeterminate position.  So a seek is
    // necessary to force things back to the beginning of the stream.
    // But then the seek fails for some stream types.  So the safest thing
    // to do seems to be to open 2 AVFormatContext.  One for probing info
    // and the other for reading.
    if ( avformat_open_input( &info_ic, stream->path, NULL, NULL ) < 0 )
    {
        return 0;
    }
    if ( avformat_find_stream_info( info_ic, NULL ) < 0 )
        goto fail;

    title->opaque_priv = (void*)info_ic;
    stream->ffmpeg_ic = info_ic;
    stream->hb_stream_type = ffmpeg;
    stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
    av_init_packet( stream->ffmpeg_pkt );
    stream->chapter_end = INT64_MAX;

    if ( !scan )
    {
        // we're opening for read. scan passed out codec params that
        // indexed its stream so we need to remap them so they point
        // to this stream.
        stream->ffmpeg_video_id = title->video_id;
        av_log_set_level( AV_LOG_ERROR );
    }
    else
    {
        // we're opening for scan. let ffmpeg put some info into the
        // log about what we've got.
        stream->ffmpeg_video_id = title->video_id;
        av_log_set_level( AV_LOG_INFO );
        av_dump_format( info_ic, 0, stream->path, 0 );
        av_log_set_level( AV_LOG_ERROR );

        // accept this file if it has at least one video stream we can decode
        int i;
        for (i = 0; i < info_ic->nb_streams; ++i )
        {
            if ( info_ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO )
            {
                break;
            }
        }
        if ( i >= info_ic->nb_streams )
            goto fail;
    }
    return 1;

  fail:
    if ( info_ic ) avformat_close_input( &info_ic );
    return 0;
}

static void ffmpeg_close( hb_stream_t *d )
{
    avformat_close_input( &d->ffmpeg_ic );
    if ( d->ffmpeg_pkt != NULL )
    {
        free( d->ffmpeg_pkt );
        d->ffmpeg_pkt = NULL;
    }
}

static void add_ffmpeg_audio(hb_title_t *title, hb_stream_t *stream, int id)
{
    AVStream *st           = stream->ffmpeg_ic->streams[id];
    AVCodecContext *codec  = st->codec;
    AVDictionaryEntry *tag = av_dict_get(st->metadata, "language", NULL, 0);

    hb_audio_t *audio            = calloc(1, sizeof(*audio));
    audio->id                    = id;
    audio->config.in.track       = id;
    audio->config.in.codec       = HB_ACODEC_FFMPEG;
    audio->config.in.codec_param = codec->codec_id;
    // set the bitrate to 0; decavcodecaBSInfo will be called and fill the rest
    audio->config.in.bitrate     = 0;

    // set the input codec and extradata for Passthru
    switch (codec->codec_id)
    {
        case AV_CODEC_ID_AAC:
        {
            int len = MIN(codec->extradata_size, HB_CONFIG_MAX_SIZE);
            memcpy(audio->priv.config.extradata.bytes, codec->extradata, len);
            audio->priv.config.extradata.length = len;
            audio->config.in.codec              = HB_ACODEC_FFAAC;
        } break;

        case AV_CODEC_ID_AC3:
            audio->config.in.codec       = HB_ACODEC_AC3;
            break;

        case AV_CODEC_ID_DTS:
        {
            switch (codec->profile)
            {
                case FF_PROFILE_DTS:
                case FF_PROFILE_DTS_ES:
                case FF_PROFILE_DTS_96_24:
                    audio->config.in.codec = HB_ACODEC_DCA;
                    break;

                case FF_PROFILE_DTS_HD_MA:
                case FF_PROFILE_DTS_HD_HRA:
                    audio->config.in.codec = HB_ACODEC_DCA_HD;
                    break;

                default:
                    break;
            }
        } break;

        case AV_CODEC_ID_MP3:
            audio->config.in.codec = HB_ACODEC_MP3;
            break;

        default:
            break;
    }

    set_audio_description(audio,
                          lang_for_code2(tag != NULL ? tag->value : "und"));
    hb_list_add(title->list_audio, audio);
}

/*
 * Format:
 *   MkvVobSubtitlePrivateData = ( Line )*
 *   Line = FieldName ':' ' ' FieldValue '\n'
 *   FieldName = [^:]+
 *   FieldValue = [^\n]+
 *
 * The line of interest is:
 *   PaletteLine = "palette" ':' ' ' RRGGBB ( ',' ' ' RRGGBB )*
 *
 * More information on the format at:
 *   http://www.matroska.org/technical/specs/subtitles/images.html
 */
static int ffmpeg_parse_vobsub_extradata_mkv( AVCodecContext *codec, hb_subtitle_t *subtitle )
{
    // lines = (string) codec->extradata;
    char *lines = malloc( codec->extradata_size + 1 );
    if ( lines == NULL )
        return 1;
    memcpy( lines, codec->extradata, codec->extradata_size );
    lines[codec->extradata_size] = '\0';

    uint32_t rgb[16];
    int gotPalette = 0;
    int gotDimensions = 0;

    char *curLine, *curLine_parserData;
    for ( curLine = strtok_r( lines, "\n", &curLine_parserData );
          curLine;
          curLine = strtok_r( NULL, "\n", &curLine_parserData ) )
    {
        if (!gotPalette)
        {
            int numElementsRead = sscanf(curLine, "palette: "
                "%06x, %06x, %06x, %06x, "
                "%06x, %06x, %06x, %06x, "
                "%06x, %06x, %06x, %06x, "
                "%06x, %06x, %06x, %06x",
                &rgb[0],  &rgb[1],  &rgb[2],  &rgb[3],
                &rgb[4],  &rgb[5],  &rgb[6],  &rgb[7],
                &rgb[8],  &rgb[9],  &rgb[10], &rgb[11],
                &rgb[12], &rgb[13], &rgb[14], &rgb[15]);

            if (numElementsRead == 16) {
                gotPalette = 1;
            }
        }
        if (!gotDimensions)
        {
            int numElementsRead = sscanf(curLine, "size: %dx%d",
                &subtitle->width, &subtitle->height);

            if (numElementsRead == 2) {
                gotDimensions = 1;
            }
        }
        if (gotPalette && gotDimensions)
            break;
    }

    if (subtitle->width == 0 || subtitle->height == 0)
    {
        subtitle->width = 720;
        subtitle->height = 480;
    }

    free( lines );

    if ( gotPalette )
    {
        int i;
        for (i=0; i<16; i++)
            subtitle->palette[i] = hb_rgb2yuv(rgb[i]);
        subtitle->palette_set = 1;
        return 0;
    }
    else
    {
        return 1;
    }
}

/*
 * Format: 8-bit {0,Y,Cb,Cr} x 16
 */
static int ffmpeg_parse_vobsub_extradata_mp4( AVCodecContext *codec, hb_subtitle_t *subtitle )
{
    if ( codec->extradata_size != 4*16 )
        return 1;

    int i, j;
    for ( i=0, j=0; i<16; i++, j+=4 )
    {
        subtitle->palette[i] =
            codec->extradata[j+1] << 16 |   // Y
            codec->extradata[j+2] << 8  |   // Cb
            codec->extradata[j+3] << 0;     // Cr
        subtitle->palette_set = 1;
    }
    if (codec->width <= 0 || codec->height <= 0)
    {
        subtitle->width = 720;
        subtitle->height = 480;
    }
    else
    {
        subtitle->width = codec->width;
        subtitle->height = codec->height;
    }
    return 0;
}

/*
 * Parses the 'subtitle->palette' information from the specific VOB subtitle track's private data.
 * Returns 0 if successful or 1 if parsing failed or was incomplete.
 */
static int ffmpeg_parse_vobsub_extradata( AVCodecContext *codec, hb_subtitle_t *subtitle )
{
    // XXX: Better if we actually chose the correct parser based on the input container
    return
        ffmpeg_parse_vobsub_extradata_mkv( codec, subtitle ) &&
        ffmpeg_parse_vobsub_extradata_mp4( codec, subtitle );
}

static void add_ffmpeg_subtitle( hb_title_t *title, hb_stream_t *stream, int id )
{
    AVStream *st = stream->ffmpeg_ic->streams[id];
    AVCodecContext *codec = st->codec;

    hb_subtitle_t *subtitle = calloc( 1, sizeof(*subtitle) );

    subtitle->id = id;

    switch ( codec->codec_id )
    {
        case AV_CODEC_ID_DVD_SUBTITLE:
            subtitle->format = PICTURESUB;
            subtitle->source = VOBSUB;
            subtitle->config.dest = RENDERSUB;  // By default render (burn-in) the VOBSUB.
            subtitle->codec = WORK_DECVOBSUB;
            if ( ffmpeg_parse_vobsub_extradata( codec, subtitle ) )
                hb_log( "add_ffmpeg_subtitle: malformed extradata for VOB subtitle track; "
                        "subtitle colors likely to be wrong" );
            break;
        case AV_CODEC_ID_TEXT:
            subtitle->format = TEXTSUB;
            subtitle->source = UTF8SUB;
            subtitle->config.dest = PASSTHRUSUB;
            subtitle->codec = WORK_DECUTF8SUB;
            break;
        case AV_CODEC_ID_MOV_TEXT: // TX3G
            subtitle->format = TEXTSUB;
            subtitle->source = TX3GSUB;
            subtitle->config.dest = PASSTHRUSUB;
            subtitle->codec = WORK_DECTX3GSUB;
            break;
        case AV_CODEC_ID_SSA:
            subtitle->format = TEXTSUB;
            subtitle->source = SSASUB;
            subtitle->config.dest = PASSTHRUSUB;
            subtitle->codec = WORK_DECSSASUB;
            break;
        case AV_CODEC_ID_HDMV_PGS_SUBTITLE:
            subtitle->format = PICTURESUB;
            subtitle->source = PGSSUB;
            subtitle->config.dest = RENDERSUB;
            subtitle->codec = WORK_DECPGSSUB;
            break;
        default:
            hb_log( "add_ffmpeg_subtitle: unknown subtitle stream type: 0x%x", (int) codec->codec_id );
            free(subtitle);
            return;
    }

    AVDictionaryEntry *tag;
    iso639_lang_t *language;

    tag = av_dict_get( st->metadata, "language", NULL, 0 );
    language = lang_for_code2( tag ? tag->value : "und" );
    strcpy( subtitle->lang, language->eng_name );
    strncpy( subtitle->iso639_2, language->iso639_2, 4 );

    // Copy the extradata for the subtitle track
    subtitle->extradata = malloc( codec->extradata_size );
    memcpy( subtitle->extradata, codec->extradata, codec->extradata_size );
    subtitle->extradata_size = codec->extradata_size;

    subtitle->track = id;
    hb_list_add(title->list_subtitle, subtitle);
}

static char *get_ffmpeg_metadata_value( AVDictionary *m, char *key )
{
    AVDictionaryEntry *tag = NULL;

    while ( (tag = av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX)) )
    {
        if ( !strcmp( key, tag->key ) )
        {
            return tag->value;
        }
    }
    return NULL;
}

static void add_ffmpeg_attachment( hb_title_t *title, hb_stream_t *stream, int id )
{
    AVStream *st = stream->ffmpeg_ic->streams[id];
    AVCodecContext *codec = st->codec;

    enum attachtype type;
    const char *name = get_ffmpeg_metadata_value( st->metadata, "filename" );
    switch ( codec->codec_id )
    {
        case AV_CODEC_ID_TTF:
            // Libav sets codec ID based on mime type of the attachment
            type = FONT_TTF_ATTACH;
            break;
        default:
        {
            int len = name ? strlen( name ) : 0;
            if( len >= 4 &&
                ( !strcmp( name + len - 4, ".ttc" ) ||
                  !strcmp( name + len - 4, ".TTC" ) ||
                  !strcmp( name + len - 4, ".ttf" ) ||
                  !strcmp( name + len - 4, ".TTF" ) ) )
            {
                // Some attachments don't have the right mime type.
                // So also trigger on file name extension.
                type = FONT_TTF_ATTACH;
                break;
            }
            // Ignore unrecognized attachment type
            return;
        }
    }

    hb_attachment_t *attachment = calloc( 1, sizeof(*attachment) );

    // Copy the attachment name and data
    attachment->type = type;
    attachment->name = strdup( name );
    attachment->data = malloc( codec->extradata_size );
    memcpy( attachment->data, codec->extradata, codec->extradata_size );
    attachment->size = codec->extradata_size;

    hb_list_add(title->list_attachment, attachment);
}

static int ffmpeg_decmetadata( AVDictionary *m, hb_title_t *title )
{
    int result = 0;
    AVDictionaryEntry *tag = NULL;
    while ( (tag = av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX)) )
    {
        if ( !strcasecmp( "TITLE", tag->key ) )
        {
            hb_metadata_set_name(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "ARTIST", tag->key ) )
        {
            hb_metadata_set_artist(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "DIRECTOR", tag->key ) ||
                  !strcasecmp( "album_artist", tag->key ) )
        {
            hb_metadata_set_album_artist(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "COMPOSER", tag->key ) )
        {
            hb_metadata_set_composer(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "DATE_RELEASED", tag->key ) ||
                  !strcasecmp( "date", tag->key ) )
        {
            hb_metadata_set_release_date(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "SUMMARY", tag->key ) ||
                  !strcasecmp( "comment", tag->key ) )
        {
            hb_metadata_set_comment(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "GENRE", tag->key ) )
        {
            hb_metadata_set_genre(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "DESCRIPTION", tag->key ) )
        {
            hb_metadata_set_description(title->metadata, tag->value);
            result = 1;
        }
        else if ( !strcasecmp( "SYNOPSIS", tag->key ) )
        {
            hb_metadata_set_long_description(title->metadata, tag->value);
            result = 1;
        }
    }
    return result;
}

static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream, hb_title_t *title )
{
    AVFormatContext *ic = stream->ffmpeg_ic;

    // 'Barebones Title'
    title->type = HB_FF_STREAM_TYPE;
    title->index = 1;

    // Copy part of the stream path to the title name
    char *sep = hb_strr_dir_sep(stream->path);
    if (sep)
        strcpy(title->name, sep+1);
    char *dot_term = strrchr(title->name, '.');
    if (dot_term)
        *dot_term = '\0';

    uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
    title->duration = dur;
    dur /= 90000;
    title->hours    = dur / 3600;
    title->minutes  = ( dur % 3600 ) / 60;
    title->seconds  = dur % 60;

    // set the title to decode the first video stream in the file
    title->demuxer = HB_NULL_DEMUXER;
    title->video_codec = 0;
    int i;
    int pix_fmt = -1;
    for (i = 0; i < ic->nb_streams; ++i )
    {
        if ( ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
           !(ic->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC) &&
             avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
             title->video_codec == 0 )
        {
            AVCodecContext *context = ic->streams[i]->codec;
            pix_fmt = context->pix_fmt;
            if ( context->pix_fmt != AV_PIX_FMT_YUV420P &&
                 !sws_isSupportedInput( context->pix_fmt ) )
            {
                hb_log( "ffmpeg_title_scan: Unsupported color space" );
                continue;
            }
            title->video_id = i;
            stream->ffmpeg_video_id = i;
            if ( ic->streams[i]->sample_aspect_ratio.num &&
                 ic->streams[i]->sample_aspect_ratio.den )
            {
                title->pixel_aspect_width = ic->streams[i]->sample_aspect_ratio.num;
                title->pixel_aspect_height = ic->streams[i]->sample_aspect_ratio.den;
            }

            if ( context->codec_id == AV_CODEC_ID_H264 )
                title->flags |= HBTF_NO_IDR;

            title->video_codec = WORK_DECAVCODECV;
            title->video_codec_param = context->codec_id;
        }
        else if ( ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
                  avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
        {
            add_ffmpeg_audio( title, stream, i );
        }
        else if ( ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE )
        {
            add_ffmpeg_subtitle( title, stream, i );
        }
        else if ( ic->streams[i]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT )
        {
            add_ffmpeg_attachment( title, stream, i );
        }
    }

    title->container_name = strdup( ic->iformat->name );
    title->data_rate = ic->bit_rate;

    hb_deep_log( 2, "Found ffmpeg %d chapters, container=%s", ic->nb_chapters, ic->iformat->name );

    if( ic->nb_chapters != 0 )
    {
        AVChapter *m;
        uint64_t duration_sum = 0;
        for( i = 0; i < ic->nb_chapters; i++ )
            if( ( m = ic->chapters[i] ) != NULL )
            {
                AVDictionaryEntry *tag;
                hb_chapter_t * chapter;
                chapter = calloc( sizeof( hb_chapter_t ), 1 );
                chapter->index    = i+1;
                chapter->duration = ( m->end / ( (double) m->time_base.num * m->time_base.den ) ) * 90000  - duration_sum;
                duration_sum     += chapter->duration;

                int seconds      = ( chapter->duration + 45000 ) / 90000;
                chapter->hours   = ( seconds / 3600 );
                chapter->minutes = ( seconds % 3600 ) / 60;
                chapter->seconds = ( seconds % 60 );

                tag = av_dict_get( m->metadata, "title", NULL, 0 );
                /* Ignore generic chapter names set by MakeMKV
                 * ("Chapter 00" etc.).
                 * Our default chapter names are better. */
                if( tag && tag->value &&
                    ( strncmp( "Chapter ", tag->value, 8 ) ||
                      strlen( tag->value ) > 11 ) )
                {
                    hb_chapter_set_title( chapter, tag->value );
                }
                else
                {
                    char chapter_title[80];
                    sprintf( chapter_title, "Chapter %d", chapter->index );
                    hb_chapter_set_title( chapter, chapter_title );
                }

                hb_deep_log( 2, "Added chapter %i, name='%s', dur=%"PRIu64", (%02i:%02i:%02i)",
                             chapter->index, chapter->title, chapter->duration,
                             chapter->hours, chapter->minutes, chapter->seconds );

                hb_list_add( title->list_chapter, chapter );
            }
    }

    /*
     * Fill the metadata.
     */
    // JJJ: is this necessary? can we just get this metadata from libav api's?
    if (!decmetadata( title ))
    {
        ffmpeg_decmetadata( ic->metadata, title );
    }

    if( hb_list_count( title->list_chapter ) == 0 )
    {
        // Need at least one chapter
        hb_chapter_t * chapter;
        chapter = calloc( sizeof( hb_chapter_t ), 1 );
        chapter->index = 1;
        chapter->duration = title->duration;
        chapter->hours = title->hours;
        chapter->minutes = title->minutes;
        chapter->seconds = title->seconds;
        hb_list_add( title->list_chapter, chapter );
    }
#ifdef USE_HWD
    hb_va_dxva2_t * dxva2 = NULL;
    dxva2 = hb_va_create_dxva2( dxva2, title->video_codec_param );
    if (dxva2)
    {
        title->hwd_support = 1;
        hb_va_close(dxva2);
        dxva2 = NULL;
    }
    else
        title->hwd_support = 0;
   if ( hb_check_hwd_fmt(pix_fmt) == 0)
       title->hwd_support = 0;
#else
    // Eliminate compiler warning "pix_fmt set but not used"
    (void)pix_fmt;
    title->hwd_support = 0;
#endif

    return title;
}

static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
{
    if ( pts == AV_NOPTS_VALUE )
        return AV_NOPTS_VALUE;
    return (int64_t)( (double)pts * conv_factor );
}

static int ffmpeg_is_keyframe( hb_stream_t *stream )
{
    uint8_t *pkt;

    switch ( stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->codec_id )
    {
        case AV_CODEC_ID_VC1:
            // XXX the VC1 codec doesn't mark key frames so to get previews
            // we do it ourselves here. The decoder gets messed up if it
            // doesn't get a SEQ header first so we consider that to be a key frame.
            pkt = stream->ffmpeg_pkt->data;
            if ( !pkt[0] && !pkt[1] && pkt[2] == 1 && pkt[3] == 0x0f )
                return 1;

            return 0;

        case AV_CODEC_ID_WMV3:
            // XXX the ffmpeg WMV3 codec doesn't mark key frames.
            // Only M$ could make I-frame detection this complicated: there
            // are two to four bits of unused junk ahead of the frame type
            // so we have to look at the sequence header to find out how much
            // to skip. Then there are three different ways of coding the type
            // depending on whether it's main or advanced profile then whether
            // there are bframes or not so we have to look at the sequence
            // header to get that.
            pkt = stream->ffmpeg_pkt->data;
            uint8_t *seqhdr = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id]->codec->extradata;
            int pshift = 2;
            if ( ( seqhdr[3] & 0x02 ) == 0 )
                // no FINTERPFLAG
                ++pshift;
            if ( ( seqhdr[3] & 0x80 ) == 0 )
                // no RANGEREDUCTION
                ++pshift;
            if ( seqhdr[3] & 0x70 )
                // stream has b-frames
                return ( ( pkt[0] >> pshift ) & 0x3 ) == 0x01;

            return ( ( pkt[0] >> pshift ) & 0x2 ) == 0;

        default:
            break;
    }
    return ( stream->ffmpeg_pkt->flags & AV_PKT_FLAG_KEY );
}

hb_buffer_t * hb_ffmpeg_read( hb_stream_t *stream )
{
    int err;
    hb_buffer_t * buf;

  again:
    if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
    {
        // av_read_frame can return EAGAIN.  In this case, it expects
        // to be called again to get more data.
        if ( err == AVERROR(EAGAIN) )
        {
            goto again;
        }
        // XXX the following conditional is to handle avi files that
        // use M$ 'packed b-frames' and occasionally have negative
        // sizes for the null frames these require.
        if ( err != AVERROR(ENOMEM) || stream->ffmpeg_pkt->size >= 0 )
            // eof
            return NULL;
    }
    if ( stream->ffmpeg_pkt->stream_index == stream->ffmpeg_video_id )
    {
        if ( stream->need_keyframe )
        {
            // we've just done a seek (generally for scan or live preview) and
            // want to start at a keyframe. Some ffmpeg codecs seek to a key
            // frame but most don't. So we spin until we either get a keyframe
            // or we've looked through 50 video frames without finding one.
            if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
            {
                av_free_packet( stream->ffmpeg_pkt );
                goto again;
            }
            stream->need_keyframe = 0;
        }
        ++stream->frames;
    }
    if ( stream->ffmpeg_pkt->size <= 0 )
    {
        // M$ "invalid and inefficient" packed b-frames require 'null frames'
        // following them to preserve the timing (since the packing puts two
        // or more frames in what looks like one avi frame). The contents and
        // size of these null frames are ignored by the ff_h263_decode_frame
        // as long as they're < 20 bytes. We need a positive size so we use
        // one byte if we're given a zero or negative size. We don't know
        // if the pkt data points anywhere reasonable so we just stick a
        // byte of zero in our outbound buf.
        buf = hb_buffer_init( 1 );
        *buf->data = 0;
    }
    else
    {
        // sometimes we get absurd sizes from ffmpeg
        if ( stream->ffmpeg_pkt->size >= (1 << 25) )
        {
            hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
            av_free_packet( stream->ffmpeg_pkt );
            return hb_ffmpeg_read( stream );
        }
        buf = hb_buffer_init( stream->ffmpeg_pkt->size );
        memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
    }
    buf->s.id = stream->ffmpeg_pkt->stream_index;

    // compute a conversion factor to go from the ffmpeg
    // timebase for the stream to HB's 90kHz timebase.
    AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
    double tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;

    buf->s.start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
    buf->s.renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
    if ( buf->s.renderOffset >= 0 && buf->s.start == AV_NOPTS_VALUE )
    {
        buf->s.start = buf->s.renderOffset;
    }
    else if ( buf->s.renderOffset == AV_NOPTS_VALUE && buf->s.start >= 0 )
    {
        buf->s.renderOffset = buf->s.start;
    }

    /*
     * Fill out buf->s.stop for subtitle packets
     *
     * libavcodec's MKV demuxer stores the duration of UTF-8 subtitles (AV_CODEC_ID_TEXT)
     * in the 'convergence_duration' field for some reason.
     *
     * Other subtitles' durations are stored in the 'duration' field.
     *
     * VOB subtitles (AV_CODEC_ID_DVD_SUBTITLE) do not have their duration stored in
     * either field. This is not a problem because the VOB decoder can extract this
     * information from the packet payload itself.
     *
     * SSA subtitles (AV_CODEC_ID_SSA) do not have their duration stored in
     * either field. This is not a problem because the SSA decoder can extract this
     * information from the packet payload itself.
     */
    enum AVCodecID ffmpeg_pkt_codec;
    enum AVMediaType codec_type;
    ffmpeg_pkt_codec = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_id;
    codec_type = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index]->codec->codec_type;
    switch ( codec_type )
    {
        case AVMEDIA_TYPE_VIDEO:
            buf->s.type = VIDEO_BUF;
            /*
             * libav avcodec_decode_video2() needs AVPacket flagged with AV_PKT_FLAG_KEY
             * for some codecs. For example, sequence of PNG in a mov container.
             */
            if ( stream->ffmpeg_pkt->flags & AV_PKT_FLAG_KEY )
            {
                buf->s.frametype |= HB_FRAME_KEY;
            }
            break;

        case AVMEDIA_TYPE_AUDIO:
            buf->s.type = AUDIO_BUF;
            break;

        case AVMEDIA_TYPE_SUBTITLE:
            buf->s.type = SUBTITLE_BUF;
            break;

        default:
            buf->s.type = OTHER_BUF;
            break;
    }
    if ( ffmpeg_pkt_codec == AV_CODEC_ID_TEXT ) {
        int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->convergence_duration;
        int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
        buf->s.stop = buf->s.start + buf_duration;
    }
    if ( ffmpeg_pkt_codec == AV_CODEC_ID_MOV_TEXT ) {
        int64_t ffmpeg_pkt_duration = stream->ffmpeg_pkt->duration;
        int64_t buf_duration = av_to_hb_pts( ffmpeg_pkt_duration, tsconv );
        buf->s.stop = buf->s.start + buf_duration;
    }

    /*
     * Check to see whether this buffer is on a chapter
     * boundary, if so mark it as such in the buffer then advance
     * chapter_end to the end of the next chapter.
     * If there are no chapters, chapter_end is always initialized to INT64_MAX
     * (roughly 3 million years at our 90KHz clock rate) so the test
     * below handles both the chapters & no chapters case.
     */
    if ( stream->ffmpeg_pkt->stream_index == stream->ffmpeg_video_id &&
         buf->s.start >= stream->chapter_end )
    {
        hb_chapter_t *chapter = hb_list_item( stream->title->list_chapter,
                                              stream->chapter+1 );
        if( chapter )
        {
            stream->chapter++;
            stream->chapter_end += chapter->duration;
            buf->s.new_chap = stream->chapter + 1;
            hb_deep_log( 2, "ffmpeg_read starting chapter %i at %"PRId64,
                         stream->chapter + 1, buf->s.start);
        } else {
            // Must have run out of chapters, stop looking.
            stream->chapter_end = INT64_MAX;
            buf->s.new_chap = 0;
        }
    } else {
        buf->s.new_chap = 0;
    }
    av_free_packet( stream->ffmpeg_pkt );
    return buf;
}

static int ffmpeg_seek( hb_stream_t *stream, float frac )
{
    AVFormatContext *ic = stream->ffmpeg_ic;
    int res;
    if ( frac > 0. )
    {
        int64_t pos = (double)stream->ffmpeg_ic->duration * (double)frac +
                ffmpeg_initial_timestamp( stream );
        res = avformat_seek_file( ic, -1, 0, pos, pos, AVSEEK_FLAG_BACKWARD);
        if (res < 0)
        {
            hb_error("avformat_seek_file failed");
        }
    }
    else
    {
        int64_t pos = ffmpeg_initial_timestamp( stream );
        res = avformat_seek_file( ic, -1, 0, pos, pos, AVSEEK_FLAG_BACKWARD);
        if (res < 0)
        {
            hb_error("avformat_seek_file failed");
        }
    }
    stream->need_keyframe = 1;
    return 1;
}

// Assumes that we are always seeking forward
static int ffmpeg_seek_ts( hb_stream_t *stream, int64_t ts )
{
    AVFormatContext *ic = stream->ffmpeg_ic;
    int64_t pos;
    int ret;

    pos = ts * AV_TIME_BASE / 90000 + ffmpeg_initial_timestamp( stream );
    AVStream *st = stream->ffmpeg_ic->streams[stream->ffmpeg_video_id];
    // timebase must be adjusted to match timebase of stream we are
    // using for seeking.
    pos = av_rescale(pos, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
    stream->need_keyframe = 1;
    // Seek to the nearest timestamp before that requested where
    // there is an I-frame
    ret = avformat_seek_file( ic, stream->ffmpeg_video_id, 0, pos, pos, 0);
    return ret;
}