How to remove a few seconds from .mp4 file using ffmpeg?

How to remove a few seconds from .mp4 file using ffmpeg? I have test.mp4 file and I want to remove 10s from 11:00 to 11:10


Solution 1:

Fast but possibly not accurate

This avoids re-encoding, but you can only cut on key frames, so it may not choose the duration you want.

  1. Create segments:

    ffmpeg  -t 00:11:00 -i input.mp4 -map 0 -c copy segment1.mp4
    ffmpeg -ss 00:11:10 -i input.mp4 -map 0 -c copy segment2.mp4
    
  2. Create input.txt:

    file 'segment1.mp4'
    file 'segment2.mp4'
    
  3. Concatenate with the concat demuxer:

    ffmpeg -f concat -i input.txt -map 0 -c copy output.mp4
    

Slow but accurate

You can try to do this without re-encoding, but since you can only cut on keyframes it will possibly not align with your desired cut times, so if you need accuracy you'll need to re-encode:

ffmpeg -i input.mp4 -filter_complex \
  "[0:v]trim=end=660,setpts=N/FRAME_RATE/TB[v0]; \
   [0:a]atrim=end=660,asetpts=N/SR/TB[a0]; \
   [0:v]trim=start=670,setpts=N/FRAME_RATE/TB[v1]; \
   [0:a]atrim=start=670,asetpts=N/SR/TB[a1]; \
   [v0][a0][v1][a1]concat=n=2:v=1:a=1[v][a]" \
  -map "[v]" -map "[a]" output.mp4
  • (a)trim will allow you to choose your clips.
  • (a)setpts resets timestamps.
  • concat concatenates the clips.

See FFmpeg Filter Documentation for details on each filter.

Solution 2:

I think u have to cut the video to 2 parts then merge them together. first 'time-value' is starting point, second 'time-value' is length of video u want to cut. In eg below first cut starts at 00:00:00 and length is 11 minutes, second cut starts at 11 mins 10 sec, and length is 10 mins.

cutting:

ffmpeg -i test.mp4 -ss 00:00:00 -t 00:11:00 -acodec copy -vcodec copy test1.mp4

ffmpeg -i test.mp4 -ss 00:11:10 -t 00:10:00 -acodec copy -vcodec copy test2.mp4

merge:

cat test1.mp4 test2.mp4 >> test3.mp4

I haven't tried it, let me know if it works.

Solution 3:

I used the knowledge here to create a shell script.

Save it to a file with a name and .sh extension such as video-cutter.sh Use chmod +x video-cutter.sh to allow it for execution.

paste the content above on the file an save it

#!/bin/bash

echo 'Input file:' $1
echo 'Output file:' $2
echo 'Start time of segment' $3
echo 'End time of segment' $4

ffmpeg -t $3 -i $1 -map 0 -c copy segment1.mp4

ffmpeg -ss $4 -i $1 -map 0 -c copy segment2.mp4

echo "file 'segment1.mp4'" >> input.txt
echo "file 'segment2.mp4'" >> input.txt 

ffmpeg -f concat -i input.txt -map 0 -c copy $2

echo 'Finished. Saved at ' $2

rm input.txt
rm segment1.mp4
rm segment2.mp4

to execute it run ./video-cutter.sh test.mp4 test-without-segment.mp4 startTime endTime

example: ./video-cutter.sh originalfile.mp4 outputfile.mp4 00:11:00 00:11:10