forked from Momo707577045/m3u8-downloader
-
Notifications
You must be signed in to change notification settings - Fork 7
/
mux-mp4.js
7051 lines (6119 loc) · 209 KB
/
mux-mp4.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
(function(f){var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.muxjs = f()})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) Brightcove
* Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
*
* A stream-based aac 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(31);
var aacUtils = require(2);
// Constants
var AacStream;
/**
* Splits an incoming stream of binary data into ADTS and ID3 Frames.
*/
AacStream = function() {
var
everything = new Uint8Array(),
timeStamp = 0;
AacStream.prototype.init.call(this);
this.setTimestamp = function(timestamp) {
timeStamp = timestamp;
};
this.push = function(bytes) {
var
frameSize = 0,
byteIndex = 0,
bytesLeft,
chunk,
packet,
tempLength;
// If there are bytes remaining from the last segment, prepend them to the
// bytes that were pushed in
if (everything.length) {
tempLength = everything.length;
everything = new Uint8Array(bytes.byteLength + tempLength);
everything.set(everything.subarray(0, tempLength));
everything.set(bytes, tempLength);
} else {
everything = bytes;
}
while (everything.length - byteIndex >= 3) {
if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
(everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
(everything[byteIndex + 2] === '3'.charCodeAt(0))) {
// Exit early because we don't have enough to parse
// the ID3 tag header
if (everything.length - byteIndex < 10) {
break;
}
// check framesize
frameSize = aacUtils.parseId3TagSize(everything, byteIndex);
// Exit early if we don't have enough in the buffer
// to emit a full packet
// Add to byteIndex to support multiple ID3 tags in sequence
if (byteIndex + frameSize > everything.length) {
break;
}
chunk = {
type: 'timed-metadata',
data: everything.subarray(byteIndex, byteIndex + frameSize)
};
this.trigger('data', chunk);
byteIndex += frameSize;
continue;
} else if (((everything[byteIndex] & 0xff) === 0xff) &&
((everything[byteIndex + 1] & 0xf0) === 0xf0)) {
// Exit early because we don't have enough to parse
// the ADTS frame header
if (everything.length - byteIndex < 7) {
break;
}
frameSize = aacUtils.parseAdtsSize(everything, byteIndex);
// Exit early if we don't have enough in the buffer
// to emit a full packet
if (byteIndex + frameSize > everything.length) {
break;
}
packet = {
type: 'audio',
data: everything.subarray(byteIndex, byteIndex + frameSize),
pts: timeStamp,
dts: timeStamp
};
this.trigger('data', packet);
byteIndex += frameSize;
continue;
}
byteIndex++;
}
bytesLeft = everything.length - byteIndex;
if (bytesLeft > 0) {
everything = everything.subarray(byteIndex);
} else {
everything = new Uint8Array();
}
};
this.reset = function() {
everything = new Uint8Array();
this.trigger('reset');
};
this.endTimeline = function() {
everything = new Uint8Array();
this.trigger('endedtimeline');
};
};
AacStream.prototype = new Stream();
module.exports = AacStream;
},{"2":2,"31":31}],2:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) Brightcove
* Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
*
* Utilities to detect basic properties and metadata about Aac data.
*/
'use strict';
var ADTS_SAMPLING_FREQUENCIES = [
96000,
88200,
64000,
48000,
44100,
32000,
24000,
22050,
16000,
12000,
11025,
8000,
7350
];
var parseId3TagSize = function(header, byteIndex) {
var
returnSize = (header[byteIndex + 6] << 21) |
(header[byteIndex + 7] << 14) |
(header[byteIndex + 8] << 7) |
(header[byteIndex + 9]),
flags = header[byteIndex + 5],
footerPresent = (flags & 16) >> 4;
// if we get a negative returnSize clamp it to 0
returnSize = returnSize >= 0 ? returnSize : 0;
if (footerPresent) {
return returnSize + 20;
}
return returnSize + 10;
};
var getId3Offset = function(data, offset) {
if (data.length - offset < 10 ||
data[offset] !== 'I'.charCodeAt(0) ||
data[offset + 1] !== 'D'.charCodeAt(0) ||
data[offset + 2] !== '3'.charCodeAt(0)) {
return offset;
}
offset += parseId3TagSize(data, offset);
return getId3Offset(data, offset);
};
// TODO: use vhs-utils
var isLikelyAacData = function(data) {
var offset = getId3Offset(data, 0);
return data.length >= offset + 2 &&
(data[offset] & 0xFF) === 0xFF &&
(data[offset + 1] & 0xF0) === 0xF0 &&
// verify that the 2 layer bits are 0, aka this
// is not mp3 data but aac data.
(data[offset + 1] & 0x16) === 0x10;
};
var parseSyncSafeInteger = function(data) {
return (data[0] << 21) |
(data[1] << 14) |
(data[2] << 7) |
(data[3]);
};
// return a percent-encoded representation of the specified byte range
// @see http://en.wikipedia.org/wiki/Percent-encoding
var percentEncode = function(bytes, start, end) {
var i, result = '';
for (i = start; i < end; i++) {
result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
}
return result;
};
// return the string representation of the specified byte range,
// interpreted as ISO-8859-1.
var parseIso88591 = function(bytes, start, end) {
return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
};
var parseAdtsSize = function(header, byteIndex) {
var
lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
middle = header[byteIndex + 4] << 3,
highTwo = header[byteIndex + 3] & 0x3 << 11;
return (highTwo | middle) | lowThree;
};
var parseType = function(header, byteIndex) {
if ((header[byteIndex] === 'I'.charCodeAt(0)) &&
(header[byteIndex + 1] === 'D'.charCodeAt(0)) &&
(header[byteIndex + 2] === '3'.charCodeAt(0))) {
return 'timed-metadata';
} else if ((header[byteIndex] & 0xff === 0xff) &&
((header[byteIndex + 1] & 0xf0) === 0xf0)) {
return 'audio';
}
return null;
};
var parseSampleRate = function(packet) {
var i = 0;
while (i + 5 < packet.length) {
if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
// If a valid header was not found, jump one forward and attempt to
// find a valid ADTS header starting at the next byte
i++;
continue;
}
return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
}
return null;
};
var parseAacTimestamp = function(packet) {
var frameStart, frameSize, frame, frameHeader;
// find the start of the first frame and the end of the tag
frameStart = 10;
if (packet[5] & 0x40) {
// advance the frame start past the extended header
frameStart += 4; // header size field
frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
}
// parse one or more ID3 frames
// http://id3.org/id3v2.3.0#ID3v2_frame_overview
do {
// determine the number of bytes in this frame
frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
if (frameSize < 1) {
return null;
}
frameHeader = String.fromCharCode(packet[frameStart],
packet[frameStart + 1],
packet[frameStart + 2],
packet[frameStart + 3]);
if (frameHeader === 'PRIV') {
frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
for (var i = 0; i < frame.byteLength; i++) {
if (frame[i] === 0) {
var owner = parseIso88591(frame, 0, i);
if (owner === 'com.apple.streaming.transportStreamTimestamp') {
var d = frame.subarray(i + 1);
var size = ((d[3] & 0x01) << 30) |
(d[4] << 22) |
(d[5] << 14) |
(d[6] << 6) |
(d[7] >>> 2);
size *= 4;
size += d[7] & 0x03;
return size;
}
break;
}
}
}
frameStart += 10; // advance past the frame header
frameStart += frameSize; // advance past the frame body
} while (frameStart < packet.byteLength);
return null;
};
module.exports = {
isLikelyAacData: isLikelyAacData,
parseId3TagSize: parseId3TagSize,
parseAdtsSize: parseAdtsSize,
parseType: parseType,
parseSampleRate: parseSampleRate,
parseAacTimestamp: parseAacTimestamp
};
},{}],3:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) Brightcove
* Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
*/
'use strict';
var Stream = require(31);
var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
var AdtsStream;
var
ADTS_SAMPLING_FREQUENCIES = [
96000,
88200,
64000,
48000,
44100,
32000,
24000,
22050,
16000,
12000,
11025,
8000,
7350
];
/*
* Accepts a ElementaryStream and emits data events with parsed
* AAC Audio Frames of the individual packets. Input audio in ADTS
* format is unpacked and re-emitted as AAC frames.
*
* @see http://wiki.multimedia.cx/index.php?title=ADTS
* @see http://wiki.multimedia.cx/?title=Understanding_AAC
*/
AdtsStream = function(handlePartialSegments) {
var
buffer,
frameNum = 0;
AdtsStream.prototype.init.call(this);
this.push = function(packet) {
var
i = 0,
frameLength,
protectionSkipBytes,
frameEnd,
oldBuffer,
sampleCount,
adtsFrameDuration;
if (!handlePartialSegments) {
frameNum = 0;
}
if (packet.type !== 'audio') {
// ignore non-audio data
return;
}
// Prepend any data in the buffer to the input data so that we can parse
// aac frames the cross a PES packet boundary
if (buffer) {
oldBuffer = buffer;
buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
buffer.set(oldBuffer);
buffer.set(packet.data, oldBuffer.byteLength);
} else {
buffer = packet.data;
}
// unpack any ADTS frames which have been fully received
// for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
while (i + 5 < buffer.length) {
// Look for the start of an ADTS header..
if ((buffer[i] !== 0xFF) || (buffer[i + 1] & 0xF6) !== 0xF0) {
// If a valid header was not found, jump one forward and attempt to
// find a valid ADTS header starting at the next byte
i++;
continue;
}
// The protection skip bit tells us if we have 2 bytes of CRC data at the
// end of the ADTS header
protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;
// Frame length is a 13 bit integer starting 16 bits from the
// end of the sync sequence
frameLength = ((buffer[i + 3] & 0x03) << 11) |
(buffer[i + 4] << 3) |
((buffer[i + 5] & 0xe0) >> 5);
sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
adtsFrameDuration = (sampleCount * ONE_SECOND_IN_TS) /
ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
frameEnd = i + frameLength;
// If we don't have enough data to actually finish this ADTS frame, return
// and wait for more data
if (buffer.byteLength < frameEnd) {
return;
}
// Otherwise, deliver the complete AAC frame
this.trigger('data', {
pts: packet.pts + (frameNum * adtsFrameDuration),
dts: packet.dts + (frameNum * adtsFrameDuration),
sampleCount: sampleCount,
audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
channelcount: ((buffer[i + 2] & 1) << 2) |
((buffer[i + 3] & 0xc0) >>> 6),
samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
// assume ISO/IEC 14496-12 AudioSampleEntry default of 16
samplesize: 16,
data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
});
frameNum++;
// If the buffer is empty, clear it and return
if (buffer.byteLength === frameEnd) {
buffer = undefined;
return;
}
// Remove the finished frame from the buffer and start the process again
buffer = buffer.subarray(frameEnd);
}
};
this.flush = function() {
frameNum = 0;
this.trigger('done');
};
this.reset = function() {
buffer = void 0;
this.trigger('reset');
};
this.endTimeline = function() {
buffer = void 0;
this.trigger('endedtimeline');
};
};
AdtsStream.prototype = new Stream();
module.exports = AdtsStream;
},{"29":29,"31":31}],4:[function(require,module,exports){
/**
* mux.js
*
* Copyright (c) Brightcove
* Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
*/
'use strict';
var Stream = require(31);
var ExpGolomb = require(30);
var H264Stream, NalByteStream;
var PROFILES_WITH_OPTIONAL_SPS_DATA;
/**
* Accepts a NAL unit byte stream and unpacks the embedded NAL units.
*/
NalByteStream = function() {
var
syncPoint = 0,
i,
buffer;
NalByteStream.prototype.init.call(this);
/*
* Scans a byte stream and triggers a data event with the NAL units found.
* @param {Object} data Event received from H264Stream
* @param {Uint8Array} data.data The h264 byte stream to be scanned
*
* @see H264Stream.push
*/
this.push = function(data) {
var swapBuffer;
if (!buffer) {
buffer = data.data;
} else {
swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
swapBuffer.set(buffer);
swapBuffer.set(data.data, buffer.byteLength);
buffer = swapBuffer;
}
var len = buffer.byteLength;
// Rec. ITU-T H.264, Annex B
// scan for NAL unit boundaries
// a match looks like this:
// 0 0 1 .. NAL .. 0 0 1
// ^ sync point ^ i
// or this:
// 0 0 1 .. NAL .. 0 0 0
// ^ sync point ^ i
// advance the sync point to a NAL start, if necessary
for (; syncPoint < len - 3; syncPoint++) {
if (buffer[syncPoint + 2] === 1) {
// the sync point is properly aligned
i = syncPoint + 5;
break;
}
}
while (i < len) {
// look at the current byte to determine if we've hit the end of
// a NAL unit boundary
switch (buffer[i]) {
case 0:
// skip past non-sync sequences
if (buffer[i - 1] !== 0) {
i += 2;
break;
} else if (buffer[i - 2] !== 0) {
i++;
break;
}
// deliver the NAL unit if it isn't empty
if (syncPoint + 3 !== i - 2) {
this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
}
// drop trailing zeroes
do {
i++;
} while (buffer[i] !== 1 && i < len);
syncPoint = i - 2;
i += 3;
break;
case 1:
// skip past non-sync sequences
if (buffer[i - 1] !== 0 ||
buffer[i - 2] !== 0) {
i += 3;
break;
}
// deliver the NAL unit
this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
syncPoint = i - 2;
i += 3;
break;
default:
// the current byte isn't a one or zero, so it cannot be part
// of a sync sequence
i += 3;
break;
}
}
// filter out the NAL units that were delivered
buffer = buffer.subarray(syncPoint);
i -= syncPoint;
syncPoint = 0;
};
this.reset = function() {
buffer = null;
syncPoint = 0;
this.trigger('reset');
};
this.flush = function() {
// deliver the last buffered NAL unit
if (buffer && buffer.byteLength > 3) {
this.trigger('data', buffer.subarray(syncPoint + 3));
}
// reset the stream state
buffer = null;
syncPoint = 0;
this.trigger('done');
};
this.endTimeline = function() {
this.flush();
this.trigger('endedtimeline');
};
};
NalByteStream.prototype = new Stream();
// values of profile_idc that indicate additional fields are included in the SPS
// see Recommendation ITU-T H.264 (4/2013),
// 7.3.2.1.1 Sequence parameter set data syntax
PROFILES_WITH_OPTIONAL_SPS_DATA = {
100: true,
110: true,
122: true,
244: true,
44: true,
83: true,
86: true,
118: true,
128: true,
138: true,
139: true,
134: true
};
/**
* Accepts input from a ElementaryStream and produces H.264 NAL unit data
* events.
*/
H264Stream = function() {
var
nalByteStream = new NalByteStream(),
self,
trackId,
currentPts,
currentDts,
discardEmulationPreventionBytes,
readSequenceParameterSet,
skipScalingList;
H264Stream.prototype.init.call(this);
self = this;
/*
* Pushes a packet from a stream onto the NalByteStream
*
* @param {Object} packet - A packet received from a stream
* @param {Uint8Array} packet.data - The raw bytes of the packet
* @param {Number} packet.dts - Decode timestamp of the packet
* @param {Number} packet.pts - Presentation timestamp of the packet
* @param {Number} packet.trackId - The id of the h264 track this packet came from
* @param {('video'|'audio')} packet.type - The type of packet
*
*/
this.push = function(packet) {
if (packet.type !== 'video') {
return;
}
trackId = packet.trackId;
currentPts = packet.pts;
currentDts = packet.dts;
nalByteStream.push(packet);
};
/*
* Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
* for the NALUs to the next stream component.
* Also, preprocess caption and sequence parameter NALUs.
*
* @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
* @see NalByteStream.push
*/
nalByteStream.on('data', function(data) {
var
event = {
trackId: trackId,
pts: currentPts,
dts: currentDts,
data: data
};
switch (data[0] & 0x1f) {
case 0x05:
event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
break;
case 0x06:
event.nalUnitType = 'sei_rbsp';
event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
break;
case 0x07:
event.nalUnitType = 'seq_parameter_set_rbsp';
event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
event.config = readSequenceParameterSet(event.escapedRBSP);
break;
case 0x08:
event.nalUnitType = 'pic_parameter_set_rbsp';
break;
case 0x09:
event.nalUnitType = 'access_unit_delimiter_rbsp';
break;
default:
break;
}
// This triggers data on the H264Stream
self.trigger('data', event);
});
nalByteStream.on('done', function() {
self.trigger('done');
});
nalByteStream.on('partialdone', function() {
self.trigger('partialdone');
});
nalByteStream.on('reset', function() {
self.trigger('reset');
});
nalByteStream.on('endedtimeline', function() {
self.trigger('endedtimeline');
});
this.flush = function() {
nalByteStream.flush();
};
this.partialFlush = function() {
nalByteStream.partialFlush();
};
this.reset = function() {
nalByteStream.reset();
};
this.endTimeline = function() {
nalByteStream.endTimeline();
};
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count {number} the number of entries in this scaling list
* @param expGolombDecoder {object} an ExpGolomb pointed to the
* start of a scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
skipScalingList = function(count, expGolombDecoder) {
var
lastScale = 8,
nextScale = 8,
j,
deltaScale;
for (j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = expGolombDecoder.readExpGolomb();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = (nextScale === 0) ? lastScale : nextScale;
}
};
/**
* Expunge any "Emulation Prevention" bytes from a "Raw Byte
* Sequence Payload"
* @param data {Uint8Array} the bytes of a RBSP from a NAL
* unit
* @return {Uint8Array} the RBSP without any Emulation
* Prevention Bytes
*/
discardEmulationPreventionBytes = function(data) {
var
length = data.byteLength,
emulationPreventionBytesPositions = [],
i = 1,
newLength, newData;
// Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
emulationPreventionBytesPositions.push(i + 2);
i += 2;
} else {
i++;
}
}
// If no Emulation Prevention Bytes were found just return the original
// array
if (emulationPreventionBytesPositions.length === 0) {
return data;
}
// Create a new array to hold the NAL unit data
newLength = length - emulationPreventionBytesPositions.length;
newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === emulationPreventionBytesPositions[0]) {
// Skip this byte
sourceIndex++;
// Remove this position index
emulationPreventionBytesPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
};
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
readSequenceParameterSet = function(data) {
var
frameCropLeftOffset = 0,
frameCropRightOffset = 0,
frameCropTopOffset = 0,
frameCropBottomOffset = 0,
sarScale = 1,
expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
chromaFormatIdc, picOrderCntType,
numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
picHeightInMapUnitsMinus1,
frameMbsOnlyFlag,
scalingListCount,
sarRatio,
aspectRatioIdc,
i;
expGolombDecoder = new ExpGolomb(data);
profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
if (chromaFormatIdc === 3) {
expGolombDecoder.skipBits(1); // separate_colour_plane_flag
}
expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16, expGolombDecoder);
} else {
skipScalingList(64, expGolombDecoder);
}
}
}
}
}
expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
if (picOrderCntType === 0) {
expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
}
}
expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
frameMbsOnlyFlag = expGolombDecoder.readBits(1);
if (frameMbsOnlyFlag === 0) {
expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
}
expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
}
if (expGolombDecoder.readBoolean()) {
// vui_parameters_present_flag
if (expGolombDecoder.readBoolean()) {
// aspect_ratio_info_present_flag
aspectRatioIdc = expGolombDecoder.readUnsignedByte();
switch (aspectRatioIdc) {
case 1: sarRatio = [1, 1]; break;
case 2: sarRatio = [12, 11]; break;
case 3: sarRatio = [10, 11]; break;
case 4: sarRatio = [16, 11]; break;
case 5: sarRatio = [40, 33]; break;
case 6: sarRatio = [24, 11]; break;
case 7: sarRatio = [20, 11]; break;
case 8: sarRatio = [32, 11]; break;
case 9: sarRatio = [80, 33]; break;
case 10: sarRatio = [18, 11]; break;
case 11: sarRatio = [15, 11]; break;
case 12: sarRatio = [64, 33]; break;
case 13: sarRatio = [160, 99]; break;
case 14: sarRatio = [4, 3]; break;
case 15: sarRatio = [3, 2]; break;
case 16: sarRatio = [2, 1]; break;
case 255: {
sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
expGolombDecoder.readUnsignedByte(),
expGolombDecoder.readUnsignedByte() << 8 |
expGolombDecoder.readUnsignedByte() ];
break;
}
}
if (sarRatio) {
sarScale = sarRatio[0] / sarRatio[1];
}
}
}
return {
profileIdc: profileIdc,
levelIdc: levelIdc,
profileCompatibility: profileCompatibility,
width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2),
sarRatio: sarRatio
};
};
};
H264Stream.prototype = new Stream();
module.exports = {
H264Stream: H264Stream,
NalByteStream: NalByteStream
};
},{"30":30,"31":31}],5:[function(require,module,exports){
// constants
var AUDIO_PROPERTIES = [
'audioobjecttype',
'channelcount',
'samplerate',
'samplingfrequencyindex',
'samplesize'
];
module.exports = AUDIO_PROPERTIES;
},{}],6:[function(require,module,exports){
var VIDEO_PROPERTIES = [
'width',
'height',
'profileIdc',
'levelIdc',
'profileCompatibility',
'sarRatio'
];
module.exports = VIDEO_PROPERTIES;
},{}],7:[function(require,module,exports){
/**
* mux.js
*