Skip to content

fieldmatch_videotoolbox + decimate_videotoolbox: the inverse telecine stages of #1105 on the GPU, output identical to CPU (exploratory, tested on macOS only) #1108

Open

Description

@classicjazz

What should the engine do?

Two new FFmpeg filters that run the two stages of inverse telecine on VideoToolbox frames with Metal compute kernels:

  • fieldmatch_videotoolbox, a GPU fieldmatch.
  • decimate_videotoolbox, a GPU decimate.

Their output is identical to CPU fieldmatch and decimate: the same frames, timestamps, matches, combed flags and dropped frames.

This came out of the bwdif_videotoolbox work (#1102), in parallel with the engine work for #853 that landed in #1105. It is exploratory. It does not replace anything in #1105, which built the part I did not: the film check at load, the session handling, the timeline and the API. These filters would only swap two stages inside the chain #1105 builds.

The FFmpeg patch, the FFmpegBuild changes, the kernel tests and the comparison scripts are attached (ivtc-videotoolbox-files.zip), written with Claude Code. As with #1102, I'm not a software engineer and it has only run on a Mac, so please treat it as material to keep, rework or discard, not as a PR.

On the GPU engine, #1105's chain and the chain these filters would allow are:

main:      fieldmatch=order=auto:combmatch=full,decimate,format=nv12,hwupload,bwdif_videotoolbox=mode=send_frame:parity=auto:deint=interlaced
proposed:  format=nv12,hwupload,fieldmatch_videotoolbox=order=auto:combmatch=full,decimate_videotoolbox,bwdif_videotoolbox=mode=send_frame:parity=auto:deint=interlaced

Adding the filters to the build changes nothing for hosts. The engine keeps its CPU stages until DeinterlaceFilter is changed to use them.

What each piece brings over main

CPU time per input frame on an M1 Max (details under Testing 3):

Piece Replaces on main What it brings SD (480, 576) 1080
fieldmatch_videotoolbox CPU fieldmatch with combmatch=full Takes the most expensive stage off the CPU. Its cost stops depending on the picture. 1.6 to 6.0 ms becomes 0.1 to 0.6 ms 9.5 to 9.7 ms becomes 0.5 to 1.8 ms
decimate_videotoolbox CPU decimate Lets the frames stay on the GPU after fieldmatch_videotoolbox. Without it, the GPU fieldmatch would need a download and a second upload. No saving: about 0.2 ms either way 1.15 ms becomes 0.3 to 0.4 ms, upload included
Both, in #1105's chain The CPU stages before hwupload One upload at the head of the chain, then everything on the GPU 1.8 to 6.3 ms becomes 0.5 to 0.8 ms 10.7 to 10.9 ms becomes 1.0 to 1.8 ms

Motivating media or use case

1. It takes CPU time back at every resolution, and the most where it matters most. #1105's chain on the GPU engine against the proposed chain. One filter thread, two runs, minus a decode-only baseline, so the upload counts in both:

Clip Size main, CPU time Proposed, CPU time Saved Share of one core at 29.97 fps, main → proposed
3:2 film, clean 720x480 1.78 ms 0.48 to 0.56 ms 1.2 to 1.3 ms 5.3% → 1.6%
3:2 film with noise 720x480 6.27 to 6.28 ms 0.64 to 0.82 ms 5.5 to 5.6 ms 18.8% → 2.2%
3:2 film 720x576 2.19 to 2.22 ms 0.52 to 0.61 ms 1.6 to 1.7 ms 6.6% → 1.7%
3:2 film 1920x1080 10.88 to 10.94 ms 1.09 to 1.80 ms 9.1 to 9.8 ms 32.7% → 4.3%
Off-air CBS, ATSC 1.0 (true interlace), my HDHomeRun 1920x1080 10.69 to 10.78 ms 0.97 to 1.11 ms 9.6 to 9.8 ms 32.2% → 3.1%

Whether HD should be sampled is a separate decision, and the film check at load would still cost more at HD (see "What the engine would need").

2. The GPU cost does not depend on the picture. CPU fieldmatch at the same 720x480 costs 1.4 ms of wall time on clean film and 5.8 ms on the same film with noise, because its comb test branches on every pixel. #1105 measured 2.9 ms on the Friends DVDs, between the two. Grainy film, the usual NTSC DVD, is on the expensive side. fieldmatch_videotoolbox measured 0.8 to 1.4 ms of wall time on both clips, and at most 0.6 ms of CPU time.

3. Nothing that #1105 measured or tested changes. The output is identical, so these describe the proposed chain as well:

  • the film check at load and its thresholds;
  • the 23.976 timeline, and the re-anchor on a gap;
  • the tests in InverseTelecineChainTests.

The film check at load itself is not touched. It keeps CPU fieldmatch with combmatch=none and its own block measure.

What it costs.

  • The GPU chain's wall time is 1.2 to 3.0 ms a frame. Most of it is the filter thread waiting on the GPU, not working.
  • It is 2,156 lines of FFmpeg patch to carry, in the style of the yadif_videotoolbox and bwdif_videotoolbox patches already in the build.

Anything you tried instead?

  • Merging the two filters into one, to save GPU waits.
    • A commit-and-wait costs about 0.23 ms on the M1 Max. With decimate_videotoolbox waiting once per cycle, a merged filter would save about 0.05 ms per frame.
    • It would also need option names that match neither CPU filter. Both have blockx, blocky, chroma, scthresh and ppsrc, with different defaults.
    • So they stay two filters, each a mirror of its CPU filter.
  • Keeping CPU decimate after a GPU fieldmatch. That needs hwdownload after fieldmatch_videotoolbox and a second hwupload before bwdif_videotoolbox. CPU decimate is cheap at SD, so this would cost more than it saves.
  • Using fieldmatch's comb scores to tell film from video, in place of idet. On my synthetic pair, film and true video scored the same (medians 63 and 65). feat(deinterlace): inverse telecine for hard-telecined NTSC film (#853) #1105's worst-block cadence check solves this properly.

ivtc-videotoolbox-files.zip

Area

Performance

Host app / integration context

Sodalite

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

    Supplemental details

    Everything below was measured on an Apple M1 Max, macOS 27.2, FFmpeg n8.1.3 built locally with this patch and bwdif-videotoolbox.patch. Nothing has run on an Apple TV, iPhone or iPad, build.sh has not been run, and the engine has not been changed to use the filters.

    What's attached

    File What it is
    ivtc-videotoolbox.patch FFmpeg patch, 2,156 lines. Applies to n8.1.3 with git apply, with or without bwdif-videotoolbox.patch first
    ffmpegbuild-changes.diff build.sh, FilterAvailabilityTests.swift and README.md changes. The patch above goes in patches/
    ivtc-tests/harness/ A macOS program per filter that compares the kernels with vf_fieldmatch.c and vf_decimate.c compiled from n8.1.3
    ivtc-tests/*.sh The scripts behind every number here: test clips, CPU against GPU comparison, timing against main's chain, per-platform compile
    ivtc-tests/*-results.txt Their output from my runs
    README.txt Build and run lines

    FFmpeg patch

    File Change
    libavfilter/metal/vf_fieldmatch_videotoolbox.metal New, 336 lines. Six kernels.
    libavfilter/vf_fieldmatch_videotoolbox.m New, 1,022 lines. The filter.
    libavfilter/metal/vf_decimate_videotoolbox.metal New, 69 lines. One kernel.
    libavfilter/vf_decimate_videotoolbox.m New, 641 lines. The filter.
    libavfilter/allfilters.c +2, next to ff_vf_decimate and ff_vf_fieldmatch.
    libavfilter/Makefile +6, shaped like the yadif_videotoolbox entry.
    configure +2: *_filter_deps="metal corevideo videotoolbox", the same as yadif_videotoolbox.

    FFmpegBuild

    File Change
    build.sh A patch_ffmpeg_ivtc_videotoolbox step after patch_ffmpeg_bwdif_videotoolbox. It skips if the filter file exists and stops the build if the patch does not apply, like the other patches/ steps. --enable-filter for both, next to fieldmatch and decimate.
    FilterAvailabilityTests.swift A test that both filters are in the build.
    README.md Filter lists, patch count (sixteen to seventeen), and a bullet for the new patch.

    What the engine would need

    Claude's reading of AetherEngine main at 3820c494, not tried:

    • The chain. DeinterlaceFilter.swift:339 puts fieldmatch and decimate before format,hwupload when inverse telecine runs on the GPU engine, because decimate takes CPU frames only (class doc, line 69). With these filters the two stages would move after hwupload, as in the proposed line above.
    • Availability. inverseTelecineFiltersLinked (line 144) checks for fieldmatch and decimate. The proposed chain would also need fieldmatch_videotoolbox and decimate_videotoolbox, and would fall back to today's chain when either is missing.
    • A fallback for refused frames. fieldmatch_videotoolbox refuses, when the graph is configured, a frame height that is not a multiple of 4 and any pixel format other than NV12 (see below). The engine would then build feat(deinterlace): inverse telecine for hard-telecined NTSC film (#853) #1105's chain instead. feat(deinterlace): inverse telecine for hard-telecined NTSC film (#853) #1105's sources, 480 and 576 lines of 8-bit MPEG-2, are never refused.
    • Nothing else. The filters keep CPU decimate's timestamps (first frame plus one tick per kept frame), so breaksInverseTelecineCadence and the rebuild on a seek work the same.
    • Not covered: the film check at load at HD. TelecineCadenceProbe runs CPU fieldmatch and a Swift block measure on up to 300 frames inside a 2 s budget. These filters do not change that, and at 1080 it would cost more. That belongs to an HD follow-up, if there is one.

    How the filters work

    The GPU measures, the CPU decides. Each filter is a copy of its CPU filter with the loops over pixels moved to Metal:

    CPU code (n8.1.3) On the GPU
    build_abs_diff_mask + build_diff_map diff_map: the map of where the two fields differ a little or a lot
    The accumulation loop of compare_fields match_sums: the six sums (Pc, Pm, Pml, Nc, Nm, Nml), per 64 columns of a row
    The first half of calc_combed_score comb_mask: the [1 -3 4 -3 1] comb test on a candidate frame, read in place, never built
    The second half comb_count: combed pixels per half-block
    luma_abs_diff luma_diff, for combmatch=sc
    create_weave_frame weave: the output frame when the match is not the current frame
    calc_diffs (decimate) block_diff: absolute differences per half-block

    Why the sums are exact.

    • The kernels read the planes as unsigned integer textures (R8Uint, and RG8Uint for NV12's UV), so the samples are the same integers the CPU sees.
    • Each thread writes its partial sums, and the CPU adds them in 64 bits, as the CPU filters' uint64_t and int64_t totals do. Integer sums do not depend on order, so the totals are exactly the CPU's.
    • Everything after the loops is the CPU filters' code, unchanged: compare_fields' ratios, checkmm, the scene change and combed checks, decimate's choice of the frame to drop, and the timestamps.

    Round trips. A commit and wait costs about 0.24 ms, against 0.02 ms for the GPU work itself.

    • fieldmatch_videotoolbox scores every candidate the mode can ask for in one submission. A frame costs one wait, plus one more when the output must be woven (2 frames in 5 on 3:2 film).
    • The CPU filter scores lazily. The extra scores cannot change a result, because the decision code reads only the ones the CPU would have computed. The debug line shows only those, so it matches the CPU filter's line.
    • decimate_videotoolbox commits each frame's metric without waiting and waits once per cycle, because vf_decimate.c reads the metrics only when the cycle is complete.
    • Matched frames and kept frames go out by reference, with no GPU work.

    Supported, and refused when the graph is configured:

    Supported Refused
    Pixel format NV12 (what hwupload makes of 8-bit 4:2:0) Everything else (CPU fieldmatch takes only 8-bit planar input)
    fieldmatch mode pc, pc_n (default), pc_u pc_n_ub, pcn, pcn_ub
    fieldmatch options order, field, combmatch, mchroma, y0/y1, cthresh, combpel, scthresh, even blockx/blocky ppsrc, combdbg, chroma=1, odd block sizes
    decimate options All but ppsrc ppsrc
    Frame height A multiple of 4 (480, 576, 720, 1080) Others, such as 486 (see below)

    #1105's options (order=auto:combmatch=full, decimate defaults) are all supported.

    Testing

    1. The kernels against vf_fieldmatch.c and vf_decimate.c. The attached programs compile the two CPU filters from n8.1.3 and compare every number the decision code reads. The only change to vf_fieldmatch.c is one added line that copies compare_fields' six sums out before they are used.

    Covered Values
    Sizes 32x16, 37x16, 40x20, 64x24, 100x36, 176x144, 333x100, 720x480, 720x576, 1920x1080 (decimate: 16x16 to 1920x1080, odd sizes included)
    Content Noise, still frames (all three equal), moving hard edges, telecine-like field pairs, flat with sparse spikes, low noise
    compare_fields Every ordered pair of p, c and n, both fields, chroma on and off, with and without an exclusion band
    Comb score All five candidate frames, both fields, cthresh -1, 0, 4, 9, 20, blocks 16x16, 4x4, 8x32, 32x8
    decimate Blocks 4x4 to 512x512, chroma on and off

    Result: fieldmatch 15,000 cases (29,400 values), decimate 288 cases, 0 differences, the same on three runs.

    The test can fail. Planted bugs were caught:

    • one threshold changed from > 19 to > 18: 292 differences;
    • a wrong edge-row tap: 214;
    • a block one column short in decimate: 156.

    2. The whole chain inside ffmpeg. Each clip and option set ran through CPU fieldmatch,decimate and through the two new filters. They were compared on:

    • the framemd5 of the output, timestamps included;
    • fieldmatch's per-frame debug line (comb scores, match, combed flag);
    • decimate's per-cycle lines (both metrics per frame, which frame is dropped).
    Clips Option sets
    480i 3:2 film TFF and BFF, the same with noise, a zooming fractal, true 59.94i video at 480, 576i, 1080i 3:2 film, 31 s of off-air CBS (ATSC 1.0, 1080i MPEG-2) from my HDHomeRun combmatch full (#1105's), sc and none; modes pc, pc_n, pc_u; mchroma=0; forced order=bff:field=top; an exclusion band with cthresh=4:combpel=40 and 8x32 blocks; cthresh=-1; low scthresh. decimate: default (#1105's), chroma=0, 16x16 blocks, cycle=4, mixed=1, other thresholds

    Result: 80 of 80 combinations identical on all three comparisons. Between them they ran from 0 to 834 combed frames and from 0 to 208 dropped frames.

    Two details were needed to compare logs:

    • -loglevel repeat+debug, because FFmpeg otherwise collapses repeated lines at points that depend on thread timing;
    • logging decimate's metrics for the partial cycle at end of stream, as the CPU filter does.

    3. Speed against main (timing-engine.sh). One filter thread, best of three per run, two runs, minus a decode-only baseline. Per input frame, wall time / CPU time in ms:

    Chain 480 clean 480 noisy 576 1080 film 1080 CBS
    CPU fieldmatch=order=auto:combmatch=full 1.41 / 1.56 5.77-5.79 / 5.98-6.00 1.75-1.76 / 1.91-1.92 9.06-9.10 / 9.62-9.65 9.08-9.10 / 9.48-9.49
    CPU decimate 0.04 / 0.19 0.02-0.04 / 0.18-0.20 0.07 / 0.22-0.23 0.66-0.67 / 1.14-1.16 0.87-0.88 / 1.15
    hwupload alone 0.00-0.01 / 0.04 0.00-0.02 / 0.04 0.00-0.01 / 0.05 0.02-0.03 / 0.24-0.25 0.01-0.03 / 0.23-0.28
    hwupload,fieldmatch_videotoolbox 0.89-1.26 / 0.22-0.49 0.77-1.37 / 0.13-0.60 0.99-1.07 / 0.36-0.41 2.04-2.33 / 1.05-1.78 1.19-1.20 / 0.49-0.51
    hwupload,decimate_videotoolbox 0.27-0.29 / 0.18-0.19 0.20-0.25 / 0.08-0.11 0.22-0.23 / 0.09-0.11 0.08-0.19 / 0.29 0.39-0.42 / 0.37-0.41
    main's GPU-engine chain 1.64 / 1.78 6.21-6.24 / 6.27-6.28 2.18-2.20 / 2.19-2.22 10.72-10.75 / 10.88-10.94 10.68-10.69 / 10.69-10.78
    Proposed chain 1.23-1.38 / 0.48-0.56 1.65-1.84 / 0.64-0.82 1.39-1.41 / 0.52-0.61 2.45-2.97 / 1.09-1.80 2.63-2.67 / 0.97-1.11
    • The CPU numbers repeat to within 0.05 ms. The GPU numbers move more between runs (up to 0.6 ms), because they are mostly waiting, and the wait depends on the GPU's clock state.
    • CPU time of the GPU chains includes the upload and Metal's own overhead. On main the upload handles 4 frames in 5 (after decimate); in the proposed chain it handles all 5.
    • feat(deinterlace): inverse telecine for hard-telecined NTSC film (#853) #1105 measured decimate at 1.15 ms per SD frame on an M1 Pro, decode included. On my 480 and 576 clips it measured about 0.2 ms of CPU time. I have not looked into the difference. Either way, at SD decimate_videotoolbox is there to keep the chain on the GPU, not for speed.
    • Deferring the woven frame into the next frame's submission would remove one wait on 2 frames in 5. I did not do it, because it adds a frame to the seek preroll. feat(deinterlace): inverse telecine for hard-telecined NTSC film (#853) #1105 measured that preroll at 69 to 77 ms, against 43 to 45 ms without inverse telecine.

    4. Build.

    • The patch applies with git apply --check to a clean n8.1.3 and on top of bwdif-videotoolbox.patch.
    • configure sets both CONFIG_*_VIDEOTOOLBOX_FILTER. The macOS build has no warnings in the new files.
    • The kernels compile with xcrun metal for the AIR target of every build.sh slice I tried (tvOS 16, tvOS simulator, iOS 16, visionOS 1, macOS 14). The wrappers compile for the same targets with -Werror=partial-availability.

    Found along the way

    Where Finding
    vf_fieldmatch.c (n8.1.3), compare_fields On a plane with an odd number of rows, the last pass reads one row past the plane (srcnf at row height) and a tbuffer row that build_abs_diff_mask did not write for this frame. This is Claude's reading of the code, not something I saw go wrong. A 720x486 frame has a 243-row chroma plane. #1105's sources (480 and 576 lines) never hit it. The GPU filter refuses heights that are not a multiple of 4, so such a source would stay on CPU fieldmatch.
    vf_fieldmatch.c, compare_fields A pair that mixes p, c or n with b or u reads the row above the plane (nxtp -= nxt_linesize with a field base of 1), and the kernel test showed its sums changing from run to run. No caller passes such a pair (it is only ever called with c against p or n, or p against n), so the filter is not affected. Noted in case someone extends the modes.
    bwdif_videotoolbox, yadif_videotoolbox (both already in the build) With deint=interlaced, a frame that is not marked interlaced passes through by reference and keeps the upstream frames context, while the filter's output link has its own. hwdownload after it fails ("Input frame is not the in the configured hwframe context"). #1105's GPU chain already passes most frames through this way and plays on an Apple TV, so the engine is not affected. It only stops a test from downloading the output, which is why the full chain with bwdif_videotoolbox is compared on timing only.

    Not verified

    • Apple TV, iPhone, iPad. Nothing has run on a device. The waits that make up most of the GPU time may cost more or less on an A15 or A19, and the CPU savings are M1 Max numbers.
    • build.sh. Not run. The frameworks are not rebuilt, so the new FilterAvailabilityTests test fails until they are.
    • Inside AetherEngine. Measured in ffmpeg only. DeinterlaceFilter has not been changed to use the filters.
    • Real film sources. The film clips are synthetic, and the noise is generated, not real film grain. The only real capture is true interlace. I have not yet run an NTSC DVD episode or an ATSC recording of a film-sourced show.
    • The full chain's output against CPU. fieldmatch_videotoolbox,decimate_videotoolbox is compared frame for frame. The chain with bwdif_videotoolbox after it runs, but could not be compared through hwdownload (see above).
  3. superuser404notfound commented on Nov 22, 2026

    @superuser404notfound
    Owner

    Thanks a lot for this, and for shipping the harness and the scripts with it. They made checking it straightforward.

    I've taken both filters in. Where it stands:

    FFmpegBuild (main, not released yet). The patch is in as patches/ivtc-videotoolbox.patch, with three changes from your version:

    • decimate_videotoolbox advanced fid to the cycle length before it read the cycle's metrics. After a failed command buffer, the next frame (or the EOF flush) wrote one slot past the queue, and a failed submission left a frame in a slot the next one overwrote. A GPU failure now latches, and later frames are freed and refused.
    • fieldmatch_videotoolbox now has fieldmatch_init's two checks (blockx/blocky a power of two, combpel at most blockx * blocky), so both filters accept the same options.
    • A nil compute encoder fails the frame instead of committing half a command buffer, and a failed GPU weave reports AVERROR_EXTERNAL instead of ENOMEM.

    Your harness and matrix.sh gave the same result here on an M1: 0 differences in the kernels, and 63 of 63 combinations identical (I don't have your CBS capture). They now live in Tests/ivtc-videotoolbox/, because the GPU filters copy the CPU decision code and an FFmpeg bump could change one side only.

    AetherEngine (branch feat/ae1108-gpu-ivtc). On the GPU engine the chain becomes your proposed one. The CPU stages before the upload stay as the fallback in these cases:

    • the linked build doesn't have the filters;
    • the frames aren't 8-bit 4:2:0 (format=nv12 ahead of the GPU filters would subsample 4:2:2 chroma across the two fields of a combed frame before fieldmatch separates them);
    • the height isn't a multiple of 4;
    • the GPU filters fail to build or error. A running error keeps bwdif_videotoolbox and moves only the cadence to the CPU.

    The warm-up also builds the GPU cadence graph, and VideoDeinterlace.inverseTelecineIsHardware reports which one runs. A test compares the GPU chain with the CPU-cadence chain picture for picture after the download, and they match. aetherctl play on a telecined 480i clip runs at 24 fps with no lost frame, across a seek too.

    One correction to the numbers. Your timing counts user time only, and Metal's submissions show up as system time. On my M1 (not Max), with raw input so the MPEG-2 decoder's threads aren't counted, user plus system time per input frame:

    Source CPU stages GPU stages
    480i film, clean 1.8 ms CPU, 1.7 ms wall 1.5 ms CPU, 2.6 ms wall
    480i film, noisy 6.1 ms CPU, 6.3 ms wall 1.8 ms CPU, 3.7 ms wall
    576i film 2.3 ms CPU, 2.5 ms wall 1.8 ms CPU, 3.2 ms wall
    1080i film 11.5 ms CPU, 12.6 ms wall 3.5 ms CPU, 7.3 ms wall

    So the saving is real everywhere. On clean SD it's small, and the wall time goes up by about 0.8 ms. On grain and at 1080 it's large. Nothing has run on an Apple TV yet.

    Next is an FFmpegBuild release, then the engine pin and an engine release. Once it's in a TestFlight build, a run of a real NTSC DVD episode on your Apple TV would be the most useful check. With the matching Sodalite update, Stats for Nerds will show whether IVTC runs on the GPU.

  4. superuser404notfound commented on Nov 22, 2026

    @superuser404notfound
    Owner

    Released in 7.73.0 (bbcf3b8), on FFmpegBuild 3.19.0. Sodalite and AetherPlayer are bumped to it.

    A real NTSC DVD episode on your Apple TV is still the check I'd like most, once you have a build with it. Stats for Nerds will show IVTC (GPU) + bwdif_videotoolbox (GPU) when the GPU cadence runs, and IVTC (CPU) when it fell back.

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