DEV Community

Mason K
Mason K

Posted on

FFmpeg concat demuxer: join clips without re-encoding, and a pre-flight check that stops silent corruption

TL;DR

We'll join clips with ffmpeg -f concat -c copy, reproduce what goes wrong when the inputs differ, and write a Python pre-flight check that refuses to join mismatched files. Tested on FFmpeg 6.1.1.

1. The happy path 🎬

Make two clips that match (this uses synthetic test sources):

ffmpeg -f lavfi -i testsrc=size=640x360:rate=30:duration=3 \
       -f lavfi -i sine=frequency=440:duration=3 \
       -c:v libx264 -pix_fmt yuv420p -g 30 -c:a aac -ar 48000 a.mp4
Enter fullscreen mode Exit fullscreen mode

Write a list file. The header is optional for plain file lines, but if you use it, the docs say ffconcat version 1.0 must be exactly as written on the first line, with no BOM.

# list.txt
file 'a.mp4'
file 'a.mp4'
Enter fullscreen mode Exit fullscreen mode

Join:

ffmpeg -f concat -i list.txt -c copy joined.mp4
Enter fullscreen mode Exit fullscreen mode

Per the FFmpeg formats docs, timestamps are adjusted so each file starts where the previous one ended.

2. The unsafe file name error

printf "file '/tmp/w/a.mp4'\n" > abs.txt
ffmpeg -f concat -i abs.txt -c copy x.mp4
Enter fullscreen mode Exit fullscreen mode
[concat @ 0x55eeca51a0c0] Unsafe file name '/tmp/w/a.mp4'
Enter fullscreen mode Exit fullscreen mode

The safe option defaults to 1. Use relative paths, or pass -safe 0 for lists you generate yourself.

⚠️ Note: Never use -safe 0 on lists that include user-supplied paths.

3. Reproduce the silent failure

Now a second clip at 25 fps with 44.1 kHz audio:

ffmpeg -f lavfi -i testsrc2=size=640x360:rate=25:duration=3 \
       -f lavfi -i sine=frequency=660:duration=3 \
       -c:v libx264 -pix_fmt yuv420p -g 25 -c:a aac -ar 44100 b.mp4
printf "file 'a.mp4'\nfile 'b.mp4'\n" > list.txt
ffmpeg -f concat -safe 0 -i list.txt -c copy out.mp4; echo $?
ffprobe -v error -show_entries stream=codec_type,r_frame_rate,sample_rate,duration -of csv=p=0 out.mp4
Enter fullscreen mode Exit fullscreen mode
0
video,30/1,5.000000
audio,48000,0/0,5.533833
Enter fullscreen mode Exit fullscreen mode

Exit code 0, no warning. We expected six seconds each. The audio is labelled 48 kHz though half of it is 44.1 kHz. The docs say all files must have the same streams (same codecs, time base, etc.), and the demuxer does not enforce it.

4. A pre-flight check 🛠️

# check_concat.py
import json, subprocess, sys

def probe(path):
    out = subprocess.check_output([
        "ffprobe", "-v", "error", "-show_entries",
        "stream=codec_type,codec_name,width,height,r_frame_rate,sample_rate,time_base,pix_fmt",
        "-of", "json", path])
    streams = json.loads(out)["streams"]
    return sorted(streams, key=lambda s: s["codec_type"])

def main(paths):
    ref, bad = probe(paths[0]), False
    for p in paths[1:]:
        cur = probe(p)
        if cur != ref:
            bad = True
            print(f"MISMATCH {p}")
            for a, b in zip(ref, cur):
                for k in a:
                    if a.get(k) != b.get(k):
                        print(f"  {a['codec_type']}.{k}: {a.get(k)} vs {b.get(k)}")
    sys.exit(1 if bad else 0)

if __name__ == "__main__":
    main(sys.argv[1:])
Enter fullscreen mode Exit fullscreen mode

Run against our clips:

python3 check_concat.py a.mp4 b.mp4
Enter fullscreen mode Exit fullscreen mode
MISMATCH b.mp4
  audio.sample_rate: 48000 vs 44100
  audio.time_base: 1/48000 vs 1/44100
  video.r_frame_rate: 30/1 vs 25/1
  video.time_base: 1/15360 vs 1/12800
Enter fullscreen mode Exit fullscreen mode

Exit code 1. Gate your pipeline on that.

5. Normalize, then copy

ffmpeg -i b.mp4 -vf fps=30 -ar 48000 -c:v libx264 -pix_fmt yuv420p -g 30 -c:a aac b2.mp4
python3 check_concat.py a.mp4 b2.mp4 && \
  ffmpeg -f concat -i list2.txt -c copy ok.mp4
Enter fullscreen mode Exit fullscreen mode

Result in my run: 6.00 s video, 6.04 s audio. The extra 40 ms is AAC priming and padding.

6. Or use the concat filter

ffmpeg -i a.mp4 -i b.mp4 -filter_complex \
"[0:v]fps=30,format=yuv420p[v0];[1:v]fps=30,format=yuv420p[v1];\
[0:a]aresample=48000[a0];[1:a]aresample=48000[a1];\
[v0][a0][v1][a1]concat=n=2:v=1:a=1[v][a]" \
-map "[v]" -map "[a]" -c:v libx264 -c:a aac out_filter.mp4
Enter fullscreen mode Exit fullscreen mode
Method Re-encodes Needs matching inputs Speed
concat demuxer + copy No Yes Fast
concat filter Yes No (normalize in graph) Slower

My run gave 6.00 s video and 6.03 s audio.

Wrapping up

Next, look at the duration, inpoint and outpoint directives for trimming inside a list (docs note inpoint works best with intra-frame codecs), and our earlier keyframe-accurate trim post if you cut before joining. Tags: #ffmpeg #tutorial #video.

Top comments (2)

Collapse
 
fredabila profile image
Fred Abila •

The pre-flight check is the right gate, and catching sample rate and frame rate before -c copy is exactly what stops the silent 5.5s audio on a 6s join. I'd add two more fields to the probe: channel_layout (or channels) and profile, because a 5.1 clip next to a stereo one, or High 4.1 next to Baseline, will also copy "successfully" and then break in a player. After a clean join, remux with -movflags +faststart, and listen at each seam — the 40 ms of AAC priming you already measured can still click even when the durations look close.

Collapse
 
frankshan001 profile image
shansjl •

Your step 3 is the part people miss: exit code 0 plus a 5.53 s audio track on a "6 s" join, with no warning. A pre-flight gate before -c copy is the right fix.

One thing I'd add is a post-flight check on the output, since the input check can't catch everything (fredabila's channel_layout/profile point is a good example). In CutVoke (an open-source video editor I maintain), the end-to-end demo script ffprobes the exported file and fails unless width/height, r_frame_rate (30/1), and the codecs are what the project asked for. It also fails if the duration is off by more than 0.1 s, decodes the whole file to -f null, and checks that the audio isn't silent or clipping: github.com/frankShan001/CutVoke/bl...

That export re-encodes (closer to your section 6 than to stream copy), so it trades speed for not caring about mismatched inputs. Your table sums up that trade-off well.