Skip to content
CLEARER IDEAS. BETTER EXECUTION.PROGRAMMING · CREATIVE AI · WORKFLOWS
Menu & topics
Video & audio

Why a One-Second Soundtrack Cuts a Four-Second Video in FFmpeg

Reproduce a short FFmpeg export with -shortest, loop the audio input, and verify the video frame and audio sample counts.

A long film strip stretched between two reels, with a shorter loop of blue audio tape and a pencil on a wooden table
Film between two reels beside a shorter loop of blue audio tape.
The short answerWhen the added audio ends first, -shortest can cut the picture too. Loop the short audio input so the finite video sets the output length, then verify the selected streams.

The source clip contains 96 frames. The first export contains 24. Both come from a local 24 fps test pattern. The export gained a soundtrack, yet its reported duration fell from 4 seconds to 1 second. This is the expected result when the output uses `-shortest` and its selected audio ends before the video. The flag has no way to know that the picture was meant to set the length.

The corrected export keeps 96 frames and reports 4 seconds. It repeats the audio input before writing the output, then uses the same ending rule. This time, the finite video ends first. The evidence comes from files encoded and decoded locally, with a generated test pattern and a 440 Hz test tone. Use those inputs to check the timing decision before substituting a soundtrack whose musical ending or licensing requires a separate decision.

Compare the two files at the point where the picture disappears

The video input is `pattern.mkv`, a 160 by 90 pixel pattern generated by FFmpeg's `testsrc2` source at 24 frames per second for 4 seconds. It has a video stream and no audio. The second input is `tone.wav`, a 1-second tone generated at 48,000 samples per second. The script creates both assets locally. They are synthetic test material and their contents do not come from a media library or video generation service.

The baseline output is `short.mkv`. It explicitly maps video from the first input and audio from the second. The video is encoded as FFV1 and the audio as signed 16-bit PCM. The output uses `-shortest`. It has both requested streams, so the result is more subtle than a missing soundtrack or a missing picture. In the local run, ffprobe reports a 1.000000-second container duration and counts 24 video frames. It is a complete file under that command's ending rule, even though it is short relative to the source video.

The corrected output is `looped.mkv`. It maps the same streams and uses the same codecs and ending rule. The single change is `-stream_loop -1` before the audio input. That asks FFmpeg to repeat that input indefinitely. The output remains finite because the selected video is still a finite stream. ffprobe reads 96 video frames and reports 4.000000 seconds. The observed change is from a 24-frame export to a 96-frame export for this input pair. The fixture does not need a player or a judgement about whether the edit looks smooth.

Compare the exports with the source clip as well as with each other. If you only compare the outputs, the second looks longer but you have no direct evidence that it recovered the original frame count. The source and the looped output both show 96 in the probe result. A separate comparison of decoded frame hashes also matches all 96, in order. The baseline frame hashes match only the first 24 frames of the source. Those two assertions provide different evidence from the duration displayed for the container.

Read the option from the input it applies to

The command in the original example opens `pattern.mkv` first. It then places any audio loop arguments immediately before `-i tone.wav`. This is the part to inspect when adapting the fix. The loop is an input option. If the option appears before the video input instead, you are changing which stream can end. That would be a different experiment. Keep the placement next to the input you intend to repeat so another person can verify the association without reconstructing the entire command.

The first map, `-map 0:v:0`, takes the first video stream of input 0. The second map, `-map 1:a:0`, takes the first audio stream of input 1. The indices are clear because the example deliberately builds two simple files. A real clip may already have audio. If the intention is to replace that audio, map the desired streams explicitly. If the original audio should be mixed with a new soundtrack, first define the mix and decide which resulting stream should control the end. The small fixture is a replacement-style construction with a silent picture source and one added tone.

Place `-shortest` with the output options for the named export. The role of the flag in this setup is to stop when one selected output stream ends. It does not mean “use the video length.” In the baseline the tone is the shorter stream. When the tone is extended by looping and the video remains finite, the picture sets the ending in this two-stream fixture. This explanation is limited to the command and outputs that ran. Streams with gaps, different start times, or other mapping rules warrant a separate check.

FFmpeg documents -stream_loop as an input option, with -1 for indefinite repetition. The -shortest output option ends encoding when the shortest output stream ends. FFmpeg command documentation, input loops and shortest output

Read the supported command from the Python list in the code. The fixture runs each executable with a list of arguments, a working directory reserved for the experiment, and a timeout. That means the command can write its four named media files within the supplied output directory without asking for interactive input. It uses `-n` to refuse overwriting an existing media file. The Python function also expects a fresh output directory. To reproduce the experiment a second time, give it a different unused directory so you can compare the two runs. The code never needs an API key or source footage from a real project.

audio_duration.py

"""Owned test-pattern and tone fixture for FFmpeg input-loop placement."""
import json
from pathlib import Path
import shutil
import subprocess
import sys


def run(binary, args, root):
    result = subprocess.run([binary, *args], cwd=root, check=True, capture_output=True,
                            text=True, encoding='utf-8', timeout=40)
    return result.stdout


def probe(ffprobe, filename, root):
    return json.loads(run(ffprobe, ['-v', 'error', '-count_frames', '-show_entries',
                                   'stream=codec_type,codec_name,nb_read_frames,avg_frame_rate:format=duration',
                                   '-of', 'json', filename], root))


def experiment(root):
    root = Path(root).resolve()
    root.mkdir()
    ffmpeg = shutil.which('ffmpeg')
    ffprobe = shutil.which('ffprobe')
    if not ffmpeg or not ffprobe:
        raise RuntimeError('FFmpeg and ffprobe must be installed')
    common = ['-nostdin', '-hide_banner', '-loglevel', 'error', '-n']
    run(ffmpeg, [*common, '-f', 'lavfi', '-i', 'testsrc2=size=160x90:rate=24:duration=4',
                 '-c:v', 'ffv1', 'pattern.mkv'], root)
    run(ffmpeg, [*common, '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000:duration=1',
                 '-c:a', 'pcm_s16le', 'tone.wav'], root)
    for filename, loop_args in [('short.mkv', []), ('looped.mkv', ['-stream_loop', '-1'])]:
        run(ffmpeg, [*common, '-i', 'pattern.mkv', *loop_args, '-i', 'tone.wav',
                     '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'ffv1',
                     '-c:a', 'pcm_s16le', '-shortest', filename], root)
    info = {name: probe(ffprobe, name, root) for name in ('pattern.mkv', 'tone.wav', 'short.mkv', 'looped.mkv')}
    info['ffmpeg'] = run(ffmpeg, ['-version'], root).splitlines()[0]
    info['ffprobe'] = run(ffprobe, ['-version'], root).splitlines()[0]
    (root / 'probes.json').write_text(json.dumps(info, indent=2), encoding='utf-8')
    return info


if __name__ == '__main__':
    print(json.dumps(experiment(sys.argv[1]), indent=2))

Recorded local check: 8 local test methods on original synthetic testsrc2 video and sine audio. Actual 96-frame 4-second source and 1-second tone. Unlooped shortest export 24 frames/1 second, looped shortest export 96 frames/4 seconds. Decoded video hashes match the first 24 or all 96 source hashes. Decoded mono PCM sample counts 48000 and 192000. This tests the given mapping and codecs, with no player, listening, timestamp equality, AI video or benchmark claim.; environment: Python 3.12.3 Windows; ffmpeg version 2026-01-26-git-fe0813d6e2-full_build-www.gyan.dev

Keep the fixture small enough to inspect completely

The four-second and one-second lengths make a simple test. At a fixed 24 frames per second, the expected counts are 96 and 24 if the outputs stop on those exact durations. The original local run matches those counts. A short pattern also makes it practical to decode the whole output for verification. In a project with a longer clip, choose a minimal test excerpt with the same relevant mapping and duration rules before running a full export.

The test tone is useful because it can be created on demand. The number 440 identifies the generated frequency and the number 48,000 identifies the sample rate. Neither tells you whether repeating a real soundtrack will sound natural. A musical passage may include a fade, a pause, or an audible jump at the repeat boundary. Treat loop quality as another requirement when you choose actual audio. The local test asks whether a tone supplies the full length of audio while the video runs to the end.

Use codecs and a container that let you inspect the result you intend to test. FFV1 and PCM are choices for this retained Matroska fixture. This article does not claim that those choices suit a browser, phone, or publishing site. If a delivery format calls for a different video or audio codec, run the command for that format and check the result independently. Encoder behavior and timestamp details can matter when judging end boundaries. Do not assume that every delivery export will have the same rounded duration string as these files.

If you replace the synthetic video with a project clip during diagnosis, keep the clip's actual frame rate and duration in the record. The pattern begins with no preexisting audio or deliberate time offset. A camera recording or a prior edit can have additional streams and different timing. First inspect what is present. Then write down which video and audio streams should appear in the export and which should set its duration. With this information you can tell whether a short file came from input selection, an ending rule, or a distinct trim in the command.

Verify the duration, the picture, and the sample count separately

The `probe` function calls ffprobe with `-count_frames` and requests a compact JSON result. It records each stream's type, codec, counted frames, and average frame rate, plus the reported container duration. For video in this fixture the stream count reads `24` or `96`, depending on the file. Use the video stream entry when checking that number. The audio entry also has a frame count in the probe output. An audio frame in that report is not one audio sample, so do not multiply or compare the audio count as if it were a video frame count.

FFprobe can count frames and report the count in each stream section. FFprobe documentation, counted frames

The test harness checks that the video source has only the video stream, 96 counted frames, and a four-second duration. It checks that the WAV uses PCM and reports one second. It then tests that the baseline has 24 frames and the looped output has 96. A separate check compares the stream types of both results. Taken together, these assertions show that retaining the picture length was achieved while including the soundtrack. Checking only the video count would not catch an export that accidentally omitted the audio stream.

For a stronger check on the picture, the harness decodes the video in each file and requests FFmpeg's `framemd5` output. It compares the digest fields in order. The test for `short.mkv` matches its decoded hashes against the first 24 from the source. The test for `looped.mkv` matches the entire decoded hash sequence. This comparison addresses the decoded frame contents and their order under the local command. It does not compare container bytes or prove that each timestamp and every metadata field is identical.

To verify the audio length in a unit that is easier to interpret, the test decodes the audio to one channel of signed 16-bit little-endian PCM at 48,000 samples per second. It divides the byte length by 2 to count samples in that decoded result. The baseline yields 48,000 samples and the looped output yields 192,000. At the selected decode rate those lengths correspond to one and four seconds. The comparison is a count after the specified decode, not a measurement of perceived audio continuity, delay, or loudness.

All eight local test methods passed using Python 3.12.3 on Windows and FFmpeg and ffprobe build `2026-01-26-git-fe0813d6e2`. The retained test output and probe JSON record the measured quantities. The commands were run on November 6, 2026. The version string contains the build date, which is different from the date of the test. If you see another result in a different build, keep both details with the command and the input files so the difference can be reproduced.

Decide what should fill the time after the soundtrack ends

A looping tone gives the experiment an audio stream that does not end before the picture. A real editor still has to decide what belongs in the remaining time. One possible design is to repeat a music bed intended for looping. Another is to leave silence after the short passage. A third is to edit the video down to the music deliberately. These are choices about the output, and each has its own timing test. The looped output here implements only the first timing shape using a synthetic tone.

If the brief asks for silence after a short sound effect, do not interpret “keep all video frames” as “repeat the effect until the end.” Make a project-specific test for the intended ending. For example, check that the video has the expected final frame and inspect the audio during the later part of the export using a method appropriate to that project's audio contract. A file with the correct overall length can still violate the creative requirement. The two-file comparison in this article will help isolate the ending flag, while the silence decision needs a new fixture.

If the soundtrack is meant to determine the end, the short export may be the intended result. Write that expectation explicitly, including whether it should keep only the first portion of the video or apply a more deliberate edit. When a project has both picture-led and music-led presets, test each with the same unequal inputs. This can reveal a mistake where both presets call a shared function with identical timing options even though their exported lengths should differ.

For material that should loop, inspect a real repeat boundary when you choose the asset. A synthesized tone that fills four seconds says little about a music track with a transient at the start or reverberation at the end. A video can retain every frame and still have an audio cut that an editor wants to revise. Keep the structural verification and any listening review as distinct records. Here the retained tests are structural, and there was no listening session used as evidence.

Diagnose an unexpected duration before changing the export preset

If a project export suddenly becomes shorter, capture the exact command and probe each input by itself. Identify the stream selected as video and the stream selected as audio. Check their lengths and then inspect the order of the input options. A command that loops the wrong input can look correct at a glance if all the expected flags appear somewhere in it. The position of each flag is part of the evidence. Compare the planned mapping with the streams actually found in the output.

Change one timing decision at a time. Reproduce the shortened export first, then add the audio input loop while holding the source, mapping, and codecs constant. If that returns the expected frames, repeat the test with the project's real output requirements in a separate run. If it does not, compare the output with the source again before changing several options together. A mismatch between frame count and apparent duration can require examining the time information rather than simply looking for a different stopping flag.

A source file can itself be incomplete. If the clips arrived from an external job, run a separate video download acceptance check before treating an output duration difference as an editing issue. That check establishes whether you have the input you intended to edit. In this fixture the source pattern is under local control and is checked before the two outputs are compared. When working with external media, preserve the source until you have confirmed which operation actually removed the missing section.

Record the three numbers that make this particular case easy to compare. Keep the source video frame count, the output video frame count, and the length reported for the output file. If the audio length matters, record the selected sample rate and the observed sample count as well. These fields answer different questions. A name such as “full export” does not establish what is in the file, and a status code indicating success does not establish that the picture reached the intended end.

Test the handoff that will run after a successful export

Suppose the project automatically places the output in a folder that feeds an editor. The exporter can finish successfully with a one-second file under `-shortest`. If that file is not what the project requested, an acceptance check can catch the mismatch before it reaches the next step. Define the condition that matters, such as preserving the number of picture frames for a constant-rate fixture and including the intended audio stream. Then test that the handoff rejects the short version and accepts the looped version when that is the project's chosen rule.

Decide what your test can infer from the source. In this exercise the source has a controlled frame rate and no existing audio. A project that intentionally changes the frame rate may expect a different number of frames in the output. A project that trims leading silence could expect different audio sample counts. Do not copy these numerical assertions into a job with a different contract. Use the numbers from your own fixture and compare the conditions that are supposed to survive the transformation.

When saving records for later diagnosis, preserve the output names and the distinct roles of the files. The fixture directory contains the source pattern, the source tone, and both exported videos. It also has a compact report of what ffprobe read. A project can keep a similar record for a small reproduction without collecting a customer's source media. If it needs to make a decision about real playback, that decision can be tested in the target player using an asset cleared for that purpose. The original example gives you a repeatable check on the output length before that next step.

Choose which evidence belongs in a timing regression

If the project only needs to catch this accidental truncation, use a known constant-rate clip and compare the source and output counts. It is useful to assert that the fixture itself has the number of frames you expect before comparing anything derived from it. Otherwise an incorrectly generated one-second source could produce a one-second export and satisfy a comparison that only checks equality. The first assertion in the local suite prevents that mistake by checking the source's type, count, and duration. A production acceptance rule might instead use a project record that declares the intended length.

If the project also promises a particular timeline, add a separate check for presentation timestamps. The frame hash test reads the digest at the end of each row. It leaves the timestamp fields out deliberately. This keeps the question about frame contents separate from the question about when those frames are presented. For example, a future test that shifts a video later could have matching frame hashes with a different start time. Check start time and duration or the intended timestamps for that case. Nothing in the fixture requires a comparison of timestamps, so there is no claim that one was run.

Think about what changes if a future export uses a different encoder. The lossless fixture keeps the same decoded frame hashes, which makes equality a straightforward local assertion. If an export intentionally changes the pixels, a strict digest comparison may reject the very transformation you requested. Decide whether the new test cares about frame count, sequence, geometry, or decoded visual content. Preserve the frame hash assertion for the lossless case and design a separate expected result for the new case instead of weakening both tests.

Keep a finite ending in any adaptation that repeats an input without limit. In the fixture, the selected video stream ends and `-shortest` stops the output. A command that also loops the video would no longer have that same end condition. Decide what limits the duration before running such an export. The reproduction uses a subprocess timeout as a bound on the test run itself. That timeout is separate from the media duration and is never used to produce the four-second result. A command that only stops because a test times out has failed the reproduction, even if it left a file in the output directory.

Prepared with AI assistance and automated review. The test videos and audio were produced and checked locally from synthetic inputs. The lead photograph illustrates the timing problem.