-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathEBML.js
18433 lines (16670 loc) · 531 KB
/
EBML.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.EBML = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
},{}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tools_1 = require("./tools");
var int64_buffer_1 = require("int64-buffer");
var tools = require("./tools");
var schema = require("matroska-schema");
var byEbmlID = schema.byEbmlID;
// https://www.matroska.org/technical/specs/index.html
var State;
(function (State) {
State[State["STATE_TAG"] = 1] = "STATE_TAG";
State[State["STATE_SIZE"] = 2] = "STATE_SIZE";
State[State["STATE_CONTENT"] = 3] = "STATE_CONTENT";
})(State || (State = {}));
var EBMLDecoder = /** @class */ (function () {
function EBMLDecoder() {
this._buffer = new tools_1.Buffer(0);
this._tag_stack = [];
this._state = State.STATE_TAG;
this._cursor = 0;
this._total = 0;
this._schema = byEbmlID;
this._result = [];
}
EBMLDecoder.prototype.decode = function (chunk) {
this.readChunk(chunk);
var diff = this._result;
this._result = [];
return diff;
};
EBMLDecoder.prototype.readChunk = function (chunk) {
// 読みかけの(読めなかった) this._buffer と 新しい chunk を合わせて読み直す
this._buffer = tools.concat([this._buffer, new tools_1.Buffer(chunk)]);
while (this._cursor < this._buffer.length) {
// console.log(this._cursor, this._total, this._tag_stack);
if (this._state === State.STATE_TAG && !this.readTag()) {
break;
}
if (this._state === State.STATE_SIZE && !this.readSize()) {
break;
}
if (this._state === State.STATE_CONTENT && !this.readContent()) {
break;
}
}
};
EBMLDecoder.prototype.getSchemaInfo = function (tagNum) {
return this._schema[tagNum] || {
name: "unknown",
level: -1,
type: "unknown",
description: "unknown"
};
};
/**
* vint された parsing tag
* @return - return false when waiting for more data
*/
EBMLDecoder.prototype.readTag = function () {
// tag.length が buffer の外にある
if (this._cursor >= this._buffer.length) {
return false;
}
// read ebml id vint without first byte
var tag = (0, tools_1.readVint)(this._buffer, this._cursor);
// tag が読めなかった
if (tag == null) {
return false;
}
// >>>>>>>>>
// tag 識別子
//const tagStr = this._buffer.toString("hex", this._cursor, this._cursor + tag.length);
//const tagNum = parseInt(tagStr, 16);
// 上と等価
var buf = this._buffer.slice(this._cursor, this._cursor + tag.length);
var tagNum = buf.reduce(function (o, v, i, arr) { return o + v * Math.pow(16, 2 * (arr.length - 1 - i)); }, 0);
var schema = this.getSchemaInfo(tagNum);
var tagObj = {
EBML_ID: tagNum.toString(16),
schema: schema,
type: schema.type,
name: schema.name,
level: schema.level,
tagStart: this._total,
tagEnd: this._total + tag.length,
sizeStart: this._total + tag.length,
sizeEnd: null,
dataStart: null,
dataEnd: null,
dataSize: null,
data: null
};
// | tag: vint | size: vint | data: Buffer(size) |
this._tag_stack.push(tagObj);
// <<<<<<<<
// ポインタを進める
this._cursor += tag.length;
this._total += tag.length;
// 読み込み状態変更
this._state = State.STATE_SIZE;
return true;
};
/**
* vint された現在のタグの内容の大きさを読み込む
* @return - return false when waiting for more data
*/
EBMLDecoder.prototype.readSize = function () {
// tag.length が buffer の外にある
if (this._cursor >= this._buffer.length) {
return false;
}
// read ebml datasize vint without first byte
var size = (0, tools_1.readVint)(this._buffer, this._cursor);
// まだ読めない
if (size == null) {
return false;
}
// >>>>>>>>>
// current tag の data size 決定
var tagObj = this._tag_stack[this._tag_stack.length - 1];
tagObj.sizeEnd = tagObj.sizeStart + size.length;
tagObj.dataStart = tagObj.sizeEnd;
tagObj.dataSize = size.value;
if (size.value === -1) {
// unknown size
tagObj.dataEnd = -1;
if (tagObj.type === "m") {
tagObj.unknownSize = true;
}
}
else {
tagObj.dataEnd = tagObj.sizeEnd + size.value;
}
// <<<<<<<<
// ポインタを進める
this._cursor += size.length;
this._total += size.length;
this._state = State.STATE_CONTENT;
return true;
};
/**
* データ読み込み
*/
EBMLDecoder.prototype.readContent = function () {
var tagObj = this._tag_stack[this._tag_stack.length - 1];
// master element は子要素を持つので生データはない
if (tagObj.type === 'm') {
// console.log('content should be tags');
tagObj.isEnd = false;
this._result.push(tagObj);
this._state = State.STATE_TAG;
// この Mastert Element は空要素か
if (tagObj.dataSize === 0) {
// 即座に終了タグを追加
var elm = Object.assign({}, tagObj, { isEnd: true });
this._result.push(elm);
this._tag_stack.pop(); // スタックからこのタグを捨てる
}
return true;
}
// waiting for more data
if (this._buffer.length < this._cursor + tagObj.dataSize) {
return false;
}
// タグの中身の生データ
var data = this._buffer.slice(this._cursor, this._cursor + tagObj.dataSize);
// 読み終わったバッファを捨てて読み込んでいる部分のバッファのみ残す
this._buffer = this._buffer.slice(this._cursor + tagObj.dataSize);
tagObj.data = data;
// >>>>>>>>>
switch (tagObj.type) {
//case "m": break;
// Master-Element - contains other EBML sub-elements of the next lower level
case "u":
tagObj.value = data.readUIntBE(0, data.length);
break;
// Unsigned Integer - Big-endian, any size from 1 to 8 octets
case "i":
tagObj.value = data.readIntBE(0, data.length);
break;
// Signed Integer - Big-endian, any size from 1 to 8 octets
case "f":
tagObj.value = tagObj.dataSize === 4 ? data.readFloatBE(0) :
tagObj.dataSize === 8 ? data.readDoubleBE(0) :
(console.warn("cannot read ".concat(tagObj.dataSize, " octets float. failback to 0")), 0);
break;
// Float - Big-endian, defined for 4 and 8 octets (32, 64 bits)
case "s":
tagObj.value = data.toString("ascii");
break; // ascii
// Printable ASCII (0x20 to 0x7E), zero-padded when needed
case "8":
tagObj.value = data.toString("utf8");
break;
// Unicode string, zero padded when needed (RFC 2279)
case "b":
tagObj.value = data;
break;
// Binary - not interpreted by the parser
case "d":
tagObj.value = (0, tools_1.convertEBMLDateToJSDate)(new int64_buffer_1.Int64BE(data).toNumber());
break;
// nano second; Date.UTC(2001,1,1,0,0,0,0) === 980985600000
// Date - signed 8 octets integer in nanoseconds with 0 indicating
// the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC)
}
if (tagObj.value === null) {
throw new Error("unknown tag type:" + tagObj.type);
}
this._result.push(tagObj);
// <<<<<<<<
// ポインタを進める
this._total += tagObj.dataSize;
// タグ待ちモードに変更
this._state = State.STATE_TAG;
this._cursor = 0;
this._tag_stack.pop(); // remove the object from the stack
while (this._tag_stack.length > 0) {
var topEle = this._tag_stack[this._tag_stack.length - 1];
// 親が不定長サイズなので閉じタグは期待できない
if (topEle.dataEnd < 0) {
this._tag_stack.pop(); // 親タグを捨てる
return true;
}
// 閉じタグの来るべき場所まで来たかどうか
if (this._total < topEle.dataEnd) {
break;
}
// 閉じタグを挿入すべきタイミングが来た
if (topEle.type !== "m") {
throw new Error("parent element is not master element");
}
var elm = Object.assign({}, topEle, { isEnd: true });
this._result.push(elm);
this._tag_stack.pop();
}
return true;
};
return EBMLDecoder;
}());
exports.default = EBMLDecoder;
},{"./tools":6,"int64-buffer":17,"matroska-schema":18}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tools = require("./tools");
var tools_1 = require("./tools");
var schema = require("matroska-schema");
var byEbmlID = schema.byEbmlID;
var EBMLEncoder = /** @class */ (function () {
function EBMLEncoder() {
this._schema = byEbmlID;
this._buffers = [];
this._stack = [];
}
EBMLEncoder.prototype.encode = function (elms) {
var _this = this;
return tools.concat(elms.reduce(function (lst, elm) {
return lst.concat(_this.encodeChunk(elm));
}, [])).buffer;
};
EBMLEncoder.prototype.encodeChunk = function (elm) {
if (elm.type === "m") {
if (!elm.isEnd) {
this.startTag(elm);
}
else {
this.endTag(elm);
}
}
else {
// ensure that we are working with an internal `Buffer` instance
elm.data = tools_1.Buffer.from(elm.data);
this.writeTag(elm);
}
return this.flush();
};
EBMLEncoder.prototype.flush = function () {
var ret = this._buffers;
this._buffers = [];
return ret;
};
EBMLEncoder.prototype.getSchemaInfo = function (tagName) {
var tagNums = Object.keys(this._schema).map(Number);
for (var i = 0; i < tagNums.length; i++) {
var tagNum = tagNums[i];
if (this._schema[tagNum].name === tagName) {
return new tools_1.Buffer(tagNum.toString(16), 'hex');
}
}
return null;
};
EBMLEncoder.prototype.writeTag = function (elm) {
var tagName = elm.name;
var tagId = this.getSchemaInfo(tagName);
var tagData = elm.data;
if (tagId == null) {
throw new Error('No schema entry found for ' + tagName);
}
var data = tools.encodeTag(tagId, tagData);
/**
* 親要素が閉じタグあり(isEnd)なら閉じタグが来るまで待つ(children queに入る)
*/
if (this._stack.length > 0) {
var last = this._stack[this._stack.length - 1];
last.children.push({
tagId: tagId,
elm: elm,
children: [],
data: data
});
return;
}
this._buffers = this._buffers.concat(data);
return;
};
EBMLEncoder.prototype.startTag = function (elm) {
var tagName = elm.name;
var tagId = this.getSchemaInfo(tagName);
if (tagId == null) {
throw new Error('No schema entry found for ' + tagName);
}
/**
* 閉じタグ不定長の場合はスタックに積まずに即時バッファに書き込む
*/
if (elm.unknownSize) {
var data = tools.encodeTag(tagId, new tools_1.Buffer(0), elm.unknownSize);
this._buffers = this._buffers.concat(data);
return;
}
var tag = {
tagId: tagId,
elm: elm,
children: [],
data: null
};
if (this._stack.length > 0) {
this._stack[this._stack.length - 1].children.push(tag);
}
this._stack.push(tag);
};
EBMLEncoder.prototype.endTag = function (elm) {
var tagName = elm.name;
var tag = this._stack.pop();
if (tag == null) {
throw new Error("EBML structure is broken");
}
if (tag.elm.name !== elm.name) {
throw new Error("EBML structure is broken");
}
var childTagDataBuffers = tag.children.reduce(function (lst, child) {
if (child.data === null) {
throw new Error("EBML structure is broken");
}
return lst.concat(child.data);
}, []);
var childTagDataBuffer = tools.concat(childTagDataBuffers);
if (tag.elm.type === "m") {
tag.data = tools.encodeTag(tag.tagId, childTagDataBuffer, tag.elm.unknownSize);
}
else {
tag.data = tools.encodeTag(tag.tagId, childTagDataBuffer);
}
if (this._stack.length < 1) {
this._buffers = this._buffers.concat(tag.data);
}
};
return EBMLEncoder;
}());
exports.default = EBMLEncoder;
},{"./tools":6,"matroska-schema":18}],4:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var events_1 = require("events");
var tools = require("./tools");
/**
* This is an informal code for reference.
* EBMLReader is a class for getting information to enable seeking Webm recorded by MediaRecorder.
* So please do not use for regular WebM files.
*/
var EBMLReader = /** @class */ (function (_super) {
__extends(EBMLReader, _super);
function EBMLReader() {
var _this = _super.call(this) || this;
_this.logGroup = "";
_this.hasLoggingStarted = false;
_this.metadataloaded = false;
_this.chunks = [];
_this.stack = [];
_this.segmentOffset = 0;
_this.last2SimpleBlockVideoTrackTimestamp = [0, 0];
_this.last2SimpleBlockAudioTrackTimestamp = [0, 0];
_this.lastClusterTimestamp = 0;
_this.lastClusterPosition = 0;
_this.timestampScale = 1000000; // webm default TimestampScale is 1ms
_this.metadataSize = 0;
_this.metadatas = [];
_this.cues = [];
_this.firstVideoBlockRead = false;
_this.firstAudioBlockRead = false;
_this.currentTrack = { TrackNumber: -1, TrackType: -1, DefaultDuration: null, CodecDelay: null };
_this.trackTypes = [];
_this.trackDefaultDuration = [];
_this.trackCodecDelay = [];
_this.trackInfo = { type: "nothing" };
_this.ended = false;
_this.logging = false;
_this.use_duration_every_simpleblock = false;
_this.use_webp = false;
_this.use_segment_info = true;
_this.drop_default_duration = true;
return _this;
}
/**
* emit final state.
*/
EBMLReader.prototype.stop = function () {
this.ended = true;
this.emit_segment_info();
// clean up any unclosed Master Elements at the end of the stream.
while (this.stack.length) {
this.stack.pop();
if (this.logging) {
console.groupEnd();
}
}
// close main group if set, logging is enabled, and has actually logged anything.
if (this.logging && this.hasLoggingStarted && this.logGroup) {
console.groupEnd();
}
};
/**
* emit chunk info
*/
EBMLReader.prototype.emit_segment_info = function () {
var data = this.chunks;
this.chunks = [];
if (!this.metadataloaded) {
this.metadataloaded = true;
this.metadatas = data;
var videoTrackNum = this.trackTypes.indexOf(1); // find first video track
var audioTrackNum = this.trackTypes.indexOf(2); // find first audio track
this.trackInfo = videoTrackNum >= 0 && audioTrackNum >= 0 ? { type: "both", trackNumber: videoTrackNum }
: videoTrackNum >= 0 ? { type: "video", trackNumber: videoTrackNum }
: audioTrackNum >= 0 ? { type: "audio", trackNumber: audioTrackNum }
: { type: "nothing" };
if (!this.use_segment_info) {
return;
}
this.emit("metadata", { data: data, metadataSize: this.metadataSize });
}
else {
if (!this.use_segment_info) {
return;
}
var timestamp = this.lastClusterTimestamp;
var duration = this.duration;
var timestampScale = this.timestampScale;
this.emit("cluster", { timestamp: timestamp, data: data });
this.emit("duration", { timestampScale: timestampScale, duration: duration });
}
};
EBMLReader.prototype.read = function (elm) {
var _this = this;
var drop = false;
if (this.ended) {
// reader is finished
return;
}
if (elm.type === "m") {
// 閉じタグの自動挿入
if (elm.isEnd) {
this.stack.pop();
}
else {
var parent_1 = this.stack[this.stack.length - 1];
if (parent_1 != null && parent_1.level >= elm.level) {
// 閉じタグなしでレベルが下がったら閉じタグを挿入
this.stack.pop();
// From http://w3c.github.io/media-source/webm-byte-stream-format.html#webm-media-segments
// This fixes logging for webm streams with Cluster of unknown length and no Cluster closing elements.
if (this.logging) {
console.groupEnd();
}
parent_1.dataEnd = elm.dataEnd;
parent_1.dataSize = elm.dataEnd - parent_1.dataStart;
parent_1.unknownSize = false;
var o = Object.assign({}, parent_1, { name: parent_1.name, type: parent_1.type, isEnd: true });
this.chunks.push(o);
}
this.stack.push(elm);
}
}
if (elm.type === "m" && elm.name == "Segment") {
if (this.segmentOffset != 0) {
console.warn("Multiple segments detected!");
}
this.segmentOffset = elm.dataStart;
this.emit("segment_offset", this.segmentOffset);
}
else if (elm.type === "b" && elm.name === "SimpleBlock") {
var _a = tools.ebmlBlock(elm.data), timestamp = _a.timecode, trackNumber = _a.trackNumber, frames_1 = _a.frames;
if (this.trackTypes[trackNumber] === 1) { // trackType === 1 => video track
if (!this.firstVideoBlockRead) {
this.firstVideoBlockRead = true;
if (this.trackInfo.type === "both" || this.trackInfo.type === "video") {
var CueTime = this.lastClusterTimestamp + timestamp;
this.cues.push({ CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime });
this.emit("cue_info", {
CueTrack: trackNumber,
CueClusterPosition: this.lastClusterPosition,
CueTime: this.lastClusterTimestamp
});
this.emit("cue", { CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime });
}
}
this.last2SimpleBlockVideoTrackTimestamp = [this.last2SimpleBlockVideoTrackTimestamp[1], timestamp];
}
else if (this.trackTypes[trackNumber] === 2) { // trackType === 2 => audio track
if (!this.firstAudioBlockRead) {
this.firstAudioBlockRead = true;
if (this.trackInfo.type === "audio") {
var CueTime = this.lastClusterTimestamp + timestamp;
this.cues.push({ CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime });
this.emit("cue_info", {
CueTrack: trackNumber,
CueClusterPosition: this.lastClusterPosition,
CueTime: this.lastClusterTimestamp
});
this.emit("cue", { CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: CueTime });
}
}
this.last2SimpleBlockAudioTrackTimestamp = [this.last2SimpleBlockAudioTrackTimestamp[1], timestamp];
}
if (this.use_duration_every_simpleblock) {
this.emit("duration", { timestampScale: this.timestampScale, duration: this.duration });
}
if (this.use_webp) {
frames_1.forEach(function (frame) {
var startcode = frame.slice(3, 6).toString("hex");
if (startcode !== "9d012a") {
return;
} // VP8 の場合
var webpBuf = tools.VP8BitStreamToRiffWebPBuffer(frame);
var webp = new Blob([webpBuf], { type: "image/webp" });
var currentTime = _this.duration;
_this.emit("webp", { currentTime: currentTime, webp: webp });
});
}
}
else if (elm.type === "m" && elm.name === "Cluster" && elm.isEnd === false) {
this.firstVideoBlockRead = false;
this.firstAudioBlockRead = false;
this.emit_segment_info();
this.emit("cluster_ptr", elm.tagStart);
this.lastClusterPosition = elm.tagStart;
}
else if (elm.type === "u" && elm.name === "Timestamp") {
this.lastClusterTimestamp = elm.value;
}
else if (elm.type === "u" && elm.name === "TimestampScale") {
this.timestampScale = elm.value;
}
else if (elm.type === "m" && elm.name === "TrackEntry") {
if (elm.isEnd) {
this.trackTypes[this.currentTrack.TrackNumber] = this.currentTrack.TrackType;
this.trackDefaultDuration[this.currentTrack.TrackNumber] = this.currentTrack.DefaultDuration;
this.trackCodecDelay[this.currentTrack.TrackNumber] = this.currentTrack.CodecDelay;
}
else {
this.currentTrack = { TrackNumber: -1, TrackType: -1, DefaultDuration: null, CodecDelay: null };
}
}
else if (elm.type === "u" && elm.name === "TrackType") {
this.currentTrack.TrackType = elm.value;
}
else if (elm.type === "u" && elm.name === "TrackNumber") {
this.currentTrack.TrackNumber = elm.value;
}
else if (elm.type === "u" && elm.name === "CodecDelay") {
this.currentTrack.CodecDelay = elm.value;
}
else if (elm.type === "u" && elm.name === "DefaultDuration") {
// media source api は DefaultDuration を計算するとバグる。
// https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22
// chrome 58 ではこれを回避するために DefaultDuration 要素を抜き取った。
// chrome 58 以前でもこのタグを抜き取ることで回避できる
if (this.drop_default_duration) {
console.warn("DefaultDuration detected!, remove it");
drop = true;
}
else {
this.currentTrack.DefaultDuration = elm.value;
}
}
else if (elm.name === "unknown") {
console.warn(elm);
}
if (!this.metadataloaded && elm.dataEnd > 0) {
this.metadataSize = elm.dataEnd;
}
if (!drop) {
this.chunks.push(elm);
}
if (this.logging) {
this.put(elm);
}
};
Object.defineProperty(EBMLReader.prototype, "duration", {
/**
* DefaultDuration が定義されている場合は最後のフレームのdurationも考慮する
* 単位 timestampScale
*
* !!! if you need duration with seconds !!!
* ```js
* const nanosec = reader.duration * reader.timestampScale;
* const sec = nanosec / 1000 / 1000 / 1000;
* ```
*/
get: function () {
if (this.trackInfo.type === "nothing") {
console.warn("no video, no audio track");
return 0;
}
// defaultDuration は 生の nano sec
var defaultDuration = 0;
// nanoseconds
var codecDelay = 0;
var lastTimestamp = 0;
var _defaultDuration = this.trackDefaultDuration[this.trackInfo.trackNumber];
if (typeof _defaultDuration === "number") {
defaultDuration = _defaultDuration;
}
else {
// https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22
// default duration がないときに使う delta
if (this.trackInfo.type === "both") {
if (this.last2SimpleBlockAudioTrackTimestamp[1] > this.last2SimpleBlockVideoTrackTimestamp[1]) {
// audio diff
defaultDuration = (this.last2SimpleBlockAudioTrackTimestamp[1] -
this.last2SimpleBlockAudioTrackTimestamp[0]) * this.timestampScale;
// audio delay
var delay = this.trackCodecDelay[this.trackTypes.indexOf(2)]; // 2 => audio
if (typeof delay === "number") {
codecDelay = delay;
}
// audio timestamp
lastTimestamp = this.last2SimpleBlockAudioTrackTimestamp[1];
}
else {
// video diff
defaultDuration = (this.last2SimpleBlockVideoTrackTimestamp[1] -
this.last2SimpleBlockVideoTrackTimestamp[0]) * this.timestampScale;
// video delay
var delay = this.trackCodecDelay[this.trackTypes.indexOf(1)]; // 1 => video
if (typeof delay === "number") {
codecDelay = delay;
}
// video timestamp
lastTimestamp = this.last2SimpleBlockVideoTrackTimestamp[1];
}
}
else if (this.trackInfo.type === "video") {
defaultDuration = (this.last2SimpleBlockVideoTrackTimestamp[1] - this.last2SimpleBlockVideoTrackTimestamp[0]) * this.timestampScale;
var delay = this.trackCodecDelay[this.trackInfo.trackNumber]; // 2 => audio
if (typeof delay === "number") {
codecDelay = delay;
}
lastTimestamp = this.last2SimpleBlockVideoTrackTimestamp[1];
}
else if (this.trackInfo.type === "audio") {
defaultDuration = (this.last2SimpleBlockAudioTrackTimestamp[1] - this.last2SimpleBlockAudioTrackTimestamp[0]) * this.timestampScale;
var delay = this.trackCodecDelay[this.trackInfo.trackNumber]; // 1 => video
if (typeof delay === "number") {
codecDelay = delay;
}
lastTimestamp = this.last2SimpleBlockAudioTrackTimestamp[1];
} // else { not reached }
}
// convert to timestampscale
var duration_nanosec = ((this.lastClusterTimestamp + lastTimestamp) * this.timestampScale) + defaultDuration - codecDelay;
var duration = duration_nanosec / this.timestampScale;
return Math.floor(duration);
},
enumerable: false,
configurable: true
});
EBMLReader.prototype.addListener = function (event, listener) {
return _super.prototype.addListener.call(this, event, listener);
};
EBMLReader.prototype.put = function (elm) {
if (!this.hasLoggingStarted) {
this.hasLoggingStarted = true;
if (this.logging && this.logGroup) {
console.groupCollapsed(this.logGroup);
}
}
if (elm.type === "m") {
if (elm.isEnd) {
console.groupEnd();
}
else {
console.group(elm.name + ":" + elm.tagStart);
}
}
else if (elm.type === "b") {
// for debug
//if(elm.name === "SimpleBlock"){
//const o = EBML.tools.ebmlBlock(elm.value);
//console.log(elm.name, elm.type, o.trackNumber, o.timestamp);
//}else{
console.log(elm.name, elm.type);
//}
}
else {
console.log(elm.name, elm.tagStart, elm.type, elm.value);
}
};
return EBMLReader;
}(events_1.EventEmitter));
exports.default = EBMLReader;
},{"./tools":6,"events":15}],5:[function(require,module,exports){
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.tools = exports.Reader = exports.Encoder = exports.Decoder = exports.version = void 0;
__exportStar(require("./EBML"), exports);
var EBMLDecoder_1 = require("./EBMLDecoder");
exports.Decoder = EBMLDecoder_1.default;
var EBMLEncoder_1 = require("./EBMLEncoder");
exports.Encoder = EBMLEncoder_1.default;
var EBMLReader_1 = require("./EBMLReader");
exports.Reader = EBMLReader_1.default;
var tools = require("./tools");
exports.tools = tools;
var version = require("../package.json").version;
exports.version = version;
},{"../package.json":21,"./EBML":1,"./EBMLDecoder":2,"./EBMLEncoder":3,"./EBMLReader":4,"./tools":6}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertEBMLDateToJSDate = exports.createFloatBuffer = exports.createIntBuffer = exports.createUIntBuffer = exports.encodeValueToBuffer = exports.concat = exports.putRefinedMetaData = exports.extractElement = exports.removeElement = exports.makeMetadataSeekable = exports.createRIFFChunk = exports.VP8BitStreamToRiffWebPBuffer = exports.WebPBlockFilter = exports.WebPFrameFilter = exports.encodeTag = exports.readBlock = exports.ebmlBlock = exports.writeVint = exports.readVint = exports.Buffer = void 0;
/// <reference types="node"/>
var int64_buffer_1 = require("int64-buffer");
var EBMLEncoder_1 = require("./EBMLEncoder");
var buffer_1 = require("buffer");
var ebml_1 = require('ebml/lib/ebml.js');
var _block = require("ebml-block");
var buffer_2 = require("buffer");
Object.defineProperty(exports, "Buffer", { enumerable: true, get: function () { return buffer_2.Buffer; } });
exports.readVint = ebml_1.tools.readVint;
exports.writeVint = ebml_1.tools.writeVint;
exports.ebmlBlock = _block;
function readBlock(buf) {
return (0, exports.ebmlBlock)(new buffer_1.Buffer(buf));
}
exports.readBlock = readBlock;
/**
* @param end - if end === false then length is unknown
*/
function encodeTag(tagId, tagData, unknownSize) {
if (unknownSize === void 0) { unknownSize = false; }
return concat([
tagId,
unknownSize ?
new buffer_1.Buffer('01ffffffffffffff', 'hex') :
(0, exports.writeVint)(tagData.length),
tagData
]);
}
exports.encodeTag = encodeTag;
/**
* @return - SimpleBlock to WebP Filter
*/
function WebPFrameFilter(elms) {
return WebPBlockFilter(elms).reduce(function (lst, elm) {
var o = (0, exports.ebmlBlock)(elm.data);
return o.frames.reduce(function (lst, frame) {
// https://developers.Blob.com/speed/webp/docs/riff_container
var webpBuf = VP8BitStreamToRiffWebPBuffer(frame);
var webp = new Blob([webpBuf], { type: "image/webp" });
return lst.concat(webp);
}, lst);
}, []);
}
exports.WebPFrameFilter = WebPFrameFilter;
/**
* WebP ファイルにできる SimpleBlock の パスフィルタ
*/
function WebPBlockFilter(elms) {
return elms.reduce(function (lst, elm) {
if (elm.type !== "b") {
return lst;
}
if (elm.name !== "SimpleBlock") {
return lst;
}
var o = (0, exports.ebmlBlock)(elm.data);
var hasWebP = o.frames.some(function (frame) {
// https://tools.ietf.org/html/rfc6386#section-19.1
var startcode = frame.slice(3, 6).toString("hex");
return startcode === "9d012a";
});
if (!hasWebP) {
return lst;
}
return lst.concat(elm);
}, []);
}
exports.WebPBlockFilter = WebPBlockFilter;
/**
* @param frame - VP8 BitStream のうち startcode をもつ frame
* @return - WebP ファイルの ArrayBuffer
*/
function VP8BitStreamToRiffWebPBuffer(frame) {
var VP8Chunk = createRIFFChunk("VP8 ", frame);
var WebPChunk = concat([
new buffer_1.Buffer("WEBP", "ascii"),
VP8Chunk
]);
return createRIFFChunk("RIFF", WebPChunk);
}
exports.VP8BitStreamToRiffWebPBuffer = VP8BitStreamToRiffWebPBuffer;
/**
* RIFF データチャンクを作る
*/
function createRIFFChunk(FourCC, chunk) {
var chunkSize = new buffer_1.Buffer(4);
chunkSize.writeUInt32LE(chunk.byteLength, 0);
return concat([
new buffer_1.Buffer(FourCC.substr(0, 4), "ascii"),
chunkSize,
chunk,
new buffer_1.Buffer(chunk.byteLength % 2 === 0 ? 0 : 1) // padding
]);
}
exports.createRIFFChunk = createRIFFChunk;
/* Original Metadata
m 0 EBML
u 1 EBMLVersion 1
u 1 EBMLReadVersion 1
u 1 EBMLMaxIDLength 4
u 1 EBMLMaxSizeLength 8
s 1 DocType webm
u 1 DocTypeVersion 4
u 1 DocTypeReadVersion 2
m 0 Segment
m 1 Info segmentContentStartPos, all CueClusterPositions provided in
info.cues will be relative to here and will need adjusted
u 2 TimestampScale 1000000
8 2 MuxingApp Chrome
8 2 WritingApp Chrome
m 1 Tracks tracksStartPos
m 2 TrackEntry
u 3 TrackNumber 1
u 3 TrackUID 31790271978391090
u 3 TrackType 2
s 3 CodecID A_OPUS
b 3 CodecPrivate <Buffer 19>
m 3 Audio
f 4 SamplingFrequency 48000
u 4 Channels 1
m 2 TrackEntry
u 3 TrackNumber 2
u 3 TrackUID 24051277436254136
u 3 TrackType 1
s 3 CodecID V_VP8
m 3 Video
u 4 PixelWidth 1024
u 4 PixelHeight 576
m 1 Cluster clusterStartPos
u 2 Timestamp 0
b 2 SimpleBlock track:2 timestamp:0 keyframe:true invisible:false discardable:false lacing:1
*/
/* Desired Metadata
m 0 EBML
u 1 EBMLVersion 1
u 1 EBMLReadVersion 1
u 1 EBMLMaxIDLength 4
u 1 EBMLMaxSizeLength 8
s 1 DocType webm
u 1 DocTypeVersion 4
u 1 DocTypeReadVersion 2
m 0 Segment
m 1 SeekHead -> This is SeekPosition 0, so all SeekPositions can be calculated as
(bytePos - segmentContentStartPos), which is 44 in this case
m 2 Seek
b 3 SeekID -> Buffer([0x15, 0x49, 0xA9, 0x66]) Info
u 3 SeekPosition -> infoStartPos =
m 2 Seek
b 3 SeekID -> Buffer([0x16, 0x54, 0xAE, 0x6B]) Tracks
u 3 SeekPosition { tracksStartPos }
m 2 Seek
b 3 SeekID -> Buffer([0x1C, 0x53, 0xBB, 0x6B]) Cues
u 3 SeekPosition { cuesStartPos }
m 1 Info
f 2 Duration 32480 -> overwrite, or insert if it doesn't exist
u 2 TimestampScale 1000000
8 2 MuxingApp Chrome
8 2 WritingApp Chrome
m 1 Tracks
m 2 TrackEntry
u 3 TrackNumber 1
u 3 TrackUID 31790271978391090
u 3 TrackType 2
s 3 CodecID A_OPUS
b 3 CodecPrivate <Buffer 19>
m 3 Audio
f 4 SamplingFrequency 48000
u 4 Channels 1
m 2 TrackEntry
u 3 TrackNumber 2
u 3 TrackUID 24051277436254136
u 3 TrackType 1
s 3 CodecID V_VP8
m 3 Video
u 4 PixelWidth 1024
u 4 PixelHeight 576
m 1 Cues -> cuesStartPos
m 2 CuePoint
u 3 CueTime 0
m 3 CueTrackPositions
u 4 CueTrack 1
u 4 CueClusterPosition 3911
m 2 CuePoint
u 3 CueTime 600
m 3 CueTrackPositions
u 4 CueTrack 1
u 4 CueClusterPosition 3911
m 1 Cluster
u 2 Timestamp 0
b 2 SimpleBlock track:2 timestamp:0 keyframe:true invisible:false discardable:false lacing:1
*/
/**
* convert the metadata from a streaming webm bytestream to a seekable file by inserting Duration, Seekhead and Cues
* @param originalMetadata - orginal metadata (everything before the clusters start) from media recorder
* @param duration - Duration (TimestampScale)
* @param cuesInfo - cue points for clusters
* @param cuesOffset - extra space to leave before cue points
* @param cuesPosition - location for cue points (if zero, put after tracks metadata)
*/
function makeMetadataSeekable(originalMetadata, duration, cuesInfo, cuesOffset, cuesPosition) {
if (cuesOffset === void 0) { cuesOffset = 0; }
if (cuesPosition === void 0) { cuesPosition = 0; }
// extract the header, we can reuse this as-is
var header = extractElement("EBML", originalMetadata);
var headerSize = encodedSizeOfEbml(header);
//console.error("Header size: " + headerSize);
//printElementIds(header);
// After the header comes the Segment open tag, which in this implementation is always 12 bytes (4 byte id, 8 byte 'unknown length')
// After that the segment content starts. All SeekPositions and CueClusterPosition must be relative to segmentContentStartPos
var segmentContentStartPos = headerSize + 12;
//console.error("segmentContentStartPos: " + segmentContentStartPos);
// find the original metadata size, and adjust it for header size and Segment start element
// so we can keep all positions relative to segmentContentStartPos
var originalMetadataSize = originalMetadata[originalMetadata.length - 1].dataEnd - segmentContentStartPos;
//console.error("Original Metadata size: " + originalMetadataSize);
//printElementIds(originalMetadata);
// extract the segment info, remove the potentially existing Duration element, and add our own one.
var info = extractElement("Info", originalMetadata);
removeElement("Duration", info);
info.splice(1, 0, { name: "Duration", type: "f", data: createFloatBuffer(duration, 8) });
var infoSize = encodedSizeOfEbml(info);