get-video-mime
Version:
A simple CLI tool to get a video's MIME string including relevant codes for use with MediaSource Extension.
75 lines (52 loc) • 2.07 kB
JavaScript
/**
* Define a simple Transform stream to process each chunk of the video
* and try to detect the MIME
*/
const { Transform } = require('stream');
const MP4Box = require('mp4box');
class DetectMIME extends Transform {
constructor(setMime) {
super();
this.mime = '';
this.mp4boxfile = MP4Box.createFile();
this.chuckStart = 0;
// If MP4Box emits an error pass it down the stream
this.mp4boxfile.onError = (error) => { this.emit(error); };
// When MP4Box has enough to parse the file, grab the MIME
this.mp4boxfile.onReady = (info) => {
if (! info || ! info.mime) {
this.emit(new Error('Non MIME returned from MP4Box.js'));
return;
}
this.mime = info.mime;
// MP4Box.js reports opus audio as Opus in the codec string and Firefox doesn't like that
// and it says the mime type is not supported. We'll special case this and lower case opus.
this.mime = this.mime.replace('Opus', 'opus');
setMime(this.mime);
};
}
_transform(chunk, encoding, next) {
// No need to process if we already have the MIME
if (this.mime) {
next();
return;
}
// Convert the Buffer into an ArrayBuffer
// https://stackoverflow.com/a/31394257/931860
const arrayBuffer = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
// This is required for MP4Box.js
arrayBuffer.fileStart = this.chuckStart;
// Add this chunk to MP4Box.js
this.mp4boxfile.appendBuffer(arrayBuffer);
// Increment the chunkStart
this.chuckStart += chunk.byteLength;
next();
}
_flush(next) {
// When we're done, output the detected MIME
this.push(this.mime);
// Signal that we are done processing
next();
}
}
module.exports = DetectMIME;