The `bt470bg` Trap: A Valid Color Name That Broke 22 HEVC Encodes

· 6 min read · DevOps ffmpeglibx265hevccolor-metadatavideo-pipelinepythondebugging

The Failure Looked Like a Deleted Queue

On 28 and 29 November, 22 HEVC jobs on the infrastructure I manage failed in a burst. The pending count was also falling, which made the failures look like a side effect of cleanup. The accounting said the queue was draining normally; the useful signal was inside the failure rows.

Each job spent about 30 seconds inside FFmpeg and then returned the same line:

!! FAIL ffmpeg rc=4294967274 ue "bt470bg"
[libx265 @ 000001d12ff5e8c0] Error setting option color_trc to value bt470bg.
[vost#0:0/libx265 @ 000001d12ff5e680] Error applying encoder options: Invalid argument
Error opening output file <staging>\02d42c85931c_out.mp4.

rc=4294967274 is the unsigned form of -22, EINVAL. The source files were PAL-era SD, and ffprobe reported the same tuple on all of them:

color_primaries=bt470bg
color_transfer=bt470bg
color_space=bt470bg

Nothing in that output is corrupt. In ITU-T H.273, transfer_characteristics=5 is BT.470-6 System B/G, the transfer function used by PAL SD. bt470bg is the name ffprobe prints for that value. The value was valid. The next program in the chain did not accept the name.

A Valid Tag Became an Invalid Option

The encoder wrapper built its argument list from the probe output. The relevant field was passed through unchanged:

if c_trc and c_trc not in ("unknown", "unspecified", "reserved"):
    args.extend(["-color_trc", c_trc])

That is where the failure starts. FFmpeg has more than one color-name table. ffprobe prints the alias it uses for display; -color_trc parses the canonical name it accepts as an option. For H.273 value 5 those are different strings.

The A/B test was small enough to run by hand:

ffmpeg -v error -i source.mp4 -t 1 -c:v libx265 -color_trc bt470bg  out.mp4  # rc=-22
ffmpeg -v error -i source.mp4 -t 1 -c:v libx265 -color_trc gamma28  out.mp4  # rc=0

gamma28 is the same H.273 value 5. The output read back as bt470bg; the picture was unchanged. This was a rename, not a color decision. The same trap exists for bt470m → gamma22, bt2020_10bit → bt2020-10, and a few other aliases.

The wrapper had been treating a display name as an encoder option. libx265 rejected the whole option dictionary before it wrote the first frame, which is why every failure cost about 30 seconds and left no partial output.

Three Tables, Not One

The first fix added an alias map and a whitelist. It translated bt470bg to gamma28 for -color_trc, kept the original name for primaries and matrix, and derived the test set from ffmpeg -h full. The error disappeared.

Then the same normalized string was passed into -x265-params.

That was the second bug. x265 has its own VUI name table. It accepts transfer=bt470bg, not transfer=gamma28. When the wrapper wrote -x265-params transfer=gamma28, x265 logged:

[libx265 @ ...] Invalid value for transfer: gamma28.

It then dropped the parameter and continued. The encode returned 0. The output container had no transfer tag:

color_range=tv
color_space=bt470bg
color_transfer=unknown
color_primaries=unknown

A hard failure is visible. A silent tag loss is not. The SSIM gate still passed because SSIM compares decoded pictures, and the decoded pictures were fine. The metadata was the part that disappeared.

There are three tables and two spellings for the same H.273 value in this pipeline:

SurfaceName for value 5Result
ffprobebt470bgPrints the display alias
FFmpeg -color_trcgamma28Accepts gamma28; rejects bt470bg with EINVAL
-x265-paramstransfer=bt470bgAccepts bt470bg; drops gamma28 and returns 0

The final wrapper stopped duplicating the color tags. The four values go through -color_* only; libx265 maps avctx->color_* into x265_param->vui.* itself. -x265-params keeps only the HDR10 static metadata that has no FFmpeg option equivalent: master-display and max-cll.

🔍 Color normalizer and whitelist (32-line excerpt from `library_run.py`)
COLOR_ALIASES = {
    "trc": {"bt470m": "gamma22", "bt470bg": "gamma28", "bt1361": "bt1361e",
            "bt2020_10bit": "bt2020-10", "bt2020_12bit": "bt2020-12"},
    "prim": {"smpte428_1": "smpte428"},
    "matrix": {},
}

COLOR_VALID = {
    "trc": frozenset(("bt709", "gamma22", "gamma28", "smpte170m", "smpte240m",
                      "linear", "log100", "log316", "iec61966-2-4", "bt1361e",
                      "iec61966-2-1", "bt2020-10", "bt2020-12", "smpte2084",
                      "smpte428", "smpte428_1", "arib-std-b67")),
    "prim": frozenset(("bt709", "bt470m", "bt470bg", "smpte170m", "smpte240m",
                       "film", "bt2020", "smpte428", "smpte431", "smpte432",
                       "jedec-p22", "ebu3213")),
    "matrix": frozenset(("rgb", "bt709", "fcc", "bt470bg", "smpte170m",
                         "smpte240m", "ycgco", "bt2020nc", "bt2020_ncl",
                         "bt2020c", "bt2020_cl", "smpte2085",
                         "chroma-derived-nc", "chroma-derived-c", "ictcp")),
}

def color_tag(kind, value, hdr=False):
    v = (value or "").strip().lower()
    if v in ("", "unknown", "unspecified", "reserved", "n/a", "none"):
        return ""
    v = COLOR_ALIASES[kind].get(v, v)
    if v in COLOR_VALID[kind]:
        return v
    if kind == "trc" and hdr:
        raise ValueError("unsupported HDR transfer %r on this build" % value)
    log("   ! colour tag %s=%r is not an encoder option on this build - dropped" % (kind, value))
    return ""

The Rule for Unknown Tags

The normalizer has one policy split: SDR fails open, HDR fails closed.

The same pass also rejects self-contradictory HDR tuples before encoding: PQ or HLG transfer on PAL-era primaries such as bt470bg, bt470m, smpte170m or film, and an HDR transfer with an RGB matrix on YUV pixels. Those rows go to SKIP with the full tuple in the reason, not to FAIL; a source that contradicts itself is not a valid master, but it is not an encoder crash either. bt709 primaries with PQ are tolerated because that combination occurs in real, lazily tagged footage and remains decodable.

Verify the Bitstream, Not the Container

A container tag is a claim. The SPS is the copy that a decoder reads. After the fix, I checked the encoded bitstream with trace_headers rather than asking ffprobe what the container said:

ffmpeg -hide_banner -i "$out" -map 0:v:0 -c copy \
  -bsf:v trace_headers -f null - 2>&1 \
  | grep -E "colour_primaries|transfer_characteristics|matrix_coeffs|full_range"

The first production file from the repaired set returned:

colour_primaries           = 5
transfer_characteristics   = 5
matrix_coeffs              = 5
full_range                 = 0

That is the assertion the container cannot make for itself. It also catches the exact failure mode of the first fix: an encode that exits 0 with the tag missing.

The 22-row set now stands at 11 done, 10 pending, 1 skip, 0 failed. The skip is a policy result, not a crash: the file would have saved about 7%, below the 10% floor. The first verified replacement encoded at SSIM 0.9936, with the bitstream tuple above. No bt470bg failure has appeared since the fix.

The Result

The queue was not deleting work. It was rejecting a valid color tag because three programs disagreed on which of the two H.273 spellings to accept.

The useful takeaway is narrower than “validate metadata”. A protocol value and a command-line option name are different interfaces. A normalizer that fixes one interface can still poison the next one, and an encoder that returns 0 after dropping an unknown parameter is more dangerous than one that refuses the job.

🛡️ Production Infrastructure & SRE

Dealing with flaky containers, cloud cost bloat, or unexplained outages?

Real production reliability comes from understanding the kernel and the protocol layers, not just restarting containers. I manage 162 containers across 3 hosts running 24/7 client workloads.

Lee Teong Hoe

Lee Teong Hoe · Mr Hoelee

Full-stack developer & DevOps engineer based in Malaysia. I run my own production infrastructure and build web systems for small businesses — this blog is the living record.

Hiring? Profile & stack · Malaysian SME? Website design & development ↗ · All posts