'ffprobe/ffmpeg reports different video duration when file given via stdin

I am trying to determine the duration of an MP4 video using ffmpeg, which is possible of course, except that when the data is streamed in via stdin (a requirement in my case) the duration is reported to be smaller than it actually is. I have the same problem with ffprobe.

The video's actual length is ~13 seconds.

Examples below of the output I receive using ffprobe.

Reading file from disk (correct duration):

$ ffprobe video.mp4
...
Duration: 00:00:13.05, start: 0.000000, bitrate: 736 kb/s
...

Streaming in the file (incorrect duration):

$ cat video.mp4 | ffprobe -i -
...
Duration: 00:00:08.40, start: 0.080000, bitrate: N/A
...

How can I get ffprobe to report the correct duration whilst also streaming in the file via stdin?



Solution 1:[1]

You can use ffprobe's -show_packets option, which will "Show information about each packet contained in the input multimedia stream". (Read about it in the ffprobe docs.)

With this option ffprobe will output an entry for each packet in the stream like so:

dts_time=13.008000

So we can grep the output for dts_time:

$ cat video.mp4 | ffprobe -i - -show_packets | grep dts_time
...
dts_time=13.008000
dts_time=13.029333

The last line of the output will contain the timestamp of the last packet, which can be taken as the duration of the video, so to get that we can do something like:

$ cat video.mp4 \
    | ffprobe -i - -show_packets -v quiet \
    | grep dts_time \
    | tail -n 1 \
    | awk -F"=" '{print $2}'
13.029333

Solution 2:[2]

Your input MP4s look to be fragmented, in which case, ffmpeg will stop probing after the first fragment moof box, and report its duration. This is not an issue with regular MP4s.

You can run cat fragmented.mp4 | ffmpeg -i - -c copy -f null - 2>&1 | grep -oP "(?<=time=)[\d:\.]+" for such files.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gyan