alpha2-engine 0.5.2

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
//! Text rendering for captions, text generators and layouts, rasterized by the portable text host.
//!
//! The engine draws text from host-registered font bytes, so browser preview and native export
//! draw identical pixels given the same fonts. A host keeps one [`TextTextures`] beside its frame
//! provider, calls [`TextTextures::prepare`] before each frame, and answers
//! [`crate::FrameProvider::text`] from it.

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_layout::{
    PictureSize, ShadowPixels, TextAnimation, TextBounds, TextDraw, animated_text_key, shaped_key,
    text_draw,
};
use alpha2_model::{Generator, TextContent, 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;

pub(crate) fn picture(size: RenderSize) -> PictureSize {
    PictureSize::new(size.width, size.height).expect("a render size is a picture size")
}

/// High 64 bits of a text cache key before the font set is added. Never zero, so text keys never
/// collide with host source keys ([`RenderCacheKey::source`]).
const TEXT_CACHE_DOMAIN: u64 = 0x6361_7074_696f_6e73;

/// Next font set identity; every store and every added font takes a new one.
static NEXT_FONT_SET: AtomicU64 = AtomicU64::new(1);

/// Rasterized texts kept between frames, beyond those of the current frame.
const RETAINED_TEXTS: usize = 16;

/// Resolved layouts kept between frames, beyond those of the current frame.
const RETAINED_LAYOUTS: usize = 8;

/// Shaped texts kept for layout (LRU).
const RETAINED_SHAPED: usize = 256;

/// Where [`TextTextures`] keeps rasterized pixels: a GPU texture or CPU memory.
pub trait TextUpload {
    /// Stores tightly packed premultiplied sRGB-encoded RGBA of `size` as a text source.
    ///
    /// # Errors
    /// Returns [`RenderError::InvalidImageData`] when `rgba8` does not match `size`, or an upload
    /// failure.
    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError>;
}

/// The pixels of one prepared text.
#[derive(Debug)]
pub struct TextPixels(TextStorage);

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

impl TextPixels {
    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 layout box position.
#[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,
    /// Per-axis pixel margin around the decorated text for overflowing ink (such as accents).
    /// Placement ignores it, so such ink never moves the text.
    pub margin: [u32; 2],
    /// Result cache key for this texture, or `None` to bypass the cache. Like
    /// [`crate::FrameProvider::source_key`], it promises the pixels depend on nothing else.
    pub cache_key: Option<RenderCacheKey>,
    /// Background boxes as a separate texture (with its cache key) when the text has both boxes
    /// and shadows, since shadows lie between them. `texture` then holds no boxes.
    pub background: Option<(SourceView<'a>, Option<RenderCacheKey>)>,
    /// Glyph shadows, first on top, in picture pixels.
    pub shadows: &'a [ShadowPixels],
}

/// Why text could not be prepared.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TextError {
    /// The text host refused: no fonts, 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: Arc<TextPixels>,
    background: Option<Arc<TextPixels>>,
    shadows: Vec<ShadowPixels>,
    /// Pixel identity: the static key, mixed with the animator state hash when animated, so
    /// identical animation moments share pixels and cache entries.
    content: u64,
    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 its text requests for re-rasterizing evicted texts.
struct LayoutEntry {
    prepared: Arc<PreparedLayout>,
    requests: Vec<(u64, TextDraw)>,
    last_used: u64,
}

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,
    /// Font set identity 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>,
    /// Layout resolutions so far (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 and drops rasterized texts.
    ///
    /// # 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();
        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()
    }

    /// Requested families no registered font has, sorted
    /// ([`alpha2_text::TextRasterizer::unmatched_families`]).
    #[must_use]
    pub fn unmatched_font_families(&self) -> Vec<String> {
        self.rasterizer.unmatched_families()
    }

    /// Rasterizes and uploads every text and resolves every layout `frame` shows at `size` that is
    /// not already held, evicting 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;
        let picture = picture(size);
        for text in frame_texts(frame) {
            let key = animated_text_key(text.content, text.style, picture, text.time);
            if let Some(entry) = self.entries.get_mut(&key) {
                entry.last_used = self.frame;
                continue;
            }
            let mut draw = text_draw(&text.content.text(), text.style, picture, key);
            if !text.style.animators.is_empty() {
                draw.animation = Some(TextAnimation {
                    animators: alpha2_eval::sample_text_animators(&text.style.animators, text.time),
                    runs: text.content.runs().to_vec(),
                    time: text.time,
                });
            }
            self.rasterize(renderer, key, &draw)?;
        }
        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(())
    }

    fn rasterize(
        &mut self,
        renderer: &dyn TextUpload,
        key: u64,
        draw: &TextDraw,
    ) -> Result<(), TextError> {
        let request = &draw.request;
        let states = draw.states(&self.rasterizer).map_err(TextError::Raster)?;
        let content = match &states {
            // Identical animation moments share pixels; an all-identity state (hash 0) matches the
            // static text.
            Some((_, hash)) => {
                let content = match *hash {
                    0 => text_key_of(request),
                    hash => mix_key(text_key_of(request), hash),
                };
                if let Some(held) = self.entries.values().find(|entry| entry.content == content) {
                    let shared = TextEntry {
                        texture: Arc::clone(&held.texture),
                        background: held.background.clone(),
                        shadows: draw.shadows.clone(),
                        content,
                        width: held.width,
                        height: held.height,
                        margin: held.margin,
                        corner: held.corner,
                        last_used: self.frame,
                    };
                    self.entries.insert(key, shared);
                    return Ok(());
                }
                content
            }
            None => key,
        };
        let raster = match &states {
            Some((states, hash)) if *hash != 0 => self
                .rasterizer
                .rasterize_animated(request, states)
                .map_err(TextError::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 margin holds only overflowing ink and takes no part in placement.
        let margin = corner.map(|corner| corner.saturating_sub(request.decoration_margin()));
        let size =
            RenderSize::new(texture_size.width, texture_size.height).map_err(TextError::Render)?;
        let texture = renderer
            .upload_text(size, &raster.pixels.rgba8)
            .map_err(TextError::Render)?;
        let background = raster
            .background
            .as_deref()
            .map(|rgba8| renderer.upload_text(size, rgba8))
            .transpose()
            .map_err(TextError::Render)?;
        // Pixels are `Send` on native targets, where hosts move the store between threads; wasm
        // is single-threaded.
        #[cfg_attr(target_arch = "wasm32", allow(clippy::arc_with_non_send_sync))]
        let (texture, background) = (Arc::new(texture), background.map(Arc::new));
        self.entries.insert(
            key,
            TextEntry {
                texture,
                background,
                shadows: draw.shadows.clone(),
                content,
                width: texture_size.width,
                height: texture_size.height,
                margin,
                corner,
                last_used: self.frame,
            },
        );
        Ok(())
    }

    /// Resolves `plan` at `time` and `size` and rasterizes its texts. A held layout only
    /// re-rasterizes evicted texts.
    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 picture = picture(size);
        let shaped =
            alpha2_layout::shape_texts(&evaluated, picture, |request| self.shape(request, frame))
                .map_err(TextError::Raster)?;
        let resolved = alpha2_layout::resolve(&evaluated, picture, &shaped);
        let (texts, requests) = alpha2_layout::layout_texts(&evaluated, &resolved, picture);
        let mut boxes = Vec::with_capacity(texts.len());
        for text in &texts {
            boxes.push(match text {
                None => None,
                Some(text_key) => {
                    let draw = &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, draw)?,
                    }
                    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(())
    }

    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)
    }

    /// Layout resolutions so far, 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))
    }

    /// [`crate::measure_layout`] with these fonts.
    ///
    /// # Errors
    /// Returns [`TextError::Raster`] as [`Self::prepare`] would.
    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, picture(size), canvas)
            .map_err(TextError::Raster)
    }

    /// [`Self::prepare`] for `project` at `time`; skips 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)
    }

    /// [`crate::measure_text`] with these fonts.
    ///
    /// # Errors
    /// Returns [`TextError::Raster`] as [`Self::prepare`] would for the text.
    pub fn measure(
        &self,
        text: &str,
        style: &TextStyle,
        size: RenderSize,
    ) -> Result<TextBounds, TextError> {
        crate::measure_text(&self.rasterizer, text, style, picture(size)).map_err(TextError::Raster)
    }

    /// The prepared text with `key`, as [`crate::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(entry.content)),
            background: entry.background.as_ref().map(|background| {
                (
                    background.view(),
                    Some(self.background_cache_key(entry.content)),
                )
            }),
            shadows: &entry.shadows,
        })
    }

    /// Result cache key of text `key`: font set and domain in the high half, text in the low.
    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))
    }

    /// [`Self::cache_key`] in a separate domain for the background plane.
    fn background_cache_key(&self, key: u64) -> RenderCacheKey {
        let high = (TEXT_CACHE_DOMAIN ^ self.font_set) ^ (1 << 62);
        RenderCacheKey::from_value((u128::from(high) << 64) | u128::from(key))
    }
}

/// A text a frame may draw, with the time its animators are keyed in.
#[derive(Copy, Clone, Debug)]
pub(crate) struct FrameText<'f> {
    pub(crate) content: &'f TextContent,
    pub(crate) style: &'f TextStyle,
    pub(crate) time: alpha2_time::MediaTime,
}

/// Every text `frame` may draw: captions, then text generators of drawn clips. Duplicates repeat.
pub(crate) fn frame_texts<'f>(frame: &'f FrameDesc<'_>) -> impl Iterator<Item = FrameText<'f>> {
    let captions = frame.captions.iter().map(|caption| FrameText {
        content: caption.text,
        style: caption.style,
        time: caption.local_time,
    });
    let generators = frame
        .visual
        .iter()
        .filter(|clip| frame.draws(clip))
        .flat_map(|clip| {
            let own = clip
                .generator
                .map(|generator| (generator, 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 {
                                generator, start, ..
                            } => Some((generator, generator_time(step.time(time), *start))),
                            _ => None,
                        })
                });
            own.into_iter().chain(steps)
        })
        .filter_map(|(generator, time)| match generator {
            Generator::Text { text, style } => Some(FrameText {
                content: text,
                style,
                time,
            }),
            _ => None,
        });
    captions.chain(generators)
}

/// A composition generator step's picture time: step time plus start.
pub(crate) const fn generator_time(
    step: alpha2_time::MediaTime,
    start: alpha2_time::MediaTime,
) -> alpha2_time::MediaTime {
    alpha2_time::MediaTime(step.ticks().saturating_add(start.ticks()))
}

/// `key` mixed with an animation's state `hash`: FNV-1a, never zero.
fn mix_key(key: u64, hash: u64) -> u64 {
    let mut mixed = key;
    for byte in hash.to_le_bytes() {
        mixed = (mixed ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
    }
    mixed.max(1)
}

/// Key for `request` without animators, from every field but the content version.
fn text_key_of(request: &TextRasterRequest) -> u64 {
    alpha2_layout::layout_text_key(
        &TextRasterRequest {
            content_version: 1,
            ..request.clone()
        },
        &[],
        &[],
    )
}

/// A host's frame provider combined with its text store.
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.
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. Equal keys 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()
}