User Tools

Site Tools


ffmpeg:video:duration

ffmpeg - Video - Duration

Using Regex

# Use perl-regex.
ffmpeg -i "input.mkv" -c copy -f null /dev/null 2>&1 | tail -n 1 | grep -Po "(?<=time=)([0-9]{1,2}:[0-9]{2}:[0-9]{2})"
 
or
 
# Use extended-regex.
ffmpeg -i "input.mkv" -c copy -f null /dev/null 2>&1 | tail -n 1 | grep -oE "[0-9]{1}:[0-9]{2}:[0-9]{2}"
 
or
 
ffmpeg -i "input.mkv" -c copy -f null /dev/null 2>&1 | grep -oE "[0-9]{1}:[0-9]{2}:[0-9]{2}" | tail -n 1
 
or
 
ffmpeg -i "input.mkv" 2>&1 | grep -oE "[0-9]{1}:[0-9]{2}:[0-9]{2}" | head -n 1

NOTE: This gets the figures directly from ffmpeg.

  • This returns an estimate of the duration based on the bitrate and size of the file.

Getting the data from the video stream

ffprobe -v error -select_streams v:0 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1 "input.mkv"

NOTE: This often returns N/A for .mkv files.


Getting the data from the container

ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "input.mkv"
 
ffprobe -v error -select_streams v:0 -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "input.mkv"

WARNING: This returns the duration of the entire container, and not just the duration of the video.


By Packet duration_time

This method reads each video packet, individually, and totals up each packet size.

  • Sums up the duration_time of the -show_entries command.
video_pkt_durations=$(ffprobe -v error -select_streams v:0 -skip_frame nokey -show_entries packet=duration_time -of default=nokey=1:noprint_wrappers=1 "input.mkv")
 
sum_video_pkt_duration=0
precision=6
count_video_pkt_duration=0
 
#echo "Calculating video pkt_duration..."
for video_pkt_duration in $video_pkt_durations; do
  sum_video_pkt_duration=$(echo "${sum_video_pkt_duration} + ${video_pkt_duration}" | bc)
 
  (( count_video_pkt_duration++ ))
done;
 
video_duration=$( echo "scale=${precision}; ${sum_video_pkt_duration} " | bc)
 
echo "DURATION=${video_duration}"
echo "VIDEO FRAMES=${count_video_pkt_duration}"

NOTE: This is very accurate but may take a while.


Calculate duration using Size and Bitrate

duration=$( echo "scale=6; (${video_size} * 8) / ${bitrate}" | bc)

Calculate duration using Size and Bitrate

duration = NUMBER_OF_FRAMES / FPS

NOTE: Returns the duration in seconds.


ffmpeg/video/duration.txt · Last modified: 2025/05/27 18:34 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki