6

I have two videos that I want to trim, and then merge the trimmed output. They're all the same size/codec so I'd like to do that without re-encoding too much. But if I do:

ffmpeg -i clip1.mp4 -ss 1.2 -t 2.0 -c copy clip1.trimmed.mp4
ffmpeg -i clip2.mp4 -ss 0.2 -t 2.0 -c copy clip2.trimmed.mp4
ffmpeg -filter_complex '[0:0] [0:1] [1:0] [1:1] concat=n=2:v=1:a=1 [v] [a]'\
-map [v] -map [a] -c:v libx264 merge.mp4

The merged video has issues with audio/video synchronization. This doesn't happen if I replace -c copy by -vcodec libx264 in the trimming command. Is it possible that by not re-encoding, something goes wrong with the timing?


The correct answer, from Mulvya:

ffmpeg -ss 1.2 -t 2.0 -i clip1.mp4 -ss 0.2 -t 2.0 -i clip2.mp4 \
   -filter_complex '[0:v] [0:a] [1:v] [1:a] concat=n=2:v=1:a=1 [v] [a]" \
   -map [v] -map [a] -c:v libx264 merge.mp4

In case that helps, I would add that the syntaxe to add clip specific filters is like:

ffmpeg -ss 1.2 -t 2.0 -i clip1.mp4 -ss 0.2 -t 2.0 -i clip2.mp4 \
   -filter_complex '[0:v]scale=1920:960[v0]; [v0] [0:a] [1:v] [1:a] concat=n=2:v=1:a=1 [v] [a]" \
   -map [v] -map [a] -c:v libx264 merge.mp4

2 Answers 2

5

Since you are ultimately re-encoding the merged segments, just do it in one command,

ffmpeg -ss 1.2 -t 2.0 -i clip1.mp4 -ss 0.2 -t 2.0 -i clip2.mp4 \
       -filter_complex '[0:v] [0:a] [1:v] [1:a] concat=n=2:v=1:a=1 [v] [a]" \
       -map [v] -map [a] -c:v libx264 merge.mp4
3

Merging videos without re-encoding is possible and described in the answers to this other question.

Splitting a video without re-encoding may only be possible for lossless formats. Lossy codecs like h264 (usually) use a series of keyframes and then encode intermediate frames as diffs between current frame and the previous frame. (This is why you get that weird drifting in a damaged video why is goes away on a scene change.)

Theoretically, you might be able to split a video if the cut is just before a key frame. Figuring out where those keyframes are and how to make the cut there is beyond me.

2
  • Ok thanks! Since the user choses exactly where to cut, I'll have to re-encode the trimmed bit
    – Guig
    Apr 5, 2016 at 23:26
  • To figure that out, you can look at the NAL packet headers. Key frames have a very specific header.
    – Aron
    Apr 6, 2016 at 5:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .