Dev.to WebDev 🛠 Dev 👁 0 📖 2 min read

Split a video into equal parts with ffmpeg.wasm (and why to force keyframes)

I build Mediaextractr, a set of file tools that run in the browser. One of them splits a video into equal parts, or into pieces of a set length. Here is how it works with ffmpeg.wasm, and the one flag that matters most.

I build Mediaextractr, a set of file tools that run in the browser. One of them splits a video into equal parts, or into pieces of a set length. Here is how it works with ffmpeg.wasm, and the one flag that matters most.

The tempting shortcut

You can split with stream copy (-c copy). It is very fast, because nothing is re-encoded. The catch: a copied segment can only begin on a keyframe that already exists in the source. If you ask for 30 second pieces and the keyframes do not fall on those marks, the pieces come out longer or shorter than you asked.

Re-encode and force a keyframe at every cut

So the tool re-encodes, and tells the encoder to place a keyframe exactly where each cut will be:

ffmpeg -i input.mp4 \
  -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1" \
  -c:v libx264 -preset veryfast -crf 23 -pix_fmt yuv420p \
  -c:a aac -b:a 160k \
  -force_key_frames "expr:gte(t,n_forced*30)" \
  -f segment -segment_time 30 -reset_timestamps 1 \
  -map 0:v:0 -map "0:a:0?" \
  part%03d.mp4

What each part does:

  • The scale filter makes the width and height even, which yuv420p H.264 needs.
  • -force_key_frames adds a keyframe at 0, 30, 60 seconds and so on.
  • -f segment -segment_time 30 writes a new file at each of those points.
  • -reset_timestamps 1 makes every piece start at zero, so it plays properly on its own.
  • -map "0:a:0?" keeps the first audio track if there is one. The ? stops a silent video from failing.

For equal parts instead of a fixed length, read the duration first and use duration / parts as the segment length.

In the browser

With ffmpeg.wasm the same arguments go to exec, minus the leading ffmpeg. The input is written to the in-memory file system, and each part is read back and bundled for download. The file is not uploaded.

The honest cost

Re-encoding in WebAssembly is much slower than desktop ffmpeg, and the whole job has to fit in the browser's memory. Short clips are comfortable. A long, high resolution video on a phone may be slow or may fail. For very large files, run the command above on a computer.

If you want to try it without setting anything up: Split a video into parts.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.