2 * A tool for presenting an ArrayBuffer as a stream for writing some simple data types.
6 * Released under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL
13 * Create an ArrayBuffer of the given length and present it as a writable stream with methods
14 * for writing data in different formats.
16 var ArrayBufferDataStream = function(length) {
17 this.data = new Uint8Array(length);
21 ArrayBufferDataStream.prototype.seek = function(offset) {
25 ArrayBufferDataStream.prototype.writeBytes = function(arr) {
26 for (var i = 0; i < arr.length; i++) {
27 this.data[this.pos++] = arr[i];
31 ArrayBufferDataStream.prototype.writeByte = function(b) {
32 this.data[this.pos++] = b;
36 ArrayBufferDataStream.prototype.writeU8 = ArrayBufferDataStream.prototype.writeByte;
38 ArrayBufferDataStream.prototype.writeU16BE = function(u) {
39 this.data[this.pos++] = u >> 8;
40 this.data[this.pos++] = u;
43 ArrayBufferDataStream.prototype.writeDoubleBE = function(d) {
45 bytes = new Uint8Array(new Float64Array([d]).buffer);
47 for (var i = bytes.length - 1; i >= 0; i--) {
48 this.writeByte(bytes[i]);
52 ArrayBufferDataStream.prototype.writeFloatBE = function(d) {
54 bytes = new Uint8Array(new Float32Array([d]).buffer);
56 for (var i = bytes.length - 1; i >= 0; i--) {
57 this.writeByte(bytes[i]);
62 * Write an ASCII string to the stream
64 ArrayBufferDataStream.prototype.writeString = function(s) {
65 for (var i = 0; i < s.length; i++) {
66 this.data[this.pos++] = s.charCodeAt(i);
71 * Write the given 32-bit integer to the stream as an EBML variable-length integer using the given byte width
72 * (use measureEBMLVarInt).
74 * No error checking is performed to ensure that the supplied width is correct for the integer.
76 * @param i Integer to be written
77 * @param width Number of bytes to write to the stream
79 ArrayBufferDataStream.prototype.writeEBMLVarIntWidth = function(i, width) {
82 this.writeU8((1 << 7) | i);
85 this.writeU8((1 << 6) | (i >> 8));
89 this.writeU8((1 << 5) | (i >> 16));
94 this.writeU8((1 << 4) | (i >> 24));
95 this.writeU8(i >> 16);
101 * JavaScript converts its doubles to 32-bit integers for bitwise operations, so we need to do a
102 * division by 2^32 instead of a right-shift of 32 to retain those top 3 bits
104 this.writeU8((1 << 3) | ((i / 4294967296) & 0x7));
105 this.writeU8(i >> 24);
106 this.writeU8(i >> 16);
107 this.writeU8(i >> 8);
111 throw new RuntimeException("Bad EBML VINT size " + width);
116 * Return the number of bytes needed to encode the given integer as an EBML VINT.
118 ArrayBufferDataStream.prototype.measureEBMLVarInt = function(val) {
119 if (val < (1 << 7) - 1) {
120 /* Top bit is set, leaving 7 bits to hold the integer, but we can't store 127 because
121 * "all bits set to one" is a reserved value. Same thing for the other cases below:
124 } else if (val < (1 << 14) - 1) {
126 } else if (val < (1 << 21) - 1) {
128 } else if (val < (1 << 28) - 1) {
130 } else if (val < 34359738367) { // 2 ^ 35 - 1 (can address 32GB)
133 throw new RuntimeException("EBML VINT size not supported " + val);
137 ArrayBufferDataStream.prototype.writeEBMLVarInt = function(i) {
138 this.writeEBMLVarIntWidth(i, this.measureEBMLVarInt(i));
142 * Write the given unsigned 32-bit integer to the stream in big-endian order using the given byte width.
143 * No error checking is performed to ensure that the supplied width is correct for the integer.
145 * Omit the width parameter to have it determined automatically for you.
147 * @param u Unsigned integer to be written
148 * @param width Number of bytes to write to the stream
150 ArrayBufferDataStream.prototype.writeUnsignedIntBE = function(u, width) {
151 if (width === undefined) {
152 width = this.measureUnsignedInt(u);
155 // Each case falls through:
158 this.writeU8(Math.floor(u / 4294967296)); // Need to use division to access >32 bits of floating point var
160 this.writeU8(u >> 24);
162 this.writeU8(u >> 16);
164 this.writeU8(u >> 8);
169 throw new RuntimeException("Bad UINT size " + width);
174 * Return the number of bytes needed to hold the non-zero bits of the given unsigned integer.
176 ArrayBufferDataStream.prototype.measureUnsignedInt = function(val) {
177 // Force to 32-bit unsigned integer
178 if (val < (1 << 8)) {
180 } else if (val < (1 << 16)) {
182 } else if (val < (1 << 24)) {
184 } else if (val < 4294967296) {
192 * Return a view on the portion of the buffer from the beginning to the current seek position as a Uint8Array.
194 ArrayBufferDataStream.prototype.getAsDataArray = function() {
195 if (this.pos < this.data.byteLength) {
196 return this.data.subarray(0, this.pos);
197 } else if (this.pos == this.data.byteLength) {
200 throw "ArrayBufferDataStream's pos lies beyond end of buffer";
204 if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
205 module.exports = ArrayBufferDataStream;
207 window.ArrayBufferDataStream = ArrayBufferDataStream;
212 * Allows a series of Blob-convertible objects (ArrayBuffer, Blob, String, etc) to be added to a buffer. Seeking and
213 * overwriting of blobs is allowed.
215 * You can supply a FileWriter, in which case the BlobBuffer is just used as temporary storage before it writes it
216 * through to the disk.
218 * By Nicholas Sherlock
220 * Released under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL
223 var BlobBuffer = function(fs) {
224 return function(destination) {
227 writePromise = Promise.resolve(),
231 if (typeof FileWriter !== "undefined" && destination instanceof FileWriter) {
232 fileWriter = destination;
233 } else if (fs && destination) {
237 // Current seek offset
240 // One more than the index of the highest byte ever written
243 // Returns a promise that converts the blob to an ArrayBuffer
244 function readBlobAsBuffer(blob) {
245 return new Promise(function (resolve, reject) {
247 reader = new FileReader();
249 reader.addEventListener("loadend", function () {
250 resolve(reader.result);
253 reader.readAsArrayBuffer(blob);
257 function convertToUint8Array(thing) {
258 return new Promise(function (resolve, reject) {
259 if (thing instanceof Uint8Array) {
261 } else if (thing instanceof ArrayBuffer || ArrayBuffer.isView(thing)) {
262 resolve(new Uint8Array(thing));
263 } else if (thing instanceof Blob) {
264 resolve(readBlobAsBuffer(thing).then(function (buffer) {
265 return new Uint8Array(buffer);
268 //Assume that Blob will know how to read this thing
269 resolve(readBlobAsBuffer(new Blob([thing])).then(function (buffer) {
270 return new Uint8Array(buffer);
276 function measureData(data) {
278 result = data.byteLength || data.length || data.size;
280 if (!Number.isInteger(result)) {
281 throw "Failed to determine size of element";
288 * Seek to the given absolute offset.
290 * You may not seek beyond the end of the file (this would create a hole and/or allow blocks to be written in non-
291 * sequential order, which isn't currently supported by the memory buffer backend).
293 this.seek = function (offset) {
295 throw "Offset may not be negative";
299 throw "Offset may not be NaN";
302 if (offset > this.length) {
303 throw "Seeking beyond the end of file is not allowed";
310 * Write the Blob-convertible data to the buffer at the current seek position.
312 * Note: If overwriting existing data, the write must not cross preexisting block boundaries (written data must
313 * be fully contained by the extent of a previous write).
315 this.write = function (data) {
320 length: measureData(data)
322 isAppend = newEntry.offset >= this.length;
324 this.pos += newEntry.length;
325 this.length = Math.max(this.length, this.pos);
327 // After previous writes complete, perform our write
328 writePromise = writePromise.then(function () {
330 return new Promise(function(resolve, reject) {
331 convertToUint8Array(newEntry.data).then(function(dataArray) {
334 buffer = Buffer.from(dataArray.buffer),
336 handleWriteComplete = function(err, written, buffer) {
337 totalWritten += written;
339 if (totalWritten >= buffer.length) {
342 // We still have more to write...
343 fs.write(fd, buffer, totalWritten, buffer.length - totalWritten, newEntry.offset + totalWritten, handleWriteComplete);
347 fs.write(fd, buffer, 0, buffer.length, newEntry.offset, handleWriteComplete);
350 } else if (fileWriter) {
351 return new Promise(function (resolve, reject) {
352 fileWriter.onwriteend = resolve;
354 fileWriter.seek(newEntry.offset);
355 fileWriter.write(new Blob([newEntry.data]));
357 } else if (!isAppend) {
358 // We might be modifying a write that was already buffered in memory.
360 // Slow linear search to find a block we might be overwriting
361 for (var i = 0; i < buffer.length; i++) {
365 // If our new entry overlaps the old one in any way...
366 if (!(newEntry.offset + newEntry.length <= entry.offset || newEntry.offset >= entry.offset + entry.length)) {
367 if (newEntry.offset < entry.offset || newEntry.offset + newEntry.length > entry.offset + entry.length) {
368 throw new Error("Overwrite crosses blob boundaries");
371 if (newEntry.offset == entry.offset && newEntry.length == entry.length) {
372 // We overwrote the entire block
373 entry.data = newEntry.data;
378 return convertToUint8Array(entry.data)
379 .then(function (entryArray) {
380 entry.data = entryArray;
382 return convertToUint8Array(newEntry.data);
383 }).then(function (newEntryArray) {
384 newEntry.data = newEntryArray;
386 entry.data.set(newEntry.data, newEntry.offset - entry.offset);
391 // Else fall through to do a simple append, as we didn't overwrite any pre-existing blocks
394 buffer.push(newEntry);
399 * Finish all writes to the buffer, returning a promise that signals when that is complete.
401 * If a FileWriter was not provided, the promise is resolved with a Blob that represents the completed BlobBuffer
402 * contents. You can optionally pass in a mimeType to be used for this blob.
404 * If a FileWriter was provided, the promise is resolved with null as the first argument.
406 this.complete = function (mimeType) {
407 if (fd || fileWriter) {
408 writePromise = writePromise.then(function () {
412 // After writes complete we need to merge the buffer to give to the caller
413 writePromise = writePromise.then(function () {
417 for (var i = 0; i < buffer.length; i++) {
418 result.push(buffer[i].data);
421 return new Blob(result, {mimeType: mimeType});
430 if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
431 module.exports = BlobBuffer(require('fs'));
433 window.BlobBuffer = BlobBuffer(null);
436 * WebM video encoder for Google Chrome. This implementation is suitable for creating very large video files, because
437 * it can stream Blobs directly to a FileWriter without buffering the entire video in memory.
439 * When FileWriter is not available or not desired, it can buffer the video in memory as a series of Blobs which are
440 * eventually returned as one composite Blob.
442 * By Nicholas Sherlock.
444 * Based on the ideas from Whammy: https://github.com/antimatter15/whammy
446 * Released under the WTFPLv2 https://en.wikipedia.org/wiki/WTFPL
452 var WebMWriter = function(ArrayBufferDataStream, BlobBuffer) {
453 function extend(base, top) {
457 [base, top].forEach(function(obj) {
458 for (var prop in obj) {
459 if (Object.prototype.hasOwnProperty.call(obj, prop)) {
460 target[prop] = obj[prop];
469 * Decode a Base64 data URL into a binary string.
471 * Returns the binary string, or false if the URL could not be decoded.
473 function decodeBase64WebPDataURL(url) {
474 if (typeof url !== "string" || !url.match(/^data:image\/webp;base64,/i)) {
478 return window.atob(url.substring("data:image\/webp;base64,".length));
482 * Convert a raw binary string (one character = one output byte) to an ArrayBuffer
484 function stringToArrayBuffer(string) {
486 buffer = new ArrayBuffer(string.length),
487 int8Array = new Uint8Array(buffer);
489 for (var i = 0; i < string.length; i++) {
490 int8Array[i] = string.charCodeAt(i);
497 * Convert the given canvas to a WebP encoded image and return the image data as a string.
499 function renderAsWebP(canvas, quality) {
501 frame = canvas.toDataURL('image/webp', quality);
503 return decodeBase64WebPDataURL(frame);
506 function extractKeyframeFromWebP(webP) {
507 // Assume that Chrome will generate a Simple Lossy WebP which has this header:
509 keyframeStartIndex = webP.indexOf('VP8 ');
511 if (keyframeStartIndex == -1) {
512 throw "Failed to identify beginning of keyframe in WebP image";
515 // Skip the header and the 4 bytes that encode the length of the VP8 chunk
516 keyframeStartIndex += 'VP8 '.length + 4;
518 return webP.substring(keyframeStartIndex);
521 // Just a little utility so we can tag values as floats for the EBML encoder's benefit
522 function EBMLFloat32(value) {
526 function EBMLFloat64(value) {
531 * Write the given EBML object to the provided ArrayBufferStream.
533 * The buffer's first byte is at bufferFileOffset inside the video file. This is used to complete offset and
534 * dataOffset fields in each EBML structure, indicating the file offset of the first byte of the EBML element and
537 function writeEBML(buffer, bufferFileOffset, ebml) {
538 // Is the ebml an array of sibling elements?
539 if (Array.isArray(ebml)) {
540 for (var i = 0; i < ebml.length; i++) {
541 writeEBML(buffer, bufferFileOffset, ebml[i]);
543 // Is this some sort of raw data that we want to write directly?
544 } else if (typeof ebml === "string") {
545 buffer.writeString(ebml);
546 } else if (ebml instanceof Uint8Array) {
547 buffer.writeBytes(ebml);
549 // We're writing an EBML element
550 ebml.offset = buffer.pos + bufferFileOffset;
552 buffer.writeUnsignedIntBE(ebml.id); // ID field
554 // Now we need to write the size field, so we must know the payload size:
556 if (Array.isArray(ebml.data)) {
557 // Writing an array of child elements. We won't try to measure the size of the children up-front
560 sizePos, dataBegin, dataEnd;
562 if (ebml.size === -1) {
563 // Write the reserved all-one-bits marker to note that the size of this element is unknown/unbounded
564 buffer.writeByte(0xFF);
566 sizePos = buffer.pos;
568 /* Write a dummy size field to overwrite later. 4 bytes allows an element maximum size of 256MB,
569 * which should be plenty (we don't want to have to buffer that much data in memory at one time
572 buffer.writeBytes([0, 0, 0, 0]);
575 dataBegin = buffer.pos;
577 ebml.dataOffset = dataBegin + bufferFileOffset;
578 writeEBML(buffer, bufferFileOffset, ebml.data);
580 if (ebml.size !== -1) {
581 dataEnd = buffer.pos;
583 ebml.size = dataEnd - dataBegin;
585 buffer.seek(sizePos);
586 buffer.writeEBMLVarIntWidth(ebml.size, 4); // Size field
588 buffer.seek(dataEnd);
590 } else if (typeof ebml.data === "string") {
591 buffer.writeEBMLVarInt(ebml.data.length); // Size field
592 ebml.dataOffset = buffer.pos + bufferFileOffset;
593 buffer.writeString(ebml.data);
594 } else if (typeof ebml.data === "number") {
595 // Allow the caller to explicitly choose the size if they wish by supplying a size field
597 ebml.size = buffer.measureUnsignedInt(ebml.data);
600 buffer.writeEBMLVarInt(ebml.size); // Size field
601 ebml.dataOffset = buffer.pos + bufferFileOffset;
602 buffer.writeUnsignedIntBE(ebml.data, ebml.size);
603 } else if (ebml.data instanceof EBMLFloat64) {
604 buffer.writeEBMLVarInt(8); // Size field
605 ebml.dataOffset = buffer.pos + bufferFileOffset;
606 buffer.writeDoubleBE(ebml.data.value);
607 } else if (ebml.data instanceof EBMLFloat32) {
608 buffer.writeEBMLVarInt(4); // Size field
609 ebml.dataOffset = buffer.pos + bufferFileOffset;
610 buffer.writeFloatBE(ebml.data.value);
611 } else if (ebml.data instanceof Uint8Array) {
612 buffer.writeEBMLVarInt(ebml.data.byteLength); // Size field
613 ebml.dataOffset = buffer.pos + bufferFileOffset;
614 buffer.writeBytes(ebml.data);
616 throw "Bad EBML datatype " + typeof ebml.data;
619 throw "Bad EBML datatype " + typeof ebml.data;
623 return function(options) {
625 MAX_CLUSTER_DURATION_MSEC = 5000,
626 DEFAULT_TRACK_NUMBER = 1,
628 writtenHeader = false,
629 videoWidth, videoHeight,
631 clusterFrameBuffer = [],
632 clusterStartTime = 0,
636 quality: 0.95, // WebM image quality from 0.0 (worst) to 1.0 (best)
637 fileWriter: null, // Chrome FileWriter in order to stream to a file instead of buffering to memory (optional)
638 fd: null, // Node.JS file descriptor to write to instead of buffering (optional)
640 // You must supply one of:
641 frameDuration: null, // Duration of frames in milliseconds
642 frameRate: null, // Number of frames per second
646 Cues: {id: new Uint8Array([0x1C, 0x53, 0xBB, 0x6B]), positionEBML: null},
647 SegmentInfo: {id: new Uint8Array([0x15, 0x49, 0xA9, 0x66]), positionEBML: null},
648 Tracks: {id: new Uint8Array([0x16, 0x54, 0xAE, 0x6B]), positionEBML: null},
653 "id": 0x4489, // Duration
654 "data": new EBMLFloat64(0)
661 blobBuffer = new BlobBuffer(options.fileWriter || options.fd);
663 function fileOffsetToSegmentRelative(fileOffset) {
664 return fileOffset - ebmlSegment.dataOffset;
668 * Create a SeekHead element with descriptors for the points in the global seekPoints array.
670 * 5 bytes of position values are reserved for each node, which lie at the offset point.positionEBML.dataOffset,
671 * to be overwritten later.
673 function createSeekHead() {
675 seekPositionEBMLTemplate = {
676 "id": 0x53AC, // SeekPosition
677 "size": 5, // Allows for 32GB video files
678 "data": 0 // We'll overwrite this when the file is complete
682 "id": 0x114D9B74, // SeekHead
686 for (var name in seekPoints) {
688 seekPoint = seekPoints[name];
690 seekPoint.positionEBML = Object.create(seekPositionEBMLTemplate);
693 "id": 0x4DBB, // Seek
696 "id": 0x53AB, // SeekID
699 seekPoint.positionEBML
708 * Write the WebM file header to the stream.
710 function writeHeader() {
711 seekHead = createSeekHead();
715 "id": 0x1a45dfa3, // EBML
718 "id": 0x4286, // EBMLVersion
722 "id": 0x42f7, // EBMLReadVersion
726 "id": 0x42f2, // EBMLMaxIDLength
730 "id": 0x42f3, // EBMLMaxSizeLength
734 "id": 0x4282, // DocType
738 "id": 0x4287, // DocTypeVersion
742 "id": 0x4285, // DocTypeReadVersion
749 "id": 0x1549a966, // Info
752 "id": 0x2ad7b1, // TimecodeScale
753 "data": 1e6 // Times will be in miliseconds (1e6 nanoseconds per step = 1ms)
756 "id": 0x4d80, // MuxingApp
757 "data": "webm-writer-js",
760 "id": 0x5741, // WritingApp
761 "data": "webm-writer-js"
763 segmentDuration // To be filled in later
768 "id": 0x1654ae6b, // Tracks
771 "id": 0xae, // TrackEntry
774 "id": 0xd7, // TrackNumber
775 "data": DEFAULT_TRACK_NUMBER
778 "id": 0x73c5, // TrackUID
779 "data": DEFAULT_TRACK_NUMBER
782 "id": 0x9c, // FlagLacing
786 "id": 0x22b59c, // Language
790 "id": 0x86, // CodecID
794 "id": 0x258688, // CodecName
798 "id": 0x83, // TrackType
805 "id": 0xb0, // PixelWidth
809 "id": 0xba, // PixelHeight
820 "id": 0x18538067, // Segment
821 "size": -1, // Unbounded size
830 bufferStream = new ArrayBufferDataStream(256);
832 writeEBML(bufferStream, blobBuffer.pos, [ebmlHeader, ebmlSegment]);
833 blobBuffer.write(bufferStream.getAsDataArray());
835 // Now we know where these top-level elements lie in the file:
836 seekPoints.SegmentInfo.positionEBML.data = fileOffsetToSegmentRelative(segmentInfo.offset);
837 seekPoints.Tracks.positionEBML.data = fileOffsetToSegmentRelative(tracks.offset);
841 * Create a SimpleBlock keyframe header using these fields:
842 * timecode - Time of this keyframe
843 * trackNumber - Track number from 1 to 126 (inclusive)
844 * frame - Raw frame data payload string
846 * Returns an EBML element.
848 function createKeyframeBlock(keyframe) {
850 bufferStream = new ArrayBufferDataStream(1 + 2 + 1);
852 if (!(keyframe.trackNumber > 0 && keyframe.trackNumber < 127)) {
853 throw "TrackNumber must be > 0 and < 127";
856 bufferStream.writeEBMLVarInt(keyframe.trackNumber); // Always 1 byte since we limit the range of trackNumber
857 bufferStream.writeU16BE(keyframe.timecode);
860 bufferStream.writeByte(
865 "id": 0xA3, // SimpleBlock
867 bufferStream.getAsDataArray(),
874 * Create a Cluster node using these fields:
876 * timecode - Start time for the cluster
878 * Returns an EBML element.
880 function createCluster(cluster) {
885 "id": 0xe7, // Timecode
886 "data": Math.round(cluster.timecode)
892 function addCuePoint(trackIndex, clusterTime, clusterFileOffset) {
897 "id": 0xB3, // CueTime
901 "id": 0xB7, // CueTrackPositions
904 "id": 0xF7, // CueTrack
908 "id": 0xF1, // CueClusterPosition
909 "data": fileOffsetToSegmentRelative(clusterFileOffset)
918 * Write a Cues element to the blobStream using the global `cues` array of CuePoints (use addCuePoint()).
919 * The seek entry for the Cues in the SeekHead is updated.
921 function writeCues() {
928 cuesBuffer = new ArrayBufferDataStream(16 + cues.length * 32); // Pretty crude estimate of the buffer size we'll need
930 writeEBML(cuesBuffer, blobBuffer.pos, ebml);
931 blobBuffer.write(cuesBuffer.getAsDataArray());
933 // Now we know where the Cues element has ended up, we can update the SeekHead
934 seekPoints.Cues.positionEBML.data = fileOffsetToSegmentRelative(ebml.offset);
938 * Flush the frames in the current clusterFrameBuffer out to the stream as a Cluster.
940 function flushClusterFrameBuffer() {
941 if (clusterFrameBuffer.length == 0) {
945 // First work out how large of a buffer we need to hold the cluster data
949 for (var i = 0; i < clusterFrameBuffer.length; i++) {
950 rawImageSize += clusterFrameBuffer[i].frame.length;
954 buffer = new ArrayBufferDataStream(rawImageSize + clusterFrameBuffer.length * 32), // Estimate 32 bytes per SimpleBlock header
956 cluster = createCluster({
957 timecode: Math.round(clusterStartTime),
960 for (var i = 0; i < clusterFrameBuffer.length; i++) {
961 cluster.data.push(createKeyframeBlock(clusterFrameBuffer[i]));
964 writeEBML(buffer, blobBuffer.pos, cluster);
965 blobBuffer.write(buffer.getAsDataArray());
967 addCuePoint(DEFAULT_TRACK_NUMBER, Math.round(clusterStartTime), cluster.offset);
969 clusterFrameBuffer = [];
970 clusterStartTime += clusterDuration;
974 function validateOptions() {
975 // Derive frameDuration setting if not already supplied
976 if (!options.frameDuration) {
977 if (options.frameRate) {
978 options.frameDuration = 1000 / options.frameRate;
980 throw "Missing required frameDuration or frameRate setting";
985 function addFrameToCluster(frame) {
986 frame.trackNumber = DEFAULT_TRACK_NUMBER;
988 // Frame timecodes are relative to the start of their cluster:
989 frame.timecode = Math.round(clusterDuration);
991 clusterFrameBuffer.push(frame);
993 clusterDuration += frame.duration;
995 if (clusterDuration >= MAX_CLUSTER_DURATION_MSEC) {
996 flushClusterFrameBuffer();
1001 * Rewrites the SeekHead element that was initially written to the stream with the offsets of top level elements.
1003 * Call once writing is complete (so the offset of all top level elements is known).
1005 function rewriteSeekHead() {
1007 seekHeadBuffer = new ArrayBufferDataStream(seekHead.size),
1008 oldPos = blobBuffer.pos;
1010 // Write the rewritten SeekHead element's data payload to the stream (don't need to update the id or size)
1011 writeEBML(seekHeadBuffer, seekHead.dataOffset, seekHead.data);
1013 // And write that through to the file
1014 blobBuffer.seek(seekHead.dataOffset);
1015 blobBuffer.write(seekHeadBuffer.getAsDataArray());
1017 blobBuffer.seek(oldPos);
1021 * Rewrite the Duration field of the Segment with the newly-discovered video duration.
1023 function rewriteDuration() {
1025 buffer = new ArrayBufferDataStream(8),
1026 oldPos = blobBuffer.pos;
1028 // Rewrite the data payload (don't need to update the id or size)
1029 buffer.writeDoubleBE(clusterStartTime);
1031 // And write that through to the file
1032 blobBuffer.seek(segmentDuration.dataOffset);
1033 blobBuffer.write(buffer.getAsDataArray());
1035 blobBuffer.seek(oldPos);
1039 * Add a frame to the video. Currently the frame must be a Canvas element.
1041 this.addFrame = function(canvas, duration) {
1042 //if (writtenHeader) {
1043 // if (canvas.width != videoWidth || canvas.height != videoHeight) {
1044 // throw "Frame size differs from previous frames";
1047 videoWidth = canvas.width;
1048 videoHeight = canvas.height;
1051 writtenHeader = true;
1055 webP = renderAsWebP(canvas, options.quality);
1058 throw "Couldn't decode WebP frame, does the browser support WebP?";
1062 frame: extractKeyframeFromWebP(webP),
1063 duration: ((typeof duration == 'number')?duration:options.frameDuration)
1068 * Finish writing the video and return a Promise to signal completion.
1070 * If the destination device was memory (i.e. options.fileWriter was not supplied), the Promise is resolved with
1071 * a Blob with the contents of the entire video.
1073 this.complete = function() {
1074 flushClusterFrameBuffer();
1080 return blobBuffer.complete('video/webm');
1083 this.getWrittenSize = function() {
1084 return blobBuffer.length;
1087 options = extend(optionDefaults, options || {});
1092 if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
1093 module.exports = WebMWriter(require("./ArrayBufferDataStream"), require("./BlobBuffer"));
1095 window.WebMWriter = WebMWriter(ArrayBufferDataStream, BlobBuffer);