Skip to content

media: apple: jpeg: add a baseline JPEG decoder - #4160

Open
RyanTheTide wants to merge 2 commits into
mainfrom
media-parity/jpeg-decode
Open

RyanTheTide wants to merge 2 commits into
mainfrom
media-parity/jpeg-decode

Conversation

@RyanTheTide

Copy link
Copy Markdown
Contributor

The JPEG engine can decode, but the driver only exposed the encoder. This adds a hardware JPEG decoder device and checks it on real hardware.

Problem: no hardware JPEG decode on any Apple SoC. Both apple-jpeg nodes are encoders, so MJPEG and JPEG decode (GStreamer v4l2jpegdec, viewers) runs on the CPU.

Change: a second V4L2 stateful decoder device per engine, apple-jpeg-dec. OUTPUT takes JPEG. CAPTURE gives NV12, NV16 or NV24 (MCU-padded, with the visible size in the compose rectangle). The engine parses the tables and restart markers itself. The driver checks the envelope with v4l2_jpeg_parse_header() and programs the geometry from the public m1n1 JPEG experiment, moved to the wide-address layout. Source-change event plus V4L2_FMT_FLAG_DYN_RESOLUTION handle the first frame and mid-stream size changes. Decode is enabled only on T6041 and T8140. T6050 and untested engines stay encode-only.

Tested: 7.3.0-aurora-fleet94 on J616s (M4 Pro, T6041) and Neo (T8140), both engines on each. 20 baseline JPEGs (4:2:0/4:2:2/4:4:4/grey, 33x17 to 3840x2160, odd sizes, q50/q90, restart intervals, optimized Huffman) decode with max abs diff 1 per plane against the ffmpeg mjpeg decoder: Y PSNR 64.8-71.0 dB. Hardware output is bit-identical between the two boards. Conversions to other chroma layouts give max diff 1 against a box-average/replicate model. Hardware encode then decode gives max diff 1 against ffmpeg's decode of the same file. GStreamer 1.28.9 filesrc ! jpegparse ! v4l2jpegdec picks the node (rank 257) and matches the reference, including an 8-frame stream with 7 size changes. Neo 1080p 4:2:0 789 fps, 4K 211 fps; J616s 401 fps, 4K 106 fps (one job in flight). KUnit apple-jpeg 18/18 (4 new cases) on arm64 qemu. checkpatch --strict and W=1 are clean.

Risk: two-way door. The change is new code paths behind a new video device. The encoder's job programming is unchanged. Adding a node shifts /dev/videoN numbering after the JPEG nodes on T6041/T8140 systems.

Still to run: T6050 (K114s) decode, which needs its own job layout. T8112/T8122/T6000 decode once a board is free. T8132 (J713) shares the T6041 variant, so decode is enabled there, but it has not been run on that board yet.

Closes #4101

Decode programming and envelope checks
  • Register sequence: the m1n1 experiment's decode path (proxyclient/experiments/jpeg.py, jpeg_doc.md), with the legacy offsets mapped to the wide-address layout through the existing decode_block_base (0x16c) and layout fields. MODE for decode is 0x757, checked on both engines. The completion arrives as the same interrupt bit as an encode.
  • Right/bottom edge sample counts are rounded up. With the experiment's floor, the half-filled chroma column of an odd-width 4:2:2 JPEG differed by up to 6 codes. With ceil it matches to 1.
  • Accepted: SOF0, 8-bit, 1 or 3 components, 4:2:0/4:2:2/4:4:4/grey, one interleaved scan of every component, DC/AC tables 0-1, quantisation tables 0-3, no Adobe RGB transform. Anything else comes back at QBUF time as an ERROR OUTPUT buffer, without using a CAPTURE buffer. Corrupt entropy data fails the job (status 0x20, or the engine timeout for truncated data), and the engine recovers on the next job.
  • The JPEG OUTPUT buffer budget is at least 8 MiB (3 bytes per pixel above that), so clients that size buffers from a small first frame survive a 4K one later.
  • On a mid-stream change the next CAPTURE buffer comes back empty with LAST, no job runs until CAPTURE restarts, and a STOP sent meanwhile still drains after the restart. GStreamer issues STOP at EOS while the change is pending.
Per-file results

All rows give max abs diff 1 (or 0) on Y, Cb and Cr. They are identical on J616s and Neo.

file Y PSNR dB Cb Cr
420 640x480 q90 65.65 65.89 65.73
420 641x481 q90 65.63 65.78 65.68
420 642x482 q90 65.62 65.80 65.68
420 33x17 q90 64.83 inf 63.96
420 1920x1080 q90 / rst1 / rst5b / optimized 65.57 65.89 65.78
420 1920x1080 q50 70.72 60.91 73.16
420 3840x2160 q90 65.56 65.92 65.75
422 642x482 q90 65.62 65.75 65.75
422 643x479 q90 65.66 65.79 65.82
422 1920x1080 q90 / rst2b 65.57 65.84 65.81
422 3840x2160 q50 71.00 58.66 69.35
444 642x482 q90 65.62 65.80 65.70
444 1920x1080 q90 65.57 65.77 65.78
444 3840x2160 q50 71.00 58.16 66.04
grey 642x482 q90 / 1920x1080 q50 65.62 / 70.72 128 128
ffmpeg-encoded 420 1920x1080 66.37 66.99 66.99
decode rate, one job in flight Neo T8140 J616s T6041
1080p 4:2:0 q90 789 fps 401 fps (755 in an earlier run)
1080p 4:2:2 q90 651 fps 328 fps
1080p 4:4:4 q90 466 fps 234 fps
4K 4:2:0 q90 211 fps 106 fps (145 earlier)
4K 4:4:4 q50 127 fps 69 fps

Hardware encode then decode, against the encoder's source frame: Y 37.4 dB / CbCr 38.1 dB at q90, 33.1/34.9 dB at q50 (noisy test frame).

The JPEG engine decodes as well as encodes, but the driver only exposed
the encoder, so JPEG decode (MJPEG cameras, image viewers, GStreamer's
v4l2jpegdec) fell back to the CPU.

Add a second V4L2 stateful decoder device per engine, "apple-jpeg-dec":
OUTPUT takes V4L2_PIX_FMT_JPEG, CAPTURE gives NV12, NV16 or NV24 in one
buffer, MCU-padded, with the visible size as the compose rectangle.
The engine parses the tables and restart markers itself; the driver
checks the envelope with v4l2_jpeg_parse_header() (baseline SOF0,
8-bit, 4:2:0/4:2:2/4:4:4/grey, one interleaved scan, Huffman tables 0-1)
and programs the geometry. JPEGs it refuses come back at once with an
ERROR OUTPUT buffer. Greyscale decodes to NV12 with neutral chroma; the
engine also converts between the three chroma layouts (box average down,
replication up).

The decode programming follows the public m1n1 JPEG experiment
(proxyclient/experiments/jpeg.py), moved to the wide-address layout,
with MODE 0x757, and the edge sample counts rounded up (the odd-width
4:2:2 chroma column was wrong with them rounded down). The CAPTURE
format is set from the first JPEG's headers with a source change event;
the OUTPUT format advertises V4L2_FMT_FLAG_DYN_RESOLUTION so clients
wait for it. A later JPEG with other headers ends the decoded stream
with an empty LAST buffer and another event, and a STOP sent meanwhile
still drains once CAPTURE restarts, which GStreamer relies on at EOS.

Decode is enabled on the T6041 and T8140 engines, where it was checked
on hardware; the T6050 job layout and the untested engines keep only
the encoder.

Signed-off-by: Ryan Murray <ryan@aurorasilicon.org>
@RyanTheTide
RyanTheTide requested review from a team as code owners December 3, 2026 08:20
@github-actions github-actions Bot added area:media Area from CODEOWNERS (bot) blast:m1 Macs affected, from Merge risk (bot) blast:m2 Macs affected, from Merge risk (bot) blast:m3 Macs affected, from Merge risk (bot) blast:m4 Macs affected, from Merge risk (bot) blast:m5 Macs affected, from Merge risk (bot) blast:neo Macs affected, from Merge risk (bot) door:two-way Revertible or not, from Merge risk (bot) needs-hw-row No hardware row at the PR head (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) labels Dec 3, 2026
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Merge readiness at 90babf76: not ready yet

Check Detail
CI at head ok 9 checks passed
Review no needs one approving review from Core, Omarchy Mac or Aurora Maintainers (not the author)
Requested changes no requested by DjDeveloperr
Hardware row at head ok comment at 90babf76
Conflicts ok none
PR text ok Risk: two-way · . The change is new code paths behind a new video device. The encoder's job programming is unchanged. Adding a node shifts /dev/videoN numbering after the JPEG nodes on T6041/T8140 systems. Still to run: T6050 (K114s) decode, which needs its own job layout. T8112/T8122/T6000 decode once a board is free. T8132 (J713) shares the T6041 variant, so decode is enabled there, but it has not been run on that board yet. Closes #4101

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.

Verdict: FINISH at f10fdf1

Failure: A valid multiplanar OUTPUT buffer with a nonzero data_offset is parsed from the wrong address. VB2 copies the offset from the application buffer and includes it in bytesused. aj_dec_buf_prepare_out() at apple-jpeg-drv.c:1073–1086 gives the JPEG parser the plane base and bytesused instead. A baseline JPEG preceded by an application header therefore starts with the wrong bytes at the parser and is returned in error. The decode job at apple-jpeg-drv.c:406–407 likewise starts DMA at the plane base and uses the allocation size. Use the same validated payload range for parsing and programming the JPEG input, with the required address alignment and documented hardware padding.

Checked: I traced V4L2 OUTPUT preparation, DMA job setup, CAPTURE geometry, the shared completion path and source-change handling. The reported hardware results cover ordinary unprefixed frames. Please consider splitting the header and geometry support from the decoder queue and controls so each can be reviewed independently.

@DjDeveloperr DjDeveloperr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Request changes at f10fdf19: one decoder rule is broken, small fix. Geometry and buffer checks look right.

V4L2_DEC_CMD_START after a source change hangs the stream. aj_decoder_cmd() (apple-jpeg-drv.c:990-995) returns 0 for START but leaves cap_restart set, and aj_job_ready() (line 486) then refuses every job. No second event is sent, so the client waits forever. dev-decoder.rst ("Dynamic Resolution Change", step 1) lets a client resume with START instead of a CAPTURE restart when its buffers are large enough. Fix in the START branch:

if (ret)
	return ret;
vb2_clear_last_buffer_dequeued(v4l2_m2m_get_dst_vq(ctx->fh.m2m_ctx));
spin_lock_irqsave(&ctx->drain_lock, flags);
ctx->cap_restart = false;
ctx->change_last = false;
spin_unlock_irqrestore(&ctx->drain_lock, flags);
v4l2_m2m_try_schedule(ctx->fh.m2m_ctx);
return 0;

I built this on the merge with main: W=1 and checkpatch clean, KUnit passes. aj_dec_run() already rejects a buffer that is too small for the new size, so this is safe.

Please also run two things on hardware and post the result:

  1. A stream whose frame header does not match the programmed size. The header is checked at QBUF, but the buffer stays mapped in the client. Also, v4l2_jpeg_parse_header() keeps the last of two SOF segments, while the engine may use the first. Test: 640x480 with a second 3840x2160 SOF in front, and a 640x480 OUTPUT buffer rewritten to a 4K JPEG between QBUF and CAPTURE STREAMON. Pass means: nothing written past the CAPTURE buffer (check a neighbouring buffer filled with a pattern), no DART fault, next job is good. If the engine follows the stream's size, refuse a second SOF and copy the JPEG into a driver buffer.
  2. T8132: this PR turns decode on there and it has not run on that chip. Either set decode only for T6041 and T8140, or wait for a row. We can give one on our J773g.

data_offset from the earlier review: returning -EINVAL for a nonzero offset in aj_dec_buf_prepare_out() is enough.

Checked on the merge of this head with main dc4d6f06:

  • W=1 arm64 objects clean, checkpatch --strict clean, KUnit (UML) 18/18.
  • Header parsing: zero sizes, more than 16384, 12-bit, progressive, multi-scan, odd chroma factors and out-of-range table selectors are refused. Sizes fit in u32. A job needs the header, layout and buffer size to match, and output_end is the end of the CAPTURE plane.
  • Format changes cannot happen under a running job. Drain, STOP during a pending change and queue stop mid-job follow the m2m helpers. Locks nest in one order.
  • Encoder job building is unchanged. Engines without decode register no second node.

Rows: J616s and Neo are in the body, but without the head SHA. After the push, post one line with the new head for J700 or J616s, plus T8132 if decode stays on there.

@github-actions github-actions Bot added the changes-requested A reviewer requested changes (bot) label Dec 3, 2026
Clear the pending CAPTURE restart and LAST state after a successful START, then retry scheduling. Reject nonzero OUTPUT data offsets before parsing, since the decoder uses a padded buffer beginning at the plane base.

Signed-off-by: DjDeveloperr <hey@djdev.me>
@DjDeveloperr

Copy link
Copy Markdown
Contributor

Pushed 90babf764ad0. A successful decoder START clears the CAPTURE restart and pending LAST state, then reschedules. OUTPUT buffers with a nonzero data offset are rejected before parsing, since the engine uses a padded buffer starting at the plane base.

Both JPEG objects built with arm64 W=1 and strict checkpatch passed. A host fixture ran the production queue functions and verified successful START, failed START preserving state, STOP/EOS and offset rejection. The START case failed on the prior head.

Still needed is an independent review and exact-head decode on J700 or J616s and J773g, including a resolution change that resumes with START and confirmation that writes stay within the programmed CAPTURE buffer.

@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: MERGE at 90babf7.

Checked: The OUTPUT prepare path rejects a nonzero data offset before parsing, and the supported zero-offset path matches the decoder's padded DMA input. The exact callbacks passed valid zero-offset preparation, offset and DMA alignment rejection, successful START after a source change, busy START with pending state preserved, and STOP/EOS. Successful START clears both restart flags and the last-buffer state before scheduling outside the drain lock. Job construction still verifies CAPTURE layout and length before programming the engine.

Follow-ups: Nonzero OUTPUT data offsets are explicitly unsupported on this path. Applications need to place the coded payload at the plane base.

@DjDeveloperr

Copy link
Copy Markdown
Contributor

J773g (Apple M4 Mac mini, T8132) JPEG + scaler module row receipt:

  • Result: PASS (VERDICT PASS J773g, exit 0)
  • Tested heads (combined candidate module build on 7.3.0-j773g-main3685+):
    • aurora-silicon/linux#4160 @ 90babf764ad0
    • aurora-silicon/linux#4165 @ 87c6f8b7affd
  • Boot: 7.3.0-j773g-main3685+, boot_id=d0d3b57e-600d-47ea-b29d-55a6f8a39963 (zero reboot, zero sleep, stock modules restored and verified afterwards)
  • Kit: edge-jpeg-scaler-rows-20261203 (KIT.sha256 d1fb43d9ee0e, J773g/SHA256SUMS 3117d179eb53)
  • Arm results:
    • Stock: PASS encode 256x128, 1103 bytes, PASS scaler 256x128 to 256x128 CAPTURE-first, 131072 bytes, stock driver exposes encode only
    • Candidate: PASS encode 256x128, 1103 bytes, PASS decode START/LAST, 49152 captured bytes, 411648 untouched tail bytes, PASS scaler 256x128 to 256x128 CAPTURE-first, 131072 bytes, PASS scaler 640x480 to 256x128 CAPTURE-first, 131072 bytes, PASS lossless alignment, format negotiation only
  • Restore & kernel check: RESTORED stock modules, unchanged boot d0d3b57e-600d-47ea-b29d-55a6f8a39963, zero new matching kernel errors

@DjDeveloperr

Copy link
Copy Markdown
Contributor

MacBook Neo (J700, T8140) row, 12-03 16:40Z, zero reboot, module swap on stock 7.3.0-41.fc44.aurora (boot a66a9547): VERDICT PASS. Heads: JPEG #4160 90babf764ad0, scaler #4165 5c61925c7e10 (kit e78deea3).

  • Stock arm: scaler 256x128 -> 256x128 (capture-first, 131,072 bytes) and JPEG encode 256x128 (1,103 bytes) pass; the stock driver exposes encode only.
  • Candidate arm: JPEG encode 256x128 (1,103 bytes, same as stock); decode START/LAST 49,152 captured bytes with the 411,648-byte tail untouched; scaler 256x128 -> 256x128 and 640x480 -> 256x128 (131,072 bytes each); lossless alignment and OUTPUT TRY_FMT/S_FMT parity.
  • Stock modules restored, same boot, 0 new matching kernel errors.

Not covered: other T8140 Macs, larger frames, long runs, and the display/camera users of these blocks.

@github-actions github-actions Bot removed the needs-hw-row No hardware row at the PR head (bot) label Dec 3, 2026
@DjDeveloperr

Copy link
Copy Markdown
Contributor

Verified baseline JPEG decode on M3 Pro (J516s, T6030, HWREV 0xf0008, apple_jpeg_t8122) by swapping v4l2-jpeg.ko and apple-jpeg.ko built from 90babf764ad0 plus .decode = true on apple_jpeg_t8122 onto stock 7.3.0-f3822 (zero reboot):

  • Devices: both engines (299000000.jpeg -> /dev/video12 dec / /dev/video10 enc, 299008000.jpeg -> /dev/video14 dec / /dev/video13 enc) probed cleanly with 0 warnings/errors.
  • Matrix (26/26 PASS across both engines vs ffmpeg):
    • 4:2:0 -> NV12: 640x480, 1920x1080, odd 323x217 (coded 336x224), tiny odd 17x19 (coded 32x32), restart interval DRI=4 -> max_y=1, max_uv=1
    • 4:2:2 -> NV16: 640x480, odd 323x217 -> max_y=1, max_uv=1
    • 4:4:4 -> NV24: 640x480, odd 323x217 -> max_y=1, max_uv=1
    • grey -> NV12: 640x480, odd 323x217 -> max_y=1, max_uv=0 (exact 0x80 neutral chroma)
    • Cross-format HW chroma downsampling (4:2:2 -> NV12, 4:4:4 -> NV12 at 640x480): max_y=1, mean_uv=0.927 / 1.117
  • Dynamic resolution change: 640x480 -> 323x217 -> 1920x1080 in a single open fd passed with max_y=1, max_uv=1 on all 3 frames on both engines.
  • Negative control + recovery: progressive SOF2 rejected cleanly with V4L2_BUF_FLAG_ERROR (flags=0x4041), followed immediately by valid decode (max_y=1, max_uv=1) on both engines.
  • Encoder regression & PMGR: both encoders produced identical 19,927-byte valid 640x480 JPEGs; jpg PMGR domain returned cleanly to off-0 with both devices suspended after idle.

Once #4160 lands, we can follow up with .decode = true on apple_jpeg_t8122 (plus KUnit coverage) to enable hardware JPEG decode across the M3 family (T8122/T603x).

This branch has not been deployed

No deployments
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:m1 Macs affected, from Merge risk (bot) blast:m2 Macs affected, from Merge risk (bot) blast:m3 Macs affected, from Merge risk (bot) blast:m4 Macs affected, from Merge risk (bot) blast:m5 Macs affected, from Merge risk (bot) blast:neo Macs affected, from Merge risk (bot) changes-requested A reviewer requested changes (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.

media: apple: jpeg: no hardware JPEG decode on any SoC (both engines are encode-only)

2 participants