-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.ts
545 lines (457 loc) · 17.3 KB
/
main.ts
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
import { EBMLElement, EBML, EBMLFloat64, EBMLFloat32, EBMLId } from "./ebml";
import { WriteTarget, ArrayBufferWriteTarget, FileSystemWritableFileStreamWriteTarget } from "./write_target";
const VIDEO_TRACK_NUMBER = 1;
const AUDIO_TRACK_NUMBER = 2;
const VIDEO_TRACK_TYPE = 1;
const AUDIO_TRACK_TYPE = 2;
const MAX_CHUNK_LENGTH_MS = 2**15;
const CODEC_PRIVATE_MAX_SIZE = 2**12;
const APP_NAME = 'https://github.com/Vanilagy/webm-muxer';
const SEGMENT_SIZE_BYTES = 6;
const CLUSTER_SIZE_BYTES = 5;
interface WebMMuxerOptions {
target: 'buffer' | FileSystemWritableFileStream,
video?: {
codec: string,
width: number,
height: number
frameRate?: number
},
audio?: {
codec: string,
numberOfChannels: number,
sampleRate: number,
bitDepth?: number
}
}
interface InternalMediaChunk {
data: Uint8Array,
timestamp: number,
type: 'key' | 'delta',
trackNumber: number
}
class WebMMuxer {
private target: WriteTarget;
private options: WebMMuxerOptions;
private segment: EBMLElement;
private segmentInfo: EBMLElement;
private seekHead: {
id: number,
data: {
id: number,
data: ({
id: number,
data: Uint8Array,
size?: undefined
} | {
id: number,
size: number,
data: number
})[]
}[]
};
private tracksElement: EBMLElement;
private segmentDuration: EBMLElement;
private colourElement: EBMLElement;
private videoCodecPrivate: EBML;
private audioCodecPrivate: EBML;
private cues: EBMLElement;
private currentCluster: EBMLElement;
private currentClusterTimestamp: number;
private duration = 0;
private videoChunkQueue: InternalMediaChunk[] = [];
private audioChunkQueue: InternalMediaChunk[] = [];
private lastVideoTimestamp = 0;
private lastAudioTimestamp = 0;
private colorSpace: VideoColorSpaceInit;
private finalized = false;
constructor(options: WebMMuxerOptions) {
this.options = options;
if (options.target === 'buffer') {
this.target = new ArrayBufferWriteTarget();
} else {
this.target = new FileSystemWritableFileStreamWriteTarget(options.target);
}
this.createFileHeader();
}
private createFileHeader() {
this.writeEBMLHeader();
this.createSeekHead();
this.createSegmentInfo();
this.createTracks();
this.createSegment();
this.createCues();
}
private writeEBMLHeader() {
let ebmlHeader: EBML = { id: EBMLId.EBML, data: [
{ id: EBMLId.EBMLVersion, data: 1 },
{ id: EBMLId.EBMLReadVersion, data: 1 },
{ id: EBMLId.EBMLMaxIDLength, data: 4 },
{ id: EBMLId.EBMLMaxSizeLength, data: 8 },
{ id: EBMLId.DocType, data: 'webm' },
{ id: EBMLId.DocTypeVersion, data: 2 },
{ id: EBMLId.DocTypeReadVersion, data: 2 }
] };
this.target.writeEBML(ebmlHeader);
}
/**
* Creates a SeekHead element which is positioned near the start of the file and allows the media player to seek to
* relevant sections more easily. Since we don't know the positions of those sections yet, we'll set them later.
*/
private createSeekHead() {
const kaxCues = new Uint8Array([ 0x1c, 0x53, 0xbb, 0x6b ]);
const kaxInfo = new Uint8Array([ 0x15, 0x49, 0xa9, 0x66 ]);
const kaxTracks = new Uint8Array([ 0x16, 0x54, 0xae, 0x6b ]);
let seekHead = { id: EBMLId.SeekHead, data: [
{ id: EBMLId.Seek, data: [
{ id: EBMLId.SeekID, data: kaxCues },
{ id: EBMLId.SeekPosition, size: 5, data: 0 }
] },
{ id: EBMLId.Seek, data: [
{ id: EBMLId.SeekID, data: kaxInfo },
{ id: EBMLId.SeekPosition, size: 5, data: 0 }
] },
{ id: EBMLId.Seek, data: [
{ id: EBMLId.SeekID, data: kaxTracks },
{ id: EBMLId.SeekPosition, size: 5, data: 0 }
] }
] };
this.seekHead = seekHead;
}
private createSegmentInfo() {
let segmentDuration: EBML = { id: EBMLId.Duration, data: new EBMLFloat64(0) };
this.segmentDuration = segmentDuration;
let segmentInfo: EBML = { id: EBMLId.Info, data: [
{ id: EBMLId.TimestampScale, data: 1e6 },
{ id: EBMLId.MuxingApp, data: APP_NAME },
{ id: EBMLId.WritingApp, data: APP_NAME },
segmentDuration
] };
this.segmentInfo = segmentInfo;
}
private createTracks() {
let tracksElement = { id: EBMLId.Tracks, data: [] as EBML[] };
this.tracksElement = tracksElement;
if (this.options.video) {
// Reserve 4 kiB for the CodecPrivate element
this.videoCodecPrivate = { id: EBMLId.Void, size: 4, data: new Uint8Array(CODEC_PRIVATE_MAX_SIZE) };
let colourElement = { id: EBMLId.Colour, data: [
// All initially unspecified
{ id: EBMLId.MatrixCoefficients, data: 2 },
{ id: EBMLId.TransferCharacteristics, data: 2 },
{ id: EBMLId.Primaries, data: 2 },
{ id: EBMLId.Range, data: 0 }
] };
this.colourElement = colourElement;
tracksElement.data.push({ id: EBMLId.TrackEntry, data: [
{ id: EBMLId.TrackNumber, data: VIDEO_TRACK_NUMBER },
{ id: EBMLId.TrackUID, data: VIDEO_TRACK_NUMBER },
{ id: EBMLId.TrackType, data: VIDEO_TRACK_TYPE },
{ id: EBMLId.CodecID, data: this.options.video.codec },
this.videoCodecPrivate,
(this.options.video.frameRate ?
{ id: EBMLId.DefaultDuration, data: 1e9/this.options.video.frameRate } :
null
),
{ id: EBMLId.Video, data: [
{ id: EBMLId.PixelWidth, data: this.options.video.width },
{ id: EBMLId.PixelHeight, data: this.options.video.height },
colourElement
] }
].filter(Boolean) });
}
if (this.options.audio) {
this.audioCodecPrivate = { id: EBMLId.Void, size: 4, data: new Uint8Array(CODEC_PRIVATE_MAX_SIZE) };
tracksElement.data.push({ id: EBMLId.TrackEntry, data: [
{ id: EBMLId.TrackNumber, data: AUDIO_TRACK_NUMBER },
{ id: EBMLId.TrackUID, data: AUDIO_TRACK_NUMBER },
{ id: EBMLId.TrackType, data: AUDIO_TRACK_TYPE },
{ id: EBMLId.CodecID, data: this.options.audio.codec },
this.audioCodecPrivate,
{ id: EBMLId.Audio, data: [
{ id: EBMLId.SamplingFrequency, data: new EBMLFloat32(this.options.audio.sampleRate) },
{ id: EBMLId.Channels, data: this.options.audio.numberOfChannels},
(this.options.audio.bitDepth ?
{ id: EBMLId.BitDepth, data: this.options.audio.bitDepth } :
null
)
].filter(Boolean) }
] });
}
}
private createSegment() {
let segment: EBML = { id: EBMLId.Segment, size: SEGMENT_SIZE_BYTES, data: [
this.seekHead as EBML,
this.segmentInfo,
this.tracksElement
] };
this.segment = segment;
this.target.writeEBML(segment);
}
private createCues() {
this.cues = { id: EBMLId.Cues, data: [] };
}
private get segmentDataOffset() {
return this.target.dataOffsets.get(this.segment);
}
public addVideoChunk(chunk: EncodedVideoChunk, meta: EncodedVideoChunkMetadata, timestamp?: number) {
this.ensureNotFinalized();
if (!this.options.video) throw new Error("No video track declared.");
this.writeVideoDecoderConfig(meta);
let internalChunk = this.createInternalChunk(chunk, timestamp);
if (this.options.video.codec === 'V_VP9') this.fixVP9ColorSpace(internalChunk);
/**
* Ok, so the algorithm used to insert video and audio blocks (if both are present) is one where we want to
* insert the blocks sorted, i.e. always monotonically increasing in timestamp. This means that we can write
* an audio chunk of timestamp t_a only when we have a video chunk of timestamp t_v >= t_a, and vice versa.
* This means that we need to often queue up a lot of video/audio chunks and wait for their counterpart to
* arrive before they are written to the file. When the video writing is finished, it is important that any
* chunks remaining in the queues also be flushed to the file.
*/
this.lastVideoTimestamp = internalChunk.timestamp;
// Write all audio chunks with a timestamp smaller than the incoming video chunk
while (this.audioChunkQueue.length > 0 && this.audioChunkQueue[0].timestamp <= internalChunk.timestamp) {
let audioChunk = this.audioChunkQueue.shift();
this.writeSimpleBlock(audioChunk);
}
// Depending on the last audio chunk, either write the video chunk to the file or enqueue it
if (!this.options.audio || internalChunk.timestamp <= this.lastAudioTimestamp) {
this.writeSimpleBlock(internalChunk);
} else {
this.videoChunkQueue.push(internalChunk);
}
}
private writeVideoDecoderConfig(meta: EncodedVideoChunkMetadata) {
// Write possible video decoder metadata to the file
if (meta.decoderConfig) {
if (meta.decoderConfig.colorSpace) {
let colorSpace = meta.decoderConfig.colorSpace;
this.colorSpace = colorSpace;
this.colourElement.data = [
{ id: EBMLId.MatrixCoefficients, data: {
'rgb': 1,
'bt709': 1,
'bt470bg': 5,
'smpte170m': 6
}[colorSpace.matrix] },
{ id: EBMLId.TransferCharacteristics, data: {
'bt709': 1,
'smpte170m': 6,
'iec61966-2-1': 13
}[colorSpace.transfer] },
{ id: EBMLId.Primaries, data: {
'bt709': 1,
'bt470bg': 5,
'smpte170m': 6
}[colorSpace.primaries] },
{ id: EBMLId.Range, data: [1, 2][Number(colorSpace.fullRange)] }
];
let endPos = this.target.pos;
this.target.seek(this.target.offsets.get(this.colourElement));
this.target.writeEBML(this.colourElement);
this.target.seek(endPos);
}
if (meta.decoderConfig.description) {
this.writeCodecPrivate(this.videoCodecPrivate, meta.decoderConfig.description);
}
}
}
/** Due to [a bug in Chromium](https://bugs.chromium.org/p/chromium/issues/detail?id=1377842), VP9 streams often
* lack color space information. This method patches in that information. */
// http://downloads.webmproject.org/docs/vp9/vp9-bitstream_superframe-and-uncompressed-header_v1.0.pdf
private fixVP9ColorSpace(chunk: InternalMediaChunk) {
if (chunk.type !== 'key') return;
if (!this.colorSpace) return;
let i = 0;
// Check if it's a "superframe"
if (readBits(chunk.data, 0, 2) !== 0b10) return; i += 2;
let profile = (readBits(chunk.data, i+1, i+2) << 1) + readBits(chunk.data, i+0, i+1); i += 2;
if (profile === 3) i++;
let showExistingFrame = readBits(chunk.data, i+0, i+1); i++;
if (showExistingFrame) return;
let frameType = readBits(chunk.data, i+0, i+1); i++;
if (frameType !== 0) return; // Just to be sure
i += 2;
let syncCode = readBits(chunk.data, i+0, i+24); i += 24;
if (syncCode !== 0x498342) return;
if (profile >= 2) i++;
let colorSpaceID = {
'rgb': 7,
'bt709': 2,
'bt470bg': 1,
'smpte170m': 3
}[this.colorSpace.matrix];
writeBits(chunk.data, i+0, i+3, colorSpaceID);
}
public addAudioChunk(chunk: EncodedAudioChunk, meta: EncodedAudioChunkMetadata, timestamp?: number) {
this.ensureNotFinalized();
if (!this.options.audio) throw new Error("No audio track declared.");
let internalChunk = this.createInternalChunk(chunk, timestamp);
// Algorithm explained in `addVideoChunk`
this.lastAudioTimestamp = internalChunk.timestamp;
while (this.videoChunkQueue.length > 0 && this.videoChunkQueue[0].timestamp <= internalChunk.timestamp) {
let videoChunk = this.videoChunkQueue.shift();
this.writeSimpleBlock(videoChunk);
}
if (!this.options.video || internalChunk.timestamp <= this.lastVideoTimestamp) {
this.writeSimpleBlock(internalChunk);
} else {
this.audioChunkQueue.push(internalChunk);
}
// Write possible audio decoder metadata to the file
if (meta.decoderConfig) {
this.writeCodecPrivate(this.audioCodecPrivate, meta.decoderConfig.description);
}
}
/** Converts a read-only external chunk into an internal one for easier use. */
private createInternalChunk(externalChunk: EncodedVideoChunk | EncodedAudioChunk, timestamp?: number) {
let data = new Uint8Array(externalChunk.byteLength);
externalChunk.copyTo(data);
let internalChunk: InternalMediaChunk = {
data,
timestamp: timestamp ?? externalChunk.timestamp,
type: externalChunk.type,
trackNumber: externalChunk instanceof EncodedVideoChunk ? VIDEO_TRACK_NUMBER : AUDIO_TRACK_NUMBER
};
return internalChunk;
}
/** Writes an EBML SimpleBlock containing video or audio data to the file. */
private writeSimpleBlock(chunk: InternalMediaChunk) {
let msTime = Math.floor(chunk.timestamp / 1000);
let clusterIsTooLong = chunk.type !== 'key' && msTime - this.currentClusterTimestamp >= MAX_CHUNK_LENGTH_MS;
if (clusterIsTooLong) {
throw new Error(
`Current Matroska cluster exceeded its maximum allowed length of ${MAX_CHUNK_LENGTH_MS} ` +
`milliseconds. In order to produce a correct WebM file, you must pass in a video key frame at least ` +
`every ${MAX_CHUNK_LENGTH_MS} milliseconds.`
);
}
let shouldCreateNewClusterFromKeyFrame =
(chunk.trackNumber === VIDEO_TRACK_NUMBER || !this.options.video) &&
chunk.type === 'key' &&
msTime - this.currentClusterTimestamp >= 1000;
if (
!this.currentCluster ||
shouldCreateNewClusterFromKeyFrame
) {
this.createNewCluster(msTime);
}
let prelude = new Uint8Array(4);
let view = new DataView(prelude.buffer);
// 0x80 to indicate it's the last byte of a multi-byte number
view.setUint8(0, 0x80 | chunk.trackNumber);
view.setUint16(1, msTime - this.currentClusterTimestamp, false);
view.setUint8(3, Number(chunk.type === 'key') << 7); // Flags
let simpleBlock = { id: EBMLId.SimpleBlock, data: [
prelude,
chunk.data
] };
this.target.writeEBML(simpleBlock);
this.duration = Math.max(this.duration, msTime);
}
/**
* Replaces a placeholder EBML element with actual CodecPrivate data, then pads it with a Void Element of
* necessary size.
*/
private writeCodecPrivate(element: EBML, data: AllowSharedBufferSource) {
let endPos = this.target.pos;
this.target.seek(this.target.offsets.get(element));
element = [
{ id: EBMLId.CodecPrivate, size: 4, data: new Uint8Array(data as ArrayBuffer) },
{ id: EBMLId.Void, size: 4, data: new Uint8Array(CODEC_PRIVATE_MAX_SIZE - 2 - 4 - data.byteLength) }
];
this.target.writeEBML(element);
this.target.seek(endPos);
}
/** Creates a new Cluster element to contain video and audio chunks. */
private createNewCluster(timestamp: number) {
if (this.currentCluster) {
this.finalizeCurrentCluster();
}
this.currentCluster = { id: EBMLId.Cluster, size: CLUSTER_SIZE_BYTES, data: [
{ id: EBMLId.Timestamp, data: timestamp }
] };
this.target.writeEBML(this.currentCluster);
this.currentClusterTimestamp = timestamp;
let clusterOffsetFromSegment =
this.target.offsets.get(this.currentCluster) - this.segmentDataOffset;
// Add a CuePoint to the Cues element for better seeking
(this.cues.data as EBML[]).push({ id: EBMLId.CuePoint, data: [
{ id: EBMLId.CueTime, data: timestamp },
{ id: EBMLId.CueTrackPositions, data: [
{ id: EBMLId.CueTrack, data: VIDEO_TRACK_NUMBER },
{ id: EBMLId.CueClusterPosition, data: clusterOffsetFromSegment }
] }
] });
}
private finalizeCurrentCluster() {
let clusterSize = this.target.pos - this.target.dataOffsets.get(this.currentCluster);
let endPos = this.target.pos;
// Write the size now that we know it
this.target.seek(this.target.offsets.get(this.currentCluster) + 4);
this.target.writeEBMLVarInt(clusterSize, CLUSTER_SIZE_BYTES);
this.target.seek(endPos);
}
/** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
public finalize() {
// Flush any remaining queued chunks to the file
while (this.videoChunkQueue.length > 0) this.writeSimpleBlock(this.videoChunkQueue.shift());
while (this.audioChunkQueue.length > 0) this.writeSimpleBlock(this.audioChunkQueue.shift());
this.finalizeCurrentCluster();
this.target.writeEBML(this.cues);
let endPos = this.target.pos;
// Write the Segment size
let segmentSize = this.target.pos - this.segmentDataOffset;
this.target.seek(this.target.offsets.get(this.segment) + 4);
this.target.writeEBMLVarInt(segmentSize, SEGMENT_SIZE_BYTES);
// Write the duration of the media to the Segment
this.segmentDuration.data = new EBMLFloat64(this.duration);
this.target.seek(this.target.offsets.get(this.segmentDuration));
this.target.writeEBML(this.segmentDuration);
// Fill in SeekHead position data and write it again
this.seekHead.data[0].data[1].data =
this.target.offsets.get(this.cues) - this.segmentDataOffset;
this.seekHead.data[1].data[1].data =
this.target.offsets.get(this.segmentInfo) - this.segmentDataOffset;
this.seekHead.data[2].data[1].data =
this.target.offsets.get(this.tracksElement) - this.segmentDataOffset;
this.target.seek(this.target.offsets.get(this.seekHead));
this.target.writeEBML(this.seekHead);
this.target.seek(endPos);
this.finalized = true;
if (this.target instanceof ArrayBufferWriteTarget) {
return this.target.finalize();
} else if (this.target instanceof FileSystemWritableFileStreamWriteTarget) {
this.target.finalize();
}
return null;
}
private ensureNotFinalized() {
if (this.finalized) {
throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
}
}
}
export default WebMMuxer;
const readBits = (bytes: Uint8Array, start: number, end: number) => {
let result = 0;
for (let i = start; i < end; i++) {
let byteIndex = Math.floor(i / 8);
let byte = bytes[byteIndex];
let bitIndex = 0b111 - (i & 0b111);
let bit = (byte & (1 << bitIndex)) >> bitIndex;
result <<= 1;
result |= bit;
}
return result;
};
const writeBits = (bytes: Uint8Array, start: number, end: number, value: number) => {
for (let i = start; i < end; i++) {
let byteIndex = Math.floor(i / 8);
let byte = bytes[byteIndex];
let bitIndex = 0b111 - (i & 0b111);
byte &= ~(1 << bitIndex);
byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex;
bytes[byteIndex] = byte;
}
};