f-office 0.2.4

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
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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! 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, Mutex};

use f_office_paint::{
    AlphaMix, DEFAULT_IMAGE_BYTES_CACHE, DisplayList, GroupPlaces, ImageData, ImageFormat, ImageId,
    ImageItem, ImageLoader, ImageRef, Item, JpegQuality, JpegSample, JpegShare, LruBytesCache,
    MAX_DECODED_BYTES, MAX_DECODED_BYTES_TO_WRITE_AGAIN, PaletteClass, PictureCrop, Resampler,
    next_store_id,
};
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_header_complete, 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, whether a JPEG frame header is supported by `f_office_jpeg`,
/// the class of the palette of a PNG file ([`png_palette_class`]), and whether a PNG file has an
/// RGB color type (2 or 6).
#[derive(Clone, Copy)]
struct Header {
    pixels: Option<(usize, usize)>,
    jpeg_rewritable: bool,
    palette: Option<PaletteClass>,
    png_rgb: bool,
}

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),
                jpeg_rewritable: jpeg_frame_rewritable(data),
                palette: None,
                png_rgb: false,
            },
            ImageFormat::Png => Self {
                pixels: png_header(data).map(|header| header.pixels),
                jpeg_rewritable: false,
                palette: png_palette_class(data),
                png_rgb: png_color_type(data).is_some_and(|kind| RGB_TYPES.contains(&kind)),
            },
            _ => Self {
                pixels: None,
                jpeg_rewritable: false,
                palette: None,
                png_rgb: false,
            },
        }
    }

    /// Reads the header of a lazy [`ImageRef`] from a bounded leading prefix, falling back to full
    /// bytes when a JPEG frame header or PNG pre-`IDAT` metadata lies past the prefix.
    fn of_lazy(handle: &ImageRef, format: ImageFormat) -> Self {
        const PREFIX: usize = 64 * 1024;
        if let Some(prefix) = handle.load_prefix(PREFIX) {
            let header = Self::of(&prefix, format);
            let complete = match format {
                ImageFormat::Jpeg => header.pixels.is_some(),
                ImageFormat::Png => png_header_complete(&prefix) || prefix.len() < PREFIX,
                _ => true,
            };
            if complete {
                return header;
            }
        }
        handle.load().map_or(
            Self {
                pixels: None,
                jpeg_rewritable: false,
                palette: None,
                png_rgb: false,
            },
            |full| Self::of(&full, format),
        )
    }
}

/// Reads a big-endian `u16` at `offset` in `data`.
fn be16(data: &[u8], offset: usize) -> Option<usize> {
    let bytes: [u8; 2] = data.get(offset..offset.checked_add(2)?)?.try_into().ok()?;
    Some(usize::from(u16::from_be_bytes(bytes)))
}

/// Checks from a JPEG's frame header alone whether `f_office_jpeg::decode` can decode it within
/// [`MAX_DECODED_BYTES`] (sequential/progressive 8-bit Huffman, 1 or 3 components, valid table
/// indices, supported subsampling, and block buffer within limit).
fn jpeg_frame_rewritable(data: &[u8]) -> bool {
    let Some((marker, body)) = jpeg_sof_segment(data) else {
        return false;
    };
    if !matches!(marker, 0xC0..=0xC2) || body.first() != Some(&8) {
        return false;
    }
    let (Some(height), Some(width), Some(&count)) = (be16(body, 1), be16(body, 3), body.get(5))
    else {
        return false;
    };
    let count = usize::from(count);
    if width == 0 || height == 0 || !matches!(count, 1 | 3) {
        return false;
    }
    let Some(fields) = body.get(6..6 + 3 * count) else {
        return false;
    };
    jpeg_sampling_within_limit(fields, (width, height), count)
}

/// Validates component sampling factors and block-buffer size against [`MAX_DECODED_BYTES`].
fn jpeg_sampling_within_limit(
    fields: &[u8],
    (width, height): (usize, usize),
    count: usize,
) -> bool {
    let mut parts = [(0_usize, 0_usize); 3];
    let (mut h_max, mut v_max) = (0_usize, 0_usize);
    for (idx, &[_, sampling, table]) in fields.as_chunks::<3>().0.iter().enumerate() {
        let (h, v) = (usize::from(sampling >> 4), usize::from(sampling & 15));
        if h == 0 || v == 0 || table > 3 {
            return false;
        }
        h_max = h_max.max(h);
        v_max = v_max.max(v);
        if let Some(slot) = parts.get_mut(idx) {
            *slot = (h, v);
        }
    }
    let Some(active) = parts.get(..count) else {
        return false;
    };
    if active.iter().any(|&(h, v)| {
        !h_max.is_multiple_of(h)
            || !v_max.is_multiple_of(v)
            || !matches!((h_max / h, v_max / v), (1 | 2, 1) | (2, 2))
    }) {
        return false;
    }
    let mcus = (width.div_ceil(8 * h_max), height.div_ceil(8 * v_max));
    let Some(blocks) = active.iter().try_fold(0_usize, |sum, &(h, v)| {
        sum.checked_add(mcus.0.checked_mul(h)?.checked_mul(mcus.1.checked_mul(v)?)?)
    }) else {
        return false;
    };
    blocks
        .checked_mul(size_of::<[i32; 64]>())
        .and_then(|bytes| u64::try_from(bytes).ok())
        .is_some_and(|bytes| bytes <= MAX_DECODED_BYTES)
}

/// Advances past JPEG fill bytes (`0xFF`) and returns `(marker, after_marker)`.
fn next_jpeg_marker(data: &[u8], mut at: usize) -> Option<(u8, usize)> {
    while data.get(at) == Some(&0xFF) {
        at += 1;
    }
    Some((*data.get(at)?, at + 1))
}

/// Returns the first SOF marker byte and its segment body (after the 2-byte length) in `data`.
fn jpeg_sof_segment(data: &[u8]) -> Option<(u8, &[u8])> {
    (data.get(..2) == Some(&[0xFF, 0xD8])).then_some(())?;
    let mut at = 2_usize;
    while let Some((marker, next)) = next_jpeg_marker(data, at) {
        at = match marker {
            0xD9 | 0xDA => return None,
            0x01 | 0xD0..=0xD8 => next,
            _ => {
                let length = be16(data, next)?;
                let end = next.checked_add(length)?;
                let body = data.get(next.checked_add(2)?..end)?;
                if matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) {
                    return Some((marker, body));
                }
                end
            }
        };
    }
    None
}

/// Deferred rewrite rule for one lazy [`ImageRef`].
#[derive(Clone, Copy, Debug)]
enum LazyRewriteKind {
    Jpeg {
        quality: JpegQuality,
    },
    PngOrJpeg {
        quality: JpegQuality,
        share: JpegShare,
        jpeg_sample: Option<JpegSample>,
    },
    Png,
}

/// Specification stored per deduplicated lazy image rewrite (no decoded/re-encoded bytes pinned).
#[derive(Clone, Debug)]
struct LazyRewriteSpec {
    source: ImageRef,
    format: ImageFormat,
    part: Option<Part>,
    size: Option<Resampled>,
    kind: LazyRewriteKind,
    crop: PictureCrop,
    alpha_mix: AlphaMix,
}

/// Deduplication key for lazy image rewrites.
type LazyKey = (ImageId, Option<Part>, Option<Resampled>);

/// Lazily performs target picture rewriting (`jpeg_again`, `png_or_jpeg`, `png_again`) on demand
/// when a page or tile is rasterized or emitted to PDF, behind a bounded 16 MiB LRU cache.
#[derive(Debug)]
struct LazyRewritingLoader {
    store_id: u64,
    specs: Mutex<LazySpecTable>,
    cache: LruBytesCache,
}

#[derive(Debug, Default)]
struct LazySpecTable {
    list: Vec<LazyRewriteSpec>,
    by_key: HashMap<LazyKey, u32>,
}

impl LazyRewritingLoader {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            store_id: next_store_id(),
            specs: Mutex::new(LazySpecTable::default()),
            cache: LruBytesCache::new(DEFAULT_IMAGE_BYTES_CACHE),
        })
    }

    fn intern(self: &Arc<Self>, key: LazyKey, spec: LazyRewriteSpec) -> ImageRef {
        let byte_len = spec.source.byte_len();
        let index = {
            let Ok(mut table) = self.specs.lock() else {
                return spec.source;
            };
            if let Some(&existing) = table.by_key.get(&key) {
                existing
            } else {
                let next = u32::try_from(table.list.len()).unwrap_or(u32::MAX);
                table.list.push(spec);
                table.by_key.insert(key, next);
                next
            }
        };
        ImageRef::new(
            ImageId::new(self.store_id, index),
            byte_len,
            Arc::clone(self) as Arc<dyn ImageLoader>,
        )
    }

    fn spec(&self, index: u32) -> Option<LazyRewriteSpec> {
        let table = self.specs.lock().ok()?;
        let idx = usize::try_from(index).ok()?;
        table.list.get(idx).cloned()
    }
}

impl ImageLoader for LazyRewritingLoader {
    fn load(&self, index: u32) -> Option<Arc<[u8]>> {
        self.load_with_format(index, ImageFormat::Unknown)
            .map(|(bytes, _)| bytes)
    }

    fn load_with_format(
        &self,
        index: u32,
        fallback: ImageFormat,
    ) -> Option<(Arc<[u8]>, ImageFormat)> {
        if let Some(cached) = self.cache.get(index) {
            return Some(cached);
        }
        let spec = self.spec(index)?;
        let raw = spec.source.load()?;
        let dummy_resampling =
            |_pixels: (usize, usize), _palette: Option<PaletteClass>, _item: &ImageItem| None;
        let rewritten = match spec.kind {
            LazyRewriteKind::Jpeg { quality } => {
                jpeg_again(&raw, (spec.part, spec.size), quality, spec.crop)
                    .map(|bytes| (bytes, ImageFormat::Jpeg))
            }
            LazyRewriteKind::PngOrJpeg {
                quality,
                share,
                jpeg_sample,
            } => {
                let rewriting = Rewriting {
                    quality: Some(quality),
                    jpeg_share: Some(share),
                    jpeg_sample,
                    crop: spec.crop,
                    alpha_mix: spec.alpha_mix,
                    resampling: &dummy_resampling,
                };
                png_or_jpeg(&raw, (spec.part, spec.size), (quality, share), rewriting)
            }
            LazyRewriteKind::Png => {
                png_again(&raw, (spec.part, spec.size), spec.alpha_mix, spec.crop)
                    .map(|bytes| (bytes, ImageFormat::Png))
            }
        };
        let (bytes, format) = rewritten.unwrap_or((
            raw,
            if spec.format == ImageFormat::Unknown {
                fallback
            } else {
                spec.format
            },
        ));
        self.cache.insert(index, Arc::clone(&bytes), format);
        Some((bytes, format))
    }
}

#[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 lazy_headers: HashMap<(ImageId, ImageFormat), Header> = HashMap::new();
    let mut written: HashMap<Key, Option<Written>> = HashMap::new();
    let lazy_loader = LazyRewritingLoader::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) {
                match &image.image.data {
                    ImageData::Lazy(handle) => {
                        let handle = handle.clone();
                        rewrite_lazy_image(
                            image,
                            handle,
                            rewriting,
                            (&mut lazy_headers, &lazy_loader),
                            warnings,
                        );
                    }
                    ImageData::Inline(data) => {
                        let data = Arc::clone(data);
                        rewrite_inline_image(
                            image,
                            &data,
                            rewriting,
                            (&mut files, &mut written),
                            warnings,
                        );
                    }
                }
            }
            items
        }));
    }
    DisplayList::new(pages)
}

/// Computes target-rewritten crop (`part`), drawn geometry (`drawn`), and resampled size (`size`)
/// from an image's header alone.
fn rewrite_geometry(
    image: &ImageItem,
    header: Header,
    rewriting: Rewriting,
) -> (Option<Part>, ImageItem, Option<Resampled>) {
    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));
    (part, drawn, size)
}

/// Selects the lazy rewrite rule for `format` and `header`, or `None` when the image stays as is.
fn lazy_rewrite_kind(
    format: ImageFormat,
    header: Header,
    rewriting: Rewriting,
    part: Option<Part>,
    size: Option<Resampled>,
) -> Option<LazyRewriteKind> {
    match (format, rewriting.quality, rewriting.jpeg_share) {
        (ImageFormat::Jpeg, Some(quality), _) => Some(LazyRewriteKind::Jpeg { quality }),
        (ImageFormat::Png, Some(quality), Some(share)) if header.png_rgb => {
            Some(LazyRewriteKind::PngOrJpeg {
                quality,
                share,
                jpeg_sample: rewriting.jpeg_sample,
            })
        }
        (ImageFormat::Png, _, _) if part.is_some() || size.is_some() => Some(LazyRewriteKind::Png),
        _ => None,
    }
}

/// Returns `true` when PNG header dimensions alone exceed the decoded-RGBA byte limit for
/// rewriting.
fn exceeds_png_rewrite_limit(own: Option<(usize, usize)>) -> bool {
    let Some((width, height)) = own else {
        return false;
    };
    let rgba_bytes = (width as u64)
        .saturating_mul(height as u64)
        .saturating_mul(4);
    rgba_bytes > MAX_DECODED_BYTES_TO_WRITE_AGAIN
}

/// Attaches a deferred [`LazyRewritingLoader`] handle to a lazy [`ImageItem`] using only its
/// header, without decoding or re-encoding pixels during `Document::open`.
fn rewrite_lazy_image(
    image: &mut ImageItem,
    handle: ImageRef,
    rewriting: Rewriting,
    (lazy_headers, lazy_loader): (
        &mut HashMap<(ImageId, ImageFormat), Header>,
        &Arc<LazyRewritingLoader>,
    ),
    warnings: &mut Warnings,
) {
    let format = image.image.format;
    let header = *lazy_headers
        .entry((handle.id(), format))
        .or_insert_with(|| Header::of_lazy(&handle, format));
    let (part, drawn, size) = rewrite_geometry(image, header, rewriting);
    let Some(kind) = lazy_rewrite_kind(format, header, rewriting, part, size) else {
        return;
    };
    let cannot_rewrite = match format {
        ImageFormat::Jpeg => !header.jpeg_rewritable,
        ImageFormat::Png => exceeds_png_rewrite_limit(header.pixels),
        _ => false,
    };
    if cannot_rewrite {
        warnings.push(Warning::PictureNotWrittenAgain { format });
        return;
    }
    if part.is_some() {
        *image = drawn;
    }
    let new_handle = lazy_loader.intern(
        (handle.id(), part, size),
        LazyRewriteSpec {
            source: handle,
            format,
            part,
            size,
            kind,
            crop: rewriting.crop,
            alpha_mix: rewriting.alpha_mix,
        },
    );
    image.image.data = ImageData::Lazy(new_handle);
}

/// Eagerly rewrites an inline [`ImageItem`] (used for synthetic images and direct unit tests).
fn rewrite_inline_image(
    image: &mut ImageItem,
    data: &Arc<[u8]>,
    rewriting: Rewriting,
    (files, written): (&mut Files, &mut HashMap<Key, Option<Written>>),
    warnings: &mut Warnings,
) {
    let format = image.image.format;
    let file = files.number(data);
    let header = files.header(file, data, format);
    let (part, drawn, size) = rewrite_geometry(image, header, rewriting);
    let key = (file, part, size);
    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 header.png_rgb => 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))
            })
        }
        _ => return,
    };
    let Some((rewritten, out_format)) = again else {
        warnings.push(Warning::PictureNotWrittenAgain { format });
        return;
    };
    let (rewritten, out_format) = (Arc::clone(rewritten), *out_format);
    if part.is_some() {
        *image = drawn;
    }
    image.image.data = ImageData::Inline(rewritten);
    image.image.format = out_format;
}

/// 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;