"""
Generate the chroma siting check files: small charts that show the word WRONG when a player rebuilds the chroma
somewhere other than where the file's label says it is, and a blank field when it gets it right. See
sourceimages/chroma_siting_check/README.md.

Each file is designed for its own label (or, untagged, for the default of its format), so the rule is the same for
every file: blank means the player followed the label. A 4:2:0 file has two panels, Across and Down, which can be
wrong independently; a 4:2:2 file has only Across.

How it works: the mirror trick of the 4:2:0 player chart (make_chroma_siting_player_chart_420.py), with its colours.
A panel's background repeats a four-pixel cycle of stripes along one direction (vertical stripes across, horizontal
ones down); the word has the same chroma and the luma of the mirror image. For a player that rebuilds the chroma
as the label says, every pixel of the word is a pixel of the background, so from a distance the word disappears;
for any other player the word and background have different linear-light means and the word shows. Where the word's
edge crosses the stripes, the pattern changes phase, which shows as a faint line; the edge is staggered by 0 to 7
pixels from row to row, in a scrambled order, which cancels most of it (to about a twentieth of the word's
contrast, simulated).

As with the player charts, it only works at exactly 100%: a viewer that scales the picture averages the code
values first and the word disappears whatever the player does. The scale check in the caption shows that: its two
halves look equally bright only at 100%.

Writes 10-bit (8-bit for the 8-bit codecs) BT.709 limited range into chroma_siting_check/:

  chroma_siting_check_420-<codec>-<label>.<ext>   4:2:0, labelled left, topleft, center, or untagged (= left)
  chroma_siting_check_422-<codec>-<label>.<ext>   4:2:2, untagged (= co-sited), left, or center
  chroma_siting_check_420-hevc-pq-<label>.mp4     HDR10 (BT.2020, PQ), untagged, left or topleft
  ...-rot90.<ext>                                 stored turned 90 degrees, with a display matrix to turn it back

Needs ffmpeg with libx264 and libx265 on the PATH (or FFMPEG_BIN), numpy and Pillow.

    python sourceimages/make_chroma_siting_check.py            # all of them
    python sourceimages/make_chroma_siting_check.py hevc-pq    # only the files with hevc-pq in the name
"""
import argparse
import os
import subprocess
import tempfile
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

from chroma_siting_420_colours import BT2020_TO_709, PQ_MAX_NITS, PQ_MIN_NITS, pq_eotf, pq_oetf
from make_chroma_siting_player_chart import set_mxf_color_siting
from make_chroma_siting_player_chart_420 import BANDS, BANDS_PQ, MIRROR, light_levels

HERE = Path(__file__).resolve().parent
OUT = HERE / "chroma_siting_check"
NAME = "chroma_siting_check"
W = 640
CAPTION, ROW, LABEL = 72, 144, 128     # caption height, panel row height, label column width (all multiples of 4)
UNIT = 16                               # size of one block of the 5x7 font
STAGGER = np.array([0, 5, 2, 7, 4, 1, 6, 3])
CHECK = (488, 8, 632, 64)               # scale check: one-pixel checkerboard left, eight-pixel right
BAND = {band[0].split(" (")[0]: band for band in BANDS}
BAND_PQ = {band[0].split(" (")[0]: band for band in BANDS_PQ}     # the same bands, colours for HDR10
# What a player should do for each label: the band whose mirror matches it, across and down.
EXPECT = {
    "untagged": ("Across: co-sited", "Down: centered"),
    "left": ("Across: co-sited", "Down: centered"),
    "topleft": ("Across: co-sited", "Down: co-sited"),
    "center": ("Across: centered", "Down: centered"),
}
GLYPHS = {
    "W": ["X...X", "X...X", "X...X", "X.X.X", "X.X.X", "XX.XX", "X...X"],
    "R": ["XXXX.", "X...X", "X...X", "XXXX.", "X.X..", "X..X.", "X...X"],
    "O": [".XXX.", "X...X", "X...X", "X...X", "X...X", "X...X", ".XXX."],
    "N": ["X...X", "XX..X", "X.X.X", "X..XX", "X...X", "X...X", "X...X"],
    "G": [".XXX.", "X...X", "X....", "X.XXX", "X...X", "X...X", ".XXX."],
}


def word_mask(text="WRONG"):
    """The word as a boolean array, one cell per font block, with one block between letters."""
    cols = []
    for k, ch in enumerate(text):
        if k:
            cols.append(np.zeros((7, 1), bool))
        cols.append(np.array([[c == "X" for c in row] for row in GLYPHS[ch]]))
    return np.hstack(cols)


def panel_mask(rows, axis):
    """Where the word is in a panel row (ROW x (W - LABEL)), with its edges across the stripes staggered."""
    cells = word_mask()
    big = np.kron(cells, np.ones((UNIT, UNIT), bool))
    h, w = big.shape
    ph, pw = ROW, W - LABEL
    y0, x0 = (ph - h) // 2 // 4 * 4, (pw - w) // 2 // 4 * 4
    yy, xx = np.mgrid[0:ph, 0:pw]
    # Shift the word by 0..7 pixels along the stripes' direction, in a scrambled order that repeats every eight
    # rows (columns for Down): every phase of the cycle twice, spread out, so the edge lines cancel.
    if axis == "x":
        xx = xx - STAGGER[rows[:, None] % 8]
    else:
        yy = yy - STAGGER[np.arange(pw)[None, :] % 8]
    inside = (yy >= y0) & (yy < y0 + h) & (xx >= x0) & (xx < x0 + w)
    m = np.zeros((ph, pw), bool)
    m[inside] = big[(yy - y0)[inside], (xx - x0)[inside]]
    return m


def panels(sub, label, rotated=False):
    """The panels of a file as displayed, top to bottom: (band, axis the stripes vary along on screen, panel label).
    The band is chosen by the axis of the stored (coded) frame, which is what the label describes; a file rotated
    by 90 degrees for display swaps the axes, so its Across panel (on screen) tests the stored frame's vertical
    siting."""
    bands = [EXPECT[label][0]] if sub == "422" else list(EXPECT[label])
    out = []
    for name in bands:
        axis = BAND[name][2]
        if rotated:
            axis = "y" if axis == "x" else "x"
        out.append((name, axis, "Across" if axis == "x" else "Down"))
    return sorted(out, key=lambda p: p[1])          # Across first


def coded_coords(yy, xx, rotated):
    """Stored-frame coordinates (y, x) of displayed pixels: the stored frame is the displayed one turned 90
    degrees counterclockwise (np.rot90), and the file says to turn it back clockwise."""
    return (W - 1 - xx, yy) if rotated else (yy, xx)


def chart(sub, label, caption, rotated=False, hdr10=False):
    """Y, Cb, Cr as 10-bit codes in the stored orientation, Cb and Cr subsampled for sub ("420" or "422"), and the
    stored frame's size (width, height). With hdr10, the 4:2:0 chart's PQ colours (BT.2020), and the text and scale
    check kept between 1 and 100 cd/m^2 like them, so no display tone maps any of it."""
    pans = panels(sub, label, rotated)
    H = CAPTION + ROW * len(pans)
    if hdr10:
        bands, (ink0, ink1) = BAND_PQ, (float(pq_oetf(10)), float(pq_oetf(PQ_MAX_NITS)))
        check = (float(pq_oetf(PQ_MIN_NITS)), float(pq_oetf(PQ_MAX_NITS)))
    else:
        bands, (ink0, ink1), check = BAND, (0.15, 0.85), (0.0, 1.0)
    y = np.full((H, W), ink0)
    cb, cr = np.zeros((H, W)), np.zeros((H, W))
    for k, (name, axis, _) in enumerate(pans):
        _, _, coded_axis, mirror, (X, Z, lumas) = bands[name]
        r0 = CAPTION + k * ROW
        yy, xx = np.mgrid[r0:r0 + ROW, LABEL:W]
        cy, cx = coded_coords(yy, xx, rotated)
        u = cx if coded_axis == "x" else cy        # stored-frame position, so the cycle lines up with its chroma grid
        word = panel_mask(np.arange(r0, r0 + ROW), axis)
        lum = np.array(lumas)
        y[r0:r0 + ROW, LABEL:] = np.where(word, lum[np.array(MIRROR[mirror])[u % 4]], lum[u % 4])
        c = np.array([X, Z])[(u // 2) % 2]
        cb[r0:r0 + ROW, LABEL:], cr[r0:r0 + ROW, LABEL:] = c[..., 0], c[..., 1]
    # Caption and panel labels, luma only.
    img = Image.new("L", (W, H), 0)
    d = ImageDraw.Draw(img)
    big, small = ImageFont.load_default(size=20), ImageFont.load_default(size=14)
    d.text((12, 8), caption, fill=255, font=big)
    d.text((12, 36), "View at 100%, from a distance. A word = wrong; blank = right.", fill=220, font=small)
    d.text((12, 52), "Scale check (right): both halves equally bright, or not 100%.", fill=220, font=small)
    for k, (_, _, panel_label) in enumerate(pans):
        d.text((12, CAPTION + k * ROW + ROW // 2 - 10), panel_label, fill=255, font=big)
    text = np.zeros((H, W), bool)
    text[:CAPTION] = True
    text[:, :LABEL] = True
    y = np.where(text, ink0 + (ink1 - ink0) * np.asarray(img) / 255.0, y)
    cb[text], cr[text] = 0, 0
    x0, y0, x1, y1 = CHECK
    xm = (x0 + x1) // 2
    yy, xx = np.mgrid[y0:y1, x0:x1]
    on = np.where(xx < xm, (yy + xx) % 2, ((yy - y0) // 8 + (xx - xm) // 8) % 2)
    y[y0:y1, x0:x1] = np.where(on == 1, check[1], check[0])
    planes = [np.round(y * 876 + 64), np.round(cb * 896 + 512), np.round(cr * 896 + 512)]
    planes = [np.clip(p, 4, 1019).astype("<u2") for p in planes]
    if rotated:
        planes = [np.ascontiguousarray(np.rot90(p)) for p in planes]
    h, w = planes[0].shape
    if sub == "420":
        return [planes[0], planes[1][0::2, 0::2], planes[2][0::2, 0::2]], (w, h)
    return [planes[0], planes[1][:, 0::2], planes[2][:, 0::2]], (w, h)


# Where each label puts the chroma samples, (across co-sited, down co-sited); 4:2:2 has only the first.
SITING = {"untagged": (True, False), "left": (True, False), "topleft": (True, True), "center": (False, False)}


def upsample(c, axis, cosited):
    """Linear interpolation of a chroma plane to twice its size along axis, with the samples co-sited with the
    even luma pixels or centred between each pair, as a GPU's bilinear filter does."""
    n = c.shape[axis]
    t = np.arange(2 * n) / 2.0 if cosited else (np.arange(2 * n) - 0.5) / 2.0
    t = np.clip(t, 0, n - 1)
    i0 = np.floor(t).astype(int)
    i1 = np.minimum(i0 + 1, n - 1)
    f = t - i0
    shape = [1, 1]
    shape[axis] = -1
    f = f.reshape(shape)
    return np.take(c, i0, axis) * (1 - f) + np.take(c, i1, axis) * f


PREVIEW_SIGMA = 5.0      # blur for the distant view, in chart pixels: enough to hide the staggered edges too


def blur(img, s=PREVIEW_SIGMA):
    k = np.exp(-0.5 * (np.arange(-int(4 * s), int(4 * s) + 1) / s) ** 2)
    k /= k.sum()
    for axis in (0, 1):
        pad = [(0, 0)] * img.ndim
        pad[axis] = (len(k) // 2, len(k) // 2)
        img = np.apply_along_axis(lambda v: np.convolve(v, k, "valid"), axis, np.pad(img, pad, mode="wrap"))
    return img


def preview(planes, sub, label, rotated, hdr10, bits, right, distant=True):
    """The chart as a player shows it, as 8-bit sRGB in display orientation: with the chroma rebuilt where the label
    says (right) or at the other siting on every axis (wrong), so each panel shows the word. Made from the codes
    before encoding, so compression plays no part. The HDR10 charts are converted to SDR with 100 cd/m^2 as white,
    which is as bright as they get, so the pattern matches but the brightness is not the HDR display's.

    distant: as seen from a distance, at half the width and height: the panels blurred and shrunk in linear light
    (display gamma 2.4), since shrinking the stripes without the blur breaks the mirror and shows the word even
    when right; the caption and labels only shrunk, so they stay readable. Otherwise the chart at 1:1."""
    y, cb, cr = (p.astype(float) for p in planes)
    if bits == 8:
        y, cb, cr = ((p + 2) // 4 * 4 for p in (y, cb, cr))
    across, down = SITING[label]
    if sub == "420":
        cb, cr = (upsample(p, 0, down if right else not down) for p in (cb, cr))
    cb, cr = (upsample(p, 1, across if right else not across) for p in (cb, cr))
    y, cb, cr = (y - 64) / 876, (cb - 512) / 896, (cr - 512) / 896
    kr, kb = (0.2627, 0.0593) if hdr10 else (0.2126, 0.0722)
    r = y + 2 * (1 - kr) * cr
    b = y + 2 * (1 - kb) * cb
    g = (y - kr * r - kb * b) / (1 - kr - kb)
    rgb = np.clip(np.stack([r, g, b], -1), 0, 1)
    if hdr10:
        lin = np.clip(pq_eotf(rgb) / PQ_MAX_NITS @ BT2020_TO_709.T, 0, 1)
        rgb = lin ** (1 / 2.4)          # the same display gamma the SDR charts are viewed with
    if rotated:
        rgb = np.rot90(rgb, -1)         # turned upright after the chroma is rebuilt, as a right player does
    return to_image(distant_view(rgb) if distant else rgb)


def to_image(rgb):
    return Image.fromarray((np.clip(rgb, 0, 1) * 255).round().astype(np.uint8))


def distant_view(rgb):
    """A chart (R'G'B' 0..1, display orientation) as seen from a distance, at half the width and height: the panels
    blurred and shrunk in linear light (display gamma 2.4), since shrinking the stripes without the blur breaks the
    mirror and shows the word even when right; the caption and labels only shrunk, so they stay readable."""
    def half(a):
        h, w = a.shape[:2]
        return a.reshape(h // 2, 2, w // 2, 2, 3).mean((1, 3))
    lin = rgb ** 2.4
    small = half(lin)
    for r0 in range(CAPTION, lin.shape[0], ROW):
        # Each panel blurred on its own, so the text does not bleed in. Its outer four pixels are left out (the
        # chroma filter mixes in the next panel's or the caption's there) and replaced by repeating the pattern,
        # and the blur wraps round: the panel is a whole number of cycles both ways (four pixels for the stripes,
        # eight for the link check's blocks).
        inner = lin[r0 + 4:r0 + ROW - 4, LABEL + 4:W - 4]
        small[r0 // 2:(r0 + ROW) // 2, LABEL // 2:] = half(blur(np.pad(inner, ((4, 4), (4, 4), (0, 0)), "wrap")))
    return np.clip(small, 0, 1) ** (1 / 2.4)


# The display link check: a still R'G'B' picture, so no video decoder takes part, that shows the word WRONG when
# something between the browser and the panel subsamples the colour (a GPU sending YCbCr 4:2:2 or 4:2:0 over
# HDMI, say). The word is a one-pixel checkerboard of two colours, the background a checkerboard of 4x4 blocks of
# the same two: the same pixels, so over an RGB link the word disappears from a distance whatever the display's
# gamma. Subsampling mixes the colours of neighbouring pixels: inside the word every pixel's neighbours are the
# other colour, in the blocks mostly the same one, so the word changes colour and shows. Simulated for 4:2:2 and
# 4:2:0, with the chroma dropped, filtered co-sited [1 2 1] or averaged in pairs, at either pixel phase: the word's
# contrast is at least 0.039 (Oklab, linear light), against 0.0002 over RGB. That is as large as what such a link
# does to the check files themselves (0.03 to 0.06), so a blank link check means the link is not the cause.
# The word always shows as a texture (a finer checkerboard), even from across a room on a large-pixel screen,
# because the two colours differ in brightness. That cannot be designed away: the link's error comes from the
# colours' different luma, and pairs of nearly equal brightness were simulated at a worst case of 0.011 (brightness
# contrast 0.18) or 0.025 (0.40), against 0.039 for these (0.90). So the check asks about colour, not texture.
LINK_COLOURS = ((62, 0, 183), (90, 255, 0))
LINK_BLOCK = 4


def link_chart():
    """The link check, 640 x 216, as R'G'B' 0..1: a caption, the scale check, and one panel."""
    H = CAPTION + ROW
    img = Image.new("L", (W, H), 0)
    d = ImageDraw.Draw(img)
    big, small = ImageFont.load_default(size=20), ImageFont.load_default(size=14)
    d.text((12, 8), "Display link check: a still picture, no video", fill=255, font=big)
    d.text((12, 36), "Judge colour, not texture: letters in another colour = link subsamples.", fill=220, font=small)
    d.text((12, 52), "Scale check (right): both halves equally bright, or not 100%.", fill=220, font=small)
    d.text((12, CAPTION + ROW // 2 - 10), "Link", fill=255, font=big)
    grey = 0.15 + 0.7 * np.asarray(img) / 255.0
    rgb = np.repeat(grey[..., None], 3, 2)
    x0, y0, x1, y1 = CHECK
    xm = (x0 + x1) // 2
    yy, xx = np.mgrid[y0:y1, x0:x1]
    on = np.where(xx < xm, (yy + xx) % 2, ((yy - y0) // 8 + (xx - xm) // 8) % 2)
    rgb[y0:y1, x0:x1] = on[..., None].astype(float)
    yy, xx = np.mgrid[CAPTION:H, LABEL:W]
    word = panel_mask(np.arange(CAPTION, H), "x")
    pick = np.where(word, (yy + xx) % 2, (yy // LINK_BLOCK + xx // LINK_BLOCK) % 2)
    a, b = (np.array(c) / 255.0 for c in LINK_COLOURS)
    rgb[CAPTION:, LABEL:] = np.where(pick[..., None] == 1, b, a)
    return rgb


def subsampled_link(rgb):
    """What a link sending YCbCr 4:2:2 (BT.709, chroma averaged in pairs) does to R'G'B'."""
    kr, kb = 0.2126, 0.0722
    y = kr * rgb[..., 0] + (1 - kr - kb) * rgb[..., 1] + kb * rgb[..., 2]
    cb, cr = (rgb[..., 2] - y) / (2 * (1 - kb)), (rgb[..., 0] - y) / (2 * (1 - kr))
    cb, cr = (upsample((c[:, 0::2] + c[:, 1::2]) / 2, 1, False) for c in (cb, cr))
    r, b = y + 2 * (1 - kr) * cr, y + 2 * (1 - kb) * cb
    return np.clip(np.stack([r, (y - kr * r - kb * b) / (1 - kr - kb), b], -1), 0, 1)


def write_link_check():
    rgb = link_chart()
    for name, img in (("link", to_image(rgb)), ("link-right", to_image(distant_view(rgb))),
                      ("link-wrong", to_image(distant_view(subsampled_link(rgb))))):
        png = OUT / f"{NAME}_{name}.png"
        img.save(png, optimize=True)
        print(png.name, png.stat().st_size)


# (subsampling, codec, label, bit depth, encode arguments, extension)
LOOP = ["-stream_loop", "49"]     # 2 s for the codecs that compress a static frame to almost nothing
HEVC = ["-c:v", "libx265", "-crf", "4", "-tag:v", "hvc1", "-x265-params", "log-level=error"]
JOBS = [
    ("420", "lossless", "left", 10, ["-c:v", "ffv1"], "mkv", "FFV1"),
    ("420", "lossless", "topleft", 10, ["-c:v", "ffv1"], "mkv", "FFV1"),
    ("420", "lossless", "center", 10, ["-c:v", "ffv1"], "mkv", "FFV1"),
    ("420", "hevc", "untagged", 10, LOOP + HEVC, "mp4", "HEVC 10-bit"),
    ("420", "hevc", "left", 10, LOOP + HEVC, "mp4", "HEVC 10-bit"),
    ("420", "hevc", "topleft", 10, LOOP + HEVC, "mp4", "HEVC 10-bit"),
    ("420", "hevc", "center", 10, LOOP + HEVC, "mp4", "HEVC 10-bit"),
    ("420", "h264", "untagged", 8, LOOP + ["-c:v", "libx264", "-crf", "1"], "mp4", "H.264 8-bit"),
    ("420", "h264", "topleft", 8, LOOP + ["-c:v", "libx264", "-crf", "1"], "mp4", "H.264 8-bit"),
    ("420", "h264", "center", 8, LOOP + ["-c:v", "libx264", "-crf", "1"], "mp4", "H.264 8-bit"),
    ("422", "lossless", "left", 10, ["-c:v", "ffv1"], "mkv", "FFV1"),
    ("422", "lossless", "center", 10, ["-c:v", "ffv1"], "mkv", "FFV1"),
    ("422", "prores", "untagged", 10, ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0"], "mov",
     "ProRes 422 HQ"),
    ("422", "hevc", "untagged", 10, LOOP + HEVC, "mp4", "HEVC 4:2:2 10-bit"),
    ("422", "dnxhr", "untagged", 10, ["-c:v", "dnxhd", "-profile:v", "dnxhr_hqx"], "mxf", "DNxHR HQX"),
    ("422", "dnxhr", "center", 10, ["-c:v", "dnxhd", "-profile:v", "dnxhr_hqx"], "mxf", "DNxHR HQX"),
]
# Stored sideways, with a display matrix that turns them upright: a player has to rebuild the chroma on the stored
# frame's grid (which the label describes) and then rotate, or swap the siting if it rotates the planes first.
ROTATED = [
    ("420", "hevc", "left", 10, LOOP + HEVC, "mp4", "HEVC 10-bit"),
    ("420", "hevc", "topleft", 10, LOOP + HEVC, "mp4", "HEVC 10-bit"),
    ("420", "h264", "untagged", 8, LOOP + ["-c:v", "libx264", "-crf", "1"], "mp4", "H.264 8-bit"),
    ("420", "h264", "topleft", 8, LOOP + ["-c:v", "libx264", "-crf", "1"], "mp4", "H.264 8-bit"),
    ("422", "hevc", "untagged", 10, LOOP + HEVC, "mp4", "HEVC 4:2:2 10-bit"),
    ("422", "prores", "untagged", 10, ["-c:v", "prores_ks", "-profile:v", "3", "-vendor", "apl0"], "mov",
     "ProRes 422 HQ"),
]


# HDR10 (BT.2020, PQ, HEVC Main 10 with mastering display and light level SEI), 4:2:0 only, as the 4:2:0 chart's
# HDR10 copies: untagged, and left and topleft written explicitly.
HDR10 = [("420", "hevc-pq", label, 10, LOOP + HEVC, "mp4", "HDR10 HEVC") for label in ("untagged", "left", "topleft")]
HDR10_TAGS = "setparams=range=tv:color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc"


def file_name(sub, codec, label, ext, rotated=False):
    return f"{NAME}_{sub}-{codec}-{label}{'-rot90' if rotated else ''}.{ext}"


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("only", nargs="*", help="Write only the files whose names contain one of these")
    parser.add_argument("--previews", action="store_true",
                        help="Write only the right and wrong preview PNGs for the viewer page, not the videos")
    args = parser.parse_args()
    ffmpeg = os.environ.get("FFMPEG_BIN", "ffmpeg")
    OUT.mkdir(exist_ok=True)
    if not args.only or any(o in "link" for o in args.only):
        write_link_check()
    with tempfile.TemporaryDirectory() as tmp:
        for (sub, codec, label, bits, enc, ext, codec_name), rotated in \
                [(job, False) for job in JOBS + HDR10] + [(job, True) for job in ROTATED]:
            if args.only and not any(o in file_name(sub, codec, label, ext, rotated) for o in args.only):
                continue
            hdr10 = codec.endswith("-pq")
            sub_name = "4:2:0" if sub == "420" else "4:2:2"
            caption = f"{sub_name}  {codec_name}  " + ("no label" if label == "untagged" else f"labelled {label}")
            if rotated:
                caption += ", rotated 90"
            planes, (w, h) = chart(sub, label, caption, rotated, hdr10)
            out = OUT / file_name(sub, codec, label, ext, rotated)
            if ext in ("mp4", "mov"):           # the files on the viewer page
                for right in (True, False):
                    png = out.with_name(f"{out.stem}-{'right' if right else 'wrong'}.png")
                    preview(planes, sub, label, rotated, hdr10, bits, right).save(png, optimize=True)
                    print(png.name, png.stat().st_size)
            if args.previews:
                continue
            raw = Path(tmp) / "chart.yuv"
            if bits == 8:
                # 8-bit from the 10-bit codes here, so FFmpeg does not dither and break the mirror symmetry.
                raw.write_bytes(b"".join(((p.astype(int) + 2) // 4).clip(1, 254).astype(np.uint8).tobytes()
                                         for p in planes))
                pix = "yuv420p" if sub == "420" else "yuv422p"
            else:
                raw.write_bytes(b"".join(p.tobytes() for p in planes))
                pix = "yuv420p10le" if sub == "420" else "yuv422p10le"
            src = ["-f", "rawvideo", "-pix_fmt", pix, "-s", f"{w}x{h}", "-r", "25", "-color_range", "tv",
                   "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"]
            loc = [] if label == "untagged" or ext == "mxf" else ["-chroma_sample_location", label]
            if hdr10:
                # As the 4:2:0 chart's HDR10 copies: the tags and the chroma location set on the frames.
                src = src[:-8]
                max_cll, max_fall = light_levels(planes)
                x265 = ("log-level=error:hdr10=1:repeat-headers=1:"
                        "master-display=G(13250,34500)B(7500,3000)R(34000,16000)WP(15635,16450)L(10000000,1):"
                        f"max-cll={max_cll},{max_fall}")
                enc = enc[:-1] + [x265, "-vf", HDR10_TAGS + ("" if label == "untagged" else f":chroma_location={label}")]
                loc = []
            # The loop must come before -i; the encoder arguments after it.
            pre = LOOP if enc[:2] == LOOP else []
            post = enc[2:] if pre else enc
            if rotated:
                # Counterclockwise, in degrees: the stored frame is turned 90 counterclockwise, so turn it back.
                # -noautorotate, or FFmpeg rotates the pixels itself and writes no display matrix.
                pre = pre + ["-display_rotation", "-90", "-noautorotate"]
            subprocess.run([ffmpeg, "-v", "error", "-y"] + src + pre + ["-i", str(raw)] + post + loc + [str(out)],
                           check=True)
            if ext == "mxf" and label == "center":
                # ST 377-1 value 1, horizontal mid-point; FFmpeg can only write 4:2:0 values for center.
                out.write_bytes(set_mxf_color_siting(out.read_bytes(), 1))
            print(out.name, out.stat().st_size)


if __name__ == "__main__":
    main()
