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.