File: pes.c

package info (click to toggle)
tstools 1.13~git20151030-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,916 kB
  • sloc: ansic: 37,970; java: 2,243; makefile: 466; python: 319; sh: 5
file content (3846 lines) | stat: -rw-r--r-- 114,946 bytes parent folder | download | duplicates (2)
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
/*
 * PES reading facilities
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the MPEG TS, PS and ES tools.
 *
 * The Initial Developer of the Original Code is Amino Communications Ltd.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Amino Communications Ltd, Swavesey, Cambridge UK
 *
 * ***** END LICENSE BLOCK *****
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include "compat.h"
#include "ts_fns.h"
#include "ps_fns.h"
#include "es_fns.h"
#include "pes_fns.h"
#include "pidint_fns.h"
#include "h262_fns.h"
#include "tswrite_fns.h"
#include "printing_fns.h"
#include "misc_fns.h"


//#define DEBUG
#define DEBUG_READ_PACKETS 0
#define DEBUG_PES_ASSEMBLY 0
#define DEBUG_PROGRAM_INFO 1
#define SHOW_PROGRAM_INFO 0

#define ALLOW_OVERLONG_PACKETS 1

// PES packet stream ids
// See H.222.0 Table 2-17 and Table 2-18
// These are specifically the stream ids used to decide if a PES packet
// contains header data, filler bytes or what
#define STREAM_ID_PROGRAM_STREAM_MAP  0xbc
#define STREAM_ID_PRIVATE_STREAM_1    0xbd
#define STREAM_ID_PADDING_STREAM      0xbe
#define STREAM_ID_PRIVATE_STREAM_2    0xbf
#define STREAM_ID_ECM_STREAM          0xf0
#define STREAM_ID_EMM_STREAM          0xf1
#define STREAM_ID_DSMCC_STREAM        0xf2
#define STREAM_ID_13522_STREAM        0xf3
#define STREAM_ID_H222_A_STREAM       0xf4
#define STREAM_ID_H222_B_STREAM       0xf5
#define STREAM_ID_H222_C_STREAM       0xf6
#define STREAM_ID_H222_D_STREAM       0xf7
#define STREAM_ID_H222_E_STREAM       0xf8
#define STREAM_ID_ANCILLARY_STREAM    0xf9
#define STREAM_ID_PROGRAM_STREAM_DIRECTORY  0xff

// ============================================================
// PES packet data
// ============================================================
/*
 * Build a new PES packet datastructure
 *
 * Returns 0 if all goes well, 1 if something goes wrong
 */
static int build_PES_packet_data(PES_packet_data_p *data)
{
  PES_packet_data_p new = malloc(SIZEOF_PES_PACKET_DATA);
  if (new == NULL)
  {
    print_err("### Unable to allocate PES packet datastructure\n");
    return 1;
  }

  new->data = NULL;
  new->data_len = 0;
  new->es_data_len = 0;
  new->length = 0;
  new->posn = 0;
  new->is_video = TRUE;     // a guess
  new->data_alignment_indicator = FALSE; // another
  new->has_PTS = FALSE;     // assumed until told otherwise

  *data = new;
  return 0;
}

/*
 * Add some data to a PES packet datastructure
 *
 * - `data` is the PES packet datastructure concerned
 * - `bytes` is the data to add
 * - `bytes_len` is how much data there is
 *
 * Returns 0 if all goes well, 1 if something goes wrong
 */
static inline int extend_PES_packet_data(PES_packet_data_p data,
                                         byte              bytes[],
                                         int               bytes_len)
{
  if (data->data == NULL)
  {
    data->data = malloc(bytes_len);
    if (data->data == NULL)
    {
      print_err("### Unable to extend PES packet data array\n");
      return 1;
    }
    memcpy(data->data,bytes,bytes_len);
    data->data_len = bytes_len;
  }
  else
  {
    data->data = realloc(data->data,data->data_len + bytes_len);
    if (data->data == NULL)
    {
      print_err("### Unable to extend PES packet data array\n");
      return 1;
    }
    memcpy(&(data->data[data->data_len]),bytes,bytes_len);
    data->data_len = data->data_len + bytes_len;
  }
  return 0;  
}

/*
 * Build a dummy PES packet datastructure.
 *
 * - `data` is the "new" dummy PES packet. Do not free this,
 *   as it is remembered statically inside the function.
 * - `data_len` is the required (total) size of the dummy PES packet
 *
 * Returns 0 if all goes well, 1 if something goes wrong
 */
static inline int build_dummy_PES_packet_data(PES_packet_data_p *data,
                                              int                data_len)
{
  int  err;
  static PES_packet_data_p  local_data = NULL;
  if (local_data == NULL)
  {
    err = build_PES_packet_data(&local_data);
    if (err)
    {
      print_err("### Error building dummy PES packet\n");
      return 1;
    }
    local_data->is_video = FALSE;
  }
  if (local_data->data == NULL)
  {
    local_data->data = malloc(data_len);
    if (local_data->data == NULL)
    {
      print_err("### Unable to extend dummy PES packet data array\n");
      return 1;
    }
    memset(local_data->data,0xFF,data_len);
  }
  else if (data_len > local_data->data_len)
  {
    local_data->data = realloc(local_data->data,data_len);
    if (local_data->data == NULL)
    {
      print_err("### Unable to extend dummy PES packet data array\n");
      return 1;
    }
    memset(local_data->data,0xFF,data_len);
  }

  if (data_len != local_data->data_len)
  {
    int PES_packet_len = data_len - 6;
    // Set up the data in the PES packet
    local_data->data[0] = 0x00;
    local_data->data[1] = 0x00;
    local_data->data[2] = 0x01;  // end of the packet_start_code_prefix
    local_data->data[3] = STREAM_ID_PADDING_STREAM;
    if (PES_packet_len > 0xFFFF)
    {
      local_data->data[4] = 0;
      local_data->data[5] = 0;
    }
    else
    {
      local_data->data[4] = (byte) ((PES_packet_len & 0xFF00) >> 8);
      local_data->data[5] = (byte) ((PES_packet_len & 0x00FF));
    }
    local_data->data_len = data_len;
  }
  *data = local_data;
  return 0;  
}

/*
 * Free a PES packet datastructure
 *
 * - `data` is the PES packet datastructure, which will be freed,
 *   and returned as NULL.
 */
extern void free_PES_packet_data(PES_packet_data_p *data)
{
  if ((*data) == NULL)
    return;
  if ((*data)->data != NULL)
  {
    free((*data)->data);
    (*data)->data = NULL;
  }
  (*data)->data_len = 0;
  (*data)->length = 0;
  free(*data);
  *data = NULL;
  return;
}

// ============================================================
// Transport Stream support - PID -> PES data
// (datastructure support based on that for pidint lists in ts.c)
// ============================================================
/*
 * Initialise a new PID/PES data datastructure.
 */
static int init_peslist(peslist_p  list)
{
  int ii;
  list->length = 0;
  list->size = PESLIST_START_SIZE;
  list->data = malloc(SIZEOF_PES_PACKET_DATA*PESLIST_START_SIZE);
  if (list->data == NULL)
  {
    print_err("### Unable to allocate PES array in PID/PES data array");
    return 1;
  }
  list->pid = malloc(sizeof(uint32_t)*PESLIST_START_SIZE);
  if (list->pid == NULL)
  {
    free(list->data);
    print_err("### Unable to allocate PID array in PID/PES data array\n");
    return 1;
  }
  // Just in case...
  for (ii=0; ii<list->size; ii++)
    list->data[ii] = NULL;
  return 0;
}

/*
 * Build a new PID/PES data datastructure.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int build_peslist(peslist_p  *list)
{
  peslist_p  new = malloc(SIZEOF_PESLIST);
  if (new == NULL)
  {
    print_err("### Unable to allocate PID/PES data array\n");
    return 1;
  }

  if (init_peslist(new))
    return 1;

  *list = new;
  return 0;
}

/*
 * Tidy up and free a PID/PES data datastructure after we've finished with it
 *
 * Clears the datastructure, frees it and returns `list` as NULL.
 *
 * Does nothing if `list` is already NULL.
 */
static void free_peslist(peslist_p  *peslist)
{
  peslist_p list = *peslist;
  if (list == NULL)
    return;
  if (list->data != NULL)
  {
    int ii;
    for (ii=0; ii<list->length; ii++)
    {
      if (list->data[ii] != NULL)
        free_PES_packet_data(&list->data[ii]);
    }
    free(list->data);
    list->data = NULL;
  }
  if (list->pid != NULL)
  {
    free(list->pid);
    list->pid = NULL;
  }
  list->length = 0;
  list->size = 0;
  free(list);
  *peslist = NULL;
}

/*
 * Lookup a PID to find its index in a PID/PES data array.
 *
 * Note that if `list` is NULL, then -1 will be returned.
 *
 * Returns its index (0 or more) if the PID is in the list, -1 if it is not.
 */
static inline int pid_index_in_peslist(peslist_p  list,
                                       uint32_t   pid)
{
  int ii;
  if (list == NULL)
    return -1;
  for (ii = 0; ii < list->length; ii++)
  {
    if (list->pid[ii] == pid)
      return ii;
  }
  return -1;
}

/*
 * Lookup a PID to see if it is in a PID/PES data array.
 *
 * Note that if `list` is NULL, then FALSE will be returned.
 *
 * Returns TRUE if the PID is in the list, FALSE if it is not.
 */
static inline int pid_in_peslist(peslist_p  list,
                                 uint32_t   pid)
{
  return pid_index_in_peslist(list,pid) != -1;
}

/*
 * Start a new PES packet for a PID.
 *
 * Creates a new entry for the given PID, and returns the corresponding new
 * PES packet.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int start_packet_in_peslist(PES_reader_p       reader,
                                   uint32_t           pid,
                                   int                is_video,
                                   PES_packet_data_p *data)
{
  int err;
  int ii;
  peslist_p  list = reader->packets;

  if (list == NULL)
  {
    print_err("### Unable to append to NULL PID/PES data array\n");
    return 1;
  }
  
  err = build_PES_packet_data(data);
  if (err)
  {
    print_err("### Unable to build new PES packet datastructure"
              " for PID/PES data array\n");
    return 1;
  }
  (*data)->is_video = is_video;

  for (ii=0; ii<list->length; ii++)
  {
    if (list->pid[ii] == pid)
    {
      // There is already an entry for this PID - does it have data?
      if (list->data[ii] != NULL)
      {
        PES_packet_data_p packet = list->data[ii];
        if (reader->give_warning)
          fprint_err("!!! PID %04x (%d) already has an unfinished PES packet"
                     " associated with it\n    %d byte%s of %d bytes were already"
                     " read - ignoring them\n",pid,pid,packet->data_len,
                     (packet->data_len==1?"":"s"),packet->length);
        free_PES_packet_data(&(list->data[ii]));
      }
      list->data[ii] = *data;
      return 0;
    }
  }

  // Otherwise, we need to add a new entry to the list
  if (list->length == list->size)
  {
    int newsize = list->size + PESLIST_INCREMENT;
    list->data = realloc(list->data,newsize*SIZEOF_PES_PACKET_DATA);
    if (list->data == NULL)
    {
      print_err("### Unable to extend PID/PES data array\n");
      free_PES_packet_data(data);
      return 1;
    }
    list->pid = realloc(list->pid,newsize*sizeof(uint32_t));
    if (list->pid == NULL)
    {
      print_err("### Unable to extend PID/PES data array\n");
      free_PES_packet_data(data);
      return 1;
    }
    list->size = newsize;
  }
  list->pid[list->length] = pid;
  list->data[list->length] = *data;
  list->length++;
  return 0;
}

/*
 * Find the PES packet for a PID.
 *
 * NB: returns `data` as NULL if the data for the PID *is* NULL.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static inline int find_packet_in_peslist(peslist_p          list,
                                         uint32_t           pid,
                                         PES_packet_data_p *data)
{
  int index = pid_index_in_peslist(list,pid);
  if (index == -1)
    return 1;
  *data = list->data[index];
  return 0;
}

/*
 * Clear the PES packet for a PID.
 *
 * Leaves the entry in the PID/PES array (with NULL data pointer) around for
 * reuse.
 *
 * Returns 0 if it succeeds, 1 if some error occurs.
 */
static int clear_packet_in_peslist(peslist_p  list,
                                   uint32_t   pid)
{
  int index;

  if (list == NULL)
  {
    print_msg("Unable to clear PES packet in NULL PID/PES data array\n");
    return 1;
  }

  index = pid_index_in_peslist(list,pid);
  if (index == -1)
  {
    fprint_err("### Unable to find PID %04x (%x) in PID/PES data array,"
               " so cannot clear its data\n",pid,pid);
    return 1;
  }
  list->data[index] = NULL;
  return 0;
}

// ============================================================
// Reading the Program Stream
// ============================================================
/*
 * Return the next PES packet from the input PS file
 *
 * - `reader` is a PES reader context
 * - `packet_data` is the packet data (NULL if EOF is read)
 *
 * Returns 0 if all goes well, EOF if end of file is read, and 1 if
 * something goes wrong.
 */
static int read_next_PES_packet_from_PS(PES_reader_p       reader,
                                        PES_packet_data_p *packet_data)
{
  // Read PS packets
  // If a packet is a PES packet, return it

  for (;;)
  {
    int      err;
    byte     stream_id;    // The packet's stream id
    int      keep = FALSE; // Keep this packet?
    int      is_video = FALSE;
    struct PS_packet      packet = {0};
    struct PS_pack_header header = {0};

    err = read_PS_packet_start(reader->psreader,FALSE,&reader->posn,
                               &stream_id);
    if (err == EOF)
    {
      *packet_data = NULL;
      return EOF;
    }
    else if (err)
      return 1;

    // If it's the pack header, read it and ignore it
    if (stream_id == 0xba)
    {
      err = read_PS_pack_header_body(reader->psreader,&header);
      if (err == EOF)
      {
        fprint_err("!!! Unexpected EOF - partial PS packet at "
                   OFFSET_T_FORMAT " ignored\n",reader->posn);
        *packet_data = NULL;
        return EOF;
      }
      else if (err)
      {
        fprint_err("### Error reading data for pack header starting at "
                   OFFSET_T_FORMAT "\n",reader->posn);
        return 1;
      }
      continue;
    }

    err = read_PS_packet_body(reader->psreader,stream_id,&packet);
    if (err == EOF)
    {
      fprint_err("!!! Unexpected EOF - partial PS packet at "
                 OFFSET_T_FORMAT " ignored\n",reader->posn);
      *packet_data = NULL;
      return EOF;
    }
    else if (err)
    {
      fprint_err("### Error reading PS packet starting at "
                 OFFSET_T_FORMAT "\n",reader->posn);
      return 1;
    }

    // We have to decide whether to discard this data because it is not
    // a "PES" packet.

    // First, we know we can discard things that we are sure are part of the
    // PS infrastructure. Note that we don't need to check for 0xba (pack
    // header) because we already did that above, and we shouldn't have to
    // check for 0xb9 (MPEG_program_end_code), because that should already
    // have been interpreted as EOF by read_PS_packet_start().
    if (stream_id == 0xbb || // PS system header
        stream_id == 0xbc || // PS map
        stream_id == 0x01)   // PS directory
    {
      /* pass */;
    }
    else if (stream_id == PRIVATE1_AUDIO_STREAM_ID)
    {
      // It's private stream 1, traditionally used for Dolby (AC-3) audio
      if (reader->video_only)
        keep = FALSE;
      else if (reader->audio_stream_id == stream_id)
      {
        keep = TRUE;
        is_video = FALSE;
      }
    }
    else if ((stream_id >= 0xc0) && (stream_id <= 0xdf))
    {
      // It's a non-Dolby audio stream
      if (reader->video_only)
        keep = FALSE;
      else if (reader->audio_stream_id == stream_id)
      {
        keep = TRUE;
        is_video = FALSE;
      }
      else if (reader->audio_stream_id == 0)
      {
        // Aha - we're looking for an audio stream to use, and this is it
        reader->audio_stream_id = stream_id;
        keep = TRUE;
        is_video = FALSE;
        if (reader->give_info)
          fprint_msg("Selecting audio stream number %d\n",stream_id & 0x1F);
      }
    }
    else if (stream_id >= 0xe0 && stream_id <= 0xef)
    {
      // It's a video stream. We're assuming we only get one video
      // stream, so this is a "keeper" regardless
      keep = TRUE;
      is_video = TRUE;
    }

    if (keep)
    {
      err = build_PES_packet_data(packet_data);
      if (err) return 1;
      // We needn't copy the bytes from one "packet" to another,
      // it's easier to just transfer the array, if we're careful
      (*packet_data)->data      = packet.data;
      (*packet_data)->data_len  = packet.data_len;
      (*packet_data)->length    = packet.data_len;
      (*packet_data)->posn      = reader->posn;
      (*packet_data)->is_video  = is_video;
      // So the data array is no longer "present" in the orignal "packet"
      packet.data = NULL;
      packet.data_len = 0;
      break;
    }
    clear_PS_packet(&packet);
  }
  return 0;
}

// ============================================================
// Reading the Transport Stream
// ============================================================
/*
 * Look in the current program map to decide on the video and audio PIDs
 *
 * This is only expected to be called if the PMT has changed.
 *
 * TODO: The detection of different types of audio is not really strong enough
 * TODO: Take account of descriptors in deciding what things are, as well
 */
static void decide_pids(PES_reader_p  reader)
{
  pmt_p pmt = reader->program_map;
  int   ii;
  int   had_video = FALSE;
  int   had_audio = FALSE;

  if (pmt == NULL)
    return;

  // Since we're not expecting our datastructure to be very big,
  // or this function to be called very often, we can look at audio
  // and video separately.
  for (ii = 0; ii < pmt->num_streams; ii++)
  {
    if (IS_VIDEO_STREAM_TYPE(pmt->streams[ii].stream_type))
    {
      if (had_video)
      {
        if (reader->give_warning)
          fprint_err("!!! Multiple video streams in TS program %d, PMT"
                     " at " OFFSET_T_FORMAT " - using PID %04x\n",
                     reader->program_number,reader->posn,reader->video_pid);
        break;
      }
      else if (reader->video_pid == 0)
      {
        reader->video_pid = pmt->streams[ii].elementary_PID;
        switch (pmt->streams[ii].stream_type)
        {
        case AVC_VIDEO_STREAM_TYPE:
          reader->is_h264 = TRUE;
          reader->video_type = VIDEO_H264;
          break;
        case MPEG2_VIDEO_STREAM_TYPE:
        case MPEG1_VIDEO_STREAM_TYPE:   // well, more-or-less
          reader->is_h264 = FALSE;
          reader->video_type = VIDEO_H262;
          break;
        case AVS_VIDEO_STREAM_TYPE:
          reader->is_h264 = FALSE;
          reader->video_type = VIDEO_AVS;
          break;
        default:
          reader->is_h264 = FALSE;
          reader->video_type = VIDEO_UNKNOWN;
          break;
        }
        if (reader->give_info)
          fprint_msg("    Chose video PID %04x\n",reader->video_pid);
      }
      else if (pmt->streams[ii].elementary_PID != reader->video_pid)
      {
        if (reader->give_warning)
          fprint_err("!!! Video streams altered in TS program %d, PMT"
                     " at " OFFSET_T_FORMAT " - still using PID %04x\n",
                     reader->program_number,reader->posn,reader->video_pid);
        break;
      }
      had_video = TRUE;
    }
  }

  if (reader->video_only)
  {
    if (reader->give_info)
      print_msg("    Not interested in any audio streams\n");
    return;
  }

  for (ii = 0; ii < pmt->num_streams; ii++)
  {
    // Note that the audio detection will accept either DVB or ADTS Dolby
    // (AC-3) stream types
    if (IS_AUDIO_STREAM_TYPE(pmt->streams[ii].stream_type))
    {
      if (had_audio)
      {
        if (reader->give_warning)
          fprint_err("!!! Multiple audio streams in TS program %d, PMT"
                     " at " OFFSET_T_FORMAT " - using PID %04x\n",
                     reader->program_number,reader->posn,reader->audio_pid);
        break;
      }
      else if (reader->audio_pid == 0)
      {
        reader->audio_pid = pmt->streams[ii].elementary_PID;
        if (reader->give_info)
          fprint_msg("    Chose audio PID %04x\n",reader->audio_pid);
        if (IS_DOLBY_STREAM_TYPE(pmt->streams[ii].stream_type))
        {
          // Remember what stream type this Dolby data is using
          // - we'll assume that this doesn't change under our feet,
          // and thus we don't need to report if it changes
          reader->dolby_stream_type = pmt->streams[ii].stream_type;
          // If we're not overriding the output stream type, use it as is
          if (!reader->override_dolby_stream_type)
            reader->output_dolby_stream_type = reader->dolby_stream_type;
        }
      }
      else if (pmt->streams[ii].elementary_PID != reader->audio_pid)
      {
        if (reader->give_warning)
          fprint_err("!!! Audio streams altered in TS program %d, PMT"
                     " at " OFFSET_T_FORMAT " - still using PID %04x\n",
                     reader->program_number,reader->posn,reader->audio_pid);
        break;
      }
      had_audio = TRUE;
    }
  }

  if (!reader->override_program_data)
  {
    // Our output program data is to be the same as our input
    reader->output_video_pid = reader->video_pid;
    reader->output_audio_pid = reader->audio_pid;
    reader->output_pcr_pid = reader->pcr_pid;
    reader->output_pmt_pid = reader->pmt_pid;
  }
}

/*
 * Called to use the information extracted from a PMT packet.
 *
 * Note: don't free `pmt` after this call, as it is remembered
 * by the `reader`.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
static int refine_TS_program_info(PES_reader_p   reader,
                                  pmt_p          pmt)
{
  // If this is the *first* PMT, then just adopt its data wholesale
  if (reader->program_map == NULL)
  {
    reader->program_map = pmt;
    reader->pcr_pid = pmt->PCR_pid;
#if DEBUG_PROGRAM_INFO
    if (reader->give_info)
    {
      fprint_msg("PMT packet at " OFFSET_T_FORMAT ": first PMT, used as-is\n",
                 reader->posn);
      report_pmt(TRUE,"    ",reader->program_map);
    }
#else
    if (reader->give_info)
      report_pmt(TRUE,"    ",reader->program_map);
#endif
    // And use its information to determine our video/audio PIDs
    decide_pids(reader);
    reader->got_program_data = TRUE;
    return 0;
  }

  // Otherwise, check if this PMT contains the same information

  if (pmt->program_number != reader->program_number)
  {
    if (reader->give_info)
      fprint_msg("Ignoring PMT for program %d\n",pmt->program_number);
    free_pmt(&pmt);  // since our caller will not free it
    return 0;
  }

  if (same_pmt(pmt,reader->program_map))
  {
    free_pmt(&pmt);  // since our caller will not free it
    return 0;
  }

  // Grumble or replace? Maybe both is safest
  if (reader->give_warning)
  {
    fprint_err("!!! PMT in TS packet at " OFFSET_T_FORMAT
               " replaces previous program information\n",reader->posn);
    print_err("    Program information was:\n");
    report_pmt(FALSE,"      ",reader->program_map);
    print_err("    New program information is:\n");
    report_pmt(FALSE,"      ",pmt);
  }
  else if (reader->give_info)
  {
#if DEBUG_PROGRAM_INFO
    fprint_msg("PMT packet at " OFFSET_T_FORMAT ": updating program info\n",
               reader->posn);
#endif
    report_pmt(TRUE,"      ",pmt);
  }

  free_pmt(&reader->program_map);
  reader->program_map = pmt;
  reader->pcr_pid = pmt->PCR_pid;

  // And use this new information to determine/check our video/audio PIDs
  decide_pids(reader);
  return 0;
}

/*
 * Call this on each PMT found for the program being read from TS,
 * to refine its idea of what is in that program.
 *
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 *
 * Note that it is assumed that a particular program number will refer
 * to the same program stream throughout a TS file.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
static int extract_and_refine_TS_program_info(PES_reader_p   reader,
                                              uint32_t       pmt_pid,
                                              byte           pmt_data[],
                                              int            pmt_data_len)
{
  int     err;
  pmt_p   pmt = NULL;

  err = extract_pmt(FALSE,pmt_data,pmt_data_len,pmt_pid,&pmt);
  if (err)
  {
    print_err("### Error extracting stream list from PMT\n");
    return 1;
  }

  // If it's the wrong program, we're not interested
  if (pmt->program_number != reader->program_number)
  {
#if DEBUG_PROGRAM_INFO
    if (reader->give_info)
      fprint_msg("PMT packet at " OFFSET_T_FORMAT ": program number %d (not %d)\n",
                 reader->posn,pmt->program_number,reader->program_number);
#endif
    free_pmt(&pmt);
    return 0;
  }

  err = refine_TS_program_info(reader,pmt);
  if (err)
  {
    print_err("### Error refining TS program information from PMT\n");
    free_pmt(&pmt);
    return 1;
  }
  // Mustn't free `pmt` because it is remembered by the reader
  return 0;
}

/*
 * Look up the (first) PAT in a Transport Stream
 *
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 * - if `quiet` is not true, and the program number was given as 0, then
 *   the function will report on finding the first PAT and what program
 *   number it deduces therefrom.
 *
 * Note that it is assumed that a particular program number will refer
 * to the same program stream throughout a TS file.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
static int find_first_PAT(PES_reader_p   reader)
{
  int   err;
  int   num_read;
  pidint_list_p prog_list = NULL;

  err = find_pat(reader->tsreader,0,FALSE,!reader->give_info,
                 &num_read,&prog_list);
  if (err)
  {
    print_err("### Error finding first PAT\n");
    return 1;
  }

  if (prog_list->length == 0)
  {
    fprint_err("### No programs defined in first PAT (at " OFFSET_T_FORMAT
               ")\n",reader->tsreader->posn - TS_PACKET_SIZE);
    free_pidint_list(&prog_list);
    return 1;
  }
  else if (prog_list->length > 1 && reader->give_info)
    print_msg("Multiple programs in PAT - using the first\n\n");

  if (reader->program_number == 0)
  {
    reader->program_number = prog_list->number[0];
    reader->pmt_pid = prog_list->pid[0];
  }
  else
  {
    int   ii;
    int   got_program = FALSE;
    for (ii=0; ii<prog_list->length; ii++)
    {
      if (prog_list->number[ii] == reader->program_number)
      {
        got_program = TRUE;
        reader->pmt_pid = prog_list->pid[ii];
        break;
      }
    }
    if (!got_program)
    {
      fprint_err("### Program %d not found in first PAT at "
                 OFFSET_T_FORMAT "\n",reader->program_number,
                 reader->tsreader->posn - TS_PACKET_SIZE);
      return 1;
    }
  }
  free_pidint_list(&prog_list);
  return 0;
}

/*
 * Look up the (first after the first PAT) PMT in a Transport Stream
 *
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 *
 * Returns 0 if all goes well, 1 if something goes wrong, EOF if end-of-file
 * is found before the first (useful) PMT.
 */
static int find_first_PMT(PES_reader_p   reader)
{
  int     err;
  int     nread = 0;
  pmt_p   pmt = NULL;

  for (;;)
  {
    err = find_next_pmt(reader->tsreader,reader->pmt_pid,-1,0,
                        FALSE,!reader->give_info,&nread,&pmt);
    if (err)
    {
      fprint_err("### Error looking for program %d PMT with PID %04x"
                 " after first PAT\n",reader->program_number,reader->pmt_pid);
      return 1;
    }

    if (pmt->program_number == reader->program_number)
      break;

    if (reader->give_info)
      fprint_msg("(Program is %d, not %d - ignoring it)\n",
                 pmt->program_number,reader->program_number);

    free_pmt(&pmt);
  }

  err = refine_TS_program_info(reader,pmt);
  if (err)
  {
    print_err("### Error refining TS program information from PMT\n");
    free_pmt(&pmt);
    return 1;
  }
  // Mustn't free `pmt` because it is remembered by the reader
  return 0;
}

/*
 * Find the first program information for a Transport Stream.
 *
 * Rewinds when it has finished.
 *
 * Find the first PAT, and then the first PMT following that, and thus
 * determine the program information. Then rewind. This won't hurt it the
 * TS is well formed, since one would expect PAT and PMT at the start of
 * the stream. However, if we're reading something taken from a broadcast
 * stream, then it is unlikely that the PAT/PMT would occur near the
 * beginning, but it *is* likely that the program information will be
 * the same throughout. Thus by rewinding, we can hope to interpret useful
 * packets that occur at the start of the stream.
 *
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 * - if `quiet` is not true, and the program number was given as 0, then
 *   the function will report on finding the first PAT and what program
 *   number it deduces therefrom.
 *
 * Note that it is assumed that a particular program number will refer
 * to the same program stream throughout a TS file.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
static int determine_TS_program_info(PES_reader_p   reader)
{
  int  err;
  err = find_first_PAT(reader);
  if (err)
  {
    print_err("### Error finding TS program information\n");
    return 1;
  }
  err = find_first_PMT(reader);
  if (err)
  {
    print_err("### Error finding TS program information\n");
    return 1;
  }
  // It's only possible to rewind if we're not reading from standard
  // input. If it's not feasible, don't try.
  if (reader->tsreader->file != STDIN_FILENO)
  {
    err = seek_using_TS_reader(reader->tsreader, 0);
    if (err)
    {
      print_err("### Error rewinding TS stream after finding initial"
                " program information\n");
      return 1;
    }
    // Having rewound, we mustn't forget to reset our notion of the TS packet
    // position
    reader->posn = 0;
  }
  return 0;
}

/*
 * Start a new PES packet, for a given PID/stream id
 *
 * - `reader` is our PES reader context
 * - `pid` is the PID of the TS packet we've just read
 * - `stream_type` is the stream type of this data
 * - `payload` is the TS packets payload
 * - `payload_len` is the length of said payload
 * - if the PES packet is finished (i.e., all of it has been read in)
 *   then `finished` will be its data, otherwise `finished` will be NULL.
 *
 * Returns 0 if all went well, 1 if something went wrong
 */
static int start_new_PES_packet(PES_reader_p       reader,
                                uint32_t           pid,
                                byte               payload[],
                                int                payload_len,
                                PES_packet_data_p *finished)
{
  int  err;
  int  index;
  PES_packet_data_p  just_ended = NULL;
  PES_packet_data_p  data;

  //fprint_msg("%c",(pid==reader->video_pid?'V':'A'));fflush(stdout);
#if DEBUG_PES_ASSEMBLY
  fprint_msg(": start new %s PES packet, payload_len = %d\n",
             (pid==reader->video_pid?"video":"audio"),payload_len);
  print_data(TRUE,"Data",payload,payload_len,payload_len);
#endif
  
  if (payload_len < 6)
  {
    // It is technically possible to start a PES packet with very few
    // bytes in its first TS packet, but I can't see why anyone would
    // do it (after all, the adaptation field itself cannot be more
    // than 30 bytes (I counted quickly, I might be off by one) long,
    // which leaves *lots* of space. So I shall assume that it is an
    // error if the first six bytes (at least) of PES data are not
    // in the first TS packet
    fprint_err("### Only first %d byte%s of PES packet in its first TS packet,"
               " packet at " OFFSET_T_FORMAT "\n",payload_len,
               (payload_len==1?"":"s"),reader->posn);
    return 1;
  }
  if (payload[0] != 0 || payload[1] != 0 || payload[2] != 1)
  {
    fprint_err("### PES data starting in TS packet at " OFFSET_T_FORMAT
               " starts %02X %02X %02X, not 00 00 01\n",
               reader->posn,payload[0],payload[1],payload[2]);
    return 1;
  }

  // If PES packets with lengths of zero (i.e., meaning "unbounded") are
  // being transmitted, then we can only tell that we have reached their
  // end when we start the next PES packet for that same PID (or when we
  // reach EOF).
  index = pid_index_in_peslist(reader->packets,pid);
  if (index != -1 &&
      reader->packets->data[index] != NULL &&
      reader->packets->data[index]->length == 0)
  {
#if DEBUG_PES_ASSEMBLY
    print_msg("@@@ just ended previous packet (by implication)\n");
#endif
    just_ended = reader->packets->data[index];
    reader->packets->data[index] = NULL;
  }

  // Anyway, start a new PES packet for this TS packet's data
#if DEBUG_PES_ASSEMBLY
  print_msg("@@@ start packet in PES list\n");
#endif
  err = start_packet_in_peslist(reader,pid,pid==reader->video_pid,&data);
  if (err)
  {
    fprint_err("### Error trying to start a new PES packet,"
               " for TS packet " OFFSET_T_FORMAT "\n",reader->posn);
    return 1;
  }

#if DEBUG_PES_ASSEMBLY
  fprint_msg("@@@ extend packet - data_len was %d\n",data->data_len);
#endif
  err = extend_PES_packet_data(data,payload,payload_len);
  if (err)
  {
    print_err("### Error remembering data at start of PES packet\n");
    return 1;
  }
#if DEBUG_PES_ASSEMBLY
  fprint_msg("@@@ data_len is now %d\n",data->data_len);
#endif

  data->length = ((payload[4] << 8) | payload[5]);
  if (data->length != 0)
    data->length += 6;  // correct to the actual packet length
#if DEBUG_PES_ASSEMBLY
  else
    print_msg("@@@ PES packet marked as length 0\n");
#endif
  data->posn = reader->posn;

  // Unlikely, but have we already finished our PES packet?
  if ((data->data_len > data->length) && data->length != 0)
  {
#if ALLOW_OVERLONG_PACKETS
    int extra;
    fprint_err("### Found %d bytes of PES data, but expected %d"
               " (PES packet length + 6)\n",data->data_len,data->length);
    extra = data->data_len - data->length;
    if (extra > 0)
    {
#if 0
      int from = payload_len - extra;
      print_data(FALSE,"   End of data",payload+from,extra,extra);
#endif
      fprint_err("    In %s PES packet, PID %x, starting at "
                 OFFSET_T_FORMAT "\n",(pid==reader->video_pid?"video":"audio"),
                 pid,reader->posn);
      print_err("!!! Accepting packet anyway\n");
      *finished = data;
      err = clear_packet_in_peslist(reader->packets,pid);
      if (err) return 1;
    }
    else
      return 1;
#else
    fprint_err("### Found %d bytes of PES data, but expected %d"
               " (PES packet length + 6)\n",data->data_len,data->length);
    return 1;
#endif
  }
  else if (data->length == data->data_len)
  {
    *finished = data;
    err = clear_packet_in_peslist(reader->packets,pid);
    if (err) return 1;
  }
  else
    *finished = NULL;

  // And if we had a packet ended by this packet starting, defer this
  // result until later...
  if (just_ended)
  {
    reader->deferred = *finished;  // which might *not* be NULL
    *finished = just_ended;
  }

  return 0;
}

/*
 * Continue a PES packet, for a given PID/stream id
 *
 * - `reader` is our PES reader context
 * - `pid` is the PID of the TS packet we've just read
 * - `stream_type` is the stream type of this data
 * - `payload` is the TS packets payload
 * - `payload_len` is the length of said payload
 * - if the PES packet is finished (i.e., all of it has been read in)
 *   then `finished` will be its data, otherwise `finished` will be NULL.
 *
 * Returns 0 if all went well, 1 if something went wrong
 */
static int continue_PES_packet(PES_reader_p       reader,
                               uint32_t           pid,
                               byte               payload[],
                               int                payload_len,
                               PES_packet_data_p *finished)
{
  int  err;
  PES_packet_data_p  data;

#if DEBUG_PES_ASSEMBLY
  fprint_msg(": continue %s PES packet\n",
             (pid==reader->video_pid?"video":"audio"));
#endif
  
  err = find_packet_in_peslist(reader->packets,pid,&data);
  if (err || data == NULL)
  {
    if (reader->give_warning)
      fprint_err("!!! TS packet with PID %04x at " OFFSET_T_FORMAT
                 " continues an unstarted PES packet  - ignoring it\n",
                 pid,reader->posn);
    *finished = NULL;
    return 0;
  }

  //fprint_msg("%c",(pid==reader->video_pid?'v':'a'));fflush(stdout);

  err = extend_PES_packet_data(data,payload,payload_len);
  if (err)
  {
    print_err("### Error remembering data to continue PES packet\n");
    return 1;
  }

  if ((data->data_len > data->length) && data->length != 0)
  {
#if ALLOW_OVERLONG_PACKETS
    int extra;
    fprint_err("### Found %d bytes of PES data, but expected %d"
               " (PES packet length + 6)\n",data->data_len,data->length);
    extra = data->data_len - data->length;
    if (extra > 0)
    {
#if 0
      int from = payload_len - extra;
      print_data(FALSE,"   End of data",payload+from,extra,extra);
#endif
      fprint_err("    In %s PES packet, PID %x, starting at "
                 OFFSET_T_FORMAT "\n",(pid==reader->video_pid?"video":"audio"),
                 pid,reader->posn);
      print_err("!!! Accepting packet anyway\n");
      *finished = data;
      err = clear_packet_in_peslist(reader->packets,pid);
      if (err) return 1;
    }
    else
      return 1;
#else
    fprint_err("### Found %d bytes of PES data, but expected %d"
               " (PES packet length + 6)\n",data->data_len,data->length);
    return 1;
#endif
  }
  else if (data->data_len == data->length)
  {
    *finished = data;
    err = clear_packet_in_peslist(reader->packets,pid);
    if (err) return 1;
  }
  else
    *finished = NULL;
  
  return 0;
}

/*
 * Check for a PES packet legitimately ended by EOF
  *
  * - `reader` is a PES reader context
  * - `packet_data` is either NULL (meaning no more packets to return),
  *   or a PES packet whose length was specified as 0, meaning that it
  *   would be ended by the next PES packet with the same PID, or by EOF.
  *
  * Note that a PES packet length of 0 is *only* allowed for video ES
  * within TS, and we are only attempting to cope with a single video
  * stream (per program), so we need only expect to have to check for
  * one "outstanding" stream when we hit EOF.
*/
static void check_for_EOF_packet(PES_reader_p       reader,
                                 PES_packet_data_p *packet_data)
{
  int  ii;
  // Not trying to be very efficient - shouldn't matter
  for (ii = 0; ii < reader->packets->length; ii++)
  {
    if (reader->packets->data[ii] != NULL &&
        reader->packets->data[ii]->length == 0)
    {
      *packet_data = reader->packets->data[ii];
      reader->packets->data[ii] = NULL;
      return;
    }
  }
  *packet_data = NULL;
  return;
}

/*
 * Return the next PES packet from the input TS file
 *
 * - `reader` is a PES reader context
 * - `packet_data` is the packet data (NULL if EOF is read)
 *
 * Returns 0 if all goes well, EOF if end of file is read, and 1 if
 * something goes wrong.
 */
static int read_next_PES_packet_from_TS(PES_reader_p       reader,
                                        PES_packet_data_p *packet_data)
{
  // If we have a packet "in hand" because we read it earlier, then
  // just return it
  if (reader->deferred)
  {
    if (reader->video_only && !reader->deferred->is_video)
    {
      free_PES_packet_data(&reader->deferred);
    }
    else
    {
      *packet_data = reader->deferred;
      reader->deferred = NULL;
#if DEBUG_PES_ASSEMBLY
      print_msg("@@@ returning deferred PES packet\n");
#endif
      return 0;
    }
  }

  // If we had read EOF earlier (but not said so because of a PES
  // packet being finished by EOF), then admit to it now
  if (reader->had_eof)
  {
    *packet_data = NULL;
    return EOF;
  }

  for (;;)
  {
    int     err;
    byte   *ts_packet;
    int     payload_unit_start_indicator;
    byte   *adapt;
    int     adapt_len;
    byte   *payload;
    int     payload_len;

    uint32_t pid;

    // Remember the position of the packet we're going to read
    reader->posn = reader->tsreader->posn;

    // And read it
    // Remember that `ts_packet` will not persist, as it is a pointer
    // into the TS buffering innards
    err = read_next_TS_packet(reader->tsreader,&ts_packet);
    if (err == EOF)
    {
      // If we've been given EOF, then either we're just *read* EOF
      // instead of a packet (the obvious case), or we read some data
      // that was terminated by EOF last time, and the EOF was "deferred"
      // by the underlying buffering methods.
      // So, just in case, we'll check for an unbounded (length marked as
      // zero) video stream PES packet
      check_for_EOF_packet(reader,packet_data);
      if (*packet_data == NULL)
        return EOF;
      else
        return 0;
    }
    else if (err)
    {
      fprint_err("### Error reading TS packet at " OFFSET_T_FORMAT "\n",
                 reader->posn);
      return 1;
    }

    err = split_TS_packet(ts_packet,&pid,&payload_unit_start_indicator,
                          &adapt,&adapt_len,&payload,&payload_len);
    if (err)
    {
      fprint_err("### Error interpreting TS packet at " OFFSET_T_FORMAT "\n",
                 reader->posn);
      return 1;
    }

#if DEBUG_PES_ASSEMBLY
    fprint_msg("@@@ TS packet at " OFFSET_T_FORMAT " with pid %3x",
               reader->posn,pid);
#endif

    // If we're writing out TS packets directly to a client, then this
    // is probably a sensible place to do it.
    if (reader->write_TS_packets && reader->tswriter != NULL &&
        !reader->suppress_writing)
    {
      err = tswrite_write(reader->tswriter,ts_packet,pid,FALSE,0);
      if (err)
      {
        fprint_err("### Error writing TS packet (PID %04x) at "
                   OFFSET_T_FORMAT "\n",pid,reader->posn);
        return 1;
      }
    }

    if (pid == 0)  // PAT
    {
      // XXX We should probably check that the PAT for our program
      // has not changed...
#if DEBUG_PES_ASSEMBLY
      print_msg(": PAT\n");
#endif
    }
    else if (pid == reader->pmt_pid)
    {
#if DEBUG_PES_ASSEMBLY
      print_msg(": PMT\n");
#endif

      if (payload_unit_start_indicator && reader->pmt_data)
      {
        // This is the start of a new PMT packet, but we'd already
        // started one, so throw its data away
        fprint_err("!!! Discarding previous (uncompleted) PMT data at "
                   OFFSET_T_FORMAT "\n",reader->posn);
        free(reader->pmt_data);
        reader->pmt_data = NULL; reader->pmt_data_len = reader->pmt_data_used = 0;
      }
      else if (!payload_unit_start_indicator && !reader->pmt_data)
      {
        // This is the continuation of a PMT packet, but we hadn't
        // started one yet
        fprint_err("!!! Discarding PMT continuation, no PMT started, at "
                   OFFSET_T_FORMAT "\n",reader->posn);
        continue;
      }

      err = build_psi_data(FALSE,payload,payload_len,pid,
                           &reader->pmt_data,
                           &reader->pmt_data_len,
                           &reader->pmt_data_used);
      if (err)
      {
        fprint_err("### Error %s PMT at " OFFSET_T_FORMAT "\n",
                   (payload_unit_start_indicator?"starting new":"continuing"),
                   reader->posn);
        if (reader->pmt_data) free(reader->pmt_data);
        return 1;
      }

      // Do we need more data to complete this PMT?
      if (reader->pmt_data_len > reader->pmt_data_used)
        continue;

      err = extract_and_refine_TS_program_info(reader,pid,
                                               reader->pmt_data,
                                               reader->pmt_data_len);
      if (err)
      {
        fprint_err("### Error updating program info from PMT"
                   " (TS packet at " OFFSET_T_FORMAT ")\n",reader->posn);
        if (reader->pmt_data) free(reader->pmt_data);
        return 1;
      }

      free(reader->pmt_data);
      reader->pmt_data = NULL; reader->pmt_data_len = reader->pmt_data_used = 0;

      if (reader->write_PES_packets && !reader->suppress_writing)
      {
        // XXX We *probably* should check if it's changed before doing this,
        //     but at least by outputting it again we ensure it's current
        err = write_program_data(reader,reader->tswriter);
        if (err) return 1;
        // At least make sure it doesn't get written again *too* soon
        reader->program_index = reader->program_freq;
      }
    }
    else if (payload_len > 0 &&
             (pid == reader->video_pid ||
              (pid == reader->audio_pid && !reader->video_only)))
    {
      // It's a packet we're interested in
      PES_packet_data_p  finished;
      if (payload_unit_start_indicator)
        err = start_new_PES_packet(reader,pid,payload,payload_len,
                                   &finished);
      else
        err = continue_PES_packet(reader,pid,payload,payload_len,
                                  &finished);
      if (err)
      {
        fprint_err("### Error %s PES packet (PID %04x)"
                   " with TS packet at " OFFSET_T_FORMAT "\n",
                   (payload_unit_start_indicator?"starting":"continuing"),
                   pid,reader->posn);
        print_data(FALSE,"    Data",payload,payload_len,20);
        return 1;
      }
      if (finished)
      {
#if DEBUG_PES_ASSEMBLY
        fprint_msg("@@@ PES packet with pid %x finished\n",pid);
        report_PES_data_array("    ",finished->data,finished->data_len,TRUE);
#endif

        if (pid == reader->audio_pid && reader->video_only)
        {
          // Actually, they aren't interested in audio at the moment
          // (we check this now because the user can alter this over
          // time, and when we *started* collecting the packet, they
          // might have said they *were* interested in audio)
          free_PES_packet_data(&finished);
        }
        else
        {
#if DEBUG_PES_ASSEMBLY
          print_msg("@@@ return it\n");
#endif
          *packet_data = finished;
          break;
        }
      }
    }
#if DEBUG_PES_ASSEMBLY
    else
      print_msg("\n");
#endif
  }
  return 0;
}

// ============================================================
// General functionality
// ============================================================
/*
 * Look at the start of a file to determine if it appears to be transport
 * stream. Rewinds the file when it is finished.
 *
 * The file is assumed to be Transport Stream if it starts with 0x47 as
 * the first byte, and 0x47 recurs at 188 byte intervals (in other words,
 * it appears to start with several TS packets).
 *
 * - `input` is the file to check
 * - `is_TS` is TRUE if it looks like TS, as described above.
 *
 * Returns 0 if all goes well, 1 if there was an error.
 */
extern int determine_if_TS_file(int    input,
                                int   *is_TS)
{
  int  err;
  int  ii;
  byte buf[TS_PACKET_SIZE];

  *is_TS = TRUE;

  for (ii = 0; ii < 100; ii++)
  {
    err = read_bytes(input,TS_PACKET_SIZE,buf);
    if (err == EOF)
      break;
    else if (err)
    {
      print_err("### Error trying to check if file is TS\n");
      return 1;
    }
    if (buf[0] != 0x47)
    {
      *is_TS = FALSE;
      break;
    }
  }
  err = seek_file(input,0);
  if (err)
  {
    print_err("### Error rewinding file after determining if it is TS\n");
    return 1;
  }
  return 0;
}

/*
 * Given a PES stream (PS or TS), attempt to determine if it holds H.262 or
 * H.264 data.  Sets the `video_type` flag on the reader appropriately.
 *
 * (In fact, this is only needed for PS data, as TS data "says" what it
 * contains in the PAT/PMT.)
 *
 * - `input` is the file to check
 *
 * Returns 0 if all goes well, 1 if there was an error (including the
 * stream not appearing to be either).
 */
static int determine_PES_video_type(PES_reader_p  reader)
{
  int  err;
  ES_p es;
  int  old_video_only = reader->video_only;

  err = build_elementary_stream_PES(reader,&es);
  if (err)
  {
    print_err("### Error starting elementary stream before"
              " working out if PS is H.262 or H.264\n");
    return 1;
  }

  reader->video_only = TRUE;

  err = decide_ES_video_type(es,FALSE,FALSE,&reader->video_type);
  if (err)
  {
    print_err("### Error deciding on PS video type\n");
    free_elementary_stream(&es);
    return 1;
  }
  free_elementary_stream(&es);

  reader->is_h264 = (reader->video_type == VIDEO_H264);
  reader->video_only = old_video_only;

  err = rewind_program_stream(reader->psreader);
  if (err)
  {
    print_err("### Error rewinding PS stream after determining its type\n");
    return 1;
  }
  return 0;
}

/*
 * Build a PES reader datastructure
 *
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout).
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `reader` is the resulting PES reader
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
static int build_PES_reader_datastructure(int            give_info,
                                          int            give_warnings,
                                          PES_reader_p  *reader)
{
  int  err;
  PES_reader_p new = malloc(SIZEOF_PES_READER);
  if (new == NULL)
  {
    print_err("### Unable to allocate PES reader datastructure\n");
    return 1;
  }

  new->tsreader = NULL;  // for the moment, at least
  new->psreader = NULL;  // for the moment, at least
  new->is_TS = FALSE;    // for want of better
  new->give_info = give_info;
  new->give_warning = give_warnings;
  new->posn = 0;
  new->is_h264 = FALSE;
  new->video_type = VIDEO_UNKNOWN;
  new->packet = NULL;

  new->program_number = 0;
  new->program_map = NULL;
  new->video_only = FALSE;
  new->audio_stream_id = 0;

  new->pmt_data = NULL;
  new->pmt_data_len = 0;
  new->pmt_data_used = 0;

  new->video_pid = new->audio_pid = 0;
  new->pcr_pid = new->pmt_pid = 0;
  new->got_program_data = FALSE;

  new->output_program_number = 0;
  new->output_video_pid = new->output_audio_pid = 0;
  new->output_pcr_pid = new->output_pmt_pid = 0;
  new->override_program_data = FALSE;

  new->output_dolby_stream_type =
    new->dolby_stream_type = DVB_DOLBY_AUDIO_STREAM_TYPE;
  new->override_dolby_stream_type = FALSE;

  new->tswriter = NULL;
  new->write_PES_packets = FALSE;
  new->write_TS_packets = FALSE;
  new->suppress_writing = TRUE;
  new->dont_write_current_packet = FALSE;
  new->pes_padding = 0;

  new->debug_read_packets = FALSE;

  err = build_peslist(&new->packets);
  if (err)
  {
    print_err("### Error building PES reader datastructure\n");
    free(new);
    return 1;
  }

  new->deferred = NULL;
  new->had_eof = FALSE;
  *reader = new;
  return 0;
}

/*
 * Build a PES reader datastructure for PS data
 *
 * - `ps` is the Program Stream to read the PES data from
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout).
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `reader` is the resulting PES reader
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int build_PS_PES_reader(PS_reader_p    ps,
                               int            give_info,
                               int            give_warnings,
                               PES_reader_p  *reader)
{
  int  err;

  err = build_PES_reader_datastructure(give_info,give_warnings,reader);
  if (err) return 1;

  (*reader)->is_TS = FALSE;
  (*reader)->psreader = ps;

  // Try to determine what sort of video this is (particularly, is it H.264)
  err = determine_PES_video_type(*reader);
  if (err)
  {
    print_err("### Error determining PS stream type\n");
    (void) free_PES_reader(reader);
    return 1;
  }
  return 0;
}

/*
 * Build a PES reader datastructure for TS data
 *
 * - `tsreader` is the Transport Stream to read the PES data from
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout).
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `program_number` is only used for TS data, and identifies which program
 *   to read. If this is 0 then the first program encountered in the first PAT
 *   will be read.
 * - `reader` is the resulting PES reader
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int build_TS_PES_reader(TS_reader_p    tsreader,
                               int            give_info,
                               int            give_warnings,
                               uint16_t       program_number,
                               PES_reader_p  *reader)
{
  int  err;

  err = build_PES_reader_datastructure(give_info,give_warnings,reader);
  if (err) return 1;

  (*reader)->is_TS = TRUE;
  (*reader)->tsreader = tsreader;

  (*reader)->program_number = program_number;
  (*reader)->output_program_number = program_number;

  // Work out the program information by reading the first PAT and
  // the first (following) PMT
  err = determine_TS_program_info(*reader);
  if (err)
  {
    print_err("### Error determining/checking program number\n");
    (void) free_PES_reader(reader);
    return 1;
  }
  return 0;
}

/*
 * Build a PES reader datastructure
 *
 * - `input` is the file to read the PES data from
 * - `is_TS` should be TRUE if the data is TS, FALSE if it is PS
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout).
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `program_number` is only used for TS data, and identifies which program
 *   to read. If this is 0 then the first program encountered in the first PAT
 *   will be read.
 * - `reader` is the resulting PES reader
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int build_PES_reader(int            input,
                            int            is_TS,
                            int            give_info,
                            int            give_warnings,
                            uint16_t       program_number,
                            PES_reader_p  *reader)
{
  int  err;

  if (is_TS)
  {
    TS_reader_p  tsreader;
    err = build_TS_reader(input,&tsreader);
    if (err)
    {
      print_err("### Error building TS specific reader\n");
      return 1;
    }
    err = build_TS_PES_reader(tsreader,give_info,give_warnings,program_number,
                              reader);
    if (err)
    {
      print_err("### Error building TS specific reader\n");
      free_TS_reader(&tsreader);
      return 1;
    }
  }
  else
  {
    PS_reader_p  ps;
    err = build_PS_reader(input,!give_info,&ps);
    if (err)
    {
      print_err("### Error building PS specific reader\n");
      return 1;
    }
    err = build_PS_PES_reader(ps,give_info,give_warnings,reader);
    if (err)
    {
      print_err("### Error building PS specific reader\n");
      free_PS_reader(&ps);
      return 1;
    }
  }
  return 0;
}

/*
 * Open a Transport Stream file for PES packet reading
 *
 * - `filename` is the name of the file to open.
 * - `program_number` identifies which program to read. If this is 0
 *   then the first program encountered in the first PAT will be read.
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout). If information messages are requested, and the
 *   program number is given as 0, the actual program number chosen will
 *   be reported as well.
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 *
 * Note that it is assumed that a particular program number will refer
 * to the same program stream throughout a TS file.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int open_PES_reader_for_TS(char          *filename,
                                  uint16_t       program_number,
                                  int            give_info,
                                  int            give_warnings,
                                  PES_reader_p  *reader)
{
  int   err;
  int   input;

  input = open_binary_file(filename,FALSE);
  if (input == -1)
  {
    fprint_err("### Unable to open input TS file %s\n",filename);
    return 1;
  }
  err = build_PES_reader(input,TRUE,give_info,give_warnings,program_number,
                         reader);
  if (err) return 1;
  return 0;
}

/*
 * Open a Program Stream file for PES packet reading
 *
 * - `filename` is the name of the file to open.
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout).
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int open_PES_reader_for_PS(char          *filename,
                                  int            give_info,
                                  int            give_warnings,
                                  PES_reader_p  *reader)
{
  int input = open_binary_file(filename,FALSE);
  if (input == -1)
  {
    fprint_err("### Unable to open input PS file %s\n",filename);
    return 1;
  }
  return build_PES_reader(input,FALSE,give_info,give_warnings,0,reader);
}

/*
 * Open a Program Stream or Transport Stream file for PES packet reading
 *
 * - `filename` is the name of the file to open.
 * - `give_info` is TRUE if information about program data, etc., should be
 *   output (to stdout).
 * - `give_warnings` is TRUE if warnings (starting with "!!!") should be
 *   output (to stderr), FALSE if they should be suppressed.
 * - `reader` is the PES reader context corresponding to the newly
 *   opened file.
 *
 * If the file is Transport Stream, then this is equivalent to a call
 * of::
 *
 *    err = open_PES_reader_for_TS(filename,0,give_info,give_warnings,&reader);
 *
 * i.e., the first program found is the program that will be read.
 *
 * The default behaviour in retrieving video and audio is:
 *
 * - Assume a single video stream, and retrieve any video packets
 * - For TS data, assume a single audio stream in the requested
 *   program, and return that, regardless of its type. If there
 *   is more than one audio stream in the program, it is not
 *   defined which will be chosen.
 * - For PS data, return the first non-Dolby audio stream encountered
 *   (and thus no audio if no non-Dolby stream is found).
 *
 * To request video only, call `set_PES_reader_video_only()`.
 *
 * To request a specific audio stream from PS data, call
 * `set_PES_reader_audio_stream()` (this may be called for TS data
 * as well, but will have no effect).
 *
 * To request Dolby audio, call `set_PES_reader_audio_private1()`
 * (again this will have no effect on TS data).
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int open_PES_reader(char          *filename,
                           int            give_info,
                           int            give_warnings,
                           PES_reader_p  *reader)
{
  int   err;
  int   input;
  int   is_TS;

  input = open_binary_file(filename,FALSE);
  if (input == -1)
  {
    fprint_err("### Unable to open input file %s\n",filename);
    return 1;
  }
  err = determine_if_TS_file(input,&is_TS);
  if (err)
  {
    (void) close_file(input);
    return 1;
  }
  if (is_TS)
    return build_PES_reader(input,TRUE,give_info,give_warnings,0,reader);
  else
    return build_PES_reader(input,FALSE,give_info,give_warnings,0,reader);
}

/*
 * Tell the PES reader whether we only want video data
 *
 * - `video_only` should be TRUE if audio is to be ignored, FALSE
 *   if audio should be retained.
 *
 * By default, the PES reader returns video data and a single audio
 * stream (taken from the first audio stream encountered).
 */
extern void set_PES_reader_video_only(PES_reader_p  reader,
                                      int           video_only)
{
  reader->video_only = video_only;
  return;
}

/*
 * Tell the PES reader which audio stream we want.
 *
 * By default, the PES reader returns video data and a single audio
 * stream (taken from the first audio stream encountered).
 *
 * - `reader` is the PES reader context
 * - `stream_number` is the number of the audio stream to read, from
 *   0 to 31 (0x1F).
 *
 * This call only has effect if the input data is PS.
 *
 * Returns 0 if all went well, or 1 if there was an error (specifically,
 * that `stream_number` was not in the range 0-31).
 */
extern int set_PES_reader_audio_stream(PES_reader_p  reader,
                                       int           stream_number)
{
  if (stream_number < 0 || stream_number > 0x1F)
  {
    fprint_err("### Audio stream number %d is not in range 0-31\n",
               stream_number);
    return 1;
  }
  reader->audio_stream_id = 0xc0 | stream_number;
  return 0;
}

/*
 * Tell the PES reader to get its audio stream from private stream 1
 * (this is the stream that is conventionally used for Dolby (AC-3)
 * in DVD data).
 *
 * By default, the PES reader returns video data and a single audio
 * stream (taken from the first audio stream encountered).
 *
 * - `reader` is the PES reader context
 *
 * This call only has effect if the input data is PS.
 */
extern void set_PES_reader_audio_private1(PES_reader_p  reader)
{
  reader->audio_stream_id = PRIVATE1_AUDIO_STREAM_ID;
  return;
}

/*
 * Tell the PES reader to use the given program information when outputting.
 *
 * For PS data (which does not contain TS program information), this is simply
 * a means of setting up sensible values.
 *
 * For TS data, this sets the values to use for output when writing to TS,
 * so that they may be different from those being read in.
 *
 * The above means that it may only be called after it is known whether
 * the data being read is PS or TS data.
 *
 * Note that calling it more than once is allowed - it will happily
 * overwrite any previous values.
 *
 * - `reader` is the PES reader context
 * - `program_number` is the program number to assume. If this is 0,
 *   then 1 will be used.
 * - `pmt_pid` is the PID to use for the PMT.
 * - `video_pid` is the PID to use for video data
 * - `audio_pid` is the PID to use for audio data (if any)
 * - `pcr_pid` is the PID to use for PCR data - this will often
 *   be the same as the `video_pid`
 */
extern void set_PES_reader_program_data(PES_reader_p  reader,
                                        uint16_t      program_number,
                                        uint32_t      pmt_pid,
                                        uint32_t      video_pid,
                                        uint32_t      audio_pid,
                                        uint32_t      pcr_pid)
{
  if (program_number == 0)
    program_number = 1;

  if (reader->is_TS)
  {
    reader->override_program_data = TRUE;
    reader->output_program_number = program_number;
    reader->output_pmt_pid        = pmt_pid;
    reader->output_pcr_pid        = pcr_pid;
    reader->output_video_pid      = video_pid;
    reader->output_audio_pid      = audio_pid;
  }
  else
  {
    reader->output_program_number = reader->program_number = program_number;
    reader->output_pmt_pid        = reader->pmt_pid        = pmt_pid;
    reader->output_pcr_pid        = reader->pcr_pid        = pcr_pid;
    reader->output_video_pid      = reader->video_pid      = video_pid;
    reader->output_audio_pid      = reader->audio_pid      = audio_pid;
    reader->got_program_data = TRUE;
    // Ideally we might also set the reader->program_map datastructure up
  }
}

/*
 * Tell the PES reader that the PS data it is reading is MPEG-4/AVC,
 * as opposed to MPEG-1/MPEG-2.
 */
extern void set_PES_reader_h264(PES_reader_p  reader)
{
  reader->is_h264 = TRUE;
  reader->video_type = VIDEO_H264;
}

/*
 * Tell the PES reader that the PS data it is reading is of
 * type `video_type` (which is assumed to be a legitimate value
 * such as VIDEO_H264, etc.)
 */
extern void set_PES_reader_video_type(PES_reader_p  reader,
                                      int           video_type)
{
  reader->video_type = video_type;
  reader->is_h264 = (video_type == VIDEO_H264);
}

/*
 * Tell the PES reader whether to output any Dolby (AC-3) audio data
 * it may read using the DVB stream type (0x06) or the ATSC stream
 * type (0x81).
 *
 * If it is reading TS data, then the default is to use whatever stream type
 * the Dolby audio was read with.
 *
 * If it is reading PS data, then the default is to assume DVB data. 
 *
 * This call only has effect if Dolby audio data is actually selected.
 */
extern void set_PES_reader_dolby_stream_type(PES_reader_p  reader,
                                             int           is_dvb)
{
  reader->override_dolby_stream_type = TRUE;
  reader->output_dolby_stream_type = (is_dvb?DVB_DOLBY_AUDIO_STREAM_TYPE:
                                      ATSC_DOLBY_AUDIO_STREAM_TYPE);
}

/*
 * Reposition the PES reader to an earlier packet
 *
 * It is the caller's responsibility to choose a sensible `posn` to seek to.
 *
 * Note that using this to reposition in a PES reader does not affect any
 * "higher" reading context using this PES reader - specifically, if data
 * is being read via an ES reader, then calling this function directly
 * will result in the ES reader losing its positional information.
 *
 * In this case, `seek_ES` should be called.
 *
 * - `reader` is the PES reader context
 * - `posn` is a packet position obtained from an earlier PES packet
 *   datastructure (this should *not* be a random offset in the input
 *   file, as that will not in general work).
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int set_PES_reader_position(PES_reader_p  reader,
                                   offset_t      posn)
{
  int err;
  // The positioning is easy
  if (reader->is_TS)
    err = seek_using_TS_reader(reader->tsreader,posn);
  else
    err = seek_using_PS_reader(reader->psreader,posn);
  if (err) return 1;

  // (although it's important not to forget to set the TS packet position for
  // the next packet...)
  reader->posn = posn;
  
  // But we must also make sure that we've lost any memory of previous
  // PES packet data that we were building up
  if (reader->is_TS)
  {
    int ii;
    for (ii=0; ii<reader->packets->length; ii++)
      free_PES_packet_data(&reader->packets->data[ii]);
    if (reader->deferred)
      free_PES_packet_data(&reader->deferred);
    reader->had_eof = FALSE;
  }
  return 0;
}

/*
 * Free a PES reader, and the relevant datastructures. Does not close
 * the underlying file.
 *
 * - `reader` is the PES reader context. This will be freed, and
 *   returned as NULL.
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int free_PES_reader(PES_reader_p  *reader)
{
  int err = 0;

  if ((*reader) == NULL)
    return 0;
  if ((*reader)->packet != NULL)
    free_PES_packet_data(&(*reader)->packet);

  // Forget any file
  (*reader)->tsreader = NULL;
  (*reader)->psreader = NULL;

  if ((*reader)->program_map != NULL)
  {
    free_pmt(&(*reader)->program_map);
  }
  if ((*reader)->pmt_data != NULL)
  {
    free((*reader)->pmt_data);
    (*reader)->pmt_data = NULL;
    (*reader)->pmt_data_len = 0;
    (*reader)->pmt_data_used = 0;
  }
  if ((*reader)->packets != NULL)
  {
    free_peslist(&(*reader)->packets);
  }
  if ((*reader)->is_TS)
    free_TS_reader(&(*reader)->tsreader);
  else
    free_PS_reader(&(*reader)->psreader);
  free(*reader);
  *reader = NULL;
  return err;
}

/*
 * Close a PES reader, and free the relevant datastructures.
 *
 * - `reader` is the PES reader context. This will be freed, and
 *   returned as NULL.
 *
 * Returns 0 if all goes well, 1 if something goes wrong with closing the
 * file (although in that case, the `reader` will still have been freed).
 */
extern int close_PES_reader(PES_reader_p  *reader)
{
  int err = 0;
  int err2;

  if ((*reader) == NULL)
    return 0;

  if ((*reader)->is_TS)
  {
    if ((*reader)->tsreader != NULL)
    {
      err = close_TS_reader(&(*reader)->tsreader);
      if (err) print_err("### Error closing TS reader\n");
    }
  }
  else
  {
    if ((*reader)->psreader != NULL)
    {
      err = close_PS_file(&(*reader)->psreader);
      if (err) print_err("### Error closing PS reader\n");
    }
  }

  err2 = free_PES_reader(reader);
  if (err)
    return err;
  else
    return err2;
}

/*
 * Read in the next PES packet from the input file
 *
 * - `reader` is a PES reader context
 *
 * Returns 0 if all goes well, EOF if end of file is read, and 1 if
 * something goes wrong.
 */
extern int read_next_PES_packet(PES_reader_p  reader)
{
  int err;

  if (reader->packet != NULL)
  {
    if (reader->write_PES_packets && reader->tswriter != NULL &&
        !reader->suppress_writing &&
        !reader->dont_write_current_packet)
    {
      // Aha - we need to output the previous PES packet
      uint32_t pid;
      byte    stream_id;
      if (reader->program_index == 0)
      {
        // Output the current program information
        err = write_program_data(reader,reader->tswriter);
        if (err) return 1;
        reader->program_index = reader->program_freq;
      }
      else
        reader->program_index --;
#if DEBUG_READ_PACKETS
      if (reader->debug_read_packets)
      {
        fprint_msg("<<write PES packet at " OFFSET_T_FORMAT " len %d",
                   reader->packet->posn,
                   reader->packet->data_len);
        if (reader->packet->is_video)
        {
          fprint_msg(" VIDEO eslen %d",reader->packet->es_data_len);
          if (reader->packet->data_alignment_indicator)
            print_msg(" aligned");
        }
        print_msg(">>\n");
      }
#endif
      if (reader->packet->is_video)
      {
        pid = reader->output_video_pid;
        stream_id = DEFAULT_VIDEO_STREAM_ID;
      }
      else
      {
        pid = reader->output_audio_pid;
        stream_id = DEFAULT_AUDIO_STREAM_ID;
      }
      err = write_PES_as_TS_PES_packet(reader->tswriter,
                                       reader->packet->data,
                                       reader->packet->data_len,
                                       pid,stream_id,FALSE,0,0);
      if (err)
      {
        print_err("### Error writing out PES packet as TS\n");
        return 1;
      }
      if (reader->pes_padding)
      {
        // Add some "dummy" PES packets to bulk out our output
	int  ii;
	PES_packet_data_p  dummy;
	err = build_dummy_PES_packet_data(&dummy,reader->packet->data_len);
	if (err) return 1;
	for (ii = 0; ii < reader->pes_padding; ii++)
	{
	  err = write_PES_as_TS_PES_packet(reader->tswriter,
			                   dummy->data,dummy->data_len,
			                   pid,STREAM_ID_PADDING_STREAM,FALSE,0,0);
	  if (err)
	  {
	    print_err("### Error writing out dummy PES packet as TS\n");
	    return 1;
	  }
	}
      }
    }
    // And it's our job to free each PES packet as it is no longer needed
    free_PES_packet_data(&reader->packet);
  }
  // We always undo the "don't write the current packet flag" after we (might)
  // have written it out
  reader->dont_write_current_packet = FALSE;
 
  if (reader->is_TS)
    err = read_next_PES_packet_from_TS(reader,&reader->packet);
  else
    err = read_next_PES_packet_from_PS(reader,&reader->packet);
#if DEBUG_READ_PACKETS
  if (reader->debug_read_packets)
  {
    if (err==EOF)
      print_msg("<<EOF>>\n");
    else if (!err)
      fprint_msg("<<new   PES packet at " OFFSET_T_FORMAT ">>\n",
                 reader->packet->posn);
  }
#endif

  // Higher layers want to know if a particular PES packet had a PTS or not
  if (!err)
    reader->packet->has_PTS = PES_packet_has_PTS(reader->packet);
  return err;
}

// ============================================================
// Reading bytes from PES packets
// ============================================================
/*
 * Given an MPEG-1 PES packet, determine the offset of the ES data.
 *
 * - `data` is the PES packet data, starting "00 00 01 <stream_id>
 *   <packet_length>"
 * - `data_len` is the actual length of the data therein
 *
 * Returns the required offset (i.e., packet[offset] is the first byte
 * of the ES data within the PES packet).
 */
extern int calc_mpeg1_pes_offset(byte  *data, int data_len)
{
  int posn = 6;

  while (posn < data_len && data[posn] == 0xFF) // ignore padding bytes
    posn++;                                      // (should be <= 16, but...)

  if (posn < data_len)
  {
    if ((data[posn] & 0xC0) == 0x40)         // ignore buffer scale/size
      posn += 2;

    if ((data[posn] & 0xF0) == 0x20)         // ignore PTS
      posn += 5;
    else if ((data[posn] & 0xF0) == 0x30)    // ignore PTS and DTS
      posn += 10;
    else if (data[posn] == 0x0F)             // check for paranoia
      posn ++;
    else
    {
      fprint_err("### MPEG-1 PES packet has 0x%1xX"
                 " instead of 0x40, 0x2X, 0x3X or 0x0F\n",(data[posn]&0xF0)>>4);
      posn ++;    // what else can we do?
    }
  }
  return posn;
}
/*
 * Set up ES data access for this PES packet - i.e., set up the `es_data`
 * array as an offset into the PES packet's `data` array.
 *
 * For packets that do not contain any ES data (including PSM, etc.),
 * a zero length ES data array will be set.
 *
 * Note that only packets that appear to be video (i.e., have their
 * `is_video` flag set) will be considered as potential ES data packets.
 *
 * - `packet` is the PES packet datastructure
 */
static inline void setup_PES_as_ES(PES_packet_data_p  packet)
{
  byte  stream_id;
  int   offset;

  if (!packet->is_video)
  {
    packet->es_data = packet->data + 6;  // Perhaps safer than using NULL
    packet->es_data_len = 0;
    return;
  }
  
  stream_id = packet->data[3];

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    // There is data, but it's not ES data
    packet->es_data = packet->data + 6;  // Perhaps safer than using NULL
    packet->es_data_len = 0;
    return;
  case STREAM_ID_PADDING_STREAM:
    // There's no data, it's just padding bytes
    packet->es_data = packet->data + 6;  // Perhaps safer than using NULL
    packet->es_data_len = 0;
    return;
  default:
    break;     // Otherwise, we assume ES data
  }

  // We shan't "pull apart" PTS and DTS unless the user asks specifically
  // So we just need to work out where out data is...

  // The first two bits of the PES header flags should be '10' for H.222.0
  if (IS_H222_PES(packet->data))
  {
    // Yes, it's H.222.0
    // We have to discount:
    //   * 3 bytes of packet_start_code_prefix (00 00 01)
    //   * 1 byte  of stream_id
    //   * 2 bytes of PES_packet_length
    //   * 2 bytes of PES_header_flags
    //   * 1 byte  of PES_header_data_length  -- i.e., 9 bytes thus far
    //   * PES_header_data_length bytes of PES header data
    // before we get to our ES data
    int PES_header_data_length = packet->data[8];
    offset = 9 + PES_header_data_length;
    // The data alignment indicator seems like a sensible thing to remember
    packet->data_alignment_indicator = (packet->data[6] & 0x04) >> 2;
  }
  else
  {
    // We assume it's MPEG-1
    offset = calc_mpeg1_pes_offset(packet->data,packet->data_len);
  }
  packet->es_data = packet->data + offset;
  packet->es_data_len = packet->data_len - offset;
#if 0 // XXX
  print_data(TRUE,"      ",packet->es_data,packet->es_data_len,20);
#endif

#ifdef DEBUG
  if (reader->give_info)
    print_data(TRUE,".. ES data",packet->es_data,packet->es_data_len,20);
#endif

  return;
}

/*
 * Read in the next PES packet that contains ES data we are interested in.
 * Ignores non-video packets.
 *
 * - `reader` is a PES reader context
 *
 * Returns 0 if all goes well, EOF if end of file is read, and 1 if
 * something goes wrong.
 */
extern int read_next_PES_ES_packet(PES_reader_p       reader)
{
  for (;;)
  {
    int err = read_next_PES_packet(reader);
    if (err) return err;  // either 1 or EOF

#ifdef DEBUG
    if (reader->give_info)
    {
      fprint_msg(".. PES packet at " OFFSET_T_FORMAT " is %x (",
                 reader->packet->posn,reader->packet->data[3]);
      print_stream_id(TRUE,reader->packet->data[3]);
      fprint_msg(")%s\n",(reader->packet->is_video?" VIDEO":""));
    }
#endif

    if (reader->packet->is_video)
    {
      if (reader->debug_read_packets)
        report_PES_data_array("",reader->packet->data,reader->packet->data_len,
                              TRUE);
      // Locate its ES data, and check we have some...
      setup_PES_as_ES(reader->packet);
      if (reader->packet->es_data_len > 0)
        break;
    }
  }
  return 0;
}

// ============================================================
// PES dissection
// ============================================================
/*
 * Decode a PTS or DTS value.
 *
 * - `data` is the 5 bytes containing the encoded PTS or DTS value
 * - `required_guard` should be 2 for a PTS alone, 3 for a PTS before
 *   a DTS, or 1 for a DTS after a PTS
 * - `value` is the PTS or DTS value as decoded
 *
 * Returns 0 if the PTS/DTS value is decoded successfully, 1 if an error occurs
 */
extern int decode_pts_dts(byte     data[],
                          int      required_guard,
                          uint64_t *value)
{
  uint64_t      pts1,pts2,pts3;
  int           marker;
  char         *what;
  int           guard = (data[0] & 0xF0) >> 4;

  // Rather than try to use casts to make the arithmetic come out right on both
  // Linux-with-gcc (old-style C rules) and Windows-with-VisualC++ (C99 rules),
  // it's simpler just to use intermediates that won't get cast to "int".
  unsigned int  data0 = data[0];
  unsigned int  data1 = data[1];
  unsigned int  data2 = data[2];
  unsigned int  data3 = data[3];
  unsigned int  data4 = data[4];

  switch (required_guard)
  {
  case 2:  what = "PTS"; break;  // standalone
  case 3:  what = "PTS"; break;  // before a DTS
  case 1:  what = "DTS"; break;  // always after a PTS
  default: what = "PTS/DTS"; break;  // surely some mistake?
  }

  if (guard != required_guard)
  {
    fprint_err("!!! Guard bits at start of %s data are %x, not %x\n",
               what,guard,required_guard);
  }

  pts1 = (data0 & 0x0E) >> 1;
  marker = data0 & 0x01;
  if (marker != 1)
  {
    fprint_err("### First %s marker is not 1",what);
    return 1;
  }

  pts2 = (data1 << 7) | ((data2 & 0xFE) >> 1);
  marker = data2 & 0x01;
  if (marker != 1)
  {
    fprint_err("### Second %s marker is not 1",what);
    return 1;
  }

  pts3 = (data3 << 7) | ((data4 & 0xFE) >> 1);
  marker = data4 & 0x01;
  if (marker != 1)
  {
    fprint_err("### Third %s marker is not 1",what);
    return 1;
  }
  
  *value = (pts1 << 30) | (pts2 << 15) | pts3;
  return 0;
}

/*
 * Encode a PTS or DTS.
 *
 * - `data` is the array of 5 bytes into which to encode the PTS/DTS
 * - `guard_bits` are the required guard bits: 2 for a PTS alone, 3 for
 *   a PTS before a DTS, or 1 for a DTS after a PTS
 * - `value` is the PTS or DTS value to be encoded
 */
extern void encode_pts_dts(byte    data[],
                           int     guard_bits,
                           uint64_t value)
{
  int   pts1,pts2,pts3;

#define MAX_PTS_VALUE 0x1FFFFFFFFLL
  
  if (value > MAX_PTS_VALUE)
  {
    char        *what;
    uint64_t     temp = value;
    while (temp > MAX_PTS_VALUE)
      temp -= MAX_PTS_VALUE;
    switch (guard_bits)
    {
    case 2:  what = "PTS alone"; break;
    case 3:  what = "PTS before DTS"; break;
    case 1:  what = "DTS after PTS"; break;
    default: what = "PTS/DTS/???"; break;
    }
    fprint_err("!!! value " LLU_FORMAT " for %s is more than " LLU_FORMAT
               " - reduced to " LLU_FORMAT "\n",value,what,MAX_PTS_VALUE,temp);
    value = temp;
  }

  pts1 = (int)((value >> 30) & 0x07);
  pts2 = (int)((value >> 15) & 0x7FFF);
  pts3 = (int)( value        & 0x7FFF);

  data[0] =  (guard_bits << 4) | (pts1 << 1) | 0x01;
  data[1] =  (pts2 & 0x7F80) >> 7;
  data[2] = ((pts2 & 0x007F) << 1) | 0x01;
  data[3] =  (pts3 & 0x7F80) >> 7;
  data[4] = ((pts3 & 0x007F) << 1) | 0x01;
}

/*
 * Does the given PES packet contain a PTS?
 *
 * - `packet` is the PES packet datastructure
 *
 * Returns TRUE if it does, FALSE if it does not (or is in error)
 */
extern int PES_packet_has_PTS(PES_packet_data_p  packet)
{
  byte *data = packet->data;
  
  byte  stream_id;
  int   packet_length;
  byte *bytes;

  int PTS_DTS_flags;

  if (data[0] != 0 || data[1] != 0 || data[2] != 1)
  {
    fprint_err("### PES_packet_has_PTS: "
               "PES packet start code prefix is %02x %02x %02x, not 00 00 01",
               data[0],data[1],data[2]);
    return FALSE;
  }

  stream_id = data[3];
  packet_length = (data[4] << 8) | data[5];
  bytes = data + 6;

  // if (packet_length == 0)  // Elementary video data of unspecified length
  //   return 0;

  if (packet_length == 0)
    packet_length = packet->data_len - 6;

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    return FALSE;  // Just data bytes
  case STREAM_ID_PADDING_STREAM:
    return FALSE;  // Just padding bytes
  default:
    break;     // Some sort of data we might be interested in dissecting
  }
  
  if (IS_H222_PES(data))
  {
    // It's H.222.0
    PTS_DTS_flags = (bytes[1] & 0xC0) >> 6;
  }
  else
  {
    // We assume it's MPEG-1
    // Note that the following duplicates code in calc_mpeg1_pes_offset,
    // since it wants to look partway through the data offset...
    int posn = 0;
    // Ignore any up-front padding bytes
    while (posn < packet_length && bytes[posn] == 0xFF)
      posn++;
    if (posn == packet_length)
      return FALSE;     // no space for anything else
    if ((bytes[posn] & 0xC0) == 0x40)         // ignore buffer scale/size
      posn += 2;
    if (posn == packet_length)
      return FALSE;     // no space for PTS/DTS
    if ((bytes[posn] & 0xF0) == 0x20)         // ignore PTS
      PTS_DTS_flags = 2;
    else if ((bytes[posn] & 0xF0) == 0x30)    // ignore PTS and DTS
      PTS_DTS_flags = 3;
    else
      PTS_DTS_flags = 0;
  }

  return (PTS_DTS_flags == 2 || PTS_DTS_flags == 3);
}

/*
 * Report on the content of a PES packet - specifically, its header data.
 *
 * - `prefix` is a string to put before each line of output
 * - `data` is the packet data, and `data_len` its length
 * - `show_data` should be TRUE if the start of the data for each packet should
 *   be shown
 *
 * Returns 0 if all went well, 1 if an error occurs.
 */
extern int report_PES_data_array(char   *prefix,
                                 byte   *data,
                                 int     data_len,
                                 int     show_data)
{
  // This code was originally translated from the Python code in TS.py
  
  byte  stream_id;
  int   packet_length;
  byte *bytes;

  int err;
  uint64_t pts, dts;
  
  int got_pts = FALSE;  // pessimistic
  int got_dts = FALSE;  // pessimistic

  if (data[0] != 0 || data[1] != 0 || data[2] != 1)
  {
    fprint_err("### PES packet start code prefix is %02x %02x %02x, not 00 00 01",
               data[0],data[1],data[2]);
    return 1;
  }

  stream_id = data[3];
  packet_length = (data[4] << 8) | data[5];
  bytes = data + 6;

  // if (packet_length == 0)  // Elementary video data of unspecified length
  //   return 0;

  fprint_msg("%sPES packet: stream id %02x (",prefix,stream_id);
  print_stream_id(TRUE,stream_id);
  fprint_msg("), packet length %d",packet_length);
  if (packet_length == 0)
  {
    packet_length = data_len - 6;
    fprint_msg(" (actual length %d)",packet_length);
  }
  else if (packet_length != data_len - 6)
  {
    fprint_msg(" (actual length %d)",data_len - 6);
  }

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    print_msg("\n    Just data bytes\n");
    print_data(TRUE,"    ",bytes,packet_length,20);
    return 0;  // Just data bytes
  case STREAM_ID_PADDING_STREAM:
    print_msg("\n");
    return 0;  // Just padding bytes
  default:
    break;     // Some sort of data we might be interested in dissecting
  }

  if (IS_H222_PES(data))
  {
    // Yes, it's H.222.0
    int PES_scrambling_control;
    int PES_priority;
    int data_alignment_indicator;
    int copyright;
    int original_or_copy;
    int PTS_DTS_flags;
    int ESCR_flag;
    int ES_rate_flag;
    int DSM_trick_mode_flag;
    int additional_copy_info_flag;
    int PES_CRC_flag;
    int PES_extension_flag;
    int PES_header_data_length;
    print_msg("\n");

    PES_scrambling_control = (bytes[0] & 0x30) >> 4;
    PES_priority = (bytes[0] & 0x08) >> 3;
    data_alignment_indicator = (bytes[0] & 0x04) >> 2;
    copyright = (bytes[0] & 0x02) >> 1;
    original_or_copy = bytes[0] & 0x01;

    fprint_msg("%s    scrambling %d, priority %d, data %s, %s, %s\n",
               prefix,
               PES_scrambling_control,
               PES_priority,
               (data_alignment_indicator?"aligned":"unaligned"),
               (copyright?"copyrighted":"copyright undefined"),
               (original_or_copy?"original":"copy"));

    PTS_DTS_flags = (bytes[1] & 0xC0) >> 6;
    ESCR_flag = (bytes[1] & 0x20) >> 5;
    ES_rate_flag = (bytes[1] & 0x10) >> 4;
    DSM_trick_mode_flag = (bytes[1] & 0x08) >> 3;
    additional_copy_info_flag = (bytes[1] & 0x04) >> 2;
    PES_CRC_flag = (bytes[1] & 0x02) >> 1;
    PES_extension_flag = bytes[1] & 0x01;

    fprint_msg("%s    %s, ESCR %d, ES_rate %d, DSM trick mode %d, additional copy"
               " info %d, PES CRC %d, PES extension %d\n",
               prefix,
               (PTS_DTS_flags==2?"PTS":
                PTS_DTS_flags==3?"PTS & DTS":
                PTS_DTS_flags==0?"no PTS/DTS":"<bad PTS/DTS flag>"),
               ESCR_flag,ES_rate_flag,DSM_trick_mode_flag,
               additional_copy_info_flag,PES_CRC_flag,PES_extension_flag);

    PES_header_data_length = bytes[2];

    fprint_msg("%s    PES header data length %d\n",prefix,PES_header_data_length);

    if (PTS_DTS_flags == 2)
    {
      err = decode_pts_dts(&bytes[3],2,&pts);
      if (err) return 1;
      got_pts = TRUE;
    }
    if (PTS_DTS_flags == 3)
    {
      err = decode_pts_dts(&bytes[3],3,&pts);
      if (err) return 1;
      got_pts = TRUE;
      err = decode_pts_dts(&bytes[8],1,&dts);
      if (err) return 1;
      got_dts = TRUE;
    }
    if (got_pts || got_dts)
    {
      fprint_msg("%s    PTS " LLU_FORMAT,prefix,pts);
      if (got_dts)
        fprint_msg(", DTS " LLU_FORMAT,dts);
      print_msg("\n");
    }

    if (show_data)
    {
      bytes += 3 + PES_header_data_length;
      if (prefix && strlen(prefix) > 0)
        fprint_msg("%s",prefix);
      print_data(TRUE,"    ",bytes,packet_length-3-PES_header_data_length,20);
    }
  }
  else
  {
    // We assume it's MPEG-1
    int posn = 0;
    print_msg(" (MPEG-1)\n");
    // Ignore any up-front padding bytes
    while (posn < packet_length && bytes[posn] == 0xFF)
      posn++;
    if (posn < packet_length)
    {
      if ((bytes[posn] & 0xC0) == 0x40)         // ignore buffer scale/size
        posn += 2;
      if (posn == packet_length)
        return 0;     // no space for PTS/DTS

      if ((bytes[posn] & 0xF0) == 0x20)         // PTS
      {
        err = decode_pts_dts(&bytes[posn],2,&pts);
        if (err) return 1;
        got_pts = TRUE;
        posn += 5;
      }
      else if ((bytes[posn] & 0xF0) == 0x30)    // PTS and DTS
      {
        err = decode_pts_dts(&bytes[posn],3,&pts);
        if (err) return 1;
        got_pts = TRUE;
        posn += 5;
        err = decode_pts_dts(&bytes[posn],1,&dts);
        if (err) return 1;
        got_dts = TRUE;
        posn += 5;
      }
      else if (bytes[posn] == 0x0F)             // check for paranoia
        posn ++;
      else
      {
        fprint_err("### MPEG-1 PES packet has 0x%1xX"
                   " instead of 0x40, 0x2X, 0x3X or 0x0F\n",(bytes[posn]&0xF0)>>4);
        posn ++;    // what else can we do?
      }
      if (got_pts || got_dts)
      {
        fprint_msg("%s    PTS " LLU_FORMAT,prefix,pts);
        if (got_dts)
          fprint_msg(", DTS " LLU_FORMAT,dts);
        print_msg("\n");
      }

      if (show_data)
      {
        bytes += posn;
        if (prefix && strlen(prefix) > 0)
          fprint_msg("%s",prefix);
        print_data(TRUE,"    ",bytes,packet_length-posn,20);
      }
    }
  }

  return 0;
}

/*
 * Report on the content of a PES packet.
 *
 * This gives a longer form of report than report_PES_data_array(), and
 * can also present substream data for audio stream_types.
 *
 * - `stream_type` is the stream type of the data, or -1 if it is not
 *   known (i.e., if this packet is from PS data).
 * - `payload` is the packet data.
 * - `payload_len` is the actual length of the payload (for a TS packet,
 *   this will generally be less than the PES packet's length).
 * - if `show_data_len` is non-0 then the data for the PES packet will
 *   also be shown, up to that length
 *
 * Returns 0 if all went well, 1 if something went wrong.
 */
extern void report_PES_data_array2(int         stream_type,
                                   byte       *payload,
                                   int         payload_len,
                                   int         show_data_len)
{
  int      err;
  int      with_pts = FALSE;
  int      with_dts = FALSE;
  uint64_t pts, dts;
  int      PES_packet_length;
  byte    *data = NULL;
  int      data_len = 0;
  byte     stream_id;

  if (payload_len == 0)
  {
    print_msg("  Payload has length 0\n");
    return;
  }
  else if (payload == NULL)
  {
    fprint_msg("  Payload is NULL, but should be length %d\n",payload_len);
    return;
  }

  stream_id = payload[3];
  PES_packet_length = (payload[4] << 8) | payload[5];
  print_msg("  PES header\n");
  fprint_msg("    Start code:        %02x %02x %02x\n",
             payload[0],payload[1],payload[2]);
  fprint_msg("    Stream ID:         %02x   (%d) ",stream_id,stream_id);
  print_h262_start_code_str(stream_id);
  print_msg("\n");
  fprint_msg("    PES packet length: %04x (%d)\n",
             PES_packet_length,PES_packet_length);

  if (IS_H222_PES(payload))
  {
    // Looks like H.222.0
    switch (stream_id)
    {
    case STREAM_ID_PROGRAM_STREAM_MAP:
    case STREAM_ID_PRIVATE_STREAM_2:
    case STREAM_ID_ECM_STREAM:
    case STREAM_ID_EMM_STREAM:
    case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
    case STREAM_ID_DSMCC_STREAM:
    case STREAM_ID_H222_E_STREAM:
      print_msg("    Just data bytes\n");
      print_data(TRUE,"    Data",payload+6,payload_len-6,1000);
      return;  // Just data bytes
    case STREAM_ID_PADDING_STREAM:
      print_msg("    Padding stream\n");
      return;  // Just padding bytes
    default:
      break;     // Some sort of data we might be interested in dissecting
    }

    fprint_msg("    Flags:             %02x %02x",payload[6],payload[7]);
    if (payload[6] != 0)
    {
      int scramble = (payload[6] & 0x30) >> 8;
      if (scramble != 0) fprint_msg(" scramble-control %d",scramble);
      if (ON(payload[6],0x08)) print_msg(" PES-priority");
      if (ON(payload[6],0x04)) print_msg(" data-aligned");
      if (ON(payload[6],0x02)) print_msg(" copyright");
      if (ON(payload[6],0x01)) print_msg(" original/copy");
    }
    if (payload[7] != 0)
    {
      print_msg(" :");
      if (ON(payload[7],0x80))
      {
        with_pts = TRUE;
        print_msg(" PTS");
      }
      if (ON(payload[7],0x40))
      {
        with_dts = TRUE;
        print_msg(" DTS");
      }
      if (ON(payload[7],0x20)) print_msg(" ESCR");
      if (ON(payload[7],0x10)) print_msg(" ES-rate");
      if (ON(payload[7],0x08)) print_msg(" DSM-trick-mode");
      if (ON(payload[7],0x04)) print_msg(" more-copy-info");
      if (ON(payload[7],0x02)) print_msg(" CRC");
      if (ON(payload[7],0x01)) print_msg(" extension");
    }
    print_msg("\n");
    fprint_msg("    PES header len %d\n", payload[8]);

    if (with_pts)
    {
      err = decode_pts_dts(&(payload[9]),(with_dts?3:2),&pts);
      if (!err)
        fprint_msg("    PTS " LLU_FORMAT "\n",pts);
    }
    if (with_dts)
    {
      err = decode_pts_dts(&(payload[14]),1,&dts);
      if (!err)
        fprint_msg("    DTS " LLU_FORMAT "\n",dts);
    }

    data = payload + 9 + payload[8];
    data_len = payload_len - 9 - payload[8];

    // We know this is the start of a packet. If it is private_stream_1,
    // look to see if it is AC3 or DTS
    // If it is stream type 0x81, then do the same...
    // (maybe should do this for *any* of the 0x8N private streams?)
    if (stream_type == 0x06 || stream_type == 0x81)
    {
      if (data_len >= 2 && data[0] == 0x0B && data[1] == 0x77)
        print_msg("  AC-3 audio data\n");
      else if (data_len >= 4 &&
               data[0] == 0x7F && data[1] == 0xFE &&
               data[1] == 0x80 && data[2] == 0x01)
        print_msg("  DTS audio data\n");
    }
  }
  else
  {
    // We assume it's MPEG-1
    int posn = 0;
    print_msg("    MPEG-1 packet layer packet\n");

    if (stream_id != STREAM_ID_PRIVATE_STREAM_2)
    {
      // Skip any up-front padding bytes
      while (posn < PES_packet_length && payload[6+posn] == 0xFF)
        posn++;
      if (posn != 0)
        fprint_msg("      %d stuffing byte%s\n",posn,posn==1?"":"s");

      if (posn < PES_packet_length)
      {
        if ((payload[6+posn] & 0xC0) == 0x40)
        {
          fprint_msg("      STD buffer scale %d\n",ON(payload[6+posn],5));
          fprint_msg("      STD buffer size %d\n",(payload[6+posn] & 0x1F) << 8 |
                 (payload[6+posn+1]));
          posn += 2;
        }
        if (posn == PES_packet_length)
          return;     // no space for PTS/DTS

        if ((payload[6+posn] & 0xF0) == 0x20)         // PTS
        {
          err = decode_pts_dts(&payload[6+posn],2,&pts);
          if (err) return;
          with_pts = TRUE;
          posn += 5;
        }
        else if ((payload[6+posn] & 0xF0) == 0x30)    // PTS and DTS
        {
          err = decode_pts_dts(&payload[6+posn],3,&pts);
          if (err) return;
          with_pts = TRUE;
          posn += 5;
          err = decode_pts_dts(&payload[6+posn],1,&dts);
          if (err) return;
          with_dts = TRUE;
          posn += 5;
        }
        else if (payload[6+posn] == 0x0F)             // check for paranoia
          posn ++;
        else
        {
          fprint_err("### MPEG-1 PES packet has 0x%1xX"
                     " instead of 0x40, 0x2X, 0x3X or 0x0F\n",(payload[posn]&0xF0)>>4);
          posn ++;    // what else can we do?
        }
        if (with_pts || with_dts)
        {
          fprint_msg("      PTS " LLU_FORMAT "\n",pts);
          if (with_dts)
            fprint_msg("      DTS " LLU_FORMAT "\n",dts);
          print_msg("\n");
        }

        data = payload + 6 + posn;
        data_len = payload_len - 6 - posn;
      }
    }
    else
    {
      data = payload + 6;
      data_len = payload_len - 6;
    }
  }
  if (show_data_len)
    print_data(TRUE,"    Data",data,data_len,show_data_len);
}

/*
 * If the given PES packet data contains a PTS field, return it
 *
 * - `data` is the data for this PES packet
 * - `data_len` is its length
 * - `got_pts` is TRUE if a PTS field was found, in which case
 * - `pts` is that PTS value
 *
 * Returns 0 if all went well, 1 if an error occurs.
 */
extern int find_PTS_in_PES(byte      data[],
                           int32_t   data_len,
                           int      *got_pts,
                           uint64_t *pts)
{
  byte  stream_id;
  int   packet_length;
  byte *bytes;

  int PTS_DTS_flags;

  *got_pts = FALSE;  // pessimistic

  if (data[0] != 0 || data[1] != 0 || data[2] != 1)
  {
    fprint_err("### find_PTS_in_PES:"
               " PES packet start code prefix is %02x %02x %02x, not 00 00 01\n",
            data[0],data[1],data[2]);
    return 1;
  }

  stream_id = data[3];
  packet_length = (data[4] << 8) | data[5];

  // if (packet_length == 0)  // Elementary video data of unspecified length
  //   return 0;

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    return 0;  // Just data bytes
  case STREAM_ID_PADDING_STREAM:
    return 0;  // Just padding bytes
  default:
    break;     // Some sort of data we might be interested in dissecting
  }

  bytes = data + 6;
  if (IS_H222_PES(data))
  {
    // Yes, it's H.222.0
    PTS_DTS_flags = (bytes[1] & 0xC0) >> 6;

    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3)
    {
      int err = decode_pts_dts(&bytes[3],PTS_DTS_flags,pts);
      if (err) return 1;
      *got_pts = TRUE;
    }
  }
  else
  {
    int posn = 0;
    int marker;
    // We assume it's MPEG-1
    // Ignore any up-front padding bytes
    while (posn < packet_length && bytes[posn] == 0xFF)
      posn++;
    if (posn < packet_length)
    {
      if ((bytes[posn] & 0xC0) == 0x40)         // ignore buffer scale/size
        posn += 2;
      if (posn == packet_length)
        return 0;     // no space for PTS/DTS
      marker = (bytes[posn] & 0xF0) >> 4;
      if (marker == 2 ||       // PTS
          marker == 3)         // PTS and DTS
      {
        int err = decode_pts_dts(&bytes[posn],marker,pts);
        if (err) return 1;
        *got_pts = TRUE;
      }
    }
  }
  return 0;
}

/*
 * If the given PES packet data contains a DTS field, return it
 *
 * - `data` is the data for this PES packet
 * - `data_len` is its length
 * - `got_dts` is TRUE if a DTS field was found, in which case
 * - `dts` is that DTS value
 *
 * Returns 0 if all went well, 1 if an error occurs.
 */
extern int find_DTS_in_PES(byte      data[],
                           int32_t   data_len,
                           int      *got_dts,
                           uint64_t *dts)
{
  byte  stream_id;
  int   packet_length;
  byte *bytes;

  int PTS_DTS_flags;

  *got_dts = FALSE;  // pessimistic

  if (data[0] != 0 || data[1] != 0 || data[2] != 1)
  {
    fprint_err("### find_DTS_in_PES:"
               " PES packet start code prefix is %02x %02x %02x, not 00 00 01\n",
               data[0],data[1],data[2]);
    return 1;
  }

  stream_id = data[3];
  packet_length = (data[4] << 8) | data[5];

  // if (packet_length == 0)  // Elementary video data of unspecified length
  //   return 0;

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    return 0;  // Just data bytes
  case STREAM_ID_PADDING_STREAM:
    return 0;  // Just padding bytes
  default:
    break;     // Some sort of data we might be interested in dissecting
  }

  bytes = data + 6;
  if (IS_H222_PES(data))
  {
    // Yes, it's H.222.0
    PTS_DTS_flags = (bytes[1] & 0xC0) >> 6;

    if (PTS_DTS_flags == 3)
    {
      // err = decode_pts_dts(&bytes[3],3,&pts);
      int err = decode_pts_dts(&bytes[8],1,dts);
      if (err) return 1;
      *got_dts = TRUE;
    }
  }
  else
  {
    int posn = 0;
    // We assume it's MPEG-1
    // Ignore any up-front padding bytes
    while (posn < packet_length && bytes[posn] == 0xFF)
      posn++;
    if (posn < packet_length)
    {
      if ((bytes[posn] & 0xC0) == 0x40)         // ignore buffer scale/size
        posn += 2;
      if (posn == packet_length)
        return 0;     // no space for PTS/DTS

      if ((bytes[posn] & 0xF0) == 0x30)    // PTS and DTS
      {
        int err = decode_pts_dts(&bytes[posn+5],1,dts);
        if (err) return 1;
        *got_dts = TRUE;
      }
    }
  }
  return 0;
}

/*
 * If the given PES packet data contains a PTS and/or DTS field, return it
 *
 * - `data` is the data for this PES packet
 * - `data_len` is its length
 * - `got_pts` is TRUE if a PTS field was found, in which case
 * - `pts` is that PTS value
 * - `got_dts` is TRUE if a DTS field was found, in which case
 * - `dts` is that DTS value
 *
 * Returns 0 if all went well, 1 if an error occurs.
 */
extern int find_PTS_DTS_in_PES(byte      data[],
                               int32_t   data_len,
                               int      *got_pts,
                               uint64_t *pts,
                               int      *got_dts,
                               uint64_t *dts)
{
  byte  stream_id;
  int   packet_length;
  byte *bytes;

  int PTS_DTS_flags;

  *got_pts = FALSE;  // pessimistic
  *got_dts = FALSE;

  if (data[0] != 0 || data[1] != 0 || data[2] != 1)
  {
    fprint_err("### find_PTS_DTS_in_PES"
               ": PES packet start code prefix is %02x %02x %02x, not 00 00 01\n",
               data[0],data[1],data[2]);
    return 1;
  }

  stream_id = data[3];
  packet_length = (data[4] << 8) | data[5];

  // if (packet_length == 0)  // Elementary video data of unspecified length
  //   return 0;

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    return 0;  // Just data bytes
  case STREAM_ID_PADDING_STREAM:
    return 0;  // Just padding bytes
  default:
    break;     // Some sort of data we might be interested in dissecting
  }

  bytes = data + 6;
  if (IS_H222_PES(data))
  {
    // Yes, it's H.222.0
    PTS_DTS_flags = (bytes[1] & 0xC0) >> 6;

    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3)
    {
      int err = decode_pts_dts(&bytes[3],PTS_DTS_flags,pts);
      if (err) return 1;
      *got_pts = TRUE;
    }
    if (PTS_DTS_flags == 3)
    {
      // err = decode_pts_dts(&bytes[3],3,&pts);
      int err = decode_pts_dts(&bytes[8],1,dts);
      if (err) return 1;
      *got_dts = TRUE;
    }
  }
  else
  {
    int posn = 0;
    int marker;
    // We assume it's MPEG-1
    // Ignore any up-front padding bytes
    while (posn < packet_length && bytes[posn] == 0xFF)
      posn++;
    if (posn < packet_length)
    {
      if ((bytes[posn] & 0xC0) == 0x40)         // ignore buffer scale/size
        posn += 2;
      if (posn == packet_length)
        return 0;     // no space for PTS/DTS
      marker = (bytes[posn] & 0xF0) >> 4;
      if (marker == 2 ||       // PTS
          marker == 3)         // PTS and DTS
      {
        int err = decode_pts_dts(&bytes[posn],marker,pts);
        if (err) return 1;
        *got_pts = TRUE;
      }
      if (marker == 3)    // PTS and DTS
      {
        int err = decode_pts_dts(&bytes[posn+5],1,dts);
        if (err) return 1;
        *got_dts = TRUE;
      }
    }
  }

  // If we have no DTS then it is the same as PTS
  if (*got_pts && !*got_dts)
  {
    *dts = *pts;
    *got_dts = TRUE;
  }
  return 0;
}

/*
 * If the given PES packet data contains an ESCR field, return it
 *
 * - `data` is the data for this PES packet
 * - `data_len` is its length
 * - `got_escr` is TRUE if an ESCR field was found, in which case
 * - `escr` is that ESCR value
 *
 * Returns 0 if all went well, 1 if an error occurs.
 */
extern int find_ESCR_in_PES(byte      data[],
                            int32_t   data_len,
                            int      *got_escr,
                            uint64_t *escr)
{
  byte  stream_id;
//  int   packet_length;
  byte *bytes;

  *got_escr = FALSE;  // pessimistic
  *escr = 0;

  if (data[0] != 0 || data[1] != 0 || data[2] != 1)
  {
    fprint_err("### find_ESCR_in_PES:"
               " PES packet start code prefix is %02x %02x %02x, not 00 00 01\n",
               data[0],data[1],data[2]);
    return 1;
  }

  stream_id = data[3];
//  packet_length = (data[4] << 8) | data[5];

  // if (packet_length == 0)  // Elementary video data of unspecified length
  //   return 0;

  switch (stream_id)
  {
  case STREAM_ID_PROGRAM_STREAM_MAP:
  case STREAM_ID_PRIVATE_STREAM_2:
  case STREAM_ID_ECM_STREAM:
  case STREAM_ID_EMM_STREAM:
  case STREAM_ID_PROGRAM_STREAM_DIRECTORY:
  case STREAM_ID_DSMCC_STREAM:
  case STREAM_ID_H222_E_STREAM:
    return 0;  // Just data bytes
  case STREAM_ID_PADDING_STREAM:
    return 0;  // Just padding bytes
  default:
    break;     // Some sort of data we might be interested in dissecting
  }

  bytes = data + 6;
  if (IS_H222_PES(data))    // H.222.0 may have ESCR, MPEG-1 mayn't
  {
    // Yes, it's H.222.0
    *got_escr = (bytes[1] & 0x20) == 0x20;
    if (*got_escr)
    {
      uint64_t  ESCR_base;
      uint32_t  ESCR_extn;
      int PTS_DTS_flags = (bytes[1] & 0xC0) >> 6;
      int offset;
      if (PTS_DTS_flags == 2)
        offset = 2 + 5;
      else if (PTS_DTS_flags == 3)
        offset = 2 + 10;
      else
        offset = 2 + 0;     // or so we hope
      ESCR_base =
        (bytes[offset+4] >>  3) |
        (bytes[offset+3] <<  5) |
        (bytes[offset+2] << 13) |
        (bytes[offset+1] << 20) |
        ((((uint64_t)bytes[offset]) & 0x03) << 28) |
        ((((uint64_t)bytes[offset]) & 0x38) << 27);
      ESCR_extn =
        (bytes[offset+5] >> 1) |
        (bytes[offset+4] << 7);
      *escr = ESCR_base * 300 + ESCR_extn;
    }
  }
  return 0;
}

// ============================================================
// Server support
// ============================================================
/*
 * Packets can be written out to a client via a TS writer, as a
 * "side effect" of reading them. The original mechanism was to
 * write out PES packets (as TS) as they are read. This will work
 * for PS or TS data, and writes out only those PES packets that
 * have been read for video or audio data.
 *
 * An alternative, which will only work for TS input data, is
 * to write out TS packets as they are read. This will write all
 * TS packets to the client.
 *
 * - `reader` is our PES reader context
 * - `tswriter` is the TS writer
 * - if `write_PES`, then write PES packets out as they are read from
 *   the input, otherwise write TS packets.
 * - `program_freq` is how often to write out program data (PAT/PMT)
 *   if we are writing PES data (if we are writing TS data, then the
 *   program data will be in the original TS packets)
 */
extern void set_server_output(PES_reader_p  reader,
                              TS_writer_p   tswriter,
                              int           write_PES,
                              int           program_freq)
{
  reader->tswriter = tswriter;
  reader->program_freq = program_freq;
  reader->program_index = 0;
  reader->write_PES_packets = write_PES;
  reader->write_TS_packets = !write_PES;
  reader->suppress_writing = FALSE;
  return;
}

/*
 * Start packets being written out to a TS writer (again).
 *
 * If packets were already being written out, this does nothing.
 *
 * If set_server_output() has not been called to define a TS writer
 * context, this will have no effect.
 *
 * If `reader` is NULL, nothing is done.
 */
extern void start_server_output(PES_reader_p  reader)
{
  if (reader != NULL)
    reader->suppress_writing = FALSE;
  return;
}

/*
 * Stop packets being written out to a TS writer.
 *
 * If packets were already not being written out, this does nothing.
 *
 * If `reader` is NULL, nothing is done.
 */
extern void stop_server_output(PES_reader_p  reader)
{
  if (reader != NULL)
    reader->suppress_writing = TRUE;
  return;
}

/*
 * When outputting PES packets in "normal play" mode, add ``extra`` PES
 * packets (of the same size as each real packet) to the output. This
 * makes the amount of data output be about ``extra``+1 times the amount
 * read (the discrepancy is due to any program data being written).
 *
 * This "expansion" or "padding" of the data can be useful for benchmarking
 * the recipient, as the extra data (which has an irrelevant stream id)
 * will be ignored by the video processor, but not by preceding systems.
 *
 * This does nothing if TS packets are being output directly.
 *
 * - `reader` is our PES reader context
 * - `extra` is how many extra packets to output per "real" packet.
 */
extern void set_server_padding(PES_reader_p  reader,
                               int           extra)
{
  reader->pes_padding = extra;
  return;
}

/*
 * Write out TS program data based on the information we have within the given
 * PES reader context (as amended by any calls of
 * `set_PES_reader_program_data`).
 *
 * Returns 0 if all goes well, 1 if something goes wrong.
 */
extern int write_program_data(PES_reader_p  reader,
                              TS_writer_p   output)
{
  // We know we support at most two program streams for output
  int      num_progs = 0;
  uint32_t prog_pids[2];
  byte     prog_type[2];
  int      err;
  uint32_t pcr_pid;

  // If we are writing out TS data as a side effect of reading TS when
  // assembling our PES packets, we should not write out any program
  // data ourselves, as it is (or should be) already in the TS data
  if (reader->write_TS_packets &&
      !reader->suppress_writing)        // should we care about suppression?
    return 0;

  // Of course, if we haven't *found* any program information yet,
  // there's not much we can do (even if the user is overriding the
  // program information for TS data, we still won't have worked out
  // exactly what we're doing until we've read the program information,
  // so this is probably still a sensible restriction)
  if (!reader->got_program_data)
    return 0;

  if (reader->is_TS)
  {
    // For TS, we can use the stream types from the PMT itself
    if (reader->video_pid != 0)
    {
      pmt_stream_p stream = pid_stream_in_pmt(reader->program_map,
                                              reader->video_pid);
      if (stream == NULL)
      {
        fprint_err("### Cannot find video PID %04x in program map\n",
                   reader->video_pid);
        return 1;
      }
      prog_pids[0] = reader->output_video_pid; // may not be the same
      prog_type[0] = stream->stream_type;
      num_progs = 1;
    }
    if (reader->audio_pid != 0)
    {
      pmt_stream_p stream = pid_stream_in_pmt(reader->program_map,
                                              reader->audio_pid);
      if (stream == NULL)
      {
        fprint_err("### Cannot find audio PID %04x in program map\n",
                   reader->audio_pid);
        return 1;
      }
      prog_pids[num_progs] = reader->output_audio_pid; // may not be the same
      prog_type[num_progs] = stream->stream_type;
      num_progs++;
    }
  }
  else
  {
    // For PS, we have to be given appropriate PIDs (which we'll assume the
    // user has done via the reader), and we need to deduce stream types from
    // the stream ids.

    // XXX For audio data, we can't yet tell what sort of audio we're reading,
    // so we'll make a (quiet possibly wrong) guess.

    num_progs = 1;
    prog_pids[0] = reader->output_video_pid;
    switch (reader->video_type)
    {
    case VIDEO_H264:
      prog_type[0] = AVC_VIDEO_STREAM_TYPE;
      break;
    case VIDEO_H262:
      prog_type[0] = MPEG2_VIDEO_STREAM_TYPE;
      break;
    case VIDEO_AVS:
      prog_type[0] = AVS_VIDEO_STREAM_TYPE;
      break;
    default:
      prog_type[0] = MPEG2_VIDEO_STREAM_TYPE;   // what else to do?
      break;
    }

    prog_pids[1] = reader->output_audio_pid;
    if (reader->audio_stream_id == 0)
    {
      // The user has asked for (not private data) audio, but we haven't
      // found it yet. Make something sensible up...
      prog_type[1] = MPEG2_AUDIO_STREAM_TYPE; // a random guess
    }
    else
    {
      if (reader->audio_stream_id == PRIVATE1_AUDIO_STREAM_ID)
        prog_type[1] = reader->output_dolby_stream_type;
      else
        prog_type[1] = MPEG2_AUDIO_STREAM_TYPE; // a random guess
    }
    num_progs = 2;
  }

  pcr_pid = reader->output_pcr_pid;
  if (pcr_pid == 0)
    pcr_pid = reader->output_video_pid;

#if SHOW_PROGRAM_INFO
  if (reader->give_info)
  {
    fprint_msg("PROGRAM %d: pmt %x (%d), pcr %x (%d)\n"
               "           video %x (%d) type %02x (%s)\n",
               reader->output_program_number,
               reader->output_pmt_pid,reader->output_pmt_pid,
               pcr_pid,pcr_pid,
               reader->output_video_pid,reader->output_video_pid,
               prog_type[0],h222_stream_type_str(prog_type[0]));
    if (num_progs == 2)
      fprint_msg("         audio %x (%d) type %02x (%s)\n",
                 reader->output_audio_pid,reader->output_audio_pid,
                 prog_type[1],h222_stream_type_str(prog_type[1]));
  }
#endif

  err = write_TS_program_data2(output,
                               1, // transport stream id
                               reader->output_program_number,
                               reader->output_pmt_pid,pcr_pid,
                               num_progs,prog_pids,prog_type);
  if (err)
  {
    print_err("### Error writing out TS program data\n");
    return 1;
  }
  return 0;
}

// Local Variables:
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 2
// End:
// vim: set tabstop=8 shiftwidth=2 expandtab: