javascriptvideomp4media-sourcemp4box

reencode non-fragmented mp4 into fragmented mp4


I'm using MediaSource extension to play videos. However,MediaSource only supports fragmented MP4 videos.

How can I convert a non-fragmented MP4 video into a fragmented MP4 video in JavaScript so that I can use MediaSource to play the video?

MP4Box's isFragmented boolean returns false on non-fragmented videos:

blob.arrayBuffer().then((videoBuffer => {
    mp4boxfile.onReady = function (info) {
        const isFragmented = info.isFragmented;
        if (!isFragmented) {
            //Need to reencode video into a fragmented video here
        }
    }

//...

    const chunkSize = Math.ceil(videoBuffer.byteLength / 80000);
    let start = 0;
    let currentEnd = 80000;
    let videoBufferChunk;

    for (let i = 0; i < chunkSize; i++) {
        videoBufferChunk = videoBuffer.slice(start, currentEnd);

        videoBufferChunk.fileStart = start;
        start = mp4boxfile.appendBuffer(videoBufferChunk);
        currentEnd = start + 80000;
        mp4boxfile.flush();
    }
//...
}

How can I reencode a MP4 video into a fragmented one with JavaScript?


Solution

  • You could use ffmpeg.wasm, it's basically ffmpeg for the browser but with native performance. This way you could integrate the fragmentation into your front end which is what you are trying to do, if I understand correctly.

    ffmpeg.wasm

    I am afraid I can't help you with the actual fragmentation part using ffmpeg, but this post discusses it for normal ffmpeg.