TorchCodec Video Decoding: Verify Frames and Timestamps Before Tuning

Test TorchCodec video decoding on a 300-frame H.264 clip. Compare RGB data and timestamps, recover delayed frames, and time both CPU paths after parity passes.

TorchCodec video decoding comparison drawn as two filmstrips aligned at indices 297, 298 and 299, with the custom tail highlighted.TorchCodec video decoding comparison drawn as two filmstrips aligned at indices 297, 298 and 299, with the custom tail highlighted.
Illustrative frame alignment for task:decode-parity-01. Decoder drain can return held frames for RGB conversion and comparison. Based on the TorchCodec packet decoder and low-level decoding documentation.

Your video model misses the last moment in a clip after you swap in a custom decoder. The first frame looks right, the tensor shape is familiar, and the new code finishes sooner. Before you change the clip sampler or credit the speedup, check what reached the model. This TorchCodec video decoding tutorial uses one synthetic MP4 to compare a sequential CPU pipeline against VideoDecoder frame by frame. You will get a parity verdict, a count of frames emitted during decoder drain, and, after a pass, five paired timings you can use to decide whether to keep the custom path.

PyTorch announced TorchCodec 1.0 on December 2, 2026. The release post describes the three stages used here. Demuxing reads compressed packets, packet decoding produces raw frames, and color conversion turns those frames into RGB. The high-level decoder handles all three. With the low-level API, your code also takes responsibility for collecting frames held by the packet decoder when the file ends. PyTorch release post

Opening of the PyTorch article announcing TorchCodec 1.0.
PyTorch’s publication page for “TorchCodec 1.0: The Media Layer of PyTorch.” · Original source

PyTorch’s publication page for “TorchCodec 1.0: The Media Layer of PyTorch.”

Build a clip with an answer key

  1. Start in a Python environment with TorchCodec 1.0 and a compatible PyTorch build. The TorchCodec repository lists Python 3.11–3.15 and PyTorch 2.11 or newer for 1.0. You need compatible FFmpeg shared libraries for TorchCodec video decoding and an ffmpeg executable on your path with libx264 for the fixture. Treat these as two separate checks if setup fails. TorchCodec installation and compatibility
  2. Save the script below as decode_parity.py. It creates decode-parity-01.mp4 in a fresh temporary directory. You can run it from the same directory as the Python file. The temporary directory is cleaned up after a normal exit or when the script unwinds after a parity error.
  3. Run python decode_parity.py for the complete comparison. For the controlled failure case, run python decode_parity.py --simulate-missing-tail. That flag belongs to the example script. It omits decoder drain and caps the custom output at 298 frames, so the test can demonstrate a short stream even when the amount of decoder buffering changes.

The clip is ten seconds of testsrc2 at 30 frames per second, 1920×1080, encoded as H.264 in an MP4 with yuv420p and BT.709 color signaling. The argument list comes from the TorchCodec pipeline tutorial, which uses those dimensions, rate, and duration. Its example reports 300 frames on CUDA. This article uses the same fixture recipe on CPU and derives the expected frame count from the input rate and duration. The outputs below are illustrative. TorchCodec pipeline tutorial

Keep the encoding arguments fixed for the first run. Changing the encoder settings can change which frames are buffered and when they become available. Changing the color signaling can change how the converter maps luma and chroma into RGB. The test compares two decodes of the same compressed bytes. Ordinary H.264 compression losses belong to both sides of the comparison because the original uncompressed pattern is outside the comparison.

Frame index zero should start at 0.000000 s. Index 299 should start near 9.966667 s, which is 299 / 30. The ten-second endpoint is one frame interval later. pts_seconds is the presentation timestamp, or PTS, of the frame. A clip sampler that asks what was on screen at a particular time depends on that timeline. At 9.98 s, for example, the expected frame for this constant-rate clip is index 299. Ending the decode at index 297 could leave that lookup with an empty result or an older image, depending on how the sampler handles a short stream. TorchCodec Frame reference

Input Action Expected result
task:decode-parity-01, 10 seconds, 30 fps, 1920×1080 H.264, CPU, one FFmpeg decode thread Run python decode_parity.py and read the counts, final PTS and parity verdict before the timing rows. Illustrative pass. Both paths emit 300 RGB uint8 frames shaped (3, 1080, 1920). Both end near 9.966667 s, each PTS differs from its peer by at most 0.000001 s, and the largest RGB channel difference is at most 1. Five paired timings follow.
task:decode-parity-01, same clip dimensions and settings, forced missing-tail mode Run python decode_parity.py --simulate-missing-tail and compare reference, custom, and drained in the output. Illustrative failure. A custom stream that reaches the imposed cap emits 298 frames, ends near 9.900000 s, and reports drained=0. The script exits with a parity error before timing. If omitting drain leaves fewer than 298, the run reports that lower count and its actual final PTS.

Compare the CPU outputs frame by frame

  1. Open the MP4 twice. Use exact mode on VideoDecoder and request the Frame for each index. On the custom path, select the video stream with Demuxer, pass that stream’s codec parameters to VideoPacketDecoder, and use ColorConverter to return the same RGB layout and dtype. Use one FFmpeg decode thread on both sides. VideoDecoder reference
  2. Feed packets to the packet decoder in demux order and iterate every frame it returns. At packet EOF, call drain() once and send the returned frames through the same converter and comparison as all the others. The script tags each converted frame with its origin so the diagnostic can say how many arrived during drain. VideoPacketDecoder reference
  3. Compare positions as emitted. Check each tensor’s shape, dtype, and device, then compare timestamps and the largest absolute RGB channel difference for each aligned pair. Let the loop finish so the report includes total counts and final timestamps even when one side runs out early. Use the first mismatch message to identify where the streams diverged.

TorchCodec packet decoding and end-of-stream drain feed a shared ColorConverter before RGB frames and PTS reach the parity check.TorchCodec packet decoding and end-of-stream drain feed a shared ColorConverter before RGB frames and PTS reach the parity check.
When the demuxer reaches EOF, convert each raw frame still held by the packet decoder. Based on TorchCodec’s low-level decoding tutorial and VideoPacketDecoder API reference.

The packet loop and the end-of-stream drain feed the same RGB conversion. Based on TorchCodec’s low-level decoding tutorial and packet decoder reference.

In this fixture, VideoDecoder can use its default best video stream because the file contains only one video stream. The custom path explicitly follows streams="video". Both decode on CPU. VideoDecoder uses NCHW dimension order and torch.uint8 output. On an individual Frame, the batch dimension is absent and the tensor is CHW. ColorConverter returns RGB in that same order and requires its device to match the packet decoder’s device. Checking all three dimensions makes a transposed frame a format error even when the total number of bytes is correct. Low-level decoding tutorial · ColorConverter reference

The comparison uses an absolute PTS tolerance of one microsecond. That tolerance accommodates representation differences near the same timestamp while rejecting a one-frame shift of roughly 33 milliseconds. Both paths are also checked against the fixture grid i / 30. That extra check catches a shared shift or gap that could otherwise pass a pairwise comparison. Keep the grid check specific to this generated constant-rate source. For a variable-rate recording, use its real presentation timestamps as the reference sequence and define a tolerance appropriate to its time base.

The allowed difference in RGB pixels is one integer level per channel, a test policy chosen for this example. The script takes the maximum across all pixels and all three channels. A mean would let a large difference in a small patch blend into the rest of the image, even if that patch is what the model reads. The subtraction widens both tensors to signed int16 first. An unsigned subtraction could wrap a negative result and report an incorrect absolute difference. If your application requires exact decoded bytes, set RGB_LIMIT = 0 and record that stricter rule with the result.

import argparse
from itertools import zip_longest
from math import isfinite
from pathlib import Path
from statistics import median
import subprocess
from tempfile import TemporaryDirectory
from time import perf_counter

import torch
from torchcodec.decoders import ColorConverter, Demuxer, VideoDecoder, VideoPacketDecoder

FRAME_COUNT = 300
FPS = 30
SHAPE = (3, 1080, 1920)
PTS_LIMIT = 0.000001
RGB_LIMIT = 1
DECODE_THREADS = 1
SIMULATED_COUNT = 298
ROUNDS = 5


def make_fixture(path):
    subprocess.run([
        'ffmpeg', '-y', '-hide_banner', '-loglevel', 'error',
        '-f', 'lavfi', '-i', 'testsrc2=size=1920x1080:rate=30:duration=10',
        '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-g', '30',
        '-colorspace', 'bt709', '-color_primaries', 'bt709',
        '-color_trc', 'bt709', str(path),
    ], check=True)


def reference_frames(path):
    decoder = VideoDecoder(
        path, device='cpu', seek_mode='exact', dimension_order='NCHW',
        num_ffmpeg_threads=DECODE_THREADS, output_dtype=torch.uint8,
    )
    frame_count = decoder.metadata.num_frames
    if frame_count is None:
        raise SystemExit('PARITY FAIL: VideoDecoder has no reference frame count.')
    for index in range(frame_count):
        yield decoder.get_frame_at(index), False


def custom_frames(path, simulate_missing_tail=False):
    demuxer = Demuxer(path, streams='video')
    (stream,) = demuxer.streams
    decoder = VideoPacketDecoder(
        stream.codec_parameters, device='cpu', num_ffmpeg_threads=DECODE_THREADS,
    )
    converter = ColorConverter(device='cpu', output_dtype=torch.uint8)
    emitted = 0
    for packet in demuxer:
        for raw in decoder.decode(packet):
            if not simulate_missing_tail or emitted < SIMULATED_COUNT:
                yield converter.convert(raw), False
                emitted += 1
    if not simulate_missing_tail:
        for raw in decoder.drain():
            yield converter.convert(raw), True


def frame_problem(frame, index):
    data = frame.data
    if tuple(data.shape) != SHAPE or data.dtype != torch.uint8 or data.device.type != 'cpu':
        return f'format {tuple(data.shape)} {data.dtype} {data.device}'
    pts = frame.pts_seconds
    if not isfinite(pts) or abs(pts - index / FPS) > PTS_LIMIT:
        return f'PTS {pts:.9f} s, grid expects {index / FPS:.9f} s'
    return None


def compare(path, simulate_missing_tail):
    counts = [0, 0]
    last_pts = [None, None]
    drained = 0
    max_pts_delta = 0.0
    max_rgb_delta = 0
    first_error = None
    names = ('reference', 'custom')
    pairs = zip_longest(reference_frames(path), custom_frames(path, simulate_missing_tail))
    for index, pair in enumerate(pairs):
        problems = []
        for side, record in enumerate(pair):
            if record is None:
                problems.append(f'{names[side]} has no frame')
                continue
            frame, from_drain = record
            counts[side] += 1
            last_pts[side] = frame.pts_seconds
            drained += int(from_drain)
            problem = frame_problem(frame, index)
            if problem:
                problems.append(f'{names[side]} {problem}')
        if not problems:
            ref, custom = pair[0][0], pair[1][0]
            pts_delta = abs(ref.pts_seconds - custom.pts_seconds)
            rgb_delta = int((ref.data.to(torch.int16) - custom.data.to(torch.int16)).abs().max().item())
            max_pts_delta = max(max_pts_delta, pts_delta)
            max_rgb_delta = max(max_rgb_delta, rgb_delta)
            if pts_delta > PTS_LIMIT or rgb_delta > RGB_LIMIT:
                problems.append(f'pair delta PTS={pts_delta:.9f} s, RGB={rgb_delta}')
        if problems and first_error is None:
            first_error = f'frame {index}: ' + ', '.join(problems)

    for name, count, pts in zip(names, counts, last_pts):
        end = 'none' if pts is None else f'{pts:.6f} s'
        print(f'{name}: frames={count} last_pts={end}', flush=True)
    print(f'drained={drained}', flush=True)
    if first_error or counts != [FRAME_COUNT, FRAME_COUNT]:
        detail = first_error or f'expected {FRAME_COUNT} frames on both paths'
        raise SystemExit(f'PARITY FAIL: {detail}. Keep VideoDecoder.')
    print(f'PARITY PASS: max_pts_delta={max_pts_delta:.9f} s max_rgb_delta={max_rgb_delta}', flush=True)


def timed_pass(reader, path):
    start = perf_counter()
    count = sum(1 for _ in reader(path))
    elapsed = perf_counter() - start
    if count != FRAME_COUNT:
        raise SystemExit(f'TIMING INVALID: {reader.__name__} emitted {count} frames')
    return elapsed


def benchmark(path):
    readers = (reference_frames, custom_frames)
    timings = {reader: [] for reader in readers}
    for reader in readers:
        timed_pass(reader, path)  # Warm up each path once.
    for round_index in range(ROUNDS):
        order = readers if round_index % 2 == 0 else readers[::-1]
        for reader in order:
            timings[reader].append(timed_pass(reader, path))
        ref, custom = (timings[reader][-1] for reader in readers)
        print(f'round {round_index + 1}: reference={ref:.3f} s custom={custom:.3f} s')
    for reader in readers:
        samples = timings[reader]
        print(f'{reader.__name__}: median={median(samples):.3f} s '
              f'range={min(samples):.3f}..{max(samples):.3f} s')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--simulate-missing-tail', action='store_true')
    args = parser.parse_args()
    with TemporaryDirectory() as temp_dir:
        path = Path(temp_dir) / 'decode-parity-01.mp4'
        make_fixture(path)
        compare(path, args.simulate_missing_tail)
        benchmark(path)


if __name__ == '__main__':
    main()

The reference uses the documented decoder.metadata.num_frames to bound the loop and calls get_frame_at to retrieve each image and its timestamp together. With seek_mode='exact', the initial scan supplies the content frame count. The script checks the number of frames actually yielded by each reader independently against the fixture’s 300-frame answer key. If both paths yielded the same 299 frames, the count check would still fail. If the reference provides no count, the script stops before making a parity or timing claim. Low-level decoding tutorial · VideoDecoder reference

VideoDecoder.get_all_frames() is also documented and returns a FrameBatch with data, pts_seconds and duration_seconds. Here both readers yield individual frames to keep the test from deliberately retaining two complete videos. At this resolution a full 300-frame RGB uint8 tensor alone contains about 1.87 GB of pixel data. The comparison holds only a few frames at once, plus temporary arithmetic tensors and the decoding libraries’ internal buffers. VideoDecoder reference · FrameBatch reference

The custom generator makes ordinary packet outputs and drain outputs look alike to the consumer. A single packet can produce zero, one, or multiple ready frames. The decoder can still be buffering frames when a call returns an empty list. Keep advancing the demuxer until its iterator is exhausted. An empty decode result in the middle of the file is part of the packet decoder’s documented interface. The generator preserves presentation order and uses the PTS attached to each converted frame. Sorting the result before comparison would hide an ordering error from a sequential consumer. VideoPacketDecoder reference

Find the first missing or mismatched frame

  1. In the normal run, check reference first. For this fixture it should show frames=300 last_pts=9.966667 s to the printed precision. If it falls short or the script reports a reference PTS error, rerun with the original fixture and settings before using that result to diagnose the custom decoder. The test needs a stable reference and an independent expected count.
  2. Read custom, then drained. If the custom path ends early and the prefix checks pass, trace the end of your packet loop. Verify that drain() runs after the demuxer finishes and that every returned raw frame is converted and emitted. A positive drained count in this script tells you those frames were delivered through the custom generator. A zero count on a passing run is possible when the decoder has no frames left to emit. VideoPacketDecoder reference
  3. Run the simulated failure command, then rerun the normal command. A passing normal run should restore the count and final PTS and reach the benchmark. Preserve the output of both commands if you are reviewing a decoder change. The forced case shows whether the test catches a short stream. The normal case checks the complete decoder on the generated clip.

Illustrative stat tiles contrast 300 frames ending at 9.966667 seconds with a forced 298-frame stream ending at 9.900000 seconds.Illustrative stat tiles contrast 300 frames ending at 9.966667 seconds with a forced 298-frame stream ending at 9.900000 seconds.
Illustrative two-frame shortfall for task:decode-parity-01. Source for the fixture and drain behavior is the TorchCodec 1.0 documentation, consulted December 3, 2026. Counts and timestamps are expected values for the pictured case.

Illustrative two-frame shortfall for task:decode-parity-01. Counts and timestamps represent the fixture and forced cap, informed by TorchCodec’s pipeline and packet decoder documentation, consulted December 3, 2026.

The following illustrative failure assumes that at least 298 frames were emitted before packet EOF and that the frames in that prefix pass the parity checks.

reference: frames=300 last_pts=9.966667 s
custom: frames=298 last_pts=9.900000 s
drained=0
PARITY FAIL: frame 298: custom has no frame. Keep VideoDecoder.

Index 298 is the first missing frame, since the 298 frames that arrived cover indices 0 through 297. Its expected PTS is about 9.933333 s. The final missing image should start about 9.966667 s. The comparison prints the last frame actually emitted by each path. That makes the symptom visible even when the two versions both open the same MP4 and the container header advertises the same duration. Inspecting only the container metadata would tell you about the input and leave the output shortfall undetected.

If your own custom code shows that pattern without the failure switch, check for a return or break at packet EOF that skips drain(). Then check that the drain output reaches the same consumer as frames from decode(packet). Calling drain() and ignoring its return value still loses those frames. The script uses a fresh demuxer and packet decoder per run. A drained decoder rejects further packets until reset(). If you later add seeking, the low-level tutorial also requires resetting the decoder after a demuxer seek before feeding it any more packets. Low-level decoding tutorial · VideoPacketDecoder reference

Equal frame counts with an early PTS failure call for a different check. Start at the first reported index and confirm that both readers use the same stream and that the custom reader emits every available frame in presentation order. If a local implementation substitutes packet timestamps for converted frame timestamps, restore frame.pts_seconds. The packet decoder can return a previously buffered image during a later packet call. Pairing each packet’s timestamp with whatever happens to emerge on that call can mislabel otherwise correct RGB data. VideoPacketDecoder reference · Frame reference

If format and PTS checks pass but the first error is pair delta, use the printed RGB delta at that index. Check whether the custom stage applies resizing, normalization, channel permutation, or color conversion beyond the documented ColorConverter.convert call. Restore one change at a time and rerun with the same acceptance threshold. When the script reports a format error before comparison, fix the shape or dtype first. Comparing arrays after a reshape merely because their element counts match can make a bad frame look like a color problem.

If FFmpeg never starts, check that the executable is visible to the Python process. If it starts and rejects libx264, use a build that provides the encoder and preserve the fixture settings. If TorchCodec fails to load its video backend even though the executable can generate MP4s, check the compatible FFmpeg shared-library installation for that Python environment. These errors occur before parity and need a successful reference decode before any conclusion about a custom path. TorchCodec installation and compatibility

Time complete decodes and keep the simpler path when results overlap

  1. Run the normal command on the machine where you intend to decode. Use the same CPU allocation for both paths and keep their FFmpeg thread setting at one. The script runs both in the same process. After parity, it warms each path once and records five paired rounds, alternating which reader goes first.
  2. Compare the paired rows as well as the median and range. Ask whether the custom path wins across the pairs, whether the gap is large enough to matter to your workload, and whether a second full invocation tells the same story. Use the benchmark only after the script prints PARITY PASS and confirms that every timed pass emitted 300 frames.
  3. Keep VideoDecoder for this use case if the custom path fails parity or yields no repeatable benefit. If you see a repeatable win, confirm the output on your application’s actual inputs and sampling pattern before selecting it. Change one dimension of the test at a time so you can identify what broke if a new case fails.

The timer starts immediately before consumption, so it includes opening the file and constructing the readers, as well as decoding, RGB conversion, and consumption through the final frame. The reference includes exact-mode initialization, which the API documents as scanning the file. The custom reader includes drain. The timer excludes fixture generation and parity arithmetic. This measures an end-to-end sequential read with indexed, timestamped reference frames. The published pipeline tutorial times another whole-file interface using frame iteration in approximate mode. Its workload is a useful model for matching consumption and warming both paths, and its timings belong to its own configuration. VideoDecoder reference · TorchCodec pipeline tutorial

Suppose your illustrative median is 1.84 s for the reference and 1.82 s for the custom path, with both ranges spanning 1.80–1.90 s and the quicker path switching across rounds. Keep VideoDecoder for this case. That difference is small relative to the variation and the paired results give you no consistent direction. If the reference is consistently slower, check how much of that gap you are paying for exact-mode startup, particularly if your application holds a decoder open across requests. If every request opens a new file, startup belongs in the comparison. Record which contract you timed so a coworker can reproduce the decision.

The example reads the same local file repeatedly after one verification pass and an explicit warm-up. That favors a warm-file experiment. A pipeline that processes one new file per request may see different costs from file access, initialization, or the clip sampler. Likewise, an application that consumes one full FrameBatch has a different output contract from these frame-by-frame readers. Run both implementations against the same application entry point before treating a local result as a deployment estimate. For a separate worked example of matching a benchmark’s workload and interpreting repeated runs, see Amazon Ergo vLLM benchmark verification.

If the custom reader has already reached your application and produces 298 frames where the reference produced 300, restore the application’s existing VideoDecoder route with its established stream, output format, and sampling settings. Re-run the affected clip from its original MP4. If the application cached preprocessed frames or model inputs from the short decode, regenerate those entries from the restored route. Mixing outputs from two routes would leave stale short sequences in play after the code change. Check the returned clip or sampled frames at the original failing position before closing the change.

Reuse the test at the model’s input boundary

  1. Keep the generated MP4 test as a CPU regression case. Preserve the fixture recipe, both decoder configurations, the two tolerances, and the expected terminal PTS together. This gives the next reader enough information to reproduce a failure from a short text log.
  2. Add the application’s smallest representative video and replay the real frame-selection code on both decoder outputs. For a sampler that requests frames by time, include a request late enough to exercise the tail. Carry the corresponding PTS into your assertion so an older frame substituted at the same sample position still fails.
  3. Add a separate case for each input feature your application relies on, such as variable frame rate or a second video stream. For multistream input, choose the same absolute stream index on both sides and check that the observed resolution and timestamps match the selected stream. For variable frame rate, use the reference frames’ actual timestamp sequence as your expected values. VideoDecoder reference · Low-level decoding tutorial

The per-frame test answers a question about model inputs before resizing or sampling can obscure the cause of a mismatch. The existing streaming parity tutorial applies a similar replay method to a different boundary, where an application assembles streamed model responses. To make the decoder check block a change automatically, use the regression verdict in your pull request checks, as described in the agent evaluation CI guide. If you later commit a larger representative clip with Git LFS and a contributor gets a pointer file in place of the video, see recovering a missing Git LFS fixture.

When timing or parity moves between runs, save the first failing frame index, both final PTS values, and the decoder settings with the result. A teammate can replay one clip and inspect the same frame before changing the sampler or rerunning model inference. That is the same operational principle used in Fleet Replay, applied here to the specific input boundary where an MP4 becomes a sequence of RGB tensors.

Sources

Many assistants.
One place to remember.

Bring your AI sessions, context, and usage together with Automater.

Meet Automater