Trim video files using FFmpeg

This is a note to self, and hopefully others, about how to easily and quickly trim videos without recompressing the file.

I often have long video recordings that I want to split or trim. Splitting and trimming are temporal transformations and should not be confused with the spatial transformation cropping. Cropping a video means cutting out parts of the image, and I have another blog post on cropping video files using FFmpeg.

Trimming oneliners

You can split and trim files in most graphical video editing software, but these will typically recompress the export file, reducing the video quality. It also takes a long time. A much better solution is to perform “lossless” trimming. Fortunately, a simple way is to do this with the beautiful command-line utility FFmpeg. This is all you need to do:

ffmpeg -i input.mp4 -ss 01:19:27 -to 02:18:51 -c:v copy -c:a copy output.mp4

This will cut the section from about 1h19min (after the -ss command) to 2h18min (after the -to command). The copy parts of the command are meant to copy both the original audio and video content without recompressing. This means that the above command only takes a few seconds to run.

You may instead want to specify a fixed duration to extract, in which case you can use:

ffmpeg -i input.mp4 -ss 00:01:10 -t 00:01:05 -c:v copy -c:a copy output.mp4

This will extract 1min5sec (using the -t flag) starting from 1min10sec (the -ss flag) in the file.

Keyframe seeking

I have sometimes experienced that the above commands leave black frames at the beginning of the video. After some digging around I found that this may be because of lacking keyframes. So a trick is to move the -ss command before -i in the example above:

ffmpeg -ss 01:19:27 -i input.mp4 -to 02:18:51 -c:v copy -c:a copy output.mp4

This is a trick described in the seeking part of the FFmpeg tutorial. When -ss comes first, it will adjust to the nearest keyframe of the video. Unfortunately, it will also reset the time, so that you have to adjust the end time (set with -to) based on the new beginning time of the video file.

Happy trimming!