I got a code that generates videos from scratch (got gifs, captions and audio). It works amazing when done once, however, when put in a loop and it should create more than 1 video it freezes being caused by memory leak. Upon investigation I realized that ffmpeg (v1.1.0) chains the loop iterations carrying the parameters and options from the first iteration to the second. It then breaks (overwrites) the first video and infinitely writes the second.
This is my dependency
const ffmpeg = require("fluent-ffmpeg")()
.setFfprobePath(ffprobe.path)
.setFfmpegPath(ffmpegInstaller.path)
It looks like this
async function convertGifToVideo(
gifFile,
audioFile,
subtitlesFile,
tempDirectory
) {
return new Promise((resolve, reject) => {
const outputFile = `${tempDirectory}/video_${Date.now()}.mp4`
ffmpeg
.input(gifFile)
.inputFormat("gif")
.inputOptions("-stream_loop -1")
.input(audioFile)
.outputOptions("-shortest")
.outputOptions(`-vf subtitles=${subtitlesFile}`)
.outputOptions("-report")
.output(outputFile)
.on("end", () => {
console.log(`Combined ${gifFile} and ${audioFile} into ${outputFile}`)
resolve(outputFile)
})
.on("error", (err, stdout, stderr) => {
console.error("Error combining GIF and audio:", err)
console.error("ffmpeg stdout:", stdout)
console.error("ffmpeg stderr:", stderr)
reject(err)
})
.run()
})
}
And it's called in a loop
for (const key in script) {
if (script.hasOwnProperty(key)) {
...stuff
const videoFileName = await convertGifToVideo(
gifFileName,
audioFileName,
subtitlesFileName,
tempDirectory
)
}
}
Here is a piece of log from the first video generation
ffmpeg started on 2024-01-10 at 02:58:52 Report written to "ffmpeg-20240110-025852.log" Command line: /home/simon/Documents/AFYTUBE/node_modules/@ffmpeg-installer/linux-x64/ffmpeg -f gif -stream_loop -1 -i ./temp/gif_funny_frogs.gif -i ./temp/funny_frogs.mp3 -y -shortest -vf "subtitles=./temp/funny_frogs.srt" -report ./temp/video_1704880732780.mp4
Here is a piece of log from the second one
/home/simon/Documents/AFYTUBE/node_modules/@ffmpeg-installer/linux-x64/ffmpeg -f gif -stream_loop -1 -i ./temp/gif_funny_frogs.gif -i ./temp/funny_frogs.mp3 -f gif -stream_loop -1 -i ./temp/gif_leg_exercises.gif -i ./temp/leg_exercises.mp3 -y -shortest -vf "subtitles=./temp/funny_frogs.srt" -report -shortest -vf "subtitles=./temp/leg_exercises.srt" -report ./temp/video_1704880732780.mp4 ./temp/video_1704880750879.mp4
Any ideas what I am doing wrong?