Repository navigation
feat(dovi): Metal FEL composer and Dolby Vision display metadata (not routed) - #767
Conversation
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.
…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
|
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:
Follow-up on main (fcc3ea8):
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:
On to #768. |
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
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
|
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 |
Part 5/10 of #702 by @pkajaba. CHANGELOG conflict with the #767 follow-up resolved by keeping both sides. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
…767 and merged forward)
Part 3/10 of #702, stacked on #766. It targets
mainand 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,composeAsyncbounded atmaxFramesInFlight.DoviMetalParamsis the parameter ABI,DoviShaderSourcethe kernels.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 asDolbyVisionRPUDataplusDolbyCompatibilityID. 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);UndocumentedDolbyVisionKeysTestsfails if either literal appears in another source file.DolbyCompatibilityIDmust be aCFString; aCFNumberthere aborts the render server.DoviRpuConverter.separateDualLayers: splits a packet into base layer, EL packet, converted RPU and composer parameters;convertPacketToProfile81is 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.)layerBitDepthsSupported, because no RPU libdovi accepts can reach it, and the test drives it directly). AfterreleaseOutputPool()every composition is refused:composereturns nil andcomposeAsynccompletes 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 blockingcomposetakes an in-flight slot likecomposeAsync, so the parameter slots stay bounded.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.DoviComposedFrameRpuTestspins this on the RPU attached to composed frames (curves are no-op, DM levels equal the source's); the converter doc comment states why.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 (the0x7C 0x01NAL header is stripped, a header-less RPU passes through, anything else answers nil),attachsets the RPU asCFDataand the compatibility ID as aCFStringon theCVBufferand on itsIOSurface,attach(nil)and an unusable NAL clear both keys, including a previous tenant's. The IOSurface mirror is checked on macOS only, whereCVBufferRemoveAttachmentclears 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.parseRpuParameters(unsupported depth, rejected curve, dropped residual and so on) are logged once per distinct message instead of once per frame, and ause_prev_vdr_rpu_flagRPU, which carries no mapping by design, is no longer logged as a failure.docs/architecture.mdentries forDoviRpuConverter,DoviDisplayMetadata,Metal/*and the LibDovi row.How it was tested
swift testfiltered 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 withoutDV_FEL_TESTS_DIR.DV_FEL_TESTS_DIR.swift build --build-testsandaetherctlbuild at this commit.What it does not do
dolby-vision-fel.mdsection numbers; the document arrives with the route PR (6). No comment links to an anchor, so nothing is broken, only unresolved until then.DocumentedConstantsTestspins for the composer's bounds come with the document, in feat(dovi): route Profile 7 FEL to the dual-layer decoder behind preferDualLayerDolbyVision #770.FEL stack for #702, merge in order: #765 → #766 → #767 → #768 → #769 → #770 → #771 → #772 → #773 → #774. Standalone read-ahead fixes: #775, #776.