Skip to content

Instantly share code, notes, and snippets.

@mekya
Created November 21, 2018 13:42
Show Gist options
  • Save mekya/e9e210e7c0ed85332d3664b58c7e2127 to your computer and use it in GitHub Desktop.
Save mekya/e9e210e7c0ed85332d3664b58c7e2127 to your computer and use it in GitHub Desktop.
Concatenate mp4 files.
#!/bin/bash
# concatenate second file to end of first file
# first file 1.mp4 duration: 10sec
# second file 2.mp4 duration: 20sec
# output file 1.mp4 duration: 30sec
concatenate_files()
{
file1=$1
file2=$2
outputFile=$1_out_tmp.mp4
temp1=$1_temp.ts
temp2=$2_temp.ts
ffmpeg -y -i $file1 -c copy -bsf:v h264_mp4toannexb -f mpegts $temp1
ffmpeg -y -i $file2 -c copy -bsf:v h264_mp4toannexb -f mpegts $temp2
ffmpeg -f mpegts -i "concat:$temp1|$temp2" -c copy -bsf:a aac_adtstoasc $outputFile
#replace outputFile to first file
mv $outputFile $file1
#delete second file and fifos
rm $2 $temp1 $temp2
}
# get the file name
filename=$(basename "$1")
dirname=$(dirname "$1")
#find the position of suffix,suffix of stream1_720p_1.mp4 is _1.mp4. original file stream1_720p.mp4
position=`echo $filename | grep -b -o -E "_{1}[0-9]+\.mp4$" | awk 'BEGIN {FS=":"}{print $1}'`
echo $position
if [ ! -z $position ]
then
echo "matched"
echo ${filename:0:$position}
endPosition=`echo $filename | grep -b -o -E "\.mp4$" | awk 'BEGIN {FS=":"}{print $1}'`
startPosition=`expr $position + 1`
length=`expr $endPosition - $startPosition`
streamIndex=${filename:$startPosition:$length}
originalFilename=$dirname/${filename:0:$position}.mp4
echo "original file name $originalFilename"
if [ ! -f $originalFilename ]
then
echo "Original file($originalFilename) does not exist"
exit 1
fi
#loop down to 1 to concat files and delete file if it's finished
concatenate_files $originalFilename $1
# for (( i=1; i<=$streamIndex; i++ ))
# do
# echo "stream index $i"
# done
else
echo "not matched"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment