I'm trying to concatenate two mp4 files using ffmpeg. I need this to be an automatic process hence why I chose ffmpeg. I'm converting the two files into .ts files and then concatenating them and then trying to encode that concated .ts file. The files are h264 and aac encoded and I'm hoping to keep the quality the same or as close to original as possible.

ffmpeg -i part1.mp4 -vcodec copy -vbsf h264_mp4toannexb -acodec copy part1.ts
ffmpeg -i part2.mp4 -vcodec copy -vbsf h264_mp4toannexb -acodec copy part2.ts
cat part1.ts part2.ts > parts.ts
ffmpeg -y -i parts.ts -acodec copy -ar 44100 -ab 96k -coder ac -vbsf h264_mp4toannexb parts.mp4

Unfortunately I'm getting the following error message coming back from ffmpeg during encoding:

[h264 @ 0x1012600]sps_id out of range
[h264 @ 0x1012600]non-existing SPS 0 referenced in buffering period
[h264 @ 0x1012600]sps_id out of range
[h264 @ 0x1012600]non-existing SPS 0 referenced in buffering period
[NULL @ 0x101d600]error, non monotone timestamps 13779431 >= 13779431kbits/s    
av_interleaved_write_frame(): Error while opening file

This happens about half way through encoding which makes me think that you can't concat two .ts files together and have it work.

  • 2
    As illustrated in my answer, below, transcoding the files is not necessary. FFmpeg can concatenate multiple mp4 files into a single mp4 file, without any intermediate steps and without any re-encoding. And no software except ffmpeg is needed. The only case in which re-encoding would be required is if the original files are not mp4 files but the intention is to create an mp4 file as the output file. See my answer, below, for the details. – Ed999 Mar 5 '17 at 15:03

13 Answers 13

FFmpeg has three concatenation methods.

1. concat video filter

ffmpeg -i opening.mkv -i episode.mkv -i ending.mkv \
  -filter_complex "[0:v] [0:a] [1:v] [1:a] [2:v] [2:a] concat=n=3:v=1:a=1 [v] [a]" \
  -map "[v]" -map "[a]" output.mkv

Note that this method performs a re-encode.

2. concat demuxer

$ cat mylist.txt
file '/path/to/file1'
file '/path/to/file2'
file '/path/to/file3'

$ ffmpeg -f concat -i mylist.txt -c copy output

for Windows:

(echo file 'first file.mp4' & echo file 'second file.mp4' )>list.txt
ffmpeg -safe 0 -f concat -i list.txt -c copy output.mp4

3. concat protocol

ffmpeg -i "concat:input1|input2" -codec copy output

This method does not work for many formats, including MP4, due to the nature of these formats and the simplistic concatenation performed by this method.

Which one to use

  • concat filter: Use if your inputs do not have the same parameters (width, height, etc), or are not the same formats/codecs, or if you want to perform any filtering. (You could re-encode just the inputs that don't match so they share the same codec and other parameters, then use the concat demuxer to avoid re-encoding the other inputs).

  • concat demuxer: Use when you want to avoid a re-encode and your format does not support file level concatenation (most files used by general users do not support file level concatenation).

  • concat protocol: Use with formats that support file level concatenation (MPEG-1, MPEG-2 PS, DV). Do not use with MP4.

If in doubt try the concat demuxer.

Also see

  • 3
    The Windows command prompt escape character is ^; I also ran into problems with the quotation marks so it became: ffmpeg -i concat:input1^|input2 -codec copy output – user423430 Jul 23 '15 at 4:09
  • 20
    thnx. "concat demuxer" worked for "mp4". – Bhaskar Dabhi Oct 7 '15 at 18:52
  • 5
    For a oneliner use: ffmpeg -safe 0 -f concat -i <(find . -type f -name '*' -printf "file '$PWD/%p'\n" | sort) -c copy output.mkv (mkv accepts more codecs than mp4, but you could also try it with mp4). The -safe 0 is for recent ffmpeg versions complaining about Unsafe file name, and the -type f is for only listing files. I added | sort to sort the files alphabetically; because find reads them in order as saved on filesystem. Works also for files with whitespaces. – erik Dec 2 '16 at 14:15
  • 1
    For me, in Windows, double quotation marks worked (instead of the single in your example): ffmpeg -i "concat:input1|input2" -codec copy output. There is no need to escape the pipe character. – Shovalt Dec 23 '16 at 13:31
  • 1
    @erik mentioned the -safe 0, which is important if you have file entries such as file 'Clip (February 27 2017 at 859 AM).mp4' – Maxim Veksler Mar 8 '17 at 20:08

Here's a fast (takes less than 1 minute) and lossless way to do this without needing intermediate files:-

ls Movie_Part_1.mp4 Movie_Part_2.mp4 | perl -ne 'print "file $_"' | ffmpeg -f concat -i - -c copy Movie_Joined.mp4

The "ls" contains the files to join The "perl" creates the concatenation file on-the-fly into a pipe The "-i -" part tells ffmpeg to read from the pipe

(note - my files had no spaces or weird stuff in them - you'll need appropriate shell-escaping if you want to do this idea with "hard" files).

  • 2
    Did this on OSX and it worked great! Awesome, fast lossless solution with little requirements. – GM Lucid Oct 21 '14 at 21:39
  • 4
    You can also just do ls * | perl -ne 'print "file $_"' | ffmpeg -f concat -i - -c copy Movie_Joined.mp4 if your files are well-named and in order. Worked great for me on OS X, exactly what I wanted. – natebeaty Jan 25 '16 at 18:54
  • 3
    On Linux I used this oneliner: ffmpeg -safe 0 -f concat -i <(find . -type f -name '*' -printf "file '$PWD/%p'\n" | sort) -c copy output.mkv (mkv accepts more codecs than mp4, but you could also try it with mp4). The -safe 0 is for recent ffmpeg versions complaining about Unsafe file name, and the -type f is for only listing files. I added | sort to sort the files alphabetically; because find reads them in order as saved on filesystem. Works also for files with whitespaces. – erik Dec 2 '16 at 14:14
  • 1
    In Windows CMD I used this: ls *mp4 | sed "s/\(*mp4\)/file \1/" | ffmpeg -f concat -i - -c:v copy output.mp4 – Bird Dec 30 '16 at 23:41
  • 3
    I had to add this parameter to ffmpeg to make it work: -protocol_whitelist file,tcp,http,pipe – Bensge Oct 5 '17 at 17:08
up vote 28 down vote accepted

I ended up using mpg as the intermediate format and it worked (NOTE this is a dangerous example, -qscale 0 will re-encode the video...)

ffmpeg -i 1.mp4 -qscale 0 1.mpg
ffmpeg -i 2.mp4 -qscale 0 2.mpg
cat 1.mpg 2.mpg | ffmpeg -f mpeg -i - -qscale 0 -vcodec mpeg4 output.mp4

for MP4 files:

If they are not exactly same (100% same codec, same resolution, same type) MP4 files, then you have to trans-code them into intermediate streams at first:

ffmpeg -i myfile1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp1.ts
ffmpeg -i myfile2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp2.ts
// now join
ffmpeg -i "concat:temp1.ts|temp2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

Result: Output will behave like first file ( and not a second one)

  • 1
    As illustrated in my answer, below, transcoding the files is not necessary. FFmpeg can concatenate multiple mp4 files into a single mp4 file - without any intermediate steps, and without any re-encoding. The only case in which any re-encoding would be needed is if the original files are not mp4 files but the intention is to create an mp4 file as the output file. – Ed999 Mar 5 '17 at 15:02
  • 3
    @Ed999 no, in many cases it cant directly concatenate.. ( – T.Todua Apr 23 '17 at 17:16
  • @T. Todua : I'd be interested to learn what precisely are the differences between your two mp4 source files. Are they using different sample rates (e.g. 44,100 Hz and 48,000 Hz)? Or are they using different bit rates (e.g. 128 kbps and 64 kbps)? In either such case, I don't quite understand how the command -c copy (a stream-copy instruction) would modify the source files to make them compatible. – Ed999 Apr 27 '17 at 11:11
  • 1
    @T.Todua Hi, the command works good when videos are without audio track. However, when the myfile1.mp4 is without audio and the myfile2.mp4 is with audio, the result output.mp4 is without audio. The expected output.mp4 should contains audio. How can i solve it? – AnswerZhao May 23 '17 at 9:47
  • @AnswerZhao I think you should exchange the order of filenames in the command.. instead of file1|file2, write file2|file1 – T.Todua Oct 31 '17 at 7:34

I was trying to concatenate three .mp3 audio files into one .m4a file and this ffmpeg command works.

Input command:

ffmpeg -i input1.mp3 -i input2.mp3 -i input3.mp3 -filter_complex concat=n=3:v=0:a=1 -f MOV -vn -y input.m4a

Meanings of : " -filter_complex concat=n=3:v=0:a=1" :

concat means use the media concatenate (joining) function.
n means confirm total count of input files.
v means has video? use 0 = no video, 1 = contains video.
a means has audio? use 0 = no audio, 1 = contain audio.
-f means force set file format (to see all supported formats, use ffmpeg -formats)
-vn means disable video (and also -an would disable audio if not wanted)
-y means overwrite output files (if the output file already exists).

For more info: use ffmpeg -h full print all options (including all format and codec specific options, very long)

  • f i use this -f concat -safe 0 -i "file.txt" -c copy -y "OutPut.mp4" it will concat but when some videos are with audio and some are without audio it is not working how can i sort out this. Thanks – – Ahmad Sep 5 '17 at 7:16
  • This works. Thanks for the detailed explanation in your answer. It's very helpful. – Joe T. Boka Jul 12 at 6:37

FOR MP4 FILES

For .mp4 files (which I obtained from DailyMotion.com: a 50 minute tv episode, downloadable only in three parts, as three .mp4 video files) the following was an effective solution for Windows 7, and does NOT involve re-encoding the files.

I renamed the files (as file1.mp4, file2.mp4, file3.mp4) such that the parts were in the correct order for viewing the complete tv episode.

Then I created a simple batch file (concat.bat), with the following contents:

:: Create File List
echo file file1.mp4 >  mylist.txt 
echo file file2.mp4 >> mylist.txt
echo file file3.mp4 >> mylist.txt

:: Concatenate Files
ffmpeg -f concat -i mylist.txt -c copy output.mp4

The batch file, and ffmpeg.exe, must both be put in the same folder as the .mp4 files to be joined. Then run the batch file. It will typically take less than ten seconds to run.

Detailed documentation on various ways of concatenation in ffmpeg can be found here.

You can use 'Concat filter' for quick concatenation.

It performs a re-encode. This option is best when inputs have different video/audio formats.

For Concatenating 2 files:

ffmpeg -i input1.mp4 -i input2.webm \
-filter_complex "[0:v:0] [0:a:0] [1:v:0] [1:a:0] concat=n=2:v=1:a=1 [v] [a]" \
-map "[v]" -map "[a]" output.mp4

For Concatenating 3 files:

ffmpeg -i input1.mp4 -i input2.webm -i input3.mp4 \
-filter_complex "[0:v:0] [0:a:0] [1:v:0] [1:a:0] [2:v:0] [2:a:0] concat=n=3:v=1:a=1 [v] [a]" \
-map "[v]" -map "[a]" output.mp4

This works for same as well as multiple input file types.

Here is a script I made to concatenate several GoPro mp4's into a 720p mp4. Hope it's of help.

#!/bin/sh
cmd="( "
for i; do
    cmd="${cmd}ffmpeg -i $i -ab 256000 -vb 10000000 -mbd rd -trellis 2 -cmp 2 -subcmp 2 -g 100 -f mpeg -; "
done
cmd="${cmd} ) | ffmpeg -i - -vb 10000000 -ab 256000 -s 1280x720 -y out-`date +%F-%H%M.%S`.mp4"
echo "${cmd}"
eval ${cmd}

based on rogerdpack's and Ed999's responses, I've created my .sh version

#!/bin/bash

[ -e list.txt ] && rm list.txt
for f in *.mp4
do
   echo "file $f" >> list.txt
done

ffmpeg -f concat -i list.txt -c copy joined-out.mp4 && rm list.txt

it joins all the *.mp4 files in current folder into joined-out.mp4

tested on mac.

resulting filesize is exact sum of my 60 tested files. Should not be any loss. Just what I needed

ffmpeg \
  -i input_1.mp4 \
  -i input_2.mp4 \
  -filter_complex '[0:v]pad=iw*2:ih[int];[int][1:v]overlay=W/2:0[vid]' \
  -map [vid] \
  -c:v libx264 \
  -crf 23 \
  -preset veryfast \
  output.mp4
  • 1
    Not just posting an answer, you could add little explanation which understand the solution better to OP and future readers as well. – Balagurunathan Marimuthu Aug 28 '17 at 9:19
  • 1
    This created a new silent video with both inputs playing as the same time next to each other. I expected concatenation would create a video where input_1.mp4 played and then input_2.mp4 – Alexx Roche Jan 29 at 0:27
  • 2
    This was the wrong answer entirely. This didn't concat the videos, it just plays them silently side-by-side, like @AlexxRoche had mentioned. – Kalob Taulien Feb 11 at 18:38

Merging all mp4 files from current directory

I personnaly like not creating external file that I have to delete afterwards, so my solution was following which includes files numbering listing (like file_1_name, file_2_name, file_10_name, file_20_name, file_100_name, ...)

#!/bin/bash
filesList=""
for file in $(ls -1v *.mp4);do #lists even numbered file
    filesList="${filesList}${file}|"
done
filesList=${filesList%?} # removes trailing pipe
ffmpeg -i "concat:$filesList" -c copy $(date +%Y%m%d_%H%M%S)_merged.mp4

this worked for me (on windows)

ffmpeg -i "concat:input1|input2" -codec copy output

in particular

ffmpeg -i "concat:01.mp4|02.mp4" -codec copy output.mp4

Python

Using some python code to do it with as many mp4 there are in a folder import glob import os

stringa = ""
for f in glob.glob("*.mp4"):
    stringa += f + "|"

os.system("ffmpeg -i \"concat:" + stringa + "\" -codec copy output.mp4")
  • 1
    The concat protocol should not be used with MP4 and will not work as mentioned in the accepted answer. – LordNeckbeard May 26 at 20:17
  • @LordNeckbeard I wonder if you know the answer to this ffmpeg question about concatenating 2 MP4 videos while specifying the output bitrate? video.stackexchange.com/q/24569/5657 Thanks. – Ryan Jul 27 at 17:52
  • @Ryan Got an answer now. I was too slow. – LordNeckbeard Jul 27 at 18:53
  • @LordNeckbeard My guess is that your answer would be the best one, still, if you're up for it! I'm not particularly satisfied with my own. – Ryan Jul 27 at 19:05
  • 1
    @Ryan Thanks for the vote of confidence, and maybe I'll take a closer look, but Gyan knows his stuff and I've been getting increasingly lazy, or maybe just less interested in Stack Exchange/FFmpeg/computers lately. Only 4 or so answers on SE in the last month... Maybe I'll get back into it during the dark season. – LordNeckbeard Jul 27 at 20:48

From the documentation here: https://trac.ffmpeg.org/wiki/Concatenate

If you have MP4 files, these could be losslessly concatenated by first transcoding them to MPEG-2 transport streams. With H.264 video and AAC audio, the following can be used:

ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate2.ts
ffmpeg -i "concat:intermediate1.ts|intermediate2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

This approach works on all platforms.

I needed the ability to encapsulate this in a cross platform script, so I used fluent-ffmpeg and came up with the following solution:

const unlink = path =>
  new Promise((resolve, reject) =>
    fs.unlink(path, err => (err ? reject(err) : resolve()))
  )

const createIntermediate = file =>
  new Promise((resolve, reject) => {
    const out = `${Math.random()
      .toString(13)
      .slice(2)}.ts`

    ffmpeg(file)
      .outputOptions('-c', 'copy', '-bsf:v', 'h264_mp4toannexb', '-f', 'mpegts')
      .output(out)
      .on('end', () => resolve(out))
      .on('error', reject)
      .run()
  })

const concat = async (files, output) => {
  const names = await Promise.all(files.map(createIntermediate))
  const namesString = names.join('|')

  await new Promise((resolve, reject) =>
    ffmpeg(`concat:${namesString}`)
      .outputOptions('-c', 'copy', '-bsf:a', 'aac_adtstoasc')
      .output(output)
      .on('end', resolve)
      .on('error', reject)
      .run()
  )

  names.map(unlink)
}

concat(['file1.mp4', 'file2.mp4', 'file3.mp4'], 'output.mp4').then(() =>
  console.log('done!')
)

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.