DEV Community

Peiguan
Peiguan

Posted on

Why Does This Hit the Road Dude Clip Look Washed Out or Crushed After I Drop It Into a Browser?

A 15-second Hit the Road Dude remake is a dark cab, a bright window, and a short list of tones that have to stay put. If the file is limited range (TV levels, Y' 16-235) and a browser or an NLE treats it as full range (PC levels, Y' 0-255), the blacks lift and the highlights go dull. If the file is full range and the editor expands 16-235, values below 16 and above 235 get crushed. I wanted a measurement of coded Y' min/max, the color_range flag, and what an RGB conversion does under each assumption, from the pixels rather than from a look.

This is a measurement on synthetic 9:16 clips. I did not use a paid studio render. The product, for context, is a 15-second 9:16 remake with a newly generated voice at hittheroaddude.app. As of 24 November 2026, a single run is $9.99 at 480p or $12.99 at 720p. The check below is on files I built myself.

I built the files with ffmpeg 7.1.5 and read them with a small Python checker. A lossless encode with the matching range= flag keeps the designed luma patches. A second encode with the wrong flag is not a fair mismatch test: x264 converts the pixels. The washed and crushed examples below are a bitstream retag only (h264_metadata=video_full_range_flag=… with -c copy), so the coded Y' values stay put and only the flag moves.

The test files

The maker is make_range_test_clips.py (published next to this post). It writes five 720x1280 files, 15 seconds, 30 fps, 450 frames, AAC at 48 kHz unless noted. Each frame is a still test pattern: a black luma band, a white luma band, a mid-grey band, and a bottom band with chroma strips.

  • limited_control.mp4 — designed Y' 16 / 235 / 125, flagged TV (color_range=tv, range=tv).
  • full_control.mp4 — designed Y' 0 / 255 / 128, flagged PC (color_range=pc, range=pc).
  • washed_limited_as_pc.mp4 — a bitstream retag of the limited control, video_full_range_flag=1. Same coded pixels, now flagged PC.
  • crushed_full_as_tv.mp4 — a bitstream retag of the full control, video_full_range_flag=0. Same coded pixels, now flagged TV.
  • social_limited.mp4 — a second H.264/AAC pass of the limited control as a social-share stand-in: CRF 28, High profile, 44.1 kHz AAC, +faststart.
$ python3 make_range_test_clips.py
wrote limited_control.mp4, full_control.mp4, washed_limited_as_pc.mp4, crushed_full_as_tv.mp4, social_limited.mp4
Enter fullscreen mode Exit fullscreen mode

The checker

The script decodes every frame to raw yuv420p with no scale filter, so the reported Y' / U / V extrema are the coded values, then renders RGB24 twice: once with scale=in_range=tv:out_range=pc and once with in_range=pc. That second pair is the mismatch you get after a drop into a browser or an NLE that assumes the wrong levels. I am quoting both.

$ python3 range_check.py limited_control.mp4 full_control.mp4 washed_limited_as_pc.mp4 crushed_full_as_tv.mp4 social_limited.mp4
Enter fullscreen mode Exit fullscreen mode

Designed vs measured

limited_control.mp4 is flagged color_range='tv' → TV / limited (16-235). Coded Y' min=16 max=235 mean=124.687500. The black band is Y' min=16 max=16 mean=16.000000. The white band is Y' min=235 max=235 mean=235.000000. The mid band, designed 125, came out Y' 124.000000. U min=58 max=199 mean=128.000000; V min=36 max=221 mean=127.500000 — the chroma strips did not hold a designed 16/240 pair, so I am not going to treat chroma extrema as a pass/fail. The luma patches did. Pixel verdict: LIMITED RANGE pixels. Flag and extrema agree.

RGB if treated as TV (expanded to 0-255): black R 0 G 0 B 0 mean=0.000000; white R 253 G 255 B 255 mean=254.333333. RGB if treated as PC (0-255 as-is): black R 16 G 16 B 16 mean=16.000000; white R 233 G 235 B 235 mean=234.333333. That second column is the washed-out look: blacks sit at 16, whites never reach 255.

full_control.mp4 is flagged color_range='pc' → PC / full (0-255), pix_fmt yuvj420p. Coded Y' min=0 max=255 mean=128.625000. Black band Y' 0.000000, white band Y' 255.000000, mid band designed 128 and measured 130.000000. Pixel verdict: FULL RANGE pixels. Flag and extrema agree. RGB under both assumptions reported black 0 and white 255, as you would expect when the coded extrema already sit at the edges of 0-255.

washed_limited_as_pc.mp4 is the useful mismatch. Coded Y' is identical to the limited control: min=16 max=235 mean=124.687500, black 16.000000, white 235.000000, mid 124.000000, same U/V extrema. The flag is now color_range='pc' and pix_fmt yuvj420p. Pixel verdict: LIMITED RANGE pixels. FLAG vs PIXELS: tagged PC/full, but coded Y' stays inside 16-235 (washed-out risk). RGB under both of my forced conversions reported black R 16 G 16 B 16 and white R 233 G 235 B 235 mean=234.333333. Once the file is tagged PC / yuvj420p, the decode path honoured the (wrong) flag and left the washed levels in place; the in_range=tv request did not expand them. That is the browser/NLE failure mode I wanted to catch.

crushed_full_as_tv.mp4 is the other mismatch. Coded Y' is identical to the full control: min=0 max=255 mean=128.625000, black 0, white 255, mid 130.000000. The flag is now color_range='tv'. Pixel verdict: FULL RANGE pixels. FLAG vs PIXELS: tagged TV/limited, but coded Y' leaves 16-235 (crushed risk). A player that expands 16-235 will treat 0-15 as super-black and 236-255 as super-white. On this pattern the black and white bands already sit at 0 and 255, so the RGB extrema still report 0 and 255 after a TV expand — the clipping is at the legal edges. The flag and the coded extrema still disagree, which is the thing to flag before you drop the file into a timeline.

social_limited.mp4 stayed limited. Flag color_range='tv', profile High (the controls were High 4:4:4 Predictive). Coded Y' min=16 max=235 mean=124.689121 — a small move from 124.687500 after the CRF 28 pass. Black and white bands still measured 16.000000 and 235.000000. U min=57 max=203, V min=32 max=222. RGB under the two assumptions matched the limited control (TV-treated black 0, PC-treated black 16 and white mean=234.333333). A social re-encode did not, by itself, flip the range flag or smash the luma patches.

What I take from this

Read the flag and the coded Y' extrema, and do not treat them as the same fact. A limited clip dropped into a PC-level timeline looks washed: Y' 16 becomes RGB 16, Y' 235 becomes something like RGB 233-235, mean 234.333333 on this white patch, not 255. A full-range clip tagged as TV is a crushed-risk file even when a particular pattern's 0 and 255 patches still report 0 and 255 after an expand. A second encode with the wrong range= flag is a conversion, not a retag; use -c copy and h264_metadata if you want to test the flag alone.

The maker and the checker follow, in full.

make_range_test_clips.py

#!/usr/bin/env python3
"""Build synthetic 9:16 clips with known limited (16-235) or full (0-255) Y'C'bC'r.

Clips are test patterns, not a paid studio render.

Usage:
  python3 make_range_test_clips.py --out .
"""
from __future__ import annotations

import argparse
import subprocess
import tempfile
from pathlib import Path

import numpy as np

W, H = 720, 1280
FPS = 30
DURATION = 15.0
SR = 48000


def yuv420_pattern(black: int, white: int, mid: int, chroma_lo: int, chroma_hi: int) -> bytes:
    """Four luma bands plus four chroma strips in the bottom band."""
    Y = np.empty((H, W), dtype=np.uint8)
    Y[0:320, :] = black
    Y[320:640, :] = white
    Y[640:960, :] = mid
    Y[960:1280, :] = mid
    U = np.full((H // 2, W // 2), 128, dtype=np.uint8)
    V = np.full((H // 2, W // 2), 128, dtype=np.uint8)
    # Bottom luma band (rows 960-1279) → chroma rows 480-639, four equal strips.
    strip = (W // 2) // 4
    U[480:640, 0:strip] = chroma_lo
    V[480:640, 0:strip] = 128
    U[480:640, strip : 2 * strip] = chroma_hi
    V[480:640, strip : 2 * strip] = 128
    U[480:640, 2 * strip : 3 * strip] = 128
    V[480:640, 2 * strip : 3 * strip] = chroma_lo
    U[480:640, 3 * strip :] = 128
    V[480:640, 3 * strip :] = chroma_hi
    return Y.tobytes() + U.tobytes() + V.tobytes()


def encode_yuv(frame: bytes, dest: Path, color_range: str, extra_vf: str | None = None) -> None:
    """Lossless H.264 with an explicit TV or PC range flag. No range conversion."""
    assert color_range in {"tv", "pc"}
    with tempfile.TemporaryDirectory() as td:
        raw = Path(td) / "frame.yuv"
        raw.write_bytes(frame)
        wav = Path(td) / "tone.wav"
        subprocess.check_call(
            [
                "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
                "-f", "lavfi", "-i", f"sine=frequency=220:sample_rate={SR}:duration={DURATION}",
                "-ac", "1", str(wav),
            ]
        )
        vf = ["setsar=1", "setdar=9/16"]
        if extra_vf:
            vf.append(extra_vf)
        cmd = [
            "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
            "-stream_loop", "-1",
            "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", f"{W}x{H}", "-r", str(FPS),
            "-i", str(raw),
            "-i", str(wav),
            "-t", str(DURATION),
            "-vf", ",".join(vf),
            "-c:v", "libx264", "-preset", "veryfast", "-qp", "0", "-pix_fmt", "yuv420p",
            "-color_range", color_range,
            "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709",
            "-x264-params", f"colorprim=bt709:transfer=bt709:colormatrix=bt709:range={color_range}",
            "-c:a", "aac", "-b:a", "128k", "-ar", str(SR), "-ac", "1",
            "-movflags", "+faststart",
            str(dest),
        ]
        subprocess.check_call(cmd)


def social_reencode(src: Path, dest: Path) -> None:
    """A naive second H.264 pass, typical of a social-share re-encode.

    Lets ffmpeg pick color range handling; strips an explicit range intent
    on the command line so we can measure what survived.
    """
    subprocess.check_call(
        [
            "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
            "-i", str(src),
            "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p",
            "-profile:v", "high",
            "-c:a", "aac", "-b:a", "96k", "-ar", "44100", "-ac", "1",
            "-movflags", "+faststart",
            str(dest),
        ]
    )


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--out", type=Path, default=Path("."))
    args = p.parse_args()
    out = args.out
    out.mkdir(parents=True, exist_ok=True)

    limited = yuv420_pattern(black=16, white=235, mid=125, chroma_lo=16, chroma_hi=240)
    full = yuv420_pattern(black=0, white=255, mid=128, chroma_lo=0, chroma_hi=255)

    encode_yuv(limited, out / "limited_control.mp4", "tv")
    encode_yuv(full, out / "full_control.mp4", "pc")
    # Retag only. A second encode with the "wrong" range flag lets x264
    # convert the pixels. h264_metadata flips video_full_range_flag
    # without touching the coded Y' values — the actual washed/crushed case.
    subprocess.check_call(
        [
            "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
            "-i", str(out / "limited_control.mp4"),
            "-c", "copy",
            "-bsf:v", "h264_metadata=video_full_range_flag=1",
            str(out / "washed_limited_as_pc.mp4"),
        ]
    )
    subprocess.check_call(
        [
            "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
            "-i", str(out / "full_control.mp4"),
            "-c", "copy",
            "-bsf:v", "h264_metadata=video_full_range_flag=0",
            str(out / "crushed_full_as_tv.mp4"),
        ]
    )
    social_reencode(out / "limited_control.mp4", out / "social_limited.mp4")
    print(
        "wrote limited_control.mp4, full_control.mp4, "
        "washed_limited_as_pc.mp4, crushed_full_as_tv.mp4, social_limited.mp4"
    )


if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

range_check.py

#!/usr/bin/env python3
"""Measure Y' / C'b / C'r min/max and the color_range flag (TV vs PC).

Decodes to raw yuv420p without an explicit range conversion, and also
renders RGB24 twice: once treating the file as limited (TV) and once as
full (PC), which is the mismatch you get after a drop into a browser or NLE.

Usage:
  python3 range_check.py [clip.mp4 ...]
"""
from __future__ import annotations

import argparse
import json
import subprocess
import sys
from pathlib import Path

import numpy as np

W_EXPECT = None  # read from file


def ffprobe_video(path: Path) -> dict:
    raw = subprocess.check_output(
        [
            "ffprobe", "-hide_banner", "-loglevel", "error",
            "-select_streams", "v:0",
            "-show_entries",
            "stream=width,height,pix_fmt,color_range,color_space,color_primaries,color_transfer,codec_name,profile,avg_frame_rate,nb_frames",
            "-of", "json",
            str(path),
        ],
        text=True,
    )
    return json.loads(raw)["streams"][0]


def range_label(value: str | None) -> str:
    v = (value or "").strip().lower()
    if v in {"tv", "limited", "mpeg", "1"}:
        return "TV / limited (16-235)"
    if v in {"pc", "full", "jpeg", "2"}:
        return "PC / full (0-255)"
    return f"unspecified ({value!r})"


def decode_yuv420(path: Path, width: int, height: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Decode every frame to yuv420p. No scale filter, so range should stay as coded."""
    raw = subprocess.check_output(
        [
            "ffmpeg", "-hide_banner", "-loglevel", "error",
            "-i", str(path),
            "-an", "-f", "rawvideo", "-pix_fmt", "yuv420p",
            "pipe:1",
        ]
    )
    frame_size = width * height * 3 // 2
    n = len(raw) // frame_size
    if n == 0 or len(raw) != n * frame_size:
        raise RuntimeError(f"{path}: unexpected raw size {len(raw)} for {width}x{height}")
    Ys, Us, Vs = [], [], []
    for i in range(n):
        buf = raw[i * frame_size : (i + 1) * frame_size]
        y = np.frombuffer(buf[0 : width * height], dtype=np.uint8).reshape(height, width)
        uv = buf[width * height :]
        u = np.frombuffer(uv[0 : (width // 2) * (height // 2)], dtype=np.uint8).reshape(height // 2, width // 2)
        v = np.frombuffer(uv[(width // 2) * (height // 2) :], dtype=np.uint8).reshape(height // 2, width // 2)
        Ys.append(y)
        Us.append(u)
        Vs.append(v)
    return np.stack(Ys), np.stack(Us), np.stack(Vs)


def decode_rgb(path: Path, assumed: str) -> np.ndarray:
    """Render RGB24 forcing in_range to tv or pc (the NLE/browser assumption)."""
    assert assumed in {"tv", "pc"}
    probe = ffprobe_video(path)
    width, height = int(probe["width"]), int(probe["height"])
    raw = subprocess.check_output(
        [
            "ffmpeg", "-hide_banner", "-loglevel", "error",
            "-i", str(path),
            "-an",
            "-vf", f"scale=in_range={assumed}:out_range=pc,format=rgb24",
            "-f", "rawvideo", "-pix_fmt", "rgb24",
            "pipe:1",
        ]
    )
    frame_size = width * height * 3
    n = len(raw) // frame_size
    if n == 0 or len(raw) != n * frame_size:
        raise RuntimeError(f"{path}: unexpected rgb size {len(raw)} for {width}x{height}")
    # Use first and last frame only for min/max (pattern is static).
    first = np.frombuffer(raw[0:frame_size], dtype=np.uint8).reshape(height, width, 3)
    last = np.frombuffer(raw[(n - 1) * frame_size :], dtype=np.uint8).reshape(height, width, 3)
    return np.stack([first, last])


def band_stats(arr: np.ndarray, r0: int, r1: int) -> dict:
    sl = arr[:, r0:r1, :]
    return {
        "min": int(sl.min()),
        "max": int(sl.max()),
        "mean": float(sl.mean()),
    }


def classify_coded(y_min: int, y_max: int) -> str:
    """A simple TV vs PC guess from coded Y' extrema (not from the flag)."""
    # Full-range material reaches below 16 or above 235.
    touches_full = y_min < 16 or y_max > 235
    sits_in_limited = y_min >= 16 and y_max <= 235
    if touches_full:
        return "FULL RANGE pixels (Y' outside 16-235)"
    if sits_in_limited:
        return "LIMITED RANGE pixels (Y' inside 16-235)"
    return "UNCLEAR"


def report(path: Path) -> None:
    info = ffprobe_video(path)
    width, height = int(info["width"]), int(info["height"])
    flagged = range_label(info.get("color_range"))
    Y, U, V = decode_yuv420(path, width, height)
    y_min, y_max = int(Y.min()), int(Y.max())
    u_min, u_max = int(U.min()), int(U.max())
    v_min, v_max = int(V.min()), int(V.max())
    print(f"== {path.name} ==")
    print(
        f"  {width}x{height} {info.get('pix_fmt')} {info.get('codec_name')} "
        f"profile={info.get('profile')} frames={Y.shape[0]} "
        f"color_range={info.get('color_range')!r} → {flagged}"
    )
    print(
        f"  colorspace={info.get('color_space')} primaries={info.get('color_primaries')} "
        f"trc={info.get('color_transfer')}"
    )
    print(
        f"  coded Y' min={y_min} max={y_max} mean={Y.mean():.6f}  "
        f"U min={u_min} max={u_max} mean={U.mean():.6f}  "
        f"V min={v_min} max={v_max} mean={V.mean():.6f}"
    )
    # Designed bands for 1280-tall pattern.
    if height == 1280:
        black = band_stats(Y, 0, 320)
        white = band_stats(Y, 320, 640)
        mid = band_stats(Y, 640, 960)
        print(
            f"  luma bands  black Y' min={black['min']} max={black['max']} mean={black['mean']:.6f}  "
            f"white Y' min={white['min']} max={white['max']} mean={white['mean']:.6f}  "
            f"mid Y' min={mid['min']} max={mid['max']} mean={mid['mean']:.6f}"
        )
    print(f"  pixel verdict: {classify_coded(y_min, y_max)}")

    rgb_tv = decode_rgb(path, "tv")
    rgb_pc = decode_rgb(path, "pc")
    # Black / white bands in RGB (use channel min/max; greys should be equal RGB).
    def rgb_band(rgb: np.ndarray, r0: int, r1: int) -> str:
        sl = rgb[:, r0:r1, :, :]
        return (
            f"R {int(sl[...,0].min())}-{int(sl[...,0].max())} "
            f"G {int(sl[...,1].min())}-{int(sl[...,1].max())} "
            f"B {int(sl[...,2].min())}-{int(sl[...,2].max())} "
            f"mean={sl.mean():.6f}"
        )

    if height == 1280:
        print("  RGB if treated as TV (in_range=tv, expanded to 0-255):")
        print(f"    black  {rgb_band(rgb_tv, 0, 320)}")
        print(f"    white  {rgb_band(rgb_tv, 320, 640)}")
        print("  RGB if treated as PC (in_range=pc, 0-255 as-is):")
        print(f"    black  {rgb_band(rgb_pc, 0, 320)}")
        print(f"    white  {rgb_band(rgb_pc, 320, 640)}")
    else:
        print(
            f"  RGB TV-assumed min={int(rgb_tv.min())} max={int(rgb_tv.max())}  "
            f"PC-assumed min={int(rgb_pc.min())} max={int(rgb_pc.max())}"
        )
    # Flag vs pixels mismatch.
    flag = (info.get("color_range") or "").lower()
    pixels_full = y_min < 16 or y_max > 235
    if flag in {"tv", "limited", "mpeg"} and pixels_full:
        print("  FLAG vs PIXELS: tagged TV/limited, but coded Y' leaves 16-235 (crushed risk).")
    elif flag in {"pc", "full", "jpeg"} and not pixels_full and y_min >= 16 and y_max <= 235:
        print("  FLAG vs PIXELS: tagged PC/full, but coded Y' stays inside 16-235 (washed-out risk).")
    else:
        print("  FLAG vs PIXELS: tag and coded extrema agree on the range class.")
    print()


def main() -> int:
    p = argparse.ArgumentParser()
    p.add_argument("clips", nargs="*", type=Path)
    args = p.parse_args()
    clips = args.clips or [
        Path("limited_control.mp4"),
        Path("full_control.mp4"),
        Path("washed_limited_as_pc.mp4"),
        Path("crushed_full_as_tv.mp4"),
        Path("social_limited.mp4"),
    ]
    for c in clips:
        if not c.exists():
            print(f"missing {c}", file=sys.stderr)
            return 1
        report(c)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Enter fullscreen mode Exit fullscreen mode

Top comments (0)