Skip to content

dither_videotoolbox: libplacebo's dither as a Metal filter for VideoToolbox frames, exact integer output (tested on macOS only) #1133

Backlog

Description

@classicjazz

What should the engine do?

A new FFmpeg filter, dither_videotoolbox: libplacebo's pl_shader_dither as a Metal kernel that reduces VideoToolbox frames to a lower bit depth (P010 to NV12, P210 to NV16, P410 to NV24, P216 to P210, P416 to P410), with vf_libplacebo's dither option names and values and libplacebo's render presets.

format=p010,hwupload,dither_videotoolbox

The kernel works on integer code values, so every output sample is exactly defined and checked against a C reference. The FFmpeg patch, the tests and the timing scripts are attached (dither-videotoolbox-files.zip), written with Claude Code. As with #1102 and #1108, I'm not a software engineer and it has only run on a Mac, so please treat it as material to use, rework or replace, not as a PR.

Built on the template from #1102: the bwdif_videotoolbox wrapper at 1848189d28. One commit on top of 26276.

FFmpeg has no dither filter of its own; its depth-reducing dither lives in libswscale. So there is no CPU filter to twin, but the five fate-hw tests still have CPU-computed references (Supplemental details). The five filters I'm filing:

Filter Kind Issue
deblock_videotoolbox Exact twin of CPU deblock #DEBLOCK
deband_videotoolbox Exact twin of CPU deband #DEBAND
debanditer_videotoolbox libplacebo's deband #DEBANDITER
dither_videotoolbox libplacebo's dither this one
chroma444_videotoolbox libplacebo's chroma scalers #CHROMA444

Adding the filter to a build changes nothing for current hosts.

dither-videotoolbox-files.zip

Motivating media or use case

One dither, at the end. A chain that keeps more precision than its output (deband to P010 as in #DEBANDITER, chroma to P416 as in #CHROMA444, or a 10-bit source shown on an 8-bit route) has to reduce to the output depth once, at the output size, or rounding brings the bands back. #957's plan lists dithering after tone mapping, as a FrameChain stage, which works on half-float RGB; so this filter is not that stage. It could run in a graph, and its integer rule and matrices are a tested reference for such a stage (the same rule and the same matrix, not bit-identical output, since the stage starts from float RGB).

What it costs, per frame, one filter thread, wall time / CPU time (Testing 3). FFmpeg's CPU way to do the same job is swscale's 10 to 8-bit conversion with its own dither, a different method:

Input swscale p010 to nv12 (CPU time) dither_videotoolbox, blue noise preset=fast (rounding)
1080 P010 0.9 ms 0.15 to 0.2 ms / 0.3 ms 0.05 to 0.1 ms / 0.2 ms
2160 P010 3.7 ms 0.3 ms / 0.6 ms 0.2 ms / 0.45 ms

Area

Performance

Host app / integration context

No response

Would you be willing to open a PR?

No

Activity

  1. added
    enhancement
    on Nov 25, 2026
  2. quint-aether commented on Nov 25, 2026

    @quint-aether

    This is one of a set of GPU filter proposals built on the bwdif_videotoolbox template from #1102, and it ties into the dithering step planned in #957.

    The table in the body still has placeholders. Going by the open issues, they map to:

    Other related threads are #1108 (fieldmatch_videotoolbox and decimate_videotoolbox) and #957 (the opt-in FrameChain processing stage, which lists dithering after tone mapping). The attached patch is kept here as reference material. Whether and how to use it is up to the maintainer.

    Automated triage by Quint (Claude). A maintainer reads every issue and will follow up.

  3. classicjazz commented on Nov 25, 2026

    @classicjazz
    Author

    Everything below was measured on an Apple M1 Max, macOS 27.2.1. Nothing has run on an Apple TV, iPhone or iPad.

    What's attached

    File What it is
    dither-videotoolbox.patch FFmpeg patch, one commit. Applies to master with PR 26276 at 1848189d28
    tests/ The CPU-reference anchors and fate reference check, e2e.sh against dither_ref_tool with its controls, the tiny-size and commands checks, the kernel test and bench sources, the availability compile check, results
    timing/ timing.sh (all five filters), extra.sh, results
    README.txt Layout, build and run lines, expected results
    File in the patch Lines What
    libavfilter/metal/vf_dither_videotoolbox.metal 270 Two kernels (per plane, and both planes of a two-plane frame)
    libavfilter/vf_dither_videotoolbox.m 760 The wrapper
    libavfilter/dither_noise.{c,h} 204, 46 The blue noise and Bayer matrices
    doc/filters.texi +92 New section
    tests/fate/filter-video.mak, refs +32, 5 refs Five fate-hw tests
    configure, Makefile, allfilters.c, Changelog, version.h +7 Registration; libavfilter minor 13 to 14

    What it is

    • Source: libplacebo src/shaders/dithering.c and src/dither.c, LGPL-2.1-or-later, read at commit cb1ad12c. The blue noise generator is Wessel Dankers' (2013), from mpv by way of libplacebo; the white noise is pcg3d (Jarzynski and Olano).
    • Methods: blue noise, ordered (Bayer), ordered_fixed, white noise, none. libplacebo's 8-frame temporal mode is mapped to the eight symmetries of the matrix.
    • Options: vf_libplacebo's dithering, dither_lut_size, dither_temporal (off by default, as in libplacebo), plus preset (fast: rounding; default and high_quality: blue noise, 64x64, static), format, depth, planes. dithering=auto and dither_lut_size=0, the defaults, take the preset's value. Unlike vf_libplacebo, where dithering and dither_temporal are runtime commands, none of them is (Testing 4).
    • Matrix size: the 64x64 blue noise matrix is generated once per process (14 ms). Larger ones are generated at every configuration: graph setup measured 0.5 s at 128x128 and 8.2 s at 256x256. The docs and the warning say so.
    • Depth: depth below the format carries a lower target in a deeper format, limited range only. For 4 bits or less libplacebo also corrects for gamma; this filter does not, and the docs say so.
    • Exactness: integer code values and 32-bit integer math (the float form of the rounding rule, for a fused stage, lives in the kernel test, not in the filter); limited range on a shifted grid (one step is one code of the target depth), full range on a scaled grid. Ties in the noise generator are broken with a fixed generator instead of rand(), so the matrix is the same on every run.
    • Pass-through: when neither format nor depth changes, the output link takes the input's frames context.

    The template points

    Point Here
    Availability macos(10.11), ios(8.3). The earlier version claimed ios(8.0) and failed the iOS 8.0 build on setBytes and twice on MTLResourceStorageModeShared (iOS 9); the matrix buffer now uses MTLResourceCPUCacheModeDefaultCache, the same value, 0. 0 errors at iOS 8.0, tvOS 12.0, macOS 10.11 (x86_64)
    Context The template's typed context with its computed size and static_assert
    Nil checks, one command buffer, formats in config_output Yes. A full range frames context with depth below the format is refused there too; a full range frame is still checked per frame
    Attachments The new depth is the pixel buffer's own format; nothing to remove
    Copyright, const externs, every parameter read, integer unpacking Yes

    Testing

    1. fate-hw, all five references computed on the CPU.

    Test Reference
    blue-8bit 8-bit content shifted into P010 must come back unchanged under any dither, since no bias in [0, 1) crosses a step. Reference: the 8-bit source. (Checked under all six methods.)
    fast Round to nearest, against lutyuv with min(floor((val+2)/4),255)*4. That differs from plain swscale 10 to 8, so the test is not trivial
    ordered2, ordered2-joint The 2x2 ordered matrix [[0,2],[3,1]] ff_dither_bayer builds, applied with geq (B = 2*((x+y) mod 2) + (y mod 2)), through each kernel
    depth4 preset=fast:depth=4: round to a 4-bit target in NV12, against lutyuv with min(floor((val+32)/64),15)*64. (anchors.sh also checks depths 1, 6 and 7.)

    All five identical to their CPU references. Real dithering changes all 10 frames against fast.

    2. Against dither_ref_tool, a C reference of the same dither including the blue noise matrix, every byte, inside ffmpeg. 42 cases: every method, temporal, joint, full range, 1920x1080, 720x480 and 853x481, p010, p210, p216, p416. 42 of 42 identical.

    The comparison can fail: the same blue-noise output checked against the reference for ordered, temporal, full range, a 32x32 matrix or no dither differs in 9.1 to 11.6 million bytes; these five controls are at the end of e2e.sh. dither_ref_tool builds its matrices from the patch's own dither_noise.c; what checks the matrices is the kernel test. Run against the installed libplacebo 7.387.0 (build.sh without a checkout, --installed): Bayer identical to pl_generate_bayer_matrix at every size from 2x2 to 256x256, and the kernels match the CPU reference on 5,346 cases, 484 million samples, 0 mismatches. Blue noise needs libplacebo's source with rand() replaced, since the installed library breaks ties with rand().

    Tiny and odd sizes (tiny-sizes.sh): 1x1, 2x2, 3x3, 37x11 and 39x9, every method, static and temporal, separate and joint: 100 of 100 identical to dither_ref_tool.

    3. Speed (timing/). Raw input, one filter thread, best of three, minus reading and hwupload (GPU) or reading (CPU), CPU time as user plus system. Two runs:

    Chain 1080 wall ms 1080 CPU ms 2160 wall ms 2160 CPU ms
    swscale p010 to nv12 (CPU, reference job) 0.21 / 0.22 0.90 / 0.91 0.22 / 0.18 3.81 / 3.74
    dither_videotoolbox (blue noise) 0.18 / 0.14 0.33 / 0.28 0.33 / 0.32 0.60 / 0.61
    preset=fast 0.04 / 0.08 0.16 / 0.23 0.22 / 0.16 0.47 / 0.43
    planes=joint 0.13 / 0.15 0.29 / 0.29 0.30 / 0.32 0.56 / 0.59

    The reader runs in its own thread, so wall minus baseline is a lower bound, and here it hides almost all of swscale's work (3.7 ms of CPU against 0.1 ms of wall time at 2160 with scale=threads=1, in extra-results.txt). Read CPU time. The dither rows run on noise1080.p010 and noise2160.p010; the command that made them wasn't recorded, and the README gives one that makes equivalent inputs. planes=joint isn't the default: on the M1 Max it measured 3 to 8% slower in the kernel bench; it stays an option to measure on Apple TV GPUs.

    4. Runtime commands and option bounds (commands.sh, 10 frames of testsrc2). No runtime commands: dithering, dither_temporal, dither_lut_size, depth and preset sent with sendcmd get Function not implemented, enable gets Not yet implemented, a following ping answers, and 0 of 10 frames change. Out-of-range values are refused at init (dither_temporal is now a plain bool, so -1 is too), and an output format without the input's planes, or deeper than the input, is refused at configuration. The same options set at init change the output, as the control.

    Open tasks

    Shared by all five filters (the same list in #DEBLOCK, #DEBAND, #DEBANDITER, #CHROMA444 and this one):

    • The shared Metal helper (rule 4 from bwdif_videotoolbox: a Metal (GPU) bwdif whose output matches CPU bwdif exactly (tested on macOS only) #1102). Each filter repeats about 150 to 200 lines of device, library, pipeline, texture cache and output pool setup, as bwdif_videotoolbox does. You planned the helper in libavfilter/metal/ as a separate factoring patch once 26244 and 26276 have settled; these filters would move onto it afterwards, mostly mechanically. Not done here, on purpose.
    • The metallib's Metal language version. FFmpeg builds the metallib with xcrun -sdk macosx metal and no -std, so the oldest OS that can load the library comes from the SDK, not from the API_AVAILABLE annotations. A kernel that uses newer features (deblock's SIMD-group attributes need MSL 2.0, macOS 10.13 / iOS 11) fails cleanly in newLibraryWithData on an older OS, with an error. A -std per target, or annotations that follow the language version, would settle it for every Metal filter.
    • Timeline and the pass-through fix. None of these filters supports enable: a timeline bypass would hand on input frames with the input's frames context, the pre-existing problem from Fairy's review that you're fixing separately for yadif and bwdif. Timeline support could follow that fix.
    • FFmpegBuild. The patches are on master with 26276 and don't apply to n8.1 as they are; there is no FFmpegBuild diff with them.
    • Overlapping lines. All five and bwdif add a Changelog line and the same libavfilter minor bump, so the patches touch the same lines there. Stacked on the others, this one also conflicts in tests/fate/filter-video.mak with all four and in doc/filters.texi with deblock and deband.
    • Engine integration. Where each filter would run (in a graph, or as the math behind a FrameChain stage under Opt-in video processing stage (HDR tone mapping, debanding, dithering, chroma upsampling, 3D LUT) on the software path #957), what option turns it on, and what the stats should show. Not decided, and not proposed here.
    • Devices. Nothing has run on an Apple TV, iPhone or iPad (see "What I can test" below).
    • Docs build. The doc/filters.texi sections are unbuilt (no makeinfo here).

    This filter:

    • Blue noise against libplacebo's src/dither.c: needs a libplacebo source tree (the kernel test's build.sh with a checkout); not re-run since the port. Everything else in the kernel test was re-run against the installed library.
    • What HDMI carries for P010 SDR. The software route already hands 10-bit SDR to the display layer as P010 (AetherEngine ce3f7f35, audit DEC-107). Not checked: whether tvOS sends 10 bits to the TV, which decides whether a dither to 8 bits is needed at all on that route.
    • planes=joint on Apple TV GPUs. It measured slower on the M1 Max, so it isn't the default; worth one measurement on an A15 or A19.
    • The order of stages around it (deband, chroma, ML, MetalFX, then dither last) is a design assumption from my notes, not something you have agreed to.
  4. superuser404notfound commented on Nov 25, 2026

    @superuser404notfound
    Owner

    Thanks for this one too. Same base as the other three: 26276 round 4 (6efb91b844) on an M1.

    What I checked

    • The patch applies cleanly, builds without warnings, and the five fate-hw tests pass.
    • Your first open item, blue noise against libplacebo's source. I compiled libplacebo's src/dither.c at cb1ad12c with rand() swapped for your generator and the same seed. Every blue noise matrix from 4x4 to 256x256 is identical to ff_dither_blue_noise, and each one is a permutation. Bayer is identical from 2x2 to 256x256. So the tie-breaker really is the only difference.
    • A reference of my own, written from libplacebo's dithering.c and sh_prng rather than from dither_ref_tool. The temporal position is computed the way the shader does it, fract(rot * pos + 1) in float with the matrix uploaded column-major. pcg3d and the fixed Bayer come from the GLSL, the matrices from libplacebo's dither.c, and the rounding is exact. 177 cases, 10 frames each so all eight phases plus the wrap: every method, LUT sizes 1, 2, 3, 4 and 6, static and temporal, separate and joint, 1920x1080, 853x481 and 37x11, p010, p210, p410, p216 and p416 in, full range on both grids, and depths 1, 4, 6, 7 and 8. 177 of 177 identical.
    • Controls that must differ, and do. With the rotation matrix transposed, 557,433 of 6,161,070 bytes differ, so your symmetry table follows libplacebo's column-major upload and not the transposed reading. Static against temporal, full against limited range, a 32x32 against the 64x64 matrix, and none against blue noise all differ too.
    • Refusing blue noise at dither_lut_size=1 is right. libplacebo's generator divides by gauss_radius, which is 0 there.
    • The wrapper compiles with no availability errors at iOS 8.0, tvOS 12.0 and macOS 10.11.

    Three fixes from the later bwdif rounds

    The same three as in #1131 and #1132. The comment above CVBufferPropagateAttachments makes the same assumption as deblock's table did. The format change isn't the problem, the reused pixel buffer is.

    1. CVBufferRemoveAllAttachments before propagating. Six P010 frames, each output freed right away so the pool hands back the same buffer, only the first input tagged HLG. Before, all six outputs carried HLG. After, only the first.
    2. The range falls back to the link's color_range when the input frames context leaves it unspecified. The resolved range is kept for frames that carry none. Here it matters in two places. With a full-range link the pool was 420v, now 420f. And depth=6 on a full-range link used to pass configuration and then fail the first frame with EINVAL; now it is refused at configuration, as your comment there intends. The grid itself came out right in my probe either way (code 1000 to 249), because buffersrc still handed the frame on with the link's range.
    3. All five fate-hw tests are P010 in, so the whole list sits behind HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE.

    There is no process_command, so the fourth fix from #1130 doesn't apply. FATE and all 177 cases pass again with the fixes in place. They sit as a second commit on top of yours on a local branch.

    Your other open items

    • What HDMI carries for P010 SDR: I haven't checked it either. Nothing in the engine reduces depth today. Since ce3f7f35 the software route keeps P010, and the Dolby Vision shader already has its own dither down to 10 bits. So there is no place for this filter in the current pipeline, and the HDMI question only matters once a stage produces more bits than the route carries.
    • The order of stages: Opt-in video processing stage (HDR tone mapping, debanding, dithering, chroma upsampling, 3D LUT) on the software path #957 still puts dither last, after tone mapping. Because that stage works on half-float RGB, this filter would be its tested reference rather than the code that runs, as you wrote.

    What happens next

    Same as the other filters. Nothing goes upstream before 26276 is merged and the shared Metal helper is in. Then the filters move onto it and go up one at a time, with you as co-author.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: videoenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions