DEV Community

Peiguan
Peiguan

Posted on

Is This "15-Second" Hit the Road Dude Clip Actually 15.000 Seconds? Container vs Stream Duration vs Frame Count

The FAQ is blunt: every clip is 15 seconds, vertical 9:16, at 480p or 720p, with sound. That is the product. It is not a length slider, and this is not a note about why the studio ships one length. It is a question about the file you are holding after an edit: do three common clocks — container duration, stream duration, and frame-count divided by fps — actually agree on 15.000 seconds?

They often don't. One missing frame at 30 fps is 1/30 s, or 0.033333 s. An edit list can make the container longer than the video stream. A 30000/1001 "30 fps" file can be a clean 15.015 s of picture with 15.000 s of audio. I measured all of that on synthetic 9:16 clips built with ffmpeg 7.1.5. No paid customer renders are used.

The test files

Six stand-ins: a clean 450-frame file at 30 fps (exactly 15.000 s of picture), one frame short, one frame long, a 15-second request at 30000/1001, a clean pre-trim original, and a stream-copy trim that is not on a keyframe.

The maker is make_duration_test_clips.py (published next to this post). It writes a 450-frame 30 fps file, a 449-frame file, a 451-frame file, a 15-second request at 30000/1001, a clean pre-trim original, and a stream-copy trim.

$ python3 make_duration_test_clips.py
wrote exact_15.mp4, frames_449.mp4, frames_451.mp4, ntsc_15.mp4, pre_trim.mp4, trim_elst.mp4
Enter fullscreen mode Exit fullscreen mode

The checker

The script asks ffprobe for container duration, each stream's duration and start time, and a counted frame total. It also parses elst and reports empty_edit entries. Segment duration in an edit list is in the movie timescale (mvhd), not the media timescale (mdhd). Mixing those up shrinks every number by about 15× on these files.

#!/usr/bin/env python3
"""Compare container duration, stream duration, and frame-count/fps on an MP4.

Also lists edit-list entries (elst), including empty_edit, so you can see
why the three clocks disagree. This is a duration report, not a fix tool
(see the companion edit-list guide for remux vs filter repairs).
"""
from __future__ import annotations

import argparse, json, struct, subprocess
from pathlib import Path


def u32(b, i): return struct.unpack(">I", b[i:i+4])[0]
def s32(b, i): return struct.unpack(">i", b[i:i+4])[0]
def u64(b, i): return struct.unpack(">Q", b[i:i+8])[0]
def s64(b, i): return struct.unpack(">q", b[i:i+8])[0]


def boxes(data, start=0, end=None):
    if end is None:
        end = len(data)
    i = start
    while i + 8 <= end:
        size = u32(data, i)
        typ, hdr = data[i+4:i+8], 8
        if size == 1:
            if i + 16 > end:
                break
            size, hdr = u64(data, i+8), 16
        elif size == 0:
            size = end - i
        if size < hdr or i + size > end:
            break
        yield typ, i, size, hdr, data[i+hdr:i+size]
        i += size


def walk(data, start, end):
    for typ, pos, size, hdr, payload in boxes(data, start, end):
        yield typ, payload
        if typ in {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts"}:
            yield from walk(data, pos+hdr, pos+size)


def mvhd_timescale(data):
    for typ, pos, size, hdr, payload in boxes(data):
        if typ != b"moov":
            continue
        for ttyp, _, _, _, pay in boxes(data, pos+hdr, pos+size):
            if ttyp == b"mvhd" and len(pay) >= 20:
                return u32(pay, 20 if pay[0] == 1 else 12)
    return 0


def parse_elst(payload, timescale):
    if len(payload) < 8:
        return []
    version, n, i, out = payload[0], u32(payload, 4), 8, []
    for _ in range(n):
        if version == 1:
            if i + 20 > len(payload):
                break
            seg, mt, rate, i = u64(payload, i), s64(payload, i+8), u32(payload, i+16), i+20
        else:
            if i + 12 > len(payload):
                break
            seg, mt, rate, i = u32(payload, i), s32(payload, i+4), u32(payload, i+8), i+12
        out.append({
            "segment_duration_s": (seg / timescale) if timescale else None,
            "media_time": mt,
            "empty_edit": mt == -1,
        })
    return out


def edit_lists(path: Path):
    data = path.read_bytes()
    movie_ts, results = mvhd_timescale(data), []
    for typ, pos, size, hdr, _ in boxes(data):
        if typ != b"moov":
            continue
        for ttyp, tpos, tsize, thdr, _ in boxes(data, pos+hdr, pos+size):
            if ttyp != b"trak":
                continue
            handler, media_ts, elst = "unknown", 0, None
            for typ2, pay2 in walk(data, tpos+thdr, tpos+tsize):
                if typ2 == b"hdlr" and len(pay2) >= 12:
                    handler = pay2[8:12].decode("latin1", "replace")
                elif typ2 == b"mdhd" and len(pay2) >= 16:
                    media_ts = u32(pay2, 16 if pay2[0] == 1 else 12)
                elif typ2 == b"elst":
                    elst = pay2
            ts = movie_ts or media_ts
            results.append({
                "handler": handler,
                "timescale": ts,
                "entries": parse_elst(elst, ts) if elst is not None else [],
            })
    return results


def ffprobe(path: Path) -> dict:
    cmd = ["ffprobe", "-v", "error", "-show_format", "-show_streams",
           "-count_frames", "-of", "json", str(path)]
    return json.loads(subprocess.check_output(cmd, text=True))


def fnum(v):
    try:
        return float(v)
    except (TypeError, ValueError):
        return None


def fps_of(stream):
    for key in ("avg_frame_rate", "r_frame_rate"):
        raw = stream.get(key) or "0/0"
        if "/" in raw:
            a, b = raw.split("/", 1)
            try:
                if float(b):
                    return float(a) / float(b)
            except ValueError:
                continue
    return None


def report(path: Path) -> int:
    info = ffprobe(path)
    fmt, streams = info.get("format") or {}, info.get("streams") or []
    video = next((s for s in streams if s.get("codec_type") == "video"), None)
    audio = next((s for s in streams if s.get("codec_type") == "audio"), None)
    print(f"file: {path.name}  ({path.stat().st_size} bytes, {fmt.get('format_name')})")
    cdur = fnum(fmt.get("duration"))
    print(f"container duration: {cdur:.6f} s" if cdur is not None else "container duration: n/a")
    clocks = {"container": cdur}

    def frames_of(st):
        n = st.get("nb_read_frames") or st.get("nb_frames")
        try:
            return int(n) if n not in (None, "N/A") else None
        except ValueError:
            return None

    if video:
        dur, start = fnum(video.get("duration")), fnum(video.get("start_time")) or 0.0
        end, fps, n = (start + dur) if dur is not None else None, fps_of(video), frames_of(video)
        extra = ""
        if n and fps:
            clocks["frame_count/fps"] = n / fps
            extra = f"  frames={n} fps={video.get('avg_frame_rate')} frame_count/fps={n/fps:.6f} s"
        print(
            f"video: {video.get('codec_name')} {video.get('width')}x{video.get('height')} "
            f"duration={dur:.6f} s start={start:.6f}s end={(end or 0):.6f}s{extra}"
        )
        clocks.update(video_stream=dur, video_start=start, video_end=end)
    else:
        print("video: none")
    if audio:
        dur, start = fnum(audio.get("duration")), fnum(audio.get("start_time")) or 0.0
        end = (start + dur) if dur is not None else None
        print(
            f"audio: {audio.get('codec_name')} {audio.get('sample_rate')}Hz {audio.get('channels')}ch "
            f"duration={dur:.6f} s start={start:.6f}s end={(end or 0):.6f}s"
        )
        clocks.update(audio_stream=dur, audio_start=start, audio_end=end)
    else:
        print("audio: none")

    lists = edit_lists(path)
    if not lists:
        print("edit lists: none found")
    else:
        print("edit lists:")
        for tr in lists:
            if not tr["entries"]:
                print(f"  {tr['handler']}: no elst (movie timescale {tr['timescale']})")
                continue
            parts = []
            for i, e in enumerate(tr["entries"]):
                tag = "empty_edit" if e["empty_edit"] else f"media_time={e['media_time']}"
                ds = e["segment_duration_s"]
                parts.append(f"[{i}] {tag} segment={ds:.6f}s" if ds is not None else f"[{i}] {tag}")
            print(f"  {tr['handler']}: {len(tr['entries'])} "
                  f"entr{'y' if len(tr['entries'])==1 else 'ies'}; " + "; ".join(parts))

    present = {k: clocks[k] for k in ("container", "video_stream", "frame_count/fps") if clocks.get(k) is not None}
    print("clocks: " + "  ".join(f"{k}={v:.6f}s" for k, v in present.items()))
    disagree = []
    vals = list(present.values())
    if len(vals) >= 2 and (max(vals) - min(vals)) > 0.0005:
        disagree.append(
            f"picture clocks differ by {max(vals)-min(vals):.6f}s "
            f"(min={min(vals):.6f}, max={max(vals):.6f})"
        )
    vstart = clocks.get("video_start") or 0.0
    if vstart > 0.0005:
        disagree.append(
            f"video start_time is {vstart:.6f}s "
            "(presentation is delayed or an edit list is in play)"
        )
    aend, vend = clocks.get("audio_end"), clocks.get("video_end")
    if aend is not None and vend is not None and abs(aend - vend) > 0.02:
        disagree.append(f"audio end {aend:.6f}s vs video end {vend:.6f}s (abs diff {abs(aend-vend):.6f}s)")
    if disagree:
        print("disagree: " + " | ".join(disagree))
    else:
        print("disagree: no (picture clocks match within 0.0005 s)")
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("files", nargs="+", type=Path)
    args = ap.parse_args()
    rc = 0
    for i, p in enumerate(args.files):
        if i:
            print()
        if not p.is_file():
            print(f"missing: {p}")
            rc = 1
            continue
        rc = report(p) or rc
    return rc


if __name__ == "__main__":
    raise SystemExit(main())
Enter fullscreen mode Exit fullscreen mode

What I measured

The clean 15-second file is actually 15.000 seconds on all three picture clocks, and the audio matches:

$ python3 duration_check.py exact_15.mp4
file: exact_15.mp4  (6921202 bytes, mov,mp4,m4a,3gp,3g2,mj2)
container duration: 15.000000 s
video: h264 480x854 duration=15.000000 s start=0.000000s end=15.000000s  frames=450 fps=30/1 frame_count/fps=15.000000 s
audio: aac 48000Hz 1ch duration=15.000000 s start=0.000000s end=15.000000s
edit lists:
  vide: 1 entry; [0] media_time=0 segment=15.000000s
  soun: 1 entry; [0] media_time=1024 segment=15.000000s
clocks: container=15.000000s  video_stream=15.000000s  frame_count/fps=15.000000s
disagree: no (picture clocks match within 0.0005 s)
Enter fullscreen mode Exit fullscreen mode

A single elst entry with media_time=0 that covers the whole track is normal. The audio media_time=1024 is AAC encoder delay (1024 samples at 48 kHz is 0.0213 s), not a trim.

One frame short of 15 seconds is 14.966667 s on every picture clock (449 / 30). One frame long is 15.033333 s of picture, but the audio in that file was still 15.000 s, so the soundtrack ends 0.033333 s before the last frame:

$ python3 duration_check.py frames_449.mp4 frames_451.mp4
file: frames_449.mp4  (6906229 bytes, ...)
container duration: 14.966667 s
video: ... frames=449 fps=30/1 frame_count/fps=14.966667 s
audio: ... duration=14.954000 s ...
clocks: container=14.966667s  video_stream=14.966667s  frame_count/fps=14.966667s
disagree: no (picture clocks match within 0.0005 s)

file: frames_451.mp4  (6952454 bytes, ...)
container duration: 15.033333 s
video: ... frames=451 fps=30/1 frame_count/fps=15.033333 s
audio: ... duration=15.000000 s start=0.000000s end=15.000000s
clocks: container=15.033333s  video_stream=15.033333s  frame_count/fps=15.033333s
disagree: audio end 15.000000s vs video end 15.033333s (abs diff 0.033333s)
Enter fullscreen mode Exit fullscreen mode

A 15-second request at 30000/1001 is not 15.000 either. 450 frames at that rate are 15.015000 s, and all three picture clocks agreed on that number. The audio stayed 15.000 s. If you only look at the container and round to "15 s", you miss 15 milliseconds of picture.

When the three clocks disagree with each other

The interesting file is the stream-copy trim. I asked ffmpeg for -ss 0.40 -c copy on a 15.000 s original with a 1-second GOP. The picture clocks stopped agreeing:

$ python3 duration_check.py trim_elst.mp4
file: trim_elst.mp4  (6477275 bytes, mov,mp4,m4a,3gp,3g2,mj2)
container duration: 14.595000 s
video: h264 480x854 duration=14.000000 s start=0.600000s end=14.600000s  frames=420 fps=30/1 frame_count/fps=14.000000 s
audio: aac 48000Hz 1ch duration=14.594667 s start=0.005000s end=14.599667s
edit lists:
  vide: 2 entries; [0] empty_edit segment=0.600000s; [1] media_time=0 segment=14.000000s
  soun: 2 entries; [0] empty_edit segment=0.005000s; [1] media_time=0 segment=14.595000s
clocks: container=14.595000s  video_stream=14.000000s  frame_count/fps=14.000000s
disagree: picture clocks differ by 0.595000s (min=14.000000, max=14.595000) | video start_time is 0.600000s (presentation is delayed or an edit list is in play)
Enter fullscreen mode Exit fullscreen mode

Read those numbers as three different questions. Frame-count / fps is 14.000 s because 420 frames remain (the copy dropped one 30-frame GOP). The video stream duration is also 14.000 s, but its start time is 0.600 s, so the last frame is presented at 14.600 s. The container is 14.595 s, which follows the audio more closely. The video edit list explains the start offset: an empty_edit of 0.600 s, then 14.000 s of media. I asked for a 0.40 s trim; a stream-copy cut between keyframes is not a precise 0.40 s trim, and the three clocks will not tell you "15 seconds" or even the same number as each other.

How to read the three numbers

  • Container duration. What ffprobe prints for the file. Players often use this for the scrubber. It can follow the longest track, including an empty edit.
  • Stream duration. How long that track says it is, from its own start. Add start_time if you want the presentation end.
  • Frame-count / fps. nb_read_frames / avg_frame_rate. This ignores empty edits. 449 frames at 30 fps is 14.966667 s, even if someone labeled the export "15s".

If you just paid for a clip and have not edited it, the FAQ's "every clip is 15 seconds" is the product description. After a remux, a trim, or a round trip through an editor, run the checker on the file you are about to post and believe the three clocks, not the filename.

Checked 2026-11-18 (Asia/Shanghai) on ffmpeg 7.1.5. The run log is in files/dv/run_log.txt.

Top comments (0)