jmuxer 2.0.3 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2811 +1 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('stream')) :
3
- typeof define === 'function' && define.amd ? define(['stream'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.JMuxer = factory(global.stream));
5
- })(this, (function (stream) { 'use strict';
6
-
7
- function _typeof(obj) {
8
- "@babel/helpers - typeof";
9
-
10
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
11
- _typeof = function (obj) {
12
- return typeof obj;
13
- };
14
- } else {
15
- _typeof = function (obj) {
16
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
17
- };
18
- }
19
-
20
- return _typeof(obj);
21
- }
22
-
23
- function _classCallCheck(instance, Constructor) {
24
- if (!(instance instanceof Constructor)) {
25
- throw new TypeError("Cannot call a class as a function");
26
- }
27
- }
28
-
29
- function _defineProperties(target, props) {
30
- for (var i = 0; i < props.length; i++) {
31
- var descriptor = props[i];
32
- descriptor.enumerable = descriptor.enumerable || false;
33
- descriptor.configurable = true;
34
- if ("value" in descriptor) descriptor.writable = true;
35
- Object.defineProperty(target, descriptor.key, descriptor);
36
- }
37
- }
38
-
39
- function _createClass(Constructor, protoProps, staticProps) {
40
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
41
- if (staticProps) _defineProperties(Constructor, staticProps);
42
- return Constructor;
43
- }
44
-
45
- function _defineProperty(obj, key, value) {
46
- if (key in obj) {
47
- Object.defineProperty(obj, key, {
48
- value: value,
49
- enumerable: true,
50
- configurable: true,
51
- writable: true
52
- });
53
- } else {
54
- obj[key] = value;
55
- }
56
-
57
- return obj;
58
- }
59
-
60
- function _inherits(subClass, superClass) {
61
- if (typeof superClass !== "function" && superClass !== null) {
62
- throw new TypeError("Super expression must either be null or a function");
63
- }
64
-
65
- subClass.prototype = Object.create(superClass && superClass.prototype, {
66
- constructor: {
67
- value: subClass,
68
- writable: true,
69
- configurable: true
70
- }
71
- });
72
- if (superClass) _setPrototypeOf(subClass, superClass);
73
- }
74
-
75
- function _getPrototypeOf(o) {
76
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
77
- return o.__proto__ || Object.getPrototypeOf(o);
78
- };
79
- return _getPrototypeOf(o);
80
- }
81
-
82
- function _setPrototypeOf(o, p) {
83
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
84
- o.__proto__ = p;
85
- return o;
86
- };
87
-
88
- return _setPrototypeOf(o, p);
89
- }
90
-
91
- function _isNativeReflectConstruct() {
92
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
93
- if (Reflect.construct.sham) return false;
94
- if (typeof Proxy === "function") return true;
95
-
96
- try {
97
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
98
- return true;
99
- } catch (e) {
100
- return false;
101
- }
102
- }
103
-
104
- function _assertThisInitialized(self) {
105
- if (self === void 0) {
106
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
107
- }
108
-
109
- return self;
110
- }
111
-
112
- function _possibleConstructorReturn(self, call) {
113
- if (call && (typeof call === "object" || typeof call === "function")) {
114
- return call;
115
- } else if (call !== void 0) {
116
- throw new TypeError("Derived constructors may only return object or undefined");
117
- }
118
-
119
- return _assertThisInitialized(self);
120
- }
121
-
122
- function _createSuper(Derived) {
123
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
124
-
125
- return function _createSuperInternal() {
126
- var Super = _getPrototypeOf(Derived),
127
- result;
128
-
129
- if (hasNativeReflectConstruct) {
130
- var NewTarget = _getPrototypeOf(this).constructor;
131
-
132
- result = Reflect.construct(Super, arguments, NewTarget);
133
- } else {
134
- result = Super.apply(this, arguments);
135
- }
136
-
137
- return _possibleConstructorReturn(this, result);
138
- };
139
- }
140
-
141
- function _slicedToArray(arr, i) {
142
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
143
- }
144
-
145
- function _arrayWithHoles(arr) {
146
- if (Array.isArray(arr)) return arr;
147
- }
148
-
149
- function _iterableToArrayLimit(arr, i) {
150
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
151
-
152
- if (_i == null) return;
153
- var _arr = [];
154
- var _n = true;
155
- var _d = false;
156
-
157
- var _s, _e;
158
-
159
- try {
160
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
161
- _arr.push(_s.value);
162
-
163
- if (i && _arr.length === i) break;
164
- }
165
- } catch (err) {
166
- _d = true;
167
- _e = err;
168
- } finally {
169
- try {
170
- if (!_n && _i["return"] != null) _i["return"]();
171
- } finally {
172
- if (_d) throw _e;
173
- }
174
- }
175
-
176
- return _arr;
177
- }
178
-
179
- function _unsupportedIterableToArray(o, minLen) {
180
- if (!o) return;
181
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
182
- var n = Object.prototype.toString.call(o).slice(8, -1);
183
- if (n === "Object" && o.constructor) n = o.constructor.name;
184
- if (n === "Map" || n === "Set") return Array.from(o);
185
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
186
- }
187
-
188
- function _arrayLikeToArray(arr, len) {
189
- if (len == null || len > arr.length) len = arr.length;
190
-
191
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
192
-
193
- return arr2;
194
- }
195
-
196
- function _nonIterableRest() {
197
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
198
- }
199
-
200
- function _createForOfIteratorHelper(o, allowArrayLike) {
201
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
202
-
203
- if (!it) {
204
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
205
- if (it) o = it;
206
- var i = 0;
207
-
208
- var F = function () {};
209
-
210
- return {
211
- s: F,
212
- n: function () {
213
- if (i >= o.length) return {
214
- done: true
215
- };
216
- return {
217
- done: false,
218
- value: o[i++]
219
- };
220
- },
221
- e: function (e) {
222
- throw e;
223
- },
224
- f: F
225
- };
226
- }
227
-
228
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
229
- }
230
-
231
- var normalCompletion = true,
232
- didErr = false,
233
- err;
234
- return {
235
- s: function () {
236
- it = it.call(o);
237
- },
238
- n: function () {
239
- var step = it.next();
240
- normalCompletion = step.done;
241
- return step;
242
- },
243
- e: function (e) {
244
- didErr = true;
245
- err = e;
246
- },
247
- f: function () {
248
- try {
249
- if (!normalCompletion && it.return != null) it.return();
250
- } finally {
251
- if (didErr) throw err;
252
- }
253
- }
254
- };
255
- }
256
-
257
- var logger;
258
- var errorLogger;
259
- function setLogger() {
260
- /*eslint-disable */
261
- logger = console.log;
262
- errorLogger = console.error;
263
- /*eslint-enable */
264
- }
265
- function log(message) {
266
- if (logger) {
267
- for (var _len = arguments.length, optionalParams = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
268
- optionalParams[_key - 1] = arguments[_key];
269
- }
270
-
271
- logger.apply(void 0, [message].concat(optionalParams));
272
- }
273
- }
274
- function error(message) {
275
- if (errorLogger) {
276
- for (var _len2 = arguments.length, optionalParams = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
277
- optionalParams[_key2 - 1] = arguments[_key2];
278
- }
279
-
280
- errorLogger.apply(void 0, [message].concat(optionalParams));
281
- }
282
- }
283
-
284
- var NALU = /*#__PURE__*/function () {
285
- function NALU(data) {
286
- _classCallCheck(this, NALU);
287
-
288
- this.payload = data;
289
- this.nri = (this.payload[0] & 0x60) >> 5; // nal_ref_idc
290
-
291
- this.ntype = this.payload[0] & 0x1f;
292
- this.isvcl = this.ntype == 1 || this.ntype == 5;
293
- this.stype = ''; // slice_type
294
-
295
- this.isfmb = false; // first_mb_in_slice
296
- }
297
-
298
- _createClass(NALU, [{
299
- key: "toString",
300
- value: function toString() {
301
- return "".concat(NALU.type(this), ": NRI: ").concat(this.getNri());
302
- }
303
- }, {
304
- key: "getNri",
305
- value: function getNri() {
306
- return this.nri;
307
- }
308
- }, {
309
- key: "type",
310
- value: function type() {
311
- return this.ntype;
312
- }
313
- }, {
314
- key: "isKeyframe",
315
- value: function isKeyframe() {
316
- return this.ntype === NALU.IDR;
317
- }
318
- }, {
319
- key: "getPayload",
320
- value: function getPayload() {
321
- return this.payload;
322
- }
323
- }, {
324
- key: "getPayloadSize",
325
- value: function getPayloadSize() {
326
- return this.payload.byteLength;
327
- }
328
- }, {
329
- key: "getSize",
330
- value: function getSize() {
331
- return 4 + this.getPayloadSize();
332
- }
333
- }, {
334
- key: "getData",
335
- value: function getData() {
336
- var result = new Uint8Array(this.getSize());
337
- var view = new DataView(result.buffer);
338
- view.setUint32(0, this.getSize() - 4);
339
- result.set(this.getPayload(), 4);
340
- return result;
341
- }
342
- }], [{
343
- key: "NDR",
344
- get: function get() {
345
- return 1;
346
- }
347
- }, {
348
- key: "IDR",
349
- get: function get() {
350
- return 5;
351
- }
352
- }, {
353
- key: "SEI",
354
- get: function get() {
355
- return 6;
356
- }
357
- }, {
358
- key: "SPS",
359
- get: function get() {
360
- return 7;
361
- }
362
- }, {
363
- key: "PPS",
364
- get: function get() {
365
- return 8;
366
- }
367
- }, {
368
- key: "AUD",
369
- get: function get() {
370
- return 9;
371
- }
372
- }, {
373
- key: "TYPES",
374
- get: function get() {
375
- var _ref;
376
-
377
- return _ref = {}, _defineProperty(_ref, NALU.IDR, 'IDR'), _defineProperty(_ref, NALU.SEI, 'SEI'), _defineProperty(_ref, NALU.SPS, 'SPS'), _defineProperty(_ref, NALU.PPS, 'PPS'), _defineProperty(_ref, NALU.NDR, 'NDR'), _defineProperty(_ref, NALU.AUD, 'AUD'), _ref;
378
- }
379
- }, {
380
- key: "type",
381
- value: function type(nalu) {
382
- if (nalu.ntype in NALU.TYPES) {
383
- return NALU.TYPES[nalu.ntype];
384
- } else {
385
- return 'UNKNOWN';
386
- }
387
- }
388
- }]);
389
-
390
- return NALU;
391
- }();
392
-
393
- function appendByteArray(buffer1, buffer2) {
394
- var tmp = new Uint8Array((buffer1.byteLength | 0) + (buffer2.byteLength | 0));
395
- tmp.set(buffer1, 0);
396
- tmp.set(buffer2, buffer1.byteLength | 0);
397
- return tmp;
398
- }
399
- function secToTime(sec) {
400
- var seconds,
401
- hours,
402
- minutes,
403
- result = '';
404
- seconds = Math.floor(sec);
405
- hours = parseInt(seconds / 3600, 10) % 24;
406
- minutes = parseInt(seconds / 60, 10) % 60;
407
- seconds = seconds < 0 ? 0 : seconds % 60;
408
-
409
- if (hours > 0) {
410
- result += (hours < 10 ? '0' + hours : hours) + ':';
411
- }
412
-
413
- result += (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
414
- return result;
415
- }
416
-
417
- /**
418
- * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
419
- */
420
- var ExpGolomb = /*#__PURE__*/function () {
421
- function ExpGolomb(data) {
422
- _classCallCheck(this, ExpGolomb);
423
-
424
- this.data = data;
425
- this.index = 0;
426
- this.bitLength = data.byteLength * 8;
427
- }
428
-
429
- _createClass(ExpGolomb, [{
430
- key: "setData",
431
- value: function setData(data) {
432
- this.data = data;
433
- this.index = 0;
434
- this.bitLength = data.byteLength * 8;
435
- }
436
- }, {
437
- key: "bitsAvailable",
438
- get: function get() {
439
- return this.bitLength - this.index;
440
- }
441
- }, {
442
- key: "skipBits",
443
- value: function skipBits(size) {
444
- // console.log(` skip bits: size=${size}, ${this.index}.`);
445
- if (this.bitsAvailable < size) {
446
- //throw new Error('no bytes available');
447
- return false;
448
- }
449
-
450
- this.index += size;
451
- }
452
- }, {
453
- key: "readBits",
454
- value: function readBits(size) {
455
- var moveIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
456
- // console.log(` read bits: size=${size}, ${this.index}.`);
457
- var result = this.getBits(size, this.index, moveIndex); // console.log(` read bits: result=${result}`);
458
-
459
- return result;
460
- }
461
- }, {
462
- key: "getBits",
463
- value: function getBits(size, offsetBits) {
464
- var moveIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
465
-
466
- if (this.bitsAvailable < size) {
467
- //throw new Error('no bytes available');
468
- return 0;
469
- }
470
-
471
- var offset = offsetBits % 8;
472
-
473
- var _byte = this.data[offsetBits / 8 | 0] & 0xff >>> offset;
474
-
475
- var bits = 8 - offset;
476
-
477
- if (bits >= size) {
478
- if (moveIndex) {
479
- this.index += size;
480
- }
481
-
482
- return _byte >> bits - size;
483
- } else {
484
- if (moveIndex) {
485
- this.index += bits;
486
- }
487
-
488
- var nextSize = size - bits;
489
- return _byte << nextSize | this.getBits(nextSize, offsetBits + bits, moveIndex);
490
- }
491
- }
492
- }, {
493
- key: "skipLZ",
494
- value: function skipLZ() {
495
- var leadingZeroCount;
496
-
497
- for (leadingZeroCount = 0; leadingZeroCount < this.bitLength - this.index; ++leadingZeroCount) {
498
- if (this.getBits(1, this.index + leadingZeroCount, false) !== 0) {
499
- // console.log(` skip LZ : size=${leadingZeroCount}, ${this.index}.`);
500
- this.index += leadingZeroCount;
501
- return leadingZeroCount;
502
- }
503
- }
504
-
505
- return leadingZeroCount;
506
- }
507
- }, {
508
- key: "skipUEG",
509
- value: function skipUEG() {
510
- this.skipBits(1 + this.skipLZ());
511
- }
512
- }, {
513
- key: "skipEG",
514
- value: function skipEG() {
515
- this.skipBits(1 + this.skipLZ());
516
- }
517
- }, {
518
- key: "readUEG",
519
- value: function readUEG() {
520
- var prefix = this.skipLZ();
521
- return this.readBits(prefix + 1) - 1;
522
- }
523
- }, {
524
- key: "readEG",
525
- value: function readEG() {
526
- var value = this.readUEG();
527
-
528
- if (0x01 & value) {
529
- // the number is odd if the low order bit is set
530
- return 1 + value >>> 1; // add 1 to make it even, and divide by 2
531
- } else {
532
- return -1 * (value >>> 1); // divide by two then make it negative
533
- }
534
- }
535
- }, {
536
- key: "readBoolean",
537
- value: function readBoolean() {
538
- return this.readBits(1) === 1;
539
- }
540
- }, {
541
- key: "readUByte",
542
- value: function readUByte() {
543
- var numberOfBytes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
544
- return this.readBits(numberOfBytes * 8);
545
- }
546
- }, {
547
- key: "readUShort",
548
- value: function readUShort() {
549
- return this.readBits(16);
550
- }
551
- }, {
552
- key: "readUInt",
553
- value: function readUInt() {
554
- return this.readBits(32);
555
- }
556
- }]);
557
-
558
- return ExpGolomb;
559
- }();
560
-
561
- var H264Parser = /*#__PURE__*/function () {
562
- function H264Parser(remuxer) {
563
- _classCallCheck(this, H264Parser);
564
-
565
- this.remuxer = remuxer;
566
- this.track = remuxer.mp4track;
567
- }
568
-
569
- _createClass(H264Parser, [{
570
- key: "parseSPS",
571
- value: function parseSPS(sps) {
572
- var config = H264Parser.readSPS(new Uint8Array(sps));
573
- this.track.fps = config.fps;
574
- this.track.width = config.width;
575
- this.track.height = config.height;
576
- this.track.sps = [new Uint8Array(sps)];
577
- this.track.codec = 'avc1.';
578
- var codecarray = new DataView(sps.buffer, sps.byteOffset + 1, 4);
579
-
580
- for (var i = 0; i < 3; ++i) {
581
- var h = codecarray.getUint8(i).toString(16);
582
-
583
- if (h.length < 2) {
584
- h = '0' + h;
585
- }
586
-
587
- this.track.codec += h;
588
- }
589
- }
590
- }, {
591
- key: "parsePPS",
592
- value: function parsePPS(pps) {
593
- this.track.pps = [new Uint8Array(pps)];
594
- }
595
- }, {
596
- key: "parseNAL",
597
- value: function parseNAL(unit) {
598
- if (!unit) return false;
599
- var push = false;
600
-
601
- switch (unit.type()) {
602
- case NALU.IDR:
603
- case NALU.NDR:
604
- push = true;
605
- break;
606
-
607
- case NALU.PPS:
608
- if (!this.track.pps) {
609
- this.parsePPS(unit.getPayload());
610
-
611
- if (!this.remuxer.readyToDecode && this.track.pps && this.track.sps) {
612
- this.remuxer.readyToDecode = true;
613
- }
614
- }
615
-
616
- push = true;
617
- break;
618
-
619
- case NALU.SPS:
620
- if (!this.track.sps) {
621
- this.parseSPS(unit.getPayload());
622
-
623
- if (!this.remuxer.readyToDecode && this.track.pps && this.track.sps) {
624
- this.remuxer.readyToDecode = true;
625
- }
626
- }
627
-
628
- push = true;
629
- break;
630
-
631
- case NALU.AUD:
632
- log('AUD - ignoing');
633
- break;
634
-
635
- case NALU.SEI:
636
- log('SEI - ignoing');
637
- break;
638
- }
639
-
640
- return push;
641
- }
642
- }], [{
643
- key: "extractNALu",
644
- value: function extractNALu(buffer) {
645
- var i = 0,
646
- length = buffer.byteLength,
647
- value,
648
- state = 0,
649
- result = [],
650
- left,
651
- lastIndex = 0;
652
-
653
- while (i < length) {
654
- value = buffer[i++]; // finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01)
655
-
656
- switch (state) {
657
- case 0:
658
- if (value === 0) {
659
- state = 1;
660
- }
661
-
662
- break;
663
-
664
- case 1:
665
- if (value === 0) {
666
- state = 2;
667
- } else {
668
- state = 0;
669
- }
670
-
671
- break;
672
-
673
- case 2:
674
- case 3:
675
- if (value === 0) {
676
- state = 3;
677
- } else if (value === 1 && i < length) {
678
- if (lastIndex != i - state - 1) {
679
- result.push(buffer.subarray(lastIndex, i - state - 1));
680
- }
681
-
682
- lastIndex = i;
683
- state = 0;
684
- } else {
685
- state = 0;
686
- }
687
-
688
- break;
689
- }
690
- }
691
-
692
- if (lastIndex < length) {
693
- left = buffer.subarray(lastIndex, length);
694
- }
695
-
696
- return [result, left];
697
- }
698
- /**
699
- * Advance the ExpGolomb decoder past a scaling list. The scaling
700
- * list is optionally transmitted as part of a sequence parameter
701
- * set and is not relevant to transmuxing.
702
- * @param decoder {ExpGolomb} exp golomb decoder
703
- * @param count {number} the number of entries in this scaling list
704
- * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
705
- */
706
-
707
- }, {
708
- key: "skipScalingList",
709
- value: function skipScalingList(decoder, count) {
710
- var lastScale = 8,
711
- nextScale = 8,
712
- deltaScale;
713
-
714
- for (var j = 0; j < count; j++) {
715
- if (nextScale !== 0) {
716
- deltaScale = decoder.readEG();
717
- nextScale = (lastScale + deltaScale + 256) % 256;
718
- }
719
-
720
- lastScale = nextScale === 0 ? lastScale : nextScale;
721
- }
722
- }
723
- /**
724
- * Read a sequence parameter set and return some interesting video
725
- * properties. A sequence parameter set is the H264 metadata that
726
- * describes the properties of upcoming video frames.
727
- * @param data {Uint8Array} the bytes of a sequence parameter set
728
- * @return {object} an object with configuration parsed from the
729
- * sequence parameter set, including the dimensions of the
730
- * associated video frames.
731
- */
732
-
733
- }, {
734
- key: "readSPS",
735
- value: function readSPS(data) {
736
- var decoder = new ExpGolomb(data);
737
- var frameCropLeftOffset = 0,
738
- frameCropRightOffset = 0,
739
- frameCropTopOffset = 0,
740
- frameCropBottomOffset = 0,
741
- sarScale = 1,
742
- profileIdc,
743
- numRefFramesInPicOrderCntCycle,
744
- picWidthInMbsMinus1,
745
- picHeightInMapUnitsMinus1,
746
- frameMbsOnlyFlag,
747
- scalingListCount,
748
- fps = 0;
749
- decoder.readUByte(); // skip NAL header
750
- // rewrite NAL
751
-
752
- var rbsp = [],
753
- hdr_bytes = 1,
754
- nal_bytes = data.byteLength;
755
-
756
- for (var i = hdr_bytes; i < nal_bytes; i++) {
757
- if (i + 2 < nal_bytes && decoder.readBits(24, false) === 0x000003) {
758
- rbsp.push(decoder.readBits(8));
759
- rbsp.push(decoder.readBits(8));
760
- i += 2; // emulation_prevention_three_byte
761
-
762
- decoder.readBits(8);
763
- } else {
764
- rbsp.push(decoder.readBits(8));
765
- }
766
- }
767
-
768
- decoder.setData(new Uint8Array(rbsp)); // end of rewrite data
769
-
770
- profileIdc = decoder.readUByte(); // profile_idc
771
-
772
- decoder.readBits(5); // constraint_set[0-4]_flag, u(5)
773
-
774
- decoder.skipBits(3); // reserved_zero_3bits u(3),
775
-
776
- decoder.readUByte(); // level_idc u(8)
777
-
778
- decoder.skipUEG(); // seq_parameter_set_id
779
- // some profiles have more optional data we don't need
780
-
781
- if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
782
- var chromaFormatIdc = decoder.readUEG();
783
-
784
- if (chromaFormatIdc === 3) {
785
- decoder.skipBits(1); // separate_colour_plane_flag
786
- }
787
-
788
- decoder.skipUEG(); // bit_depth_luma_minus8
789
-
790
- decoder.skipUEG(); // bit_depth_chroma_minus8
791
-
792
- decoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
793
-
794
- if (decoder.readBoolean()) {
795
- // seq_scaling_matrix_present_flag
796
- scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
797
-
798
- for (var _i = 0; _i < scalingListCount; ++_i) {
799
- if (decoder.readBoolean()) {
800
- // seq_scaling_list_present_flag[ i ]
801
- if (_i < 6) {
802
- H264Parser.skipScalingList(decoder, 16);
803
- } else {
804
- H264Parser.skipScalingList(decoder, 64);
805
- }
806
- }
807
- }
808
- }
809
- }
810
-
811
- decoder.skipUEG(); // log2_max_frame_num_minus4
812
-
813
- var picOrderCntType = decoder.readUEG();
814
-
815
- if (picOrderCntType === 0) {
816
- decoder.readUEG(); // log2_max_pic_order_cnt_lsb_minus4
817
- } else if (picOrderCntType === 1) {
818
- decoder.skipBits(1); // delta_pic_order_always_zero_flag
819
-
820
- decoder.skipEG(); // offset_for_non_ref_pic
821
-
822
- decoder.skipEG(); // offset_for_top_to_bottom_field
823
-
824
- numRefFramesInPicOrderCntCycle = decoder.readUEG();
825
-
826
- for (var _i2 = 0; _i2 < numRefFramesInPicOrderCntCycle; ++_i2) {
827
- decoder.skipEG(); // offset_for_ref_frame[ i ]
828
- }
829
- }
830
-
831
- decoder.skipUEG(); // max_num_ref_frames
832
-
833
- decoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
834
-
835
- picWidthInMbsMinus1 = decoder.readUEG();
836
- picHeightInMapUnitsMinus1 = decoder.readUEG();
837
- frameMbsOnlyFlag = decoder.readBits(1);
838
-
839
- if (frameMbsOnlyFlag === 0) {
840
- decoder.skipBits(1); // mb_adaptive_frame_field_flag
841
- }
842
-
843
- decoder.skipBits(1); // direct_8x8_inference_flag
844
-
845
- if (decoder.readBoolean()) {
846
- // frame_cropping_flag
847
- frameCropLeftOffset = decoder.readUEG();
848
- frameCropRightOffset = decoder.readUEG();
849
- frameCropTopOffset = decoder.readUEG();
850
- frameCropBottomOffset = decoder.readUEG();
851
- }
852
-
853
- if (decoder.readBoolean()) {
854
- // vui_parameters_present_flag
855
- if (decoder.readBoolean()) {
856
- // aspect_ratio_info_present_flag
857
- var sarRatio;
858
- var aspectRatioIdc = decoder.readUByte();
859
-
860
- switch (aspectRatioIdc) {
861
- case 1:
862
- sarRatio = [1, 1];
863
- break;
864
-
865
- case 2:
866
- sarRatio = [12, 11];
867
- break;
868
-
869
- case 3:
870
- sarRatio = [10, 11];
871
- break;
872
-
873
- case 4:
874
- sarRatio = [16, 11];
875
- break;
876
-
877
- case 5:
878
- sarRatio = [40, 33];
879
- break;
880
-
881
- case 6:
882
- sarRatio = [24, 11];
883
- break;
884
-
885
- case 7:
886
- sarRatio = [20, 11];
887
- break;
888
-
889
- case 8:
890
- sarRatio = [32, 11];
891
- break;
892
-
893
- case 9:
894
- sarRatio = [80, 33];
895
- break;
896
-
897
- case 10:
898
- sarRatio = [18, 11];
899
- break;
900
-
901
- case 11:
902
- sarRatio = [15, 11];
903
- break;
904
-
905
- case 12:
906
- sarRatio = [64, 33];
907
- break;
908
-
909
- case 13:
910
- sarRatio = [160, 99];
911
- break;
912
-
913
- case 14:
914
- sarRatio = [4, 3];
915
- break;
916
-
917
- case 15:
918
- sarRatio = [3, 2];
919
- break;
920
-
921
- case 16:
922
- sarRatio = [2, 1];
923
- break;
924
-
925
- case 255:
926
- {
927
- sarRatio = [decoder.readUByte() << 8 | decoder.readUByte(), decoder.readUByte() << 8 | decoder.readUByte()];
928
- break;
929
- }
930
- }
931
-
932
- if (sarRatio && sarRatio[0] > 0 && sarRatio[1] > 0) {
933
- sarScale = sarRatio[0] / sarRatio[1];
934
- }
935
- }
936
-
937
- if (decoder.readBoolean()) {
938
- decoder.skipBits(1);
939
- }
940
-
941
- if (decoder.readBoolean()) {
942
- decoder.skipBits(4);
943
-
944
- if (decoder.readBoolean()) {
945
- decoder.skipBits(24);
946
- }
947
- }
948
-
949
- if (decoder.readBoolean()) {
950
- decoder.skipUEG();
951
- decoder.skipUEG();
952
- }
953
-
954
- if (decoder.readBoolean()) {
955
- var unitsInTick = decoder.readUInt();
956
- var timeScale = decoder.readUInt();
957
- var fixedFrameRate = decoder.readBoolean();
958
- var frameDuration = timeScale / (2 * unitsInTick);
959
-
960
- if (fixedFrameRate) {
961
- fps = frameDuration;
962
- }
963
- }
964
- }
965
-
966
- return {
967
- fps: fps > 0 ? fps : undefined,
968
- width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
969
- height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)
970
- };
971
- }
972
- }, {
973
- key: "parseHeader",
974
- value: function parseHeader(unit) {
975
- var decoder = new ExpGolomb(unit.getPayload()); // skip NALu type
976
-
977
- decoder.readUByte();
978
- unit.isfmb = decoder.readUEG() === 0;
979
- unit.stype = decoder.readUEG();
980
- }
981
- }]);
982
-
983
- return H264Parser;
984
- }();
985
-
986
- var aacHeader;
987
- var AACParser = /*#__PURE__*/function () {
988
- function AACParser(remuxer) {
989
- _classCallCheck(this, AACParser);
990
-
991
- this.remuxer = remuxer;
992
- this.track = remuxer.mp4track;
993
- }
994
-
995
- _createClass(AACParser, [{
996
- key: "setAACConfig",
997
- value: function setAACConfig() {
998
- var objectType,
999
- sampleIndex,
1000
- channelCount,
1001
- config = new Uint8Array(2),
1002
- headerData = AACParser.getAACHeaderData;
1003
- if (!headerData) return;
1004
- objectType = ((headerData[2] & 0xC0) >>> 6) + 1;
1005
- sampleIndex = (headerData[2] & 0x3C) >>> 2;
1006
- channelCount = (headerData[2] & 0x01) << 2;
1007
- channelCount |= (headerData[3] & 0xC0) >>> 6;
1008
- /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config */
1009
-
1010
- config[0] = objectType << 3;
1011
- config[0] |= (sampleIndex & 0x0E) >> 1;
1012
- config[1] |= (sampleIndex & 0x01) << 7;
1013
- config[1] |= channelCount << 3;
1014
- this.track.codec = 'mp4a.40.' + objectType;
1015
- this.track.channelCount = channelCount;
1016
- this.track.config = config;
1017
- this.remuxer.readyToDecode = true;
1018
- }
1019
- }], [{
1020
- key: "samplingRateMap",
1021
- get: function get() {
1022
- return [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
1023
- }
1024
- }, {
1025
- key: "getAACHeaderData",
1026
- get: function get() {
1027
- return aacHeader;
1028
- }
1029
- }, {
1030
- key: "getHeaderLength",
1031
- value: function getHeaderLength(data) {
1032
- return data[1] & 0x01 ? 7 : 9; // without CRC 7 and with CRC 9 Refs: https://wiki.multimedia.cx/index.php?title=ADTS
1033
- }
1034
- }, {
1035
- key: "getFrameLength",
1036
- value: function getFrameLength(data) {
1037
- return (data[3] & 0x03) << 11 | data[4] << 3 | (data[5] & 0xE0) >>> 5; // 13 bits length ref: https://wiki.multimedia.cx/index.php?title=ADTS
1038
- }
1039
- }, {
1040
- key: "isAACPattern",
1041
- value: function isAACPattern(data) {
1042
- return data[0] === 0xff && (data[1] & 0xf0) === 0xf0 && (data[1] & 0x06) === 0x00;
1043
- }
1044
- }, {
1045
- key: "extractAAC",
1046
- value: function extractAAC(buffer) {
1047
- var i = 0,
1048
- length = buffer.byteLength,
1049
- result = [],
1050
- headerLength,
1051
- frameLength;
1052
-
1053
- if (!AACParser.isAACPattern(buffer)) {
1054
- error('Invalid ADTS audio format');
1055
- return result;
1056
- }
1057
-
1058
- headerLength = AACParser.getHeaderLength(buffer);
1059
-
1060
- if (!aacHeader) {
1061
- aacHeader = buffer.subarray(0, headerLength);
1062
- }
1063
-
1064
- while (i < length) {
1065
- frameLength = AACParser.getFrameLength(buffer);
1066
- result.push(buffer.subarray(headerLength, frameLength));
1067
- buffer = buffer.slice(frameLength);
1068
- i += frameLength;
1069
- }
1070
-
1071
- return result;
1072
- }
1073
- }]);
1074
-
1075
- return AACParser;
1076
- }();
1077
-
1078
- var Event = /*#__PURE__*/function () {
1079
- function Event(type) {
1080
- _classCallCheck(this, Event);
1081
-
1082
- this.listener = {};
1083
- this.type = type | '';
1084
- }
1085
-
1086
- _createClass(Event, [{
1087
- key: "on",
1088
- value: function on(event, fn) {
1089
- if (!this.listener[event]) {
1090
- this.listener[event] = [];
1091
- }
1092
-
1093
- this.listener[event].push(fn);
1094
- return true;
1095
- }
1096
- }, {
1097
- key: "off",
1098
- value: function off(event, fn) {
1099
- if (this.listener[event]) {
1100
- var index = this.listener[event].indexOf(fn);
1101
-
1102
- if (index > -1) {
1103
- this.listener[event].splice(index, 1);
1104
- }
1105
-
1106
- return true;
1107
- }
1108
-
1109
- return false;
1110
- }
1111
- }, {
1112
- key: "offAll",
1113
- value: function offAll() {
1114
- this.listener = {};
1115
- }
1116
- }, {
1117
- key: "dispatch",
1118
- value: function dispatch(event, data) {
1119
- if (this.listener[event]) {
1120
- this.listener[event].map(function (each) {
1121
- each.apply(null, [data]);
1122
- });
1123
- return true;
1124
- }
1125
-
1126
- return false;
1127
- }
1128
- }]);
1129
-
1130
- return Event;
1131
- }();
1132
-
1133
- /**
1134
- * Generate MP4 Box
1135
- * taken from: https://github.com/dailymotion/hls.js
1136
- */
1137
- var MP4 = /*#__PURE__*/function () {
1138
- function MP4() {
1139
- _classCallCheck(this, MP4);
1140
- }
1141
-
1142
- _createClass(MP4, null, [{
1143
- key: "init",
1144
- value: function init() {
1145
- MP4.types = {
1146
- avc1: [],
1147
- // codingname
1148
- avcC: [],
1149
- btrt: [],
1150
- dinf: [],
1151
- dref: [],
1152
- esds: [],
1153
- ftyp: [],
1154
- hdlr: [],
1155
- mdat: [],
1156
- mdhd: [],
1157
- mdia: [],
1158
- mfhd: [],
1159
- minf: [],
1160
- moof: [],
1161
- moov: [],
1162
- mp4a: [],
1163
- mvex: [],
1164
- mvhd: [],
1165
- sdtp: [],
1166
- stbl: [],
1167
- stco: [],
1168
- stsc: [],
1169
- stsd: [],
1170
- stsz: [],
1171
- stts: [],
1172
- tfdt: [],
1173
- tfhd: [],
1174
- traf: [],
1175
- trak: [],
1176
- trun: [],
1177
- trex: [],
1178
- tkhd: [],
1179
- vmhd: [],
1180
- smhd: []
1181
- };
1182
- var i;
1183
-
1184
- for (i in MP4.types) {
1185
- if (MP4.types.hasOwnProperty(i)) {
1186
- MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
1187
- }
1188
- }
1189
-
1190
- var videoHdlr = new Uint8Array([0x00, // version 0
1191
- 0x00, 0x00, 0x00, // flags
1192
- 0x00, 0x00, 0x00, 0x00, // pre_defined
1193
- 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
1194
- 0x00, 0x00, 0x00, 0x00, // reserved
1195
- 0x00, 0x00, 0x00, 0x00, // reserved
1196
- 0x00, 0x00, 0x00, 0x00, // reserved
1197
- 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
1198
- ]);
1199
- var audioHdlr = new Uint8Array([0x00, // version 0
1200
- 0x00, 0x00, 0x00, // flags
1201
- 0x00, 0x00, 0x00, 0x00, // pre_defined
1202
- 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
1203
- 0x00, 0x00, 0x00, 0x00, // reserved
1204
- 0x00, 0x00, 0x00, 0x00, // reserved
1205
- 0x00, 0x00, 0x00, 0x00, // reserved
1206
- 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
1207
- ]);
1208
- MP4.HDLR_TYPES = {
1209
- video: videoHdlr,
1210
- audio: audioHdlr
1211
- };
1212
- var dref = new Uint8Array([0x00, // version 0
1213
- 0x00, 0x00, 0x00, // flags
1214
- 0x00, 0x00, 0x00, 0x01, // entry_count
1215
- 0x00, 0x00, 0x00, 0x0c, // entry_size
1216
- 0x75, 0x72, 0x6c, 0x20, // 'url' type
1217
- 0x00, // version 0
1218
- 0x00, 0x00, 0x01 // entry_flags
1219
- ]);
1220
- var stco = new Uint8Array([0x00, // version
1221
- 0x00, 0x00, 0x00, // flags
1222
- 0x00, 0x00, 0x00, 0x00 // entry_count
1223
- ]);
1224
- MP4.STTS = MP4.STSC = MP4.STCO = stco;
1225
- MP4.STSZ = new Uint8Array([0x00, // version
1226
- 0x00, 0x00, 0x00, // flags
1227
- 0x00, 0x00, 0x00, 0x00, // sample_size
1228
- 0x00, 0x00, 0x00, 0x00 // sample_count
1229
- ]);
1230
- MP4.VMHD = new Uint8Array([0x00, // version
1231
- 0x00, 0x00, 0x01, // flags
1232
- 0x00, 0x00, // graphicsmode
1233
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
1234
- ]);
1235
- MP4.SMHD = new Uint8Array([0x00, // version
1236
- 0x00, 0x00, 0x00, // flags
1237
- 0x00, 0x00, // balance
1238
- 0x00, 0x00 // reserved
1239
- ]);
1240
- MP4.STSD = new Uint8Array([0x00, // version 0
1241
- 0x00, 0x00, 0x00, // flags
1242
- 0x00, 0x00, 0x00, 0x01]); // entry_count
1243
-
1244
- var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
1245
-
1246
- var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
1247
-
1248
- var minorVersion = new Uint8Array([0, 0, 0, 1]);
1249
- MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
1250
- MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
1251
- }
1252
- }, {
1253
- key: "box",
1254
- value: function box(type) {
1255
- for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1256
- payload[_key - 1] = arguments[_key];
1257
- }
1258
-
1259
- var size = 8,
1260
- i = payload.length,
1261
- len = i,
1262
- result; // calculate the total size we need to allocate
1263
-
1264
- while (i--) {
1265
- size += payload[i].byteLength;
1266
- }
1267
-
1268
- result = new Uint8Array(size);
1269
- result[0] = size >> 24 & 0xff;
1270
- result[1] = size >> 16 & 0xff;
1271
- result[2] = size >> 8 & 0xff;
1272
- result[3] = size & 0xff;
1273
- result.set(type, 4); // copy the payload into the result
1274
-
1275
- for (i = 0, size = 8; i < len; ++i) {
1276
- // copy payload[i] array @ offset size
1277
- result.set(payload[i], size);
1278
- size += payload[i].byteLength;
1279
- }
1280
-
1281
- return result;
1282
- }
1283
- }, {
1284
- key: "hdlr",
1285
- value: function hdlr(type) {
1286
- return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
1287
- }
1288
- }, {
1289
- key: "mdat",
1290
- value: function mdat(data) {
1291
- return MP4.box(MP4.types.mdat, data);
1292
- }
1293
- }, {
1294
- key: "mdhd",
1295
- value: function mdhd(timescale, duration) {
1296
- return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, // version 0
1297
- 0x00, 0x00, 0x00, // flags
1298
- 0x00, 0x00, 0x00, 0x02, // creation_time
1299
- 0x00, 0x00, 0x00, 0x03, // modification_time
1300
- timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
1301
- duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
1302
- 0x55, 0xc4, // 'und' language (undetermined)
1303
- 0x00, 0x00]));
1304
- }
1305
- }, {
1306
- key: "mdia",
1307
- value: function mdia(track) {
1308
- return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
1309
- }
1310
- }, {
1311
- key: "mfhd",
1312
- value: function mfhd(sequenceNumber) {
1313
- return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
1314
- sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
1315
- ]));
1316
- }
1317
- }, {
1318
- key: "minf",
1319
- value: function minf(track) {
1320
- if (track.type === 'audio') {
1321
- return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
1322
- } else {
1323
- return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
1324
- }
1325
- }
1326
- }, {
1327
- key: "moof",
1328
- value: function moof(sn, baseMediaDecodeTime, track) {
1329
- return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
1330
- }
1331
- /**
1332
- * @param tracks... (optional) {array} the tracks associated with this movie
1333
- */
1334
-
1335
- }, {
1336
- key: "moov",
1337
- value: function moov(tracks, duration, timescale) {
1338
- var i = tracks.length,
1339
- boxes = [];
1340
-
1341
- while (i--) {
1342
- boxes[i] = MP4.trak(tracks[i]);
1343
- }
1344
-
1345
- return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(timescale, duration)].concat(boxes).concat(MP4.mvex(tracks)));
1346
- }
1347
- }, {
1348
- key: "mvex",
1349
- value: function mvex(tracks) {
1350
- var i = tracks.length,
1351
- boxes = [];
1352
-
1353
- while (i--) {
1354
- boxes[i] = MP4.trex(tracks[i]);
1355
- }
1356
-
1357
- return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
1358
- }
1359
- }, {
1360
- key: "mvhd",
1361
- value: function mvhd(timescale, duration) {
1362
- var bytes = new Uint8Array([0x00, // version 0
1363
- 0x00, 0x00, 0x00, // flags
1364
- 0x00, 0x00, 0x00, 0x01, // creation_time
1365
- 0x00, 0x00, 0x00, 0x02, // modification_time
1366
- timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
1367
- duration >> 24 & 0xFF, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
1368
- 0x00, 0x01, 0x00, 0x00, // 1.0 rate
1369
- 0x01, 0x00, // 1.0 volume
1370
- 0x00, 0x00, // reserved
1371
- 0x00, 0x00, 0x00, 0x00, // reserved
1372
- 0x00, 0x00, 0x00, 0x00, // reserved
1373
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
1374
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
1375
- 0xff, 0xff, 0xff, 0xff // next_track_ID
1376
- ]);
1377
- return MP4.box(MP4.types.mvhd, bytes);
1378
- }
1379
- }, {
1380
- key: "sdtp",
1381
- value: function sdtp(track) {
1382
- var samples = track.samples || [],
1383
- bytes = new Uint8Array(4 + samples.length),
1384
- flags,
1385
- i; // leave the full box header (4 bytes) all zero
1386
- // write the sample table
1387
-
1388
- for (i = 0; i < samples.length; i++) {
1389
- flags = samples[i].flags;
1390
- bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
1391
- }
1392
-
1393
- return MP4.box(MP4.types.sdtp, bytes);
1394
- }
1395
- }, {
1396
- key: "stbl",
1397
- value: function stbl(track) {
1398
- return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
1399
- }
1400
- }, {
1401
- key: "avc1",
1402
- value: function avc1(track) {
1403
- var sps = [],
1404
- pps = [],
1405
- i,
1406
- data,
1407
- len; // assemble the SPSs
1408
-
1409
- for (i = 0; i < track.sps.length; i++) {
1410
- data = track.sps[i];
1411
- len = data.byteLength;
1412
- sps.push(len >>> 8 & 0xFF);
1413
- sps.push(len & 0xFF);
1414
- sps = sps.concat(Array.prototype.slice.call(data)); // SPS
1415
- } // assemble the PPSs
1416
-
1417
-
1418
- for (i = 0; i < track.pps.length; i++) {
1419
- data = track.pps[i];
1420
- len = data.byteLength;
1421
- pps.push(len >>> 8 & 0xFF);
1422
- pps.push(len & 0xFF);
1423
- pps = pps.concat(Array.prototype.slice.call(data));
1424
- }
1425
-
1426
- var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
1427
- sps[3], // profile
1428
- sps[4], // profile compat
1429
- sps[5], // level
1430
- 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
1431
- 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
1432
- ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
1433
- ]).concat(pps))),
1434
- // "PPS"
1435
- width = track.width,
1436
- height = track.height; // console.log('avcc:' + Hex.hexDump(avcc));
1437
-
1438
- return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
1439
- 0x00, 0x00, 0x00, // reserved
1440
- 0x00, 0x01, // data_reference_index
1441
- 0x00, 0x00, // pre_defined
1442
- 0x00, 0x00, // reserved
1443
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
1444
- width >> 8 & 0xFF, width & 0xff, // width
1445
- height >> 8 & 0xFF, height & 0xff, // height
1446
- 0x00, 0x48, 0x00, 0x00, // horizresolution
1447
- 0x00, 0x48, 0x00, 0x00, // vertresolution
1448
- 0x00, 0x00, 0x00, 0x00, // reserved
1449
- 0x00, 0x01, // frame_count
1450
- 0x12, 0x62, 0x69, 0x6E, 0x65, // binelpro.ru
1451
- 0x6C, 0x70, 0x72, 0x6F, 0x2E, 0x72, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
1452
- 0x00, 0x18, // depth = 24
1453
- 0x11, 0x11]), // pre_defined = -1
1454
- avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
1455
- 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
1456
- 0x00, 0x2d, 0xc6, 0xc0])) // avgBitrate
1457
- );
1458
- }
1459
- }, {
1460
- key: "esds",
1461
- value: function esds(track) {
1462
- var configlen = track.config.byteLength;
1463
- var data = new Uint8Array(26 + configlen + 3);
1464
- data.set([0x00, // version 0
1465
- 0x00, 0x00, 0x00, // flags
1466
- 0x03, // descriptor_type
1467
- 0x17 + configlen, // length
1468
- 0x00, 0x01, // es_id
1469
- 0x00, // stream_priority
1470
- 0x04, // descriptor_type
1471
- 0x0f + configlen, // length
1472
- 0x40, // codec : mpeg4_audio
1473
- 0x15, // stream_type
1474
- 0x00, 0x00, 0x00, // buffer_size
1475
- 0x00, 0x00, 0x00, 0x00, // maxBitrate
1476
- 0x00, 0x00, 0x00, 0x00, // avgBitrate
1477
- 0x05, // descriptor_type
1478
- configlen]);
1479
- data.set(track.config, 26);
1480
- data.set([0x06, 0x01, 0x02], 26 + configlen); // return new Uint8Array([
1481
- // 0x00, // version 0
1482
- // 0x00, 0x00, 0x00, // flags
1483
- //
1484
- // 0x03, // descriptor_type
1485
- // 0x17+configlen, // length
1486
- // 0x00, 0x01, //es_id
1487
- // 0x00, // stream_priority
1488
- //
1489
- // 0x04, // descriptor_type
1490
- // 0x0f+configlen, // length
1491
- // 0x40, //codec : mpeg4_audio
1492
- // 0x15, // stream_type
1493
- // 0x00, 0x00, 0x00, // buffer_size
1494
- // 0x00, 0x00, 0x00, 0x00, // maxBitrate
1495
- // 0x00, 0x00, 0x00, 0x00, // avgBitrate
1496
- //
1497
- // 0x05 // descriptor_type
1498
- // ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
1499
-
1500
- return data;
1501
- }
1502
- }, {
1503
- key: "mp4a",
1504
- value: function mp4a(track) {
1505
- var audiosamplerate = track.audiosamplerate;
1506
- return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
1507
- 0x00, 0x00, 0x00, // reserved
1508
- 0x00, 0x01, // data_reference_index
1509
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
1510
- 0x00, track.channelCount, // channelcount
1511
- 0x00, 0x10, // sampleSize:16bits
1512
- 0x00, 0x00, // pre_defined
1513
- 0x00, 0x00, // reserved2
1514
- audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, //
1515
- 0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
1516
- }
1517
- }, {
1518
- key: "stsd",
1519
- value: function stsd(track) {
1520
- if (track.type === 'audio') {
1521
- return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
1522
- } else {
1523
- return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
1524
- }
1525
- }
1526
- }, {
1527
- key: "tkhd",
1528
- value: function tkhd(track) {
1529
- var id = track.id,
1530
- duration = track.duration,
1531
- width = track.width,
1532
- height = track.height,
1533
- volume = track.volume;
1534
- return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, // version 0
1535
- 0x00, 0x00, 0x07, // flags
1536
- 0x00, 0x00, 0x00, 0x00, // creation_time
1537
- 0x00, 0x00, 0x00, 0x00, // modification_time
1538
- id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
1539
- 0x00, 0x00, 0x00, 0x00, // reserved
1540
- duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
1541
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
1542
- 0x00, 0x00, // layer
1543
- 0x00, 0x00, // alternate_group
1544
- volume >> 0 & 0xff, volume % 1 * 10 >> 0 & 0xff, // track volume // FIXME
1545
- 0x00, 0x00, // reserved
1546
- 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
1547
- width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
1548
- height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
1549
- ]));
1550
- }
1551
- }, {
1552
- key: "traf",
1553
- value: function traf(track, baseMediaDecodeTime) {
1554
- var sampleDependencyTable = MP4.sdtp(track),
1555
- id = track.id;
1556
- return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
1557
- 0x00, 0x00, 0x00, // flags
1558
- id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF // track_ID
1559
- ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x00, // version 0
1560
- 0x00, 0x00, 0x00, // flags
1561
- baseMediaDecodeTime >> 24, baseMediaDecodeTime >> 16 & 0XFF, baseMediaDecodeTime >> 8 & 0XFF, baseMediaDecodeTime & 0xFF // baseMediaDecodeTime
1562
- ])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
1563
- 16 + // tfdt
1564
- 8 + // traf header
1565
- 16 + // mfhd
1566
- 8 + // moof header
1567
- 8), // mdat header
1568
- sampleDependencyTable);
1569
- }
1570
- /**
1571
- * Generate a track box.
1572
- * @param track {object} a track definition
1573
- * @return {Uint8Array} the track box
1574
- */
1575
-
1576
- }, {
1577
- key: "trak",
1578
- value: function trak(track) {
1579
- track.duration = track.duration || 0xffffffff;
1580
- return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
1581
- }
1582
- }, {
1583
- key: "trex",
1584
- value: function trex(track) {
1585
- var id = track.id;
1586
- return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
1587
- 0x00, 0x00, 0x00, // flags
1588
- id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
1589
- 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
1590
- 0x00, 0x00, 0x00, 0x00, // default_sample_duration
1591
- 0x00, 0x00, 0x00, 0x00, // default_sample_size
1592
- 0x00, 0x01, 0x00, 0x01 // default_sample_flags
1593
- ]));
1594
- }
1595
- }, {
1596
- key: "trun",
1597
- value: function trun(track, offset) {
1598
- var samples = track.samples || [],
1599
- len = samples.length,
1600
- arraylen = 12 + 16 * len,
1601
- array = new Uint8Array(arraylen),
1602
- i,
1603
- sample,
1604
- duration,
1605
- size,
1606
- flags,
1607
- cts;
1608
- offset += 8 + arraylen;
1609
- array.set([0x00, // version 0
1610
- 0x00, 0x0f, 0x01, // flags
1611
- len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
1612
- offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
1613
- ], 0);
1614
-
1615
- for (i = 0; i < len; i++) {
1616
- sample = samples[i];
1617
- duration = sample.duration;
1618
- size = sample.size;
1619
- flags = sample.flags;
1620
- cts = sample.cts;
1621
- array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
1622
- size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
1623
- flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
1624
- cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
1625
- ], 12 + 16 * i);
1626
- }
1627
-
1628
- return MP4.box(MP4.types.trun, array);
1629
- }
1630
- }, {
1631
- key: "initSegment",
1632
- value: function initSegment(tracks, duration, timescale) {
1633
- if (!MP4.types) {
1634
- MP4.init();
1635
- }
1636
-
1637
- var movie = MP4.moov(tracks, duration, timescale),
1638
- result;
1639
- result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
1640
- result.set(MP4.FTYP);
1641
- result.set(movie, MP4.FTYP.byteLength);
1642
- return result;
1643
- }
1644
- }]);
1645
-
1646
- return MP4;
1647
- }();
1648
-
1649
- var track_id = 1;
1650
- var BaseRemuxer = /*#__PURE__*/function () {
1651
- function BaseRemuxer() {
1652
- _classCallCheck(this, BaseRemuxer);
1653
- }
1654
-
1655
- _createClass(BaseRemuxer, [{
1656
- key: "flush",
1657
- value: function flush() {
1658
- this.mp4track.len = 0;
1659
- this.mp4track.samples = [];
1660
- }
1661
- }, {
1662
- key: "isReady",
1663
- value: function isReady() {
1664
- if (!this.readyToDecode || !this.samples.length) return null;
1665
- return true;
1666
- }
1667
- }], [{
1668
- key: "getTrackID",
1669
- value: function getTrackID() {
1670
- return track_id++;
1671
- }
1672
- }]);
1673
-
1674
- return BaseRemuxer;
1675
- }();
1676
-
1677
- var AACRemuxer = /*#__PURE__*/function (_BaseRemuxer) {
1678
- _inherits(AACRemuxer, _BaseRemuxer);
1679
-
1680
- var _super = _createSuper(AACRemuxer);
1681
-
1682
- function AACRemuxer(timescale) {
1683
- var _this;
1684
-
1685
- _classCallCheck(this, AACRemuxer);
1686
-
1687
- _this = _super.call(this);
1688
- _this.readyToDecode = false;
1689
- _this.nextDts = 0;
1690
- _this.dts = 0;
1691
- _this.mp4track = {
1692
- id: BaseRemuxer.getTrackID(),
1693
- type: 'audio',
1694
- channelCount: 0,
1695
- len: 0,
1696
- fragmented: true,
1697
- timescale: timescale,
1698
- duration: timescale,
1699
- samples: [],
1700
- config: '',
1701
- codec: ''
1702
- };
1703
- _this.samples = [];
1704
- _this.aac = new AACParser(_assertThisInitialized(_this));
1705
- return _this;
1706
- }
1707
-
1708
- _createClass(AACRemuxer, [{
1709
- key: "resetTrack",
1710
- value: function resetTrack() {
1711
- this.readyToDecode = false;
1712
- this.mp4track.codec = '';
1713
- this.mp4track.channelCount = '';
1714
- this.mp4track.config = '';
1715
- this.mp4track.timescale = this.timescale;
1716
- this.nextDts = 0;
1717
- this.dts = 0;
1718
- }
1719
- }, {
1720
- key: "remux",
1721
- value: function remux(frames) {
1722
- if (frames.length > 0) {
1723
- for (var i = 0; i < frames.length; i++) {
1724
- var frame = frames[i];
1725
- var payload = frame.units;
1726
- var size = payload.byteLength;
1727
- this.samples.push({
1728
- units: payload,
1729
- size: size,
1730
- duration: frame.duration
1731
- });
1732
- this.mp4track.len += size;
1733
-
1734
- if (!this.readyToDecode) {
1735
- this.aac.setAACConfig();
1736
- }
1737
- }
1738
- }
1739
- }
1740
- }, {
1741
- key: "getPayload",
1742
- value: function getPayload() {
1743
- if (!this.isReady()) {
1744
- return null;
1745
- }
1746
-
1747
- var payload = new Uint8Array(this.mp4track.len);
1748
- var offset = 0;
1749
- var samples = this.mp4track.samples;
1750
- var mp4Sample, duration;
1751
- this.dts = this.nextDts;
1752
-
1753
- while (this.samples.length) {
1754
- var sample = this.samples.shift();
1755
- sample.units;
1756
- duration = sample.duration;
1757
-
1758
- if (duration <= 0) {
1759
- log("remuxer: invalid sample duration at DTS: ".concat(this.nextDts, " :").concat(duration));
1760
- this.mp4track.len -= sample.size;
1761
- continue;
1762
- }
1763
-
1764
- this.nextDts += duration;
1765
- mp4Sample = {
1766
- size: sample.size,
1767
- duration: duration,
1768
- cts: 0,
1769
- flags: {
1770
- isLeading: 0,
1771
- isDependedOn: 0,
1772
- hasRedundancy: 0,
1773
- degradPrio: 0,
1774
- dependsOn: 1
1775
- }
1776
- };
1777
- payload.set(sample.units, offset);
1778
- offset += sample.size;
1779
- samples.push(mp4Sample);
1780
- }
1781
-
1782
- if (!samples.length) return null;
1783
- return new Uint8Array(payload.buffer, 0, this.mp4track.len);
1784
- }
1785
- }]);
1786
-
1787
- return AACRemuxer;
1788
- }(BaseRemuxer);
1789
-
1790
- var H264Remuxer = /*#__PURE__*/function (_BaseRemuxer) {
1791
- _inherits(H264Remuxer, _BaseRemuxer);
1792
-
1793
- var _super = _createSuper(H264Remuxer);
1794
-
1795
- function H264Remuxer(timescale) {
1796
- var _this;
1797
-
1798
- _classCallCheck(this, H264Remuxer);
1799
-
1800
- _this = _super.call(this);
1801
- _this.readyToDecode = false;
1802
- _this.nextDts = 0;
1803
- _this.dts = 0;
1804
- _this.mp4track = {
1805
- id: BaseRemuxer.getTrackID(),
1806
- type: 'video',
1807
- len: 0,
1808
- fragmented: true,
1809
- sps: '',
1810
- pps: '',
1811
- fps: 30,
1812
- width: 0,
1813
- height: 0,
1814
- timescale: timescale,
1815
- duration: timescale,
1816
- samples: []
1817
- };
1818
- _this.samples = [];
1819
- _this.h264 = new H264Parser(_assertThisInitialized(_this));
1820
- return _this;
1821
- }
1822
-
1823
- _createClass(H264Remuxer, [{
1824
- key: "resetTrack",
1825
- value: function resetTrack() {
1826
- this.readyToDecode = false;
1827
- this.mp4track.sps = '';
1828
- this.mp4track.pps = '';
1829
- this.nextDts = 0;
1830
- this.dts = 0;
1831
- }
1832
- }, {
1833
- key: "remux",
1834
- value: function remux(frames) {
1835
- var _iterator = _createForOfIteratorHelper(frames),
1836
- _step;
1837
-
1838
- try {
1839
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1840
- var frame = _step.value;
1841
- var units = [];
1842
- var size = 0;
1843
-
1844
- var _iterator2 = _createForOfIteratorHelper(frame.units),
1845
- _step2;
1846
-
1847
- try {
1848
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1849
- var unit = _step2.value;
1850
-
1851
- if (this.h264.parseNAL(unit)) {
1852
- units.push(unit);
1853
- size += unit.getSize();
1854
- }
1855
- }
1856
- } catch (err) {
1857
- _iterator2.e(err);
1858
- } finally {
1859
- _iterator2.f();
1860
- }
1861
-
1862
- if (units.length > 0 && this.readyToDecode) {
1863
- this.mp4track.len += size;
1864
- this.samples.push({
1865
- units: units,
1866
- size: size,
1867
- keyFrame: frame.keyFrame,
1868
- duration: frame.duration
1869
- });
1870
- }
1871
- }
1872
- } catch (err) {
1873
- _iterator.e(err);
1874
- } finally {
1875
- _iterator.f();
1876
- }
1877
- }
1878
- }, {
1879
- key: "getPayload",
1880
- value: function getPayload() {
1881
- if (!this.isReady()) {
1882
- return null;
1883
- }
1884
-
1885
- var payload = new Uint8Array(this.mp4track.len);
1886
- var offset = 0;
1887
- var samples = this.mp4track.samples;
1888
- var mp4Sample, duration;
1889
- this.dts = this.nextDts;
1890
-
1891
- while (this.samples.length) {
1892
- var sample = this.samples.shift(),
1893
- units = sample.units;
1894
- duration = sample.duration;
1895
-
1896
- if (duration <= 0) {
1897
- log("remuxer: invalid sample duration at DTS: ".concat(this.nextDts, " :").concat(duration));
1898
- this.mp4track.len -= sample.size;
1899
- continue;
1900
- }
1901
-
1902
- this.nextDts += duration;
1903
- mp4Sample = {
1904
- size: sample.size,
1905
- duration: duration,
1906
- cts: 0,
1907
- flags: {
1908
- isLeading: 0,
1909
- isDependedOn: 0,
1910
- hasRedundancy: 0,
1911
- degradPrio: 0,
1912
- isNonSync: sample.keyFrame ? 0 : 1,
1913
- dependsOn: sample.keyFrame ? 2 : 1
1914
- }
1915
- };
1916
-
1917
- var _iterator3 = _createForOfIteratorHelper(units),
1918
- _step3;
1919
-
1920
- try {
1921
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1922
- var unit = _step3.value;
1923
- payload.set(unit.getData(), offset);
1924
- offset += unit.getSize();
1925
- }
1926
- } catch (err) {
1927
- _iterator3.e(err);
1928
- } finally {
1929
- _iterator3.f();
1930
- }
1931
-
1932
- samples.push(mp4Sample);
1933
- }
1934
-
1935
- if (!samples.length) return null;
1936
- return new Uint8Array(payload.buffer, 0, this.mp4track.len);
1937
- }
1938
- }]);
1939
-
1940
- return H264Remuxer;
1941
- }(BaseRemuxer);
1942
-
1943
- var RemuxController = /*#__PURE__*/function (_Event) {
1944
- _inherits(RemuxController, _Event);
1945
-
1946
- var _super = _createSuper(RemuxController);
1947
-
1948
- function RemuxController(env) {
1949
- var _this;
1950
-
1951
- _classCallCheck(this, RemuxController);
1952
-
1953
- _this = _super.call(this, 'remuxer');
1954
- _this.initialized = false;
1955
- _this.trackTypes = [];
1956
- _this.tracks = {};
1957
- _this.seq = 1;
1958
- _this.env = env;
1959
- _this.timescale = 1000;
1960
- _this.mediaDuration = 0;
1961
- return _this;
1962
- }
1963
-
1964
- _createClass(RemuxController, [{
1965
- key: "addTrack",
1966
- value: function addTrack(type) {
1967
- if (type === 'video' || type === 'both') {
1968
- this.tracks.video = new H264Remuxer(this.timescale);
1969
- this.trackTypes.push('video');
1970
- }
1971
-
1972
- if (type === 'audio' || type === 'both') {
1973
- this.tracks.audio = new AACRemuxer(this.timescale);
1974
- this.trackTypes.push('audio');
1975
- }
1976
- }
1977
- }, {
1978
- key: "reset",
1979
- value: function reset() {
1980
- var _iterator = _createForOfIteratorHelper(this.trackTypes),
1981
- _step;
1982
-
1983
- try {
1984
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1985
- var type = _step.value;
1986
- this.tracks[type].resetTrack();
1987
- }
1988
- } catch (err) {
1989
- _iterator.e(err);
1990
- } finally {
1991
- _iterator.f();
1992
- }
1993
-
1994
- this.initialized = false;
1995
- }
1996
- }, {
1997
- key: "destroy",
1998
- value: function destroy() {
1999
- this.tracks = {};
2000
- this.offAll();
2001
- }
2002
- }, {
2003
- key: "flush",
2004
- value: function flush() {
2005
- if (!this.initialized) {
2006
- if (this.isReady()) {
2007
- this.dispatch('ready');
2008
- this.initSegment();
2009
- this.initialized = true;
2010
- this.flush();
2011
- }
2012
- } else {
2013
- var _iterator2 = _createForOfIteratorHelper(this.trackTypes),
2014
- _step2;
2015
-
2016
- try {
2017
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2018
- var type = _step2.value;
2019
- var track = this.tracks[type];
2020
- var pay = track.getPayload();
2021
-
2022
- if (pay && pay.byteLength) {
2023
- var moof = MP4.moof(this.seq, track.dts, track.mp4track);
2024
- var mdat = MP4.mdat(pay);
2025
- var payload = appendByteArray(moof, mdat);
2026
- var data = {
2027
- type: type,
2028
- payload: payload,
2029
- dts: track.dts
2030
- };
2031
-
2032
- if (type === 'video') {
2033
- data.fps = track.mp4track.fps;
2034
- }
2035
-
2036
- this.dispatch('buffer', data);
2037
- var duration = secToTime(track.dts / this.timescale);
2038
- log("put segment (".concat(type, "): dts: ").concat(track.dts, " frames: ").concat(track.mp4track.samples.length, " second: ").concat(duration));
2039
- track.flush();
2040
- this.seq++;
2041
- }
2042
- }
2043
- } catch (err) {
2044
- _iterator2.e(err);
2045
- } finally {
2046
- _iterator2.f();
2047
- }
2048
- }
2049
- }
2050
- }, {
2051
- key: "initSegment",
2052
- value: function initSegment() {
2053
- var tracks = [];
2054
-
2055
- var _iterator3 = _createForOfIteratorHelper(this.trackTypes),
2056
- _step3;
2057
-
2058
- try {
2059
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2060
- var type = _step3.value;
2061
- var track = this.tracks[type];
2062
-
2063
- if (this.env == 'browser') {
2064
- var _data = {
2065
- type: type,
2066
- payload: MP4.initSegment([track.mp4track], this.mediaDuration, this.timescale)
2067
- };
2068
- this.dispatch('buffer', _data);
2069
- } else {
2070
- tracks.push(track.mp4track);
2071
- }
2072
- }
2073
- } catch (err) {
2074
- _iterator3.e(err);
2075
- } finally {
2076
- _iterator3.f();
2077
- }
2078
-
2079
- if (this.env == 'node') {
2080
- var data = {
2081
- type: 'all',
2082
- payload: MP4.initSegment(tracks, this.mediaDuration, this.timescale)
2083
- };
2084
- this.dispatch('buffer', data);
2085
- }
2086
-
2087
- log('Initial segment generated.');
2088
- }
2089
- }, {
2090
- key: "isReady",
2091
- value: function isReady() {
2092
- var _iterator4 = _createForOfIteratorHelper(this.trackTypes),
2093
- _step4;
2094
-
2095
- try {
2096
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2097
- var type = _step4.value;
2098
- if (!this.tracks[type].readyToDecode || !this.tracks[type].samples.length) return false;
2099
- }
2100
- } catch (err) {
2101
- _iterator4.e(err);
2102
- } finally {
2103
- _iterator4.f();
2104
- }
2105
-
2106
- return true;
2107
- }
2108
- }, {
2109
- key: "remux",
2110
- value: function remux(data) {
2111
- var _iterator5 = _createForOfIteratorHelper(this.trackTypes),
2112
- _step5;
2113
-
2114
- try {
2115
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2116
- var type = _step5.value;
2117
- var frames = data[type];
2118
- if (type === 'audio' && this.tracks.video && !this.tracks.video.readyToDecode) continue;
2119
- /* if video is present, don't add audio until video get ready */
2120
-
2121
- if (frames.length > 0) {
2122
- this.tracks[type].remux(frames);
2123
- }
2124
- }
2125
- } catch (err) {
2126
- _iterator5.e(err);
2127
- } finally {
2128
- _iterator5.f();
2129
- }
2130
-
2131
- this.flush();
2132
- }
2133
- }]);
2134
-
2135
- return RemuxController;
2136
- }(Event);
2137
-
2138
- var BufferController = /*#__PURE__*/function (_Event) {
2139
- _inherits(BufferController, _Event);
2140
-
2141
- var _super = _createSuper(BufferController);
2142
-
2143
- function BufferController(sourceBuffer, type) {
2144
- var _this;
2145
-
2146
- _classCallCheck(this, BufferController);
2147
-
2148
- _this = _super.call(this, 'buffer');
2149
- _this.type = type;
2150
- _this.queue = new Uint8Array();
2151
- _this.cleaning = false;
2152
- _this.pendingCleaning = 0;
2153
- _this.cleanOffset = 30;
2154
- _this.cleanRanges = [];
2155
- _this.sourceBuffer = sourceBuffer;
2156
-
2157
- _this.sourceBuffer.addEventListener('updateend', function () {
2158
- if (_this.pendingCleaning > 0) {
2159
- _this.initCleanup(_this.pendingCleaning);
2160
-
2161
- _this.pendingCleaning = 0;
2162
- }
2163
-
2164
- _this.cleaning = false;
2165
-
2166
- if (_this.cleanRanges.length) {
2167
- _this.doCleanup();
2168
-
2169
- return;
2170
- }
2171
- });
2172
-
2173
- _this.sourceBuffer.addEventListener('error', function () {
2174
- _this.dispatch('error', {
2175
- type: _this.type,
2176
- name: 'buffer',
2177
- error: 'buffer error'
2178
- });
2179
- });
2180
-
2181
- return _this;
2182
- }
2183
-
2184
- _createClass(BufferController, [{
2185
- key: "destroy",
2186
- value: function destroy() {
2187
- this.queue = null;
2188
- this.sourceBuffer = null;
2189
- this.offAll();
2190
- }
2191
- }, {
2192
- key: "doCleanup",
2193
- value: function doCleanup() {
2194
- if (!this.cleanRanges.length) {
2195
- this.cleaning = false;
2196
- return;
2197
- }
2198
-
2199
- var range = this.cleanRanges.shift();
2200
- log("".concat(this.type, " remove range [").concat(range[0], " - ").concat(range[1], ")"));
2201
- this.cleaning = true;
2202
- this.sourceBuffer.remove(range[0], range[1]);
2203
- }
2204
- }, {
2205
- key: "initCleanup",
2206
- value: function initCleanup(cleanMaxLimit) {
2207
- try {
2208
- if (this.sourceBuffer.updating) {
2209
- this.pendingCleaning = cleanMaxLimit;
2210
- return;
2211
- }
2212
-
2213
- if (this.sourceBuffer.buffered && this.sourceBuffer.buffered.length && !this.cleaning) {
2214
- for (var i = 0; i < this.sourceBuffer.buffered.length; ++i) {
2215
- var start = this.sourceBuffer.buffered.start(i);
2216
- var end = this.sourceBuffer.buffered.end(i);
2217
-
2218
- if (cleanMaxLimit - start > this.cleanOffset) {
2219
- end = cleanMaxLimit - this.cleanOffset;
2220
-
2221
- if (start < end) {
2222
- this.cleanRanges.push([start, end]);
2223
- }
2224
- }
2225
- }
2226
-
2227
- this.doCleanup();
2228
- }
2229
- } catch (e) {
2230
- error("Error occured while cleaning ".concat(this.type, " buffer - ").concat(e.name, ": ").concat(e.message));
2231
- }
2232
- }
2233
- }, {
2234
- key: "doAppend",
2235
- value: function doAppend() {
2236
- if (!this.queue.length) return;
2237
- if (!this.sourceBuffer || this.sourceBuffer.updating) return;
2238
-
2239
- try {
2240
- this.sourceBuffer.appendBuffer(this.queue);
2241
- this.queue = new Uint8Array();
2242
- } catch (e) {
2243
- var name = 'unexpectedError';
2244
-
2245
- if (e.name === 'QuotaExceededError') {
2246
- log("".concat(this.type, " buffer quota full"));
2247
- name = 'QuotaExceeded';
2248
- } else {
2249
- error("Error occured while appending ".concat(this.type, " buffer - ").concat(e.name, ": ").concat(e.message));
2250
- name = 'InvalidStateError';
2251
- }
2252
-
2253
- this.dispatch('error', {
2254
- type: this.type,
2255
- name: name,
2256
- error: 'buffer error'
2257
- });
2258
- }
2259
- }
2260
- }, {
2261
- key: "feed",
2262
- value: function feed(data) {
2263
- this.queue = appendByteArray(this.queue, data);
2264
- }
2265
- }]);
2266
-
2267
- return BufferController;
2268
- }(Event);
2269
-
2270
- var JMuxer = /*#__PURE__*/function (_Event) {
2271
- _inherits(JMuxer, _Event);
2272
-
2273
- var _super = _createSuper(JMuxer);
2274
-
2275
- function JMuxer(options) {
2276
- var _this;
2277
-
2278
- _classCallCheck(this, JMuxer);
2279
-
2280
- _this = _super.call(this, 'jmuxer');
2281
- _this.isReset = false;
2282
- var defaults = {
2283
- node: '',
2284
- mode: 'both',
2285
- // both, audio, video
2286
- flushingTime: 1500,
2287
- maxDelay: 500,
2288
- clearBuffer: true,
2289
- fps: 30,
2290
- readFpsFromTrack: false,
2291
- // defaults to false to keep existing functionality
2292
- debug: false,
2293
- onReady: function onReady() {},
2294
- // function called when MSE is ready to accept frames
2295
- onError: function onError() {} // function called when jmuxer encounters any buffer related error
2296
-
2297
- };
2298
- _this.options = Object.assign({}, defaults, options);
2299
- _this.env = (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && typeof window === 'undefined' ? 'node' : 'browser';
2300
-
2301
- if (_this.options.debug) {
2302
- setLogger();
2303
- }
2304
-
2305
- if (!_this.options.fps) {
2306
- _this.options.fps = 30;
2307
- }
2308
-
2309
- _this.frameDuration = 1000 / _this.options.fps | 0;
2310
- _this.remuxController = new RemuxController(_this.env);
2311
-
2312
- _this.remuxController.addTrack(_this.options.mode);
2313
-
2314
- _this.initData();
2315
- /* events callback */
2316
-
2317
-
2318
- _this.remuxController.on('buffer', _this.onBuffer.bind(_assertThisInitialized(_this)));
2319
-
2320
- if (_this.env == 'browser') {
2321
- _this.remuxController.on('ready', _this.createBuffer.bind(_assertThisInitialized(_this)));
2322
-
2323
- _this.initBrowser();
2324
- }
2325
-
2326
- return _this;
2327
- }
2328
-
2329
- _createClass(JMuxer, [{
2330
- key: "initData",
2331
- value: function initData() {
2332
- this.lastCleaningTime = Date.now();
2333
- this.kfPosition = [];
2334
- this.kfCounter = 0;
2335
- this.pendingUnits = {};
2336
- this.remainingData = new Uint8Array();
2337
- this.startInterval();
2338
- }
2339
- }, {
2340
- key: "initBrowser",
2341
- value: function initBrowser() {
2342
- if (typeof this.options.node === 'string' && this.options.node == '') {
2343
- error('no video element were found to render, provide a valid video element');
2344
- }
2345
-
2346
- this.node = typeof this.options.node === 'string' ? document.getElementById(this.options.node) : this.options.node;
2347
- this.mseReady = false;
2348
- this.setupMSE();
2349
- }
2350
- }, {
2351
- key: "createStream",
2352
- value: function createStream() {
2353
- var feed = this.feed.bind(this);
2354
- var destroy = this.destroy.bind(this);
2355
- this.stream = new stream.Duplex({
2356
- writableObjectMode: true,
2357
- read: function read(size) {},
2358
- write: function write(data, encoding, callback) {
2359
- feed(data);
2360
- callback();
2361
- },
2362
- "final": function final(callback) {
2363
- destroy();
2364
- callback();
2365
- }
2366
- });
2367
- return this.stream;
2368
- }
2369
- }, {
2370
- key: "setupMSE",
2371
- value: function setupMSE() {
2372
- window.MediaSource = window.MediaSource || window.WebKitMediaSource;
2373
-
2374
- if (!window.MediaSource) {
2375
- throw 'Oops! Browser does not support media source extension.';
2376
- }
2377
-
2378
- this.isMSESupported = !!window.MediaSource;
2379
- this.mediaSource = new MediaSource();
2380
- this.url = URL.createObjectURL(this.mediaSource);
2381
- this.node.src = this.url;
2382
- this.mseEnded = false;
2383
- this.mediaSource.addEventListener('sourceopen', this.onMSEOpen.bind(this));
2384
- this.mediaSource.addEventListener('sourceclose', this.onMSEClose.bind(this));
2385
- this.mediaSource.addEventListener('webkitsourceopen', this.onMSEOpen.bind(this));
2386
- this.mediaSource.addEventListener('webkitsourceclose', this.onMSEClose.bind(this));
2387
- }
2388
- }, {
2389
- key: "endMSE",
2390
- value: function endMSE() {
2391
- if (!this.mseEnded) {
2392
- try {
2393
- this.mseEnded = true;
2394
- this.mediaSource.endOfStream();
2395
- } catch (e) {
2396
- error('mediasource is not available to end');
2397
- }
2398
- }
2399
- }
2400
- }, {
2401
- key: "feed",
2402
- value: function feed(data) {
2403
- var remux = false,
2404
- slices,
2405
- left,
2406
- duration,
2407
- chunks = {
2408
- video: [],
2409
- audio: []
2410
- };
2411
- if (!data || !this.remuxController) return;
2412
- duration = data.duration ? parseInt(data.duration) : 0;
2413
-
2414
- if (data.video) {
2415
- data.video = appendByteArray(this.remainingData, data.video);
2416
-
2417
- var _H264Parser$extractNA = H264Parser.extractNALu(data.video);
2418
-
2419
- var _H264Parser$extractNA2 = _slicedToArray(_H264Parser$extractNA, 2);
2420
-
2421
- slices = _H264Parser$extractNA2[0];
2422
- left = _H264Parser$extractNA2[1];
2423
- this.remainingData = left || new Uint8Array();
2424
-
2425
- if (slices.length > 0) {
2426
- chunks.video = this.getVideoFrames(slices, duration);
2427
- remux = true;
2428
- } else {
2429
- error('Failed to extract any NAL units from video data:', left);
2430
- return;
2431
- }
2432
- }
2433
-
2434
- if (data.audio) {
2435
- slices = AACParser.extractAAC(data.audio);
2436
-
2437
- if (slices.length > 0) {
2438
- chunks.audio = this.getAudioFrames(slices, duration);
2439
- remux = true;
2440
- } else {
2441
- error('Failed to extract audio data from:', data.audio);
2442
- return;
2443
- }
2444
- }
2445
-
2446
- if (!remux) {
2447
- error('Input object must have video and/or audio property. Make sure it is a valid typed array');
2448
- return;
2449
- }
2450
-
2451
- this.remuxController.remux(chunks);
2452
- }
2453
- }, {
2454
- key: "getVideoFrames",
2455
- value: function getVideoFrames(nalus, duration) {
2456
- var _this2 = this;
2457
-
2458
- var units = [],
2459
- frames = [],
2460
- fd = 0,
2461
- tt = 0,
2462
- keyFrame = false,
2463
- vcl = false;
2464
-
2465
- if (this.pendingUnits.units) {
2466
- units = this.pendingUnits.units;
2467
- vcl = this.pendingUnits.vcl;
2468
- keyFrame = this.pendingUnits.keyFrame;
2469
- this.pendingUnits = {};
2470
- }
2471
-
2472
- var _iterator = _createForOfIteratorHelper(nalus),
2473
- _step;
2474
-
2475
- try {
2476
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2477
- var nalu = _step.value;
2478
- var unit = new NALU(nalu);
2479
-
2480
- if (unit.type() === NALU.IDR || unit.type() === NALU.NDR) {
2481
- H264Parser.parseHeader(unit);
2482
- }
2483
-
2484
- if (units.length && vcl && (unit.isfmb || !unit.isvcl)) {
2485
- frames.push({
2486
- units: units,
2487
- keyFrame: keyFrame
2488
- });
2489
- units = [];
2490
- keyFrame = false;
2491
- vcl = false;
2492
- }
2493
-
2494
- units.push(unit);
2495
- keyFrame = keyFrame || unit.isKeyframe();
2496
- vcl = vcl || unit.isvcl;
2497
- }
2498
- } catch (err) {
2499
- _iterator.e(err);
2500
- } finally {
2501
- _iterator.f();
2502
- }
2503
-
2504
- if (units.length) {
2505
- // lets keep indecisive nalus as pending in case of fixed fps
2506
- if (!duration) {
2507
- this.pendingUnits = {
2508
- units: units,
2509
- keyFrame: keyFrame,
2510
- vcl: vcl
2511
- };
2512
- } else if (vcl) {
2513
- frames.push({
2514
- units: units,
2515
- keyFrame: keyFrame
2516
- });
2517
- } else {
2518
- var last = frames.length - 1;
2519
-
2520
- if (last >= 0) {
2521
- frames[last].units = frames[last].units.concat(units);
2522
- }
2523
- }
2524
- }
2525
-
2526
- fd = duration ? duration / frames.length | 0 : this.frameDuration;
2527
- tt = duration ? duration - fd * frames.length : 0;
2528
- frames.map(function (frame) {
2529
- frame.duration = fd;
2530
-
2531
- if (tt > 0) {
2532
- frame.duration++;
2533
- tt--;
2534
- }
2535
-
2536
- _this2.kfCounter++;
2537
-
2538
- if (frame.keyFrame && _this2.options.clearBuffer) {
2539
- _this2.kfPosition.push(_this2.kfCounter * fd / 1000);
2540
- }
2541
- });
2542
- log("jmuxer: No. of frames of the last chunk: ".concat(frames.length));
2543
- return frames;
2544
- }
2545
- }, {
2546
- key: "getAudioFrames",
2547
- value: function getAudioFrames(aacFrames, duration) {
2548
- var frames = [],
2549
- fd = 0,
2550
- tt = 0;
2551
-
2552
- var _iterator2 = _createForOfIteratorHelper(aacFrames),
2553
- _step2;
2554
-
2555
- try {
2556
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2557
- var units = _step2.value;
2558
- frames.push({
2559
- units: units
2560
- });
2561
- }
2562
- } catch (err) {
2563
- _iterator2.e(err);
2564
- } finally {
2565
- _iterator2.f();
2566
- }
2567
-
2568
- fd = duration ? duration / frames.length | 0 : this.frameDuration;
2569
- tt = duration ? duration - fd * frames.length : 0;
2570
- frames.map(function (frame) {
2571
- frame.duration = fd;
2572
-
2573
- if (tt > 0) {
2574
- frame.duration++;
2575
- tt--;
2576
- }
2577
- });
2578
- return frames;
2579
- }
2580
- }, {
2581
- key: "destroy",
2582
- value: function destroy() {
2583
- this.stopInterval();
2584
-
2585
- if (this.stream) {
2586
- this.remuxController.flush();
2587
- this.stream.push(null);
2588
- this.stream = null;
2589
- }
2590
-
2591
- if (this.remuxController) {
2592
- this.remuxController.destroy();
2593
- this.remuxController = null;
2594
- }
2595
-
2596
- if (this.bufferControllers) {
2597
- for (var type in this.bufferControllers) {
2598
- this.bufferControllers[type].destroy();
2599
- }
2600
-
2601
- this.bufferControllers = null;
2602
- this.endMSE();
2603
- }
2604
-
2605
- this.node = false;
2606
- this.mseReady = false;
2607
- this.videoStarted = false;
2608
- this.mediaSource = null;
2609
- }
2610
- }, {
2611
- key: "reset",
2612
- value: function reset() {
2613
- this.stopInterval();
2614
- this.isReset = true;
2615
- this.node.pause();
2616
-
2617
- if (this.remuxController) {
2618
- this.remuxController.reset();
2619
- }
2620
-
2621
- if (this.bufferControllers) {
2622
- for (var type in this.bufferControllers) {
2623
- this.bufferControllers[type].destroy();
2624
- }
2625
-
2626
- this.bufferControllers = null;
2627
- this.endMSE();
2628
- }
2629
-
2630
- this.initData();
2631
-
2632
- if (this.env == 'browser') {
2633
- this.initBrowser();
2634
- }
2635
-
2636
- log('JMuxer was reset');
2637
- }
2638
- }, {
2639
- key: "createBuffer",
2640
- value: function createBuffer() {
2641
- if (!this.mseReady || !this.remuxController || !this.remuxController.isReady() || this.bufferControllers) return;
2642
- this.bufferControllers = {};
2643
-
2644
- for (var type in this.remuxController.tracks) {
2645
- var track = this.remuxController.tracks[type];
2646
-
2647
- if (!JMuxer.isSupported("".concat(type, "/mp4; codecs=\"").concat(track.mp4track.codec, "\""))) {
2648
- error('Browser does not support codec');
2649
- return false;
2650
- }
2651
-
2652
- var sb = this.mediaSource.addSourceBuffer("".concat(type, "/mp4; codecs=\"").concat(track.mp4track.codec, "\""));
2653
- this.bufferControllers[type] = new BufferController(sb, type);
2654
- this.bufferControllers[type].on('error', this.onBufferError.bind(this));
2655
- }
2656
- }
2657
- }, {
2658
- key: "startInterval",
2659
- value: function startInterval() {
2660
- var _this3 = this;
2661
-
2662
- this.interval = setInterval(function () {
2663
- if (_this3.options.flushingTime) {
2664
- _this3.applyAndClearBuffer();
2665
- } else if (_this3.bufferControllers) {
2666
- _this3.cancelDelay();
2667
- }
2668
- }, this.options.flushingTime || 1000);
2669
- }
2670
- }, {
2671
- key: "stopInterval",
2672
- value: function stopInterval() {
2673
- if (this.interval) {
2674
- clearInterval(this.interval);
2675
- }
2676
- }
2677
- }, {
2678
- key: "cancelDelay",
2679
- value: function cancelDelay() {
2680
- if (this.options.node.buffered && this.options.node.buffered.length > 0 && !this.options.node.seeking) {
2681
- var end = this.options.node.buffered.end(0);
2682
-
2683
- if (end - this.options.node.currentTime > this.options.maxDelay / 1000) {
2684
- console.log('delay', this.delay++);
2685
- this.options.node.currentTime = end - 0.001;
2686
- }
2687
- }
2688
- }
2689
- }, {
2690
- key: "releaseBuffer",
2691
- value: function releaseBuffer() {
2692
- for (var type in this.bufferControllers) {
2693
- this.bufferControllers[type].doAppend();
2694
- }
2695
- }
2696
- }, {
2697
- key: "applyAndClearBuffer",
2698
- value: function applyAndClearBuffer() {
2699
- if (this.bufferControllers) {
2700
- this.releaseBuffer();
2701
- this.clearBuffer();
2702
- }
2703
- }
2704
- }, {
2705
- key: "getSafeClearOffsetOfBuffer",
2706
- value: function getSafeClearOffsetOfBuffer(offset) {
2707
- var maxLimit = this.options.mode === 'audio' && offset || 0,
2708
- adjacentOffset;
2709
-
2710
- for (var i = 0; i < this.kfPosition.length; i++) {
2711
- if (this.kfPosition[i] >= offset) {
2712
- break;
2713
- }
2714
-
2715
- adjacentOffset = this.kfPosition[i];
2716
- }
2717
-
2718
- if (adjacentOffset) {
2719
- this.kfPosition = this.kfPosition.filter(function (kfDelimiter) {
2720
- if (kfDelimiter < adjacentOffset) {
2721
- maxLimit = kfDelimiter;
2722
- }
2723
-
2724
- return kfDelimiter >= adjacentOffset;
2725
- });
2726
- }
2727
-
2728
- return maxLimit;
2729
- }
2730
- }, {
2731
- key: "clearBuffer",
2732
- value: function clearBuffer() {
2733
- if (this.options.clearBuffer && Date.now() - this.lastCleaningTime > 10000) {
2734
- for (var type in this.bufferControllers) {
2735
- var cleanMaxLimit = this.getSafeClearOffsetOfBuffer(this.node.currentTime);
2736
- this.bufferControllers[type].initCleanup(cleanMaxLimit);
2737
- }
2738
-
2739
- this.lastCleaningTime = Date.now();
2740
- }
2741
- }
2742
- }, {
2743
- key: "onBuffer",
2744
- value: function onBuffer(data) {
2745
- if (this.options.readFpsFromTrack && typeof data.fps !== 'undefined' && this.options.fps != data.fps) {
2746
- this.options.fps = data.fps;
2747
- this.frameDuration = Math.ceil(1000 / data.fps);
2748
- log("JMuxer changed FPS to ".concat(data.fps, " from track data"));
2749
- }
2750
-
2751
- if (this.env == 'browser') {
2752
- if (this.bufferControllers && this.bufferControllers[data.type]) {
2753
- this.bufferControllers[data.type].feed(data.payload);
2754
- }
2755
- } else if (this.stream) {
2756
- this.stream.push(data.payload);
2757
- }
2758
-
2759
- if (this.options.flushingTime === 0) {
2760
- this.applyAndClearBuffer();
2761
- }
2762
- }
2763
- /* Events on MSE */
2764
-
2765
- }, {
2766
- key: "onMSEOpen",
2767
- value: function onMSEOpen() {
2768
- this.mseReady = true;
2769
- URL.revokeObjectURL(this.url); // this.createBuffer();
2770
-
2771
- if (typeof this.options.onReady === 'function') {
2772
- this.options.onReady.call(null, this.isReset);
2773
- }
2774
- }
2775
- }, {
2776
- key: "onMSEClose",
2777
- value: function onMSEClose() {
2778
- this.mseReady = false;
2779
- this.videoStarted = false;
2780
- }
2781
- }, {
2782
- key: "onBufferError",
2783
- value: function onBufferError(data) {
2784
- if (data.name == 'QuotaExceeded') {
2785
- log("JMuxer cleaning ".concat(data.type, " buffer due to QuotaExceeded error"));
2786
- this.bufferControllers[data.type].initCleanup(this.node.currentTime);
2787
- return;
2788
- } else if (data.name == 'InvalidStateError') {
2789
- log('JMuxer is reseting due to InvalidStateError');
2790
- this.reset();
2791
- } else {
2792
- this.endMSE();
2793
- }
2794
-
2795
- if (typeof this.options.onError === 'function') {
2796
- this.options.onError.call(null, data);
2797
- }
2798
- }
2799
- }], [{
2800
- key: "isSupported",
2801
- value: function isSupported(codec) {
2802
- return window.MediaSource && window.MediaSource.isTypeSupported(codec);
2803
- }
2804
- }]);
2805
-
2806
- return JMuxer;
2807
- }(Event);
2808
-
2809
- return JMuxer;
2810
-
2811
- }));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("stream")):"function"==typeof define&&define.amd?define(["stream"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).JMuxer=t(e.stream)}(this,(function(e){"use strict";function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t(e)}function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,n){return t&&r(e.prototype,t),n&&r(e,n),e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&u(e,t)}function o(e){return o=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},o(e)}function u(e,t){return u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},u(e,t)}function c(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function f(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return c(e)}function l(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=o(e);if(t){var i=o(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return f(this,n)}}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==n)return;var r,i,a=[],s=!0,o=!1;try{for(n=n.call(e);!(s=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);s=!0);}catch(e){o=!0,i=e}finally{try{s||null==n.return||n.return()}finally{if(o)throw i}}return a}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e,t){if(e){if("string"==typeof e)return y(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(e,t):void 0}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function p(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=d(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}var v,m;function k(e){if(v){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];v.apply(void 0,[e].concat(n))}}function g(e){if(m){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];m.apply(void 0,[e].concat(n))}}var b=function(){function e(t){n(this,e),this.payload=t,this.nri=(96&this.payload[0])>>5,this.ntype=31&this.payload[0],this.isvcl=1==this.ntype||5==this.ntype,this.stype="",this.isfmb=!1}return i(e,[{key:"toString",value:function(){return"".concat(e.type(this),": NRI: ").concat(this.getNri())}},{key:"getNri",value:function(){return this.nri}},{key:"type",value:function(){return this.ntype}},{key:"isKeyframe",value:function(){return this.ntype===e.IDR}},{key:"getPayload",value:function(){return this.payload}},{key:"getPayloadSize",value:function(){return this.payload.byteLength}},{key:"getSize",value:function(){return 4+this.getPayloadSize()}},{key:"getData",value:function(){var e=new Uint8Array(this.getSize());return new DataView(e.buffer).setUint32(0,this.getSize()-4),e.set(this.getPayload(),4),e}}],[{key:"NDR",get:function(){return 1}},{key:"IDR",get:function(){return 5}},{key:"SEI",get:function(){return 6}},{key:"SPS",get:function(){return 7}},{key:"PPS",get:function(){return 8}},{key:"AUD",get:function(){return 9}},{key:"TYPES",get:function(){var t;return a(t={},e.IDR,"IDR"),a(t,e.SEI,"SEI"),a(t,e.SPS,"SPS"),a(t,e.PPS,"PPS"),a(t,e.NDR,"NDR"),a(t,e.AUD,"AUD"),t}},{key:"type",value:function(t){return t.ntype in e.TYPES?e.TYPES[t.ntype]:"UNKNOWN"}}]),e}();function S(e,t){var n=new Uint8Array((0|e.byteLength)+(0|t.byteLength));return n.set(e,0),n.set(t,0|e.byteLength),n}var w,x=function(){function e(t){n(this,e),this.data=t,this.index=0,this.bitLength=8*t.byteLength}return i(e,[{key:"setData",value:function(e){this.data=e,this.index=0,this.bitLength=8*e.byteLength}},{key:"bitsAvailable",get:function(){return this.bitLength-this.index}},{key:"skipBits",value:function(e){if(this.bitsAvailable<e)return!1;this.index+=e}},{key:"readBits",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this.getBits(e,this.index,t);return n}},{key:"getBits",value:function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(this.bitsAvailable<e)return 0;var r=t%8,i=this.data[t/8|0]&255>>>r,a=8-r;if(a>=e)return n&&(this.index+=e),i>>a-e;n&&(this.index+=a);var s=e-a;return i<<s|this.getBits(s,t+a,n)}},{key:"skipLZ",value:function(){var e;for(e=0;e<this.bitLength-this.index;++e)if(0!==this.getBits(1,this.index+e,!1))return this.index+=e,e;return e}},{key:"skipUEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"skipEG",value:function(){this.skipBits(1+this.skipLZ())}},{key:"readUEG",value:function(){var e=this.skipLZ();return this.readBits(e+1)-1}},{key:"readEG",value:function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}},{key:"readBoolean",value:function(){return 1===this.readBits(1)}},{key:"readUByte",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;return this.readBits(8*e)}},{key:"readUShort",value:function(){return this.readBits(16)}},{key:"readUInt",value:function(){return this.readBits(32)}}]),e}(),A=function(){function e(t){n(this,e),this.remuxer=t,this.track=t.mp4track}return i(e,[{key:"parseSPS",value:function(t){var n=e.readSPS(new Uint8Array(t));this.track.fps=n.fps,this.track.width=n.width,this.track.height=n.height,this.track.sps=[new Uint8Array(t)],this.track.codec="avc1.";for(var r=new DataView(t.buffer,t.byteOffset+1,4),i=0;i<3;++i){var a=r.getUint8(i).toString(16);a.length<2&&(a="0"+a),this.track.codec+=a}}},{key:"parsePPS",value:function(e){this.track.pps=[new Uint8Array(e)]}},{key:"parseNAL",value:function(e){if(!e)return!1;var t=!1;switch(e.type()){case b.IDR:case b.NDR:t=!0;break;case b.PPS:this.track.pps||(this.parsePPS(e.getPayload()),!this.remuxer.readyToDecode&&this.track.pps&&this.track.sps&&(this.remuxer.readyToDecode=!0)),t=!0;break;case b.SPS:this.track.sps||(this.parseSPS(e.getPayload()),!this.remuxer.readyToDecode&&this.track.pps&&this.track.sps&&(this.remuxer.readyToDecode=!0)),t=!0;break;case b.AUD:k("AUD - ignoing");break;case b.SEI:k("SEI - ignoing")}return t}}],[{key:"extractNALu",value:function(e){for(var t,n,r=0,i=e.byteLength,a=0,s=[],o=0;r<i;)switch(t=e[r++],a){case 0:0===t&&(a=1);break;case 1:a=0===t?2:0;break;case 2:case 3:0===t?a=3:1===t&&r<i?(o!=r-a-1&&s.push(e.subarray(o,r-a-1)),o=r,a=0):a=0}return o<i&&(n=e.subarray(o,i)),[s,n]}},{key:"skipScalingList",value:function(e,t){for(var n=8,r=8,i=0;i<t;i++)0!==r&&(r=(n+e.readEG()+256)%256),n=0===r?n:r}},{key:"readSPS",value:function(t){var n,r,i,a,s,o,u=new x(t),c=0,f=0,l=0,h=0,d=1,y=0;u.readUByte();for(var p=[],v=t.byteLength,m=1;m<v;m++)m+2<v&&3===u.readBits(24,!1)?(p.push(u.readBits(8)),p.push(u.readBits(8)),m+=2,u.readBits(8)):p.push(u.readBits(8));if(u.setData(new Uint8Array(p)),n=u.readUByte(),u.readBits(5),u.skipBits(3),u.readUByte(),u.skipUEG(),100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){var k=u.readUEG();if(3===k&&u.skipBits(1),u.skipUEG(),u.skipUEG(),u.skipBits(1),u.readBoolean()){o=3!==k?8:12;for(var g=0;g<o;++g)u.readBoolean()&&(g<6?e.skipScalingList(u,16):e.skipScalingList(u,64))}}u.skipUEG();var b=u.readUEG();if(0===b)u.readUEG();else if(1===b){u.skipBits(1),u.skipEG(),u.skipEG(),r=u.readUEG();for(var S=0;S<r;++S)u.skipEG()}if(u.skipUEG(),u.skipBits(1),i=u.readUEG(),a=u.readUEG(),0===(s=u.readBits(1))&&u.skipBits(1),u.skipBits(1),u.readBoolean()&&(c=u.readUEG(),f=u.readUEG(),l=u.readUEG(),h=u.readUEG()),u.readBoolean()){if(u.readBoolean()){var w;switch(u.readUByte()){case 1:w=[1,1];break;case 2:w=[12,11];break;case 3:w=[10,11];break;case 4:w=[16,11];break;case 5:w=[40,33];break;case 6:w=[24,11];break;case 7:w=[20,11];break;case 8:w=[32,11];break;case 9:w=[80,33];break;case 10:w=[18,11];break;case 11:w=[15,11];break;case 12:w=[64,33];break;case 13:w=[160,99];break;case 14:w=[4,3];break;case 15:w=[3,2];break;case 16:w=[2,1];break;case 255:w=[u.readUByte()<<8|u.readUByte(),u.readUByte()<<8|u.readUByte()]}w&&w[0]>0&&w[1]>0&&(d=w[0]/w[1])}if(u.readBoolean()&&u.skipBits(1),u.readBoolean()&&(u.skipBits(4),u.readBoolean()&&u.skipBits(24)),u.readBoolean()&&(u.skipUEG(),u.skipUEG()),u.readBoolean()){var A=u.readUInt(),U=u.readUInt();u.readBoolean()&&(y=U/(2*A))}}return{fps:y>0?y:void 0,width:Math.ceil((16*(i+1)-2*c-2*f)*d),height:(2-s)*(a+1)*16-(s?2:4)*(l+h)}}},{key:"parseHeader",value:function(e){var t=new x(e.getPayload());t.readUByte(),e.isfmb=0===t.readUEG(),e.stype=t.readUEG()}}]),e}(),U=function(){function e(t){n(this,e),this.remuxer=t,this.track=t.mp4track}return i(e,[{key:"setAACConfig",value:function(){var t,n,r,i=new Uint8Array(2),a=e.getAACHeaderData;a&&(t=1+((192&a[2])>>>6),n=(60&a[2])>>>2,r=(1&a[2])<<2,r|=(192&a[3])>>>6,i[0]=t<<3,i[0]|=(14&n)>>1,i[1]|=(1&n)<<7,i[1]|=r<<3,this.track.codec="mp4a.40."+t,this.track.channelCount=r,this.track.config=i,this.remuxer.readyToDecode=!0)}}],[{key:"samplingRateMap",get:function(){return[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350]}},{key:"getAACHeaderData",get:function(){return w}},{key:"getHeaderLength",value:function(e){return 1&e[1]?7:9}},{key:"getFrameLength",value:function(e){return(3&e[3])<<11|e[4]<<3|(224&e[5])>>>5}},{key:"isAACPattern",value:function(e){return 255===e[0]&&240==(240&e[1])&&0==(6&e[1])}},{key:"extractAAC",value:function(t){var n,r,i=0,a=t.byteLength,s=[];if(!e.isAACPattern(t))return g("Invalid ADTS audio format"),s;for(n=e.getHeaderLength(t),w||(w=t.subarray(0,n));i<a;)r=e.getFrameLength(t),s.push(t.subarray(n,r)),t=t.slice(r),i+=r;return s}}]),e}(),B=function(){function e(t){n(this,e),this.listener={},this.type=""|t}return i(e,[{key:"on",value:function(e,t){return this.listener[e]||(this.listener[e]=[]),this.listener[e].push(t),!0}},{key:"off",value:function(e,t){if(this.listener[e]){var n=this.listener[e].indexOf(t);return n>-1&&this.listener[e].splice(n,1),!0}return!1}},{key:"offAll",value:function(){this.listener={}}},{key:"dispatch",value:function(e,t){return!!this.listener[e]&&(this.listener[e].map((function(e){e.apply(null,[t])})),!0)}}]),e}(),D=function(){function e(){n(this,e)}return i(e,null,[{key:"init",value:function(){var t;for(t in e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],mvex:[],mvhd:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var n=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:n,audio:r};var i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var s=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,s,u,s,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,i))}},{key:"box",value:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];for(var i,a=8,s=n.length,o=s;s--;)a+=n[s].byteLength;for((i=new Uint8Array(a))[0]=a>>24&255,i[1]=a>>16&255,i[2]=a>>8&255,i[3]=255&a,i.set(e,4),s=0,a=8;s<o;++s)i.set(n[s],a),a+=n[s].byteLength;return i}},{key:"hdlr",value:function(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}},{key:"mdat",value:function(t){return e.box(e.types.mdat,t)}},{key:"mdhd",value:function(t,n){return e.box(e.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}},{key:"mdia",value:function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}},{key:"mfhd",value:function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}},{key:"minf",value:function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}},{key:"moof",value:function(t,n,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,n))}},{key:"moov",value:function(t,n,r){for(var i=t.length,a=[];i--;)a[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(r,n)].concat(a).concat(e.mvex(t)))}},{key:"mvex",value:function(t){for(var n=t.length,r=[];n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[e.types.mvex].concat(r))}},{key:"mvhd",value:function(t,n){var r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,t>>24&255,t>>16&255,t>>8&255,255&t,n>>24&255,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,r)}},{key:"sdtp",value:function(t){var n,r,i=t.samples||[],a=new Uint8Array(4+i.length);for(r=0;r<i.length;r++)n=i[r].flags,a[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return e.box(e.types.sdtp,a)}},{key:"stbl",value:function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}},{key:"avc1",value:function(t){var n,r,i,a=[],s=[];for(n=0;n<t.sps.length;n++)i=(r=t.sps[n]).byteLength,a.push(i>>>8&255),a.push(255&i),a=a.concat(Array.prototype.slice.call(r));for(n=0;n<t.pps.length;n++)i=(r=t.pps[n]).byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(r));var o=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),u=t.width,c=t.height;return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,255&u,c>>8&255,255&c,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,98,105,110,101,108,112,114,111,46,114,117,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])))}},{key:"esds",value:function(e){var t=e.config.byteLength,n=new Uint8Array(26+t+3);return n.set([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5,t]),n.set(e.config,26),n.set([6,1,2],26+t),n}},{key:"mp4a",value:function(t){var n=t.audiosamplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,n>>8&255,255&n,0,0]),e.box(e.types.esds,e.esds(t)))}},{key:"stsd",value:function(t){return"audio"===t.type?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}},{key:"tkhd",value:function(t){var n=t.id,r=t.duration,i=t.width,a=t.height,s=t.volume;return e.box(e.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,n>>24&255,n>>16&255,n>>8&255,255&n,0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,0,0,0,0,0,0,0,0,0,s>>0&255,s%1*10>>0&255,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,a>>8&255,255&a,0,0]))}},{key:"traf",value:function(t,n){var r=e.sdtp(t),i=t.id;return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),e.box(e.types.tfdt,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.trun(t,r.length+16+16+8+16+8+8),r)}},{key:"trak",value:function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}},{key:"trex",value:function(t){var n=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}},{key:"trun",value:function(t,n){var r,i,a,s,o,u,c=t.samples||[],f=c.length,l=12+16*f,h=new Uint8Array(l);for(n+=8+l,h.set([0,0,15,1,f>>>24&255,f>>>16&255,f>>>8&255,255&f,n>>>24&255,n>>>16&255,n>>>8&255,255&n],0),r=0;r<f;r++)a=(i=c[r]).duration,s=i.size,o=i.flags,u=i.cts,h.set([a>>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*r);return e.box(e.types.trun,h)}},{key:"initSegment",value:function(t,n,r){e.types||e.init();var i,a=e.moov(t,n,r);return(i=new Uint8Array(e.FTYP.byteLength+a.byteLength)).set(e.FTYP),i.set(a,e.FTYP.byteLength),i}}]),e}(),C=1,E=function(){function e(){n(this,e)}return i(e,[{key:"flush",value:function(){this.mp4track.len=0,this.mp4track.samples=[]}},{key:"isReady",value:function(){return!(!this.readyToDecode||!this.samples.length)||null}}],[{key:"getTrackID",value:function(){return C++}}]),e}(),T=function(e){s(r,e);var t=l(r);function r(e){var i;return n(this,r),(i=t.call(this)).readyToDecode=!1,i.nextDts=0,i.dts=0,i.mp4track={id:E.getTrackID(),type:"audio",channelCount:0,len:0,fragmented:!0,timescale:e,duration:e,samples:[],config:"",codec:""},i.samples=[],i.aac=new U(c(i)),i}return i(r,[{key:"resetTrack",value:function(){this.readyToDecode=!1,this.mp4track.codec="",this.mp4track.channelCount="",this.mp4track.config="",this.mp4track.timescale=this.timescale,this.nextDts=0,this.dts=0}},{key:"remux",value:function(e){if(e.length>0)for(var t=0;t<e.length;t++){var n=e[t],r=n.units,i=r.byteLength;this.samples.push({units:r,size:i,duration:n.duration}),this.mp4track.len+=i,this.readyToDecode||this.aac.setAACConfig()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var e,t,n=new Uint8Array(this.mp4track.len),r=0,i=this.mp4track.samples;for(this.dts=this.nextDts;this.samples.length;){var a=this.samples.shift();a.units,(t=a.duration)<=0?(k("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(t)),this.mp4track.len-=a.size):(this.nextDts+=t,e={size:a.size,duration:t,cts:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:1}},n.set(a.units,r),r+=a.size,i.push(e))}return i.length?new Uint8Array(n.buffer,0,this.mp4track.len):null}}]),r}(E),P=function(e){s(r,e);var t=l(r);function r(e){var i;return n(this,r),(i=t.call(this)).readyToDecode=!1,i.nextDts=0,i.dts=0,i.mp4track={id:E.getTrackID(),type:"video",len:0,fragmented:!0,sps:"",pps:"",fps:30,width:0,height:0,timescale:e,duration:e,samples:[]},i.samples=[],i.h264=new A(c(i)),i}return i(r,[{key:"resetTrack",value:function(){this.readyToDecode=!1,this.mp4track.sps="",this.mp4track.pps="",this.nextDts=0,this.dts=0}},{key:"remux",value:function(e){var t,n=p(e);try{for(n.s();!(t=n.n()).done;){var r,i=t.value,a=[],s=0,o=p(i.units);try{for(o.s();!(r=o.n()).done;){var u=r.value;this.h264.parseNAL(u)&&(a.push(u),s+=u.getSize())}}catch(e){o.e(e)}finally{o.f()}a.length>0&&this.readyToDecode&&(this.mp4track.len+=s,this.samples.push({units:a,size:s,keyFrame:i.keyFrame,duration:i.duration}))}}catch(e){n.e(e)}finally{n.f()}}},{key:"getPayload",value:function(){if(!this.isReady())return null;var e,t,n=new Uint8Array(this.mp4track.len),r=0,i=this.mp4track.samples;for(this.dts=this.nextDts;this.samples.length;){var a=this.samples.shift(),s=a.units;if((t=a.duration)<=0)k("remuxer: invalid sample duration at DTS: ".concat(this.nextDts," :").concat(t)),this.mp4track.len-=a.size;else{this.nextDts+=t,e={size:a.size,duration:t,cts:0,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,isNonSync:a.keyFrame?0:1,dependsOn:a.keyFrame?2:1}};var o,u=p(s);try{for(u.s();!(o=u.n()).done;){var c=o.value;n.set(c.getData(),r),r+=c.getSize()}}catch(e){u.e(e)}finally{u.f()}i.push(e)}}return i.length?new Uint8Array(n.buffer,0,this.mp4track.len):null}}]),r}(E),L=function(e){s(r,e);var t=l(r);function r(e){var i;return n(this,r),(i=t.call(this,"remuxer")).initialized=!1,i.trackTypes=[],i.tracks={},i.seq=1,i.env=e,i.timescale=1e3,i.mediaDuration=0,i}return i(r,[{key:"addTrack",value:function(e){"video"!==e&&"both"!==e||(this.tracks.video=new P(this.timescale),this.trackTypes.push("video")),"audio"!==e&&"both"!==e||(this.tracks.audio=new T(this.timescale),this.trackTypes.push("audio"))}},{key:"reset",value:function(){var e,t=p(this.trackTypes);try{for(t.s();!(e=t.n()).done;){var n=e.value;this.tracks[n].resetTrack()}}catch(e){t.e(e)}finally{t.f()}this.initialized=!1}},{key:"destroy",value:function(){this.tracks={},this.offAll()}},{key:"flush",value:function(){if(this.initialized){var e,t=p(this.trackTypes);try{for(t.s();!(e=t.n()).done;){var n=e.value,r=this.tracks[n],i=r.getPayload();if(i&&i.byteLength){var a={type:n,payload:S(D.moof(this.seq,r.dts,r.mp4track),D.mdat(i)),dts:r.dts};"video"===n&&(a.fps=r.mp4track.fps),this.dispatch("buffer",a);var s=(o=r.dts/this.timescale,u=void 0,c=void 0,f=void 0,l=void 0,l="",u=Math.floor(o),(c=parseInt(u/3600,10)%24)>0&&(l+=(c<10?"0"+c:c)+":"),l+=((f=parseInt(u/60,10)%60)<10?"0"+f:f)+":"+((u=u<0?0:u%60)<10?"0"+u:u));k("put segment (".concat(n,"): dts: ").concat(r.dts," frames: ").concat(r.mp4track.samples.length," second: ").concat(s)),r.flush(),this.seq++}}}catch(e){t.e(e)}finally{t.f()}}else this.isReady()&&(this.dispatch("ready"),this.initSegment(),this.initialized=!0,this.flush());var o,u,c,f,l}},{key:"initSegment",value:function(){var e,t=[],n=p(this.trackTypes);try{for(n.s();!(e=n.n()).done;){var r=e.value,i=this.tracks[r];if("browser"==this.env){var a={type:r,payload:D.initSegment([i.mp4track],this.mediaDuration,this.timescale)};this.dispatch("buffer",a)}else t.push(i.mp4track)}}catch(e){n.e(e)}finally{n.f()}if("node"==this.env){var s={type:"all",payload:D.initSegment(t,this.mediaDuration,this.timescale)};this.dispatch("buffer",s)}k("Initial segment generated.")}},{key:"isReady",value:function(){var e,t=p(this.trackTypes);try{for(t.s();!(e=t.n()).done;){var n=e.value;if(!this.tracks[n].readyToDecode||!this.tracks[n].samples.length)return!1}}catch(e){t.e(e)}finally{t.f()}return!0}},{key:"remux",value:function(e){var t,n=p(this.trackTypes);try{for(n.s();!(t=n.n()).done;){var r=t.value,i=e[r];"audio"===r&&this.tracks.video&&!this.tracks.video.readyToDecode||i.length>0&&this.tracks[r].remux(i)}}catch(e){n.e(e)}finally{n.f()}this.flush()}}]),r}(B),R=function(e){s(r,e);var t=l(r);function r(e,i){var a;return n(this,r),(a=t.call(this,"buffer")).type=i,a.queue=new Uint8Array,a.cleaning=!1,a.pendingCleaning=0,a.cleanOffset=30,a.cleanRanges=[],a.sourceBuffer=e,a.sourceBuffer.addEventListener("updateend",(function(){a.pendingCleaning>0&&(a.initCleanup(a.pendingCleaning),a.pendingCleaning=0),a.cleaning=!1,a.cleanRanges.length&&a.doCleanup()})),a.sourceBuffer.addEventListener("error",(function(){a.dispatch("error",{type:a.type,name:"buffer",error:"buffer error"})})),a}return i(r,[{key:"destroy",value:function(){this.queue=null,this.sourceBuffer=null,this.offAll()}},{key:"doCleanup",value:function(){if(this.cleanRanges.length){var e=this.cleanRanges.shift();k("".concat(this.type," remove range [").concat(e[0]," - ").concat(e[1],")")),this.cleaning=!0,this.sourceBuffer.remove(e[0],e[1])}else this.cleaning=!1}},{key:"initCleanup",value:function(e){try{if(this.sourceBuffer.updating)return void(this.pendingCleaning=e);if(this.sourceBuffer.buffered&&this.sourceBuffer.buffered.length&&!this.cleaning){for(var t=0;t<this.sourceBuffer.buffered.length;++t){var n=this.sourceBuffer.buffered.start(t),r=this.sourceBuffer.buffered.end(t);e-n>this.cleanOffset&&n<(r=e-this.cleanOffset)&&this.cleanRanges.push([n,r])}this.doCleanup()}}catch(e){g("Error occured while cleaning ".concat(this.type," buffer - ").concat(e.name,": ").concat(e.message))}}},{key:"doAppend",value:function(){if(this.queue.length&&this.sourceBuffer&&!this.sourceBuffer.updating)try{this.sourceBuffer.appendBuffer(this.queue),this.queue=new Uint8Array}catch(t){var e="unexpectedError";"QuotaExceededError"===t.name?(k("".concat(this.type," buffer quota full")),e="QuotaExceeded"):(g("Error occured while appending ".concat(this.type," buffer - ").concat(t.name,": ").concat(t.message)),e="InvalidStateError"),this.dispatch("error",{type:this.type,name:e,error:"buffer error"})}}},{key:"feed",value:function(e){this.queue=S(this.queue,e)}}]),r}(B);return function(r){s(o,r);var a=l(o);function o(e){var r;n(this,o),(r=a.call(this,"jmuxer")).isReset=!1;return r.options=Object.assign({},{node:"",mode:"both",flushingTime:500,maxDelay:500,clearBuffer:!0,fps:30,readFpsFromTrack:!1,debug:!1,onReady:function(){},onError:function(){}},e),r.env="object"===("undefined"==typeof process?"undefined":t(process))&&"undefined"==typeof window?"node":"browser",r.options.debug&&(v=console.log,m=console.error),r.options.fps||(r.options.fps=30),r.frameDuration=1e3/r.options.fps|0,r.remuxController=new L(r.env),r.remuxController.addTrack(r.options.mode),r.initData(),r.remuxController.on("buffer",r.onBuffer.bind(c(r))),"browser"==r.env&&(r.remuxController.on("ready",r.createBuffer.bind(c(r))),r.initBrowser()),r}return i(o,[{key:"initData",value:function(){this.lastCleaningTime=Date.now(),this.kfPosition=[],this.kfCounter=0,this.pendingUnits={},this.remainingData=new Uint8Array,this.startInterval()}},{key:"initBrowser",value:function(){"string"==typeof this.options.node&&""==this.options.node&&g("no video element were found to render, provide a valid video element"),this.node="string"==typeof this.options.node?document.getElementById(this.options.node):this.options.node,this.mseReady=!1,this.setupMSE()}},{key:"createStream",value:function(){var t=this.feed.bind(this),n=this.destroy.bind(this);return this.stream=new e.Duplex({writableObjectMode:!0,read:function(e){},write:function(e,n,r){t(e),r()},final:function(e){n(),e()}}),this.stream}},{key:"setupMSE",value:function(){if(window.MediaSource=window.MediaSource||window.WebKitMediaSource,!window.MediaSource)throw"Oops! Browser does not support media source extension.";this.isMSESupported=!!window.MediaSource,this.mediaSource=new MediaSource,this.url=URL.createObjectURL(this.mediaSource),this.node.src=this.url,this.mseEnded=!1,this.mediaSource.addEventListener("sourceopen",this.onMSEOpen.bind(this)),this.mediaSource.addEventListener("sourceclose",this.onMSEClose.bind(this)),this.mediaSource.addEventListener("webkitsourceopen",this.onMSEOpen.bind(this)),this.mediaSource.addEventListener("webkitsourceclose",this.onMSEClose.bind(this))}},{key:"endMSE",value:function(){if(!this.mseEnded)try{this.mseEnded=!0,this.mediaSource.endOfStream()}catch(e){g("mediasource is not available to end")}}},{key:"feed",value:function(e){var t,n,r,i=!1,a={video:[],audio:[]};if(e&&this.remuxController){if(r=e.duration?parseInt(e.duration):0,e.video){e.video=S(this.remainingData,e.video);var s=h(A.extractNALu(e.video),2);if(t=s[0],n=s[1],this.remainingData=n||new Uint8Array,!(t.length>0))return void g("Failed to extract any NAL units from video data:",n);a.video=this.getVideoFrames(t,r),i=!0}if(e.audio){if(!((t=U.extractAAC(e.audio)).length>0))return void g("Failed to extract audio data from:",e.audio);a.audio=this.getAudioFrames(t,r),i=!0}i?this.remuxController.remux(a):g("Input object must have video and/or audio property. Make sure it is a valid typed array")}}},{key:"getVideoFrames",value:function(e,t){var n,r=this,i=[],a=[],s=0,o=!1,u=!1;this.pendingUnits.units&&(i=this.pendingUnits.units,u=this.pendingUnits.vcl,o=this.pendingUnits.keyFrame,this.pendingUnits={});var c,f=p(e);try{for(f.s();!(c=f.n()).done;){var l=c.value,h=new b(l);h.type()!==b.IDR&&h.type()!==b.NDR||A.parseHeader(h),i.length&&u&&(h.isfmb||!h.isvcl)&&(a.push({units:i,keyFrame:o}),i=[],o=!1,u=!1),i.push(h),o=o||h.isKeyframe(),u=u||h.isvcl}}catch(e){f.e(e)}finally{f.f()}if(i.length)if(t)if(u)a.push({units:i,keyFrame:o});else{var d=a.length-1;d>=0&&(a[d].units=a[d].units.concat(i))}else this.pendingUnits={units:i,keyFrame:o,vcl:u};return n=t?t/a.length|0:this.frameDuration,s=t?t-n*a.length:0,a.map((function(e){e.duration=n,s>0&&(e.duration++,s--),r.kfCounter++,e.keyFrame&&r.options.clearBuffer&&r.kfPosition.push(r.kfCounter*n/1e3)})),k("jmuxer: No. of frames of the last chunk: ".concat(a.length)),a}},{key:"getAudioFrames",value:function(e,t){var n,r,i=[],a=0,s=p(e);try{for(s.s();!(r=s.n()).done;){var o=r.value;i.push({units:o})}}catch(e){s.e(e)}finally{s.f()}return n=t?t/i.length|0:this.frameDuration,a=t?t-n*i.length:0,i.map((function(e){e.duration=n,a>0&&(e.duration++,a--)})),i}},{key:"destroy",value:function(){if(this.stopInterval(),this.stream&&(this.remuxController.flush(),this.stream.push(null),this.stream=null),this.remuxController&&(this.remuxController.destroy(),this.remuxController=null),this.bufferControllers){for(var e in this.bufferControllers)this.bufferControllers[e].destroy();this.bufferControllers=null,this.endMSE()}this.node=!1,this.mseReady=!1,this.videoStarted=!1,this.mediaSource=null}},{key:"reset",value:function(){if(this.stopInterval(),this.isReset=!0,this.node.pause(),this.remuxController&&this.remuxController.reset(),this.bufferControllers){for(var e in this.bufferControllers)this.bufferControllers[e].destroy();this.bufferControllers=null,this.endMSE()}this.initData(),"browser"==this.env&&this.initBrowser(),k("JMuxer was reset")}},{key:"createBuffer",value:function(){if(this.mseReady&&this.remuxController&&this.remuxController.isReady()&&!this.bufferControllers)for(var e in this.bufferControllers={},this.remuxController.tracks){var t=this.remuxController.tracks[e];if(!o.isSupported("".concat(e,'/mp4; codecs="').concat(t.mp4track.codec,'"')))return g("Browser does not support codec"),!1;var n=this.mediaSource.addSourceBuffer("".concat(e,'/mp4; codecs="').concat(t.mp4track.codec,'"'));this.bufferControllers[e]=new R(n,e),this.bufferControllers[e].on("error",this.onBufferError.bind(this))}}},{key:"startInterval",value:function(){var e=this;this.interval=setInterval((function(){e.options.flushingTime?e.applyAndClearBuffer():e.bufferControllers&&e.cancelDelay()}),this.options.flushingTime||1e3)}},{key:"stopInterval",value:function(){this.interval&&clearInterval(this.interval)}},{key:"cancelDelay",value:function(){if(this.node.buffered&&this.node.buffered.length>0&&!this.node.seeking){var e=this.node.buffered.end(0);e-this.node.currentTime>this.options.maxDelay/1e3&&(console.log("delay"),this.node.currentTime=e-.001)}}},{key:"releaseBuffer",value:function(){for(var e in this.bufferControllers)this.bufferControllers[e].doAppend()}},{key:"applyAndClearBuffer",value:function(){this.bufferControllers&&(this.releaseBuffer(),this.clearBuffer())}},{key:"getSafeClearOffsetOfBuffer",value:function(e){for(var t,n="audio"===this.options.mode&&e||0,r=0;r<this.kfPosition.length&&!(this.kfPosition[r]>=e);r++)t=this.kfPosition[r];return t&&(this.kfPosition=this.kfPosition.filter((function(e){return e<t&&(n=e),e>=t}))),n}},{key:"clearBuffer",value:function(){if(this.options.clearBuffer&&Date.now()-this.lastCleaningTime>1e4){for(var e in this.bufferControllers){var t=this.getSafeClearOffsetOfBuffer(this.node.currentTime);this.bufferControllers[e].initCleanup(t)}this.lastCleaningTime=Date.now()}}},{key:"onBuffer",value:function(e){this.options.readFpsFromTrack&&void 0!==e.fps&&this.options.fps!=e.fps&&(this.options.fps=e.fps,this.frameDuration=Math.ceil(1e3/e.fps),k("JMuxer changed FPS to ".concat(e.fps," from track data"))),"browser"==this.env?this.bufferControllers&&this.bufferControllers[e.type]&&this.bufferControllers[e.type].feed(e.payload):this.stream&&this.stream.push(e.payload),0===this.options.flushingTime&&this.applyAndClearBuffer()}},{key:"onMSEOpen",value:function(){this.mseReady=!0,URL.revokeObjectURL(this.url),"function"==typeof this.options.onReady&&this.options.onReady.call(null,this.isReset)}},{key:"onMSEClose",value:function(){this.mseReady=!1,this.videoStarted=!1}},{key:"onBufferError",value:function(e){if("QuotaExceeded"==e.name)return k("JMuxer cleaning ".concat(e.type," buffer due to QuotaExceeded error")),void this.bufferControllers[e.type].initCleanup(this.node.currentTime);"InvalidStateError"==e.name?(k("JMuxer is reseting due to InvalidStateError"),this.reset()):this.endMSE(),"function"==typeof this.options.onError&&this.options.onError.call(null,e)}}],[{key:"isSupported",value:function(e){return window.MediaSource&&window.MediaSource.isTypeSupported(e)}}]),o}(B)}));