Skip to content

bwdif_videotoolbox: a Metal (GPU) bwdif whose output matches CPU bwdif exactly (tested on macOS only) #1102

Open

Description

@classicjazz

What should the engine do?

A new FFmpeg filter, bwdif_videotoolbox: FFmpeg's bwdif deinterlacer as a Metal compute kernel over VideoToolbox frames. It is used the same way as yadif_videotoolbox:

format=nv12,hwupload,bwdif_videotoolbox=mode=send_field:parity=auto:deint=interlaced

Its output is identical to CPU bwdif, frame for frame and sample for sample. The FFmpeg patch, the FFmpegBuild changes and a standalone test program are attached (bwdif-videotoolbox-files.zip), written with Claude Code. I'm not a software engineer, and it has only been tested on a Mac, so please treat it as material for you to use, rework or replace, not as a PR.

This solves two things at once. The new filter does both, and each can be judged on its own:

What it does Also proposed for yadif?
1. bwdif on the GPU The deinterlacing algorithm of CPU bwdif, as a Metal kernel, with identical output No, this is new
2. One GPU submission per frame Both planes of a frame go to the GPU together, with one wait, instead of one submission and one wait per plane Yes: the same change for yadif_videotoolbox is issue #1101

Part 2 is in this filter so it does not start out with the slower design. If #1101 is taken, yadif_videotoolbox and bwdif_videotoolbox submit work the same way, and comparing them compares only the algorithms. If #1101 is not taken, this filter is the only one with part 2. That is fine for correctness, but in a speed comparison bwdif gets an advantage that has nothing to do with the algorithm.

Adding the filter to the build changes nothing for current hosts. AetherEngine keeps using yadif_videotoolbox unless it is switched in a separate change.

Motivating media or use case

On every interlaced source (ATSC 1.0 live TV, 1080i and 480i recordings, DVD rips), AetherEngine deinterlaces in one of two ways:

Path Filter Where it runs
Default (DeinterlaceMode.auto) yadif_videotoolbox GPU
Fallback, or .software bwdif CPU
  • The two paths run different algorithms, so the picture depends on which path a session got.
  • build.sh already names bwdif the CPU primary for better quality. It adds a longer vertical filter to yadif, with the coefficients of the BBC's Weston 3 field deinterlacer.
  • Upstream FFmpeg has GPU bwdif for CUDA and Vulkan, but not for Metal (n8.1.3 or master). AetherEngine#107 picked yadif_videotoolbox because it was the Metal deinterlacer that existed. A Metal bwdif port was described in that thread but never published.
  • A GPU bwdif would let the GPU path and the CPU fallback show the same picture, and would take bwdif's work off the CPU, which on an Apple TV is also decoding the video.

bwdif-videotoolbox-files.zip

Area

Performance

Host app / integration context

No response

Would you be willing to open a PR?

No

Activity

  1. added
    enhancement
    on Nov 21, 2026
  2. classicjazz commented on Nov 21, 2026

    @classicjazz
    Author

    Everything below was measured on an Apple M1 Max, macOS 27.2, FFmpeg n8.1.3. Nothing has run on an Apple TV, iPhone or iPad, and build.sh has not been run.

    What's attached

    File What it is
    bwdif-videotoolbox.patch FFmpeg patch, 712 lines, applies to n8.1.3 with git apply
    ffmpegbuild-changes.diff build.sh, FilterAvailabilityTests.swift and README.md changes. The patch above goes in patches/
    bwdif-kernel-test/ A standalone macOS program that compares the kernel with bwdifdsp.c, sample by sample
    README.txt Build and run lines for the test program

    FFmpeg patch

    File Change
    libavfilter/metal/vf_bwdif_videotoolbox.metal New, 182 lines. The kernel.
    libavfilter/vf_bwdif_videotoolbox.m New, 479 lines. The filter wrapper.
    libavfilter/allfilters.c +1: extern const FFFilter ff_vf_bwdif_videotoolbox;
    libavfilter/Makefile +4: objects, shaped like the yadif_videotoolbox entry.
    configure +1: bwdif_videotoolbox_filter_deps="metal corevideo videotoolbox", the same as yadif_videotoolbox.

    FFmpegBuild

    File Change
    build.sh A patch_ffmpeg_bwdif_videotoolbox step after the existing patches. It skips if the filter file exists and stops the build if the patch does not apply, like the other patches/ steps. --enable-filter=bwdif_videotoolbox next to yadif_videotoolbox.
    FilterAvailabilityTests.swift A test that bwdif_videotoolbox, yadif_videotoolbox and hwupload are in the build.
    README.md Filter lists, patch count, and a bullet for the new patch.

    The kernel

    It does bwdif's integer arithmetic, held in floats. GPUs run float math faster than 32-bit integer math, and a float holds every whole number up to 2^24 (16,777,216) exactly.

    1. Each texel is read back as the integer sample the CPU sees (scale is 255 or 65535, shift is 6 for P010).
    2. bwdifdsp.c's arithmetic runs on those values, two channels at a time for the interleaved UV plane. For samples of up to 10 bits the largest value reached is about 15.6 million, so nothing is rounded. Each right shift x >> n becomes floor(x * 2^-n), which matches C on negative values too.
    3. The result is written back so P010's low six bits stay zero.

    The limit is 10 bits. Deeper formats would pass 2^24, so the filter refuses them with an error (Pixel format p416le is deeper than 10 bits, which is not supported). AetherEngine only sends NV12 and P010.

    Rows follow vf_bwdif.c:

    Rows Filter CPU equivalent
    Kept field Copied through memcpy
    Last field of the stream Spatial only filter_intra
    Top 4 and bottom 4 rows No high-frequency term; spatial check only away from the outermost 2 filter_edge
    All other rows Full temporal and spatial filter filter_line

    Kernel cost alone, both planes of a 1080 frame, GPU time:

    Kernel NV12 P010
    Plain integer math 0.178 ms 0.185 ms
    Integer math in floats (attached) 0.138 ms 0.147 ms
    GPU yadif, for reference 0.113 ms 0.125 ms

    The wrapper

    Copied from vf_yadif_videotoolbox.m, with these differences:

    • Parameters: field_end, shift, scale and clip_max per plane, from the plane's AVComponentDescriptor.
    • Options: bwdif's. mode defaults to send_field, like CPU bwdif.
    • Size and depth limits: planes under 3 columns or 4 rows are refused with vf_bwdif.c's message; formats deeper than 10 bits are refused.
    • One GPU submission per frame (part 2 above, the same change as yadif_videotoolbox: send each frame to the GPU once, not once per plane (about 30% faster on macOS, same output) #1101 ): one command buffer and one encoder per frame, one dispatch per plane, each plane's parameters passed by value with setBytes, one commit and one wait. The CVMetalTextures are released after the wait, because the GPU reads them until then. There is no shared parameter buffer.
    • Autorelease pool: the Metal work is wrapped in @autoreleasepool, the same fix patch_ffmpeg applies to the yadif filter.

    Frame history, field order, send_field timing and end of stream come from yadif_common.c, unchanged.

    Testing

    1. Kernel against bwdifdsp.c. The attached program runs the kernel on the GPU and compares every output sample with bwdifdsp.c compiled from n8.1.3, driven row by row as vf_bwdif.c does. It covers 8-bit and P010-style 10-bit, one and two channels, ten sizes from 37x4 to 960x540, noise, gradients, moving edges and rings, both parities, both field orders, and the end-of-stream field.

    Result: 1,280 cases, 167,190,144 samples, 0 differences. The test can fail: with the CUDA typo below planted in the kernel, it reports 7,274,433 differences.

    2. Whole filter inside ffmpeg. Each input through both chains, framemd5 compared line by line:

    CPU:  format=yuv420p,bwdif=<opts>,format=yuv420p
    GPU:  format=nv12,hwupload,bwdif_videotoolbox=<opts>,hwdownload,format=nv12,format=yuv420p
    
    Input Frames out (send_field / send_frame) Result
    1080i29.97 TFF, MPEG-2 in MPEG-TS 480 / 240 identical
    Same, deint=interlaced 480 / 240 identical
    480i BFF, MPEG-2 480 / 240 identical
    1080i scrolling color bars 480 / 240 identical
    1080i 10-bit (P010), parity=tff 200 / 100 identical
    480i BFF forced to parity=tff 480 / 240 identical
    Off-air CBS, ATSC 1.0, 1080i MPEG-2, 31 s from my HDHomeRun, parity=auto:deint=interlaced 1,668 / 834 identical

    Controls: GPU yadif against CPU yadif differs on every frame, and so does GPU yadif against GPU bwdif on the CBS capture, so the comparison does catch differences.

    3. Picture quality against known originals. Five 59.94p sources, interlaced with tinterlace, deinterlaced at field rate, scored against the originals. Luma PSNR in dB, higher is better. GPU bwdif equals CPU bwdif here because the output is identical.

    Source GPU yadif GPU bwdif
    Moving test pattern, 1080 37.24 37.64
    Rotating test pattern, 1080 41.08 39.76
    Scrolling color bars, 1080 38.07 37.27
    Zooming fractal, 480 30.84 30.64
    Smooth pan and zoom, 1080 46.08 51.81

    bwdif wins clearly on the smooth pan (+5.7 dB) and loses on hard-edged synthetic patterns (by up to 1.3 dB). On the CBS capture, the two GPU filters average 48.8 dB against each other, and zoomed stills of the frames where they differ most show no visible difference.

    4. Speed. 1080i29.97, send_field, 480 frames out, nine alternating runs, the same method as #ISSUE1. Per field-rate frame:

    Filter One submission per plane One submission per frame
    GPU yadif 0.81 ms (today) 0.57 ms (with #1101 )
    GPU bwdif 0.93 ms 0.65 ms (this patch)
    • For a fair comparison, compare within a column. bwdif costs about 0.1 ms per frame more than yadif either way; that difference is the algorithm.
    • Across columns, the 0.28 ms between 0.93 and 0.65 is part 2, the submission change, the same saving #ISSUE1 gives yadif.
    • Against today's yadif (0.81 ms), this patch's bwdif is 0.16 ms faster, but only because it has part 2 and today's yadif does not.

    Both are far inside the 16.7 ms of a 59.94 fps frame. Both are far inside the 16.7 ms of a 59.94 fps frame. CPU bwdif is about 0.8 ms of one core on an M1 Max performance core (NEON); on an Apple TV the figure that matters is CPU load, which I have not measured.

    5. Build. The patch applies with git apply --check to a clean n8.1.3. configure sets CONFIG_BWDIF_VIDEOTOOLBOX_FILTER 1. The wrapper compiles with no warnings. zsh -n build.sh passes.

    Upstream bugs found (not fixed here)

    From reading the other GPU versions in n8.1.3. Not tested on those filters, and neither is built for Apple platforms, so FFmpegBuild is not affected.

    Filter Finding Status
    bwdif_cuda vf_bwdif_cuda.cu:94 uses next2_mrefs4 twice in the high-frequency term; the second should be next2_prefs4 (compare bwdifdsp.c:89). Still on release/8.1 at 660b5aa; fixed on master at 2473872.
    bwdif_cuda The temporal average d is taken from prev and next in every field, where the CPU and Vulkan versions use the frames holding the row's field. Not checked against master.
    bwdif_vulkan bwdif.comp.glsl never loads next2[4] when field_parity is false, but the high-frequency term reads it. Not checked against master.

    A Metal port translated from the CUDA kernel may carry the first two.

  3. superuser404notfound commented on Nov 21, 2026

    @superuser404notfound
    Owner

    Thanks, this is in, and it is the default GPU deinterlacer now.

    FFmpegBuild 3.17.0 ships bwdif_videotoolbox from your patch. Your kernel is unchanged. The wrapper got the same failure handling as the yadif patch from #1101, plus one more change from review. Formats the kernel cannot run (packed, more than two channels per texel, deeper than 10 bits, planes under 3x4) are now refused when the graph is configured. Before, they configured fine and failed on every frame, and a 16-bit source allocated its output pool just to be refused.

    I checked it myself with a small macOS ffmpeg built from the same tree, CPU bwdif against bwdif_videotoolbox. framemd5 matched on every frame for 1080i TFF and 480i BFF MPEG-2, testsrc2 at 1080 and at 38x10, NV12 and P010, both modes, parity auto and forced. A control (GPU yadif against CPU bwdif) differed on all 480 frames, so the comparison does catch differences. I left out the standalone kernel test program, because the whole-filter comparison covers the same ground. On an M1 a 1080p59.94 field cost 2.19 ms against 1.90 ms for yadif_videotoolbox in the same run. I also scored both against a progressive original on two La La Land scenes, interlaced and deinterlaced at field rate: bwdif came out 0.8 and 1.2 dB ahead in luma PSNR.

    AetherEngine main (2de4d3ae) builds bwdif_videotoolbox in DeinterlaceMode.auto and falls back to yadif_videotoolbox when bwdif's graph does not build. A GPU graph that errors while running still goes to the CPU, as before. deinterlace.filter in $sourceVideoStreamFormat names the one that runs. That part is not in an engine release yet. Bit-identity is shown on a Mac only, so the first Apple TV run will be the real check.

    I have not looked into the bwdif_cuda and bwdif_vulkan findings, since neither filter is built for Apple platforms.

    #1101 is upstream as FFmpeg PR 26244, with you as co-author. I'd like to take this one upstream too, once it has run on an Apple TV for a while. Shall I put you down as the author there, or do you want to submit it yourself?

  4. superuser404notfound commented on Nov 21, 2026

    @superuser404notfound
    Owner

    Released in 7.72.0. DeinterlaceMode.auto builds bwdif_videotoolbox there, with yadif_videotoolbox as the fallback.

  5. classicjazz commented on Nov 21, 2026

    @classicjazz
    Author

    Thanks for this.

    It's fine to add me as co-author to both issues upstream. I would prefer that you submit it as the owner of ffmpeg-build and all associated patches. I would recommend letting both soak before submitting. I am currently testing bwdif_toolbox using Sodalite 1.1 (15) watching sports (panning scenes and tickers) in 1080i. It seems to be working well on my Apple TV 4K (2026).

  6. superuser404notfound commented on Nov 22, 2026

    @superuser404notfound
    Owner

    Thanks, that works for me. I'll submit both as the owner with you as co-author, and I'll hold the bwdif one until it has run in TestFlight for a while. #1101 is already up as PR 26244, so that one gets its soak time during upstream review.

    Good to hear the sports test looks right. Build 15 has engine 7.72.0, so it should be bwdif. Stats for Nerds shows which filter runs on the deinterlace line. It should read bwdif_videotoolbox (GPU). If it ever shows yadif_videotoolbox or CPU on that box, please tell me, because that means the bwdif graph didn't build or failed while running.

  7. superuser404notfound commented on Nov 22, 2026

    @superuser404notfound
    Owner

    Change of plan on the timing. Since it already runs in the beta, I submitted it now: FFmpeg PR 26276, with you as co-author. Upstream review takes a while anyway, so the soak time happens in parallel.

    Your kernel is unchanged. The wrapper follows master's yadif_videotoolbox, which now returns errors from filter(). framemd5 matches CPU bwdif again on master (NV12/P010, both modes, TFF/BFF/forced parity, and the MPEG-2 FATE samples). Your CUDA/Vulkan findings are in the PR text as not tested.

    Two side findings while testing, both pre-existing and not in the PR:

    • With deint=interlaced, a frame not flagged as interlaced passes through with hwupload's frames context, and a following hwdownload refuses it. yadif_videotoolbox on master does the same. It doesn't affect AetherEngine, which never downloads after the filter.
    • mpeg2_field_encoding.ts ends on a damaged picture, and its concealed area changes from run to run, so CPU and GPU get different input for the last frame.
  8. classicjazz commented on Nov 23, 2026

    @classicjazz
    Author

    Thanks for submitting the filter upstream to FFmpeg. Their review bot's findings on bwdif_videotoolbox are valuable, not just for this filter but all other Metal filters released or in-progress. I reproduced the build failure locally, and most of the other findings trace back to the yadif_videotoolbox template the filter started from.

    Question: are you planning to fix the issues noted in FFmpegBuild's bwdif-videotoolbox.patch and then send those commits upstream? If so, I'll retest your updated patch(es).

    What I checked

    Builds and code reading only, on macOS. Nothing new was run on a device.

    The build failure reproduces with clang -fsyntax-only -target arm64-apple-ios8.0 -Werror=partial-availability. The filter is annotated ios(8.0), but setBytes:length:atIndex: needs iOS 8.3. Our compile checks missed it because they build for tvOS/iOS 16 and later. This never affects AetherEngine's iOS/tvOS 18 targets, but upstream holds each annotation to its claimed minimum.

    The same findings likely apply the other Metal filters

    I turned each finding into a general rule and checked it against the other published Metal filters:

    Rule (bot finding) bwdif_videotoolbox yadif_videotoolbox (upstream master, 4dfdbc94c6) fieldmatch_videotoolbox (#1108) decimate_videotoolbox (#1108)
    Compiles at the deployment target the annotations claim (1) fails (setBytes, iOS 8.3) fails (MTLResourceStorageModeShared, iOS 9) fails (setBytes) fails (setBytes, MTLResourceStorageModeShared)
    A GPU failure returns an error, never an unwritten frame (2) fails ok (fixed upstream in Sept and Oct 2026) ok ok
    Output pixel buffer attachments are not left marked interlaced (3) fails fails (CVBufferPropagateAttachments copies the field count) fails (same; the output is progressive) ok (passes fieldmatch's frames through)
    Setup shared, not copied per filter (4) duplicated the original duplicated duplicated
    fate-hw test, like scale_cuda's (5) none none none none
    Copyright lines in the .metal and the .m (6) partial ok prose credit only prose credit only
    metallib extern matches bin2c's const unsigned char / const unsigned int (7) fails fails fails fails
    First and last frames match the CPU filter (8) finding n/a to check to check
    Every kernel parameter is read (9) channels unused tff, field_mode unused ok ok
    No pass-through frame from the input pool (pre-existing, yadif_common.c) affected affected n/a n/a
    P010 unpacking does not rely on a GPU reciprocal (conditional) at risk n/a to check to check

    Takeaways:

    • yadif_videotoolbox needs upstream changes for rules 1, 3, 7 and 9. The pass-through issue lives in yadif_common.c, so it affects bwdif and yadif alike, and AetherEngine runs deint=interlaced. These are probably best as small separate upstream commits ahead of bwdif.
    • fieldmatch_videotoolbox and decimate_videotoolbox (fieldmatch_videotoolbox + decimate_videotoolbox: the inverse telecine stages of #1105 on the GPU, output identical to CPU (exploratory, tested on macOS only) #1108) need rules 1, 6 and 7. fieldmatch also needs rule 3. They already propagate errors. The stream-edge check (8) still needs to be done for both.
    • Rule 4 is the one design question. Every filter repeats about 130 to 200 lines of device, library, pipeline, texture cache and output pool setup. A shared helper in libavfilter/metal/utils.{h,m}, like vulkan_filter.{c,h} for the Vulkan filters, would fix rules 1, 2, 3 and 7 in one place. It would also answer the duplication finding for every later filter. It does touch the bwdif and IVTC patches FFmpegBuild already ships.

    Filters I have not shared yet

    I have early versions of four more Metal filters for VideoToolbox frames. They are built and tested on an M1 Max only, and none has run on an Apple TV yet:

    Filter Based on
    deband libplacebo's pl_shader_deband (different from FFmpeg's vf_deband, so it gets a distinct name)
    dither libplacebo's pl_shader_dither and its blue-noise generator
    chroma upsampling libplacebo's chroma scalers (bilinear, lanczos, ewa_lanczossharp)
    deblock FFmpeg's vf_deblock, a bit-exact twin (not libplacebo)

    All four were started from the same template, so they carry most of the issues above. Before I share them, I'd like to agree on an updated Metal filter template as the baseline: the fixed bwdif or yadif, plus rule 4 if you want it. Then each one goes out clean, instead of repeating this review four times. libplacebo is LGPL-2.1-or-later like FFmpeg, and the files credit its authors.

  9. superuser404notfound commented on Nov 24, 2026

    @superuser404notfound
    Owner

    Thanks for going through all four filters, the table is useful.

    Most of the bwdif_videotoolbox column is already done. Fairy's review on 26276 raised the same points, and round 2 went up this morning as 1848189d28 (reply with the details):

    Rule State in 1848189d28
    1 Annotations are ios(8.3), builds for iOS 8.0, macOS 10.11 and tvOS 12 with -Werror=partial-availability
    2 Nil command buffer or encoder returns an error
    3 Field count and field detail are removed from processed frames after the propagate
    4 Not yet, see below
    5 Four fate-hw tests (NV12 and P010, both modes, TFF and BFF), reference CRCs are CPU bwdif on the same input
    6 Copyright blocks from bwdifdsp.c and the yadif .metal, BBC lines included
    7 const unsigned char[] and const unsigned int
    8 The tests run to the end of the stream, so both boundary fields are compared
    9 channels is gone
    Pass-through Documented in the filter's section, the fix for both filters is a separate patch
    P010 Integer shift instead of the reciprocal

    Your question. The fixes go upstream first, and FFmpegBuild follows. bwdif-videotoolbox.patch is still at round 1. I'll bring it to the upstream state once the review there settles, so it changes once instead of after every round. For AetherEngine only the P010 shift matters in practice. Field attachments never reach the screen, because the engine strips them from every filter output (FrameChainOutput.swift, inputGeometryKeys). To retest the current state now, use the PR branch. It is based on master, not on the n8.1 tag FFmpegBuild pins.

    yadif_videotoolbox. 26244 already covers rule 1, since it drops the shared MTLResourceStorageModeShared buffer and its setBytes annotation is now ios(8.3). Rules 3, 7 and 9 are left. They touch the same lines as 26244, so they go as small separate commits on top of it once it is in.

    fieldmatch and decimate (#1108). These are downstream only for now. Rules 1, 6 and 7, plus rule 3 for fieldmatch, get fixed when they go upstream, on the same template as bwdif. I'll run the stream edge check (8) for both at that point.

    Template and rule 4. For the four new filters I'd start from the bwdif wrapper in 1848189d28 now, including its fate-hw pattern with CPU reference CRCs. The shared helper in libavfilter/metal/ stays a separate factoring patch after 26244 and 26276 have settled, as I wrote on 26276. Moving filters onto it later is mostly mechanical, so I wouldn't hold the new ones back for it. If Fairy's next round changes the wrapper, I'll post it here.

  10. superuser404notfound commented on Nov 24, 2026

    @superuser404notfound
    Owner

    Small change to what I wrote above: the three yadif fixes (rules 3, 7 and 9) didn't need to wait for the merge. They are on 26244 now as separate commits on top, 89d34669f6 (note). Output is unchanged, framemd5 identical on 36 configurations. A probe that sets both field attachments on the input shows them on the output without the fix and gone with it. Each commit carries a Found-by: line with your name.

  11. classicjazz commented on Nov 25, 2026

    @classicjazz
    Author

    I separately shared two different debanding filters (one based on the ffmpeg default and one based on libplacebo) , a deblock, dither (based on libplacebo), and chroma (based on libplacebo) metal filters for your consideration. They, along with my earlier shared Metal filters, likely need copyright attribution cleanup not just for you and me but also other authors of prior art.

    I rebaselined these filters from the latest bwdiff wrapper and noted the need to add a shared helper later among other to-dos.

    After you review the filters and add them to the pipeline (graph v engine, as appropriate), I can test them against VOD and live TV video in a future Sodalite test flight.

    I also have been developing a checklist and benchmarks for which filters should be enabled for what video source, which video codec, which resolutions, given a particular client device's capabilities and other considerations. My focus continues to be 4K output on an Apple TV but we should also benchmark other Apple devices with different output resolutions.

  12. superuser404notfound commented on Nov 26, 2026

    @superuser404notfound
    Owner

    Thanks. I went through all five in their own issues, so the details are there: #1130 deband, #1131 debanditer, #1132 deblock, #1133 dither, #1134 chroma444. Each one got the fixes from the later bwdif rounds (clearing the attachments of a reused buffer, the range fallback, FATE tests gated on the formats they need), on local branches based on the current bwdif head. Nothing is pushed yet.

    Where they go from here:

    When one of them makes it into a build, I'll post in its issue. That is the point where your VOD and live TV runs help most.

    Checklist and benchmarks. Yes please, that is exactly the open question for deblock and deband. Could you open it as its own issue? This one is about bwdif and already long. The number I'd want first is GPU time per frame for each filter at 4K output on the Apple TV, next to the frame budget (16.7 ms at 60 Hz). Other devices are worth adding later.

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