File: multiplexor.cpp

package info (click to toggle)
mjpegtools 1%3A2.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,460 kB
  • sloc: ansic: 60,386; cpp: 32,062; sh: 5,978; makefile: 751; asm: 103
file content (1635 lines) | stat: -rw-r--r-- 51,146 bytes parent folder | download
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
/*
 *  multiplexor.cpp:  Program/System stream Multiplex despatcher 
 *
 *  Copyright (C) 2003 Andrew Stevens <andrew.stevens@philips.com>
 *
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of version 2 of the GNU General Public License
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#define STREAM_LOGGING
#include <config.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

#include <mjpeg_types.h>
#include <mjpeg_logging.h>
#include <format_codes.h>

#include "interact.hpp"
#include "videostrm.hpp"
#include "stillsstream.hpp"
#include "audiostrm.hpp"
#include "multiplexor.hpp"


/****************
 *
 * Constructor - sets up per-run stuff and initialised parameters
 * that control syntax of generated stream from the job options set
 * by the user.
 *
 ***************/

Multiplexor::Multiplexor(MultiplexJob &job, OutputStream &output, OutputStream *index)
{
    underrun_ignore = 0;
    underruns = 0;
	start_of_new_pack = false;
    InitSyntaxParameters(job);
    InitInputStreams(job);

    psstrm = new PS_Stream(mpeg, sector_size, output, max_segment_size );
    vdr_index = index;
}

Multiplexor::~Multiplexor()
{
    delete psstrm;
    while (!estreams.empty()) {
        delete estreams.back();
        estreams.pop_back();
    }
    vstreams.clear();
    astreams.clear();
}

/******************************************************************
 *
 * Initialisation of stream syntax paramters based on selected user
 * options.  Depending of mux_format some selections may only act as
 * defaults or may simply be ignored if they are inconsistent with the
 * selected output format.
 *
 ******************************************************************/


void Multiplexor::InitSyntaxParameters(MultiplexJob &job)
{
	seg_starts_with_video = false;
	audio_buffer_size = 4 * 1024;
    mux_format = job.mux_format;
    packets_per_pack = job.packets_per_pack;
    data_rate = job.data_rate;
    mpeg = job.mpeg;
    always_sys_header_in_pack = job.always_system_headers;
    sector_transport_size = job.sector_size;
    sector_size = job.sector_size;
	split_at_seq_end = !job.multifile_segment;
    workarounds = job.workarounds;
    run_in_frames = job.run_in_frames;
    max_segment_size = static_cast<uint64_t>(job.max_segment_size)
                       * static_cast<uint64_t>(1024 * 1024);
    max_PTS = static_cast<clockticks>(job.max_PTS) * CLOCKS;
	video_delay = static_cast<clockticks>(job.video_offset);
	audio_delay = static_cast<clockticks>(job.audio_offset);
 	switch( mux_format  )
	{
	case MPEG_FORMAT_VCD :
		data_rate = 75*2352;  			 /* 75 raw CD sectors/sec */ 
	case MPEG_FORMAT_VCD_NSR : /* VCD format, non-standard rate */
		mjpeg_info( "Selecting VCD output profile");
		video_buffers_iframe_only = false;
		mpeg = 1;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = 0;
	  	always_sys_header_in_pack = 0;
	  	sector_transport_size = 2352;	      /* Each 2352 bytes with 2324 bytes payload */
	  	transport_prefix_sectors = 30;
	  	sector_size = 2324;
		buffers_in_video = 1;
		always_buffers_in_video = 0;
		buffers_in_audio = 1;   		// This is needed as otherwise we have
		always_buffers_in_audio = 1;	//  to stuff the packer header which 
                                        // must be 13 bytes for VCD audio
		vcd_zero_stuffing = 20;         // The famous 20 zero bytes for VCD
                                        // audio sectors.
		dtspts_for_all_vau = false;
		sector_align_iframeAUs = false;
        timestamp_iframe_only = false;
		seg_starts_with_video = true;
        if( job.video_tracks == 0 )
        {
            mjpeg_info( "Audio-only VCD track - variable-bit-rate (VCD2.0)");
            vbr = true;
        }
        else
            vbr = false;
		break;
		
	case  MPEG_FORMAT_MPEG2 : 
		mjpeg_info( "Selecting generic MPEG2 output profile");
		mpeg = 2;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = 1;
	  	always_sys_header_in_pack = 0;
	  	sector_transport_size = 2048;	      /* Each 2352 bytes with 2324 bytes payload */
	  	transport_prefix_sectors = 0;
	  	sector_size = 2048;
		buffers_in_video = 1;
		always_buffers_in_video = 0;
		buffers_in_audio = 1;
		always_buffers_in_audio = 1;
		vcd_zero_stuffing = 0;
		vbr = true;
        dtspts_for_all_vau = 0;
        timestamp_iframe_only = false;
        video_buffers_iframe_only = false;
		break;

	case MPEG_FORMAT_SVCD :
		data_rate = 150*2324;

	case MPEG_FORMAT_SVCD_NSR :		/* Non-standard data-rate */
		mjpeg_info( "Selecting SVCD output profile");
		mpeg = 2;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = 0;
	  	always_sys_header_in_pack = 0;
	  	sector_transport_size = 2324;
	  	transport_prefix_sectors = 0;
	  	sector_size = 2324;
		vbr = true;
		buffers_in_video = 1;
		always_buffers_in_video = 0;
		buffers_in_audio = 1;
		always_buffers_in_audio = 0;
		vcd_zero_stuffing = 0;
        dtspts_for_all_vau = 0;
		sector_align_iframeAUs = true;
		seg_starts_with_video = true;
        timestamp_iframe_only = false;
        video_buffers_iframe_only = false;
		break;

	case MPEG_FORMAT_VCD_STILL :
		data_rate = 75*2352;  			 /* 75 raw CD sectors/sec */ 
	  	vbr = false;
		mpeg = 1;
		split_at_seq_end = false;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = 0;
	  	always_sys_header_in_pack = 0;
	  	sector_transport_size = 2352;	      /* Each 2352 bytes with 2324 bytes payload */
	  	transport_prefix_sectors = 0;
	  	sector_size = 2324;
		buffers_in_video = 1;
		always_buffers_in_video = 0;
		buffers_in_audio = 1;
		always_buffers_in_audio = 0;
		vcd_zero_stuffing = 20;
		dtspts_for_all_vau = 1;
		sector_align_iframeAUs = true;
        timestamp_iframe_only = false;
        video_buffers_iframe_only = false;
		break;

	case MPEG_FORMAT_SVCD_STILL :
		mjpeg_info( "Selecting SVCD output profile");
		if( data_rate == 0 )
			data_rate = 150*2324;
		mpeg = 2;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = 0;
	  	always_sys_header_in_pack = 0;
	  	sector_transport_size = 2324;
	  	transport_prefix_sectors = 0;
	  	sector_size = 2324;
		vbr = true;
		buffers_in_video = 1;
		always_buffers_in_video = 0;
		buffers_in_audio = 1;
		always_buffers_in_audio = 0;
		vcd_zero_stuffing = 0;
        dtspts_for_all_vau = 0;
		sector_align_iframeAUs = true;
        timestamp_iframe_only = false;
        video_buffers_iframe_only = false;
		break;

    case MPEG_FORMAT_DVD :
		mjpeg_info( "Selecting generic DVD output profile (PROVISIONAL)");
        if( data_rate == 0 )
            data_rate = 1260000;
		mpeg = 2;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = false; // Handle by control packets
	  	always_sys_header_in_pack = false;
	  	sector_transport_size = 2048;
	  	transport_prefix_sectors = 0;
	  	sector_size = 2048;
		buffers_in_video = true;
		always_buffers_in_video = false;
		buffers_in_audio = true;
		always_buffers_in_audio = false;
		vcd_zero_stuffing = 0;
        dtspts_for_all_vau = 0;
		sector_align_iframeAUs = true;
        timestamp_iframe_only = true;
        video_buffers_iframe_only = true;
		vbr = true;
        break;

    case MPEG_FORMAT_DVD_NAV :
		mjpeg_info( "Selecting dvdauthor DVD output profile");
        if( data_rate == 0 )
            data_rate = 1260000;
		mpeg = 2;
	 	packets_per_pack = 1;
	  	sys_header_in_pack1 = false; // Handle by control packets
	  	always_sys_header_in_pack = false;
	  	sector_transport_size = 2048;
	  	transport_prefix_sectors = 0;
	  	sector_size = 2048;
		buffers_in_video = true;
		always_buffers_in_video = false;
		buffers_in_audio = true;
		always_buffers_in_audio = false;
		vcd_zero_stuffing = 0;
        dtspts_for_all_vau = 0;
		sector_align_iframeAUs = true;
        timestamp_iframe_only = true;
        video_buffers_iframe_only = true;
		vbr = true;
        seg_starts_with_video = true; // Needs special NAV sector 1st!
        break;
			 
	default : /* MPEG_FORMAT_MPEG1 - auto format MPEG1 */
		mjpeg_info( "Selecting generic MPEG1 output profile");
		//mpeg = 1;
		sys_header_in_pack1 = 1;
		transport_prefix_sectors = 0;
		buffers_in_video = 1;
		always_buffers_in_video = 1;
		buffers_in_audio = 0;
		always_buffers_in_audio = 1;
		vcd_zero_stuffing = 0;
        dtspts_for_all_vau = 0;
		sector_align_iframeAUs = false;
        timestamp_iframe_only = false;
        video_buffers_iframe_only = false;
        vbr = false;
		break;
	}
 
 if( job.VBR )
     vbr = true;
 if( job.CBR )
     vbr = false;
}

/**************************************
 *
 * Initialise the elementary stream readers / output sector formatter
 * objects for the various kinds of input stream.
 *
 *************************************/

void Multiplexor::InitInputStreams(MultiplexJob &job)
{
    //
    // S(VCD) Stills are sufficiently unusual to require their own
    // special initialisation
    //
	if( MPEG_STILLS_FORMAT(job.mux_format) )
        InitInputStreamsForStills( job );
    else
        InitInputStreamsForVideo( job );
}

void Multiplexor::InitInputStreamsForStills(MultiplexJob & job )
{
	std::vector<VideoParams *>::iterator vidparm = job.video_param.begin();
    unsigned int frame_interval;
    unsigned int i;
    vector<JobStream *> video_strms;
    job.GetInputStreams( video_strms, MPEG_VIDEO );
    vector<JobStream *> mpa_strms;
    job.GetInputStreams( mpa_strms, MPEG_AUDIO );

    switch( job.mux_format )
    {
    case MPEG_FORMAT_VCD_STILL :
        mjpeg_info( "Multiplexing VCD stills: %lu stills streams.", video_strms.size() );
        {
            frame_interval = 30; // 30 Frame periods
            if( mpa_strms.size() > 0 && video_strms.size() > 2  )
                mjpeg_error_exit1("VCD stills: no more than two streams (one normal one hi-res) possible");


            VCDStillsStream *str[2];
            
            for( i = 0; i< video_strms.size(); ++i )
            {
                FrameIntervals *ints = 
                    new ConstantFrameIntervals( frame_interval );
                str[i] = 
                    new VCDStillsStream( *(video_strms[i]->bs),
                                         new StillsParams( *vidparm, ints),
                                         *this );
                estreams.push_back( str[i] );
                vstreams.push_back( str[i] );
                str[i]->Init();
                ++vidparm;
            }
            if( video_strms.size() == 2 )
            {
                str[0]->SetSibling(str[1]);
                str[1]->SetSibling(str[0]);
            }
        }
        break;
    case MPEG_FORMAT_SVCD_STILL :
        mjpeg_info( "Multiplexing SVCD stills: %lu stills streams %lu audio streams", video_strms.size(), mpa_strms.size() );
        frame_interval = 30;
        if( video_strms.size() > 1 )
        {
            mjpeg_error_exit1("SVCD stills streams may only contain a single video stream");
        }
        else if( video_strms.size() > 0 )
        {
            ConstantFrameIntervals *intervals;
            StillsStream *str;
            intervals = new ConstantFrameIntervals( frame_interval );
            str = new StillsStream( *(video_strms[0]->bs),
                                    new StillsParams( *vidparm, intervals ),
                                    *this );
            estreams.push_back( str );
            vstreams.push_back( str );
            str->Init();
        }
        for( i = 0 ; i < mpa_strms.size() ; ++i )
        {
            AudioStream *audioStrm = new MPAStream( *(mpa_strms[i]->bs), *this);
            audioStrm->Init ( i);
            estreams.push_back(audioStrm);
            astreams.push_back(audioStrm);
        }
        break;
    default:
        mjpeg_error_exit1("Only VCD and SVCD stills format for the moment...");
    }

}

void Multiplexor::InitInputStreamsForVideo(MultiplexJob & job )
{
    mjpeg_info( "Multiplexing video program stream!" );

    unsigned int audio_track = 0;
    unsigned int video_track = 0;
    unsigned int subp_track = 0;
	std::vector<VideoParams *>::iterator vidparm = job.video_param.begin();
	std::vector<LpcmParams *>::iterator lpcmparm = job.lpcm_param.begin();
	std::vector<SubtitleStreamParams *>::iterator subpparm = job.subtitle_params.begin();
    std::vector<JobStream *>::iterator i;
    for( i = job.streams.begin() ; i < job.streams.end() ; ++i )
    {
        switch( (*i)->kind )
        {
            
        case MPEG_VIDEO :
        {
            VideoStream *videoStrm;
            //
            // The first video stream is made the master stream...
            //
            if( video_track == 0  && job.mux_format ==  MPEG_FORMAT_DVD_NAV )
                videoStrm = new DVDVideoStream( *(*i)->bs, 
                                                *vidparm,
                                                *this);
            else
                    videoStrm = new VideoStream( *(*i)->bs,
                                                 *vidparm,
                                                 *this);
            videoStrm->Init( video_track );
            ++video_track;
            ++vidparm;
            estreams.push_back( videoStrm );
            vstreams.push_back( videoStrm );
        }
        break;
        case MPEG_AUDIO :
        {
            AudioStream *audioStrm = new MPAStream( *(*i)->bs, *this);
            audioStrm->Init ( audio_track );
            estreams.push_back(audioStrm);
            astreams.push_back(audioStrm);
           ++audio_track;
        }
        break;
        case AC3_AUDIO :
        {
            AudioStream *audioStrm =  new AC3Stream( *(*i)->bs, *this);
            audioStrm->Init ( audio_track );
            estreams.push_back(audioStrm);
            astreams.push_back(audioStrm);
            ++audio_track;
        }
        break;
        case DTS_AUDIO :
        {
            AudioStream *audioStrm = new DTSStream( *(*i)->bs, *this);
            audioStrm->Init ( audio_track );
            estreams.push_back(audioStrm);
            astreams.push_back(audioStrm);
            ++audio_track;
        }
        break;
        case LPCM_AUDIO :
        {
            AudioStream *audioStrm =  new LPCMStream( *(*i)->bs, *lpcmparm, *this);
            audioStrm->Init ( audio_track );
            estreams.push_back(audioStrm);
            astreams.push_back(audioStrm);
            ++lpcmparm;
            ++audio_track;
        }
        break;
        case SUBP_STREAM :
        {
            // we use audios stream as base class
            SUBPStream *subpStrm =  new SUBPStream( *(*i)->bs, *subpparm,*this);
            subpStrm ->Init ( subp_track );
            estreams.push_back(subpStrm );
            astreams.push_back(subpStrm );
            ++subpparm;
            ++subp_track;
        }
        break;
        }
    }
}


/******************************************************************* 
	Find the timecode corresponding to given position in the system stream
   (assuming the SCR starts at 0 at the beginning of the stream 
@param bytepos byte position in the stream
@param ts returns the number of clockticks the bytepos is from the file start    
****************************************************************** */

void Multiplexor::ByteposTimecode(bitcount_t bytepos, clockticks &ts)
{
	ts = (bytepos*CLOCKS)/static_cast<bitcount_t>(dmux_rate);
}


/**********
 *
 * NextPosAndSCR - Update nominal (may be >= actual) byte count
 * and SCR to next output sector.
 *
 ********/

void Multiplexor::NextPosAndSCR()
{
	bytes_output += sector_transport_size;
	ByteposTimecode( bytes_output, current_SCR );
    if (start_of_new_pack)
    {
        psstrm->CreatePack (&pack_header, current_SCR, mux_rate);
        pack_header_ptr = &pack_header;
        if( include_sys_header )
            sys_header_ptr = &sys_header;
        else
            sys_header_ptr = NULL;
        
    }
    else
        pack_header_ptr = NULL;
}


/**********
 *
 * SetPosAndSCR - Update nominal (may be >= actual) byte count
 * and SCR to next output sector.
 * @param bytepos byte position in the stream
 ********/

void Multiplexor::SetPosAndSCR( bitcount_t bytepos )
{
	bytes_output = bytepos;
	ByteposTimecode( bytes_output, current_SCR );
    if (start_of_new_pack)
    {
        psstrm->CreatePack (&pack_header, current_SCR, mux_rate);
        pack_header_ptr = &pack_header;
        if( include_sys_header )
            sys_header_ptr = &sys_header;
        else
            sys_header_ptr = NULL;
        
    }
    else
        pack_header_ptr = NULL;
}

/* 
   Stream syntax parameters.
*/
		
	



typedef enum { start_segment, mid_segment, 
			   runout_segment }
segment_state;


/**
 * Compute the number of run-in sectors needed to fill up the buffers to
 * suit the type of stream being muxed.
 *
 * For stills we have to ensure an entire buffer is loaded as we only
 * ever process one frame at a time.
 * @returns the number of run-in sectors needed to fill up the buffers to suit the type of stream being muxed.
 */
#if 0
unsigned int Multiplexor::RunInSectors()
{
	std::vector<ElementaryStream *>::iterator str;
	unsigned int sectors_delay = 1;

	for( str = vstreams.begin(); str < vstreams.end(); ++str )
	{

		if( MPEG_STILLS_FORMAT( mux_format ) )
		{
			sectors_delay += static_cast<unsigned int>(1.02*(*str)->BufferSize()) / sector_size+2;
		}
		else if( vbr )
			sectors_delay += 3*(*str)->BufferSize() / ( 4 * sector_size );
		else
			sectors_delay += 5 *(*str)->BufferSize() / ( 6 * sector_size );
	}
    sectors_delay += astreams.size();
	return sectors_delay;
}
#endif
clockticks Multiplexor::RunInDelay()
{
    std::vector<ElementaryStream *>::iterator str;
    double frame_interval = 0.0;
    clockticks delay;
    
    // User has specified a particular run-in

    if(vstreams.size() != 0 )
    {
        frame_interval = CLOCKS / dynamic_cast<VideoStream *>(vstreams[0])->FrameRate();
    }
 
    if( run_in_frames != 0 ) 
    {
        if( frame_interval == 0.0 )
        {
            mjpeg_warn( "Run-in specified in frame intervals but no video stream - using 25Hz" );
            frame_interval = CLOCKS / 25.0;
        }
        delay = static_cast<clockticks>(run_in_frames * frame_interval);
    }
    else
    {
        // No run-in specified: choose something reasonable based on the 
        // specified buffer sizes
        unsigned int data_delay = 0;

        for( str = vstreams.begin(); str < vstreams.end(); ++str )
        {
            if( MPEG_STILLS_FORMAT( mux_format ) )
            {
                data_delay += static_cast<unsigned int>(1.1*(*str)->BufferSize());
            }
            else if( vbr )
                data_delay += (*str)->BufferSize() / 2 ;
            else
                data_delay += 2*(*str)->BufferSize() / 3 ;
        }
        for( str = astreams.begin(); str < astreams.end(); ++str )
        {
            data_delay += 3*(*str)->BufferSize()/4;
        }
        ByteposTimecode( data_delay, delay );
    }
    
    // Round delay a multiple of frame interval if its known...
    if( frame_interval != 0.0 )
    {
        return static_cast<clockticks>(static_cast<int>( delay / frame_interval+0.5) * frame_interval);
    }
    else
    {
        return delay;
    }

}

/**********************************************************************
 *
 *  Initializes the output stream proper. Traverses the input files
 *  and calculates their payloads.  Estimates the multiplex
 *  rate. Estimates the necessary stream delay for the different
 *  substreams.
 *
 *********************************************************************/


void Multiplexor::Init()
{
	std::vector<ElementaryStream *>::iterator str;
	clockticks delay;

	Pack_struc 			dummy_pack;
	Sys_header_struc 	dummy_sys_header;	
	Sys_header_struc *sys_hdr;
	unsigned int nominal_rate_sum;
	
	mjpeg_info("SYSTEMS/PROGRAM stream:");
	psstrm->Open();
    if( vdr_index != 0 )
        vdr_index->Open();
	
    /* These are used to make (conservative) decisions
	   about whether a packet should fit into the recieve buffers... 
	   Audio packets always have PTS fields, video packets needn'.	
	   TODO: Really this should be encapsulated in Elementary stream...?
	*/ 
	psstrm->CreatePack (&dummy_pack, 0, mux_rate);
	if( always_sys_header_in_pack )
	{
        vector<MuxStream *> muxstreams;
        AppendMuxStreamsOf( estreams, muxstreams );
		psstrm->CreateSysHeader (&dummy_sys_header, mux_rate,  
								 !vbr, 1,  true, true, muxstreams);
		sys_hdr = &dummy_sys_header;
	}
	else
		sys_hdr = NULL;
	
	nominal_rate_sum = 0;
	for( str = estreams.begin(); str < estreams.end(); ++str )
	{
		switch( (*str)->Kind() )
		{
		 case ElementaryStream::audio :
		 case ElementaryStream::subtitle :
			(*str)->SetMaxPacketData( 
				psstrm->PacketPayload( **str, NULL, NULL, 
									   false, true, false ) 
				); 
			(*str)->SetMinPacketData(
				psstrm->PacketPayload( **str, sys_hdr, &dummy_pack, 
									   always_buffers_in_audio, true, false )
				);
				
			break;
		case ElementaryStream::video :
			(*str)->SetMaxPacketData( 
				psstrm->PacketPayload( **str, NULL, NULL, 
									   false, false, false ) 
				); 
			(*str)->SetMinPacketData( 
				psstrm->PacketPayload( **str, sys_hdr, &dummy_pack, 
									   always_buffers_in_video, true, true )
				);
			break;
		default :
			mjpeg_error_exit1("INTERNAL: Only audio and video payload calculations implemented!");
			
		}

		if( (*str)->NominalBitRate() == 0 && data_rate == 0)
			mjpeg_error_exit1( "Variable bit-rate stream present: output stream (max) data-rate *must* be specified!");
		nominal_rate_sum += (*str)->NominalBitRate();
	}
		
	/* Attempt to guess a sensible mux rate for the given video and *
	 audio estreams. This is a rough and ready guess for MPEG-1 like
	 formats. */
	   
	 
	dmux_rate = static_cast<int>(1.0205 * nominal_rate_sum);
	dmux_rate = (dmux_rate/50 + 25)*50/8;
	
	mjpeg_info ("rough-guess multiplexed stream data rate    : %07d", dmux_rate*8 );
	if( data_rate != 0 )
		mjpeg_info ("target data-rate specified               : %7d", data_rate*8 );

	if( data_rate == 0 )
	{
		mjpeg_info( "Setting best-guess data rate.");
	}
	else if ( data_rate >= dmux_rate)
	{
		mjpeg_info( "Setting specified specified data rate: %7d", data_rate*8 );
		dmux_rate = data_rate;
	}
	else if ( data_rate < dmux_rate )
	{
		mjpeg_warn( "Target data rate lower than computed requirement!");
		mjpeg_warn( "N.b. a 20%% or so discrepancy in variable bit-rate");
		mjpeg_warn( "streams is common and harmless provided no time-outs will occur"); 
		dmux_rate = data_rate;
	}

	mux_rate = dmux_rate/50;


	//
	// Now that all mux parameters are set we can trigger parsing
	// of actual input stream data and calculation of associated 
	// PTS/DTS by causing the read of the first AU's...
	//
	for( str = estreams.begin(); str < estreams.end(); ++str )
	{
		(*str)->NextAU();
	}

    //
    // Now that we have both output and input streams initialised and
    // data-rates set we can make a decent job of setting the maximum
    // STD buffer delay in video streams.
    //
   
    for( str = vstreams.begin(); str < vstreams.end(); ++str )
    {
        static_cast<VideoStream*>(*str)->SetMaxStdBufferDelay( dmux_rate );
    }				 

	/* To avoid Buffer underflow, the DTS of the first video and audio AU's
	   must be offset sufficiently	forward of the SCR to allow the buffer 
	   time to fill before decoding starts. Calculate the necessary delays...
	*/

	//sectors_delay = RunInSectors();
    //ByteposTimecode( 
    //        static_cast<bitcount_t>(sectors_delay*sector_transport_size),
    //        delay );
    delay = RunInDelay();
	
    video_delay += delay;
    audio_delay += delay;

    /* 
     * The PTS of the first frame may be different from its DTS.
     * Thus to hit perfect A/V sync we need to delay audio by the difference
     * PTS-DTS.
     *
     */
    
    if(  vstreams.size() != 0 )
    {
        audio_delay += vstreams[0]->BasePTS()-vstreams[0]->BaseDTS();
    }

	mjpeg_info( "Run-in delay = %lld Video delay = %lld Audio delay = %lld",
             delay / 300,
				 video_delay / 300,
				 audio_delay / 300 );

    if( max_PTS != 0 )
        
        mjpeg_info( "Multiplexed stream will be ended at %lld seconds playback time\n", max_PTS/CLOCKS );

}

/**
   Prints the current status of the substreams. 
   @param level the desired log level 
 */
void Multiplexor::MuxStatus(log_level_t level)
{
	std::vector<ElementaryStream *>::iterator str;
	for( str = estreams.begin(); str < estreams.end(); ++str )
	{
		switch( (*str)->Kind()  )
		{
		case ElementaryStream::video :
            if( (*str)->MuxCompleted() )
                mjpeg_log( level, "Video %02x: completed", (*str)->stream_id );
            else
			    mjpeg_log( level,
					    "Video %02x: buf=%7d frame=%06d sector=%08d",
					    (*str)->stream_id,
					    (*str)->BufferSize()-(*str)->bufmodel.Space(),
					    (*str)->DecodeOrder(),
					    (*str)->nsec
				    );
			break;
		case ElementaryStream::audio :
            if( (*str)->MuxCompleted() )
                 mjpeg_log( level, "Audio %02x: completed", (*str)->stream_id );
            else
			    mjpeg_log( level,
					    "Audio %02x: buf=%7d frame=%06d sector=%08d",
					    (*str)->stream_id,
					    (*str)->BufferSize()-(*str)->bufmodel.Space(),
					    (*str)->DecodeOrder(),
					    (*str)->nsec
				    );
			break;
		default :
            if( (*str)->MuxCompleted() )
                 mjpeg_log( level, "Other %02x: completed", (*str)->stream_id );
            else
			    mjpeg_log( level,
					    "Other %02x: buf=%7d sector=%08d",
					    (*str)->stream_id,
					    (*str)->bufmodel.Space(),
					    (*str)->nsec
				    );
			break;
		}
	}
	if( !vbr )
		mjpeg_log( level,
				   "Padding : sector=%08d",
				   pstrm.nsec
			);
	
	
}


/**
   Append input substreams to the output multiplex stream.
 */
void Multiplexor::AppendMuxStreamsOf( vector<ElementaryStream *> &elem, 
                                       vector<MuxStream *> &mux )
{
	std::vector<ElementaryStream *>::iterator str;
    for( str = elem.begin(); str < elem.end(); ++str )
    {
        mux.push_back( static_cast<MuxStream *>( *str ) );
    }
}

/******************************************************************
    Program start-up packets.  Generate any irregular packets						
needed at the start of the stream...
	Note: *must* leave a sensible in-stream system header in
	sys_header.
	TODO: get rid of this grotty sys_header global.
******************************************************************/
void Multiplexor::OutputPrefix( )
{
    vector<MuxStream *> vmux,amux,emux;
    AppendMuxStreamsOf( vstreams, vmux );
    AppendMuxStreamsOf( astreams, amux );
    AppendMuxStreamsOf( estreams, emux );

	/* Deal with transport padding */
	SetPosAndSCR( bytes_output + 
				  transport_prefix_sectors*sector_transport_size );
	
	/* VCD: Two padding packets with video and audio system headers */

	switch (mux_format)
	{
	case MPEG_FORMAT_VCD :
	case MPEG_FORMAT_VCD_NSR :

		/* Annoyingly VCD generates seperate system headers for
		   audio and video ... DOH... */
		if( astreams.size() > 1 || vstreams.size() > 1 ||
			astreams.size() + vstreams.size() != estreams.size() )
		{
				mjpeg_error_exit1("VCD man only have max. 1 audio and 1 video stream");
		}

        if( vstreams.size() > 0 )
        {
		/* First packet carries video-info-only sys_header */
		psstrm->CreateSysHeader (&sys_header, mux_rate, 
								 false, true, 
								 true, true, vmux  );
		sys_header_ptr = &sys_header;
		pack_header_ptr = &pack_header;
	  	OutputPadding( false);		
        }

        if( astreams.size() > 0 )
        {

            /* Second packet carries audio-info-only sys_header */
            psstrm->CreateSysHeader (&sys_header, mux_rate,  
                                     false, true, 
                                     true, true, amux );
            sys_header_ptr = &sys_header;
            pack_header_ptr = &pack_header;
            OutputPadding( true );
        }
        break;
		
	case MPEG_FORMAT_SVCD :
	case MPEG_FORMAT_SVCD_NSR :
		/* First packet carries sys_header */
		psstrm->CreateSysHeader (&sys_header, mux_rate,  !vbr, true, 
                                 true, true, emux );
		sys_header_ptr = &sys_header;
		pack_header_ptr = &pack_header;
	  	OutputPadding(false);
        break;

	case MPEG_FORMAT_VCD_STILL :
		/* First packet carries small-still sys_header */
		/* TODO No support mixed-mode stills sequences... */
		psstrm->CreateSysHeader (&sys_header, mux_rate, false, false,
								 true, true, emux );
		sys_header_ptr = &sys_header;
		pack_header_ptr = &pack_header;
		OutputPadding(  false);	
        break;
			
	case MPEG_FORMAT_SVCD_STILL :
		/* TODO: Video only at present */
		/* First packet carries video-info-only sys_header */
		psstrm->CreateSysHeader (&sys_header, mux_rate, 
								 false, true, 
								 true, true, vmux );
		sys_header_ptr = &sys_header;
		pack_header_ptr = &pack_header;
	  	OutputPadding( false);		
		break;

    case MPEG_FORMAT_DVD_NAV :
        /* A DVD System header is a weird thing.  We seem to need to
           include buffer info about streams 0xb8, 0xb9, 0xbd, 0xbf even if
           they're not physically present but the buffers for the actual
           video streams aren't included.  
        */
    {
        // MANY DVD streams appear not to include system headers
        // and some tools have weak parsers that can't handle all
        // the possible variations. Soooo probably best not to generate
        // them
        DummyMuxStream dvd_0xb9_strm_dummy( 0xb9, 1, 232*1024 );
        DummyMuxStream dvd_0xb8_strm_dummy( 0xb8, 0, 4096 );
        DummyMuxStream dvd_0xbf_strm_dummy( 0xbf, 1, 2048 );
        vector<MuxStream *> dvdmux;
		std::vector<MuxStream *>::iterator muxstr;
        dvdmux.push_back( &dvd_0xb9_strm_dummy );
        dvdmux.push_back( &dvd_0xb8_strm_dummy );
        unsigned int max_priv1_buffer = 58*1024;
        for( muxstr = amux.begin(); muxstr < amux.end(); ++muxstr )
        {
            // We mux *many* substreams on PRIVATE_STR_1
            // we set the system header buffer size to the maximum
            // of all those we find
            if( (*muxstr)->stream_id == PRIVATE_STR_1 ) 
            {
                if( (*muxstr)->BufferSize() > max_priv1_buffer )
                    max_priv1_buffer = (*muxstr)->BufferSize();
            }
            // Now the *sane* thing to do if MPEG audio is present would be
            // record this in the system header.  However, dvdauthor lacks
            // a header parser and barfs if the system headers aren't exactly
            // 18 bytes.  Soooo we simply skip them for now...
            // TOOD: Add back in when dvdauthor can parse system headers
            //else
            //    dvdmux.push_back( *muxstr );
        }
        
        DummyMuxStream dvd_priv1_strm_dummy( PRIVATE_STR_1, 1, 
                                             max_priv1_buffer );
        dvdmux.push_back( &dvd_priv1_strm_dummy );
            
        dvdmux.push_back( &dvd_0xbf_strm_dummy );
        psstrm->CreateSysHeader (&sys_header, mux_rate, !vbr, false, 
                                 true, true, dvdmux );
        sys_header_ptr = &sys_header;
        pack_header_ptr = &pack_header;
        /* It is then followed up by a pair of PRIVATE_STR_2 packets which
            we keep empty 'cos we don't know what goes there...
        */
    }
    break;

    default :
        /* Create the in-stream header in case it is needed */
        psstrm->CreateSysHeader (&sys_header, mux_rate, !vbr, false, 
                                 true, true, emux );


	}



}



/******************************************************************
    Program shutdown packets.  Generate any irregular packets
    needed at the end of the stream...
   
******************************************************************/

void Multiplexor::OutputSuffix()
{
	psstrm->CreatePack (&pack_header, current_SCR, mux_rate);
	psstrm->CreateSector (&pack_header, NULL,
						  0,
						  pstrm, 
						  false,
						  true,
						  0, 0,
						  TIMESTAMPBITS_NO );
}

/******************************************************************

	Main multiplex iteration.
	Opens and closes all needed files and manages the correct
	call od the respective Video- and Audio- packet routines.
	The basic multiplexing is done here. Buffer capacity and 
	Timestamp checking is also done here, decision is taken
	wether we should genereate a Video-, Audio- or Padding-
	packet.
******************************************************************/


	
void Multiplexor::Multiplex()

{
	segment_state seg_state;
	std::vector<bool> completed;
	std::vector<bool>::iterator pcomp;
	std::vector<ElementaryStream *>::iterator str;
	
	unsigned int packets_left_in_pack = 0; /* Suppress warning */
	bool padding_packet;
	bool video_first = true;

	Init( );

	unsigned int i;
    for(i = 0; i < estreams.size() ; ++i )
		completed.push_back(false);

    
	/*  Let's try to read in unit after unit and to write it out into
		the outputstream. The only difficulty herein lies into the
		buffer management, and into the fact the the actual access
		unit *has* to arrive in time, that means the whole unit
		(better yet, packet data), has to arrive before arrival of
		DTS. If both buffers are full we'll generate a padding packet
	  
		Of course, when we start we're starting a new segment with no
		bytes output...
	*/

	ByteposTimecode( sector_transport_size, ticks_per_sector );
	seg_state = start_segment;
	running_out = false;
	for(;;)
	{
		bool completion = true;

		for( str = estreams.begin(); str < estreams.end() ; ++str )
			completion &= (*str)->MuxCompleted();
		if( completion )
			break;

		/* A little state-machine for handling the transition from one
		   segment to the next 
		*/
		bool runout_incomplete;
		VideoStream *master;
		switch( seg_state )
		{

			/* Audio and slave video access units at end of segment.
			   If there are any audio AU's whose PTS implies they
			   should be played *before* the video AU starting the
			   next segement is presented we mux them out.  Once
			   they're gone we've finished this segment so we write
			   the suffix switch file, and start muxing a new segment.
			*/
		case runout_segment :
			runout_incomplete = false;
			for( str = estreams.begin(); str < estreams.end(); ++str )
			{
				runout_incomplete |= !(*str)->RunOutComplete();
			}

			if( runout_incomplete )
				break;

			/* Otherwise we write the stream suffix and start a new
			   stream file */
			OutputSuffix();
			psstrm->NextSegment();

			running_out = false;
			seg_state = start_segment;

			/* Starting a new segment.
			   We send the segment prefix, video and audio reciever
			   buffers are assumed to start empty.  We reset the segment
			   length count and hence the SCR.
			   
			*/

		case start_segment :
			mjpeg_info( "New sequence commences..." );
			SetPosAndSCR(0);
			MuxStatus( mjpeg_loglev_t("info") );

			for( str = estreams.begin(); str < estreams.end(); ++str )
			{
				(*str)->AllDemuxed();
			}

			packets_left_in_pack = packets_per_pack;
            start_of_new_pack = true;
			include_sys_header = sys_header_in_pack1;
			buffers_in_video = always_buffers_in_video;
			video_first = seg_starts_with_video & (vstreams.size() > 0);
			OutputPrefix();

			/* Set the offset applied to the raw PTS/DTS of AU's to
               make the DTS of the first AU in the master (video) stream
               precisely the video delay plus whatever time we wasted in
               the sequence pre-amble.

               The DTS of the remaining streams are set so that
               (modulo the relevant delay offset) they maintain the
               same relative timing to the master stream.
               
			*/

            clockticks ZeroSCR;

            if( vstreams.size() != 0 )
                ZeroSCR = vstreams[0]->BaseDTS();
            else
                ZeroSCR = estreams[0]->BaseDTS();

			for( str = vstreams.begin(); str < vstreams.end(); ++str )
				(*str)->SetSyncOffset(video_delay + current_SCR - ZeroSCR );
			for( str = astreams.begin(); str < astreams.end(); ++str )
				(*str)->SetSyncOffset(audio_delay + current_SCR - ZeroSCR );
			pstrm.nsec = 0;
			for( str = estreams.begin(); str < estreams.end(); ++str )
				(*str)->nsec = 0;
			seg_state = mid_segment;
			break;

		case mid_segment :
			/* Once we exceed our file size limit, we need to
			   start a new file soon.  If we want a single stream we
			   simply switch.
				
			   Otherwise we're in the last gop of the current segment
			   (and need to start running streams out ready for a
			   clean continuation in the next segment).
			   TODO: runout_PTS really needs to be expressed in
			   sync delay adjusted units...
			*/
			
			master = 
				vstreams.size() > 0 ? 
				static_cast<VideoStream*>(vstreams[0]) : 0 ;
			if( psstrm->SegmentLimReached() )
			{
				if( split_at_seq_end )
                    mjpeg_warn( "File size exceeded before split-point in video stream" );
                mjpeg_info( "Starting new output file...");
                psstrm->NextSegment();
			}
			else if( master != 0 && master->SeqEndRunOut() )
			{
                const AUnit *nextIframe = master->NextIFrame();
				if(  split_at_seq_end && nextIframe != 0)
				{
					runout_PTS = master->RequiredPTS(nextIframe);
                    mjpeg_info( "Sequence end marker! Running out...");
                    mjpeg_info("Run out PTS limit to AU %d %lld SCR=%lld", 
                               nextIframe->dorder,
                               runout_PTS/300, 
                               current_SCR/300 );
                    MuxStatus( mjpeg_loglev_t("info") );
					running_out = true;
					seg_state = runout_segment;
				}
                else
                {
                    mjpeg_warn( "Sequence end without following I-frame!" );
                }
			}
			break;
			
		}

		padding_packet = false;
		start_of_new_pack = (packets_left_in_pack == packets_per_pack); 
        
		for( str = estreams.begin(); str < estreams.end(); ++str )
		{
			(*str)->DemuxedTo(current_SCR);
		}


		
		//
		// Find the ready-to-mux stream with the most urgent DTS
		//
		ElementaryStream *despatch = 0;
		clockticks earliest = 0;
		for( str = estreams.begin(); str < estreams.end(); ++str )
		{
#ifdef STREAM_LOGGING
            if( (*str)->MuxCompleted() )
                mjpeg_debug( "%02x: complete", (*str)->stream_id );
            else
                mjpeg_debug("%02x: SCR=%lld (%.3f) mux=%d %d reqDTS=%lld ",
                            (*str)->stream_id,
                            current_SCR,
                            static_cast<double>(current_SCR) /(90.0*300.0),
                            (*str)->MuxPossible(current_SCR),
                            (*str)->BufferSize()-(*str)->bufmodel.Space(),
                           (*str)->RequiredDTS()/300
                            
				    );
#endif
			if( (*str)->MuxPossible(current_SCR) && 
				( !video_first || (*str)->Kind() == ElementaryStream::video )
				 )
			{
				if( despatch == 0 || earliest > (*str)->RequiredDTS() )
				{
					despatch = *str;
					earliest = (*str)->RequiredDTS();
				}
			}
		}
		
		if( underrun_ignore > 0 )
			--underrun_ignore;

		if( despatch )
		{
			despatch->BufferAndOutputSector();
			video_first = false;
			if( current_SCR >=  earliest && underrun_ignore == 0)
			{
				mjpeg_warn( "Stream %02x: data will arrive too late sent(SCR)=%lld required(DTS)=%lld", 
							despatch->stream_id, 
							current_SCR/300, 
							earliest/300 );
				MuxStatus( mjpeg_loglev_t("warn") );
				// Give the stream a chance to recover
				underrun_ignore = 300;
				++underruns;
				if( underruns > 10  )
				{
					mjpeg_error_exit1("Too many frame drops -exiting" );
				}
			}
            if( despatch->nsec > 50 &&
                despatch->Lookahead( ) != 0 && ! running_out)
                despatch->UpdateBufferMinMax();
			padding_packet = false;

		}
		else
		{
            //
            // If we got here no stream could be muxed out.
            // We therefore generate padding packets if necessary
            // usually this is because reciever buffers are likely to be
            // full.  
            //
            if( vbr )
            {
                //
                // VBR: For efficiency we bump SCR up to five times or
                // until it looks like buffer status will change
                NextPosAndSCR();
                clockticks next_change = static_cast<clockticks>(0);
                for( str = estreams.begin(); str < estreams.end(); ++str )
                {
                    clockticks change_time = (*str)->bufmodel.NextChange();
                    if( next_change == 0 || change_time < next_change )
                    {
                        next_change = change_time;
                    }
                }

                unsigned int bumps = 5;
                while( bumps > 0 
                       && next_change > current_SCR + ticks_per_sector)
                {
                    NextPosAndSCR();
                    --bumps;
                }
                            
            }
            else
            {
                // Just output a padding packet
                OutputPadding (	false);
            }
			padding_packet = true;
		}

		/* Update the counter for pack packets.  VBR is a tricky 
		   case as here padding packets are "virtual" */
		
		if( ! (vbr && padding_packet) )
		{
			--packets_left_in_pack;
			if (packets_left_in_pack == 0) 
				packets_left_in_pack = packets_per_pack;
		}

		MuxStatus( mjpeg_loglev_t("debug") );
		/* Unless sys headers are always required we turn them off after the first
		   packet has been generated */
		include_sys_header = always_sys_header_in_pack;

		pcomp = completed.begin();
		str = estreams.begin();
		while( str < estreams.end() )
		{
			if( !(*pcomp) && (*str)->MuxCompleted() )
			{
				mjpeg_info( "STREAM %02x completed", (*str)->stream_id );
				MuxStatus( mjpeg_loglev_t("debug") );
				(*pcomp) = true;
			}
			++str;
			++pcomp;
		}
	}
	// Tidy up
	
	OutputSuffix( );
	psstrm->Close();
    if( vdr_index != 0)
        vdr_index->Close();
        
	mjpeg_info( "Multiplex completion at SCR=%lld.", current_SCR/300);
	MuxStatus( mjpeg_loglev_t("info") );
	for( str = estreams.begin(); str < estreams.end(); ++str )
	{
		(*str)->Close();
        if( (*str)->nsec <= 50 )
            mjpeg_info( "BUFFERING stream too short for useful statistics");
        else
            mjpeg_info( "BUFFERING min %d Buf max %d",
                        (*str)->BufferMin(),
                        (*str)->BufferMax() 
                );
	}

    if( underruns> 0 )
	{
		mjpeg_error_exit1( "MUX STATUS: Frame data under-runs detected!" );
	}
	else
	{
		mjpeg_info( "MUX STATUS: no under-runs detected.");
	}
}

/**
   Calculate the packet payload of the output stream at a certain timestamp. 
@param strm the output stream
@param buffers the number of buffers
@param PTSstamp presentation time stamp
@param DTSstamp decoding time stamp
 */
unsigned int Multiplexor::PacketPayload( MuxStream &strm, bool buffers, 
										  bool PTSstamp, bool DTSstamp )
{
	return psstrm->PacketPayload( strm, sys_header_ptr, pack_header_ptr, 
								  buffers, 
								  PTSstamp, DTSstamp)
        - strm.StreamHeaderSize();
}

/***************************************************

  WritePacket - Write out a normal packet carrying data from one of
              the elementary stream being muxed.
@param max_packet_data_size the maximum packet data size allowed
@param strm output mux stream
@param buffers ?
@param PTSstamp presentation time stamp of the packet
@param DTSstamp decoding time stamp of the packet
@param timestamps ?
@param returns the written bytes/packets (?)
***************************************************/

struct VDRtIndex { uint32_t offset; uint8_t type; uint8_t number; uint16_t reserved; };

unsigned int 
Multiplexor::WritePacket( unsigned int     max_packet_data_size,
                                    MuxStream        &strm,
                                    bool 	 buffers,
                                    clockticks   	 PTS,
                                    clockticks   	 DTS,
                                    uint8_t 	 timestamps
	                     )
{
    unsigned int written =
        psstrm->CreateSector ( pack_header_ptr,
                               sys_header_ptr,
                               max_packet_data_size,
                               strm,
                               buffers,
                               false,
                               PTS,
                               DTS,
                               timestamps );
    NextPosAndSCR();
    return written;
}

/***************************************************

  IndexLastPacket 
  - Generate the index data (if any) for the latest
  packet generated in the specified stream.
  N.b. should usually called immediately after WritePacket.
  Its not part of WritePacket because it is not needed
  for all stream types...
***************************************************/
void
Multiplexor::IndexLastPacket( ElementaryStream &strm, int index_type )
{
    switch( strm.Kind() )
    {
        case ElementaryStream::video :
            if( index_type != NOFRAME && vdr_index != 0 )
            {
                union _ibuf 
                {
                        uint8_t bytes[sizeof(VDRtIndex)];
                        VDRtIndex istruct;     
                } indexbuf;
                
                indexbuf.istruct.offset = (int)psstrm->LastPackStart();
                indexbuf.istruct.type = index_type;
                indexbuf.istruct.number = (int)psstrm->SegmentNum();
                indexbuf.istruct.reserved = 0;
                vdr_index->Write( indexbuf.bytes, sizeof(VDRtIndex) );
                
            }
	break;
        default :
            abort(); // Currently only video indexing implemented
    }
}

/***************************************************
 *
 * WriteRawSector - Write out a packet carrying data for
 *                    a control packet with irregular content.
@param rawsector data for the raw sector
@param length length of the raw sector
 ***************************************************/

void
Multiplexor::WriteRawSector(  uint8_t *rawsector,
                               unsigned int     length
	)
{
    //
    // Writing raw sectors when packs stretch over multiple sectors
    // is a recipe for disaster!
    //
    assert( packets_per_pack == 1 );
	psstrm->RawWrite( rawsector, length );
	NextPosAndSCR();

}



/******************************************************************
	OutputPadding

	generates Pack/Sys Header/Packet information for a 
	padding stream and saves the sector

	We have to pass in a special flag to cope with appalling mess VCD
	makes of audio packets (the last 20 bytes being dropped thing) 0 =
	Fill the packet completetely.  This include "audio packets" that
    include no actual audio, only a system header and padding.
@param vcd_audio_pad flag for VCD audio padding
******************************************************************/


void Multiplexor::OutputPadding (bool vcd_audio_pad)

{
    if( vcd_audio_pad )
        psstrm->CreateSector ( pack_header_ptr, sys_header_ptr,
                               0,
                               vcdapstrm,
                               false, false,
                               0, 0,
                               TIMESTAMPBITS_NO );
    else
        psstrm->CreateSector ( pack_header_ptr, sys_header_ptr,
                               0,
                               pstrm,
                               false, false,
                               0, 0,
                               TIMESTAMPBITS_NO );
    ++pstrm.nsec;
	NextPosAndSCR();

}

 /******************************************************************
 *	OutputGOPControlSector
 *  DVD System headers are carried in peculiar sectors carrying 2
 *  PrivateStream2 packets.   We're sticking 0's in the packets
 * for anything other than the substream IDs as they're
 * merely being inserted as place-holders to provide gaps the
 * DVD authoring SW can fill in later.
 *
 * Thanks to Brent Byeler who worked out this work-around.
 *
 ******************************************************************/

void Multiplexor::OutputDVDPriv2 (	)
{
    uint8_t *packet_size_field;
    uint8_t *index;
    uint8_t *sector_buf = new uint8_t[sector_size];
    unsigned int tozero;
    assert( sector_size == 2048 );
    psstrm->BufferSectorHeader( sector_buf,
                                pack_header_ptr,
                                &sys_header,
                                index );
    psstrm->BufferPacketHeader( index,
                                   PRIVATE_STR_2,
                                   2,      // MPEG 2
                                   false,  // No buffers
                                   0,
                                   0,
                                   0,      // No timestamps
                                   0,
                                   TIMESTAMPBITS_NO,
                                   0, // Natural PES header length
                                   packet_size_field,
                                   index );
    tozero = sector_buf+1024-index;
    memset( index, 0, tozero);
    index[0] = 0x00; // Substream 1 (PCI)
    index += tozero;
    psstrm->BufferPacketSize( packet_size_field, index );    

    psstrm->BufferPacketHeader( index,
                                   PRIVATE_STR_2,
                                   2,      // MPEG 2
                                   false,  // No buffers
                                   0,
                                   0,
                                   0,      // No timestamps
                                   0,
                                   TIMESTAMPBITS_NO,
                                   0, // Natural PES header length
                                   packet_size_field,
                                   index );
    tozero = sector_buf+2048-index;
    memset( index, 0, tozero );
    index[0] = 0x01; // Substream 1 (DSI)
    index += tozero;
    psstrm->BufferPacketSize( packet_size_field, index );

    WriteRawSector( sector_buf, sector_size );

	delete [] sector_buf;
}


/* 
 * Local variables:
 *  c-file-style: "stroustrup"
 *  tab-width: 4
 *  indent-tabs-mode: nil
 * End:
 */