Does anyone know how to fetch the number of total frames from a video file using ffmpeg? The render output of ffmpeg shows the current frame and I need the frame count to calculate the progress in percent.
解决方案
Note: The presence of an edit list in MP4/M4V/M4A/MOV can affect your frame number. See Edit lists below.
ffprobe: Query the container
ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 input.mp4
This is a fast method.
Not all formats (such as Matroska) will report the number of frames resulting in the output of N/A. See the other methods listed below.
ffprobe: Count the number of frames
ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 input.mkv
This is a slow method.
Add the -skip_frame nokey option to only count key frames.
ffmpeg: Count the number of frames
If you do not have ffprobe you can use ffmpeg instead:
ffmpeg -i input.mkv -map 0:v:0 -c copy -f null -
This is a somewhat fast method.
Refer to frame= near the end of the console output.
Add the -discard nokey input option (before -i) to only count key frames.
Edit lists
Ignore the MP4/M4V/M4A/MOV edit list with the -ignore_editlist 1 input option. Default is to not ignore the edit list.
What the ffprobe options mean
-v error This hides "info" output (version info, etc) which makes parsing easier.
-count_frames Count the number of frames per stream and report it in the corresponding stream section.
-select_streams v:0 Select only the video stream.
-show_entries stream=nb_frames or -show_entries stream=nb_read_frames Show only the entry for nb_frames or nb_read_frames.
-of default=nokey=1:noprint_wrappers=1 Set output format (aka the "writer") to default, do not print the key of each field (nokey=1), and do not print the section header and footer (noprint_wrappers=1). There are shorter alternatives such as -of csv=p=0.
Also see
mediainfo
The well known mediainfo tool can output the number of frames:
mediainfo --Output="Video;%FrameCount%" input.avi
MP4Box
For MP4/M4V/M4A files.
MP4Box from gpac can show the number of frames:
MP4Box -info input.mp4
Refer to the Media Info line in the output for the video stream in question:
Media Info: Language "Undetermined (und)" - Type "vide:avc1" - 2525 samples
In this example the video stream has 2525 frames.
boxdumper
For MP4/M4V/M4A/MOV files.
boxdumper is a simple tool from l-smash. It will output a large amount of information. Under the stsz sample size box section refer to sample_count for the number of frames. In this example the input has 1900 video frames:
boxdumper input.mp4
...
[stsz: Sample Size Box]
position = 342641
size = 7620
version = 0
flags = 0x000000
sample_size = 0 (variable)
sample_count = 1900
Be aware that a file may have more than one stsz atom.