trying to extract specific frames from a video with the following command (with specific names of files removed!:
ffmpeg -i video.mp4 -vf "select-gte(n\,6956)" -vframes 10262 folder/frame%d.jpg
However, in many cases, this results in the same frame (the first one) extracted repeatedly, rather than a progression of frames extracted.
The image sequence muxer, by default, is set to assume a constant frame rate output, so it will fill in missing timestamp gaps with duplicates.
The select filter does not reset timestamps, so, in your command, there's a "gap" from 0 to the timestamp of the first selected frame.
Use instead
ffmpeg -i video.mp4 -vf "select-gte(n\,6956)" -vsync 0 -vframes 10262 folder/frame%d.jpg
This changes video sync method to prevent frame duplication.
Related
I want to extract specific frames from a video and save them on an external disk with ffmpeg with the timestamp of the video as the output name, preferably with milliseconds so that I can acquire more frames per second.
As a first approach I tried to extract the frames to the external disk with the following code, where I intend to extract 1 frame per second from a specific time interval and saving them as a sequence of images.
ffmpeg -ss 00:12:25 -to 00:12:35 -i 220718-124513_CAM0bc99448_30.mp4 -r 1 E:/images/img_%04d.png
Once I tried a different time interval, it began overwriting the images I had on the disk, because the sequence restarted, and the purpose of this is that I want to retrieve as many images as possible.
Then I tried the following code
ffmpeg -ss 00:00:00 -to 00:00:04 -i 220718-124513_CAM0bc99448_30.mp4 -vframes 1 -f image2 -strftime 1 E:/images/"img_%Y-%m-%d_%H-%M-%S.png"
thinking that it would give me the timestamp of the video but it saved the images with the local time, which solves the problem I was having, but I would like to specify the timestamp that those frames correspond on the video, preferably with milliseconds included, so that I can acquire even more frames per second (doing it this way, if I want 2 frames per second, it will save as one image only because the output names only cover seconds).
Finally I tried this code:
ffmpeg -ss 00:00:00 -to 00:00:04 -i 220718-124513_CAM0bc99448_30.mp4 -copyts -f image2 -frame_pts true -r 2 E:/images/img_%04d.png
and it supposedly solves the issue, and if there is no solution for the problem I mentioned, this will be the way I will implement this.
This is the first time I am posting on stack overflow, so if there is something missing on my question, please tell me and I will change.
Thanks in advance!
I am making a datamoshing program in C++, and I need to find a way to remove one frame from a video (specifically, the p-frame right after a sequence jump) without re-encoding the video. I am currently using h.264 but would like to be able to do this with VP9 and AV1 as well.
I have one way of going about it, but it doesn't work for one frustrating reason (mentioned later). I can turn the original video into two intermediate videos - one with just the i-frame before the sequence jump, and one with the p-frame that was two frames later. I then create a concat.txt file with the following contents:
file video.mkv
file video1.mkv
And run ffmpeg -y -f concat -i concat.txt -c copy output.mp4. This produces the expected output, although is of course not as efficient as I would like since it requires creating intermediate files and reading the .txt file from disk (performance is very important in this project).
But worse yet, I couldn't generate the intermediate videos with ffmpeg, I had to use avidemux. I tried all sorts of variations on ffmpeg -y -ss 00:00:00 -i video.mp4 -t 0.04 -codec copy video.mkv, but that command seems to really bug out with videos of length 1-2 frames - while it works for longer videos no problem. My best guess is that there is some internal checker to ensure the output video is not corrupt (which, unfortunately, is exactly what I want it to be!).
Maybe there's a way to do it this way that gets around that problem, or better yet, a more elegant solution to the problem in the first place.
Thanks!
If you know the PTS or data offset or packet index of the target frame, then you can use the noise bitstream filter. This is codec-agnostic.
ffmpeg -copyts -i input -c copy -enc_time_base -1 -bsf:v:0 noise=drop=eq(pos\,11291) out
This will drop the packet from the first video stream stored at offset 11291 in the input file. See other available variables at http://www.ffmpeg.org/ffmpeg-bitstream-filters.html#noise
I'm encoding videos by scenes. At this moment I got two solutions in order to do so. The first one is using a Python application which gives me a list of frames that represent scenes. Like this:
285
378
553
1145
...
The first scene begins from the frame 1 to 285, the second from 285 to 378 and so on. So, I made a bash script which encodes all this scenes. Basically what it does is to take the current and previous frames, then convert them to time and finally run the ffmpeg command:
begin=$(awk 'BEGIN{ print "'$previous'"/"'24'" }')
end=$(awk 'BEGIN{ print "'$current'"/"'24'" }')
time=$(awk 'BEGIN{ print "'$end'"-"'$begin'" }')
ffmpeg -i $video -r 24 -c:v libx265 -f mp4 -c:a aac -strict experimental -b:v 1.5M -ss $begin -t $time "output$count.mp4" -nostdin
This works perfect. The second method is using ffmpeg itself. I run this commands and gives me a list of times. Like this:
15.75
23.0417
56.0833
71.2917
...
Again I made a bash script that encodes all these times. In this case I don't have to convert to times because what I got are times:
time=$(awk 'BEGIN{ print "'$current'"-"'$previous'" }')
ffmpeg -i $video -r 24 -c:v libx265 -f mp4 -c:a aac -strict experimental -b:v 1.5M -ss $previous -t $time "output$count.mp4" -nostdin
After all this explained it comes the problem. Once all the scenes are encoded I need to concat them and for that what I do is to create a list with the video names and then run the ffmpeg command.
list.txt
file 'output1.mp4'
file 'output2.mp4'
file 'output3.mp4'
file 'output4.mp4'
command:
ffmpeg -f concat -i list.txt -c copy big_buck_bunny.mp4
The problem is that the "concated" video is longer than the original by 2.11 seconds. The original one lasts 596.45 seconds and the encoded lasts 598.56. I added up every video duration and I got 598.56. So, I think the problem is in the encoding process. Both videos have the same frames number. My goal is to get metrics about the encoding process, when I run VQMT to get the PSNR and SSIM I get weird results, I think is for this problem.
By the way, I'm using the big_buck_bunny video.
The probable difference is due to the copy codec. In the latter case, you tell ffmpeg to copy the segments, but it can't do that based on your input times.
It has to find first the previous I frames (a frame that can be decoded without any reference to any previous frame) and starts from here.
To get what you need, you need to either re-encode the video (like you did in the 2 former examples) or change the times to stop at I frames.
To assert I getting your issue correctly:
You have a source video (that's encoded at variable frame rate, close to 18fps)
You want to split the source video via ffmpeg, by forcing the frame rate to 24 fps.
Then you want to concat each segment.
I think the issue is mainly that you have some discrepancy in the timing (if I divide the frame index by the time you've given, I getting between 16fps to 18fps). When you are converting them in step 2, the output video segment time will be 24fps. ffmpeg does not resample in the time axis, so if you force a video rate, the video will accelerate or slow down.
There is also the issue of consistency for the stream:
Typically, a video stream must start with a I frame, so when splitting, FFMPEG has to locate the previous I frame (when using copy codec, and this changes the duration of the segment).
When you are concatenating, you could also have the issue of consistency (that is, if the segment you are concatenating does end with a I frame, and the next one starts with a I frame, it's possible FFMPEG drops either one, although I don't remember what is the current behavior now)
So, to solve your issue, if I were you, I would avoid step 2 (it's bad for quality anyway). That is, I would use ffmpeg to split the segments of interest based on the frame number (that's the only value that's not approximate in your scheme) in png or ppm frames (or to a pipe if you don't care about keeping them) and then concat all the frames by encoding them at the last step with the expected rate set to totalVideoTime / totalFrameCount.
You'll get a smaller and higher quality final video.
If you can't do what I said for whatever reason, at least for the concat input, you should use the ffconcat format:
ffconcat version 1.0
file segment1
duration 12.2
file segment2
duration 10.3
This will give you the expected duration by cutting each segment if it's longer
For selecting by frame number (instead of time as time is hard to get right on variable frame rate video), you should use the select filter like this:
-vf select=“between(n\,start_frame_num\,end_frame_num),setpts=STARTPTS"
I suggest checking the input and output frame rate and make sure they match. That could be a source of the discrepancy.
Is there any way to detect duplicate frames within the video using ffmpeg?
I tried -vf flag with select=gt(scene\,0.xxx) for scene change. But, it did not work for my case.
Use the mpdecimate filter, whose purpose is to "Drop frames that do not differ greatly from the previous frame in order to reduce frame rate."
This will generate a console readout showing which frames the filter thinks are duplicates.
ffmpeg -i input.mp4 -vf mpdecimate -loglevel debug -f null -
To generate a video with the duplicates removed
ffmpeg -i input.mp4 -vf mpdecimate,setpts=N/FRAME_RATE/TB out.mp4
The setpts filter expression generates smooth timestamps for a video at FRAME_RATE FPS. See an explanation for timestamps at What is video timescale, timebase, or timestamp in ffmpeg?
I also had this problem and Gyan's excellent answer above got me started but the result of it was desynchronized audio so I had to explore more options:
mpdecimate vs decimate filters
mpdecimate is the standard recommendation I found all over SO and the internet, but I don't think it should be the first pick
it uses heuristics so it may and will skip some duplicate frames
you can tweak the detection with frac parameter, but that's extra work you may want to avoid if you can
it is not really supposed to work with mp4 container (source), but I was using mkv so this limitation didn't apply on my case, but good to be aware of it
decimate removes frames precisely, but it is useful only for periodically occurring duplicates
detected vs actual frame rate
so you have multimedia file with duplicate frames, it is good idea to make sure that the detected frame rate matches the actual one
ffprobe in.mkv will output the detected FPS; it may look like this
Stream #0:0: Video: h264 (Main), yuvj420p(pc, bt709, progressive), 1920x1080, SAR 1:1 DAR 16:9, 25 fps, 25 tbr, 1k tbn, 50 tbc (default)
the actual frame rate can be found out if you open the media in.mkv in a media player that lets you step one frame at the time; then count the steps needed to advance the playback time for 1 second, in my case it was 30 fps
not a big surprise for me, because every 6th frame was duplicate (5 good frames and 1 duplicate), so after 25 good frames there was also 5 duplicates
what is N/FRAME_RATE/TB
except the use of FRAME_RATE variable the N/FRAME_RATE/TB is equal to the example below from ffmpeg documentation (source)
Set fixed rate of 25 frames per second:
setpts=N/(25*TB)
the math behind it perfectly explained in What is video timescale, timebase, or timestamp in ffmpeg?
it basically calculates timestamp for each frame and multiplies it with timebase TB to enhance precision
FRAME_RATE variable vs literal FPS value (e.g. 25)
this is why it is important to know your detected and actual FPS
if the detected FPS matches your actual FPS (e.g. both are 30 fps) you can happily use FRAME_RATE variable in N/FRAME_RATE/TB
but if the detected FPS differs than you have to calculate the FRAME_RATE on your own
in my case my actual FPS was 30 frames per second and I removed every 6th frame, so the target FPS is 25 which leads to N/25/TB
if I used FRAME_RATE (and I actually tried that) it would take the wrong detected fps of 25 frames i.e. FRAME_RATE=25, run it through mpdecimate filter which would remove every 6th frame and it would update to FRAME_RATE=20.833 so N/FRAME_RATE/TB would actually be N/20.833/TB which is completely wrong
to use or not to use setpts
so the setpts filter already got pretty complicated especially because of the FPS mess that duplicate frames may create
the good news is you actually may not need the setpts filter at all
here is what I used with good results
ffmpeg -i in.mkv -vf mpdecimate out.mkv
ffmpeg -i in.mkv -vf decimate=cycle=6,setpts=N/25/TB out.mkv
but the following gave me desynchronized audio
ffmpeg -i in.mkv -vf mpdecimate,setpts=N/FRAME_RATE/TB out.mkv
ffmpeg -i in.mkv -vf mpdecimate,setpts=N/25/TB out.mkv
ffmpeg -i in.mkv -vf decimate=cycle=6 out.mkv
as you see
mpdecimate and decimate does not work the same way
mpdecimate worked better for me without setpts filter
while decimate needed setpts filter and furthermore I need to avoid FRAME_RATE variable and use N/25/TB instead because the actual FPS was not detected properly
note on asetpts
it does the same job as setpts does but for audio
it didn't really fix desync audio for me but you want to use it something like this -af asetpts=N/SAMPLE_RATE/TB
maybe you are supposed to adjust the SAMPLE_RATE according to the ratio of duplicate frames removed, but it seems to me like extra unnecessary work especially when my video had the audio in sync at the beginning, so it is better to use commands that will keep it that way instead of fixing it later
tl;dr
If the usually recommended command ffmpeg -i in.mkv -vf mpdecimate,setpts=N/FRAME_RATE/TB out.mkv does not work for you try this:
ffmpeg -i in.mkv -vf mpdecimate out.mkv
or
ffmpeg -i in.mkv -vf decimate=cycle=6,setpts=N/25/TB out.mkv
(cycle=6 because every 6th frame is duplicate and N/25/TB because after removing the duplicates the video will have 25 fps (avoid the FRAME_RATE variable); adjust for your use case)
I tried the solution here and none of them seem to work when you need to trim the video and keep the audio. There is a mpdecimate_trim repo that does a good job. It basically list all the frames to be dropped (using mpdecimate) and then creates a complex filter to trim all those frames (and the corresponding audio) from the video by splitting the video and only including the portion without duplicate frames.
I did have to tweak a few options in the code though. For instance, in mpdecimate_trim.py, I had to change this line:
dframes2 = get_dframes(ffmpeg(True, "-vf", "mpdecimate=hi=576", "-loglevel", "debug", "-f", "null", "-").stderr)
I had to detect duplicates a bit more aggressively, so I changed the mpdecimate option to mpdecimate=hi=64*32:lo=64*24:frac=0.05
If your getting duplicate frozen frames after cropping you could be entering your cmd line incorrectly. I was entering the orders of parameters incorrectly causing the first few seconds of my video to freeze. Here is the fix if that is the case. Hopefully this helps you avoid getting frozen frames altogether.
ffmpeg -ss {start_time} -i {input_path} -vcodec copy -acodec copy -to {end_time} {output_path}
My goal is to split a XDCAM or a H264 video, frame-accurately, with ffmpeg.
I guess that the problem comes from its long GOP structure, but I'm looking for a way to split the video without re-encoding it.
I apply an offset to encode only a specific section of the video (let say from the 10th second to the end of the media)
Any ideas ?
Please refer to the ffmpeg documentation.
You will find an option -frames. That option can be use to specify for a given input stream (in the following the stream 0:0 is the 1st input file, first video stream) the number of frame to record. That option can be combined with other options to start somewhere in the input file (time offset, etc ....)
ffmpeg -i intput.ts -frames:0:0 100 -vcodec copy test.ts
that command demux and remux only the first 100 frame of the video (no re-encoding).
as said you can combine it with a jump. Using ' ‘-ss offset (input)’
' you can specify a "Frame Accurate" position ie. frame 14 after 1min10seconds = 0:1:10:14. that option should be use before the input like below.
ffmpeg -ss 00:00:10.0 -i intput.ts -frames:0:0 100 -vcodec copy test.ts
ffmpeg discard the first 10 second and bypass 100 frame to the muxer.
I`m not sure if it possible to do by 1 pass with ffmpeg, but 2-3
1st pass: you just dump raw frames to file
2nd pass: you find closed gop(mxdcam)/idr frame (h264) with index <= index of frame you want to start
in case indexes equal you can start mux. otherwise you need to decode sequense from closed gop/idr frame to next closed gop/idr frame and encode starting frame you want