Skip to content

media: apple: preserve stock VP9 and add queued frame operations - #704

Closed
RyanTheTide wants to merge 42 commits into
aurora-wipfrom
avd/rewrite-vp9
Closed

RyanTheTide wants to merge 42 commits into
aurora-wipfrom
avd/rewrite-vp9

Conversation

@RyanTheTide

@RyanTheTide RyanTheTide commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

VP9 keeps the stock-firmware builder byte-identical to avd/rewrite-integ at d826cca0dff6 (only its exported ops symbol changes), while ABI-2 queued open firmware uses avd_codec_frame_ops. Callback selection is fixed for the stream's lifetime. The integration core's extended queue header and closing-stream drain fix are retained.

Queued frames own separate probability/count/scratch buffers, VP-to-PP FIFOs and tile-count snapshots. Backward-refresh producers set PREV_DONE, so the core waits for their counts before preparing the next probabilities; other frames can overlap. Seventeen pinned segmentation maps prevent slot reuse from overwriting a live input map. Physical FIFO capacity bounds slot reservation. Context reset/forward updates commit only after validation, and the program preserves the context's decompression setting.

Apple payload support remains incomplete and disabled. The V3 table follows Eileen Yoon's MIT layout; Borage fills the proved tile/command fields. Unknown PIO/work records, syntax/surface mappings and packed addresses are not guessed. T6000/T8112/T8140 remain explicit Daybreak-ledger TODO rows; the accepted clean ledger identifies M1 Pro as LilyD, distinct from public Viola/V3. These incomplete packers do not replace working stock decoding.

Validation:

  • Host suite passes normally and with AddressSanitizer/UndefinedBehaviorSanitizer. It covers 16 prepared slots, real V4L2 entropy helpers, producer dependencies, map/FIFO isolation, malformed-input rollback, DMA carry, Profile 2 syntax and all compatibility callback dispatches.
  • Both complete C builders produce identical normalized programs for 480 synthetic 1080p/4K cases at FIFO 0 across the actual V3, M1 Pro, M2 and newer V4 instruction variants, 8/10-bit, key/inter, tiles and segmentation. A checksum protects the complete stock source.
  • arm64 external-module build against 7.3.0-aurora-tt3, W=1 KCFLAGS=-Werror: PASS, including modpost. The unmodified Linux queue-host test and the complete VP9 sanitizer suite also pass on the build host (100,000 shuffled queue operations; 36,424 ordered retirements).

This stays draft. Complete Apple payloads, libvpx/stateless-request differential streams, and native queued decode/CRC/throughput qualification remain required. No target hardware testing was performed; source/program equivalence does not establish preservation of measured hardware throughput.

Keep the legacy open firmware serialized while moving program storage and completion ownership into tagged frame slots. Leave Borage activation dependent on the register and completion facts absent from the clean specification.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Add deterministic host tests against production helpers and KUnit coverage of slot reuse, ordered retirement, watchdog wrap, inbox retry, command builders and completion parsing. Track the unproved Borage fields explicitly and preserve session generations over firmware reboot.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Move VP9 preparation and retirement onto frame_ops with per-slot scratch and probability snapshots and pinned segmentation maps. Add the shared queue contract and partial, fail-closed Apple layout packers with host checks. Queue-core retry integration and unresolved Apple payload fields remain draft requirements.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Keep map pin/release operations independently testable, cover slot reuse with 16 frames and compare materialized EXEC framing with legacy words. Follow the actual V3 Construct tile-record offset after its explicit zero word.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Remove contexts from the scheduling list before releasing their m2m state, reject already-scheduled jobs during teardown, and keep Apple fp pointers absent on the open backend. Preserve tagged slots over inbox-full retries and avoid periodic watchdog wakeups when only submitted frames remain.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Keep the CODECS trailer intersection with the SoC capability table when selecting the open backend. Bound firmware copies by the mapped code resource.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Only the H.264 compatibility builder explicitly completes held slice requests during preparation. Continue submitting legacy HEVC requests that retain their capture buffer.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Compile the complete codec on the host using the real kernel UAPI and V4L2 probability helpers, with only DMA and controls emulated. Cover 16 frames, forward and backward refresh, segmentation, malformed input, errors and Profile 2, including AddressSanitizer.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
…ation

Prevent queued contexts from observing the same free capacity. Run preparation on a context work item because m2m try_schedule can invoke device_run synchronously while the queue mutex is held. Drain that work before freeing the context.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Keep power through slot retirement and context drains, restore firmware before retrying reserved frames, and defer DMA releases while the DART is inactive. Re-enable a retained Apple MCPU image before mailbox link setup, without uploading it again. Pause and drain the queue for system sleep and final teardown.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Request the mailbox IRQ without automatic enable, open it only after successful firmware boot, and synchronize and close it after backend suspend. Close the host IRQ on teardown even if the final PM transition fails.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Map only DT-declared PIODMA and SRAM resources and replay the shifted SRAM base before every open CM3 boot. Keep reset, empty-domain attach/detach and firmware reboot ordered; refuse to reboot if the DMA domain cannot be restored. Keep host IRQs closed until old slots are invalidated. Add synthetic-RAM boot replay and recovery-gating KUnit coverage. Queued PIODMA use still requires the DT to describe the DMA stream as well as decode.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Replay PIODMA setup in the common boot dispatcher so queued open transports inherit it even with their own mailbox boot implementation. Keep firmware generation handling and initial-only backend fallback in the same dispatcher, and test the real open boot path through it.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Brings in the frame-queue core (avd/rewrite-core) and its runtime and
system PM, PIODMA replay and DART recovery (avd/power-idle).

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Each frame in VP to PP flight owns one hardware instruction FIFO, named
by EXEC bits 7:4. The hardware has 15 of them on v3 and later tier 1
parts and 7 on T8103 and T8140, so the 16-slot queue must not keep more
frames in flight than the variant has FIFOs.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
T6040 decodes HEVC with the v5 header. Add HEVC to its capabilities but
keep it hidden unless the loaded open firmware lists h265 in its CODECS
trailer, so older firmware without the trailer behaves as before.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
When the VP instruction queue is at least half full the open transport
slept a fixed 500-650 us (100-150 us on parts with v5 pacing) before the
next segment. Poll the queue level every 10 us instead and continue as
soon as it drops below half, keeping the old sleep as the upper bound.
The submission order and queue thresholds do not change.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
The open transport writes every instruction word to the VP FIFO register
from the CPU, sleeps while the FIFO is half full, and kicks the PP from
the VP-done interrupt thread, one frame at a time.

avd-fw queue ABI 2 moves all of that into the CM3. The host streams each
frame program into a word ring in CM3 SRAM, posts a 64-byte descriptor
and rings mailbox 0; the firmware feeds the VP FIFO, writes the PP kick
(plus one continuation kick per extra segment for HEVC, VP9 and AV1)
when the VP is done, and posts a tagged completion on mailbox 1. No
PIODMA is used, so the second DART stream that the current device trees
lack is not needed.

The transport is chosen after every firmware boot from the image info
block: ABI 2 with the SRAM ring, and an SRAM aperture matching the node.
Anything else keeps the legacy transport. Each frame in flight gets its
own instruction FIFO (the slot index), and the queue keeps at most the
FIFO count in flight. Frames of one context stay serialized by the
queue core, so different streams overlap; within a stream the gain is
the removed CPU word writes, pacing sleeps and interrupt round trip.

T6040 now loads avd-fw-v5-t2, whose SRAM aperture matches the node, and
falls back to v5-t1 when that image is not installed.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
CM3 SRAM keeps its contents across a firmware reload. After an ABI 2
image ran, a later boot of an older image would still show the queue
info magic and the driver would pick the queued transport for firmware
that does not speak it. Clear the magic before every open-firmware boot
so only an image that publishes it again selects queue mode.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
With the firmware chaining VP to PP, the VP of picture N+1 can run while
the PP of picture N is still busy, but the legacy H.264 builder kept one
set of scratch buffers, one VP to PP instruction FIFO and one slice table
per context, and the queue core held the m2m scheduler until a picture
retired.

Give H.264 two banks of everything the hardware touches while decoding a
picture (instruction FIFO, pipe state, above, loop-filter and MV row
buffers) and of the slice copies. A new picture takes a free bank and
records it in its CAPTURE buffer; retirement frees that bank. Pictures
whose last slice never arrived restart in their own bank. The legacy
transport keeps one bank, so nothing changes there.

The queue core now lets a legacy codec context hold as many pictures as
it has banks, carries each frame's FIFO address to the transport, and
only keeps the m2m scheduler for slices that hold their CAPTURE buffer,
so the next picture is prepared while the previous one decodes.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
… the queue image

HEVC gets the same two-bank treatment as H.264 on the queued transport:
the VP to PP instruction FIFO, pipe state and all row/column scratch
exist once per bank, a picture records its bank in its CAPTURE buffer,
and a new done hook frees it at retirement. The VP of picture N+1 then
overlaps the PP of picture N. The legacy transport keeps one bank. The
per-buffer bank field is now shared by both codecs.

Codecs a variant holds back until a newer firmware (fw_caps_required,
T6040 HEVC) are now also enabled when the loaded image runs the queue
ABI and lists the codec in its info-block codec mask, not only through
a CODECS trailer. Falling back to the legacy transport restores the
trailer-derived set.

Both the transport choice and the codec list come from what the image
reports at boot, and clients enumerate formats and size their contexts
before a first decode would power the decoder up, so boot the firmware
once at probe and let it autosuspend.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
avd_frame gained a DMA address for its instruction FIFO, and the host
build of the queue test has no dma_addr_t. Define it in the host shim.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
…eue_mutex

The threaded interrupt handler takes queue_mutex before it touches the
decoder. Queue reset runs from the queue worker with queue_mutex held,
and its recovery called disable_irq(), which waits for that handler
thread. When an interrupt arrived around a frame timeout, the handler
blocked on queue_mutex and the reset blocked on the handler: the worker
and the IRQ thread deadlocked with the mutex held. Runtime suspend had a
similar cycle with a submission waiting for it under queue_mutex.

Close hardware access with a spinlock instead: the handler runs the
backend's interrupt code only under irq_lock, with hw_on set and the
interrupt generation it sampled before taking queue_mutex unchanged.
Turning the IRQ off clears hw_on and bumps the generation under that
lock, so an access in progress finishes first and a handler woken by an
older firmware instance leaves the hardware alone, and then uses
disable_irq_nosync(). Device removal, which holds no queue_mutex, still
synchronizes with the handler.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
The old driver kicked the PP for every VP DONE message of the open
firmware. The legacy shim in the frame queue dropped a VP DONE that came
in while no frame was in flight. That happens when a surplus PP DONE of a
multi-kick picture completed the next frame early: the next frame's VP
DONE then found no active frame, its PP was never started, and it timed
out. Kick PP for the last submitting context in that case, as before.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Reading MBOX1_RETRIEVE when the mailbox is empty returns the previous
message again. On a spurious or early interrupt that is a repeated PP
DONE, which completes the next frame before its PP has run. The next PP
then never reports done, the frame times out and the decoder is reset.
The legacy shim and the queued transport both popped unconditionally.

Check the empty flag in MBOX1_STATUS (bit 17) first, give a message that
is not readable yet up to 10 us, and otherwise acknowledge and ignore the
interrupt. Both transports share the helper.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
A frame timeout on the J616s was followed by the machine going down with
nothing in the journal, so nothing showed how far the recovery got.
Log every recovery step (stop firmware, reset, DART flush, firmware boot)
before it runs, with the DART, runtime PM and IRQ state at the start,
refuse and warn once if recovery is ever entered with the decoder powered
off, and name the codec, slot state, frames in flight and transport in
the timeout message.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
… a loop

The Neo hung after a burst of "H0 error" (VP0, the HEVC VP, raising its
error interrupt) with "Frame processing timed out!" for every frame: each
error reset the decoder (pmgr reset, DART empty-domain flush, firmware
reload), the next frame of the same broken stream failed at once, and the
resets ran back to back, up to one per millisecond, until the machine
stopped. The frame queue inherited the same loop.

Bound it at three levels:
- A stream that fails three frames in a row in hardware is stopped: its
  frames complete with an error, without touching the decoder, until
  streaming is restarted.
- Decoder recoveries are at least 20 ms apart.
- More than eight recoveries within 10 s put the decoder in a 10 s
  cool-down in which new frames fail at once.

A faulted decoder (failed recovery) no longer blocks the m2m scheduler,
which left clients waiting forever: its frames fail at submission, the
request controls are completed so the request fd signals, and the next
clean power-up clears the fault.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
The HEVC builder computes each slice's coded data address and size from
GStreamer's layout: slices tile the OUTPUT buffer as whole NALs, bit_size
covers the whole NAL and data_byte_offset is the slice data's offset in
it. FFmpeg's V4L2 request backend gives data_byte_offset from the start
of the buffer and a bit_size of the slice data only. Every slice then got
a wrong address and a size short by its header, the VP raised its error
interrupt on every frame, and the decoder was reset once per frame. This
is the "H0 error" storm the Neo hit in an FFmpeg-based benchmark.

When the slices describe a complete, unambiguous absolute layout, rewrite
the run's private copy into the equivalent NAL-relative description. The
GStreamer layout and anything ambiguous are left untouched.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
avd-inst.h builds every instruction word with FIELD_PREP() but relied on
an indirect include. The arm64 build gets it through other headers; the
UML KUnit build of the avd tests does not and fails.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
The recovery trail queried the runtime PM state before the existing
inactive-DART check, which the PM KUnit test exercises with no device.
Check the DART first and log that case on its own.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
…e context

job_ready() admitted at most one context at a time (queued_ctx) and only
while a slot was free. Contexts that queued work while another was
admitted were rejected, and were retried only from the queue worker,
which walks the context list in order: the first context won every time
and later ones could wait for seconds. With four streams the starved
stream's OUTPUT buffer was not returned within FFmpeg's two-second poll
("Failed waiting on OUTPUT buffer") and the run failed, with no decoder
timeout or error.

Drop the reservation and the capacity condition from job_ready() so every
context with work enters the m2m job queue, which runs jobs one at a time
in arrival order. A job that finds no free slot or no transport capacity
is kept as m2m's running job and restarted by the queue worker once a
frame retires; draining its context finishes it.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
The deferred-dispatch restart in the queue worker called the backend's
max_inflight() unconditionally. The PM KUnit fixtures use backends
without a transport and crashed there. Treat a missing hook as one frame.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
The J616s hung hard three times during decode benchmarks, each time
after frame timeouts and decoder resets, once beyond what the hardware
watchdog could recover. A stuck bus access, a reset that cuts DMA in
flight, or DMA into memory the driver already gave back can do that.
Close each of those paths:

- Recovery stops the CM3 firmware, then blocks the decoder's DMA by
  attaching the empty IOMMU domain and lets in-flight transfers drain
  into DART faults, and only then asserts the pmgr reset. The domain is
  restored after the reset and checked before the firmware boots.
- A third recovery within a minute, or any failed recovery, retires the
  decoder: every later frame fails at submission without touching the
  hardware until the module is reloaded. A stream is stopped at its
  first frame that fails in hardware.
- The legacy transport never writes the VP FIFO register without room in
  its queue: it checks the level before every word (the old code only
  looked between segments, and programs exceed the 128-word queue),
  waits up to 2 ms for room, and otherwise leaves the frame to the
  watchdog.
- A PP DONE completes the active legacy frame only after its VP finished
  and its PP was kicked. A surplus PP DONE of a multi-kick picture no
  longer completes the next frame while the engine is still writing it.
- The interrupt handler's hardware access lock is now a mutex, so no
  decoder register is touched with interrupts off.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
…tting

Closing a stream (STREAMOFF, close or an m2m job abort) while it still
owned a slot reset the whole decoder, cancelling every other stream's
frames with their DMA in flight. On the J616s both resets logged before
the 04:11 hard hang came from this path (no frame had timed out), each
when FFmpeg gave up on one of four concurrent streams.

Cancel the closing stream's frames that never reached the decoder, then
wait for the ones it already owns. They complete normally, or the queue
worker times them out and recovers as for any other stuck frame. Only
if frames are still owned a second after the frame timeout does the
drain fall back to the old reset, and it says so in the log.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Retain the integration core and stream drain fix, including its extended queue contract.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Keep the stock VP9 implementation unchanged behind the compatibility transport and select per-stream frame operations only for queued or Apple firmware. Preserve the integration core queue contract and drain behavior.

Give queued VP9 frames their own VP-to-PP FIFO and tile-count snapshot, restrict reservations to physical FIFO indices, and mark backward-refresh producers PREV_DONE before the next probability preparation. Stage context resets and probability updates until packing succeeds, and preserve the context decompression bit in the generated header.

Host tests compare 360 complete normalized programs with the stock C builder, check the stock source identity and compatibility callbacks, and exercise entropy/FIFO isolation across 16 prepared slots. Apple payload completion and hardware qualification remain separate draft prerequisites.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
@RyanTheTide RyanTheTide changed the title media: apple: draft VP9 frame_ops and Apple parameter layouts media: apple: preserve stock VP9 and add queued frame operations Oct 31, 2026
The accepted clean Daybreak ledger identifies T6000 as LilyD, with a different Apple frame-parameter layout from public Viola/V3. Keep a distinct unsupported row until its remaining syntax and address meanings are proved, and exercise that row in the host layout tests.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
Exercise the actual revision/LSR/pipe-state combinations used by M1 Pro and M2 in addition to public V3 and newer V4 headers. Compare 480 complete FIFO-0 programs with normalized scratch addresses, preserving both decompression settings and Profile 0/2 syntax.

Assisted-by: LLM
Signed-off-by: Ryan Murray <[email protected]>
@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Closing per the one-PR-per-series rule. The branch stays and gets integrated into the AVD rewrite, which lands as one PR once it works on hardware.

@RyanTheTide RyanTheTide closed this Nov 1, 2026
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.

1 participant