javascriptcompressionffprobefluent-ffmpegtranscode

How To Asynchronously Check Video File size During Transcoding Process In fluent-ffmpeg


Is there a way during the ffmpeg compression process to determine over various intervals the exact filesize that a video is at?

Such as a method to get current filesize during the process to use when comparing against the videos original filesize.

For example, a potential video being transcoded takes 5 minutes, but during the process, a function will check the file size on intervals of 100 frames or every 5 seconds to ensure that the filesize hasn't exceeded the original. If it has, it will kill the process with command.kill('SIGSTOP');

const transcodeVideo = () => {
  return new Promise((resolve, reject) => {
    ffmpeg("./video.mp4")
      .setFfprobePath(pathToFfprobe.path)
      .setFfmpegPath(pathToFfmpeg)
      .videoCodec("libx264")
      .audioCodec("libmp3lame")
      .size("720x?")
      .on("error", (err) => {
        console.log(err);
      })
      .on("end", () => {
      //irrelevant resolving code in here
      })
      .save("./transVideo.mp4");
  });
};

transcodeVideo();


Solution

  • You can use the targetSize property from the "progress" event to get the current size of the target file:

    let command = ffmpeg
      // ...
      .on("progress", progress => {
        if (progress.targetSize > originalSize) {
          command.kill();
        }
      });
    

    To get the original size, you can use the standard functions in Node's fs library, e.g. fs.stat.