Skip to content

feat(probes): Dolby Vision pulse test (clip generator, tvOS host, filming harness, analysis) - #771

Merged
superuser404notfound merged 22 commits into
superuser404notfound:mainfrom
pkajaba:fel2/7-pulse-probe
Oct 15, 2026
Merged

superuser404notfound merged 22 commits into
superuser404notfound:mainfrom
pkajaba:fel2/7-pulse-probe

Conversation

@pkajaba

@pkajaba pkajaba commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Summary

Point 5 of #702: the pulse test in the repo. Clips keep the pixels constant and switch only the RPU, or only the enhancement-layer residual, so a phone filming the TV shows whether the panel uses the metadata and the composed pixels. A measurement, not a unit test. No library code changes.

What's in it

  • Probes/DolbyVisionPulse/Scripts/: gen_pulse.py, build.sh, serve.py, run_tv.sh, cut.py (one phone recording per arm), analyze.py (verdict per arm), report.py, check_el.py (Mac check that the EL clip carries the designed residual), dump_attachments.swift, sim_recording.py.
  • Device/: a minimal tvOS host that plays the clips through AVPlayer, VideoToolbox and the FEL route, on public engine API only.
  • Clip p7fel_el.mp4: constant RPU, EL residual switching on 6 patches. Arms: TE (route on) and NE (flag off, 8.1, EL dropped).
  • Counter clips p7fel_count_{null,l2}.mp4 and the control count_mel.mp4 (fel_count.py, built by build.sh): the base layer draws its frame number in its pixels, the enhancement layer draws its own only in the residual, both on one fixed GOP. On screen, matching "BL" and "EL" numbers show the residual applied to the right base picture, an empty EL panel shows it dropped, a different number shows a pairing error. SEQ=count plays T (route on), NE (flag off), TL (route on, the RPU pulses on top) and PM (AVPlayer on the 8.1 base layer). fel_count.py read checks composed frames off the TV. On the Mac our composer and DoViBaker both read BL = EL on every captured frame.
  • CI compiles the scripts and builds the host for the tvOS simulator.
  • Robustness of the scripts (from the review-fix round):
    • cut.py runs on the system Python 3.9 of macOS: ISO 8601 times with Z, +0100 or +01 and any number of fractional digits are normalised before datetime.fromisoformat, which takes them natively only from Python 3.11.
    • build.sh checks only the tools it uses (x265, dovi_tool, MP4Box, python3, curl) plus the numpy module with an install hint; ffmpeg is named as needed by the analysis scripts only. The FEL template is fetched from a pinned dovi_tool commit and checked by hash, not from main.
    • run_tv.sh stops with a message when this Mac has no address on en0 or en1, instead of continuing with an empty one.
    • build.sh and run_tv.sh are executable, so the README's first step runs as written.
    • run_tv.sh builds with the Xcode that xcode-select points at (DEVELOPER_DIR overrides) instead of a hard-coded /Applications path, and takes IFACE=<interface> for a Mac whose address is not on en0 or en1.
    • Pillow is optional as the README says: cut.py writes its per-arm plot only when Pillow is installed.
    • The README pins the fel_orig.bin URL to the same dovi_tool commit as build.sh and has a Tested-with line. The tool versions were not recorded anywhere in the probe, so the line carries placeholders (ffmpeg, dovi_tool, x265, MP4Box, Python, Xcode, tvOS) for the author to fill in before this is sent.
    • The one sentence in section 4.5 of the design document that promised the probe in a later PR now links to it.
    • serve.py ignores a Range: bytes=- header (RFC 9110: an unparsable range is ignored) and serves the whole file.
    • The Xcode project's local-package folder reference is named AetherEngine, not after a developer's checkout directory; project.yml says to rename it back after regenerating with XcodeGen.
  • CHANGELOG entry; README of the probe. No media is committed. The evidence section it feeds (section 4.5 of the design document) arrived with feat(dovi): route Profile 7 FEL to the dual-layer decoder behind preferDualLayerDolbyVision #770.
  • Public API: none.

How it was tested

  • Python and shell syntax of the scripts (cut.py also exercised with the time formats above), swiftc -typecheck of dump_attachments.swift, xcodebuild of the host for the tvOS simulator: BUILD SUCCEEDED.
  • swift build --build-tests and aetherctl build at this commit (the Swift package is unchanged).
  • sim_recording.py through analyze.py checks the analysis before a real recording is trusted. check_el.py on the Mac passes on all 1584 frames of the EL clip.

Apple TV results (EL and counter arms, follow-up)

The RPU pulse arms were filmed on an earlier build (#702 comment). The EL and counter arms below need the screen filmed on this stack; the results follow as a comment. Full table in #770.

Arm Verdict (pulse arms: per patch; counter arms: BL vs EL number)
TE (route on) pending
NE (flag off, 8.1) pending
count T (route on) pending
count NE (flag off) pending
count TL (route on, RPU pulse) pending
count PM (AVPlayer, 8.1 base) pending

What it does not do

  • Needs a television, an Apple TV and a phone on a tripod; CI only compiles.
  • The verdict comes from filmed brightness, so it is sensitive to camera drift and exposure; the probe README describes the controls.

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.
DualLayerVideoDecoder: the decoder half of the dual-layer route. It splits
each packet into base layer, enhancement layer and RPU
(DoviRpuConverter.separateDualLayers), decodes both layers on VideoToolbox
through two HardwareVideoDecoder sessions, pairs them by HEVC picture
order, composes with DoviFelComposer and delivers the frames in decode
order with the Profile 8.1 RPU attached per frame.

- Pairing: DualLayerPictureAlignment restamps each enhancement-layer
  packet with the time of the base picture in the same display slot, so an
  enhancement layer coded with B-frames over a base layer without them is
  no longer paired with a neighbouring frame's residual. A layer keeps
  access-unit pairing until its next sequence-opening IRAP after a seek.
- Bounded memory: base-layer skew K = 3 frames, at most 10 waiting
  enhancement frames, output pool 15 plus a reserve of 3. A late or broken
  EL falls back to the base layer for that frame.
- Seeks: a seek flushes every stage. A stale EL is never paired with a
  post-seek base layer and a stale BL is never delivered. The composer's
  output pool is kept across the flush instead of being dropped (it made
  the frames after a seek allocate a second pool beside the buffers the
  renderer still held): peak footprint on a 12-seek run of one test clip
  went from 674 MB to 500 MB. The pool is dropped on close.
- HardwareVideoDecoder gains an opt-in no-copy block source and a
  parameter-set open for the enhancement layer; both are off for every
  existing caller. FelResidualMeasure (the AETHER_FEL_MEASURE diagnostic,
  off by default) is here because the decoder calls it.

Nothing constructs the decoder yet: no host code selects it until the route
PR, so no source plays differently after this one. Public API: none. Not in
this PR: the capability gate, the preferDualLayerDolbyVision flag, host
wiring, dolby-vision-fel.md.

Tests: decoder, GPU slot wait, seek realignment (flush of both sessions and
the composer, stale EL not composed, waiting BL dropped at the seek, seek
during an in-flight composition), stream classification and packet balance,
CPU model, output-pool-across-flush, real-clip tests (gated on
DV_FEL_TESTS_DIR, skipped without), and a subtitle compositor test that the
Dolby Vision attachments survive compositing.
…erDualLayerDolbyVision

Host wiring for the composer and decoder. LoadOptions.preferDualLayerDolbyVision
(default false) makes a Profile 7 FEL file play through SoftwarePlaybackHost
and DualLayerVideoDecoder when the box can afford it; otherwise the existing
Profile 8.1 conversion is untouched. With the flag off no source plays
differently.

- DualLayerRouteDecision: a pure capability gate. The route is taken only
  for FEL, with a proven hardware HEVC session, a seekable VOD,
  dolbyVisionHandling .automatic and a stream inside the real-time budget
  ((3840x2160 + 1920x1080) x 30 = 311.04 Mpx/s; a 24p UHD FEL with a
  quarter-area EL needs 80%; an unknown frame rate is budgeted as 24). Every
  Profile 7 load logs exactly one `DV P7 dual-layer route: taken|not taken
  (<reason>)` line. It fails closed: when the base-layer size is unknown the
  budget cannot be evaluated, so the route is refused rather than assumed.
  The budget is an assumption until the Apple TV run confirms it.
- Wiring in AetherEngine, SoftwarePlaybackHost, VideoRoutingPolicy,
  CodecRoutePolicy and the reload path (preferDualLayerDolbyVision is a
  tuning field, correctable through reloadAtCurrentPosition(applying:)).
  An `hev1` source with in-band parameter sets (an empty hvcC) is completed
  from the head of the stream so it can be classified and take the route,
  the same rebuild the native path already does for its init.mp4.
- Audio trade-off, documented in LoadOptions, api.md and
  dolby-vision-fel.md and pinned by DualLayerRouteAudioTests: the route runs
  on the software host, whose audio FFmpeg decodes and the sample-buffer
  audio renderer plays, and on tvOS only AVPlayer emits Atmos objects. An
  E-AC-3 (JOC) track therefore plays as its 5.1 / 7.1 channel-bed core,
  without the objects, where the native route would hand it to AVPlayer
  unchanged. Not engineered around.
- Docs: dolby-vision-fel.md (the design), api.md, formats.md, README, and
  the DocumentedConstantsTests pins that tie the document's numbers to the
  code (route budget, pipeline bounds, picture-order pairing bound). The
  document arrives here, whole; code comments in the earlier PRs cite its
  section numbers.

Mac soak, measured BEFORE the output-pool fix of the decoder PR (peaks are
pre-fix; with it 12 seeks peak at 500 MB instead of 674 MB), M2 Pro, debug
aetherctl, --window:

| Run | Route | Composed / failures | Seeks landed | Drops | Steady | Peak |
|---|---|---|---|---|---|---|
| 217 s, 12 seeks | taken, budget 80% | 6143 / 0 | 15 | 6 / 6206 | 328-331 MB | 674 MB |
| 120 s, 11 seeks | taken | 4248 / 0 | 12 | 7 / 4275 | 282 MB | 600 MB |
| pause + seek while paused | taken | 2005 / 0 | 1 | 1 / 1949 | 330 MB | 352 MB |

Apple TV results: pending, nothing measured on device yet.

Tests: DualLayerRouteDecisionTests (one per exit), VideoRoutingPolicyTests,
SoftwareDecoderSelectionTests, InBandParameterSetRebuildTests,
DualLayerEdgeCaseTests, DualLayerRouteAudioTests, LoadOptionsTests,
DocumentedConstantsTests. Not in this PR: the pulse probe and the aetherctl
tooling.
…ming harness, analysis)

Probes/DolbyVisionPulse: a reproducible measurement of whether a panel
follows Dolby Vision metadata. Clips keep the pixels constant and switch
only the RPU (or, for the enhancement-layer clip, only the residual) every
72 frames, so a phone filming the television shows whether the display
uses the metadata and the composed pixels. It is a measurement, not a unit
test, and it commits no media.

- Scripts: gen_pulse.py (pattern, RPU configs, EL residual design),
  build.sh, serve.py, run_tv.sh, cut.py (one phone recording per arm),
  analyze.py (verdict per arm), report.py (the change-per-patch table and
  phase-A levels), check_el.py (checks on the Mac that the EL clip carries
  the designed residual in phase B and none in A), dump_attachments.swift
  (what VideoToolbox attaches to a decoded frame), sim_recording.py (a fake
  recording that validates the analysis).
- Device/: a minimal tvOS host that plays the clips through AVPlayer,
  VideoToolbox and the FEL route (preferDualLayerDolbyVision). It uses only
  public engine API.
- CI: compiles the scripts and builds the host for the tvOS simulator, so a
  moved public API is found in CI instead of at the television.
- The pulse test is the measurement behind the consumption evidence in
  docs/dolby-vision-fel.md section 4.5, which arrived with the route PR.

No library code changes and no behaviour change. Public API: none. Not in
this PR: the aetherctl tooling. The host builds in CI; the rest needs a
television and a phone.

Checked here: Python and shell syntax of the scripts, swiftc -typecheck of
dump_attachments.swift, xcodebuild of the host for the tvOS simulator
(BUILD SUCCEEDED), swift build --build-tests of the package.
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.
… Hz summary at verbose

DualLayerVideoDecoder.swift (and its tests):

- Prefix: the per-frame and summary lines said "[DualLayer]" while the lifecycle lines said
  "[DualLayerVideoDecoder]". All use the type name now, as "[HardwareVideoDecoder]" does.
- Shouting tags to phrases, all still .verbose: "QUEUE BL" -> "queued base layer", "QUEUE EL" ->
  "queued enhancement layer", "DROP stale EL" -> "dropped stale enhancement layer", "PRUNED EL"
  -> "pruned enhancement layer", "BYPASS no-EL" -> "bypass, no enhancement layer arrived",
  "Bypass: ..." -> "bypass, <reason>: ...", "COMPOSE FAILED (BL arrived)" -> "compose failed
  (base layer arrived last)".
- The 1 Hz "summary:" line goes from the default level to .verbose, except for a second whose
  counters include a compose failure, which stays at the default level so a failure is visible
  without enabling debug output. Healthy playback now writes nothing per second to the host
  handler.
- "S1:" in two comments next to the missing-RPU bypass is dropped; it named nothing a maintainer
  can look up.
- Tests: the summary tests read the line and its level through a DEBUG-only
  summarySinkForTesting, because .verbose never reaches EngineLog.handler; the per-frame-at-info
  test checks the new texts; a test pins that a summary with a compose failure goes out at the
  default level.

Kept at the default level, unchanged: no composer, FEL/MEL detected, primary and secondary
decoder opened, the two decoder open failures, and the one-time "reordered against the base
layer" notice. Each fires once per open or per detection.

Not changed: the verbose lines still build their text eagerly (String(format:) of the pts, queue
counts) in the pairing paths, under the decoder lock, because EngineLog.emit takes a String and
not an autoclosure.
docs/dolby-vision-fel.md sections 5.1 (rule 5), 5.10 (CPU table) and 5.11 described a 1 Hz
summary at the default level and a "[DoviFelComposer] gpu ... ms/frame" line that "stays".
Both are .verbose now (see the dual-layer decoder and composer log commits), so the text says so,
gives the log stream command that shows them, and names the one exception (a summary that counts a
compose failure stays at the default level). The summary prefix is "[DualLayerVideoDecoder]".
…reach the handler

DolbyVisionPulseHostApp.swift, SoakTally: it summed composeFailures= over the engine's 1 Hz
"[DualLayer] summary" line seen through EngineLog.handler, and took the presence of that line as
proof the FEL route ran. The summary is .verbose now, which never reaches the handler, except for
a second that counted a compose failure, so the sum stays exact. The route marker is the
once-per-open "[DualLayerVideoDecoder] FEL stream detected" line instead (still the default
level), and the matched prefix follows the rename from "[DualLayer]".
…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 10:38
superuser404notfound pushed a commit that referenced this pull request Oct 15, 2026
serve.py answered a multi-range or otherwise malformed Range header with 416
while it already ignored `bytes=-`. RFC 9110 says to ignore a Range header the
server cannot parse, so every such header now falls back to the whole file.

Follow-up to #771.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WJcXkGQrMiBPixVEFTSBJS
@superuser404notfound
superuser404notfound merged commit 1269564 into superuser404notfound:main Oct 15, 2026
@superuser404notfound

Copy link
Copy Markdown
Owner

Merged in 1269564, thank you. A self-contained, repeatable measurement with the analysis checked against a simulated recording first is exactly what this route needed before anyone trusts it on a panel.

One small follow-up on main, 104fa4d: serve.py now ignores every Range header it cannot parse (multi-range included) and serves the whole file, as it already did for bytes=-, instead of answering 416.

Notes from the review, none blocking, for whenever you touch the probe again:

  • run_tv.sh pipes the host build through tail -1, so a compile error shows only its last line.
  • PULSE_ARMS goes into the launch JSON unescaped, and the host splits it on commas, so a SOAK_URL with a quote or a comma in its query would break.
  • Each VideoToolbox arm leaves its downloaded clip in tmp (only the last one, since the name repeats).

Looking forward to the filmed EL and counter arms on this stack.

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