alpha2-engine 0.4.4

Player and exporter facade for alpha2.
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
//! Text rendering: caption tracks' cues and text generators, rasterized by
//! the portable text host.
//!
//! The engine draws text itself, from font bytes its host registers once,
//! so a browser preview and a native export of one project, given the same
//! fonts, draw the same text pixels. A host keeps one [`TextTextures`]
//! beside its frame provider, calls [`TextTextures::prepare`] for each frame
//! before rendering it, and answers [`crate::FrameProvider::text`] from it.
//! A caption is composited as a layer between tracks; a text generator's
//! texture is placed on the transparent picture the generator draws. A
//! layout generator is resolved here too, with the same fonts, and its
//! texts rasterized beside the others ([`crate::layout`]).

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use alpha2_eval::{FrameDesc, GeneratorPlan, LayoutPlan, StepOp};
use alpha2_media::EmojiPolicy;
use alpha2_model::{Generator, Rgba, TextAlign, TextStyle};
use alpha2_render::{
    CpuImage, CpuRenderer, CpuSource, RenderCacheKey, RenderError, RenderSize, Renderer,
    SourceView, UploadTexture,
};
use alpha2_text::{ShapedText, TextFont, TextRasterError, TextRasterRequest, TextRasterizer};

use crate::layout::PreparedLayout;

/// The high 64 bits of a text's result cache key, before its font set is
/// mixed in: font sets are counted from 1 and stay far below this, so those
/// bits are never zero, as a host's source keys ([`RenderCacheKey::source`])
/// leave them, and the two never meet.
const TEXT_CACHE_DOMAIN: u64 = 0x6361_7074_696f_6e73;

/// The next font set's identity: each store, and each font a store adds,
/// takes one, so no two font sets that might draw text differently in one
/// process share a text cache key.
static NEXT_FONT_SET: AtomicU64 = AtomicU64::new(1);

/// How many rasterized texts a host keeps between frames; the current
/// frame's are kept however many it shows.
const RETAINED_TEXTS: usize = 16;

/// How many resolved layouts a host keeps between frames; the current
/// frame's are kept however many it shows.
const RETAINED_LAYOUTS: usize = 8;

/// How many shaped texts a host keeps for layout, least recently used
/// first out.
const RETAINED_SHAPED: usize = 256;

/// The largest font, outline, and padding the text host draws, in pixels.
pub(crate) const MAX_FONT_PIXELS: f32 = 2_048.0;
pub(crate) const MAX_OUTLINE_PIXELS: f32 = 64.0;
const MAX_PADDING_PIXELS: f32 = 256.0;

/// Where [`TextTextures`] keeps the pixels of a rasterized text: the GPU
/// renderer uploads them to a texture, the CPU renderer keeps them.
pub trait TextUpload {
    /// Takes `rgba8`, premultiplied sRGB-encoded RGBA of `size` with rows
    /// packed, as the renderer's source for that text.
    ///
    /// # Errors
    /// Returns [`RenderError::InvalidImageData`] when `rgba8` does not hold
    /// `size`, or the GPU's upload failure.
    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError>;
}

/// The pixels of one prepared text, as the renderer that drew it keeps
/// them.
#[derive(Debug)]
pub struct TextPixels(TextStorage);

#[derive(Debug)]
enum TextStorage {
    Gpu(UploadTexture),
    Cpu(CpuSource),
}

impl TextPixels {
    /// The text as a graph source.
    fn view(&self) -> SourceView<'_> {
        match &self.0 {
            TextStorage::Gpu(texture) => SourceView::from(texture),
            TextStorage::Cpu(source) => SourceView::cpu(source),
        }
    }
}

impl TextUpload for Renderer {
    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError> {
        self.upload_rgba8(size, rgba8)
            .map(|texture| TextPixels(TextStorage::Gpu(texture)))
    }
}

impl TextUpload for CpuRenderer {
    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError> {
        let picture = CpuImage::from_premultiplied_rgba8(size, rgba8)?;
        Ok(TextPixels(TextStorage::Cpu(CpuSource::image(Arc::new(
            picture,
        )))))
    }
}

/// One prepared text: its texture, pixel size, and where its layout box
/// lies in it.
#[derive(Clone, Copy, Debug)]
pub struct TextTexture<'a> {
    /// Premultiplied, sRGB-encoded RGBA, as every source texture.
    pub texture: SourceView<'a>,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// The margin, in pixels, the same on both sides of each axis, that the
    /// texture adds around the text and its decorations for ink reaching
    /// past them: an accent above the first line, say. Placement leaves it
    /// out, so such ink never moves the text.
    pub margin: [u32; 2],
    /// The key the renderer's result cache holds results drawn from this
    /// texture under, or `None` to keep every frame showing it out of that
    /// cache. It is the provider's promise that the texture's pixels depend
    /// on nothing it leaves out, as [`crate::FrameProvider::source_key`] is
    /// for a source: [`TextTextures`] keys each text by its [`text_key`] and
    /// the fonts it was drawn with.
    pub cache_key: Option<RenderCacheKey>,
}

/// Where a text lies, as fractions of the canvas, `(0, 0)` top-left to
/// `(1, 1)` bottom-right, as its style's position is: on the picture a text
/// generator draws, before its clip's transform and effects, and on the
/// canvas for a caption. [`measure_text`] measures it.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct TextBounds {
    /// The box the style's anchor and position place: the wrapping width
    /// wide, every line's em box tall, and the whole pixels of outline and
    /// background padding around that.
    pub layout: CanvasRect,
    /// The lines' advances: from the start of the line that starts farthest
    /// left to the end of the one that ends farthest right, as tall as the
    /// layout, with the same decorations around it. It moves only as the
    /// advances do, not as glyphs with more or less ink are typed.
    pub content: CanvasRect,
    /// What the text draws: its glyphs, their outline, and the background's
    /// boxes, as [`alpha2_text::TextMeasure::ink`] bounds them at the measured
    /// size. Every pixel the text gives any alpha there meets it, give or
    /// take the pixel sampling the texture spreads it by. `None` when the text
    /// draws nothing.
    pub ink: Option<CanvasRect>,
    /// Number of laid-out lines.
    pub line_count: u32,
}

/// A rectangle as fractions of the canvas, y down.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CanvasRect {
    /// Left edge, a fraction of the canvas width.
    pub left: f32,
    /// Top edge, a fraction of the canvas height.
    pub top: f32,
    /// Right edge, a fraction of the canvas width.
    pub right: f32,
    /// Bottom edge, a fraction of the canvas height.
    pub bottom: f32,
}

/// Why text could not be prepared.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TextError {
    /// The text host refused: no fonts registered, a malformed font, or a
    /// text too large to rasterize.
    Raster(TextRasterError),
    /// The rasterized text could not be uploaded.
    Render(RenderError),
}

impl fmt::Display for TextError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Raster(TextRasterError::NoFonts) => {
                formatter.write_str("the project shows text, but no fonts were registered")
            }
            Self::Raster(error) => write!(formatter, "text failed: {error}"),
            Self::Render(error) => write!(formatter, "text upload failed: {error}"),
        }
    }
}

impl std::error::Error for TextError {}

struct TextEntry {
    texture: TextPixels,
    width: u32,
    height: u32,
    margin: [u32; 2],
    /// Where the layout box's top-left corner lies in the texture.
    corner: [u32; 2],
    last_used: u64,
}

/// A layout resolved at one size, with the requests of its texts, to
/// rasterize again one the text store has let go.
struct LayoutEntry {
    prepared: Arc<PreparedLayout>,
    requests: Vec<(u64, TextRasterRequest)>,
    last_used: u64,
}

/// A text shaped for layout, and when it was last asked for.
struct ShapedEntry {
    shaped: Arc<ShapedText>,
    last_used: u64,
}

/// Fonts and the texts rasterized with them, keyed by content and render
/// size.
pub struct TextTextures {
    rasterizer: TextRasterizer,
    /// The identity of the fonts the texts are drawn with, from
    /// [`NEXT_FONT_SET`].
    font_set: u64,
    entries: HashMap<u64, TextEntry>,
    /// Resolved layouts by [`layout_key`].
    layouts: HashMap<u128, LayoutEntry>,
    /// Texts shaped for layout, by [`shaped_key`].
    shaped: HashMap<u64, ShapedEntry>,
    /// How many layouts have been resolved: a static layout resolves once.
    resolves: u64,
    frame: u64,
}

impl fmt::Debug for TextTextures {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("TextTextures")
            .field("fonts", &self.rasterizer.font_count())
            .field("texts", &self.entries.len())
            .field("layouts", &self.layouts.len())
            .finish_non_exhaustive()
    }
}

impl Default for TextTextures {
    fn default() -> Self {
        Self::new()
    }
}

impl TextTextures {
    /// No fonts and no texts.
    #[must_use]
    pub fn new() -> Self {
        Self {
            rasterizer: TextRasterizer::empty(),
            font_set: NEXT_FONT_SET.fetch_add(1, Ordering::Relaxed),
            entries: HashMap::new(),
            layouts: HashMap::new(),
            shaped: HashMap::new(),
            resolves: 0,
            frame: 0,
        }
    }

    /// Appends an OpenType font to the fallback stack text draws with. Texts
    /// already rasterized are dropped.
    ///
    /// # Errors
    /// Returns [`TextError::Raster`] for malformed font bytes.
    pub fn add_font(
        &mut self,
        family: impl Into<String>,
        bytes: impl Into<Arc<[u8]>>,
        face_index: u32,
    ) -> Result<(), TextError> {
        self.rasterizer
            .add_font(TextFont {
                family: family.into(),
                bytes: bytes.into(),
                face_index,
            })
            .map_err(TextError::Raster)?;
        self.entries.clear();
        self.layouts.clear();
        self.shaped.clear();
        // The same text may now draw other glyphs.
        self.font_set = NEXT_FONT_SET.fetch_add(1, Ordering::Relaxed);
        Ok(())
    }

    /// Fonts in the fallback stack.
    #[must_use]
    pub fn font_count(&self) -> usize {
        self.rasterizer.font_count()
    }

    /// Rasterizes and uploads every text `frame` shows at `size` that is not
    /// already held: its captions and the text generators its clips draw.
    /// Resolves every layout it draws that is not already held, and
    /// rasterizes its texts. Forgets the least recently shown beyond a small
    /// number.
    ///
    /// # Errors
    /// Returns [`TextError`] when a text cannot be rasterized or uploaded;
    /// with no fonts registered, only if the frame shows one.
    pub fn prepare(
        &mut self,
        renderer: &dyn TextUpload,
        frame: &FrameDesc,
        size: RenderSize,
    ) -> Result<(), TextError> {
        self.frame += 1;
        for (text, style) in frame_texts(frame) {
            let key = text_key(text, style, size);
            if let Some(entry) = self.entries.get_mut(&key) {
                entry.last_used = self.frame;
                continue;
            }
            let request = text_request(text, style, size, key);
            self.rasterize(renderer, key, &request)?;
        }
        for (plan, time) in frame_layouts(frame) {
            self.prepare_layout(renderer, plan, time, size)?;
        }
        while self.layouts.len() > RETAINED_LAYOUTS {
            let Some(oldest) = self
                .layouts
                .iter()
                .filter(|(_, entry)| entry.last_used < self.frame)
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(key, _)| *key)
            else {
                break;
            };
            self.layouts.remove(&oldest);
        }
        while self.entries.len() > RETAINED_TEXTS {
            let Some(oldest) = self
                .entries
                .iter()
                .filter(|(_, entry)| entry.last_used < self.frame)
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(key, _)| *key)
            else {
                break;
            };
            self.entries.remove(&oldest);
        }
        Ok(())
    }

    /// Rasterizes `request` and uploads it as the text with `key`.
    fn rasterize(
        &mut self,
        renderer: &dyn TextUpload,
        key: u64,
        request: &TextRasterRequest,
    ) -> Result<(), TextError> {
        let raster = self
            .rasterizer
            .rasterize(request)
            .map_err(TextError::Raster)?;
        // Each text is rasterized once per key; keep no copy.
        self.rasterizer.invalidate(key);
        let texture_size = &raster.descriptor.texture;
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let corner =
            [raster.descriptor.layout_x, raster.descriptor.layout_y].map(|corner| corner as u32);
        // The anchor places the decorated text; the margin, which holds only ink reaching past
        // it, takes no part in placement.
        let margin = corner.map(|corner| corner.saturating_sub(request.decoration_margin()));
        let texture = renderer
            .upload_text(
                RenderSize::new(texture_size.width, texture_size.height)
                    .map_err(TextError::Render)?,
                &raster.pixels.rgba8,
            )
            .map_err(TextError::Render)?;
        self.entries.insert(
            key,
            TextEntry {
                texture,
                width: texture_size.width,
                height: texture_size.height,
                margin,
                corner,
                last_used: self.frame,
            },
        );
        Ok(())
    }

    /// Resolves `plan` at picture time `time` and `size`, and rasterizes its
    /// texts, unless that layout is already held: then only texts the store
    /// let go are rasterized again.
    fn prepare_layout(
        &mut self,
        renderer: &dyn TextUpload,
        plan: &LayoutPlan,
        time: alpha2_time::MediaTime,
        size: RenderSize,
    ) -> Result<(), TextError> {
        let evaluated = plan.evaluate(time);
        let key = layout_key(evaluated.key, size);
        if let Some(entry) = self.layouts.get_mut(&key) {
            entry.last_used = self.frame;
            let requests = entry.requests.clone();
            for (text, request) in &requests {
                match self.entries.get_mut(text) {
                    Some(held) => held.last_used = self.frame,
                    None => self.rasterize(renderer, *text, request)?,
                }
            }
            return Ok(());
        }
        self.resolves += 1;
        let frame = self.frame;
        let shaped =
            crate::layout::shape_texts(&evaluated, size, |request| self.shape(request, frame))?;
        let resolved = crate::layout::resolve(&evaluated, size, &shaped);
        let (texts, requests) = crate::layout::layout_texts(&evaluated, &resolved, size);
        let mut boxes = Vec::with_capacity(texts.len());
        for text in &texts {
            boxes.push(match text {
                None => None,
                Some(text_key) => {
                    let request = &requests
                        .iter()
                        .find(|(key, _)| key == text_key)
                        .expect("a request per text")
                        .1;
                    match self.entries.get_mut(text_key) {
                        Some(held) => held.last_used = self.frame,
                        None => self.rasterize(renderer, *text_key, request)?,
                    }
                    let entry = &self.entries[text_key];
                    Some(crate::layout::paint::TextBox {
                        corner: entry.corner,
                        size: [entry.width, entry.height],
                    })
                }
            });
        }
        let items = crate::layout::paint::paint_list(&evaluated, &resolved, size, &boxes);
        self.layouts.insert(
            key,
            LayoutEntry {
                prepared: Arc::new(PreparedLayout { items, texts }),
                requests,
                last_used: self.frame,
            },
        );
        Ok(())
    }

    /// `request`'s text shaped for layout, from the cache when it holds it.
    fn shape(
        &mut self,
        request: &TextRasterRequest,
        frame: u64,
    ) -> Result<Arc<ShapedText>, TextRasterError> {
        let key = shaped_key(request);
        if let Some(entry) = self.shaped.get_mut(&key) {
            entry.last_used = frame;
            return Ok(Arc::clone(&entry.shaped));
        }
        let shaped = Arc::new(self.rasterizer.shape(request)?);
        if self.shaped.len() >= RETAINED_SHAPED
            && let Some(oldest) = self
                .shaped
                .iter()
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(key, _)| *key)
        {
            self.shaped.remove(&oldest);
        }
        self.shaped.insert(
            key,
            ShapedEntry {
                shaped: Arc::clone(&shaped),
                last_used: frame,
            },
        );
        Ok(shaped)
    }

    /// How many layouts have been resolved, held or not.
    #[cfg(test)]
    #[must_use]
    pub(crate) const fn layout_resolves(&self) -> u64 {
        self.resolves
    }

    /// The prepared layout with `key`, as [`layout_key`] names it.
    #[must_use]
    pub fn layout(&self, key: u128) -> Option<Arc<PreparedLayout>> {
        self.layouts
            .get(&key)
            .map(|entry| Arc::clone(&entry.prepared))
    }

    /// Where each node of `root` lies on a picture of `size` at picture
    /// time `time`, its pixels those of a `canvas` canvas, laid out with
    /// these fonts: [`crate::measure_layout`].
    ///
    /// # Errors
    /// Returns [`TextError::Raster`] as [`Self::prepare`] would for its
    /// texts.
    pub fn measure_layout(
        &self,
        root: &alpha2_model::LayoutNode,
        time: alpha2_time::MediaTime,
        size: RenderSize,
        canvas: (u32, u32),
    ) -> Result<crate::LayoutBounds, TextError> {
        crate::measure_layout(&self.rasterizer, root, time, size, canvas)
    }

    /// [`Self::prepare`] for the frame of `project` at `time`, rendered at
    /// `size`; nothing to do, and no evaluation, when the project draws no
    /// text ([`crate::EngineProject::draws_text`]).
    ///
    /// # Errors
    /// Returns [`crate::EngineError::Evaluate`] or
    /// [`crate::EngineError::Text`].
    pub fn prepare_at(
        &mut self,
        renderer: &dyn TextUpload,
        project: &crate::EngineProject,
        time: alpha2_time::MediaTime,
        size: RenderSize,
    ) -> Result<(), crate::EngineError> {
        if !project.draws_text() {
            return Ok(());
        }
        let frame = project.evaluate(time)?;
        self.prepare(renderer, &frame, size)
            .map_err(crate::EngineError::Text)
    }

    /// Where `text` in `style` lies on a canvas of `size`, drawn with these
    /// fonts: [`measure_text`].
    ///
    /// # Errors
    /// Returns [`TextError::Raster`] as [`Self::prepare`] would for the text.
    pub fn measure(
        &self,
        text: &str,
        style: &TextStyle,
        size: RenderSize,
    ) -> Result<TextBounds, TextError> {
        measure_text(&self.rasterizer, text, style, size)
    }

    /// The prepared text with `key`, as [`text_key`] names it.
    #[must_use]
    pub fn get(&self, key: u64) -> Option<TextTexture<'_>> {
        self.entries.get(&key).map(|entry| TextTexture {
            texture: entry.texture.view(),
            width: entry.width,
            height: entry.height,
            margin: entry.margin,
            cache_key: Some(self.cache_key(key)),
        })
    }

    /// The result cache key of the text with `key`, drawn with these fonts:
    /// the font set in the high half, beside the text domain, and the text
    /// in the low half, so two keys are equal only for the same text drawn
    /// with the same fonts.
    fn cache_key(&self, key: u64) -> RenderCacheKey {
        let high = TEXT_CACHE_DOMAIN ^ self.font_set;
        RenderCacheKey::from_value((u128::from(high) << 64) | u128::from(key))
    }
}

/// Every text `frame` may draw, with its style: each caption, then each text
/// generator of a clip it draws, the clip's own source or a step of its
/// compositions. A text drawn twice is named twice.
pub(crate) fn frame_texts<'f>(
    frame: &'f FrameDesc<'_>,
) -> impl Iterator<Item = (&'f str, &'f TextStyle)> {
    let captions = frame
        .captions
        .iter()
        .map(|caption| (caption.text, caption.style));
    let generators = frame
        .visual
        .iter()
        .filter(|clip| frame.draws(clip))
        .flat_map(|clip| {
            let steps = clip
                .composition
                .iter()
                .chain(&clip.source_composition)
                .flat_map(|composition| &composition.plan().steps)
                .filter_map(|step| match &step.op {
                    StepOp::Generator { generator, .. } => Some(generator),
                    _ => None,
                });
            clip.generator.into_iter().chain(steps)
        })
        .filter_map(|generator| match generator {
            Generator::Text { text, style } => Some((text.as_str(), style)),
            _ => None,
        });
    captions.chain(generators)
}

/// A host's frame provider together with its text store: frames come from
/// the one and text from the other.
pub struct FramesWithText<'a> {
    frames: &'a dyn crate::FrameProvider,
    texts: &'a TextTextures,
}

impl<'a> FramesWithText<'a> {
    /// `frames` with the texts `texts` holds.
    #[must_use]
    pub fn new(frames: &'a dyn crate::FrameProvider, texts: &'a TextTextures) -> Self {
        Self { frames, texts }
    }
}

impl crate::FrameProvider for FramesWithText<'_> {
    fn texture_for(
        &self,
        source: &alpha2_media::SourceId,
        time: alpha2_time::MediaTime,
    ) -> Option<SourceView<'_>> {
        self.frames.texture_for(source, time)
    }

    fn pending_source_work(
        &self,
        source: &alpha2_media::SourceId,
        time: alpha2_time::MediaTime,
    ) -> Option<&alpha2_render::PendingSourceWork> {
        self.frames.pending_source_work(source, time)
    }

    fn source_key(
        &self,
        source: &alpha2_media::SourceId,
        time: alpha2_time::MediaTime,
    ) -> Option<alpha2_render::RenderCacheKey> {
        self.frames.source_key(source, time)
    }

    fn text(&self, key: u64) -> Option<TextTexture<'_>> {
        self.texts.get(key)
    }

    fn layout(&self, key: u128) -> Option<Arc<PreparedLayout>> {
        self.texts.layout(key)
    }
}

/// Every layout `frame` may draw, with its picture time: each drawn clip's
/// layout source at its source time, then each layout step of its
/// compositions at the step's time plus its start.
pub(crate) fn frame_layouts<'f>(
    frame: &'f FrameDesc<'_>,
) -> impl Iterator<Item = (&'f LayoutPlan, alpha2_time::MediaTime)> {
    frame
        .visual
        .iter()
        .filter(|clip| frame.draws(clip))
        .flat_map(|clip| {
            let own = clip
                .plan
                .and_then(GeneratorPlan::layout)
                .map(|plan| (plan, clip.source_time));
            let steps = clip
                .composition
                .iter()
                .chain(&clip.source_composition)
                .flat_map(|composition| {
                    let time = composition.time();
                    composition
                        .plan()
                        .steps
                        .iter()
                        .filter_map(move |step| match &step.op {
                            StepOp::Generator {
                                plan: Some(plan),
                                start,
                                ..
                            } => plan.layout().map(|plan| {
                                (
                                    plan,
                                    alpha2_time::MediaTime(
                                        step.time(time).ticks().saturating_add(start.ticks()),
                                    ),
                                )
                            }),
                            _ => None,
                        })
                });
            own.into_iter().chain(steps)
        })
}

/// A layout's identity at a render size: its evaluated key and the size.
/// Equal keys lay out and draw alike with the same fonts.
#[must_use]
pub fn layout_key(evaluated: u128, size: RenderSize) -> u128 {
    let mut hash = alpha2_geometry::StableHash::new();
    hash.bytes(b"layout");
    hash.bytes(&evaluated.to_le_bytes());
    hash.u32(size.width);
    hash.u32(size.height);
    hash.finish()
}

/// A layout text's raster request as a text store key: FNV-1a over a domain
/// byte and every field of the request. Never zero.
pub(crate) fn layout_text_key(request: &TextRasterRequest) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    // Layout texts take keys apart from captions' and text generators'.
    feed(&[0x4c]);
    feed_request(&mut feed, request);
    hash.max(1)
}

/// What a request is shaped from, as a shaped-text cache key.
fn shaped_key(request: &TextRasterRequest) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    feed(request.text.as_bytes());
    feed(&[0xff]);
    feed(
        request
            .font_family
            .as_deref()
            .unwrap_or_default()
            .as_bytes(),
    );
    feed(&[0xff, u8::from(request.font_family.is_some())]);
    feed(&request.font_size.to_bits().to_le_bytes());
    feed(&request.line_height.to_bits().to_le_bytes());
    hash
}

fn feed_request(feed: &mut impl FnMut(&[u8]), request: &TextRasterRequest) {
    feed(request.text.as_bytes());
    feed(&[0xff]);
    feed(
        request
            .font_family
            .as_deref()
            .unwrap_or_default()
            .as_bytes(),
    );
    feed(&[0xff, u8::from(request.font_family.is_some())]);
    for value in [request.font_size, request.max_width, request.line_height] {
        feed(&value.to_bits().to_le_bytes());
    }
    feed(&request.color);
    feed(&[match request.align {
        alpha2_media::TextAlign::Start => 0,
        alpha2_media::TextAlign::Center => 1,
        alpha2_media::TextAlign::End => 2,
    }]);
    match request.outline {
        Some(outline) => {
            feed(&[1]);
            feed(&outline.color);
            feed(&outline.width.to_bits().to_le_bytes());
        }
        None => feed(&[0]),
    }
}

/// A text's identity at a render size: the text, its style, and the size,
/// hashed (FNV-1a). Never zero.
#[must_use]
pub fn text_key(text: &str, style: &TextStyle, size: RenderSize) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut feed = |bytes: &[u8]| {
        for byte in bytes {
            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3);
        }
    };
    feed(text.as_bytes());
    feed(&[0xff]);
    // Family names cannot hold 0xff (they are UTF-8), so the text and family stay apart.
    feed(style.font_family.as_deref().unwrap_or_default().as_bytes());
    feed(&[0xff, u8::from(style.font_family.is_some())]);
    for value in [
        style.font_size,
        style.line_height,
        style.max_width,
        style.position.x,
        style.position.y,
        style.anchor.x,
        style.anchor.y,
    ] {
        feed(&value.to_bits().to_le_bytes());
    }
    feed(&rgba8(style.color));
    feed(&[match style.align {
        TextAlign::Start => 0,
        TextAlign::Center => 1,
        TextAlign::End => 2,
    }]);
    match style.outline {
        Some(outline) => {
            feed(&[1]);
            feed(&rgba8(outline.color));
            feed(&outline.width.to_bits().to_le_bytes());
        }
        None => feed(&[0]),
    }
    match style.background {
        Some(background) => {
            feed(&[1]);
            feed(&rgba8(background.color));
            feed(&background.padding.to_bits().to_le_bytes());
        }
        None => feed(&[0]),
    }
    feed(&size.width.to_le_bytes());
    feed(&size.height.to_le_bytes());
    hash.max(1)
}

/// Where `text` in `style` lies on a canvas of `size` ([`TextBounds`]), laid
/// out with `rasterizer`'s fonts as [`TextTextures::prepare`] lays it out and
/// placed as a frame places it, without drawing it. Measured at the size a
/// frame is drawn at, it agrees with that frame to the pixel; text laid out
/// at another size can break its lines elsewhere.
///
/// # Errors
/// Returns [`TextError::Raster`] when the text host refuses the text: no
/// fonts, or a style out of range.
#[allow(clippy::cast_precision_loss)]
pub fn measure_text(
    rasterizer: &TextRasterizer,
    text: &str,
    style: &TextStyle,
    size: RenderSize,
) -> Result<TextBounds, TextError> {
    let request = text_request(text, style, size, text_key(text, style, size));
    let measure = rasterizer.measure(&request).map_err(TextError::Raster)?;
    let (width, height) = (size.width as f32, size.height as f32);
    let margin = measure.decoration_margin as f32;
    let (box_width, box_height) = (measure.box_width as f32, measure.box_height as f32);
    // The layout box's top-left corner on the canvas: the anchor of the box with its decorations
    // lies at the position, as `text_placement` places the texture.
    let origin = [
        style.position.x * width - style.anchor.x * (box_width + 2.0 * margin) + margin,
        style.position.y * height - style.anchor.y * (box_height + 2.0 * margin) + margin,
    ];
    let rect = |[left, top, right, bottom]: [f32; 4]| CanvasRect {
        left: (origin[0] + left) / width,
        top: (origin[1] + top) / height,
        right: (origin[0] + right) / width,
        bottom: (origin[1] + bottom) / height,
    };
    Ok(TextBounds {
        layout: rect([-margin, -margin, box_width + margin, box_height + margin]),
        content: rect(measure.content),
        ink: measure.ink.map(rect),
        line_count: measure.line_count,
    })
}

/// A straight, sRGB-encoded color as bytes.
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub(crate) fn rgba8(color: Rgba) -> [u8; 4] {
    [color.red, color.green, color.blue, color.alpha]
        .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8)
}

/// The text host request for `text` at `size`: sizes scaled from canvas
/// fractions to pixels, within what the text host draws.
#[allow(clippy::cast_precision_loss)]
fn text_request(text: &str, style: &TextStyle, size: RenderSize, key: u64) -> TextRasterRequest {
    let font_size = (style.font_size * size.height as f32).clamp(1.0, MAX_FONT_PIXELS);
    TextRasterRequest {
        text: text.to_owned(),
        font_size,
        max_width: (style.max_width * size.width as f32).max(1.0),
        line_height: style.line_height,
        align: match style.align {
            TextAlign::Start => alpha2_media::TextAlign::Start,
            TextAlign::Center => alpha2_media::TextAlign::Center,
            TextAlign::End => alpha2_media::TextAlign::End,
        },
        color: rgba8(style.color),
        emoji_policy: EmojiPolicy::Color,
        content_version: key,
        outline: style.outline.map(|outline| alpha2_text::TextOutline {
            color: rgba8(outline.color),
            width: (outline.width * font_size).clamp(f32::MIN_POSITIVE, MAX_OUTLINE_PIXELS),
        }),
        background: style
            .background
            .map(|background| alpha2_text::TextBackground {
                color: rgba8(background.color),
                padding: (background.padding * font_size).clamp(0.0, MAX_PADDING_PIXELS),
            }),
        font_family: style.font_family.clone(),
    }
}

#[cfg(test)]
#[path = "text_tests.rs"]
mod tests;