Skip to content

feat(dovi): picture-order pairing and delivery building blocks for the dual-layer decoder - #768

Merged
superuser404notfound merged 10 commits into
superuser404notfound:mainfrom
pkajaba:fel2/4-decoder-parts
Oct 15, 2026
Merged

superuser404notfound merged 10 commits into
superuser404notfound:mainfrom
pkajaba:fel2/4-decoder-parts

Conversation

@pkajaba

@pkajaba pkajaba commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Summary

Four self-contained pieces the decoder is built from, none wired to anything. No behaviour change.

What's in it

  • HEVCPictureOrderCount: the H.265 POC (section 8.3.1) of one layer from the parameter sets and each picture's first slice header; no decoding. Anything it cannot follow answers nil rather than a guess.
    • RASL pictures (NAL types 8 and 9) of an IRAP that has NoRaslOutputFlag = 1 and is not an IDR (a CRA that opens the sequence, or a BLA) get no POC: they reference pictures from before the IRAP that a decoder starting there never had, so they are not output. The skip ends at the next IRAP. A CRA in the middle of a sequence keeps its RASL pictures in the numbering.
    • RADL pictures (POC below their IRAP's, decoded after it) keep the layer's offset instead of discarding it: POC still steps one per picture, so they land before the IRAP's slot.
  • DualLayerPictureAlignment: derives each layer's display slot from its POC and restamps each EL packet with the time of the base picture in the same slot, so an EL coded with B-frames over a base layer without them pairs the right pictures. Falls back to access-unit pairing when POC is unavailable or the slots disagree by more than 16.
    • maxBackwardRestamp: how many slots earlier than its own unit an EL picture may be restamped. The default is the 16-slot DPB bound. A base-layer frame waits for its partner only until K newer base frames have arrived, so an EL restamped further back than that finds its partner already bypassed and the pair is lost silently. The owner sets the bound from its skew bound (feat(dovi): dual-layer Profile 7 FEL decoder (not routed) #769 sets K - 1 = 2); a unit beyond it is paired by access unit and counted in unabsorbableRestamps.
  • Known limits of DualLayerPictureAlignment, documented on the type. Both end in access-unit pairing, which is what a stream gets without the type:
    • A sequence opener takes the slot "units before it". If the previous sequence's POC numbering ran ahead of its unit count (gaps in its POCs), the opener and its first followers share slots with that sequence's last pictures, and the time kept for a slot is the newer one, so a restamp into that range can land on the wrong picture. It needs a mid-stream sequence change with such gaps; a seek resets all slots.
    • A layer whose slots drift further than 16 from the unit position stops being placed until its next IDR or BLA. A CRA opens a sequence only at the start or after a seek, so an open-GOP stream that loses alignment stays on access-unit pairing until the next seek.
  • FrameSideDataRing: fixed capacity 32, lookup within +-300 ticks.
  • OrderedDelivery: hands composed frames across the VideoToolbox / Metal queue boundary in decode order. The lock rule is stated in its comments: it holds no lock of its own while calling onFrame; onFrame may take the owner's lock briefly, which cannot deadlock because no caller of fulfil or resetAsync holds a lock while waiting on the queue (only barrier() and reset() wait, and they run with no owner lock held).
  • A53SEIParser.unescapeRBSP and parseHVCCParameterSets made module-internal for the POC reader and its test.
  • 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): 226 tests in 23 suites pass on this commit alone. Real-clip tests skip without DV_FEL_TESTS_DIR.
  • Synthetic POC tests (HEVCSyntheticBitstream writes hand-built SPS, PPS and slice segment headers with a bit writer; the expected POC follows from the spec, not from running the code under test): MSB wrap forward and backward and the half-range step; IDR and BLA starting a sequence; a CRA mid-sequence and after reset(); end-of-sequence NALs; which pictures are prevTid0Pic; RASL of a sequence-opening CRA skipped, RASL of a mid-sequence CRA numbered, an IDR clearing the skip; RADL keeping the offset; emulation-prevention bytes, num_extra_slice_header_bits, pic_output_flag, colour_plane_id and SPS sub-layer flags; missing PPS or SPS, non-first slice segments, truncated headers and junk answering nil.
  • Alignment tests: a seek onto a CRA with RASL pictures keeps the alignment; a restamp beyond the bound is not placed and one within it is; the default bound places restamps up to 16 back; crafted timestamps decline instead of trapping.
  • No local clip has a CRA with RASL pictures (one of the FEL test clips is IDR-only), so the RASL path is covered by the synthetic tests only.
  • Tests that exercise a guarantee were checked by mutation: with the epoch check removed from OrderedDelivery.fulfil, the stale-epoch reset test fails (its stale ticket sits above the new base ticket, so only the epoch tells it from a live one).
  • Tests that need a pixel buffer fail, not return, when it cannot be created.
  • 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.
…e dual-layer decoder

Four self-contained pieces the dual-layer Profile 7 decoder is built from,
none of them wired to anything yet:

- HEVCPictureOrderCount: the H.265 picture order count (§8.3.1) of one
  layer, read from the parameter sets and each picture's first slice
  segment header. No decoding. Anything it cannot follow (unknown PPS/SPS,
  truncated header, pictures before the first IRAP) answers nil rather than
  a guess.
- DualLayerPictureAlignment: derives each layer's display slot from its
  POC and gives each enhancement-layer packet the presentation time of the
  base-layer picture in the same slot, so a stream whose enhancement layer
  has B-frames over a base layer without them pairs the right pictures.
  Falls back to access-unit pairing when a layer's POC is unavailable or
  the slots disagree by more than 16.
- FrameSideDataRing: fixed-capacity (32) ring of per-frame side data keyed
  by PTS, looked up within +-300 ticks.
- OrderedDelivery: hands composed frames across the VideoToolbox / Metal
  queue boundary in decode order.

Also exposes A53SEIParser.unescapeRBSP and parseHVCCParameterSets
(DoviRpuConverter+Probe) at module scope, which the POC reader and its
test use. No behaviour change: nothing calls these types. Not in this PR:
the decoder that uses them, the routing, the docs.

Tests: DualLayerPictureAlignmentTests, FrameSideDataRingTests,
OrderedDeliveryTests.
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 08:23
@superuser404notfound
superuser404notfound merged commit beb787c into superuser404notfound:main Oct 15, 2026
superuser404notfound pushed a commit that referenced this pull request Oct 15, 2026
…ps the gap

- HEVCPictureOrderCount stores an SPS only with an id up to 15 and a PPS only
  with an id up to 63 naming an SPS up to 15 (7.4.3.2, 7.4.3.3). The maps were
  keyed by an unchecked ue(v), so a stream repeating parameter sets with fresh
  ids grew them by one entry per NAL. Test included.
- OrderedDelivery's stall guard moves the head straight to the oldest pending
  ticket instead of one missing number per turn. Same frames skipped, but a
  backlog far ahead of the head no longer spins the delivery queue.
- docs/architecture.md lists the four new files.
- The real-clip suites (DualLayerPictureAlignmentTests, DoviFelRealFileTests)
  demux whole files synchronously and now take `.offCooperativePoolOneLane`.

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. The synthetic bitstream writer, with expectations worked out from 8.3.1 and not from the reader, makes the POC code checkable line by line.

Checked: both test steps locally on main with this merged (plain swift test and the one-thread pool step), 4628 tests in 634 suites, green. I also read the slice header and the SPS walk against 7.3.6.1 and 7.3.2.2, and the POC derivation against 8.3.1 (MSB wrap, prevTid0Pic, NoRaslOutputFlag, RASL skip, EOS/EOB). I found no trap and no out-of-bounds read. OrderedDelivery's locks and epochs look right as well.

Follow-up on main (f99c574):

  • HEVCPictureOrderCount stores an SPS only with id <= 15, and a PPS only with id <= 63 that names an SPS <= 15. Before, the maps were keyed by an unchecked ue(v), so a stream repeating parameter sets with fresh ids grew them by one entry per NAL. There is a test for it.
  • The stall guard now moves the head straight to the oldest pending ticket. It skips the same frames as before, but no longer spins once per missing number.
  • docs/architecture.md lists the four files.
  • The real-clip suites carry .offCooperativePoolOneLane.

Two points for #769, where the wiring decides them:

  1. FrameSideDataRing's +-300 tick window is ~3.3 ms only at 90 kHz. If the key ends up in Matroska's 1/1000 timebase, it is +-300 ms, about 7 frames at 24 fps, and after a remove… a lookup can return a neighbour's RPU. Please pin the timebase or scale the window.
  2. DualLayerPictureAlignment.extrapolate also runs for a slot below latest.slot that is missing from baseTime (pruned, or a base picture without a POC). The comment says "still to come", and the time it returns may belong to no base frame. Falling back to access-unit pairing there would match the comment.

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