puneet18
puneet18

Reputation: 4427

How to trim video by multiple frame numbers then concatenate using FFMPEG

Using following code, I'm able to trim video by time:

ffmpeg -i input.mp4 -filter_complex \
"[0:v]trim=60:65,setpts=PTS-STARTPTS[v0]; \
 [0:a]atrim=60:65,asetpts=PTS-STARTPTS[a0]; \
 [0:v]trim=120:125,setpts=PTS-STARTPTS[v1];
 [0:a]atrim=120:125,asetpts=PTS-STARTPTS[a1]; \
 [v0][a0][v1][a1]concat=n=2:v=1:a=1[out]" \
-map "[out]" output.mp4

Above code trim video from 60-65 sec & 120-125sec then concatenate in output.mp4 file.

Need to know how to trim video by using frame number and concatenate.


Is it possible to get the time by using Frame Number and fps?

frame_1_start = 100 #Frame Number
frame_1_end   = 200 #Frame Number
frame_2_start = 450 #Frame Number
frame_3_end   = 700 #Frame Number
fps = 20 # Frame per second

time_x_1 = frame_1_start/fps
time_x_2 = frame_1_end/fps
time_y_1 = frame_2_start/fps
time_y_2 = frame_2_end/fps

ffmpeg -i input.mp4 -filter_complex \
"[0:v]trim=#{time_x_1}:#{time_x_2},setpts=PTS-STARTPTS[v0]; \
 [0:a]atrim=#{time_x_1}:#{time_x_2},asetpts=PTS-STARTPTS[a0]; \
 [0:v]trim=#{time_y_1}:#{time_y_2},setpts=PTS-STARTPTS[v1];
 [0:a]atrim=#{time_y_1}:#{time_y_2},asetpts=PTS-STARTPTS[a1]; \
 [v0][a0][v1][a1]concat=n=2:v=1:a=1[out]" \
-map "[out]" output.mp4

Upvotes: 0

Views: 2956

Answers (1)

llogan
llogan

Reputation: 133863

As shown in the trim filter documentation use the start_frame and end_frame options.

Video only

ffmpeg -i input.mp4 -filter_complex \
"[0:v]trim=start_frame=25:end_frame=100,setpts=PTS-STARTPTS[v0]; \
 [0:v]trim=start_frame=200:end_frame=300,setpts=PTS-STARTPTS[v1];
 [v0][v1]concat=n=2:v=1:a=0[v]" \
-map "[v]" output.mp4

Video & audio

ffmpeg -i input.mp4 -filter_complex \
"[0:v]trim=start_frame=25:end_frame=100,setpts=PTS-STARTPTS[v0]; \
 [0:a]atrim=1:4,asetpts=PTS-STARTPTS[a0]; \
 [0:v]trim=start_frame=200:end_frame=300,setpts=PTS-STARTPTS[v1];
 [0:a]atrim=8:12,asetpts=PTS-STARTPTS[a1]; \
 [v0][a0][v1][a1]concat=n=2:v=1:a=1[v][a]" \
-map "[v]" -map "[a]" output.mp4

For atrim you can use timestamps as in your original command, or use start_sample and end_sample if you prefer to use audio samples instead. atrim does not have start_frame and end_frame.

For example, if frame rate is 25, and you want trim to include frames 25-100, then atrim would use atrim=1:4.

You can use ffprobe to get frame rate and to check if an input has audio.

Upvotes: 2

Related Questions