0

I need to encode/convert many videos on my (linux) server. And FFMPEG is resource intensive. I am running Node.js and using fluent-ffmpeg

    const Ffmpeg = require("fluent-ffmpeg");
    videos.forEach(video=> {
        covertVideo(filename, (compressionResult)=>{
            //do something here
        });
    });
    function covertVideo(filename, callback){
        var ffmpeg = new FfmpegCommand(filename);
        ffmpeg.setFfmpegPath(pathToFfmpeg);
        ffmpeg.addOptions("-threads 1")
        .fps(23)
        .complexFilter([
            "scale=w='if(gt(a,0.75),240,trunc(320*a/2)*2)':h='if(lt(a,0.75),320,trunc(240/a/2)*2)',pad=w=240:h=320:x='if(gt(a,0.75),0,(240-iw)/2)':y='if(lt(a,0.75),0,(320-ih)/2)':color=black[scaled]"
        ])
        .on('error', function(err) {
            console.log('An error occurred: ' + err.message);
            return callback(false);
          })
        .on('end', function() {
            console.log('Compression finished !');
            return callback(true);
          })
        .save("./tmp/"+filename);
    }

So, I am using foreach loop to iterate through the file to be encoded. At each loop this function above is called.

The problem here is that the foreach enters the second loop and start encoding when the first is still being encoded by FFMPEG thereby showing "Resource temporarily unavailable error".

Is there a way to queue files sent to FFMPEG so that next file is encoded when the previous is done and not concurrently.

OR

Is there a way for the Nodejs foreach to wait for ffmpeg to finish the first video before proceeding to the next loop.

Hall45
  • 1
  • 2
  • my node.js memory is fading, but it appears the issue is that you aren't waiting on ffmpeg. I'd make `covertVideo` to return `Promise` which is resolved by `ffmpeg`'s `'end'` and `'error`' events. Then, loop using a technique like [this one](https://stackoverflow.com/a/37576787/4516027) – kesh Aug 12 '22 at 14:13
  • Great @kesh. You pointed in the right direction. I changed from using a callback to using a `Promise` for the covertVideo function. And resolved the Promise by ffmpeg's end and error event. Then when consuming the promise, I used async/await make sure each loop is completed from ffmpeg's end before entering the next loop. Thanks @kesh. – Hall45 Aug 14 '22 at 11:14

0 Answers0