ferri-pdf 0.1.9

HTML and CSS to PDF renderer for print, in pure Rust
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
//! CSS Images 4 gradients: computed values and their resolution into PDF shading
//! geometry with stops normalised to the shading's own `0..=1` domain.
use crate::paint::{
    AbsoluteColor, Color, Interpolation, LengthPercentage, Point, background::Position, quantize,
};
use serde::Serialize;

/// Largest deviation of the PDF's linear interpolation between samples from the CSS colour,
/// in sRGB and alpha units: half of the 8-bit output step.
const SAMPLE_TOLERANCE: f64 = 0.5 / 255.0;
/// Halvings of a stop pair while samples still deviate; gamut mapping makes the line's
/// colour bend sharply where it meets the sRGB boundary.
const MAX_SAMPLE_DEPTH: u32 = 12;
/// Progress fractions within a candidate span compared against linear interpolation.
const SAMPLE_PROBES: [f32; 3] = [0.25, 0.5, 0.75];
/// Repeated stops beyond this count render as the average colour (CSS Images 3 §3.4.3).
const MAX_REPEATED_STOPS: usize = 4096;
/// Substitute extent for a zero radius (CSS Images 3 §3.2.2 degenerate shapes).
const DEGENERATE_SMALL_PT: f32 = 1.0e-3;
/// Substitute extent for the other radius of a zero-width or zero-height ellipse.
const DEGENERATE_LARGE_PT: f32 = 1.0e6;
/// Minimum shading range so that coincident stops keep distinct inner and outer colours.
const MIN_RANGE_PT: f32 = 1.0e-4;
const FULL_TURN_DEG: f32 = 360.0;
const STRAIGHT_DEG: f32 = 180.0;
const HALF_WEIGHT: f32 = 0.5;

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Gradient {
    pub shape: GradientShape,
    pub items: Vec<GradientItem>,
    pub repeating: bool,
    pub interpolation: Interpolation,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum GradientShape {
    Linear(LineDirection),
    Radial {
        ending: RadialEnding,
        center: Position,
    },
    /// Stop positions are fractions of a full turn clockwise from `from` degrees.
    Conic {
        from: f32,
        center: Position,
    },
}
/// Clockwise angle from "to top" in degrees, or a corner whose angle depends on the box.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub enum LineDirection {
    Angle(f32),
    Corner { right: bool, bottom: bool },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum RadialExtent {
    ClosestSide,
    FarthestSide,
    ClosestCorner,
    FarthestCorner,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum RadialEnding {
    Circle(CircleSize),
    Ellipse(EllipseSize),
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub enum CircleSize {
    Extent(RadialExtent),
    Radius(f32),
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum EllipseSize {
    Extent(RadialExtent),
    Radii([LengthPercentage; 2]),
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum GradientItem {
    Stop {
        color: AbsoluteColor,
        position: Option<LengthPercentage>,
    },
    Hint(LengthPercentage),
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GradientStop {
    pub offset: f32,
    pub color: Color,
}
/// Shading geometry in tile coordinates with positive y down.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Shading {
    Axial {
        start: Point,
        end: Point,
    },
    /// Concentric circles scaled vertically by `scale_y` about the centre.
    Radial {
        center: Point,
        radii: [f32; 2],
        scale_y: f32,
    },
    /// Rays about `center`; offset 0 points `angle` degrees clockwise from up and offsets
    /// increase clockwise over one turn.
    Conic {
        center: Point,
        angle: f32,
    },
}
/// Shading whose stops are sorted, padded beyond `0..=1`, and linear in non-premultiplied
/// colour between neighbours.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedGradient {
    pub shading: Shading,
    pub stops: Vec<GradientStop>,
}

#[derive(Clone, Copy, Debug)]
struct Placed {
    position: f32,
    color: Color,
}

impl Gradient {
    /// Resolves the gradient for an image of `size`; `None` when it has no area.
    pub fn resolve(&self, size: [f32; 2]) -> Option<ResolvedGradient> {
        let [width, height] = size;
        if width <= 0.0 || height <= 0.0 {
            return None;
        }
        let (ray, axis) = match &self.shape {
            GradientShape::Linear(direction) => {
                let angle = direction.angle(size).to_radians();
                let direction = [angle.sin(), -angle.cos()];
                let length = (width * direction[0]).abs() + (height * direction[1]).abs();
                let start = [
                    width / 2.0 - direction[0] * length / 2.0,
                    height / 2.0 - direction[1] * length / 2.0,
                ];
                (length, Axis::Line { start, direction })
            }
            GradientShape::Radial { ending, center } => {
                let center = [center[0].resolve(width), center[1].resolve(height)];
                let [rx, ry] = degenerate(ending.radii(center, size));
                (
                    rx,
                    Axis::Ray {
                        center,
                        radii: [rx, ry],
                    },
                )
            }
            GradientShape::Conic { from, center } => (
                1.0,
                Axis::Turn {
                    center: [center[0].resolve(width), center[1].resolve(height)],
                    angle: *from,
                },
            ),
        };
        // CSS Images 4 §3: one stop fills the image, regardless of its position.
        if let [GradientItem::Stop { color, .. }] = self.items.as_slice() {
            return Some(axis.solid(color.used()));
        }
        let placed = dense(&fixup(&self.items, ray), self.interpolation);
        let (low, high) = match axis {
            Axis::Line { .. } | Axis::Turn { .. } => (0.0, ray),
            Axis::Ray { center, radii } if self.repeating => (0.0, farthest(center, radii, size)),
            Axis::Ray { .. } => {
                let first = placed[0].position.max(0.0);
                let last = placed[placed.len() - 1].position;
                if last <= 0.0 {
                    return Some(axis.solid(placed[placed.len() - 1].color));
                }
                (first, last)
            }
        };
        let high = high.max(low + MIN_RANGE_PT);
        let placed = if self.repeating {
            match repeat(&placed, low, high) {
                Some(repeated) => repeated,
                None => return Some(axis.solid(average(&placed))),
            }
        } else {
            placed
        };
        let stops = clamp(&placed, low, high)
            .into_iter()
            .map(|stop| GradientStop {
                offset: (stop.position - low) / (high - low),
                color: stop.color,
            })
            .collect();
        Some(ResolvedGradient {
            shading: axis.shading(low, high),
            stops,
        })
    }
}

impl ResolvedGradient {
    /// The opacity the gradient paints at `point` of its tile, with the padding the PDF
    /// shading extends beyond its first and last stops.
    pub(crate) fn alpha_at(&self, [x, y]: Point) -> f32 {
        let offset = match self.shading {
            Shading::Axial { start, end } => {
                let axis = [end[0] - start[0], end[1] - start[1]];
                ((x - start[0]) * axis[0] + (y - start[1]) * axis[1])
                    / (axis[0] * axis[0] + axis[1] * axis[1])
            }
            Shading::Radial {
                center,
                radii,
                scale_y,
            } => {
                let distance = (x - center[0]).hypot((y - center[1]) / scale_y);
                (distance - radii[0]) / (radii[1] - radii[0])
            }
            Shading::Conic { center, angle } => {
                let clockwise_from_up = (x - center[0]).atan2(center[1] - y).to_degrees();
                (clockwise_from_up - angle).rem_euclid(FULL_TURN_DEG) / FULL_TURN_DEG
            }
        }
        .clamp(0.0, 1.0);
        let next = self.stops.partition_point(|stop| stop.offset <= offset);
        match (
            next.checked_sub(1).map(|index| self.stops[index]),
            self.stops.get(next).copied(),
        ) {
            (Some(before), Some(after)) => {
                let progress = (offset - before.offset) / (after.offset - before.offset);
                before.color.alpha + (after.color.alpha - before.color.alpha) * progress
            }
            (Some(stop), None) | (None, Some(stop)) => stop.color.alpha,
            (None, None) => 0.0,
        }
    }
}

impl LineDirection {
    /// Clockwise degrees from "to top"; corners point perpendicular to the other diagonal.
    pub fn angle(self, [width, height]: [f32; 2]) -> f32 {
        match self {
            Self::Angle(degrees) => degrees.rem_euclid(FULL_TURN_DEG),
            Self::Corner { right, bottom } => {
                let toward_top = height.atan2(width).to_degrees();
                match (right, bottom) {
                    (true, false) => toward_top,
                    (true, true) => STRAIGHT_DEG - toward_top,
                    (false, true) => STRAIGHT_DEG + toward_top,
                    (false, false) => FULL_TURN_DEG - toward_top,
                }
            }
        }
    }
}

impl RadialExtent {
    /// Distances from `center` to the selected sides, as `[horizontal, vertical]`.
    fn sides(self, center: Point, [width, height]: [f32; 2]) -> [f32; 2] {
        let horizontal = [center[0].abs(), (width - center[0]).abs()];
        let vertical = [center[1].abs(), (height - center[1]).abs()];
        match self {
            Self::ClosestSide | Self::ClosestCorner => [
                horizontal[0].min(horizontal[1]),
                vertical[0].min(vertical[1]),
            ],
            Self::FarthestSide | Self::FarthestCorner => [
                horizontal[0].max(horizontal[1]),
                vertical[0].max(vertical[1]),
            ],
        }
    }
    pub(crate) fn circle(self, center: Point, size: [f32; 2]) -> f32 {
        let [x, y] = self.sides(center, size);
        match self {
            Self::ClosestSide => x.min(y),
            Self::FarthestSide => x.max(y),
            Self::ClosestCorner | Self::FarthestCorner => x.hypot(y),
        }
    }
    /// Corner extents keep the side extents' aspect ratio and pass through the corner.
    pub(crate) fn ellipse(self, center: Point, size: [f32; 2]) -> [f32; 2] {
        let [x, y] = self.sides(center, size);
        match self {
            Self::ClosestSide | Self::FarthestSide => [x, y],
            Self::ClosestCorner | Self::FarthestCorner if x == 0.0 || y == 0.0 => [x, y],
            Self::ClosestCorner | Self::FarthestCorner => {
                [x * std::f32::consts::SQRT_2, y * std::f32::consts::SQRT_2]
            }
        }
    }
}

impl RadialEnding {
    fn radii(&self, center: Point, size: [f32; 2]) -> [f32; 2] {
        match self {
            Self::Circle(CircleSize::Extent(extent)) => [extent.circle(center, size); 2],
            Self::Circle(CircleSize::Radius(radius)) => [*radius; 2],
            Self::Ellipse(EllipseSize::Extent(extent)) => extent.ellipse(center, size),
            Self::Ellipse(EllipseSize::Radii([x, y])) => [x.resolve(size[0]), y.resolve(size[1])],
        }
    }
}

/// Zero radii become thin lines or tiny circles (CSS Images 3 §3.2.2).
fn degenerate([rx, ry]: [f32; 2]) -> [f32; 2] {
    match (rx > 0.0, ry > 0.0) {
        (true, true) => [rx, ry],
        (false, false) => [DEGENERATE_SMALL_PT; 2],
        (false, true) => [DEGENERATE_SMALL_PT, DEGENERATE_LARGE_PT],
        (true, false) => [DEGENERATE_LARGE_PT, DEGENERATE_SMALL_PT],
    }
}

#[derive(Clone, Copy)]
enum Axis {
    Line { start: Point, direction: Point },
    Ray { center: Point, radii: [f32; 2] },
    Turn { center: Point, angle: f32 },
}
impl Axis {
    fn shading(self, low: f32, high: f32) -> Shading {
        match self {
            Self::Line { start, direction } => Shading::Axial {
                start: [start[0] + direction[0] * low, start[1] + direction[1] * low],
                end: [
                    start[0] + direction[0] * high,
                    start[1] + direction[1] * high,
                ],
            },
            Self::Ray { center, radii } => Shading::Radial {
                center,
                radii: [low, high],
                scale_y: radii[1] / radii[0],
            },
            Self::Turn { center, angle } => Shading::Conic { center, angle },
        }
    }
    fn solid(self, color: Color) -> ResolvedGradient {
        ResolvedGradient {
            shading: self.shading(0.0, MIN_RANGE_PT),
            stops: vec![GradientStop { offset: 0.0, color }],
        }
    }
}

/// Largest ray distance from the centre to a tile corner, in horizontal-radius units.
fn farthest(center: Point, [rx, ry]: [f32; 2], [width, height]: [f32; 2]) -> f32 {
    [[0.0, 0.0], [width, 0.0], [width, height], [0.0, height]]
        .iter()
        .map(|corner| (corner[0] - center[0]).hypot((corner[1] - center[1]) * rx / ry))
        .fold(0.0, f32::max)
}

enum Fixed {
    Stop(f32, AbsoluteColor),
    Hint(f32),
}

/// CSS Images 3 §3.4.3 colour stop fixup; positions are in points along the ray.
fn fixup(items: &[GradientItem], ray: f32) -> Vec<Fixed> {
    let stops = items
        .iter()
        .filter(|item| matches!(item, GradientItem::Stop { .. }))
        .count();
    let mut positions: Vec<Option<f32>> = items
        .iter()
        .map(|item| match item {
            GradientItem::Stop { position, .. } => position.as_ref().map(|p| p.resolve(ray)),
            GradientItem::Hint(position) => Some(position.resolve(ray)),
        })
        .collect();
    let mut stop_index = 0;
    for (item, position) in items.iter().zip(&mut positions) {
        if let GradientItem::Stop { .. } = item {
            if stop_index == 0 && position.is_none() {
                *position = Some(0.0);
            }
            if stop_index == stops - 1 && position.is_none() {
                *position = Some(ray);
            }
            stop_index += 1;
        }
    }
    let mut largest = f32::NEG_INFINITY;
    for position in positions.iter_mut().flatten() {
        *position = position.max(largest);
        largest = *position;
    }
    // Runs of positionless stops are spaced between the neighbouring positioned stops.
    let stop_indices: Vec<usize> = (0..items.len())
        .filter(|&index| matches!(items[index], GradientItem::Stop { .. }))
        .collect();
    let mut run = 0;
    while run < stop_indices.len() {
        if positions[stop_indices[run]].is_some() {
            run += 1;
            continue;
        }
        let before = positions[stop_indices[run - 1]].expect("the first stop has a position");
        let end = (run..stop_indices.len())
            .find(|&candidate| positions[stop_indices[candidate]].is_some())
            .expect("the last stop has a position");
        let after = positions[stop_indices[end]].expect("found a positioned stop");
        let gaps = (end - run + 1) as f32;
        for step in run..end {
            positions[stop_indices[step]] =
                Some(before + (after - before) * (step - run + 1) as f32 / gaps);
        }
        run = end;
    }
    items
        .iter()
        .zip(positions)
        .map(|(item, position)| {
            let position = position.expect("fixup positions every item");
            match item {
                GradientItem::Stop { color, .. } => Fixed::Stop(position, *color),
                GradientItem::Hint(_) => Fixed::Hint(position),
            }
        })
        .collect()
}

/// Interpolation weight at `t` for a hint at fraction `hint` of the segment.
fn hinted(t: f32, hint: f32) -> f32 {
    if hint <= 0.0 {
        1.0
    } else if hint >= 1.0 {
        0.0
    } else {
        t.powf(HALF_WEIGHT.ln() / hint.ln())
    }
}

/// Non-premultiplied gamut-mapped sRGB and alpha.
type Sample = [f64; 4];

fn sample(color: &AbsoluteColor) -> Sample {
    let [red, green, blue] = color.mapped_srgb();
    [red, green, blue, f64::from(color.used_alpha())]
}
fn used([red, green, blue, alpha]: Sample) -> Color {
    Color {
        rgb: quantize([red, green, blue]),
        alpha: alpha as f32,
    }
}

/// Appends the interior samples between `start` and `end` at which linear interpolation of
/// neighbours stays within `SAMPLE_TOLERANCE` of `color(t)`.
fn subdivide(
    color: &impl Fn(f32) -> Sample,
    start: (f32, Sample),
    end: (f32, Sample),
    depth: u32,
    output: &mut Vec<(f32, Sample)>,
) {
    if depth == MAX_SAMPLE_DEPTH {
        return;
    }
    let deviates = SAMPLE_PROBES.iter().any(|&fraction| {
        let actual = color(start.0 + (end.0 - start.0) * fraction);
        (0..actual.len()).any(|channel| {
            let linear =
                start.1[channel] + (end.1[channel] - start.1[channel]) * f64::from(fraction);
            (actual[channel] - linear).abs() > SAMPLE_TOLERANCE
        })
    });
    if !deviates {
        return;
    }
    let middle_t = f32::midpoint(start.0, end.0);
    let middle = (middle_t, color(middle_t));
    subdivide(color, start, middle, depth + 1, output);
    output.push(middle);
    subdivide(color, middle, end, depth + 1, output);
}

/// Stops between which non-premultiplied linear sRGB interpolation reproduces the gradient
/// line coloured in `interpolation` (CSS Images 4 §3.5.2).
fn dense(fixed: &[Fixed], interpolation: Interpolation) -> Vec<Placed> {
    fn push(stop: Placed, output: &mut Vec<Placed>) {
        if output
            .last()
            .is_none_or(|last| last.position != stop.position || last.color != stop.color)
        {
            output.push(stop);
        }
    }
    let mut output: Vec<Placed> = Vec::new();
    let mut previous: Option<(f32, AbsoluteColor)> = None;
    let mut hint = None;
    for item in fixed {
        let (position, color) = match item {
            Fixed::Hint(position) => {
                hint = Some(*position);
                continue;
            }
            Fixed::Stop(position, color) => (*position, *color),
        };
        let Some((start, from)) = previous.replace((position, color)) else {
            push(
                Placed {
                    position,
                    color: color.used(),
                },
                &mut output,
            );
            continue;
        };
        let hint = hint.take();
        let length = position - start;
        let fraction = hint.map(|hint| {
            if length > 0.0 {
                (hint - start) / length
            } else {
                HALF_WEIGHT
            }
        });
        let at = |t: f32| {
            let weight = fraction.map_or(t, |fraction| hinted(t, fraction));
            sample(&interpolation.interpolate(&from, &color, weight))
        };
        // Premultiplied interpolation leaves a transparent end's colour unused: towards it the
        // line keeps the other end's colour and only its alpha changes.
        let mut first = sample(&from);
        let mut last = sample(&color);
        if first[3] == 0.0 {
            first[..3].copy_from_slice(&last[..3]);
        }
        if last[3] == 0.0 {
            last[..3].copy_from_slice(&first[..3]);
        }
        push(
            Placed {
                position: start,
                color: used(first),
            },
            &mut output,
        );
        if length > 0.0 {
            let mut interior = Vec::new();
            subdivide(&at, (0.0, first), (1.0, last), 0, &mut interior);
            for (t, sample) in interior {
                push(
                    Placed {
                        position: start + length * t,
                        color: used(sample),
                    },
                    &mut output,
                );
            }
        }
        push(
            Placed {
                position,
                color: used(last),
            },
            &mut output,
        );
    }
    output
}

/// Colour at `position`; `after` selects the right-hand limit at a hard stop.
fn color_at(stops: &[Placed], position: f32, after: bool) -> Color {
    let index = if after {
        stops.partition_point(|stop| stop.position <= position)
    } else {
        stops.partition_point(|stop| stop.position < position)
    };
    if index == 0 {
        return stops[0].color;
    }
    if index == stops.len() {
        return stops[index - 1].color;
    }
    let (a, b) = (stops[index - 1], stops[index]);
    if after && a.position == position {
        return a.color;
    }
    if !after && b.position == position {
        return b.color;
    }
    let t = (position - a.position) / (b.position - a.position);
    let channel = |index: usize| {
        let value = f32::from(a.color.rgb[index])
            + (f32::from(b.color.rgb[index]) - f32::from(a.color.rgb[index])) * t;
        value.round() as u8
    };
    Color {
        rgb: [channel(0), channel(1), channel(2)],
        alpha: a.color.alpha + (b.color.alpha - a.color.alpha) * t,
    }
}

/// Stops within `low..=high`, with the outer limits kept at the boundaries for padding.
fn clamp(stops: &[Placed], low: f32, high: f32) -> Vec<Placed> {
    let mut output = vec![Placed {
        position: low,
        color: color_at(stops, low, false),
    }];
    output.extend(
        stops
            .iter()
            .filter(|stop| stop.position >= low && stop.position <= high),
    );
    output.push(Placed {
        position: high,
        color: color_at(stops, high, true),
    });
    output.dedup_by(|b, a| a.position == b.position && a.color == b.color);
    output
}

/// Copies of the stop period covering `low..high`; `None` when it would exceed the limit.
fn repeat(stops: &[Placed], low: f32, high: f32) -> Option<Vec<Placed>> {
    let first = stops[0].position;
    let period = stops[stops.len() - 1].position - first;
    if period <= 0.0 {
        return None;
    }
    let start = ((low - first) / period).floor();
    let copies = ((high - first) / period).ceil() - start;
    if !copies.is_finite() || copies * stops.len() as f32 > MAX_REPEATED_STOPS as f32 {
        return None;
    }
    let mut output = Vec::with_capacity(copies as usize * stops.len());
    for copy in 0..copies as usize {
        let shift = (start + copy as f32) * period;
        output.extend(stops.iter().map(|stop| Placed {
            position: stop.position + shift,
            color: stop.color,
        }));
    }
    Some(output)
}

/// Mean premultiplied colour of one period, with coincident stops spread over unit length.
fn average(stops: &[Placed]) -> Color {
    let first = stops[0].position;
    let last = stops[stops.len() - 1].position;
    let spread: Vec<Placed> = if last > first {
        stops.to_vec()
    } else {
        let mut spread = stops.to_vec();
        let end = spread.len() - 1;
        spread[end].position = first + 1.0;
        spread
    };
    let mut sums = [0.0f32; 4];
    for pair in spread.windows(2) {
        let length = pair[1].position - pair[0].position;
        for (index, sum) in sums.iter_mut().take(3).enumerate() {
            *sum += length
                * (f32::from(pair[0].color.rgb[index]) * pair[0].color.alpha
                    + f32::from(pair[1].color.rgb[index]) * pair[1].color.alpha)
                / 2.0;
        }
        sums[3] += length * (pair[0].color.alpha + pair[1].color.alpha) / 2.0;
    }
    let total = spread[spread.len() - 1].position - spread[0].position;
    let alpha = sums[3] / total;
    if alpha <= 0.0 {
        return Color::TRANSPARENT;
    }
    Color {
        rgb: std::array::from_fn(|index| {
            (sums[index] / total / alpha)
                .round()
                .clamp(0.0, f32::from(u8::MAX)) as u8
        }),
        alpha,
    }
}