Repository navigation
media: apple: avd: update decoder and improve playback reliability - #45
Merged
Acelogic merged 29 commits intoOct 2, 2026
Merged
Conversation
Signed-off-by: sofus <[email protected]> (cherry picked from commit 2fcd762)
Signed-off-by: sofus <[email protected]> (cherry picked from commit 074acce)
Signed-off-by: sofus <[email protected]> (cherry picked from commit 54e5d74)
Signed-off-by: sofus <[email protected]> (cherry picked from commit c35aebe)
Moves the "program hw" logic away from the "prepare instructions" logic. Removes the broken vp/fifo slot logic, but adds manual slice buffer handling to h264 Signed-off-by: sofus <[email protected]> (cherry picked from commit 491f655)
Signed-off-by: sofus <[email protected]> (cherry picked from commit 42ffc49)
The capture buffers are allocated with vb2_dma_contig_memops on a device
that is not marked dma-coherent, so both the kernel and the user space
mapping are Normal-NC (pgprot_dmacoherent()). Reading decoded frames back
through such a mapping is extremely slow on Apple silicon: every load is
a serialised uncached DRAM transaction, and neither wider loads nor
non-temporal loads help.
Measured on an M1 Mac mini (T8103) with one 2304x1296 NV12 capture
buffer (13.2 MB plane, 4.5 MB of it image data) mapped by user space:
mapping memcpy NEON ld1x4 ldnp/stnp read-only u64
coherent (Normal-NC) 240 MB/s 250 MB/s 246 MB/s 124 MB/s
non-coherent (cacheable) 17.9 GB/s 23.8 GB/s 23.9 GB/s 18.8 GB/s
For a client that copies the frames to system memory (ffmpeg's
v4l2request hwaccel without a DRM-PRIME consumer, as used by Frigate)
that is ~18 ms of CPU time per 2304x1296 frame just for the copy, which
made hardware decode cost 4-5x more CPU than software decode.
Let user space opt into cacheable buffers with the standard videobuf2
mechanism: set allow_cache_hints on both queues so that
V4L2_MEMORY_FLAG_NON_COHERENT (REQBUFS/CREATE_BUFS) and
V4L2_BUF_FLAG_NO_CACHE_{INVALIDATE,CLEAN} (QBUF) are honoured, and
advertise V4L2_BUF_CAP_SUPPORTS_MMAP_CACHE_HINTS. videobuf2 then
allocates with dma_alloc_noncontiguous(), maps the buffers cacheable and
does the cache maintenance in prepare/finish (clean before the hardware
runs, invalidate at DQBUF), so the data is still correct without any
assumption about the fabric's coherency.
DMA_ATTR_NO_KERNEL_MAPPING has to go from the capture queue:
dma_alloc_noncontiguous() rejects every attribute other than
DMA_ATTR_ALLOC_SINGLE_PAGES (WARN_ON_ONCE in kernel/dma/mapping.c) and
the allocation fails with -ENOMEM. The attribute was ineffective anyway:
with an IOMMU and a blocking allocation iommu_dma_alloc() always goes
through iommu_dma_alloc_remap(), which creates the vmap mapping
regardless of the attribute.
Clients that do not pass the flag are unaffected (same coherent
allocation and mapping as before). With ffmpeg requesting
V4L2_MEMORY_FLAG_NON_COHERENT for its capture buffers, the
Frigate-like chain "-hwaccel v4l2request -i 2304x1296.h264 -vf
fps=5,scale=640:360 -f rawvideo -pix_fmt yuv420p" for 150 frames goes
from 2.97 s user + 0.09 s sys to 0.36-0.40 s user + 0.11-0.14 s sys
(software decode: 0.53 s user single-threaded, 0.76 s with the default
thread count), output bit-identical. Decode + read-back alone
("-f null -") goes from 2.75 s to 0.08 s user + 0.12 s sys, the
remaining sys time being the cache maintenance over the 13.2 MB planes.
Verified with the full clip matrix (gst v4l2slh264dec, coherent buffers,
unchanged) and repeated per-frame md5 comparison against software decode
with the non-coherent buffers.
…ries
stream_refs() pushes a reference header and its RVRA addresses only for
the DPB entries flagged V4L2_H264_DPB_ENTRY_FLAG_VALID, and the slice
commands index the references by DPB index. Nothing checks that the
indices in ref_pic_list0/1 point at VALID entries, so a slice that
references any other entry makes the VP dereference an uninitialised
reference slot:
apple-dart 269010000.iommu: translation fault: status:0x80000002
stream:0 code:0x2 (NO PMD FOR IOVA) at 0x8080800
avd 269080000.avd: Frame processing timed out! Vp: 255 (00)
i.e. a DART fault, a frame that never completes and, two seconds later,
a watchdog reset of the VP, which also disturbs the other contexts that
are decoding at the time.
This is what happens every time a client starts decoding on a non-IDR
frame, e.g. ffmpeg's v4l2request hwaccel joining a live RTSP stream
mid-GOP: the decoder has no reference pictures yet, the DPB control is
empty, and the hwaccel leaves the index of a reference it cannot find
at 0.
Validate the ref lists of P and B slices before anything is pushed to
the hardware and fail the request with -EINVAL, so the client gets the
capture buffer back with V4L2_BUF_FLAG_ERROR just like for corrupt
input and the hardware is never programmed with the bogus references.
Other stateless drivers (hantro, rkvdec) handle missing references by
substituting the destination buffer; here the safe choice is to reject
the slice, since the reference slot table cannot be filled for an entry
that has no buffer.
[7.1.13 port: the check runs right after avd_run_postamble(), so the
media request of a rejected slice is still completed (returning before it
leaves the request pending and every later request on the context fails
with EBUSY); the slice already copied is freed by avd_h264_done().]
avd_init_job() allocates MAX_SLICES (4096 for H.264) struct avd_segment entries of 2056 bytes each - about 8.4 MB, an order-10 allocation on a 16K-page kernel - with kzalloc() for every frame. Once the page cache is full of file pages (an NVR writing recordings) that contiguous allocation fails, the frame is returned with an error and the output silently loses frames: with four concurrent 2304x1296 decodes on T6000 the page allocation failure was logged in avd_init_job() and all four outputs differed from the single-stream reference. The table is only read by the CPU (its instructions are written to MMIO with writel()), so it does not need physically contiguous memory. Use kvcalloc()/kvfree(), which also checks the multiplication for overflow.
avd_h264_run() appends every slice to h264_ctx->slices[] and increments slice_num, and avd_h264_done() frees slices[0..slice_num) once the capture buffer is no longer held, but slice_num is only ever zeroed by the kzalloc() in avd_h264_start(). On a long-running stream it therefore reaches MAX_SLICES (4096) after 4096 slices - about four and a half minutes of a 15 fps single-slice camera - and every later frame is rejected with "slice_num > 4096, stream was rejected!". done() also walks an ever-growing range of already-freed entries on every frame. Reset slice_num after the slices are freed. Also complete the media request (avd_run_postamble) on the two early returns that precede it (MAX_SLICES, slice buffer allocation failure); otherwise the rejected request is never completed and every following request on the context fails with EBUSY.
A completion IRQ or the watchdog could finish the current m2m job while
avd_device_run() was still building or submitting it. v4l2-mem2mem then ran
the next job on a kworker against the same ctx->job. On T8103 this oopsed
twice: a NULL dereference in avd_submit_job() (segment table freed under the
submit loop) and, with an earlier attempt at a fix, one in avd_hevc_run()
right after avd_init_job(). Each oops left the video device lock held, so
every later access to /dev/video0 hung until reboot.
Track the device's one job in avd_dev under a spinlock: RUNNING while
avd_device_run() executes, SUBMITTED once the hardware owns it, FINISHING once
the IRQ handler or the watchdog has claimed it. The watchdog is armed only on
the move to SUBMITTED, and it resets the hardware only for the job it was
armed for. A completion during RUNNING is dropped as stale unless the END
command already went out; then it is remembered and avd_device_run() finishes
the job on return. Every finish path resets the state in
avd_job_finish_no_pm(). avd_submit_job() walks a local copy of the segment
table and frees it only at the end, and release cancels the watchdog.
Transitions log with dev_dbg("avd-job: ...") for dynamic debug.
avd_hevc_run_preamble() read the HEVC controls, including the number of slices and entry point offsets (ctrl->new_elems), before avd_run_preamble() applied the request with v4l2_ctrl_request_setup(). new_elems is scratch space: setting controls on any request writes the count there. Userspace that queues requests ahead (FFmpeg through VA-API does) sets the next picture's controls while the current one is being prepared, so the current picture could be decoded with the next picture's slice count. In WPP_C_ericsson_MAIN_2, picture 12 has 16 slices and picture 13 has one; picture 12 was sent with only its first slice and the firmware rejected it (H0 error), in 11 of 20 decodes. Reading elems at the same place is no better: before request setup it holds the previous picture's count (0 of 20 decodes correct). Apply the request first, then read the controls and their counts (elems). This also stops holding p_cur of a dynamic array across the setup, which can move the array's storage when it grows.
fill_comp() sized the compressed chroma plane for half-height chroma whatever the image format. 4:2:2 chroma is full height, so reference chroma did not fit: 4:2:2 intra streams decoded, every 4:2:2 stream with P or B slices decoded wrong. JVT-FR-EXT through GStreamer: FREXT1-3_TANDBERG_A, Hi422FR2-4_SONY_A and Hi422FR11-12_SONY_A now pass (8-bit 4:2:2; 10-bit 4:2:2 still has no P210 capture format).
The driver accepts monochrome streams and decodes them into 4:2:0 buffers, and the firmware writes zero chroma, so pictures came out green. Fill the chroma plane with 0x80 when a picture completes. HPCAMOLQ_BRCM_B and HPCVMOLQ_BRCM_B now match software decoding, through GStreamer and through VA-API.
An SPS with different luma and chroma bit depth (TSUNEQBD_A_MAIN10_ Technicolor_2: 10-bit luma, 9-bit chroma) was accepted and ended in a firmware H0 error and a watchdog reset of the VP, which disturbs every other decoding context. Only 4:2:0 has a capture format. H.264 already rejects both; do the same for HEVC so such streams fail at once.
…e run Setting a dynamic array control on a queued request with more elements than ever before reallocates the control's storage (user_to_new() in the control core) and frees the old array. avd_hevc_run() kept using p_cur of the slice params and entry point offsets without the control lock while building the job, so userspace preparing the next picture could free the arrays under it. Copy both arrays, and their element counts, under the control lock right after the request is applied, and use the copies.
…on errors stream_slices() accepted slices claiming one entry point offset more than the request carried (> count + 1). With tiles that reads one offset past the array and pushes one segment past the job table, which is sized num_slices + num_entry_point_offsets + 1. Require the sum to fit, and fail the job instead of submitting a half-built one. avd_hevc_run() returned from compute_tiles, alloc_scratch and init_job failures without avd_run_postamble(), so the applied request was never completed and a client waiting on the request fd waited forever. It also freed tile_info pointers that were uninitialised when compute_tiles failed before allocating them. Zero the run and complete the request on every path.
avd_init_job() replaced ctx->job.segments without freeing it, and only avd_submit_job() ever freed a table. A frame that was started but not submitted leaked its table: for H.264 that is 4096 segments, about 8 MiB, each time a slice of a started frame was rejected (invalid references), on stream-off in the middle of a frame, or on close. A table left over across stream-off could also be appended to by the next stream. Free the old table in avd_init_job(), on OUTPUT stream-off and on release. Jobs run one at a time and stream-off and release wait for the running job, so no submission can be walking the table.
The job table holds a header segment plus one segment per slice, but was sized for MAX_SLICES segments, so the 4096th slice of a frame wrote one segment past the end. The scan for emulation prevention bytes in stream_slice() walked the slice data until it had counted header_bit_size bits, which comes from userspace, without looking at the slice length. Stop at the end of the slice data.
10-bit 4:0:0 streams decode into P010, where filling chroma with 0x80 bytes gives 0x8080 (514) instead of mid-grey 0x8000 (512).
…capture format The previous HEVC SPS check rejected every chroma format but 4:2:0, although 8-bit 4:2:2 maps to NV16, and it made the zeroed default SPS invalid. Only reject what cannot be decoded into an offered format: bit depths other than 8 and 10, and 4:2:2 at 10 bit, which is mapped to P010 whose buffer is too small for 4:2:2 chroma (there is no P210). Do the same for H.264, which accepted 4:2:2 10-bit into P010 as well.
An IRQ can complete a job after its watchdog starts running but before the callback checks wd_seq. cancel_delayed_work does not wait for that callback. Reusing ctx->wd_seq for the next submission lets the old callback claim and reset the new job. Drain watchdog_work synchronously at the start of the sleepable device_run callback, before publishing the next generation and outside job_lock. IRQ completion remains nonblocking. This also waits for a previous timeout callback to finish its completion tail. A finite userspace schedule fixture using the extracted driver functions reproduces the premature reset before this change and preserves the next submission afterward. Kernel workqueue primitives are modeled; this is not hardware validation.
The upstream buffer rename moved scratch.tile_col[0] to bufs.above_info, but dropped its free from avd_av1_stop. The work-buffer allocator still allocates it for decoding, leaking the final DMA-coherent buffer whenever an AV1 context stops. Restore the matching free. An offline allocation fixture invoking the extracted stop function detects the old leak and verifies that all buffer records are released after this change.
A failed allocation leaves cpu NULL and size set to the failed request. A subsequent smaller H.264 slice then takes the inverted reuse shortcut and copies its payload through NULL. The failed slot is not included in the slice count, so normal completion does not clear it first. Remove the false-success shortcut and clear bookkeeping on failure. Preserve exact-size allocation: H.264 also uses the buffer size as its coded payload length, so reusing a larger allocation changes semantics. Fixes: 71f0cc9 ("media: apple: avd: dedicated submit step") Signed-off-by: iconidentify <[email protected]>
The AV1 and VP9 preambles apply request controls before allocating the instruction table. If that allocation fails, the source buffer is returned but the control request object is never completed. Clients waiting for the request can remain blocked or unable to reinitialize it. Complete the applied request before returning the allocation error, matching the other failure paths and the HEVC implementation. Fixes: 71f0cc9 ("media: apple: avd: dedicated submit step") Signed-off-by: iconidentify <[email protected]>
H.264 completion writes neutral chroma before vb2_buffer_done returns cache ownership to the CPU. With non-coherent MMAP capture, the following DMA synchronization can invalidate those dirty CPU writes. Record the pending fill on the destination buffer and perform it from buf_finish, after the framework has synchronized the buffer. Retain the chroma offset and bit depth per buffer so delayed dequeue cannot pick up another picture's format. Clear the pending fill on prepare and consume it only for successfully completed capture buffers. Fixes: f456f8a ("media: apple: avd: h264: fill chroma with grey for 4:0:0 pictures") Signed-off-by: iconidentify <[email protected]>
The codec startup error paths free only the private context after a DMA buffer allocation fails. Buffers allocated earlier in the same startup sequence become unreachable, so repeated failed STREAMON calls leak DMA memory for H.264, HEVC, VP9 and AV1. Reuse each codec's stop routine to unwind partially initialized contexts. The contexts are zero-initialized and avd_buf_free() accepts empty buffer descriptors. Clear ctx->priv after freeing the context on both startup failure and normal teardown. Signed-off-by: iconidentify <[email protected]>
AV1 ignores the return value from avd_av1_alloc_work_bufs() and continues building and submitting a frame after an allocation fails. The resulting command can reference missing or incomplete working storage. Check the allocation result before updating destination metadata or probabilities. Complete the applied request controls and return the error so avd_device_run() finishes the buffers with an error without submitting the job. Partially allocated work buffers remain owned by the context and are released by retry allocation or codec teardown. Signed-off-by: iconidentify <[email protected]>
vb2 requires start_streaming() to return all driver-owned buffers in the QUEUED state on failure. AVD leaves those buffers on the mem2mem source ready list when codec startup fails. vb2's fallback returns their buffer state but cannot remove the driver's ready links, so a direct STREAMON retry enqueues the same links again. Drain the source ready queue on every output startup error and return each buffer with VB2_BUF_STATE_QUEUED. Preserve request controls for the retry; the normal queue cleanup helper completes them and is unsuitable here. Capture startup and successful output startup remain unchanged. Signed-off-by: iconidentify <[email protected]>
Acelogic
added a commit
that referenced
this pull request
Oct 2, 2026
T8140 has sparse codec-specific VP blocks rather than the sequential layout used by earlier variants. Its HEVC stream uses DMA configuration words and an extended scratch-address table. Apply the J700 queue pacing and polling behavior to this variant while preserving earlier chips' behavior. Align the AV1 auxiliary storage and HEVC MV tail to keep their addresses outside the compressed frame data and aligned to the hardware granularity. Adapt DJ's existing J700 bring-up, integrated by Ryan, onto the public decoder series in PR #45. Preserve the original driver notices and authors. The legacy FIFO-mask experiment is not part of this port. Tested on J700/T8140 with open Asahi v5-t0 firmware: H.264, HEVC, VP9 and AV1 hardware downloads matched 1740 software-decoded frames in 34 runs, including 8/10-bit cases, vaGetImage, repeated opens and H.264/HEVC/VP9 seek. Co-authored-by: Ryan Murray <[email protected]> Co-authored-by: Ace <[email protected]>
Acelogic
added a commit
that referenced
this pull request
Oct 2, 2026
T8140 has sparse codec-specific VP blocks rather than the sequential layout used by earlier variants. Its HEVC stream uses DMA configuration words and an extended scratch-address table. Apply the J700 queue pacing and polling behavior to this variant while preserving earlier chips' behavior. Align the AV1 auxiliary storage and HEVC MV tail to keep their addresses outside the compressed frame data and aligned to the hardware granularity. Adapt DJ's existing J700 bring-up, integrated by Ryan, onto the public decoder series in PR #45. Preserve the original driver notices and authors. The legacy FIFO-mask experiment is not part of this port. Tested on J700/T8140 with Aurora v5-t0 firmware: H.264, HEVC, VP9 and AV1 hardware downloads matched 1740 software-decoded frames in 34 runs, including 8/10-bit cases, vaGetImage, repeated opens and H.264/HEVC/VP9 seek. Firmware source: https://github.com/aurora-silicon/avd-fw Revision: 9cbde5c7d993844bf086318974958b11076600a0 Document the firmware build source and installation path in Kconfig help. Retain the firmware project's license and contributor attribution. Co-authored-by: Ryan Murray <[email protected]> Co-authored-by: Ace <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Update Aurora's AVD decoder to fix playback hangs, job-completion/watchdog races, request and buffer lifetime errors, and H.264/HEVC chroma and format handling. The series also adds opt-in cacheable MMAP buffers and fixes allocation-failure cleanup and failed-stream-start retries across the codec paths.
This carries the exact 29-commit series from omacom/linux#10 to
aurora-wip: six upstream Asahi commits, the 15-patch M1 series, and eight follow-up review fixes. Changes are confined to eight files underdrivers/media/platform/apple/avd/. Original commits and contributor authorship are preserved, including sofus's decoder work and Aaron/aquarat's patches.Aurora integration check
0b4025f19a985b904f7ec96de2b74ced68c710cb; base checked:9220af926e67d662c5e0664aa79f8b7a9c778c55(aurora-wip).git merge-tree --write-treemerges the series without conflicts. Aurora's AVD files have not changed since the sharedtbbase, and the merged AVD directory is identical to the qualified source tree.git diff --checkpasses. No source changes or commit rewrites were needed for this submission.Existing M1 qualification
The exact submitted AVD head was built and loaded as a module on Asahi
7.1.13-3-1-ARCH, together with VA-API driver revision5b5046c, packaged in the now-merged omarchy-mac/omarchy-pkgs-aarch64#53. The package port into Omacom is omacom/omarchy-pkgs#616.W=1) and five kernel regression groups passed, including 149 allocation-failure cases with ASan/UBSan.Qualification report, exact revisions, hashes and results.
These are the existing September 21 qualification results, not a new Aurora hardware campaign. The complete destination Aurora kernel has not been built or booted for this submission. The experimental Chromium client retains the recorded color mismatch; boot stability, other Macs and AV1 hardware decoding are outside the campaign.