Pratik
Pratik

Reputation: 1

How to get duration of H265 video file

My device is recording video in H265 format. I want to find out duration of recorded video file using command or C code. But I didn't get any command to get duration for H265 video format.

I have seen ffmpeg and ffprobe tool to get duration for mp4 file. Is there any command or way to get H265 video file duration?

Upvotes: 0

Views: 661

Answers (1)

Rotem
Rotem

Reputation: 32084

In case the frame rate is constant, we may count the frames using FFprobe, and scale by the duration of the first frame.

If the video has a variable frame rate, we may use FFprobe for getting the duration of all video packets, and sum the total duration.


Start by creating a small sample file in raw H.265 format (for testing):

ffmpeg -y -f lavfi -i testsrc=size=192x108:rate=1:duration=100 -vcodec libx265 in.265

We may list the packets duration into a text file:

ffprobe -v error -select_streams v:0 -show_packets -show_entries packet=duration_time -of default=noprint_wrappers=1:nokey=1 in.mp4 > durations.txt

The output is:

1.000000 
1.000000  
1.000000  
1.000000 
…

Summing the list using C code is not too difficult...


Here is a Python implementation for summing the total duration of all video packets:

import subprocess as sp
import json

in_file_name = 'in.mp4'  # Input file name

# Use FFprobe for getting the packets durations of all video frames.
# ffprobe -select_streams v:0 -show_packets -show_entries packet=duration_time -of json in.mp4
data = sp.run(['ffprobe', '-select_streams', 'v:0', '-show_packets', '-show_entries', 'packet=duration_time', '-of', 'json', in_file_name], stdout=sp.PIPE).stdout

dict = json.loads(data)  # Convert from JSON (string) to dictionary 
durations_dict = dict['packets']  # Get 'packets' out of the dictionary (the result is a list of dictionaries).

# Iterate the list of durations and sum all packet durations:
total_duration = 0
for d in durations_dict:
    total_duration += float(d['duration_time'])  # Convert from string to float

print(f'total_duration = {total_duration}')  # total_duration = 100.0

The Python code uses JSON format, and reads FFprobe output through stdout pipe.

Upvotes: 1

Related Questions