1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! The streaming JPEG source path: header pre-scan, DCT
//! shrink-on-load decode, fuse selection, and the post-resize
//! orientation/ICC handling.
use super::*;
/// Decode (with DCT shrink-on-load) + SIMD resize; returns RGB pixels
/// and final dimensions. Honors EXIF auto-rotation exactly like the
/// server pipeline (`OXIMG_AUTO_ROTATE=0` disables).
pub fn decode_and_resize(
jpeg: &[u8],
max_w: u32,
max_h: u32,
parallel: usize,
) -> Result<(Vec<u8>, usize, usize), super::Error> {
// Unwind-guarded end to end: libjpeg reports fatal errors by
// unwinding out of mozjpeg's C error handler, at the header parse
// or any later stage (see panic_guard).
crate::panic_guard::catch_unwind_as_error("JPEG decode", || {
decode_and_resize_inner(jpeg, max_w, max_h, parallel)
})
.and_then(|inner| inner)
.map_err(|e| super::Error::classify(e, false))
}
fn decode_and_resize_inner(
jpeg: &[u8],
max_w: u32,
max_h: u32,
parallel: usize,
) -> Result<(Vec<u8>, usize, usize)> {
// No override surface on this helper: a default Params resolves
// every knob from the environment, like the server path.
let p = Resolved::new(&Params {
max_width: max_w,
max_height: max_h,
parallel,
..Params::default()
});
SCRATCH.with(|s| {
let s = &mut *s.borrow_mut();
// The ICC scan feeds the CMYK→RGB conversion only (this
// helper returns raw pixels, so there is no pass-through);
// OXIMG_ICC=0 downgrades CMYK sources to the naive composite
// here exactly like the server path.
let want_icc = p.icc_passthrough;
let meta = if p.auto_rotate || want_icc || decoded_bytes_cap_set() {
let mut prefix = Vec::new();
let mut r = jpeg;
crate::meta::scan_jpeg_meta(&mut r, &mut prefix, want_icc)
} else {
crate::meta::JpegMeta::NONE
};
let orientation = if p.auto_rotate {
meta.orientation
} else {
crate::meta::Orientation::UPRIGHT
};
s.jpeg_progressive = meta.progressive;
let dec = Decompress::new_mem(jpeg).context("invalid JPEG")?;
match decode_resize(s, dec, &p, orientation, Fuse::Off, meta.icc.as_deref())? {
Decoded::Pixels { dst_w, dst_h } => {
if orientation.is_upright() {
Ok((s.out8[..dst_w * dst_h * 3].to_vec(), dst_w, dst_h))
} else {
let mut rotated = Vec::new();
let (dw, dh) = crate::meta::apply_orientation(
&s.out8[..dst_w * dst_h * 3],
dst_w,
dst_h,
3,
orientation,
&mut rotated,
);
Ok((rotated, dw, dh))
}
}
#[cfg(feature = "avif")]
Decoded::YuvPlanes { .. } => unreachable!("no fuse was requested"),
#[cfg(feature = "avif")]
Decoded::PixelsSession { .. } => unreachable!("no fuse was requested"),
Decoded::Encoded(_) => unreachable!("no fuse quality was requested"),
}
})
}
/// Result of the JPEG decode stage: either resized pixels left in
/// `Scratch::out8` for a separate encode, or — on the fused path — the
/// finished JPEG bytes (decode overlapped with resize+encode).
pub(super) enum Decoded {
Pixels {
dst_w: usize,
dst_h: usize,
},
Encoded(Vec<u8>),
/// 10-bit 4:2:0 planes left in `Scratch::{y16,cb16,cr16}`, plus the
/// encoder session the fused worker already created during the
/// decode overlap — only the SVT encode itself remains.
#[cfg(feature = "avif")]
YuvPlanes {
session: crate::avif::SvtSession,
},
/// Resized pixels in `Scratch::out8` plus a color session created
/// during the decode overlap, sized for the displayed frame — the
/// oriented-AVIF preheat path: rotate, convert, encode.
#[cfg(feature = "avif")]
PixelsSession {
dst_w: usize,
dst_h: usize,
session: crate::avif::SvtSession,
},
}
/// How the JPEG decode overlaps with downstream work (all variants
/// produce identical pixels/bytes; see overlap_gate).
#[derive(Clone, Copy)]
pub(super) enum Fuse {
/// Serial: decode, then resize inline on the same thread.
Off,
/// Decode ∥ resize + incremental jpegli encode on a worker thread —
/// the same-format JPEG fast path; yields `Decoded::Encoded`.
Jpegli { quality: f32 },
/// Decode ∥ resize into `Scratch::out8` on a worker thread; the
/// (one-shot) target encoder runs after. Used for cross-format
/// targets, hiding the resize behind the decode wall.
Pixels,
/// `Pixels`, plus the worker creates the AVIF color session for
/// the *displayed* frame during the decode — the oriented-AVIF
/// path, where rotation forbids streaming the YUV conversion but
/// the ~1ms session setup still hides behind the decode wall.
#[cfg(feature = "avif")]
PixelsPreheat { params: crate::avif::AvifParams },
/// Decode ∥ resize + RGB→YUV conversion straight into the 10-bit
/// planes on the worker thread, which also creates the SVT session
/// while the decode runs — AVIF targets, hiding the resize, the
/// conversion, and the encoder setup behind the decode wall.
#[cfg(feature = "avif")]
Yuv { params: crate::avif::AvifParams },
}
pub(super) fn decode_resize<R: std::io::BufRead>(
s: &mut Scratch,
mut dec: Decompress<R>,
p: &Resolved,
orientation: crate::meta::Orientation,
fuse: Fuse,
// The source's profile, dual-purpose by path: the fused jpegli
// encoder writes it ahead of its scanlines (the other fuse
// variants embed via their one-shot encoders), while the CMYK arm
// *consumes* it as the color-conversion input and never emits it.
icc: Option<&[u8]>,
) -> Result<Decoded> {
let timing = crate::config::config().timing;
let t0 = std::time::Instant::now();
let (src_w, src_h) = dec.size();
check_src_pixels(src_w, src_h)?;
// The target box constrains the *displayed* frame; for the
// axis-swapping orientations the resize target (still in stored
// orientation — the rotation happens on the resized frame) is the
// fitted box with its axes swapped back.
let (disp_w, disp_h) = orientation.display_dims(src_w, src_h);
let (fit_w, fit_h) = fit_dims(disp_w, disp_h, p.max_width, p.max_height);
let (dst_w, dst_h) = if orientation.swaps_axes() {
(fit_h, fit_w)
} else {
(fit_w, fit_h)
};
// Shrink-on-load defaults off (see `dct_scale_num`: it only ever
// costs quality) — but that holds for the streaming arm, where the
// decode size never materializes and the shrink was buying CPU
// alone. CMYK and YCCK stage the whole frame, so there it is
// buying memory, and keeps its old default. An explicit knob
// overrides both. The colorspace is known from the header, before
// any scanline is read, so this costs nothing to ask.
let buffered = matches!(
dec.color_space(),
ColorSpace::JCS_CMYK | ColorSpace::JCS_YCCK
);
let margin = dct_margin().or_else(|| buffered.then_some(BUFFERED_DCT_MARGIN));
dec.scale(dct_scale_num(src_w, src_h, dst_w, dst_h, margin));
// The decoded-bytes estimate. Two things field validation caught
// here (issue #17 follow-up), both worth naming:
//
// 1. The scaled dimensions must be computed from the factor just
// passed to `dec.scale()`. `Decompress::width()/height()` return
// libjpeg's `image_width`/`image_height` — the *source* — and
// `output_width` is only populated at jpeg_calc_output_dimensions
// or start_decompress. Reading the accessors here estimated the
// full source and made the cheapest path in the corpus produce
// the largest figure: the very failure this cap exists to fix.
// `dct_scale_num`'s own arithmetic (num/8, rounded up) needs no
// libjpeg call.
// 2. The dominant term for a streaming JPEG is the *output* side,
// not the source: nothing full-frame is resident. The buffered
// arms (CMYK/YCCK) do materialize a frame, and progressive
// sources add coefficient arrays no output size reduces.
{
// The same `margin` the scale was chosen with, not a second
// read of the knob: the estimate has to describe the decode
// that is actually about to happen.
let num = dct_scale_num(src_w, src_h, dst_w, dst_h, margin) as usize;
let (dec_w, dec_h) = ((src_w * num).div_ceil(8), (src_h * num).div_ceil(8));
let comps = dec.components().len().max(1) as u64;
let channels = if buffered { 4 } else { 3 };
let mut cost = if buffered {
// Staged whole (4-channel CMYK) and fed to the full-frame
// resize, like the buffered formats.
DecodeCost::full_frame(dec_w, dec_h, channels, p)
} else {
DecodeCost::streaming()
};
cost = cost.with_output(dst_w, dst_h, channels);
if s.jpeg_progressive {
cost = cost.with_progressive_coefficients(src_w, src_h, comps);
}
// The decoder streams, so the only compressed-source residency
// is a buffer the caller holds (buffered remote sources — the
// term issue #22 added; zero on the streaming entry points).
cost = cost.with_compressed(s.held_source_bytes);
check_decoded_bytes(cost, "JPEG")?;
}
// CMYK and YCCK sources (print-workflow JPEGs) take a buffered
// serial path: libjpeg itself normalizes YCCK back to CMYK when
// asked for JCS_CMYK output (honoring the Adobe APP14 transform it
// parsed during the header read), the stored samples are compacted
// to RGB in place, and the resize rejoins resize_pixels_to — the
// same full-frame machinery the buffered formats (PNG/WebP/AVIF)
// feed. The requested fuse is deliberately ignored: every fuse
// worker streams 3-byte rows, and these sources are far too rare
// to justify 4-channel overlap plumbing (`Decoded::Pixels` is a
// fallback every caller already handles).
let cs = dec.color_space();
if matches!(cs, ColorSpace::JCS_CMYK | ColorSpace::JCS_YCCK) {
let mut started = dec
.to_colorspace(ColorSpace::JCS_CMYK)
.context("decode start failed")?;
let (dec_w, dec_h) = (started.width(), started.height());
scratch_u8(&mut s.chunk8, dec_w * dec_h * 4);
started
.read_scanlines_into(&mut s.chunk8[..dec_w * dec_h * 4])
.context("decode failed")?;
started.finish().context("decode finish failed")?;
cmyk_to_rgb_in_chunk8(s, dec_w, dec_h, icc);
resize_pixels_to(s, 3, dec_w, dec_h, dst_w, dst_h, p)?;
if timing {
eprintln!(
"timing cmyk({dec_w}x{dec_h}->{dst_w}x{dst_h}) total={:.1}ms",
t0.elapsed().as_secs_f64() * 1e3
);
}
return Ok(Decoded::Pixels { dst_w, dst_h });
}
// libjpeg can only convert grayscale/YCbCr/RGB sources to RGB
// output; for anything else (JCS_UNKNOWN) `dec.rgb()` aborts
// through the crate's unwinding error manager — a panic that
// bypasses the panic hook, not an `Err`. Refuse those up front
// with a real error so the HTTP layer classifies them as
// undecodable input (422) and library callers get a `Result`.
anyhow::ensure!(
matches!(
cs,
ColorSpace::JCS_GRAYSCALE | ColorSpace::JCS_YCbCr | ColorSpace::JCS_RGB
),
"unsupported JPEG color space {cs:?}"
);
let mut started = dec.rgb().context("decode start failed")?;
let (dec_w, dec_h) = (started.width(), started.height());
let row_bytes = dec_w * 3;
let linear = p.linear_light && (dec_w, dec_h) != (dst_w, dst_h);
if (dec_w, dec_h) == (dst_w, dst_h) {
// Decoded size is already the target size: output directly; a
// linear round-trip would be pure loss.
let out = scratch_u8(&mut s.out8, dec_w * dec_h * 3);
started.read_scanlines_into(out).context("decode failed")?;
started.finish().context("decode finish failed")?;
if timing {
eprintln!(
"timing decode({dec_w}x{dec_h})={:.1}ms resize=0 (exact)",
t0.elapsed().as_secs_f64() * 1e3
);
}
return Ok(Decoded::Pixels { dst_w, dst_h });
}
if let Fuse::Jpegli { quality } = fuse
&& linear
&& let Some((out, decode_ms)) =
fused_resize_encode(&mut started, dec_w, dec_h, dst_w, dst_h, quality, icc)?
{
if timing {
let total = t0.elapsed().as_secs_f64() * 1e3;
eprintln!(
"timing fused({dec_w}x{dec_h}->{dst_w}x{dst_h}) decode={decode_ms:.1}ms tail={:.1}ms total={total:.1}ms",
total - decode_ms
);
}
started.finish().context("decode finish failed")?;
return Ok(Decoded::Encoded(out));
}
if let Fuse::Pixels = fuse
&& linear
{
scratch_u8(&mut s.out8, dst_w * dst_h * 3);
if let Some((decode_ms, ())) = fused_resize_pixels(
&mut started,
dec_w,
dec_h,
dst_w,
dst_h,
&mut s.out8[..dst_w * dst_h * 3],
2,
|| Ok(()),
)? {
if timing {
let total = t0.elapsed().as_secs_f64() * 1e3;
eprintln!(
"timing fused-px({dec_w}x{dec_h}->{dst_w}x{dst_h}) decode={decode_ms:.1}ms tail={:.1}ms total={total:.1}ms",
total - decode_ms
);
}
started.finish().context("decode finish failed")?;
return Ok(Decoded::Pixels { dst_w, dst_h });
}
}
#[cfg(feature = "avif")]
if let Fuse::PixelsPreheat { params } = fuse
&& linear
{
// The session encodes the *displayed* (rotated) frame. Session
// creation is non-fatal: SVT resource pressure downgrades to
// the serial encode of the same (still good) resized pixels
// instead of failing a request the serial path would serve —
// the same philosophy as the worker-spawn fallback.
let (disp_w, disp_h) = orientation.display_dims(dst_w, dst_h);
scratch_u8(&mut s.out8, dst_w * dst_h * 3);
if let Some((decode_ms, session)) = fused_resize_pixels(
&mut started,
dec_w,
dec_h,
dst_w,
dst_h,
&mut s.out8[..dst_w * dst_h * 3],
4,
|| Ok(crate::avif::start_color_session(disp_w, disp_h, ¶ms).ok()),
)? {
if timing {
let total = t0.elapsed().as_secs_f64() * 1e3;
eprintln!(
"timing fused-px+session({dec_w}x{dec_h}->{dst_w}x{dst_h}) decode={decode_ms:.1}ms tail={:.1}ms total={total:.1}ms",
total - decode_ms
);
}
started.finish().context("decode finish failed")?;
return Ok(match session {
Some(session) => Decoded::PixelsSession {
dst_w,
dst_h,
session,
},
None => Decoded::Pixels { dst_w, dst_h },
});
}
}
#[cfg(feature = "avif")]
if let Fuse::Yuv { params } = fuse
&& linear
{
let (cw, chh) = (dst_w.div_ceil(2), dst_h.div_ceil(2));
// Truncate to the exact frame: the session encode consumes the
// whole vectors (their length feeds SVT's n_filled_len).
scratch_u16(&mut s.y16, dst_w * dst_h);
s.y16.truncate(dst_w * dst_h);
scratch_u16(&mut s.cb16, cw * chh);
s.cb16.truncate(cw * chh);
scratch_u16(&mut s.cr16, cw * chh);
s.cr16.truncate(cw * chh);
if let Some((decode_ms, session)) = fused_resize_yuv(
&mut started,
dec_w,
dec_h,
dst_w,
dst_h,
¶ms,
&mut s.y16,
&mut s.cb16,
&mut s.cr16,
)? {
if timing {
let total = t0.elapsed().as_secs_f64() * 1e3;
eprintln!(
"timing fused-yuv({dec_w}x{dec_h}->{dst_w}x{dst_h}) decode={decode_ms:.1}ms tail={:.1}ms total={total:.1}ms",
total - decode_ms
);
}
started.finish().context("decode finish failed")?;
return Ok(Decoded::YuvPlanes { session });
}
}
if linear {
// Stream each decoded chunk's rows through the SIMD resize
// kernel — the exact consumer the fused path runs on its worker
// thread, inline: the sRGB -> linear LUT fuses into row staging
// (no u16 intermediate image), and completed output rows go
// through the back LUT as they emit. Serial and fused therefore
// produce identical bytes on every architecture.
#[cfg(any(target_arch = "aarch64", target_arch = "x86_64"))]
if p.parallel <= 1
&& !crate::config::config().fir_backend
&& let Ok(mut resizer) =
crate::resize_kernel::StreamResize::<FuseKernel>::new(dec_w, dec_h, dst_w, dst_h, 3)
{
let fwd = fwd_lut_f32();
let back = back_lut();
let chunk_rows = (256 * 1024 / row_bytes).clamp(1, dec_h);
scratch_u8(&mut s.chunk8, chunk_rows * row_bytes);
scratch_u8(&mut s.out8, dst_w * dst_h * 3);
let out8 = &mut s.out8;
let mut remaining = dec_h;
while remaining > 0 {
let want = remaining.min(chunk_rows) * row_bytes;
let got = started
.read_scanlines_into(&mut s.chunk8[..want])
.context("decode failed")?
.len();
anyhow::ensure!(
got > 0 && got % row_bytes == 0,
"decoder returned a partial row"
);
remaining -= got / row_bytes;
for row in s.chunk8[..got].chunks_exact(row_bytes) {
resizer.push_row_u8(row, fwd, |oy, out| {
for (d, &v) in out8[oy * dst_w * 3..(oy + 1) * dst_w * 3]
.iter_mut()
.zip(out)
{
*d = back[v as usize];
}
});
}
}
anyhow::ensure!(
resizer.rows_emitted() == dst_h,
"decode ended before the image was complete"
);
started.finish().context("decode finish failed")?;
if timing {
eprintln!(
"timing streamed({dec_w}x{dec_h}->{dst_w}x{dst_h}) total={:.1}ms",
t0.elapsed().as_secs_f64() * 1e3
);
}
return Ok(Decoded::Pixels { dst_w, dst_h });
}
// Full-frame fallback (band-parallel resize, OXIMG_RESIZE_BACKEND
// =fir, or CPUs without the SIMD kernel): decode in chunks and
// apply the sRGB u8 -> linear u16 LUT on the fly; each chunk
// stays in L2, saving a second full-image memory pass.
let fwd = fwd_lut();
// Fully filled by the chunked LUT loop below (filled reaches
// dec_w*dec_h*3 or the decode errors out).
scratch_u16(&mut s.src16, dec_w * dec_h * 3);
let chunk_rows = (256 * 1024 / row_bytes).clamp(1, dec_h);
scratch_u8(&mut s.chunk8, chunk_rows * row_bytes);
let mut filled = 0usize; // number of u16 components filled so far
while filled < dec_w * dec_h * 3 {
let want = (dec_h * row_bytes - filled).min(chunk_rows * row_bytes);
let got = started
.read_scanlines_into(&mut s.chunk8[..want])
.context("decode failed")?
.len();
anyhow::ensure!(got > 0, "decoder returned no scanlines");
for (d, src) in s.src16[filled..filled + got]
.iter_mut()
.zip(&s.chunk8[..got])
{
*d = fwd[*src as usize];
}
filled += got;
}
started.finish().context("decode finish failed")?;
let t_decode = t0.elapsed();
let t1 = std::time::Instant::now();
scratch_u16(&mut s.dst16, dst_w * dst_h * 3);
resize_bands(
u16_as_bytes(&s.src16[..dec_w * dec_h * 3]),
dec_w,
dec_h,
u16_as_bytes_mut(&mut s.dst16[..dst_w * dst_h * 3]),
dst_w,
dst_h,
PixelType::U16x3,
p.parallel,
&mut s.resizer,
)?;
let back = back_lut();
let out = scratch_u8(&mut s.out8, dst_w * dst_h * 3);
for (d, src) in out.iter_mut().zip(&s.dst16[..dst_w * dst_h * 3]) {
*d = back[*src as usize];
}
if timing {
eprintln!(
"timing decode+fwd({dec_w}x{dec_h})={:.1}ms resize+back={:.1}ms",
t_decode.as_secs_f64() * 1e3,
t1.elapsed().as_secs_f64() * 1e3
);
}
Ok(Decoded::Pixels { dst_w, dst_h })
} else {
// Resize directly in sRGB space (speed mode)
scratch_u8(&mut s.chunk8, dec_w * dec_h * 3);
started
.read_scanlines_into(&mut s.chunk8[..dec_w * dec_h * 3])
.context("decode failed")?;
started.finish().context("decode finish failed")?;
let t_decode = t0.elapsed();
let t1 = std::time::Instant::now();
scratch_u8(&mut s.out8, dst_w * dst_h * 3);
resize_bands(
&s.chunk8[..dec_w * dec_h * 3],
dec_w,
dec_h,
&mut s.out8[..dst_w * dst_h * 3],
dst_w,
dst_h,
PixelType::U8x3,
p.parallel,
&mut s.resizer,
)?;
if timing {
eprintln!(
"timing decode({dec_w}x{dec_h})={:.1}ms resize={:.1}ms",
t_decode.as_secs_f64() * 1e3,
t1.elapsed().as_secs_f64() * 1e3
);
}
Ok(Decoded::Pixels { dst_w, dst_h })
}
}
/// The streaming JPEG source path: header pre-scan (orientation +
/// ICC), DCT shrink-on-load decode, fuse selection, and the
/// post-resize orientation/ICC application. Split out of the format
/// dispatch, where the other formats are one-line calls.
pub(super) fn process_jpeg<R: std::io::BufRead>(
s: &mut Scratch,
reader: R,
target: ImageFormat,
p: &Resolved,
) -> Result<Vec<u8>> {
Ok({
// A bounded pre-scan of the header segments (through
// the tables, up to SOS — the span libjpeg's marker
// saving covers) extracts the EXIF orientation and,
// for profile-capable targets, the APP2 ICC chain; the
// scanned bytes are re-chained in front of the stream
// so the decoder sees identical input. libjpeg-side marker saving is deliberately not
// used: its per-request memory scales with the number
// of attacker-supplied APP1 segments, while this buffer
// is hard-capped (see meta::SCAN_CAP).
let mut reader = reader;
let mut scan_prefix = Vec::new();
// Collect the profile whenever OXIMG_ICC is on: pass-through
// wants it for profile-capable targets, and the CMYK→RGB
// conversion needs it for *every* target — whether the source
// is CMYK is unknown until the frame header parses, after
// this scan. (OXIMG_ICC=0 therefore also downgrades CMYK
// sources to the naive conversion.)
let want_icc = p.icc_passthrough;
let meta = if p.auto_rotate || want_icc || decoded_bytes_cap_set() {
crate::meta::scan_jpeg_meta(&mut reader, &mut scan_prefix, want_icc)
} else {
crate::meta::JpegMeta::NONE
};
let orientation = if p.auto_rotate {
meta.orientation
} else {
crate::meta::Orientation::UPRIGHT
};
s.jpeg_progressive = meta.progressive;
let icc = meta.icc;
let reader = std::io::Read::chain(&scan_prefix[..], reader);
let dec = Decompress::new_reader(reader).context("parse JPEG")?;
// A CMYK/YCCK source's embedded profile describes ink
// coverage, not the RGB pixels this request emits: it feeds
// the CMYK→RGB conversion inside `decode_resize` and never
// reaches an output, which follows the pipeline's convention
// for profile-less sources (no profile, sRGB implied). RGB
// sources keep the pass-through, gated on the target's
// ability to carry a profile.
let cmyk = matches!(
dec.color_space(),
ColorSpace::JCS_CMYK | ColorSpace::JCS_YCCK
);
let icc_embed = if cmyk || !target_supports_icc(target) {
None
} else {
icc.as_deref()
};
// What decode_resize consumes: the conversion profile on the
// CMYK path, the fused-jpegli embed profile otherwise.
let icc_dec = if cmyk { icc.as_deref() } else { icc_embed };
// Fused decode overlap: on unless disabled (see
// overlap_gate). Band-parallel resize keeps the serial
// path so OXIMG_PAR semantics are unchanged. Jpegli
// JPEG-out additionally overlaps the incremental encode;
// every other encoder (mozjpeg presets and cross-format
// targets) overlaps decode with resize into out8/planes
// and runs its one-shot encode after.
// The fir escape hatch must also disable fusing: the
// fused workers run the in-tree SIMD kernel, and fir vs
// kernel are byte-different backends, so fusing under
// fir would make a URL's bytes load-dependent.
// Mirrors encode_output's AVIF arm (the tuned operating
// point); the session the fused workers create from
// these is what encodes the frame.
let cross_fuse = || -> Fuse {
#[cfg(feature = "avif")]
if target == ImageFormat::Avif {
return Fuse::Yuv {
params: p.avif_params(),
};
}
Fuse::Pixels
};
let fuse = if p.parallel > 1 || !overlap_gate() || crate::config::config().fir_backend {
Fuse::Off
} else if !orientation.is_upright() {
// Rotation happens on the resized frame before the
// one-shot encode — incompatible with streaming rows
// into jpegli or into the YUV planes, so oriented
// sources take the pixel fuse (decode ∥ resize kept)
// and rotate after. AVIF targets additionally
// preheat their encoder session on the worker,
// erasing most of the remaining oriented penalty
// (measured ~1ms of ~1.2ms). The rest is closed by
// measurement, not TODO: streaming the jpegli
// encode only works for flip-h (rows stay in
// order) — real-world mirrored images are too rare
// to carry the complexity — and streaming the YUV
// conversion under 90° rotation would pair chroma
// across resized columns, a correctness minefield
// for ~0.2ms.
#[cfg(feature = "avif")]
if target == ImageFormat::Avif {
Fuse::PixelsPreheat {
params: p.avif_params(),
}
} else {
Fuse::Pixels
}
#[cfg(not(feature = "avif"))]
Fuse::Pixels
} else if target == ImageFormat::Jpeg {
if p.encoder == Encoder::Jpegli {
Fuse::Jpegli { quality: p.quality }
} else {
// mozjpeg presets have no incremental encoder,
// but the decode still overlaps the resize into
// out8 (byte-identical to the serial path); the
// one-shot mozjpeg encode runs after.
Fuse::Pixels
}
} else {
cross_fuse()
};
match decode_resize(s, dec, p, orientation, fuse, icc_dec)? {
Decoded::Encoded(out) => out,
Decoded::Pixels { dst_w, dst_h } => {
let (dw, dh) = if orientation.is_upright() {
(dst_w, dst_h)
} else {
// Rotate the resized frame into chunk8 (free
// at this point) and swap it in as out8.
let dims = crate::meta::apply_orientation(
&s.out8[..dst_w * dst_h * 3],
dst_w,
dst_h,
3,
orientation,
&mut s.chunk8,
);
std::mem::swap(&mut s.out8, &mut s.chunk8);
dims
};
encode_output(s, dw, dh, 3, target, p, icc_embed)?
}
#[cfg(feature = "avif")]
Decoded::YuvPlanes { session } => {
// Conversion and encoder setup already happened
// inside the decode overlap; only the encode
// itself remains. The plane vectors are truncated
// to exactly this frame by the fused branch.
crate::avif::encode_avif_with_session(session, &s.y16, &s.cb16, &s.cr16, icc_embed)
.context(ServerFault)?
}
#[cfg(feature = "avif")]
Decoded::PixelsSession {
dst_w,
dst_h,
session,
} => {
// Rotate onto the displayed frame the preheated
// session was sized for, then convert + encode.
let dims = crate::meta::apply_orientation(
&s.out8[..dst_w * dst_h * 3],
dst_w,
dst_h,
3,
orientation,
&mut s.chunk8,
);
std::mem::swap(&mut s.out8, &mut s.chunk8);
crate::avif::encode_avif_rgb_with_session(
session,
&s.out8[..dims.0 * dims.1 * 3],
dims.0,
dims.1,
icc_embed,
)
.context(ServerFault)?
}
}
})
}