-
Notifications
You must be signed in to change notification settings - Fork 211
/
transmuxer.js
1249 lines (1038 loc) · 39.3 KB
/
transmuxer.js
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
/**
* mux.js
*
* Copyright (c) Brightcove
* Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
*
* A stream-based mp2t to mp4 converter. This utility can be used to
* deliver mp4s to a SourceBuffer on platforms that support native
* Media Source Extensions.
*/
'use strict';
var Stream = require('../utils/stream.js');
var mp4 = require('./mp4-generator.js');
var frameUtils = require('./frame-utils');
var audioFrameUtils = require('./audio-frame-utils');
var trackDecodeInfo = require('./track-decode-info');
var m2ts = require('../m2ts/m2ts.js');
var clock = require('../utils/clock');
var AdtsStream = require('../codecs/adts.js');
var H264Stream = require('../codecs/h264').H264Stream;
var AacStream = require('../aac');
var isLikelyAacData = require('../aac/utils').isLikelyAacData;
var ONE_SECOND_IN_TS = require('../utils/clock').ONE_SECOND_IN_TS;
var AUDIO_PROPERTIES = require('../constants/audio-properties.js');
var VIDEO_PROPERTIES = require('../constants/video-properties.js');
// object types
var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
var retriggerForStream = function(key, event) {
event.stream = key;
this.trigger('log', event);
};
var addPipelineLogRetriggers = function(transmuxer, pipeline) {
var keys = Object.keys(pipeline);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
// skip non-stream keys and headOfPipeline
// which is just a duplicate
if (key === 'headOfPipeline' || !pipeline[key].on) {
continue;
}
pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
}
};
/**
* Compare two arrays (even typed) for same-ness
*/
var arrayEquals = function(a, b) {
var
i;
if (a.length !== b.length) {
return false;
}
// compare the value of each element in the array
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
var generateSegmentTimingInfo = function(
baseMediaDecodeTime,
startDts,
startPts,
endDts,
endPts,
prependedContentDuration
) {
var
ptsOffsetFromDts = startPts - startDts,
decodeDuration = endDts - startDts,
presentationDuration = endPts - startPts;
// The PTS and DTS values are based on the actual stream times from the segment,
// however, the player time values will reflect a start from the baseMediaDecodeTime.
// In order to provide relevant values for the player times, base timing info on the
// baseMediaDecodeTime and the DTS and PTS durations of the segment.
return {
start: {
dts: baseMediaDecodeTime,
pts: baseMediaDecodeTime + ptsOffsetFromDts
},
end: {
dts: baseMediaDecodeTime + decodeDuration,
pts: baseMediaDecodeTime + presentationDuration
},
prependedContentDuration: prependedContentDuration,
baseMediaDecodeTime: baseMediaDecodeTime
};
};
/**
* Constructs a single-track, ISO BMFF media segment from AAC data
* events. The output of this stream can be fed to a SourceBuffer
* configured with a suitable initialization segment.
* @param track {object} track metadata configuration
* @param options {object} transmuxer options object
* @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
* in the source; false to adjust the first segment to start at 0.
*/
AudioSegmentStream = function(track, options) {
var
adtsFrames = [],
sequenceNumber,
earliestAllowedDts = 0,
audioAppendStartTs = 0,
videoBaseMediaDecodeTime = Infinity;
options = options || {};
sequenceNumber = options.firstSequenceNumber || 0;
AudioSegmentStream.prototype.init.call(this);
this.push = function(data) {
trackDecodeInfo.collectDtsInfo(track, data);
if (track) {
AUDIO_PROPERTIES.forEach(function(prop) {
track[prop] = data[prop];
});
}
// buffer audio data until end() is called
adtsFrames.push(data);
};
this.setEarliestDts = function(earliestDts) {
earliestAllowedDts = earliestDts;
};
this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
videoBaseMediaDecodeTime = baseMediaDecodeTime;
};
this.setAudioAppendStart = function(timestamp) {
audioAppendStartTs = timestamp;
};
this.flush = function() {
var
frames,
moof,
mdat,
boxes,
frameDuration,
segmentDuration,
videoClockCyclesOfSilencePrefixed;
// return early if no audio data has been observed
if (adtsFrames.length === 0) {
this.trigger('done', 'AudioSegmentStream');
return;
}
frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
adtsFrames, track, earliestAllowedDts);
track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
track, options.keepOriginalTimestamps);
// amount of audio filled but the value is in video clock rather than audio clock
videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(
track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);
// we have to build the index from byte locations to
// samples (that is, adts frames) in the audio data
track.samples = audioFrameUtils.generateSampleTable(frames);
// concatenate the audio data to constuct the mdat
mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
adtsFrames = [];
moof = mp4.moof(sequenceNumber, [track]);
boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
// bump the sequence number for next time
sequenceNumber++;
boxes.set(moof);
boxes.set(mdat, moof.byteLength);
trackDecodeInfo.clearDtsInfo(track);
frameDuration = Math.ceil(ONE_SECOND_IN_TS * 1024 / track.samplerate);
// TODO this check was added to maintain backwards compatibility (particularly with
// tests) on adding the timingInfo event. However, it seems unlikely that there's a
// valid use-case where an init segment/data should be triggered without associated
// frames. Leaving for now, but should be looked into.
if (frames.length) {
segmentDuration = frames.length * frameDuration;
this.trigger(
'segmentTimingInfo',
generateSegmentTimingInfo(
// The audio track's baseMediaDecodeTime is in audio clock cycles, but the
// frame info is in video clock cycles. Convert to match expectation of
// listeners (that all timestamps will be based on video clock cycles).
clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate),
// frame times are already in video clock, as is segment duration
frames[0].dts,
frames[0].pts,
frames[0].dts + segmentDuration,
frames[0].pts + segmentDuration,
videoClockCyclesOfSilencePrefixed || 0
)
);
this.trigger('timingInfo', {
start: frames[0].pts,
end: frames[0].pts + segmentDuration
});
}
this.trigger('data', {track: track, boxes: boxes});
this.trigger('done', 'AudioSegmentStream');
};
this.reset = function() {
trackDecodeInfo.clearDtsInfo(track);
adtsFrames = [];
this.trigger('reset');
};
};
AudioSegmentStream.prototype = new Stream();
/**
* Constructs a single-track, ISO BMFF media segment from H264 data
* events. The output of this stream can be fed to a SourceBuffer
* configured with a suitable initialization segment.
* @param track {object} track metadata configuration
* @param options {object} transmuxer options object
* @param options.alignGopsAtEnd {boolean} If true, start from the end of the
* gopsToAlignWith list when attempting to align gop pts
* @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
* in the source; false to adjust the first segment to start at 0.
*/
VideoSegmentStream = function(track, options) {
var
sequenceNumber,
nalUnits = [],
gopsToAlignWith = [],
config,
pps;
options = options || {};
sequenceNumber = options.firstSequenceNumber || 0;
VideoSegmentStream.prototype.init.call(this);
delete track.minPTS;
this.gopCache_ = [];
/**
* Constructs a ISO BMFF segment given H264 nalUnits
* @param {Object} nalUnit A data event representing a nalUnit
* @param {String} nalUnit.nalUnitType
* @param {Object} nalUnit.config Properties for a mp4 track
* @param {Uint8Array} nalUnit.data The nalUnit bytes
* @see lib/codecs/h264.js
**/
this.push = function(nalUnit) {
trackDecodeInfo.collectDtsInfo(track, nalUnit);
// record the track config
if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
config = nalUnit.config;
track.sps = [nalUnit.data];
VIDEO_PROPERTIES.forEach(function(prop) {
track[prop] = config[prop];
}, this);
}
if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
!pps) {
pps = nalUnit.data;
track.pps = [nalUnit.data];
}
// buffer video until flush() is called
nalUnits.push(nalUnit);
};
/**
* Pass constructed ISO BMFF track and boxes on to the
* next stream in the pipeline
**/
this.flush = function() {
var
frames,
gopForFusion,
gops,
moof,
mdat,
boxes,
prependedContentDuration = 0,
firstGop,
lastGop;
// Throw away nalUnits at the start of the byte stream until
// we find the first AUD
while (nalUnits.length) {
if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
break;
}
nalUnits.shift();
}
// Return early if no video data has been observed
if (nalUnits.length === 0) {
this.resetStream_();
this.trigger('done', 'VideoSegmentStream');
return;
}
// Organize the raw nal-units into arrays that represent
// higher-level constructs such as frames and gops
// (group-of-pictures)
frames = frameUtils.groupNalsIntoFrames(nalUnits);
gops = frameUtils.groupFramesIntoGops(frames);
// If the first frame of this fragment is not a keyframe we have
// a problem since MSE (on Chrome) requires a leading keyframe.
//
// We have two approaches to repairing this situation:
// 1) GOP-FUSION:
// This is where we keep track of the GOPS (group-of-pictures)
// from previous fragments and attempt to find one that we can
// prepend to the current fragment in order to create a valid
// fragment.
// 2) KEYFRAME-PULLING:
// Here we search for the first keyframe in the fragment and
// throw away all the frames between the start of the fragment
// and that keyframe. We then extend the duration and pull the
// PTS of the keyframe forward so that it covers the time range
// of the frames that were disposed of.
//
// #1 is far prefereable over #2 which can cause "stuttering" but
// requires more things to be just right.
if (!gops[0][0].keyFrame) {
// Search for a gop for fusion from our gopCache
gopForFusion = this.getGopForFusion_(nalUnits[0], track);
if (gopForFusion) {
// in order to provide more accurate timing information about the segment, save
// the number of seconds prepended to the original segment due to GOP fusion
prependedContentDuration = gopForFusion.duration;
gops.unshift(gopForFusion);
// Adjust Gops' metadata to account for the inclusion of the
// new gop at the beginning
gops.byteLength += gopForFusion.byteLength;
gops.nalCount += gopForFusion.nalCount;
gops.pts = gopForFusion.pts;
gops.dts = gopForFusion.dts;
gops.duration += gopForFusion.duration;
} else {
// If we didn't find a candidate gop fall back to keyframe-pulling
gops = frameUtils.extendFirstKeyFrame(gops);
}
}
// Trim gops to align with gopsToAlignWith
if (gopsToAlignWith.length) {
var alignedGops;
if (options.alignGopsAtEnd) {
alignedGops = this.alignGopsAtEnd_(gops);
} else {
alignedGops = this.alignGopsAtStart_(gops);
}
if (!alignedGops) {
// save all the nals in the last GOP into the gop cache
this.gopCache_.unshift({
gop: gops.pop(),
pps: track.pps,
sps: track.sps
});
// Keep a maximum of 6 GOPs in the cache
this.gopCache_.length = Math.min(6, this.gopCache_.length);
// Clear nalUnits
nalUnits = [];
// return early no gops can be aligned with desired gopsToAlignWith
this.resetStream_();
this.trigger('done', 'VideoSegmentStream');
return;
}
// Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
// when recalculated before sending off to CoalesceStream
trackDecodeInfo.clearDtsInfo(track);
gops = alignedGops;
}
trackDecodeInfo.collectDtsInfo(track, gops);
// First, we have to build the index from byte locations to
// samples (that is, frames) in the video data
track.samples = frameUtils.generateSampleTable(gops);
// Concatenate the video data and construct the mdat
mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
track, options.keepOriginalTimestamps);
this.trigger('processedGopsInfo', gops.map(function(gop) {
return {
pts: gop.pts,
dts: gop.dts,
byteLength: gop.byteLength
};
}));
firstGop = gops[0];
lastGop = gops[gops.length - 1];
this.trigger(
'segmentTimingInfo',
generateSegmentTimingInfo(
track.baseMediaDecodeTime,
firstGop.dts,
firstGop.pts,
lastGop.dts + lastGop.duration,
lastGop.pts + lastGop.duration,
prependedContentDuration));
this.trigger('timingInfo', {
start: gops[0].pts,
end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
});
// save all the nals in the last GOP into the gop cache
this.gopCache_.unshift({
gop: gops.pop(),
pps: track.pps,
sps: track.sps
});
// Keep a maximum of 6 GOPs in the cache
this.gopCache_.length = Math.min(6, this.gopCache_.length);
// Clear nalUnits
nalUnits = [];
this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
this.trigger('timelineStartInfo', track.timelineStartInfo);
moof = mp4.moof(sequenceNumber, [track]);
// it would be great to allocate this array up front instead of
// throwing away hundreds of media segment fragments
boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
// Bump the sequence number for next time
sequenceNumber++;
boxes.set(moof);
boxes.set(mdat, moof.byteLength);
this.trigger('data', {track: track, boxes: boxes});
this.resetStream_();
// Continue with the flush process now
this.trigger('done', 'VideoSegmentStream');
};
this.reset = function() {
this.resetStream_();
nalUnits = [];
this.gopCache_.length = 0;
gopsToAlignWith.length = 0;
this.trigger('reset');
};
this.resetStream_ = function() {
trackDecodeInfo.clearDtsInfo(track);
// reset config and pps because they may differ across segments
// for instance, when we are rendition switching
config = undefined;
pps = undefined;
};
// Search for a candidate Gop for gop-fusion from the gop cache and
// return it or return null if no good candidate was found
this.getGopForFusion_ = function(nalUnit) {
var
halfSecond = 45000, // Half-a-second in a 90khz clock
allowableOverlap = 10000, // About 3 frames @ 30fps
nearestDistance = Infinity,
dtsDistance,
nearestGopObj,
currentGop,
currentGopObj,
i;
// Search for the GOP nearest to the beginning of this nal unit
for (i = 0; i < this.gopCache_.length; i++) {
currentGopObj = this.gopCache_[i];
currentGop = currentGopObj.gop;
// Reject Gops with different SPS or PPS
if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
!(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
continue;
}
// Reject Gops that would require a negative baseMediaDecodeTime
if (currentGop.dts < track.timelineStartInfo.dts) {
continue;
}
// The distance between the end of the gop and the start of the nalUnit
dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
// Only consider GOPS that start before the nal unit and end within
// a half-second of the nal unit
if (dtsDistance >= -allowableOverlap &&
dtsDistance <= halfSecond) {
// Always use the closest GOP we found if there is more than
// one candidate
if (!nearestGopObj ||
nearestDistance > dtsDistance) {
nearestGopObj = currentGopObj;
nearestDistance = dtsDistance;
}
}
}
if (nearestGopObj) {
return nearestGopObj.gop;
}
return null;
};
// trim gop list to the first gop found that has a matching pts with a gop in the list
// of gopsToAlignWith starting from the START of the list
this.alignGopsAtStart_ = function(gops) {
var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
byteLength = gops.byteLength;
nalCount = gops.nalCount;
duration = gops.duration;
alignIndex = gopIndex = 0;
while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
align = gopsToAlignWith[alignIndex];
gop = gops[gopIndex];
if (align.pts === gop.pts) {
break;
}
if (gop.pts > align.pts) {
// this current gop starts after the current gop we want to align on, so increment
// align index
alignIndex++;
continue;
}
// current gop starts before the current gop we want to align on. so increment gop
// index
gopIndex++;
byteLength -= gop.byteLength;
nalCount -= gop.nalCount;
duration -= gop.duration;
}
if (gopIndex === 0) {
// no gops to trim
return gops;
}
if (gopIndex === gops.length) {
// all gops trimmed, skip appending all gops
return null;
}
alignedGops = gops.slice(gopIndex);
alignedGops.byteLength = byteLength;
alignedGops.duration = duration;
alignedGops.nalCount = nalCount;
alignedGops.pts = alignedGops[0].pts;
alignedGops.dts = alignedGops[0].dts;
return alignedGops;
};
// trim gop list to the first gop found that has a matching pts with a gop in the list
// of gopsToAlignWith starting from the END of the list
this.alignGopsAtEnd_ = function(gops) {
var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
alignIndex = gopsToAlignWith.length - 1;
gopIndex = gops.length - 1;
alignEndIndex = null;
matchFound = false;
while (alignIndex >= 0 && gopIndex >= 0) {
align = gopsToAlignWith[alignIndex];
gop = gops[gopIndex];
if (align.pts === gop.pts) {
matchFound = true;
break;
}
if (align.pts > gop.pts) {
alignIndex--;
continue;
}
if (alignIndex === gopsToAlignWith.length - 1) {
// gop.pts is greater than the last alignment candidate. If no match is found
// by the end of this loop, we still want to append gops that come after this
// point
alignEndIndex = gopIndex;
}
gopIndex--;
}
if (!matchFound && alignEndIndex === null) {
return null;
}
var trimIndex;
if (matchFound) {
trimIndex = gopIndex;
} else {
trimIndex = alignEndIndex;
}
if (trimIndex === 0) {
return gops;
}
var alignedGops = gops.slice(trimIndex);
var metadata = alignedGops.reduce(function(total, gop) {
total.byteLength += gop.byteLength;
total.duration += gop.duration;
total.nalCount += gop.nalCount;
return total;
}, { byteLength: 0, duration: 0, nalCount: 0 });
alignedGops.byteLength = metadata.byteLength;
alignedGops.duration = metadata.duration;
alignedGops.nalCount = metadata.nalCount;
alignedGops.pts = alignedGops[0].pts;
alignedGops.dts = alignedGops[0].dts;
return alignedGops;
};
this.alignGopsWith = function(newGopsToAlignWith) {
gopsToAlignWith = newGopsToAlignWith;
};
};
VideoSegmentStream.prototype = new Stream();
/**
* A Stream that can combine multiple streams (ie. audio & video)
* into a single output segment for MSE. Also supports audio-only
* and video-only streams.
* @param options {object} transmuxer options object
* @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
* in the source; false to adjust the first segment to start at media timeline start.
*/
CoalesceStream = function(options, metadataStream) {
// Number of Tracks per output segment
// If greater than 1, we combine multiple
// tracks into a single segment
this.numberOfTracks = 0;
this.metadataStream = metadataStream;
options = options || {};
if (typeof options.remux !== 'undefined') {
this.remuxTracks = !!options.remux;
} else {
this.remuxTracks = true;
}
if (typeof options.keepOriginalTimestamps === 'boolean') {
this.keepOriginalTimestamps = options.keepOriginalTimestamps;
} else {
this.keepOriginalTimestamps = false;
}
this.pendingTracks = [];
this.videoTrack = null;
this.pendingBoxes = [];
this.pendingCaptions = [];
this.pendingMetadata = [];
this.pendingBytes = 0;
this.emittedTracks = 0;
CoalesceStream.prototype.init.call(this);
// Take output from multiple
this.push = function(output) {
// buffer incoming captions until the associated video segment
// finishes
if (output.content || output.text) {
return this.pendingCaptions.push(output);
}
// buffer incoming id3 tags until the final flush
if (output.frames) {
return this.pendingMetadata.push(output);
}
// Add this track to the list of pending tracks and store
// important information required for the construction of
// the final segment
this.pendingTracks.push(output.track);
this.pendingBytes += output.boxes.byteLength;
// TODO: is there an issue for this against chrome?
// We unshift audio and push video because
// as of Chrome 75 when switching from
// one init segment to another if the video
// mdat does not appear after the audio mdat
// only audio will play for the duration of our transmux.
if (output.track.type === 'video') {
this.videoTrack = output.track;
this.pendingBoxes.push(output.boxes);
}
if (output.track.type === 'audio') {
this.audioTrack = output.track;
this.pendingBoxes.unshift(output.boxes);
}
};
};
CoalesceStream.prototype = new Stream();
CoalesceStream.prototype.flush = function(flushSource) {
var
offset = 0,
event = {
captions: [],
captionStreams: {},
metadata: [],
info: {}
},
caption,
id3,
initSegment,
timelineStartPts = 0,
i;
if (this.pendingTracks.length < this.numberOfTracks) {
if (flushSource !== 'VideoSegmentStream' &&
flushSource !== 'AudioSegmentStream') {
// Return because we haven't received a flush from a data-generating
// portion of the segment (meaning that we have only recieved meta-data
// or captions.)
return;
} else if (this.remuxTracks) {
// Return until we have enough tracks from the pipeline to remux (if we
// are remuxing audio and video into a single MP4)
return;
} else if (this.pendingTracks.length === 0) {
// In the case where we receive a flush without any data having been
// received we consider it an emitted track for the purposes of coalescing
// `done` events.
// We do this for the case where there is an audio and video track in the
// segment but no audio data. (seen in several playlists with alternate
// audio tracks and no audio present in the main TS segments.)
this.emittedTracks++;
if (this.emittedTracks >= this.numberOfTracks) {
this.trigger('done');
this.emittedTracks = 0;
}
return;
}
}
if (this.videoTrack) {
timelineStartPts = this.videoTrack.timelineStartInfo.pts;
VIDEO_PROPERTIES.forEach(function(prop) {
event.info[prop] = this.videoTrack[prop];
}, this);
} else if (this.audioTrack) {
timelineStartPts = this.audioTrack.timelineStartInfo.pts;
AUDIO_PROPERTIES.forEach(function(prop) {
event.info[prop] = this.audioTrack[prop];
}, this);
}
if (this.videoTrack || this.audioTrack) {
if (this.pendingTracks.length === 1) {
event.type = this.pendingTracks[0].type;
} else {
event.type = 'combined';
}
this.emittedTracks += this.pendingTracks.length;
initSegment = mp4.initSegment(this.pendingTracks);
// Create a new typed array to hold the init segment
event.initSegment = new Uint8Array(initSegment.byteLength);
// Create an init segment containing a moov
// and track definitions
event.initSegment.set(initSegment);
// Create a new typed array to hold the moof+mdats
event.data = new Uint8Array(this.pendingBytes);
// Append each moof+mdat (one per track) together
for (i = 0; i < this.pendingBoxes.length; i++) {
event.data.set(this.pendingBoxes[i], offset);
offset += this.pendingBoxes[i].byteLength;
}
// Translate caption PTS times into second offsets to match the
// video timeline for the segment, and add track info
for (i = 0; i < this.pendingCaptions.length; i++) {
caption = this.pendingCaptions[i];
caption.startTime = clock.metadataTsToSeconds(
caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
caption.endTime = clock.metadataTsToSeconds(
caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
event.captionStreams[caption.stream] = true;
event.captions.push(caption);
}
// Translate ID3 frame PTS times into second offsets to match the
// video timeline for the segment
for (i = 0; i < this.pendingMetadata.length; i++) {
id3 = this.pendingMetadata[i];
id3.cueTime = clock.metadataTsToSeconds(
id3.pts, timelineStartPts, this.keepOriginalTimestamps);
event.metadata.push(id3);
}
// We add this to every single emitted segment even though we only need
// it for the first
event.metadata.dispatchType = this.metadataStream.dispatchType;
// Reset stream state
this.pendingTracks.length = 0;
this.videoTrack = null;
this.pendingBoxes.length = 0;
this.pendingCaptions.length = 0;
this.pendingBytes = 0;
this.pendingMetadata.length = 0;
// Emit the built segment
// We include captions and ID3 tags for backwards compatibility,
// ideally we should send only video and audio in the data event
this.trigger('data', event);
// Emit each caption to the outside world
// Ideally, this would happen immediately on parsing captions,
// but we need to ensure that video data is sent back first
// so that caption timing can be adjusted to match video timing
for (i = 0; i < event.captions.length; i++) {
caption = event.captions[i];
this.trigger('caption', caption);
}
// Emit each id3 tag to the outside world
// Ideally, this would happen immediately on parsing the tag,
// but we need to ensure that video data is sent back first
// so that ID3 frame timing can be adjusted to match video timing
for (i = 0; i < event.metadata.length; i++) {
id3 = event.metadata[i];
this.trigger('id3Frame', id3);
}
}
// Only emit `done` if all tracks have been flushed and emitted
if (this.emittedTracks >= this.numberOfTracks) {
this.trigger('done');
this.emittedTracks = 0;
}
};
CoalesceStream.prototype.setRemux = function(val) {
this.remuxTracks = val;
};
/**
* A Stream that expects MP2T binary data as input and produces
* corresponding media segments, suitable for use with Media Source
* Extension (MSE) implementations that support the ISO BMFF byte
* stream format, like Chrome.
*/
Transmuxer = function(options) {
var
self = this,
hasFlushed = true,
videoTrack,
audioTrack;
Transmuxer.prototype.init.call(this);
options = options || {};
this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
this.transmuxPipeline_ = {};
this.setupAacPipeline = function() {
var pipeline = {};
this.transmuxPipeline_ = pipeline;
pipeline.type = 'aac';
pipeline.metadataStream = new m2ts.MetadataStream();
// set up the parsing pipeline
pipeline.aacStream = new AacStream();
pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
pipeline.adtsStream = new AdtsStream();
pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
pipeline.headOfPipeline = pipeline.aacStream;
pipeline.aacStream
.pipe(pipeline.audioTimestampRolloverStream)
.pipe(pipeline.adtsStream);
pipeline.aacStream
.pipe(pipeline.timedMetadataTimestampRolloverStream)
.pipe(pipeline.metadataStream)
.pipe(pipeline.coalesceStream);
pipeline.metadataStream.on('timestamp', function(frame) {
pipeline.aacStream.setTimestamp(frame.timeStamp);
});
pipeline.aacStream.on('data', function(data) {
if ((data.type !== 'timed-metadata' && data.type !== 'audio') || pipeline.audioSegmentStream) {
return;
}
audioTrack = audioTrack || {
timelineStartInfo: {
baseMediaDecodeTime: self.baseMediaDecodeTime
},
codec: 'adts',
type: 'audio'
};
// hook up the audio segment stream to the first track with aac data
pipeline.coalesceStream.numberOfTracks++;
pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
pipeline.audioSegmentStream.on('timingInfo',
self.trigger.bind(self, 'audioTimingInfo'));
// Set up the final part of the audio pipeline
pipeline.adtsStream
.pipe(pipeline.audioSegmentStream)
.pipe(pipeline.coalesceStream);
// emit pmt info
self.trigger('trackinfo', {
hasAudio: !!audioTrack,
hasVideo: !!videoTrack
});
});
// Re-emit any data coming from the coalesce stream to the outside world
pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
// Let the consumer know we have finished flushing the entire pipeline
pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
addPipelineLogRetriggers(this, pipeline);
};
this.setupTsPipeline = function() {