gpac / mp4box.js

JavaScript version of GPAC's MP4Box tool
https://gpac.github.io/mp4box.js/
BSD 3-Clause "New" or "Revised" License
1.94k stars 326 forks source link

Save segments to separate files #260

Open yayayayayayayayayayayaya opened 2 years ago

yayayayayayayayayayayaya commented 2 years ago

Hi everyone, thanks for this amazing project first of all!

I'm trying to load an mp4 file from disk and saving the audio and video segments back to disk using node & mp4box.js. Now the problem is the segments can't be played using MSE (other segmented mp4 work perfectly, so the issue has to be with my segmentation code). I'm doing the following:

const fs = require('fs')
var MP4Box = require('mp4box')

// ...

var mp4 = MP4Box.createFile()
mp4.onError = function(e) { console.log(e) }
mp4.onReady = function(info) {
    for (var i = 0; i < info.tracks.length; i++) {
        var nbrSamples = Math.round((info.tracks[i].nb_samples / (info.tracks[i].movie_duration / info.tracks[i].movie_timescale)) * 5)
        // ...
        mp4.setSegmentOptions(info.tracks[i].id, null, { nbSamples: nbrSamples, rapAlignement: true })
    }
    const initSegs = mp4.initializeSegmentation()
    for (let i = 0; i < initSegs.length; i++) { 
        // ... (segmentType is either audio or video)
        var path = './media/converted_mp4/TestvideoiOS_' + segmentType + '_init.mp4'
        fs.writeFileSync(path, Buffer.from(new Uint8Array(initSegs[i].buffer)))
    }
    mp4.start()
}

mp4.onSegment = function(id, user, buffer, sampleNum, is_last) {
    // ... (segmentType is either audio or video, segmentCount is segment number)
    var path = './media/converted_mp4/TestvideoiOS_' + segmentType + '_' + segmentCount + '.m4s'
    fs.writeFileSync(path, Buffer.from(new Uint8Array(buffer)))
}

var fb = fs.readFileSync('./media/converted_mp4/original.mp4').buffer
fb.fileStart = 0
mp4.appendBuffer(fb)
mp4.flush()

Is there something wrong with this approach? I can't seem to get these files playing using MSE. I hope somebody can point me in the right direction, because I can't seem to figure out what's going wrong here. Thanks a lot and best regards, Ya