Skip to content

media: apple: avd: h264: support frame-based Annex-B stateless decode - #3358

Merged
RyanTheTide merged 2 commits into
mainfrom
feat/avd-h264-frame-based
Nov 28, 2026
Merged

RyanTheTide merged 2 commits into
mainfrom
feat/avd-h264-frame-based

Conversation

@erikwb

@erikwb erikwb commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What: Enable V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED stateless H.264 decoding in the Apple AVD V4L2 driver alongside existing SLICE_BASED decoding, supporting both START_CODE_ANNEX_B and unprefixed 7.3.1 START_CODE_NONE framing (plus Chromium's default-control Annex-B compatibility path) so frame-based stateless clients such as Chromium's V4L2VideoDecoderDelegateH264 decode H.264 natively on /dev/video11 (follow-up to #3073).
Tested: J313 M1 MacBook Air (ewb-m1, 7.3.0-j313daily5-ewb342+) at c2656bf7c627: live /dev/video11 decode matrix passes 5/5 with byte-identical NV12 luma output across FRAME_BASED + ANNEX_B, FRAME_BASED + NONE (unprefixed 7.3.1 NALU), and FRAME_BASED + NONE (Chromium-style Annex-B), while FRAME_BASED + ANNEX_B with raw NALU and SLICE_BASED + ANNEX_B both return V4L2_BUF_FLAG_ERROR; 188/188 arm64 QEMU KUnit (apple-avd*) pass; program-test.py passes; earlier at 0569550b8352, Chromium H.264 Baseline (652/652 frames @ 60 fps), High+B (-228.9 mW mean / -214.7 mW median Heatpipe vs SW), and 4-slice High+B (-268.5 mW mean / -243.4 mW median Heatpipe vs SW) decoded via AVD and mpv --hwdec=vaapi (SLICE_BASED) passed with 0 errors.
Risk: two-way door · all Apple Silicon Macs with Apple AVD (M1–M4).
Not yet: non-M1 (M2/M3/M4) AVD hardware regression testing.

Details
  • Mode and start-code ABI handling (avd-v4l2.c, avd-h264.c, avd-h264-parse.c):
    • Relax V4L2_CID_STATELESS_H264_DECODE_MODE (SLICE_BASED..FRAME_BASED, default SLICE_BASED) and V4L2_CID_STATELESS_H264_START_CODE (NONE..ANNEX_B, default NONE) so existing slice-based defaults remain unchanged.
    • Validate (decode_mode, start_code) in avd_h264_mode_supported(): SLICE_BASED accepts START_CODE_NONE only (rejecting START_CODE_ANNEX_B with -EINVAL); FRAME_BASED accepts both START_CODE_ANNEX_B and START_CODE_NONE.
    • Dispatch framing in avd_h264_next_frame_nalu():
      • FRAME_BASED + START_CODE_ANNEX_B: requires Annex-B start codes (00 00 01 / 00 00 00 01) and rejects unprefixed buffers with -EINVAL.
      • FRAME_BASED + START_CODE_NONE: parses a single unprefixed ITU-T H.264 §7.3.1 VCL slice NALU (no start code, rejecting forbidden_zero_bit, non-VCL/unsupported NAL types, and embedded 00 00 01 sequences). For clients such as Chromium's V4L2VideoDecoderDelegateH264 — which writes DECODE_MODE=FRAME_BASED, never writes V4L2_CID_STATELESS_H264_START_CODE (leaving it at the START_CODE_NONE default; V4L2 also skips s_ctrl for default-valued writes), and unconditionally prepends 00 00 01 in SubmitSlice() — buffers beginning with an Annex-B start code (00 00 ... 01) are dispatched to the Annex-B scanner. Because no valid unprefixed §7.3.1 NALU begins with 0x00 (nal_unit_type == 0 is invalid), leading Annex-B start codes cannot collide with valid START_CODE_NONE payloads.
  • Standalone ITU-T H.264 §7.3.3 slice header parser (avd-h264-parse.c, avd-h264-parse.h): Scans Annex-B NALUs (00 00 01 / 00 00 00 01), handles EBSP→RBSP emulation-prevention bytes (00 00 03), parses slice headers including ref_pic_list_modification(), pred_weight_table(), and dec_ref_pic_marking(), and computes exact CABAC/CAVLC slice_data() offsets.
  • Zero-copy submission (avd-h264.c): Submits each VCL slice directly from the VB2 OUTPUT DMA buffer (run->base.coded_in + nalu.off + slice_data_off) via avd_h264_run_frame(), rejects V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF in frame-based mode, and aborts any stale held slice-based bank on mode transitions.
  • SPS validation (avd-h264.c): Bounds log2_max_frame_num_minus4, pic_order_cnt_type, and log2_max_pic_order_cnt_lsb_minus4 in avd_h264_validate_sps() while keeping avd_h264_validate_sps_fmt() permissive for pre-streaming format negotiation.
Evidence
  • Head commit: c2656bf7c627 (added on top of 0569550b8352)
  • Build (arm64 LLVM=1 W=1 KCFLAGS=-Werror): 0 errors, 0 warnings across avd-h264.o, avd-h264-parse.o, and avd-h264-test.o.
  • KUnit (./tools/testing/kunit/kunit.py run --kunitconfig=drivers/media/platform/apple/avd/tests/.kunitconfig --arch=arm64 --make_options=LLVM=1 'apple-avd*'): 188/188 passed (0 failed, 0 skipped), including avd_frame_mode_framing_test covering all (decode_mode, start_code) pairs, FRAME_BASED + START_CODE_ANNEX_B valid/error paths, FRAME_BASED + START_CODE_NONE raw 7.3.1 NALU + Chromium Annex-B + malformed/non-VCL/embedded-start-code error paths.
  • Host tests (python3 drivers/media/platform/apple/avd/tests/program-test.py): PASS.
  • Checkpatch (scripts/checkpatch.pl --strict): 0 errors, 0 warnings, 0 checks on c2656bf7c627.
  • J313 M1 MacBook Air (ewb-m1, 7.3.0-j313daily5-ewb342+ @ 786ad8d1e498 containing c2656bf7c627):
    • Direct /dev/video11 + /dev/media0 V4L2 Request API matrix on a real 64x64 libx264 Main CABAC IDR frame:
      • FRAME_BASED + START_CODE_ANNEX_B (Annex-B): err=0, y_sum=346256 (PASS)
      • FRAME_BASED + START_CODE_NONE (unprefixed 7.3.1 NALU): err=0, y_sum=346256, NV12 luma byte-identical to ANNEX_B reference (PASS)
      • FRAME_BASED + START_CODE_NONE (Chromium-style Annex-B): err=0, y_sum=346256, NV12 luma byte-identical to ANNEX_B reference (PASS)
      • FRAME_BASED + START_CODE_ANNEX_B (raw NALU without start code): err=1 (V4L2_BUF_FLAG_ERROR) (PASS)
      • SLICE_BASED + START_CODE_ANNEX_B: err=1 (V4L2_BUF_FLAG_ERROR) (PASS)
  • Earlier Chromium & mpv J313 measurements at 0569550b8352:
    • Chromium (--ignore-gpu-blocklist --enable-features=AcceleratedVideoDecoder, 1080p60): Baseline 652/652 frames @ 60 fps, High+B -228.9 mW mean / -214.7 mW median Heatpipe vs SW, 4-slice High+B -268.5 mW mean / -243.4 mW median vs SW, 0 AVD errors; mpv --hwdec=vaapi (SLICE_BASED) unaffected.

Enable V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED paired with
V4L2_STATELESS_H264_START_CODE_ANNEX_B alongside the existing
SLICE_BASED + START_CODE_NONE path so frame-based stateless clients
(such as Chromium's V4L2VideoDecoderDelegateH264) can decode H.264
natively on Apple AVD without breaking FFmpeg, GStreamer, or
libva-v4l2-request.

- Relax V4L2_CID_STATELESS_H264_DECODE_MODE (SLICE_BASED..FRAME_BASED,
  default SLICE_BASED) and V4L2_CID_STATELESS_H264_START_CODE
  (NONE..ANNEX_B, default NONE) without rejecting updates while
  streaming, and validate mode/start-code pairing per frame in
  avd_h264_run().
- Tighten avd_h264_validate_sps() to bound log2_max_frame_num_minus4,
  pic_order_cnt_type, and log2_max_pic_order_cnt_lsb_minus4 while
  keeping avd_h264_validate_sps_fmt() permissive for pre-streaming
  format negotiation.
- Add a standalone Annex-B NALU scanner and ITU-T H.264 7.3.3 slice
  header parser (avd-h264-parse.c/h) with EBSP->RBSP emulation
  prevention byte handling, ref_pic_list_modification(),
  pred_weight_table(), dec_ref_pic_marking(), and exact CABAC/CAVLC
  slice_data() offset computation.
- Submit frame-based slices zero-copy directly from the OUTPUT DMA
  buffer via avd_h264_run_frame(), rejecting HOLD_CAPTURE_BUF and
  aborting any stale held slice-based bank on mode switch.
- Add KUnit coverage for SPS bounds, Annex-B scanning, EBSP/RBSP
  bitreading, slice header fields, reference list modification,
  prediction weights, reference marking, and real libx264 Annex-B
  bitstreams, and update the host test harness accordingly.

Signed-off-by: Erik Bourget <[email protected]>
@erikwb
erikwb requested review from a team as code owners November 27, 2026 06:07
@erikwb
erikwb requested review from Acelogic and malik-na November 27, 2026 06:07
@github-actions github-actions Bot added area:media Area from CODEOWNERS (bot) blast:all Macs affected, from Merge risk (bot) door:two-way Revertible or not, from Merge risk (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) labels Nov 27, 2026
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Merge readiness at c2656bf7: not ready yet

Check Detail
CI at head no failing: pr-text / pr-text
Review no needs one approving review from Core or Omarchy Mac (not the author)
Requested changes ok none
Hardware row at head ok in the PR body at c2656bf7
Conflicts ok none
PR text ok Risk: two-way · all Apple Silicon Macs with Apple AVD (M1–M4).

Areas: area:media

Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels.

@aurora-silicon-review aurora-silicon-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FRAME_BASED accepts the START_CODE_NONE setting but unconditionally invokes the Annex-B scanner, which rejects a buffer without a start code. The V4L2 stateless-codec documentation defines NONE as slices without a start code. Enforce a supported mode/framing combination or implement the advertised one. If Chromium requires compatibility behavior, explain how that is reconciled with the ABI and test both each supported combination and its error path. Keep the non-M1 regression row open.

@RyanTheTide

Copy link
Copy Markdown
Contributor

Regression row at 0569550b, J700 (MacBook Neo, A18 Pro, AVD hw 40018) and J413 (M2 Air): no change to slice-based H.264. The frame-based path wasn't exercised.

Setup: the PR head's drivers/media/platform/apple/avd/ was built as apple-avd.ko against the fleet89 tree (same config and toolchain; BTF stripped so it loads on the shipped kernel). It was swapped in on the running fleet89 kernel; no reboot. Each clip was decoded with GStreamer v4l2slh264dec → I420, md5 of the whole output, first with the stock module, then with this PR's.

clip reference (ffmpeg h264, buildbox) J700 stock J700 PR J413 stock J413 PR
1080p High, B-frames, 60 f e8116c20321e e8116c20321e e8116c20321e e55cf31df5b1* e55cf31df5b1*
1080p High, B-frames, 300 f 2c335bd70192 2c335bd70192 2c335bd70192 037ca1ab4e10* 037ca1ab4e10*
2160p High, B-frames, 120 f ab8dcc997da5 ab8dcc997da5 ab8dcc997da5 ab8dcc997da5 ab8dcc997da5

* The J413 1080p differences come from GStreamer 1.28.8's NV12 → I420 conversion on that Mac's Fedora 44 stack, not from AVD. A direct NV12 dump of the same decode matches the reference byte for byte (1322f74c1887). Stock and PR are identical in every cell.

  • All decodes: rc 0, full frame counts, no AVD resets, timeouts or DART faults in the kernel log. Stock module restored on both Macs afterwards.
  • Not covered: GStreamer opens the decoder in its default mode (Opened H264 slice based decoder without start-codes), so these rows only show that the slice-based path is unchanged. The new FRAME_BASED + Annex-B path needs a client that selects it (Chromium). I can't run that headless on these Macs tonight.

…te mode pairs

Validate H.264 decode-mode and start-code pairings in avd_h264_mode_supported() and implement framing dispatch in avd_h264_next_frame_nalu():
- SLICE_BASED accepts START_CODE_NONE only and rejects START_CODE_ANNEX_B with -EINVAL.
- FRAME_BASED + START_CODE_ANNEX_B requires Annex-B start codes and rejects unprefixed buffers with -EINVAL.
- FRAME_BASED + START_CODE_NONE parses a single unprefixed ITU-T H.264 7.3.1 VCL slice NALU (no start code, rejecting non-VCL types, forbidden_zero_bit, and embedded start codes), while dispatching buffers beginning with a leading Annex-B start code to the Annex-B scanner for clients (such as Chromium's V4L2VideoDecoderDelegateH264) that select FRAME_BASED without writing START_CODE and leave it at this driver's START_CODE_NONE default. Because no valid unprefixed 7.3.1 NALU starts with 0x00, leading Annex-B start codes cannot collide with valid START_CODE_NONE payloads.
- Add KUnit coverage for the mode/start-code matrix, both FRAME_BASED framing paths, Chromium's default-control path, and malformed/unsupported inputs.

Signed-off-by: Erik Bourget <[email protected]>
@erikwb

erikwb commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in c2656bf7c627:

  • Added avd_h264_mode_supported() and avd_h264_next_frame_nalu() so FRAME_BASED + START_CODE_NONE now implements unprefixed ITU-T H.264 §7.3.1 single-slice NALU framing per the V4L2 stateless documentation (rejecting forbidden_zero_bit, non-VCL/unsupported NAL types, and embedded 00 00 01 start codes), while FRAME_BASED + START_CODE_ANNEX_B strictly requires Annex-B start codes (rejecting unprefixed buffers with -EINVAL) and SLICE_BASED + START_CODE_ANNEX_B is rejected with -EINVAL.
  • Reconciling Chromium with the V4L2 ABI: Chromium's media/gpu/v4l2/v4l2_video_decoder_delegate_h264.cc sets V4L2_CID_STATELESS_H264_DECODE_MODE = FRAME_BASED, never sets V4L2_CID_STATELESS_H264_START_CODE (leaving it at this driver's START_CODE_NONE default, and V4L2 skips s_ctrl when a default value is written), yet unconditionally prepends 00 00 01 in SubmitSlice(). In FRAME_BASED + START_CODE_NONE, a buffer beginning with a leading Annex-B start code (00 00 ... 01) is dispatched to the Annex-B scanner; this cannot collide with valid unprefixed §7.3.1 payloads because no valid H.264 NALU starts with 0x00 (nal_unit_type == 0 is invalid).
  • Testing: Added avd_frame_mode_framing_test in avd-h264-test.c covering all mode/start-code combinations and error paths (188/188 apple-avd* arm64 QEMU KUnit tests pass, program-test.py passes, checkpatch --strict 0 errors/0 warnings), and verified all 5 mode/framing/error cases on live J313 AVD hardware (/dev/video11, byte-identical NV12 luma output across all three valid FRAME_BASED paths). Kept the non-M1 regression row open in **Not yet:**.

@aurora-silicon-review aurora-silicon-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: HOLD for hosted CI and frame-based hardware qualification. The framing code addresses my earlier change request.

Checked: Both frame scans now use the selected framing. FRAME_BASED/NONE accepts an unprefixed VCL unit and explicitly retains Annex-B autodetection for clients that leave the default control. FRAME_BASED/ANNEX_B takes the Annex-B scanner, while the slice-based mode still requires NONE. The new KUnit fixture covers the raw and compatibility branches. The prior J700 and J413 rows exercised slice-based decode. Please attach current-head frame-based outputs, including raw and Annex-B, before landing.

@github-actions github-actions Bot added the ci-failing A check failed at the PR head (bot) label Nov 27, 2026
@RyanTheTide

Copy link
Copy Markdown
Contributor

Code-owner review requested from @aurora-silicon/core for c2656bf7c627. The J413 and J700 direct V4L2 Request regression matrix is being prepared for this head.

@RyanTheTide

Copy link
Copy Markdown
Contributor

J413 M2 Air hardware row at c2656bf7c627. Built the complete AVD driver directory and its video-number header from that head against the saved fleet89 kernel ABI, then temporarily loaded the module on the 13.5 stub. Used the direct V4L2 Request API with a 64×64 Main-profile CABAC IDR.

Mode and input J413 result
Slice, NONE, raw NALU PASS, bit-exact luma versus stock and FFmpeg
Frame, NONE, raw NALU PASS, same luma
Frame, ANNEX_B, prefixed NALU PASS, same luma
Frame, default NONE, Chromium-style prefixed NALU PASS, same luma
Frame, ANNEX_B, raw NALU Rejected as expected, both buffers marked ERROR
Slice, ANNEX_B, prefixed NALU Rejected as expected, both buffers marked ERROR

The four successful captures had luma SHA-256 db7740b8796d5cc1 (prefix). The two deliberate error cases each logged one failed-frame diagnostic. After loading the candidate, eDP was still connected, keyboard and trackpad were registered, both built-in audio cards remained present, Wi-Fi gateway replies were 3/3, and offscreen rendering selected Apple M2 G14G (glmark2 5858). No new SELinux denials. Restored the stock AVD module and removed the staging files. The saved kernel remained running with empty next entry, Enforcing and zero failed units. This was a same-boot module trial.

@RyanTheTide

Copy link
Copy Markdown
Contributor

J316s M1 Pro regression at c2656bf7c627. Same fleet89 ABI and same AVD module bytes as the J413 row (9ce43ceb848fd098 SHA-256 prefix). The four accepted Request API cases matched stock and software luma; both unsupported mode/framing combinations returned buffer ERROR. The two rejected jobs generated the two expected AVD diagnostics, with no additional kernel errors or SELinux denials.

Candidate runtime smoke: DRM reported the headless setup, SPI keyboard and trackpad registered, ALSA built-in cards present, gateway ICMP 3/3, and Apple M1 Pro G13S completed 32 EGL clear/readback cycles with GL error 0. Restored the stock driver on the same saved fleet89 boot. Next entry empty, Enforcing, zero failed units, staging removed.

@RyanTheTide

Copy link
Copy Markdown
Contributor

Boot-time regression at c2656bf7c627 on J473 (M2) and J316s (M1 Pro). Both one-shots used the same previously qualified 94ea195b6eb5 Image, stock Stage 2 and normal command line. Only apple-avd.ko in the disposable nightly module tree was replaced by the exact PR build. The loaded module’s build ID matched the candidate from boot on both Macs.

Check J473 (T8112) J316s (T6000)
Request API matrix 4/4 valid operations software-exact, 2/2 invalid pairings rejected as intended Same
Display and input HDMI and USB-C DP connected, input devices present Expected headless DRM state, SPI keyboard and trackpad present
Audio ALSA cards and desktop sink enumeration ALSA cards and protected speaker hold sink present
Network and GPU Gateway 3/3, Apple G14G EGL 32/32 Gateway 3/3, Apple G13S EGL 32/32
Boot and restore Enforcing, 0 failed units, 0 new AVCs; saved fleet89 restored, empty next entry Same

The J473 paired GPU timestamp stress passed queue depth 1 and timed out at depth 16 in both arms, including the same nightly Image booted with the original signed AVD module. That symptom reproduced independently of the AVD overlay. J413’s 13.5 live-module row is above and used no reboot.

@RyanTheTide

Copy link
Copy Markdown
Contributor

The frame-based modes accept raw and Annex-B requests, and the existing slice mode still matches stock output. Hosted checks at c2656bf7c627 and the direct request matrices passed. The boot-time regression rows cover T8112 and T6000. Hardware results

If decoding regresses after merge, revert this merge with git revert -m 1 <merge-commit>.

@RyanTheTide
RyanTheTide merged commit f0b7236 into main Nov 28, 2026
20 of 23 checks passed
@RyanTheTide
RyanTheTide deleted the feat/avd-h264-frame-based branch November 28, 2026 01:13
@RyanTheTide

Copy link
Copy Markdown
Contributor

Merged as f0b72363b06d88b70e370ddc589ec4b34225d23c. All seven changed file blobs match the tested head. To revert, run git revert -m 1 f0b72363b06d88b70e370ddc589ec4b34225d23c.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:media Area from CODEOWNERS (bot) blast:all Macs affected, from Merge risk (bot) ci-failing A check failed at the PR head (bot) door:two-way Revertible or not, from Merge risk (bot) needs-review No approving review from Core or Omarchy Mac yet (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants