I have one file main.mp4
which I split into two mp4 files; first_half.mp4
and second_half.mp4
. Using ffmpeg I then merge three files one at the front: one at the middle of first_half.mp4
and second_half.mp4
, and one at the after second_half.mp4
In order to join the files I first convert them to .ts
format then join them using the concat protocol. The problem is that the quality becomes horrible and pixelated. After inspecting the split fragments I found out that their quality was okay and the quality only depreciated when I converted to .ts
.
How can i keep the quality of the ts files same as the original files?
I have also tried concat demuxer but it maintains quality but only works for first file as it ends up distorting subsequent files.
Here are my commands:
// cut first half
$cmd ="ffmpeg -i main.mp4 -vcodec copy -acodec copy -ss 00:00:00 -t 00:15:00 first_half.mp4 -y";
shell_exec($cmd);
//convert to ts
$cmd = "ffmpeg -i first_half.mp4 -vcodec copy -acodec copy -bsf:v h264_mp4toannexb -f mpegts in first_half.ts -y -b:v 1000000";
shell_exec($cmd);
//cut second half
$cmd ="ffmpeg -i main.mp4 -vcodec copy -acodec copy -ss 00:15:00 -t $length second_half.mp4 -y";
shell_exec($cmd);
//convert to ts
$cmd = "ffmpeg -i second_half.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts in second_half.ts -y -b:v 1000000";
shell_exec($cmd);
//transcode the "slices"
$cmd = "ffmpeg -i front.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts in front.ts -y -b:v 1000000";
shell_exec($cmd);
$cmd = "ffmpeg -i middle.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts in middle.ts -y -b:v 1000000";
shell_exec($cmd);
$cmd = "ffmpeg -i end.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts in end.ts -y -b:v 1000000";
shell_exec($cmd);
//concatenate them
$cmd = 'ffmpeg -i "concat:front.ts|first_half.ts|middle.ts|second_half.ts|end.ts" -c copy output.mp4 -y -b 10000000';
shell_exec($cmd);