Split Video into Variable Lengths with FFmpeg

Splitting a video into segments of differing and precise lengths is a common task in video processing. This guide provides a straightforward tutorial on how to use FFmpeg, a powerful command-line tool, to cut a single video file into multiple parts of variable durations. You will learn how to segment your videos using both individual commands for precise cuts and the built-in segment muxer for splitting a video at multiple timestamps in one go.

Method 1: Splitting Using Precise Cut Commands

The most precise way to extract variable segments is by running individual commands for each segment using the start time (-ss) and duration (-t) parameters, or end time (-to).

To extract a segment, use the following command structure:

ffmpeg -ss [start_time] -i input.mp4 -t [duration] -c copy output.mp4

Example workflow for three custom segments:

  1. Segment 1 (0 to 45 seconds):

    ffmpeg -ss 00:00:00 -i input.mp4 -t 45 -c copy segment1.mp4
  2. Segment 2 (45 seconds to 2 minutes and 15 seconds - duration of 90 seconds):

    ffmpeg -ss 00:00:45 -i input.mp4 -t 90 -c copy segment2.mp4
  3. Segment 3 (2 minutes and 15 seconds to 5 minutes - duration of 165 seconds):

    ffmpeg -ss 00:02:15 -i input.mp4 -t 165 -c copy segment3.mp4

Method 2: Splitting with the Segment Muxer (Single Command)

If you want to split an entire video into multiple variable segments in a single command, you can use FFmpeg’s segment muxer. This method is highly efficient because it automatically cuts the video at a list of comma-separated timestamps.

The syntax for splitting at specific time markers is:

ffmpeg -i input.mp4 -f segment -segment_times 30,120,300 -c copy output_%03d.mp4

This command results in four segments: * Segment 0: 0 to 30 seconds * Segment 1: 30 to 120 seconds * Segment 2: 120 to 300 seconds * Segment 3: 300 seconds to the end of the video

Keyframe Accuracy vs. Re-encoding

When using -c copy, FFmpeg can only cut the video at keyframes (I-frames). If your split points do not align with a keyframe, the player may show a frozen frame or black screen at the start of a segment until the next keyframe is reached.

If absolute frame-perfect accuracy is required for your variable cuts, you must re-encode the video. To do this, remove the -c copy flag (or specify a video codec like -c:v libx264):

ffmpeg -ss 00:00:45 -i input.mp4 -t 90 -c:v libx264 -c:a aac segment2.mp4