f-office 0.1.0

Renders Office Open XML documents the way Microsoft Office does.
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
//! The files of the pictures that a target's PDF writer writes again.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use f_office_paint::{
    AlphaMix, DisplayList, GroupPlaces, ImageFormat, ImageItem, Item, JpegQuality, JpegSample,
    JpegShare, MAX_DECODED_BYTES, MAX_DECODED_BYTES_TO_WRITE_AGAIN, PaletteClass, PictureCrop,
    Resampler,
};
use f_office_units::div_round_i128;

use crate::{Warning, Warnings};
use f_office_paint::image_header::{jpeg_header, png_color_type, png_header, png_palette_class};

mod resample;

/// The pixels of a file that the writer keeps, as left, top, right and bottom pixel edges.
type Part = [usize; 4];

/// The pixel size to which the writer resamples a picture, and how it finds the new pixels.
type Resampled = ((usize, usize), Resampler);

/// A picture file, by the number of its bytes ([`Files::number`]), the part of its pixels that
/// the writer keeps, or `None` for all, and the pixel size at which the writer writes it with
/// how it finds its pixels, or `None` for the part's own.
type Key = (usize, Option<Part>, Option<Resampled>);

/// The picture files of a display list. Each file gets a number for its bytes, so that two
/// files of the same bytes share what the writer writes, and the header of each file is read
/// once for each format. The uses of one file hold the same `Arc`, since a story reads each of
/// its parts once, so the bytes of each `Arc` are hashed only when the registry first meets
/// it: the work grows with the size of the files and with the count of their uses, and not
/// with the product of the two.
#[derive(Default)]
struct Files {
    /// The number of each `Arc`, by the place of its bytes in memory.
    by_place: HashMap<SamePlace, usize>,
    /// The number of each content, by its bytes.
    by_bytes: HashMap<Arc<[u8]>, usize>,
    /// What the header gives for each number in each format.
    headers: HashMap<(usize, ImageFormat), Header>,
}

impl Files {
    /// The number of the bytes of `data`: the same for two `Arc`s of the same bytes.
    fn number(&mut self, data: &Arc<[u8]>) -> usize {
        let by_bytes = &mut self.by_bytes;
        *self
            .by_place
            .entry(SamePlace(Arc::clone(data)))
            .or_insert_with(|| {
                count_read_bytes(data.len());
                let next = by_bytes.len();
                *by_bytes.entry(Arc::clone(data)).or_insert(next)
            })
    }

    /// What the header of the file `number`, whose bytes are `data`, gives in `format`.
    fn header(&mut self, number: usize, data: &[u8], format: ImageFormat) -> Header {
        *self.headers.entry((number, format)).or_insert_with(|| {
            count_read_bytes(data.len());
            Header::of(data, format)
        })
    }
}

/// The `Arc` of a file, compared and hashed by the place of its bytes in memory and not by the
/// bytes. It keeps the `Arc`, so that no other file takes that place while it lives.
struct SamePlace(Arc<[u8]>);

impl PartialEq for SamePlace {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for SamePlace {}

impl Hash for SamePlace {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.as_ptr().addr().hash(state);
    }
}

/// What the writer reads from the header of a picture file: the pixel size of a JPEG or PNG
/// file, when the header gives it, and the class of the palette of a PNG file
/// ([`png_palette_class`]).
#[derive(Clone, Copy)]
struct Header {
    pixels: Option<(usize, usize)>,
    palette: Option<PaletteClass>,
}

impl Header {
    /// Reads the header of the file `data` in `format`.
    fn of(data: &[u8], format: ImageFormat) -> Self {
        match format {
            ImageFormat::Jpeg => Self {
                pixels: jpeg_header(data).map(|header| header.pixels),
                palette: None,
            },
            ImageFormat::Png => Self {
                pixels: png_header(data).map(|header| header.pixels),
                palette: png_palette_class(data),
            },
            _ => Self {
                pixels: None,
                palette: None,
            },
        }
    }
}

#[cfg(test)]
thread_local! {
    /// The bytes of picture files that [`Files`] reads on this thread: the whole file for the
    /// hash of each `Arc` that it meets first, and the whole file for each header that it
    /// reads, as an upper bound. A test bounds the work of many uses of one file by this
    /// count, and not by a time.
    static READ_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Counts `bytes` read bytes of picture files (`READ_BYTES`). Only a test build keeps the
/// count.
fn count_read_bytes(bytes: usize) {
    #[cfg(test)]
    READ_BYTES.with(|read| read.set(read.get() + bytes));
    #[cfg(not(test))]
    let _ = bytes;
}

/// The pixel size at which the writer writes a picture of the given pixels, of the given
/// palette class when it is a PNG picture of a palette of one, in its item, with how it finds
/// the new pixels, or `None` for its own ([`f_office_paint::Writer::resampled_size`]).
pub type Resampling<'a> =
    &'a dyn Fn((usize, usize), Option<PaletteClass>, &ImageItem) -> Option<Resampled>;

/// How the target's writer writes the files of pictures ([`f_office_paint::Writer`]).
#[derive(Clone, Copy)]
pub struct Rewriting<'a> {
    /// The quality at which it writes each JPEG picture again, or `None` to keep the files.
    pub quality: Option<JpegQuality>,
    /// The share of the color under Flate below which it writes an opaque RGB picture of a PNG
    /// file as a JPEG file at `quality`, or `None` to keep each PNG file lossless.
    pub jpeg_share: Option<JpegShare>,
    /// The second test of a picture that `jpeg_share` takes, which keeps it a JPEG file, or
    /// `None` for none.
    pub jpeg_sample: Option<JpegSample>,
    /// How it writes a cropped picture.
    pub crop: PictureCrop,
    /// How it mixes the colors of a picture with an alpha when it resamples it.
    pub alpha_mix: AlphaMix,
    /// The pixel size to which it resamples a picture.
    pub resampling: Resampling<'a>,
}

/// Writes the file of each picture of the pages again as the target's writer does. With a JPEG
/// `quality`, each JPEG picture becomes a baseline JPEG file at that quality. When the writer
/// writes the visible part of a cropped picture ([`PictureCrop::keeps_visible_part`]), an
/// upright cropped JPEG or PNG picture keeps only the pixels of its visible part
/// ([`visible_part`]), and is drawn at its clip with no clip. Each JPEG or PNG picture to which
/// `resampling` gives a pixel size, for its own pixels or its visible part's and the class of
/// its palette ([`png_palette_class`]), is resampled to it first as `resampling` and the crop
/// say ([`part_resampled`]), and a PNG picture stays a PNG file. Pages that show the same file with the same part
/// at the same size share the new one, and each file is hashed and its header read once
/// ([`Files`]). A file that the decoder does not read, such as a CMYK or
/// a lossless JPEG file, a JPEG file whose frame needs more than [`MAX_DECODED_BYTES`] or a PNG
/// file whose RGBA pixels need more than [`MAX_DECODED_BYTES_TO_WRITE_AGAIN`], stays as it is with
/// its clip, with a warning for each use, and so do turned pictures and the pictures inside a
/// group of a picture's own items, which the writer writes in the picture's own space; a
/// picture in a group of the page's items, which only cuts it ([`page_images`]), is written as
/// the page's. Without a JPEG quality, a JPEG picture also stays as it is.
pub fn write_pictures_again(
    list: DisplayList,
    rewriting: Rewriting,
    warnings: &mut Warnings,
) -> DisplayList {
    let mut files = Files::default();
    let mut written: HashMap<Key, Option<Written>> = HashMap::new();
    let mut pages = Vec::new();
    for page in list.into_pages() {
        pages.push(page.map_items(|mut items| {
            for image in page_images(&mut items) {
                let (data, format) = (&image.image.data, image.image.format);
                let file = files.number(data);
                let header = files.header(file, data, format);
                // A turned picture has no pixel size of its own here.
                let own = header.pixels.filter(|_| image.turn.is_none());
                let part = own
                    .filter(|_| rewriting.crop.keeps_visible_part())
                    .and_then(|own| visible_part(image, own));
                let drawn = part.map_or_else(|| image.clone(), |_| at_clip(image));
                let shown = part.map(|[left, top, right, bottom]| (right - left, bottom - top));
                let size = shown
                    .or(own)
                    .and_then(|pixels| (rewriting.resampling)(pixels, header.palette, &drawn));
                let key = (file, part, size);
                let data = &image.image.data;
                let again = match (format, rewriting.quality, rewriting.jpeg_share) {
                    (ImageFormat::Jpeg, Some(quality), _) => {
                        written.entry(key).or_insert_with(|| {
                            jpeg_again(data, (part, size), quality, rewriting.crop)
                                .map(|file| (file, ImageFormat::Jpeg))
                        })
                    }
                    (ImageFormat::Png, Some(quality), Some(share))
                        if png_color_type(data).is_some_and(|kind| RGB_TYPES.contains(&kind)) =>
                    {
                        written.entry(key).or_insert_with(|| {
                            png_or_jpeg(data, (part, size), (quality, share), rewriting)
                        })
                    }
                    (ImageFormat::Png, _, _) if part.is_some() || size.is_some() => {
                        written.entry(key).or_insert_with(|| {
                            png_again(data, (part, size), rewriting.alpha_mix, rewriting.crop)
                                .map(|file| (file, ImageFormat::Png))
                        })
                    }
                    _ => continue,
                };
                let Some((data, format)) = again else {
                    warnings.push(Warning::PictureNotWrittenAgain { format });
                    continue;
                };
                let (data, format) = (Arc::clone(data), *format);
                if part.is_some() {
                    *image = drawn;
                }
                image.image.data = data;
                image.image.format = format;
            }
            items
        }));
    }
    DisplayList::new(pages)
}

/// The pictures that the writer writes as the page's own among `items`: each picture item, and
/// each picture in a group of the page's items ([`GroupPlaces::Page`]), whose clip cuts it
/// without a space of its own.
fn page_images(items: &mut [Item]) -> Vec<&mut ImageItem> {
    let mut found = Vec::new();
    for item in items {
        match item {
            Item::Image(image) => found.push(image),
            Item::Group(group) if group.places == GroupPlaces::Page => {
                found.extend(page_images(&mut group.items));
            }
            Item::Glyphs(_)
            | Item::Rect(_)
            | Item::Path(_)
            | Item::Gradient(_)
            | Item::Group(_) => {}
        }
    }
    found
}

/// The pixels of a file of `own` pixels that the clip of `image` shows, or `None` without a
/// clip, or for a clip that shows no whole pixel: from the clip's left and top edges in the
/// file's pixels, each rounded to the nearest pixel, a half up, as many pixels as the clip's
/// width and height in the file's pixels, each rounded the same way. An edge of the clip
/// beyond the file, from a crop below zero, counts as the file's edge.
fn visible_part(image: &ImageItem, own: (usize, usize)) -> Option<Part> {
    let (rect, clip) = rect_and_clip(image)?;
    edges_of(rect, clip, own)
}

/// The left, top, right and bottom edges in units of the rectangle of `image` and of the part
/// of its clip that lies on it ([`ImageItem::shown`]), or `None` without such a part.
fn rect_and_clip(image: &ImageItem) -> Option<([i64; 4], [i64; 4])> {
    let clip = image.shown()?;
    let edges = |x: i64, y: i64, width: i64, height: i64| {
        Some([x, y, x.checked_add(width)?, y.checked_add(height)?])
    };
    let rect = edges(
        image.x.units(),
        image.y.units(),
        image.width.units(),
        image.height.units(),
    )?;
    let clip = edges(
        clip.x.units(),
        clip.y.units(),
        clip.width.units(),
        clip.height.units(),
    )?;
    Some((rect, clip))
}

/// The pixels of a file of `own` pixels drawn in `rect` that `clip` shows, both given as left,
/// top, right and bottom edges in units ([`visible_part`]), or `None` when the rounded part
/// starts before the file or ends after it.
fn edges_of(rect: [i64; 4], clip: [i64; 4], own: (usize, usize)) -> Option<Part> {
    // The pixels that the clip from `start` to `end` shows on a side of `count` pixels from
    // `from` to `to`: its start and its length in pixels, each rounded to the nearest pixel, a
    // half up.
    let side = |start: i64, end: i64, from: i64, to: i64, count: usize| {
        let [start, end, from, to] = [start, end, from, to].map(i128::from);
        let (count, length) = (i128::try_from(count).ok()?, to - from);
        (length > 0).then_some(())?;
        let pixels = |offset: i128| div_round_i128(offset * count, length);
        let first = pixels(start - from);
        let last = first + pixels(end - start);
        let inside = first >= 0 && first < last && last <= count;
        inside.then_some((usize::try_from(first).ok()?, usize::try_from(last).ok()?))
    };
    let [x0, y0, x1, y1] = rect;
    let (left, right) = side(clip[0], clip[2], x0, x1, own.0)?;
    let (top, bottom) = side(clip[1], clip[3], y0, y1, own.1)?;
    Some([left, top, right, bottom])
}

/// The item of `image` drawn at the part of its clip that lies on its rectangle, with no clip.
fn at_clip(image: &ImageItem) -> ImageItem {
    let mut drawn = image.clone();
    if let Some(clip) = image.shown() {
        (drawn.x, drawn.y, drawn.width, drawn.height) = (clip.x, clip.y, clip.width, clip.height);
        drawn.clip = None;
    }
    drawn
}

/// The samples of `part` of a picture of `own` pixels with `channels` interleaved samples each,
/// or `None` when the part does not lie inside it.
fn cut(samples: &[u8], own: (usize, usize), channels: usize, part: Part) -> Option<Vec<u8>> {
    let [left, top, right, bottom] = part;
    (right <= own.0 && bottom <= own.1 && left < right && top < bottom).then_some(())?;
    let row = own.0.checked_mul(channels)?;
    let mut out = Vec::with_capacity((right - left) * (bottom - top) * channels);
    for y in top..bottom {
        let start = y * row + left * channels;
        out.extend_from_slice(samples.get(start..start + (right - left) * channels)?);
    }
    Some(out)
}

/// A JPEG file written again at `quality`: its `part` resampled to `size` as `crop` says, each
/// when it is given ([`part_resampled`]). `None`, which keeps the file with a warning, when the
/// file does not decode, the part does not lie inside it, or the encoder cannot write the
/// result (a side of 0 or above 65,535 pixels).
fn jpeg_again(
    data: &[u8],
    (part, size): (Option<Part>, Option<Resampled>),
    quality: JpegQuality,
    crop: PictureCrop,
) -> Option<Arc<[u8]>> {
    let samples = f_office_jpeg::decode(data, MAX_DECODED_BYTES).ok()?;
    let channels = samples.channels();
    let own = (samples.width(), samples.height());
    let picture = (samples.into_data(), own, channels.count());
    let (own, values) = part_resampled(picture, (part, size), (crop, AlphaMix::Plain))?;
    let samples = f_office_jpeg::Samples::new(own, channels, values).ok()?;
    f_office_jpeg::encode(&samples, quality.get())
        .ok()
        .map(Into::into)
}

/// A file that the writer writes, with its format.
type Written = (Arc<[u8]>, ImageFormat);

/// The PNG color types of RGB pictures, without and with an alpha.
const RGB_TYPES: [u8; 2] = [2, 6];

/// The level at which the writer's choice compresses a picture's color with Flate.
const FLATE_LEVEL: u32 = 6;

/// The file of an RGB picture of the PNG file `data`, as the writer writes it when it writes
/// opaque pictures as JPEG files below `share` of their color under Flate: its `part`
/// resampled to `size` as the crop says, each when it is given ([`part_resampled`]). An opaque
/// picture, whose every alpha is whole, becomes a JPEG file of its color at `quality` when that
/// file is smaller than `share` of the color compressed with Flate at [`FLATE_LEVEL`], and the
/// writer's second test, when it has one, takes it too ([`JpegSample::takes`], with each strip
/// of [`JpegSample::strips`] compressed on its own at the same level). Every other picture is written as [`png_again`] writes it when it has a part or a size, and keeps
/// its file otherwise. `None`, which keeps the file with a warning, as [`png_again`] says.
fn png_or_jpeg(
    data: &Arc<[u8]>,
    (part, size): (Option<Part>, Option<Resampled>),
    (quality, share): (JpegQuality, JpegShare),
    rewriting: Rewriting,
) -> Option<Written> {
    let lossless = || {
        if part.is_none() && size.is_none() {
            return Some((Arc::clone(data), ImageFormat::Png));
        }
        png_again(data, (part, size), rewriting.alpha_mix, rewriting.crop)
            .map(|file| (file, ImageFormat::Png))
    };
    let Ok(picture) =
        f_office_paint::decode_file(data, ImageFormat::Png, MAX_DECODED_BYTES_TO_WRITE_AGAIN)
    else {
        return lossless();
    };
    if picture.color().has_alpha() && picture.to_rgba8().pixels().any(|pixel| pixel.0[3] < 255) {
        return lossless();
    }
    let (Ok(width), Ok(height)) = (
        usize::try_from(picture.width()),
        usize::try_from(picture.height()),
    ) else {
        return lossless();
    };
    let pixels = picture.to_rgb8().into_raw();
    let (shown, color) = part_resampled(
        (pixels, (width, height), 3),
        (part, size),
        (rewriting.crop, AlphaMix::Plain),
    )?;
    let flate = flate_size(&color)?;
    let second = match rewriting.jpeg_sample {
        Some(sample) => sample.takes(sample_size(&color, shown)?, shown.1, (flate, color.len())),
        None => true,
    };
    let samples = f_office_jpeg::Samples::new(shown, f_office_jpeg::Channels::Rgb, color).ok()?;
    let jpeg = f_office_jpeg::encode(&samples, quality.get()).ok()?;
    if share.takes(jpeg.len(), flate) && second {
        return Some((jpeg.into(), ImageFormat::Jpeg));
    }
    lossless()
}

/// The size of `bytes` compressed with Flate at [`FLATE_LEVEL`], as a zlib stream.
fn flate_size(bytes: &[u8]) -> Option<usize> {
    let mut flate =
        flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(FLATE_LEVEL));
    std::io::Write::write_all(&mut flate, bytes).ok()?;
    flate.finish().ok().map(|stream| stream.len())
}

/// The size under Flate of the sample of the RGB `color` of a picture of `(width, height)`
/// pixels: the sum of the sizes of its strips ([`JpegSample::strips`]), each compressed on its
/// own ([`flate_size`]), so that the rows that two strips share count in each. `None` when the
/// color holds fewer rows.
fn sample_size(color: &[u8], (width, height): (usize, usize)) -> Option<usize> {
    let row = width.checked_mul(3)?;
    JpegSample::strips(height).try_fold(0_usize, |sum, rows| {
        let strip = color.get(rows.start.checked_mul(row)?..rows.end.checked_mul(row)?)?;
        sum.checked_add(flate_size(strip)?)
    })
}

/// A PNG file of its `part` resampled to `size` as `crop` says, each when it is given
/// ([`part_resampled`]), with its color and its alpha, if it has one, as 8-bit samples, the
/// colors of a picture with an alpha mixed as `alpha_mix` says when it is resampled
/// ([`AlphaMix`]). `None`, which keeps the file with a warning, when the file does not decode
/// with the picture decode's first step ([`f_office_paint::decode_file`]) within the writer's
/// own limit ([`MAX_DECODED_BYTES_TO_WRITE_AGAIN`], larger than the outputs' because the writer
/// writes a smaller file), or the part does not lie inside it.
fn png_again(
    data: &[u8],
    (part, size): (Option<Part>, Option<Resampled>),
    alpha_mix: AlphaMix,
    crop: PictureCrop,
) -> Option<Arc<[u8]>> {
    let picture =
        f_office_paint::decode_file(data, ImageFormat::Png, MAX_DECODED_BYTES_TO_WRITE_AGAIN)
            .ok()?;
    let (pixels, channels, color) = if picture.color().has_alpha() {
        (
            picture.to_rgba8().into_raw(),
            4,
            image::ExtendedColorType::Rgba8,
        )
    } else {
        (
            picture.to_rgb8().into_raw(),
            3,
            image::ExtendedColorType::Rgb8,
        )
    };
    let own = (
        usize::try_from(picture.width()).ok()?,
        usize::try_from(picture.height()).ok()?,
    );
    let (size, small) = part_resampled((pixels, own, channels), (part, size), (crop, alpha_mix))?;
    let mut file = Vec::new();
    image::ImageEncoder::write_image(
        image::codecs::png::PngEncoder::new(&mut file),
        &small,
        u32::try_from(size.0).ok()?,
        u32::try_from(size.1).ok()?,
        color,
    )
    .ok()?;
    Some(file.into())
}

/// The pixel size and the samples of `part` of a picture of `own` pixels with `channels`
/// interleaved samples each, resampled to the size of `wanted` as its resampler says, the colors
/// of RGBA samples mixed as `alpha_mix` says. The part is cut first and resampled as a picture
/// of its own, unless `crop` resamples a part at its scale
/// ([`PictureCrop::VisiblePartAtScale`]) and the part takes the mean of the area: then it comes
/// from the whole picture ([`resample::resample_part_at_scale`]). With no part, the whole
/// picture; with no size, or the part's own, the part as it is. `None` when the part does not
/// lie inside the picture.
fn part_resampled(
    (pixels, own, channels): (Vec<u8>, (usize, usize), usize),
    (part, wanted): (Option<Part>, Option<Resampled>),
    (crop, alpha_mix): (PictureCrop, AlphaMix),
) -> Option<((usize, usize), Vec<u8>)> {
    let Some(part) = part else {
        return Some(resampled_mix((pixels, own, channels), wanted, alpha_mix));
    };
    let [left, top, right, bottom] = part;
    let shown = (right.saturating_sub(left), bottom.saturating_sub(top));
    if let Some((size, Resampler::Filter(limit))) = wanted
        && crop == PictureCrop::VisiblePartAtScale
        && size != shown
        && !limit.takes_linear(shown)
    {
        (right <= own.0 && bottom <= own.1 && left < right && top < bottom).then_some(())?;
        let at_scale =
            |samples: &[u8]| resample::resample_part_at_scale(samples, own, channels, part, size);
        return Some((size, mixed(pixels, channels, alpha_mix, at_scale)));
    }
    let pixels = cut(&pixels, own, channels, part)?;
    Some(resampled_mix((pixels, shown, channels), wanted, alpha_mix))
}

/// The pixel size and the `pixels` of a picture of `own` pixels with `channels` interleaved
/// samples each, resampled to the size of `wanted` as its resampler says, the colors of RGBA
/// samples mixed as `alpha_mix` says; with no size, or its own, the picture as it is.
fn resampled_mix(
    (pixels, own, channels): (Vec<u8>, (usize, usize), usize),
    wanted: Option<Resampled>,
    alpha_mix: AlphaMix,
) -> ((usize, usize), Vec<u8>) {
    let Some((size, resampler)) = wanted.filter(|(size, _)| *size != own) else {
        return (own, pixels);
    };
    let by_filter = |samples: &[u8]| resample::resample_by(resampler, samples, own, channels, size);
    (size, mixed(pixels, channels, alpha_mix, by_filter))
}

/// The samples that `resample` makes of `pixels` of `channels` interleaved samples each: of
/// RGBA samples whose colors `alpha_mix` weights, from the premultiplied samples, each new color
/// divided by its new alpha; else from the samples as they are.
fn mixed(
    pixels: Vec<u8>,
    channels: usize,
    alpha_mix: AlphaMix,
    resample: impl Fn(&[u8]) -> Vec<u8>,
) -> Vec<u8> {
    if channels == 4 && alpha_mix == AlphaMix::Weighted {
        divided_by_alpha(resample(&premultiplied(pixels)))
    } else {
        resample(&pixels)
    }
}

/// RGBA samples with each color multiplied by its alpha over 255, rounded to the nearest
/// level, a half to even ([`AlphaMix::Weighted`]).
fn premultiplied(mut samples: Vec<u8>) -> Vec<u8> {
    for [red, green, blue, alpha] in samples.as_chunks_mut::<4>().0 {
        let alpha = u32::from(*alpha);
        for color in [red, green, blue] {
            *color = weighted_level(u32::from(*color) * alpha);
        }
    }
    samples
}

/// `product` over 255, rounded to the nearest whole level, a half to even.
fn weighted_level(product: u32) -> u8 {
    let (whole, rest) = (product / 255, product % 255);
    // A rest of 127.5 cannot occur, as 255 is odd, so the nearest level is plain.
    let level = if rest * 2 > 255 { whole + 1 } else { whole };
    u8::try_from(level).unwrap_or(u8::MAX)
}

/// Premultiplied RGBA samples with each color divided by its alpha again, as a reader of a
/// soft mask marked with a black matte does: the color times 255 over the alpha, rounded to the
/// nearest level and at most 255, and 0 where the alpha is 0.
fn divided_by_alpha(mut samples: Vec<u8>) -> Vec<u8> {
    for [red, green, blue, alpha] in samples.as_chunks_mut::<4>().0 {
        let alpha = u32::from(*alpha);
        for color in [red, green, blue] {
            *color = if alpha == 0 {
                0
            } else {
                let value = (u32::from(*color) * 255 * 2 + alpha) / (alpha * 2);
                u8::try_from(value.min(255)).unwrap_or(u8::MAX)
            };
        }
    }
    samples
}

#[cfg(test)]
mod tests;