oximg 0.8.0

High-performance image compression: library, CLI, and self-hostable server (PoC).
Documentation
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
//! Full-frame source paths: PNG, WebP, and AVIF decode + the
//! shared orientation-aware resize they feed. (JPEG streams; it
//! lives in `jpeg`.)

use super::*;

pub(super) fn process_png<R: std::io::Read>(
    s: &mut Scratch,
    mut reader: R,
    target: ImageFormat,
    p: &Params,
) -> Result<Vec<u8>> {
    let timing = crate::config::config().timing;
    let t0 = std::time::Instant::now();
    s.srcbuf.clear();
    reader
        .read_to_end(&mut s.srcbuf)
        .context("read PNG source")?;
    let mut decoder = png::Decoder::new(std::io::Cursor::new(&s.srcbuf[..]));
    decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
    let mut png_reader = decoder.read_info().context("parse PNG")?;
    {
        let hdr = png_reader.info();
        check_src_pixels(hdr.width as usize, hdr.height as usize)?;
        // PNG has no shrink-on-load: the whole frame materializes,
        // normalized to RGB8 or RGBA8 (EXPAND|STRIP_16 upstream).
        let channels = match hdr.color_type {
            png::ColorType::Rgba | png::ColorType::GrayscaleAlpha => 4,
            // Palette sources can carry tRNS, which EXPAND resolves to
            // RGBA; assume the wider staging rather than under-count.
            png::ColorType::Indexed => 4,
            _ => 3,
        };
        let (sw, sh) = (hdr.width as usize, hdr.height as usize);
        // The eXIf orientation is parsed below this block, so which way
        // the fit runs is not known yet — and an axis-swapping
        // orientation with an asymmetric box can make the real output
        // several times larger than the unoriented fit. Take the larger
        // of the two candidates: over-counting the output side is the
        // safe direction for a limit.
        let (ow, oh) = larger_fit(sw, sh, p);
        check_decoded_bytes(
            DecodeCost::full_frame(sw, sh, channels, p)
                .with_output(ow, oh, channels)
                .with_compressed(s.srcbuf.len()),
            "PNG",
        )?;
    }
    // eXIf orientation (raw TIFF per the PNG spec; a stray JPEG-style
    // prefix is tolerated like browsers do). Only chunks ahead of the
    // image data are seen — the orientation must steer the resize box,
    // so it has to be known before decoding. The registration allows
    // post-IDAT placement, but Chrome and Firefox also honor only
    // pre-IDAT eXIf, so serving those unrotated is browser parity, and
    // fail-safe besides.
    let orientation = if auto_rotate(p) {
        png_reader
            .info()
            .exif_metadata
            .as_ref()
            .and_then(|d| crate::meta::Orientation::from_exif_payload(d))
            .unwrap_or(crate::meta::Orientation::UPRIGHT)
    } else {
        crate::meta::Orientation::UPRIGHT
    };
    // iCCP profile (the png crate has already inflated it), bytes
    // passed through untouched.
    let icc: Option<Vec<u8>> = if icc_passthrough(p) && target_supports_icc(target) {
        png_reader
            .info()
            .icc_profile
            .as_ref()
            .filter(|c| !c.is_empty() && c.len() <= ICC_CAP)
            .map(|c| c.to_vec())
    } else {
        None
    };

    // Hot path: plain RGB8, non-interlaced, linear-light mode. Rows are
    // sRGB->linear LUT-mapped as they are decoded, so the pixels never
    // take a second full-image pass (and never exist as a full u8 copy).
    {
        let (ct, bits) = png_reader.output_color_type();
        let hdr = png_reader.info();
        let (src_w, src_h) = (hdr.width as usize, hdr.height as usize);
        let (dst_w, dst_h) = fit_dims(src_w, src_h, p.max_width, p.max_height);
        if ct == png::ColorType::Rgb
            && bits == png::BitDepth::Eight
            && !hdr.interlaced
            && (src_w, src_h) != (dst_w, dst_h)
            && linear_light(p)
            // Oriented PNGs are rare; they take the general arm below
            // rather than teaching the row-streaming path to rotate.
            && orientation.is_upright()
        {
            let fwd = fwd_lut();
            // Fully filled row by row; the row-count check below rejects
            // truncated streams before the buffer is consumed.
            scratch_u16(&mut s.src16, src_w * src_h * 3);
            let mut y = 0usize;
            while let Some(row) = png_reader.next_row().context("decode PNG")? {
                let dst = &mut s.src16[y * src_w * 3..(y + 1) * src_w * 3];
                for (d, &b) in dst.iter_mut().zip(row.data()) {
                    *d = fwd[b as usize];
                }
                y += 1;
            }
            anyhow::ensure!(y == src_h, "PNG row count mismatch");
            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[..src_w * src_h * 3]),
                src_w,
                src_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, &v) in out.iter_mut().zip(&s.dst16[..dst_w * dst_h * 3]) {
                *d = back[v as usize];
            }
            let t_resize = t1.elapsed();
            let t2 = std::time::Instant::now();
            let out = encode_output(s, dst_w, dst_h, 3, target, p, icc.as_deref());
            if timing {
                eprintln!(
                    "timing png(fused) decode+fwd({src_w}x{src_h})={:.1}ms resize+back={:.1}ms encode={:.1}ms",
                    t_decode.as_secs_f64() * 1e3,
                    t_resize.as_secs_f64() * 1e3,
                    t2.elapsed().as_secs_f64() * 1e3
                );
            }
            return out;
        }
    }

    let buf_len = png_reader.output_buffer_size().context("PNG too large")?;
    scratch_u8(&mut s.chunk8, buf_len);
    let info = png_reader
        .next_frame(&mut s.chunk8[..buf_len])
        .context("decode PNG")?;
    let (src_w, src_h) = (info.width as usize, info.height as usize);
    let len = info.buffer_size();

    // Normalize to RGB8/RGBA8 (EXPAND leaves grayscale as 1-2 channels).
    let channels = match info.color_type {
        png::ColorType::Rgb => 3,
        png::ColorType::Rgba => 4,
        png::ColorType::Grayscale => {
            gray_to_rgb(s, len, 1);
            3
        }
        png::ColorType::GrayscaleAlpha => {
            gray_to_rgb(s, len, 2);
            4
        }
        png::ColorType::Indexed => anyhow::bail!("unexpanded indexed PNG"),
    };

    let t_decode = t0.elapsed();
    let t1 = std::time::Instant::now();
    let (dst_w, dst_h) = resize_pixels_oriented(s, channels, src_w, src_h, orientation, p)?;
    let t_resize = t1.elapsed();
    let t2 = std::time::Instant::now();
    let out = encode_output(s, dst_w, dst_h, channels, target, p, icc.as_deref());
    if timing {
        eprintln!(
            "timing png decode({src_w}x{src_h})={:.1}ms resize={:.1}ms encode={:.1}ms",
            t_decode.as_secs_f64() * 1e3,
            t_resize.as_secs_f64() * 1e3,
            t2.elapsed().as_secs_f64() * 1e3
        );
    }
    out
}

/// The larger of the two fits a source could take once its orientation
/// is known: axis-swapping orientations fit the *displayed* frame, and
/// with an asymmetric box that can be several times the unoriented
/// result. Used where the estimate runs before the orientation is
/// parsed — over-counting the output side keeps a limit safe.
pub(super) fn larger_fit(w: usize, h: usize, p: &Params) -> (usize, usize) {
    let a = fit_dims(w, h, p.max_width, p.max_height);
    let b = fit_dims(h, w, p.max_width, p.max_height);
    if a.0 * a.1 >= b.0 * b.1 {
        a
    } else {
        (b.1, b.0)
    }
}

/// Expand grayscale(+alpha) pixels in `chunk8[..len]` to RGB(A) in place.
pub(super) fn gray_to_rgb(s: &mut Scratch, len: usize, in_ch: usize) {
    let out_ch = in_ch + 2;
    let pixels = len / in_ch;
    // The reverse loop below writes every output position.
    scratch_u8(&mut s.chunk8, pixels * out_ch);
    for i in (0..pixels).rev() {
        let g = s.chunk8[i * in_ch];
        let a = if in_ch == 2 {
            s.chunk8[i * in_ch + 1]
        } else {
            0
        };
        let o = i * out_ch;
        s.chunk8[o] = g;
        s.chunk8[o + 1] = g;
        s.chunk8[o + 2] = g;
        if in_ch == 2 {
            s.chunk8[o + 3] = a;
        }
    }
}

pub(super) fn process_webp<R: std::io::Read>(
    s: &mut Scratch,
    mut reader: R,
    target: ImageFormat,
    p: &Params,
) -> Result<Vec<u8>> {
    s.srcbuf.clear();
    reader
        .read_to_end(&mut s.srcbuf)
        .context("read WebP source")?;

    // Decode with libwebp's built-in scaler when we are shrinking well past
    // the target, keeping the same quality headroom as the JPEG DCT path:
    // decode at >= margin x target, then hand the remainder to linear-light
    // Lanczos. libwebp's scaler alone (scale straight to target) is what
    // costs other servers their score.
    let timing = crate::config::config().timing;
    let t0 = std::time::Instant::now();
    // One mux parse serves both metadata chunks: the ICC profile and
    // the EXIF orientation (raw TIFF or JPEG-style prefixed; writers
    // disagree, browsers accept both).
    let (icc, exif) = webp_metadata(
        &s.srcbuf,
        icc_passthrough(p) && target_supports_icc(target),
        auto_rotate(p),
    );
    let orientation = exif
        .and_then(|d| crate::meta::Orientation::from_exif_payload(&d))
        .unwrap_or(crate::meta::Orientation::UPRIGHT);
    // Animated sources render their first frame, like other image
    // proxies: swap the container for the frame's bitstream (metadata
    // was already read from the full container above). A first frame
    // that does not cover the canvas keeps the original bytes and
    // fails with the animation error below, as before.
    if let Some(frame) = webp_first_frame(&s.srcbuf) {
        s.srcbuf.clear();
        s.srcbuf.extend_from_slice(&frame);
    }
    let (src_w, src_h, channels, dec_w, dec_h) = webp_decode_into_chunk8(s, orientation, p)?;
    let _ = (src_w, src_h);
    let t_dec = t0.elapsed();

    let t1 = std::time::Instant::now();
    let (dst_w, dst_h) = resize_pixels_oriented(s, channels, dec_w, dec_h, orientation, p)?;
    let t_resize = t1.elapsed();

    let t2 = std::time::Instant::now();
    let out = encode_output(s, dst_w, dst_h, channels, target, p, icc.as_deref())?;
    if timing {
        eprintln!(
            "timing webp decode({dec_w}x{dec_h})={:.1}ms resize={:.1}ms encode={:.1}ms",
            t_dec.as_secs_f64() * 1e3,
            t_resize.as_secs_f64() * 1e3,
            t2.elapsed().as_secs_f64() * 1e3
        );
    }
    Ok(out)
}

/// AVIF: decode via dav1d, resize, re-encode via SVT-AV1. AV1 has no
/// reduced-resolution decode mode, so unlike JPEG/WebP the decode always
/// runs at full source resolution.
#[cfg(feature = "avif")]
pub(super) fn process_avif<R: std::io::Read>(
    s: &mut Scratch,
    mut reader: R,
    target: ImageFormat,
    p: &Params,
) -> Result<Vec<u8>> {
    s.srcbuf.clear();
    reader
        .read_to_end(&mut s.srcbuf)
        .context("read AVIF source")?;

    let timing = crate::config::config().timing;
    let t0 = std::time::Instant::now();
    // avif-parse exposes neither colr nor irot/imir; both come from
    // our own bounded container walk.
    let icc = if icc_passthrough(p) && target_supports_icc(target) {
        crate::avif::extract_icc(&s.srcbuf)
    } else {
        None
    };
    let orientation = if auto_rotate(p) {
        crate::avif::extract_orientation(&s.srcbuf)
    } else {
        crate::meta::Orientation::UPRIGHT
    };
    {
        // Before the decode allocates: dav1d has no shrink-on-load, so
        // the whole frame materializes. Dimensions come from the
        // container probe; four channels covers the alpha auxiliary
        // item, and 10/12-bit sources stage two bytes per sample, which
        // the linear-light term already accounts for.
        let (pw, ph) = crate::avif::probe_avif(&s.srcbuf)?;
        check_src_pixels(pw, ph)?;
        let (ow, oh) = larger_fit(pw, ph, p);
        check_decoded_bytes(
            DecodeCost::full_frame(pw, ph, 4, p)
                .with_output(ow, oh, 4)
                .with_compressed(s.srcbuf.len()),
            "AVIF",
        )?;
    }
    let (src_w, src_h, channels) = crate::avif::decode_avif_into(&s.srcbuf, &mut s.chunk8)?;
    let t_dec = t0.elapsed();

    let t1 = std::time::Instant::now();
    let (dst_w, dst_h) = resize_pixels_oriented(s, channels, src_w, src_h, orientation, p)?;
    let t_resize = t1.elapsed();

    let t2 = std::time::Instant::now();
    let out = encode_output(s, dst_w, dst_h, channels, target, p, icc.as_deref())?;
    if timing {
        eprintln!(
            "timing avif decode({src_w}x{src_h})={:.1}ms resize={:.1}ms encode={:.1}ms",
            t_dec.as_secs_f64() * 1e3,
            t_resize.as_secs_f64() * 1e3,
            t2.elapsed().as_secs_f64() * 1e3
        );
    }
    Ok(out)
}

/// Decode `srcbuf` (WebP) into `chunk8`, scaling during decode down to
/// margin x target when the source is much larger. Returns
/// (src_w, src_h, channels, decoded_w, decoded_h).
pub(super) fn webp_decode_into_chunk8(
    s: &mut Scratch,
    orientation: crate::meta::Orientation,
    p: &Params,
) -> Result<(usize, usize, usize, usize, usize)> {
    use libwebp_sys as w;
    // SAFETY: FFI cluster reading only `s.srcbuf`, which is live for the whole
    // block. A zeroed WebPDecoderConfig is libwebp's documented pre-init state and
    // the WebPInitDecoderConfig ABI check is enforced; `output.u.RGBA` is the arm
    // libwebp fills for MODE_RGB/MODE_RGBA. WebPFreeDecBuffer runs exactly once on
    // both the error and success paths.
    unsafe {
        let mut config: w::WebPDecoderConfig = std::mem::zeroed();
        anyhow::ensure!(
            w::WebPInitDecoderConfig(&mut config),
            "libwebp ABI mismatch"
        );
        let status = w::WebPGetFeatures(s.srcbuf.as_ptr(), s.srcbuf.len(), &mut config.input);
        anyhow::ensure!(
            status == w::VP8StatusCode::VP8_STATUS_OK,
            "parse WebP header"
        );
        anyhow::ensure!(
            config.input.has_animation == 0,
            "animated WebP is unsupported"
        );
        let (src_w, src_h) = (config.input.width as usize, config.input.height as usize);
        check_src_pixels(src_w, src_h)?;
        let channels = if config.input.has_alpha != 0 { 4 } else { 3 };
        // Conservative for WebP: libwebp's decode scaler may shrink
        // this below the source (decided a few lines down), so the
        // full frame is an upper bound, not the exact figure.
        let (ow, oh) = larger_fit(src_w, src_h, p);
        check_decoded_bytes(
            DecodeCost::full_frame(src_w, src_h, channels as u64, p)
                .with_output(ow, oh, channels as u64)
                .with_compressed(s.srcbuf.len()),
            "WebP",
        )?;

        // The stored-space resize target: fit the *displayed* frame,
        // swap back for axis-swapping orientations. Deciding the decode
        // scale from the unoriented fit would under-decode sources
        // whose displayed aspect fits the box differently.
        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)
        };
        let need_w = ((dst_w as f64) * dct_margin()).ceil() as usize;
        let (dec_w, dec_h) = if need_w < src_w {
            let scale = need_w as f64 / src_w as f64;
            (
                need_w.max(dst_w),
                (((src_h as f64) * scale).round() as usize).max(dst_h),
            )
        } else {
            (src_w, src_h)
        };
        if (dec_w, dec_h) != (src_w, src_h) {
            config.options.use_scaling = 1;
            config.options.scaled_width = dec_w as i32;
            config.options.scaled_height = dec_h as i32;
        }
        // libwebp's threaded decode pipelines entropy decoding and
        // reconstruction across two threads (the same setting libvips
        // ships); like band-parallel resize this briefly exceeds the CPU
        // slot without oversubscribing on average.
        if crate::config::config().webp_decode_threads {
            config.options.use_threads = 1;
        }
        config.output.colorspace = if channels == 4 {
            w::WEBP_CSP_MODE::MODE_RGBA
        } else {
            w::WEBP_CSP_MODE::MODE_RGB
        };

        let status = w::WebPDecode(s.srcbuf.as_ptr(), s.srcbuf.len(), &mut config);
        if status != w::VP8StatusCode::VP8_STATUS_OK {
            w::WebPFreeDecBuffer(&mut config.output);
            anyhow::bail!("decode WebP: {status:?}");
        }
        let buf = &config.output.u.RGBA;
        let stride = buf.stride as usize;
        let row = dec_w * channels;
        // Every row is copied below before the buffer is read.
        scratch_u8(&mut s.chunk8, dec_h * row);
        for y in 0..dec_h {
            // SAFETY: after VP8_STATUS_OK the output buffer holds dec_h rows spaced
            // `stride` bytes apart, each with dec_w * channels (= row) valid bytes, per
            // the WebPRGBABuffer contract; y < dec_h keeps every read in bounds, and the
            // buffer is not freed until after this loop.
            let src_row = std::slice::from_raw_parts(buf.rgba.add(y * stride), row);
            s.chunk8[y * row..(y + 1) * row].copy_from_slice(src_row);
        }
        w::WebPFreeDecBuffer(&mut config.output);
        Ok((src_w, src_h, channels, dec_w, dec_h))
    }
}

/// Resize the fully decoded pixels in `chunk8` honoring an EXIF-style
/// orientation: the box fits the *displayed* frame, the resize runs in
/// the stored orientation, and the pixels rotate afterwards on the
/// small output frame — the same strategy as the JPEG arm, shared by
/// the PNG/WebP/AVIF full-frame paths.
pub(super) fn resize_pixels_oriented(
    s: &mut Scratch,
    channels: usize,
    src_w: usize,
    src_h: usize,
    orientation: crate::meta::Orientation,
    p: &Params,
) -> Result<(usize, usize)> {
    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)
    };
    resize_pixels_to(s, channels, src_w, src_h, dst_w, dst_h, p)?;
    if orientation.is_upright() {
        return Ok((dst_w, dst_h));
    }
    // chunk8 held the decoded source; it is free once the resize is
    // done, so rotate into it and swap it in as out8.
    let dims = crate::meta::apply_orientation(
        &s.out8[..dst_w * dst_h * channels],
        dst_w,
        dst_h,
        channels,
        orientation,
        &mut s.chunk8,
    );
    std::mem::swap(&mut s.out8, &mut s.chunk8);
    Ok(dims)
}

/// Resize the fully decoded pixels in `chunk8` (3 or 4 channels) into
/// `out8` at exactly `dst_w`x`dst_h`. RGB follows the same
/// linear-light path as JPEG; alpha images are premultiplied before
/// resampling and unpremultiplied after.
pub(super) fn resize_pixels_to(
    s: &mut Scratch,
    channels: usize,
    src_w: usize,
    src_h: usize,
    dst_w: usize,
    dst_h: usize,
    p: &Params,
) -> Result<(usize, usize)> {
    let src_len = src_w * src_h * channels;
    if (src_w, src_h) == (dst_w, dst_h) {
        scratch_u8(&mut s.out8, src_len);
        let (chunk8, out8) = (&s.chunk8, &mut s.out8);
        out8[..src_len].copy_from_slice(&chunk8[..src_len]);
        return Ok((dst_w, dst_h));
    }

    if linear_light(p) {
        let (fwd, back) = (fwd_lut(), back_lut());
        // Fully overwritten by the LUT/premultiply loops just below.
        scratch_u16(&mut s.src16, src_len);
        if channels == 4 {
            for (d, src) in s.src16[..src_len]
                .chunks_exact_mut(4)
                .zip(s.chunk8[..src_len].chunks_exact(4))
            {
                let a = src[3] as u32 * 257;
                for c in 0..3 {
                    // Premultiply in linear light so resampling never bleeds
                    // color from fully transparent pixels.
                    d[c] = ((fwd[src[c] as usize] as u32 * a) / 65535) as u16;
                }
                d[3] = a as u16;
            }
        } else {
            for (d, src) in s.src16[..src_len].iter_mut().zip(&s.chunk8[..src_len]) {
                *d = fwd[*src as usize];
            }
        }
        let dst_len = dst_w * dst_h * channels;
        scratch_u16(&mut s.dst16, dst_len);
        resize_bands(
            u16_as_bytes(&s.src16[..src_len]),
            src_w,
            src_h,
            u16_as_bytes_mut(&mut s.dst16[..dst_len]),
            dst_w,
            dst_h,
            if channels == 4 {
                PixelType::U16x4
            } else {
                PixelType::U16x3
            },
            p.parallel,
            &mut s.resizer,
        )?;
        scratch_u8(&mut s.out8, dst_len);
        if channels == 4 {
            for (d, src) in s.out8[..dst_len]
                .chunks_exact_mut(4)
                .zip(s.dst16[..dst_len].chunks_exact(4))
            {
                let a = src[3] as u32;
                for (out, &pre) in d[..3].iter_mut().zip(&src[..3]) {
                    let un = (pre as u32 * 65535)
                        .checked_div(a)
                        .map_or(0, |v| v.min(65535)) as u16;
                    *out = back[un as usize];
                }
                d[3] = (a / 257) as u8;
            }
        } else {
            for (d, src) in s.out8[..dst_len].iter_mut().zip(&s.dst16[..dst_len]) {
                *d = back[*src as usize];
            }
        }
    } else {
        if channels == 4 {
            // Premultiply in place (u8 approximation for speed mode).
            for px in s.chunk8[..src_len].chunks_exact_mut(4) {
                let a = px[3] as u32;
                for c in px[..3].iter_mut() {
                    *c = ((*c as u32 * a + 127) / 255) as u8;
                }
            }
        }
        let dst_len = dst_w * dst_h * channels;
        scratch_u8(&mut s.out8, dst_len);
        let (chunk8, out8) = (&s.chunk8, &mut s.out8);
        resize_bands(
            &chunk8[..src_len],
            src_w,
            src_h,
            &mut out8[..dst_len],
            dst_w,
            dst_h,
            if channels == 4 {
                PixelType::U8x4
            } else {
                PixelType::U8x3
            },
            p.parallel,
            &mut s.resizer,
        )?;
        if channels == 4 {
            for px in s.out8[..dst_len].chunks_exact_mut(4) {
                let a = px[3] as u32;
                for c in px[..3].iter_mut() {
                    *c = (*c as u32 * 255).checked_div(a).map_or(0, |v| v.min(255)) as u8;
                }
            }
        }
    }
    Ok((dst_w, dst_h))
}