Skip to content

fix(dovi): bound the fel compose stall, keep two compositions in flight and compose in place as read_write - #970

Closed
pkajaba wants to merge 11 commits into
superuser404notfound:mainfrom
pkajaba:pr/fel-robustness
Closed

pkajaba wants to merge 11 commits into
superuser404notfound:mainfrom
pkajaba:pr/fel-robustness

Conversation

@pkajaba

@pkajaba pkajaba commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Five changes to the Profile 7 FEL (dual-layer) route, all behind the DualLayerDolbyVision trait:

  1. Two compositions in flight, pool reserve independent of that limit (perf(dovi)). Two in-flight compositions cover the measured compose latency; the output pool reserve no longer follows the in-flight limit.
  2. Compose queue with a bounded, reported compose stall (feat(dovi)). Frames are composed on a queue of their own instead of on the VideoToolbox callback thread. If the GPU stops completing, queued frames go out as the base layer with the RPU that keeps their mapping. After 600 such frames, or the 4th stall episode without 240 healthy compositions in between, the decoder reports VideoDecoderError.composerStalled once, so the host stops instead of retrying forever. The inverse-NLQ table and MMR coefficients are read from per-frame tables, and the enhancement layer is upsampled with exact weights and rounded half up (at most one code of difference on 0.1 to 1% of samples, the exact ties).
  3. No output-metadata copy on the dual-layer route (fix(dovi)). The composer writes into the decoded base-layer buffer, so the copy of every frame into a 4K pool only costs memory there. Single-layer paths, the enhancement decoders and the software host keep it.
  4. In-place compose binds each plane once, as read_write (fix(dovi)). Replaces the double binding of one texture (read and write) in a kernel. The in-place kernels are built only on a device reporting read/write texture tier 2; below it the pool path is used. One default-level log line reports the tier and whether in-place is on.
  5. Annex B chroma filter for the enhancement layer (feat(dovi)). The enhancement chroma is upsampled with the 8-tap Annex B filter instead of the bilinear read. This changes picture bits: chroma stays within one 12-bit code of the spec model, except 3 Cb samples of one clip at a maximum error of 2. GPU cost is about +0.2 to +0.7 ms per 4K frame on the Mac.

Tested on Mac

  • swift build --build-tests --traits DualLayerDolbyVision: builds, also after merging main (the probe, join and digest code from the merged inputs PR) into this branch; 140 focused tests in 9 suites pass on the merge.
  • Focused suites with the trait on (86 tests in 9 suites): DoviFelInPlaceComposeTests (in-place bit-for-bit against the pool path), BaseLayerCopyOptOutTests, DualLayerGpuSlotWaitTests, DoviCpuModelTests, DoviEnhancementUpsamplerTests, DoviFrameTablesTests, DualLayerDeadlineBypassTests, DoviComposeAsyncTests: pass. DocumentedConstantsTests (XCTest): passes after the docs and constants were aligned.
  • Earlier measurements of the same changes on the Mac: base-layer copy opt-out, 240 composed frames of two real FEL clips bit-identical with and without it, app IOSurface 338 MB to 36 MB; in-place read_write, 0 of 120 frames differ from the pool path on two real FEL clips.
  • The full suite, the strict-pool run and the tvOS and iOS builds were not run locally; they run on CI for this draft.

Still needs Apple TV

  • Base-layer copy opt-out, picture identity: compare the 4K FEL clip over a long GOP on the A12, opt-out against allowsInPlaceOutputMetadata = false; VideoToolbox may keep the buffer as a reference picture, which would show as drift until the next IDR. If it differs, keep the copy for frames composed in place.
  • Annex B chroma filter: GPU cost on the A12 is unmeasured; check the compose time of the 4K FEL clip and 0 drops.
  • Base-layer copy opt-out: an A12 soak measured the process peak at 509 to 538 MB against 621 to 667 MB before, with 0 drops, on the earlier build of this change; repeat on this branch.
  • In-place read_write compose on the A12: one run of the 4K FEL clip in place and with AETHER_FEL_INPLACE=0. Earlier run: tier 2 and in place on, 0 drops and 0 compose failures in both arms. Still open: identical picture in place and in the pool path on the device.
  • Compose queue: a soak with seeks to confirm 0 drops and that the stall path stays silent on a healthy GPU.

Marked draft until CI is green and those checks pass.

…eserve independent of that limit

Two in-flight compositions are what the measured compose latency needs; the pool reserve no longer follows the in-flight limit, so the margin is two frame intervals (100 ms floor and 50 ms grace cap kept). The 1 Hz summary logs once per session when compositions cannot keep up with the stream's frame rate. Comments, the pool cap test and the reserve figure match the code.

Source: perf/fel-memory-inflight @ 0d898df3
…mpose stall

Dual-layer frames are now composed on a dedicated compose queue, never on
the VideoToolbox callback thread, with up to two compositions in flight.

A GPU that stops completing is handled instead of waited on. Queued frames
go out as the base layer, each with the RPU that keeps its mapping. The
stall is bounded and reported: after 600 base-layer frames without a slot
coming free, or at the 4th stall episode unless 240 healthy compositions
came between, the decoder reports VideoDecoderError.composerStalled once
through onFatalDecodeError and refuses further packets, so the host surfaces
a stop rather than retrying forever. The counts are of frames and verdicts,
not clock time, and a flush resets only the per-stall frame count.

The enhancement layer is upsampled with exact weights and its code is
rounded half up, as the spec's integer rounding does. This changes picture
bits by at most one code on 0.1-1% of samples, the ties. The inverse-NLQ
table and the MMR coefficients are read from per-frame tables instead of a
64-bit product per sample.

The new dual-layer tests build only with the DualLayerDolbyVision trait.
docs/dolby-vision-fel.md describes the queue, the recoverable stall and its
invariants.

Ported from TheFireKahuna/AetherEngine

Source: fel/coding-queue @ ac47c6f3
…without the metadata copy

The output-metadata normalizer copies every VideoToolbox frame that lacks imageBufferModifiable into
its own 4K pixel buffer pool before it adds the colour and aspect attachments. On the dual-layer
route the composer writes its result into that same decoded base-layer buffer, so the copy protects
nothing there and only costs memory: about 315 MB of IOSurface in the app on the Mac, about 120 MB
of peak on the Apple TV.

HardwareVideoDecoder gains allowsInPlaceOutputMetadata, set by DualLayerVideoDecoder on its
base-layer decoder only. Single-layer paths, the enhancement decoders and the software host keep
the copy unless VideoToolbox grants the flag.

Tested on the Mac: 240 composed frames of two real FEL clips are bit-identical in all planes, colour
tags, RPU digest and attachment key sets, with and without the change. Two 370 s runs each with
14 seeks: the app's IOSurface falls from 338 MB to 36 MB and the summed peak of app and decoder
service from 875-876 MB to 791-816 MB.

Source: fel/bl-copy-optout @ 8ef53dc2
…d those kernels only at tier 2

The in-place compose bound one base-layer texture twice in one kernel, as
read and as write, which Metal does not promise to keep coherent. Each plane
is now bound once: luma as a 16-bit read_write texture, chroma as a 32-bit
read_write texture (one Cb and Cr pair per texel). The in-place kernels share
the pool kernels' bodies, so the pool path and its output are unchanged. The
in-place output is pinned bit for bit against the pool path for every dither
mode, residual setting and chroma curve kind.

read_write on a 16-bit plane needs read/write texture tier 2. The in-place
kernels sit in their own block of the shader source, appended only on a
device that reports tier 2, so a device below it compiles no read_write text
and takes the pool path; a driver that refuses read_write can no longer cache
a failed compile and take the pool kernels down with it. At tier 2 the two
in-place pipelines are optional: if either fails to build, the frame takes
the pool path instead of falling back to the raw base layer. One
default-level log line gives the reported tier and whether in-place compose
is on, so a device that loses in-place is told apart from AETHER_FEL_INPLACE=0.

Source: fix/fel-inplace-read-write @ a8b93045
…s, and pin the documented constants

The dual-layer docs and DocumentedConstantsTests now match the code: two
compositions in flight give a deadline backstop of 6 frames (about 150 MB at
4K) and 7 pending frames at the stall guard; the enhancement layer is upsampled
bilinearly from explicit texel reads and rounded half up; the NLQ and MMR tables
are bound at buffers 2 and 3 of every compose kernel. CHANGELOG entries for the
compose queue and stall report and for the base-layer copy opt-out.

@quint-aether quint-aether Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review

Status: 🟠 Needs changes. Real issues to fix before merge.

The PR moves the FEL slot wait off the VideoToolbox callback onto a serial compose queue, with feed-side backpressure and a bounded stall mode. It also drops to two compositions in flight, reads NLQ/MMR from per-frame tables with an exact bilinear EL upsampler, removes the normalizer copy on the dual-layer base layer, and makes in-place compose bind each plane once as read_write (tier 2 only). The direction is right: the fix lives in the engine, and the locking (leaf composeBacklog, no lock held across the slot wait or the fatal handler, epoch mirror for flush and close) holds up on a close read.

Findings

  • Should fix: the base-layer copy opt-out makes in-place compose write composed pixels into VideoToolbox's own output buffer, even though VideoToolbox did not grant imageBufferModifiable. docs/architecture.md says that is the case where VideoToolbox may still hold the buffer as a reference picture. The evidence that this is safe comes from the Mac only, and the planned Apple TV check covers memory and drops, not picture identity. The architecture doc also still states the old rule. (Sources/AetherEngine/Decoder/HardwareVideoDecoder.swift:140)
  • Question: the stall bound turns a session that is still showing a valid base-layer picture into softwarePipelineFailed after 600 frames. Is ending playback the intended outcome, rather than staying on the base layer? (Sources/AetherEngine/Decoder/DualLayerVideoDecoder.swift:634)
  • Nit: on the episode that crosses maxComposeStallEpisodes, enterStallMode logs "compose stalled for good" and then "sending frames as the base layer until the GPU frees one" right after it. The second line reads as if playback continues. (Sources/AetherEngine/Decoder/DualLayerVideoDecoder.swift:1302)

Checklist: CHANGELOG yes, docs yes (dolby-vision-fel.md thorough; architecture.md not updated for the opt-out), tests yes, traits both ways yes (everything stays behind DualLayerDolbyVision; the new tests have #if guards)

Needs a device run: On the A12, picture identity in place with the copy opt-out against the copy path, over a long GOP stretch. Drift until the next IDR would show reference-picture corruption. Also the planned checks: in-place read_write against the pool path, the soak with seeks showing 0 drops and a silent stall path, and bypassQueueWaitMaxMs on a healthy GPU.

Thanks for the careful work and the unusually complete documentation of the threading model.

Automated review by Quint (Claude) of 23f315b. It reads the code, it does not build or run it; a maintainer reviews and merges.

/// the app) only costs memory. Frames that go out as the base layer (bypass, refused compose) gain
/// the same colour and aspect attachments on every frame. Every other path keeps the copy unless
/// VideoToolbox grants `imageBufferModifiable`.
var allowsInPlaceOutputMetadata: Bool = false

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this flag on, the normalizer returns VideoToolbox's own buffer whenever imageBufferModifiable is absent. The in-place composer then writes composed pixels into that buffer. Before this PR, those writes went into the normalizer's owned copy whenever the attachments differed, which per the PR body was every frame. docs/architecture.md (lines 104 to 108) gives the reason the copy exists: "VideoToolbox decode callbacks can retain their image buffer as a reference picture." If the A12 hardware decoder does that for the P7 base layer, later frames decode from composed pixels. That shows as drift until the next IDR, and a drop or memory count would not catch it.

The 240-frame bit-identity run on the Mac is good evidence for the Mac decoder. The Apple TV checks listed in the PR measure memory and drops only. Suggest two things:

  • Add an A12 picture comparison over a long GOP: in place with the opt-out, against allowsInPlaceOutputMetadata = false.
  • Update docs/architecture.md with the dual-layer exception and why it holds.

If the device run shows a difference, keep the copy for frames that will be composed in place and skip it only for the pool path.

/// The bound on one stall mode: this many frames sent out as the base layer without a single slot
/// coming free (about 25 s of video at 24 fps) and the GPU is taken to be gone for good. Counted in
/// frames, never in clock time, like the verdict itself.
static let maxComposeStallBypassFrames = 600

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question, not a defect. In stall mode every frame still goes out as a valid base layer with its mapping-preserving RPU, and the display layer does not depend on our Metal queue. So after 600 frames this bound ends a session that is still showing a correct base-layer picture, and the software host turns it into softwarePipelineFailed. Is that the intended product behaviour, rather than staying on the base layer and logging? If it is, a sentence in §5.6 on why a stopped session beats a base-layer picture would help the next reader (for example: the GPU is shared with something the host needs). The maintainer should make this call.

let episodes = composeStallEpisodes
composeBacklog.unlock()
composeResultLock.lock(); totalComposeStalls += 1; composeResultLock.unlock()
if episodes > Self.maxComposeStallEpisodes {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: when this branch reports the fatal error, the function still logs compose stalled: ... sending frames as the base layer until the GPU frees one right after compose stalled for good. In a device log the session then reads as continuing. Consider skipping the entry line, or rewording it, when the report fired.

The 2:1 4:2:0 enhancement-layer chroma is now upsampled with the Annex B
filter in the Metal composer, computed in integers and rounded half up.
Other chroma ratios keep the exact-weight read. Luma is unchanged and
stays bit-identical.

Measured against the spec model on 8 clips x 3 frames at 4K: chroma is
within one 12-bit code on every sample except 3 Cb samples of one clip
(max error 2). GPU cost is about +0.2 to +0.7 ms per 4K frame on Mac;
the A12 has not been measured yet.

Source: fel/annexb-chroma @ c11c4203
…eger enhancement plane

The reference kernel the tile kernel is compared against still called the site
helper with the old signature and sampled the enhancement chroma as a float
texture, so the library no longer compiled. It now takes the per-frame NLQ and
MMR tables and reads the enhancement plane as 16-bit integer codes, like the
shipped kernels.

@quint-aether quint-aether Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review

Status: 🟠 Needs changes. Real issues to fix before merge.

Since 23f315b the PR adds the Annex B.3 default chroma filter for a half-size enhancement layer. It also adds per-frame NLQ and MMR tables, integer EL planes with exact-weight bilinear reads rounded half up, and a DEBUG-only A/B and capture harness. The direction is still right. The filter lives in the composer, is tested exactly against an integer model (both edges and odd sizes), and an EL at the base layer's size keeps its exact texel read.

Findings

  • Should fix (still open from the last review): the dual-layer base-layer copy opt-out lets in-place compose write into VideoToolbox's own buffer without imageBufferModifiable. docs/architecture.md (lines 104 to 108) still states the old rule and was not updated in this push, and nobody has answered the reference-picture question yet. (Sources/AetherEngine/Decoder/HardwareVideoDecoder.swift:140, inline comment unchanged)
  • Question (still open): should the 600-frame stall bound end a session that is still showing a valid base layer? Left for the maintainer. (Sources/AetherEngine/Decoder/DualLayerVideoDecoder.swift:634)
  • Nit (still open): on the reported episode, enterStallMode still logs "sending frames as the base layer until the GPU frees one" right after "compose stalled for good". (Sources/AetherEngine/Decoder/DualLayerVideoDecoder.swift:1306, previously flagged at 1302)
  • Nit: docs/dolby-vision-fel.md:122 says the EL luma is read from "four explicit texel reads". dovi_upsample_el uses one gather, and the shader comment says the gather measured cheaper. (docs/dolby-vision-fel.md:122)
  • Nit: none of the new numbers quoted in §5.6 are pinned in DocumentedConstantsTests: 4 slices, 2 s, 600 frames, 3 episodes, 240 compositions, and the reserve cap of 17 buffers / 423 MB. The constants and the doc can drift apart silently.

Checklist: CHANGELOG yes, docs yes (dolby-vision-fel.md covers Annex B and the tables; architecture.md still not updated for the opt-out), tests yes, traits both ways yes (DEBUG-only flags and variants are guarded on both the Swift and shader side)

Needs a device run: On the A12:

  • Compose GPU time and drops for the 4K FEL clip with the Annex B chroma filter. Odd chroma sites now read 16 EL texels, and the 4:2:2 and 4:4:4 step-up kernels evaluate sites more than once.
  • Picture identity, in place with the copy opt-out against the copy path, over a long GOP.
  • In place read_write against the pool path.
  • The soak with seeks: 0 drops, a silent stall path, and bypassQueueWaitMaxMs on a healthy GPU.

Thanks for the careful measurements behind the filter change.

Automated review by Quint (Claude) of 4003010. It reads the code, it does not build or run it; a maintainer reviews and merges.

Comment thread docs/dolby-vision-fel.md Outdated
**Kernels** (`DoviShaderSource.swift`). Luma: base code → piece selection → polynomial (evaluated in
normalized float) or MMR when the luma curve uses MMR → plus the inverse-NLQ residual of the
enhancement-layer luma, upsampled with one hardware-bilinear fetch →
enhancement-layer luma, upsampled bilinearly from four explicit texel reads with exact weights, the code rounded half up →

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the luma path does not use four explicit texel reads. dovi_upsample_el fetches the 2x2 footprint with one gather on the integer texture. The shader comment says the gather measured cheaper (0.41 ms against 0.45 ms on an M4 Pro), and four reads are only what the chroma bilinear fallback (dovi_upsample_el_uv) does. Suggest: "upsampled bilinearly from one gather of the 2x2 footprint, with exact weights, the code rounded half up".

Document the dual-layer exception to the output-metadata copy and why the stall bound ends the session, quote the luma upsample as the gather it is, pin the stall constants and the output buffer budget in the documented-constants checks, and stop logging that frames continue as the base layer on the episode that reports the stop.
@pkajaba

pkajaba commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Pushed fixes for the points below.

  • Copy opt-out (HardwareVideoDecoder.swift:140): docs/architecture.md now names the dual-layer exception and the reference-picture risk it accepts. What backs it today is the Mac only: 240 frames of two real FEL clips bit-identical with and without the copy. The long-GOP picture comparison on the A12 (opt-out against the copy) is added to "Still needs Apple TV" and the PR stays a draft until it runs. If it shows a difference, the plan is the one you suggest: keep the copy for frames composed in place, skip it for the pool path only.
  • Stall bound (DualLayerVideoDecoder.swift:634): this is a product call, left to the maintainer. §5.6 now states the intent (a base-layer picture on a stream the host asked to compose is a silent loss that looks like success, and only a reported error lets the host retry or pick another route) and that the two constants are the bound.
  • Log line on the reported episode: the "sending frames as the base layer" line is no longer logged when the fatal report fires.
  • dolby-vision-fel.md:122: reworded to one gather of the 2x2 footprint.
  • Pinned numbers: DocumentedConstantsTests now pins 4 slices, 2 s, 600 frames, 3 episodes, 240 compositions and 14 + 3 buffers / 423 MB against §5.6.

The all-traits job failed once on Issue309SilentTransportDeathTests ("first byte is slower than the stall threshold", wall-clock) while the Metal suites ran in parallel; nothing in this PR touches the reader.

@quint-aether quint-aether Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review

Status: 🟢 Clean. Nothing left to fix, ready for a maintainer.

Since 4003010 the push answers every point from the last two reviews. The code changes behind them are unchanged. The direction is still right: the compose stall handling, the in-place read_write binding and the Annex B chroma filter all live in the engine, behind DualLayerDolbyVision.

Findings

  • Fixed: docs/architecture.md now names the dual-layer exception (allowsInPlaceOutputMetadata) and the reference-picture risk it accepts. The only evidence so far is the Mac run, and the A12 long-GOP comparison is listed as still open. That answer holds. What remains is a device check, not a code defect (see below).
  • Answered: §5.6 now explains why the 600-frame / 3-episode bound ends the session, and leaves that product decision to the maintainer.
  • Fixed: enterStallMode no longer logs "sending frames as the base layer" on the episode that reports the fatal error (DualLayerVideoDecoder.swift:1302).
  • Fixed: dolby-vision-fel.md now describes the EL luma read as one gather of the 2x2 footprint.
  • Fixed: DocumentedConstantsTests.testComposeStallBoundsMatchDocumentation pins 4 slices, 2 s, 600, 3, 240 and 14 + 3 / 423 MB against §5.6.

No new findings.

Checklist: CHANGELOG yes, docs yes, tests yes, traits both ways yes

Needs a device run: On the A12, before merge:

  • Picture identity over a long GOP: in place with the copy opt-out, against allowsInPlaceOutputMetadata = false. If it differs, keep the copy for frames composed in place.
  • In-place read_write against the pool path.
  • Compose GPU time and drops with the Annex B chroma filter on the 4K FEL clip.
  • The soak with seeks: 0 drops, a silent stall path, and bypassQueueWaitMaxMs on a healthy GPU.

The PR is no longer marked draft, but its body says it stays a draft until these checks pass.

Thanks for working through each point so carefully.

Automated review by Quint (Claude) of 8c39d61. It reads the code, it does not build or run it; a maintainer reviews and merges.

@quint-aether quint-aether Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review

Status: 🟢 Clean. Nothing left to fix, ready for a maintainer.

I checked the new head 7dc2423. Since 8c39d61 it is a rebase onto main, the CHANGELOG context now includes #969, and nothing this review covers has changed. The earlier fixes are still in place. The A12 device checks listed in the last review are still open.

Automated review by Quint (Claude) of 7dc2423. It reads the code, it does not build or run it; a maintainer reviews and merges.

@superuser404notfound

Copy link
Copy Markdown
Owner

Merged into main as 1f984bc5, thanks a lot for this one, and for answering the review points so thoroughly.

The only conflict was CHANGELOG.md against #969 (both sections kept, #969's "Added" first, this PR's "Changed" after it). The code merged cleanly on top of #969. Local run of the merge:

  • trait off: XCTest 828, Swift Testing 5610, green
  • DualLayerDolbyVision: XCTest 832, Swift Testing 5978, green, also under LIBDISPATCH_COOPERATIVE_POOL_STRICT=1
  • the seven standalone Scripts/test-*.sh: green

On the stall bound: keeping it as is. A GPU that completes nothing for 600 frames is broken rather than slow, and a reported error is the only outcome a host can act on. A base-layer picture that looks like success is not.

Still open on the Apple TV, from your list, with the first one mattering most because it decides whether the copy opt-out stays as it is:

  1. Copy opt-out, picture identity over a long GOP on the A12 against allowsInPlaceOutputMetadata = false (drift until the next IDR would mean VideoToolbox still references the buffer; then keep the copy for frames composed in place).
  2. Annex B chroma filter: compose time of the 4K FEL clip and 0 drops.
  3. Memory soak on this branch.
  4. In-place read_write against the pool path, same picture on the device.
  5. Soak with seeks: 0 drops, stall path silent on a healthy GPU.

Unreleased for now, it goes out with the next engine release.

@superuser404notfound

Copy link
Copy Markdown
Owner

Closing as merged: your sync merge 7dc2423e has the same tree as 1f984bc5 on main, byte for byte, so everything in it landed. GitHub only shows it as open because the merge commit on main is a different one.

@superuser404notfound

Copy link
Copy Markdown
Owner

Released in 7.56.0 (76ad51a7).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants