FFmpeg -shortest: Stop Encoding When Shortest Stream Ends

This article explains how to use the -shortest option in FFmpeg to automatically end your output file as soon as the shortest input stream finishes. You will learn the correct command syntax, why this option sometimes fails to stop immediately due to stream buffering, and how to fix trailing audio or video issues using advanced parameters like -max_interleave_delta and -fflags shortest.

Basic Usage of the -shortest Option

The -shortest flag is an output option. To use it correctly, you must place it after your input files and before your output file in the command line.

Here is the standard syntax for combining a long video and a shorter audio track (or vice versa):

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -shortest output.mp4

In this command: * -i video.mp4 and -i audio.wav load the inputs. * -map 0:v and -map 1:a select the video from the first input and the audio from the second input. * -shortest tells FFmpeg to stop writing to output.mp4 the moment either the video or audio stream runs out of data.

Troubleshooting: Why -shortest Doesn’t Stop Immediately

Sometimes, the resulting video still contains a few extra seconds of frozen video or silence at the end. This happens because FFmpeg buffers packets to ensure proper interleaving of audio and video. If one stream finishes, FFmpeg may continue reading buffered packets from the other stream before finalizing the file.

To force FFmpeg to stop instantly when the shortest stream ends, you can use the following advanced workarounds.

1. Use the -max_interleave_delta Option

By reducing the maximum interleaving buffer size, you prevent FFmpeg from buffering too much data ahead of time. Adding -max_interleave_delta 100M (or a smaller value like 1M) is the most reliable way to force a clean cut.

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -shortest -max_interleave_delta 100M output.mp4

2. Enable the shortest fflag

In newer versions of FFmpeg, you can pass the shortest flag directly to the formatter flags to improve accuracy:

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -fflags shortest -shortest output.mp4

3. Use the shortest Parameter in Filtergraphs

If you are mixing audio or applying filters, some filters have their own shortest parameters. For example, if you are using the amix filter to mix multiple audio inputs, you should define the duration option within the filter itself:

ffmpeg -i video.mp4 -i audio1.mp3 -i audio2.mp3 -filter_complex "[1:a][2:a]amix=inputs=2:duration=shortest[a]" -map 0:v -map "[a]" -shortest output.mp4