Skip to content

feat(dovi): Metal FEL composer and Dolby Vision display metadata (not routed) - #767

Merged
superuser404notfound merged 7 commits into
superuser404notfound:mainfrom
pkajaba:fel2/3-composer
Oct 15, 2026
Merged

superuser404notfound merged 7 commits into
superuser404notfound:mainfrom
pkajaba:fel2/3-composer

Conversation

@pkajaba

@pkajaba pkajaba commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Part 3/10 of #702, stacked on #766. It targets main and carries the commits of PRs 1 and 2, so review only the top commit; the diff shrinks to it as the earlier PRs merge.

Summary

The composer and the Dolby Vision metadata plumbing, with nothing selecting them yet. No behaviour change for any source.

What's in it

  • DoviFelComposer (Metal): rebuilds the 12-bit picture from base layer, enhancement layer and RPU: reshaping curves (polynomial and MMR), inverse NLQ, MMR chroma, bilinear EL upsampling, ordered dither to 10-bit, pooled P010 output, composeAsync bounded at maxFramesInFlight. DoviMetalParams is the parameter ABI, DoviShaderSource the kernels.
  • Output pool across seeks: flush() keeps the pool and trims idle buffers, releaseOutputPool() drops it on teardown. Dropping it on flush made the frames after a seek allocate a second full pool beside the buffers the renderer still held (about +260 MB at 4K for about 0.6 s per seek). Measured end to end with the decoder (feat(dovi): dual-layer Profile 7 FEL decoder (not routed) #769): peak 674 MB to 500 MB over 12 seeks.
  • DoviDisplayMetadata: attaches the Profile 8.1 RPU as DolbyVisionRPUData plus DolbyCompatibilityID. Both keys are undocumented Apple keys, defined only in this file and labelled as such (point 4 of Support for Dolby Vision Profile 7 Full Enhancement Layer #702); UndocumentedDolbyVisionKeysTests fails if either literal appears in another source file. DolbyCompatibilityID must be a CFString; a CFNumber there aborts the render server.
  • DoviRpuConverter.separateDualLayers: splits a packet into base layer, EL packet, converted RPU and composer parameters; convertPacketToProfile81 is now that walk with the EL dropped. One behaviour difference from before: when a packet's only NALs are RPU/EL and its RPU was dropped (libdovi or the guard refused it), the packet is left untouched as before, but the call now reports failure; it used to report success, which hid the degrade from callers that act on the result. A packet with several RPUs commits once: each RPU's raw bytes, parameters, converted RPU and flags are collected in locals and stored together after it has converted, so the outputs are those of the last RPU that fully succeeded, never a mix of two. (Tests: two valid RPUs in a packet, and a second RPU that fails the guard.)
  • Reshaping follows the reference composer more closely (the shader and the parameter walk, no ABI change):
    • An MMR input (luma, Cb, Cr) is clamped to the pivot range of its own component before the cross terms are formed, as the reference composer does. A component with fewer than 2 pivots has no range and is left as is.
    • The prediction is floored at 0 before the residual is added, for polynomial and MMR alike, so a negative prediction cannot be pulled back up by the residual.
    • Real-file oracle numbers are unchanged on all three clips.
  • Composer guards. An RPU whose EL bit depth is not 10 is refused (the EL is bound as a 10-in-16 plane and the NLQ constants assume a 10-bit code; libdovi 3.4 already rejects it at parse time, so this is defence in depth; the check is its own function, layerBitDepthsSupported, because no RPU libdovi accepts can reach it, and the test drives it directly). After releaseOutputPool() every composition is refused: compose returns nil and composeAsync completes with nil and returns its slot, so no pool is rebuilt after teardown; the torn-down check is made inside the same lock as pool creation, so a teardown that lands between a composition's first look and its pool request cannot leave a fresh pool behind that nothing releases. The blocking compose takes an in-flight slot like composeAsync, so the parameter slots stay bounded.
  • Mode 2 is pinned. The RPU attached to composed frames is converted with dovi_convert_rpu_with_mode(rpu, 2), not mode 5: the composer has already applied the reshaping and added the residual, so the display side must not reshape again. Mode 2 sets both curves to no-op (and drops the EL/NLQ part) while keeping L1/L2 and the other display metadata. DoviComposedFrameRpuTests pins this on the RPU attached to composed frames (curves are no-op, DM levels equal the source's); the converter doc comment states why.
  • The CRC-valid mutation fuzz and the real-file guard test (deferred from fix(dovi): refuse hostile RPUs before libdovi can abort the process #765), and the pool-threshold-follows-look-ahead test.
  • The FEL math and upsampler tests now drive the production kernel (DoviFelComposer.compose, the math tests with the raw-VDR debug mode) and read the result back, with expectations worked out from the reference formulas and written down as numbers; the CPU emulations of the sampler and of the arithmetic that stood in for the kernel are gone, so these tests cannot pass while the shader is wrong. The layout probe now reads 96 slots back (the scalars, then per component the first element of every array and every NLQ scalar), so swapped neighbours and offset drift are caught, not only a moved tail.
  • DoviDisplayMetadataTests (new): the RPU payload form (the 0x7C 0x01 NAL header is stripped, a header-less RPU passes through, anything else answers nil), attach sets the RPU as CFData and the compatibility ID as a CFString on the CVBuffer and on its IOSurface, attach(nil) and an unusable NAL clear both keys, including a previous tenant's. The IOSurface mirror is checked on macOS only, where CVBufferRemoveAttachment clears it; tvOS is not checked by these tests.
  • DoviElBitDepthTests (new): the real RPUs carry a 10-bit EL and are accepted; a Profile 7 RPU with a 9-bit EL is refused (by libdovi, end to end); the composer's own depth check is tested directly.
  • Parse-time rejections in parseRpuParameters (unsupported depth, rejected curve, dropped residual and so on) are logged once per distinct message instead of once per frame, and a use_prev_vdr_rpu_flag RPU, which carries no mapping by design, is no longer logged as a failure.
  • New GPU tests for the MMR clamp and the floor at 0, and a compose-after-teardown test, and a test that pool creation itself is refused after teardown.
  • docs/architecture.md entries for DoviRpuConverter, DoviDisplayMetadata, Metal/* and the LibDovi row.
  • Public API: none.

How it was tested

  • swift test filtered to every test file the stack adds or changes up to this PR (cumulative: git diff --name-only --diff-filter=AM origin/main HEAD -- Tests/AetherEngineTests, one suite per file): 178 tests in 18 suites pass on this commit alone. Real-clip tests skip without DV_FEL_TESTS_DIR.
  • Reference check, offline and not part of the suite: on real FEL clips the composed output matches DoViBaker, a spec-following reference composer, within +-1 code value. Re-run after the MMR clamp and the floor at 0: the numbers on the three clips are unchanged.
  • Real-clip tests skip without DV_FEL_TESTS_DIR.
  • swift build --build-tests and aetherctl build at this commit.

What it does not do


FEL stack for #702, merge in order: #765 → #766 → #767 → #768 → #769 → #770 → #771 → #772 → #773 → #774. Standalone read-ahead fixes: #775, #776.

libdovi is built panic=abort, so a single panic ends the host process. A
CRC-valid but hostile Dolby Vision RPU could reach one on the native
Profile 7 -> 8.1 conversion.

Adds DoviRpuGuard: it checks the RPU CRC and pre-scans the payload for the
inputs that make libdovi 3.4 panic or allocate without bound (linear
interpolation pieces, polynomial/MMR mixes that break the writer, pivot and
block counts the payload cannot hold, undefined display-management block
lengths). The existing paths now check each RPU with it before parsing: the Profile 8.1
conversion in DoviRpuConverter (convertPacketToProfile81), the
enhancement-layer-type probe, and the DolbyVisionRecordAudit RPU read. The
mode 2 convert -> write pair on a parsed RPU is factored into
DoviRpuConverter.convertedUnspec62 so the tests drive production's own entry
point. A rejected RPU degrades the frame to the HDR10 base exactly as a
libdovi failure already did (superuser404notfound#135).

This hardens the existing native 8.1 conversion; it changes no routing and
adds no Dolby Vision FEL code. The guard knows the paths listed above; it
does not prove there are no others.

Tests: DoviRpuGuardTests (crafted RPUs, verdicts, conversion round trip) and
a DolbyVisionRecordAudit case. The CRC-valid mutation fuzz and the
real-file guard test arrive with the composer, whose parameter walk they
also exercise.
…or reordered streams

Adds the SampleBufferRenderer pieces the dual-layer Dolby Vision path needs
for pacing, as inert, opt-in additions:

- felVideoLookaheadFrames (9) and mayEnqueueVideoFrame / setFELLookahead:
  a gate that runs BEFORE decode and refuses a compressed frame more than
  nine frame intervals ahead of the playback clock, so composed 4K frames
  (about 25 MB each) cannot pile up behind Apple's readiness gate alone.
- displayOrderPTS: estimates a packet's display-order PTS in decode order
  from the largest amount a later packet fell below the highest PTS seen,
  so B-frame streams do not swing the cap with the position in the GOP. A
  gap larger than HEVC's 16-picture reorder ceiling is treated as a
  timestamp discontinuity and does not poison the learned lead.

Nothing calls the gate yet and it is off unless setFELLookahead(enabled:)
is called, so non-FEL pacing is unchanged. The decoder and the host wiring
come in later PRs; the composer-side pool sizing that follows this cap
(DoviFelComposer.outputPoolAllocationThreshold) is pinned in the composer PR.

Tests: SampleBufferRendererLookaheadTests, SampleBufferRendererReorderDepthTests.
… routed)

Adds the pieces that rebuild a Profile 7 FEL picture, with nothing selecting
them yet.

- DoviFelComposer (Metal): rebuilds the 12-bit picture from base layer,
  enhancement layer and RPU: reshaping curves (polynomial and MMR), inverse
  NLQ, MMR chroma, bilinear EL upsampling, ordered dither down to 10-bit,
  output in a pooled P010 buffer, composeAsync bounded at maxFramesInFlight.
  DoviMetalParams is the parameter ABI, DoviShaderSource the kernels. The
  output pool survives a seek flush (flush() trims idle buffers,
  releaseOutputPool() drops it on teardown): dropping it made post-seek
  frames allocate a second full pool beside the buffers the renderer still
  held, about +260 MB at 4K for ~0.6 s per seek; measured end to end with
  the decoder in the next PRs, peak 674 -> 500 MB over 12 seeks.
- DoviDisplayMetadata: attaches the Profile 8.1 RPU as DolbyVisionRPUData
  plus DolbyCompatibilityID (a CFString: a CFNumber aborts the render
  server). Both keys are undocumented; they are defined in this one file
  and UndocumentedDolbyVisionKeysTests fails if either literal appears in
  another source file.
- DoviRpuConverter.separateDualLayers splits one packet into base layer,
  enhancement-layer packet, converted RPU and composer parameters;
  convertPacketToProfile81 is now that walk with the EL dropped. The RPU
  attached to composed frames is converted with mode 2 (the composer has
  already applied the reshaping and added the residual, so the display side
  must not reshape again); DoviComposedFrameRpuTests pins this.

Nothing calls the composer, so no behaviour changes for any source. Public
API: none. Not in this PR: the dual-layer decoder, the routing flag and
host wiring, the aetherctl tooling, and dolby-vision-fel.md (comments here
cite its section numbers; the document arrives with the route PR).

Tests: GPU curve sweep, edge cases and adversarial inputs, layout probe (the
GPU reads each parameter sub-block back at the offset Swift wrote it),
shader/ABI sync, dither, enhancement upsampler, FEL math, FEL and
CRC-valid-mutation fuzzers, converter and guard tests, async compose,
look-ahead pool sizing. The real-clip tests skip without DV_FEL_TESTS_DIR.
DoviFelComposer.swift, recordGPUTime: the "[DoviFelComposer] gpu X ms/frame over N frames"
line repeats every 120 composed frames (about every 5 s at 24 fps) for the whole session. Moved
from the default level to .verbose, so it reaches OSLog's debug level only and no longer the host
handler or a default log stream.

Kept at the default level, unchanged: the shader compilation error (once per process), the
command buffer errors (real failures), the logOnce parse-time rejections (bounded to 64 distinct
lines), and the one-shot non-zero linear_deadzone_threshold notice.
A GPU that keeps failing would otherwise log the same line for every frame.
The decoder's per-second summary still counts each failed compose.
…dual

The composer floored the prediction at 0 before adding the enhancement-layer
residual but did not cap it at the top. A prediction above full scale (seen
in chroma MMR on saturated colours) plus a negative residual then stayed at
vdr_max instead of landing below it. DoViBaker caps the polynomial and the
MMR result at full scale before the residual as well.

Against DoViBaker's integer pipeline on a real FEL RPU (fel_orig.bin from
dovi_tool's test assets, 200,000 random base and enhancement samples), Cr
differed by up to 199 12-bit codes on 1.2% of samples before this change and
by at most 1 code after it, the same as Y and Cb.

dovi_denormalize now clamps to [0, vdr_max]. Test: a prediction of 1.1 with a
-100 EL code residual lands on 3996, through the luma table and through
chroma MMR.
…DoViBaker does

N3 asserted that a prediction above the VDR range keeps its overshoot until
the residual is added (3979). DoViBaker caps the mapping result at 0xffff
first (polynompialMapping and mmrMapping return uint16_t), which for N3's
inputs is (65535 - 3192 + 8) >> 4 = 3896, the value the previous commit
produces. The test's own header names DoViBaker as the oracle.
@superuser404notfound
superuser404notfound marked this pull request as ready for review October 15, 2026 06:55
@superuser404notfound
superuser404notfound merged commit 4000a9f into superuser404notfound:main Oct 15, 2026
superuser404notfound pushed a commit that referenced this pull request Oct 15, 2026
…e reporting change

- separateDualLayers reads the RPU header only when the dual-layer outputs
  want it. convertPacketToProfile81 (extractEL and extractParams off) threw
  the FEL/MEL and flag results away, so today's P7 to 8.1 path paid an extra
  libdovi call and a String allocation per frame for nothing.
- Test: a packet whose only NALs are a refused RPU and an EL stays byte for
  byte as it was and now reports failure, the one behaviour change #767 names.
- CHANGELOG: Unreleased > Changed entry for that reporting change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@superuser404notfound

Copy link
Copy Markdown
Owner

Merged, thank you @pkajaba. This is a big piece of work, and the tests that drive the production kernel against numbers worked out from the reference formulas made it reviewable.

What I checked:

  • Full suite on main with this merged: 4579 tests in 629 suites, green.
  • The shader and the parameter walk against the libdovi 3.4 source: pivot prefix sums and piece selection, the fixed-point coefficients, MMR term order and per-component clamp, NLQ ranges, and buffer bounds against num_pivots/MMR order. I found no out-of-bounds read, no division by zero and no Swift/MSL layout mismatch. The slot and semaphore handling and the teardown lock also look right.
  • convertPacketToProfile81 against the old implementation: the output bytes are the same, and the reporting change is the only difference. On main it surfaces only as the one-shot log in HLSSegmentProducer and in the dovitest counter.

Follow-up on main (fcc3ea8):

  • separateDualLayers now reads the RPU header only when extractEL || extractParams. The P8.1 rewrite discarded the FEL/MEL and flag results, so today's P7 path paid an extra libdovi call and a string allocation per frame.
  • A test pins the reporting change: a packet of only a refused RPU plus an EL is left byte for byte as it was, and the call returns false.
  • An [Unreleased] > Changed CHANGELOG entry.

Three edge cases I left alone. They only produce wrong pixels and never touch memory, so take them up if you think they're worth it:

  1. vdr_in_max that shifts down to 0 disables the NLQ ceiling (nlq.vdr_in_max > 0 in dovi_eval_inv_nlq). With a huge slope and shift 0, int(mag) then wraps. The final clamp contains it, but treating 0 as "no residual" or refusing it in parseNlqParams would be stricter.
  2. MMR coefficients near Int32.max with coef_shift 0 put int(rint(...)) in dovi_denormalize out of range. That conversion is implementation-defined in MSL, though it's still clamped afterwards.
  3. The chroma dispatch and textures use blW/2 and blH/2. With an odd base-layer width or height, the last chroma column or row of a pooled output is never written. Real DV streams are even.

On to #768.

superuser404notfound pushed a commit that referenced this pull request Oct 15, 2026
CI's one-thread cooperative pool job failed twice on main after #767, both
times in the AE#711 fixture writer: `video 4/120` and `video 60/120` when its
fixed 20 s deadline ran out, with the writer still taking samples.

The new Dolby Vision suites block their thread for seconds at a time: the
synchronous compose waits on the GPU, and the CRC-valid fuzz and the guard's
exp-Golomb sweep are CPU loops. On the one-thread pool that thread is the only
one, so everything else, including the playing-capture test, waits behind
them. Locally under LIBDISPATCH_COOPERATIVE_POOL_STRICT=1 that test took
16.5 s without the Dolby Vision suites, 38 s with them, and 24 s with them
marked `.offCooperativePool`, the trait made for tests that block on purpose.

The fixture's deadline is now a stall deadline: it only gives up after 20 s
in which the writer took nothing, which is the deadlock it was written for.
A slow writer that is still moving is not one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
superuser404notfound pushed a commit that referenced this pull request Oct 15, 2026
069a7a7 moved the #767 suites off the cooperative pool, which fixed the
one-thread job, but `BlockingExecutor` adds a thread per blocked job: their
CPU and GPU loops then all ran at once and took the 3-core runner from the
timing tests beside them (SourceOpenRecovery request count, CancellableLoad
ceiling, the composeAsync outstanding bound, all failing in the plain
`swift test` step that had passed before).

`.offCooperativePoolOneLane` runs them off the pool and one case at a time
across every suite that carries it. `DoviComposeAsyncTests` keeps the plain
trait: its cases are short deadlock watchdogs with one-minute limits, and the
time a case waits for the lane counts against its limit.

Locally, two rounds each: plain step 48-49 s, one-thread step 38-39 s, and
the AE#711 playing capture at 18 s and 7 s (it was 38 s on the one-thread
pool with the suites on it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@superuser404notfound

Copy link
Copy Markdown
Owner

One more note for the rest of the stack. After this merged, main CI failed in the one-thread cooperative pool step. The new Dolby Vision suites block their thread for seconds at a time (the sync compose waits on the GPU, and the fuzz loops are CPU-bound), and on that job the pool has only the one thread. Fixed on main in 069a7a7 and f1ba851: those suites now carry .offCooperativePoolOneLane, which runs them off the pool and one case at a time. DoviComposeAsyncTests carries the plain .offCooperativePool, because time spent waiting for the lane counts against .timeLimit. Please give the same trait to any compute- or GPU-heavy suite you add in #768 onward. CI doesn't run on the fork branches, so I'll run both test steps locally before each merge.

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