Skip to content

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

Merged
DjDeveloperr merged 2 commits into
mainfrom
media-parity/jpeg-decode
Dec 5, 2026
Merged

DjDeveloperr merged 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 approved by aurora-silicon-review, DjDeveloperr, but GitHub does not count it yet (code owner from Core, Omarchy Mac or Aurora Maintainers needed, or approval went stale)
Requested changes ok none
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).

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Verified baseline JPEG hardware decode on J316s (MacBook Pro 16" M1 Pro, T6000, HWREV 0xd1013, apple_jpeg_t6000 / aj_legacy32 32-bit DMA) by swapping apple-jpeg.ko built from 90babf764ad0 plus .decode = true on apple_jpeg_t6000 onto stock saved EDGE 7.3.0-1675a62307d2-47318133913.1-aurora-edge (aura 1.0.0b19, stub 13.5, GStreamer 1.28.9, zero reboot):

  • Devices: both engines (409000000.jpeg -> /dev/video15 enc / /dev/video16 dec; 409008000.jpeg -> /dev/video17 enc / /dev/video18 dec) probed cleanly with 0 warnings/errors and 0 DART faults.
  • Native decode matrix (21/21 PASS on BOTH engines vs ffmpeg, max_diff <= 1, gt4 = 0 on every plane):
    • 4:2:0 -> NV12: 33x17, 640x480, 641x481, 642x482, 1920x1080 (q50/q90/opt/RST1/RST5b/ffmpeg), 3840x2160 -> Y PSNR 64.83–70.72 dB, Cb/Cr 60.91–73.16 dB / inf, max_diff <= 1.
    • 4:2:2 -> NV16: 642x482, 643x479, 1920x1080 (q90/RST2b), 3840x2160 -> Y PSNR 65.57–71.00 dB, max_diff <= 1.
    • 4:4:4 -> NV24: 642x482, 1920x1080, 3840x2160 -> Y PSNR 65.57–71.00 dB, max_diff <= 1.
    • grey -> NV12: 642x482, 1920x1080 -> Y PSNR 65.62–70.72 dB, max_diff = 1, chroma exact [128].
    • Engine 0 vs Engine 1: 21/21 bit-identical (diff = 0).
  • Cross-format HW chroma conversions (18/18 PASS): 4:2:0, 4:2:2, 4:4:4, grey -> NV12/NV16/NV24 all max_diff <= 1 (Y 65.57–65.66 dB, Cb/Cr 65.66–65.96 dB, grey chroma exact [128]).
  • Throughput (ajdec): 1080p 4:2:0 q90 401 fps (q50 478 fps), 1080p 4:2:2 326 fps, 1080p 4:4:4 233 fps, 1080p grey 575 fps, 4K 4:2:0 106 fps.
  • GStreamer 1.28.9 (v4l2jpegdec): registered at rank 257; all 6 single files, 8-frame dynamic-resolution-change sequence (000.yuv..007.yuv), and 300-frame runs PASS.
  • Negative controls (4/4): progressive (SOF2), 4:1:1, truncated header, and ff422 rejected cleanly with V4L2_BUF_FLAG_ERROR (flags 0x4041), zero crashes.
  • Restore: stock signed apple_jpeg reloaded cleanly (video15/video16 encoders back), Enforcing, 0 failed units, 0 DART faults.

Once #4160 lands, we have the follow-up commit ready to set .decode = true on apple_jpeg_t6000 (+ aj_legacy32 KUnit coverage), enabling hardware JPEG decode across the M1 family (T8103/T600x).

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

Quick ping @DjDeveloperr: 90babf764ad0 has all CI green (build, host-tests, KUnit jpeg, pr-text, readiness), aurora-silicon-review APPROVED, and PASS hardware rows across T8140 (J700), T6030 (J516s), and T6000 (J316s). Only the stale CHANGES_REQUESTED at f10fdf19 is holding merge — could you dismiss/re-review so #4160 can land and unblock the .decode = true follow-ups (T8122/T6030/T6000)?

@DjDeveloperr

Copy link
Copy Markdown
Contributor

I rechecked 90babf764ad0. The new START path clears the restart state and reschedules the queue, the nonzero OUTPUT offset is rejected, and the exact-head J773g row covers T8132. The remaining item from my review is the CAPTURE bounds check when the device and parser see differing geometry. The current matrix and progressive-SOF control do not cover that case. Please attach the result for the two cases in the original review, or point me to an existing receipt. I can clear the change request once the capture-boundary and next-job checks are in.

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

@DjDeveloperr on the remaining item (CAPTURE bounds when the device and the parser see different geometry): I found no existing receipt for your two cases. The matrix rows and the progressive-SOF control all use self-consistent streams. Below is what the code at 90babf764ad0 does in each case. A hardware row for both cases is queued on J616s (T6041, where decode is enabled in this PR). I'll post its VERDICT here at this head. No hardware result yet.

Which geometry the engine is programmed with

  • aj_dec_buf_prepare_out() parses the headers once, at QBUF, from the kernel mapping of the OUTPUT plane (apple_jpeg_parse_header() -> v4l2_jpeg_parse_header()). That parser overwrites out->frame on every SOF0/SOF1, so it keeps the last SOF.
  • I checked this off-hardware by compiling v4l2-jpeg.c and apple_jpeg_parse_header() verbatim from 90babf764ad0 on the host. For case (a), 640x480 with a 3840x2160 SOF0 in front, both return 0 and report 640x480 from the second SOF. ffmpeg's probe reports 3840x2160 for the same file (first SOF), and libjpeg rejects it ("two SOF markers").
  • aj_dec_run() programs buf->hdr.width/height (plane sizes, MCU counts, right/bottom edges). It runs only if those match ctx->cfg and the layout's sizeimage <= vb2_plane_size(dst). So the programmed geometry always fits the CAPTURE buffer.
  • output_end = CAPTURE plane base + vb2_plane_size - 1 is written to the engine's output-end register.

Why the code alone cannot rule out an overrun

  • The job runs with AJ_IO_FLAGS_FROM_STREAM, and the engine parses the JPEG itself from the OUTPUT buffer at device_run (input_size = the whole plane). Nothing re-checks the bytes at device_run.
  • Case (b) works exactly as you describe: the client keeps its writable mmap after QBUF, so the engine can see a 3840x2160 stream while the registers say 640x480.
  • Whether CAPTURE can be overrun therefore depends on two hardware facts:
    1. whether the engine takes its frame size from the registers or from a SOF it parses;
    2. whether it stops at output_end.
  • If the registers win, or output_end is enforced, nothing is written past the buffer.
  • If the stream wins and output_end is not enforced, a 3840x2160 NV12 job would write about 12.4 MB from a 460,800-byte buffer.
  • DART limits that to mapped IOVA. Anything outside the mappings faults, but the client's neighbouring CAPTURE buffers and the OUTPUT buffer in the same domain would be overwritten silently.
  • If the row shows the stream wins, the fix is what you proposed. v4l2_jpeg_parse_header() does not reject a second SOF, so apple_jpeg_parse_header() would need its own SOF count to refuse one. The JPEG would also be copied into a driver-owned buffer at QBUF so the engine decodes the bytes that were checked.
The queued hardware row (both cases + next job)

Zero-reboot module swap of apple-jpeg.ko onto the saved Edge kernel, restored to the stock signed module afterwards. The module is built from #4409's 4302e8a8. Under drivers/media/platform/apple/jpeg/ it differs from 90babf764ad0 only by .decode = true on T8112/T8122 and the matching KUnit expectation, so the T6041 path is this head's code. A static aarch64 V4L2 m2m test runs on every decoder engine:

  • Case A: 640x480 baseline with a 3840x2160 SOF0 inserted before the real SOF0.
  • Case B: a valid 640x480 JPEG is QBUF'd from an mmap'd OUTPUT buffer. After the source change, that same buffer is overwritten in place with a 3840x2160 baseline JPEG, then CAPTURE STREAMON.
  • Guards:
    • 8 CAPTURE buffers, each filled with its own pseudo-random pattern; the mismatch job writes into the last one allocated.
    • Checked afterwards: every other CAPTURE buffer; the target from sizeimage to the end of its page-rounded mapping; the OUTPUT JPEG bytes; the OUTPUT buffer past the JPEG.
    • The kernel log (dart|fault|jpeg) is captured before and after.
    • Fails on any DART translation fault, "engine reset failed", Oops or WARNING.
  • Next job: a normal 640x480 decode on the same context and on a fresh context, each compared with ffmpeg (max abs diff <= 1, as in the matrix rows).
  • Also reported (informational): whether the mismatch job completed or errored, how much of the target it wrote, and its output vs the 640x480 reference and vs the top-left 640x480 of the 4K reference. This shows which geometry the engine followed.
  • Off-hardware so far: the test's self-test passes; its guards catch a 1-byte write at sizeimage and a 1-byte write in a neighbour buffer.

@RyanTheTide

Copy link
Copy Markdown
Contributor Author

@DjDeveloperr here is the hardware result for the two geometry-mismatch cases from your review, at this head's driver code. VERDICT PASS: nothing was written past the CAPTURE buffer, and the next jobs are clean.

Ran on the MacBook Neo (J700, T8140, decode enabled in this PR), both engines, as a zero-reboot apple-jpeg.ko swap on the saved Edge kernel 7.3.0-1675a62307d2-47318133913.1-aurora-edge. The stock signed module was restored afterwards. The module is built from #4409's 4302e8a8; for T8140, its drivers/media/platform/apple/jpeg/ code is identical to 90babf764ad0.

  • Case A (a 3840x2160 SOF0 in front of the real 640x480 SOF0): the job completes (DONE). Its output matches the 640x480 reference (max diff 1) and does not match the top-left of the 4K reference (max diff 255). So the engine follows the same last SOF that the driver programs.
  • Case B (OUTPUT mmap rewritten in place with a 3840x2160 JPEG after QBUF): the job ends in ERROR (status 0x20, buffer flagged ERROR, payload 0). It changed bytes only inside sizeimage (458,952 of 460,800). Nothing changed past sizeimage, in the other 7 pattern-filled CAPTURE buffers, or in the OUTPUT buffer.
  • Next job: a normal 640x480 decode on the same context and on a fresh context both complete, with max abs diff 1 against ffmpeg.
  • Kernel log: 0 DART faults, 0 Oops/WARNING. There is one job failed: status 0x20 per engine, for the case B job.

Per engine: 56/56 checks pass, 0 fail.

Tested: J700 (T8140) both JPEG engines, cases A and B plus next-job checks; VERDICT PASS.
Risk: none new. The engine stays inside output_end when the stream changes under it, and the driver reports the job as ERROR.

Method and guards
  • Kit: ajgeom, a static aarch64 V4L2 m2m test. It allocates 8 CAPTURE buffers, each filled with its own pseudo-random pattern, and runs the mismatch job into the last one.
  • Checks afterwards:
    • the target buffer from sizeimage to the end of its page-rounded mapping (460800..475136);
    • every other CAPTURE buffer;
    • the OUTPUT JPEG bytes, and the OUTPUT buffer past the JPEG (to 8 MiB).
  • The kernel log is captured from a /dev/kmsg marker. Any DART translation fault, "engine reset failed", Oops or WARNING fails the row.
  • The test's self-test catches a 1-byte write at sizeimage and a 1-byte write in a neighbour buffer.
  • After the row: stock signer Build time autogenerated kernel key, module taint empty, encoder nodes back, staging removed, same boot, Enforcing, 0 failed units.

@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.

Verdict: MERGE at 90babf764ad0.

The START change clears the restart flags under the drain lock, resets the last-buffer state, and schedules the queue. The new OUTPUT guard rejects nonzero offsets before parsing.

The J700 receipt resolves my CAPTURE bounds request. Both engines passed 56/56 checks, kept writes inside the selected buffer, and completed the next decode. The child head used by that test only changes the T8112 and T8122 variants and their tests, so the T8140 path matches this head. The J773g row covers T8132. Apple build, Host Tests and JPEG KUnit passed at this head.

@github-actions github-actions Bot removed the changes-requested A reviewer requested changes (bot) label Dec 5, 2026
@DjDeveloperr
DjDeveloperr merged commit ae83c74 into main Dec 5, 2026
12 checks passed
@DjDeveloperr
DjDeveloperr deleted the media-parity/jpeg-decode branch December 5, 2026 10:31
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) 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