Skip to main content

alpha2_engine/
text.rs

1//! Text rendering for captions, text generators and layouts, rasterized by the portable text host.
2//!
3//! The engine draws text from host-registered font bytes, so browser preview and native export
4//! draw identical pixels given the same fonts. A host keeps one [`TextTextures`] beside its frame
5//! provider, calls [`TextTextures::prepare`] before each frame, and answers
6//! [`crate::FrameProvider::text`] from it.
7
8use std::collections::HashMap;
9use std::fmt;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU64, Ordering};
12
13use alpha2_eval::{FrameDesc, GeneratorPlan, LayoutPlan, StepOp};
14use alpha2_layout::{
15    PictureSize, ShadowPixels, TextAnimation, TextBounds, TextDraw, animated_text_key, shaped_key,
16    text_draw,
17};
18use alpha2_model::{Generator, TextContent, TextStyle};
19use alpha2_render::{
20    CpuImage, CpuRenderer, CpuSource, RenderCacheKey, RenderError, RenderSize, Renderer,
21    SourceView, UploadTexture,
22};
23use alpha2_text::{ShapedText, TextFont, TextRasterError, TextRasterRequest, TextRasterizer};
24
25use crate::layout::PreparedLayout;
26
27pub(crate) fn picture(size: RenderSize) -> PictureSize {
28    PictureSize::new(size.width, size.height).expect("a render size is a picture size")
29}
30
31/// High 64 bits of a text cache key before the font set is added. Never zero, so text keys never
32/// collide with host source keys ([`RenderCacheKey::source`]).
33const TEXT_CACHE_DOMAIN: u64 = 0x6361_7074_696f_6e73;
34
35/// Next font set identity; every store and every added font takes a new one.
36static NEXT_FONT_SET: AtomicU64 = AtomicU64::new(1);
37
38/// Rasterized texts kept between frames, beyond those of the current frame.
39const RETAINED_TEXTS: usize = 16;
40
41/// Resolved layouts kept between frames, beyond those of the current frame.
42const RETAINED_LAYOUTS: usize = 8;
43
44/// Shaped texts kept for layout (LRU).
45const RETAINED_SHAPED: usize = 256;
46
47/// Where [`TextTextures`] keeps rasterized pixels: a GPU texture or CPU memory.
48pub trait TextUpload {
49    /// Stores tightly packed premultiplied sRGB-encoded RGBA of `size` as a text source.
50    ///
51    /// # Errors
52    /// Returns [`RenderError::InvalidImageData`] when `rgba8` does not match `size`, or an upload
53    /// failure.
54    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError>;
55}
56
57/// The pixels of one prepared text.
58#[derive(Debug)]
59pub struct TextPixels(TextStorage);
60
61#[derive(Debug)]
62enum TextStorage {
63    Gpu(UploadTexture),
64    Cpu(CpuSource),
65}
66
67impl TextPixels {
68    fn view(&self) -> SourceView<'_> {
69        match &self.0 {
70            TextStorage::Gpu(texture) => SourceView::from(texture),
71            TextStorage::Cpu(source) => SourceView::cpu(source),
72        }
73    }
74}
75
76impl TextUpload for Renderer {
77    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError> {
78        self.upload_rgba8(size, rgba8)
79            .map(|texture| TextPixels(TextStorage::Gpu(texture)))
80    }
81}
82
83impl TextUpload for CpuRenderer {
84    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError> {
85        let picture = CpuImage::from_premultiplied_rgba8(size, rgba8)?;
86        Ok(TextPixels(TextStorage::Cpu(CpuSource::image(Arc::new(
87            picture,
88        )))))
89    }
90}
91
92/// One prepared text: its texture, pixel size and layout box position.
93#[derive(Clone, Copy, Debug)]
94pub struct TextTexture<'a> {
95    /// Premultiplied, sRGB-encoded RGBA, as every source texture.
96    pub texture: SourceView<'a>,
97    /// Width in pixels.
98    pub width: u32,
99    /// Height in pixels.
100    pub height: u32,
101    /// Per-axis pixel margin around the decorated text for overflowing ink (such as accents).
102    /// Placement ignores it, so such ink never moves the text.
103    pub margin: [u32; 2],
104    /// Result cache key for this texture, or `None` to bypass the cache. Like
105    /// [`crate::FrameProvider::source_key`], it promises the pixels depend on nothing else.
106    pub cache_key: Option<RenderCacheKey>,
107    /// Background boxes as a separate texture (with its cache key) when the text has both boxes
108    /// and shadows, since shadows lie between them. `texture` then holds no boxes.
109    pub background: Option<(SourceView<'a>, Option<RenderCacheKey>)>,
110    /// Glyph shadows, first on top, in picture pixels.
111    pub shadows: &'a [ShadowPixels],
112}
113
114/// Why text could not be prepared.
115#[derive(Clone, Debug, Eq, PartialEq)]
116#[non_exhaustive]
117pub enum TextError {
118    /// The text host refused: no fonts, a malformed font, or a text too large to rasterize.
119    Raster(TextRasterError),
120    /// The rasterized text could not be uploaded.
121    Render(RenderError),
122}
123
124impl fmt::Display for TextError {
125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            Self::Raster(TextRasterError::NoFonts) => {
128                formatter.write_str("the project shows text, but no fonts were registered")
129            }
130            Self::Raster(error) => write!(formatter, "text failed: {error}"),
131            Self::Render(error) => write!(formatter, "text upload failed: {error}"),
132        }
133    }
134}
135
136impl std::error::Error for TextError {}
137
138struct TextEntry {
139    texture: Arc<TextPixels>,
140    background: Option<Arc<TextPixels>>,
141    shadows: Vec<ShadowPixels>,
142    /// Pixel identity: the static key, mixed with the animator state hash when animated, so
143    /// identical animation moments share pixels and cache entries.
144    content: u64,
145    width: u32,
146    height: u32,
147    margin: [u32; 2],
148    /// Where the layout box's top-left corner lies in the texture.
149    corner: [u32; 2],
150    last_used: u64,
151}
152
153/// A layout resolved at one size, with its text requests for re-rasterizing evicted texts.
154struct LayoutEntry {
155    prepared: Arc<PreparedLayout>,
156    requests: Vec<(u64, TextDraw)>,
157    last_used: u64,
158}
159
160struct ShapedEntry {
161    shaped: Arc<ShapedText>,
162    last_used: u64,
163}
164
165/// Fonts and the texts rasterized with them, keyed by content and render size.
166pub struct TextTextures {
167    rasterizer: TextRasterizer,
168    /// Font set identity from [`NEXT_FONT_SET`].
169    font_set: u64,
170    entries: HashMap<u64, TextEntry>,
171    /// Resolved layouts by [`layout_key`].
172    layouts: HashMap<u128, LayoutEntry>,
173    /// Texts shaped for layout, by [`shaped_key`].
174    shaped: HashMap<u64, ShapedEntry>,
175    /// Layout resolutions so far (a static layout resolves once).
176    resolves: u64,
177    frame: u64,
178}
179
180impl fmt::Debug for TextTextures {
181    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182        formatter
183            .debug_struct("TextTextures")
184            .field("fonts", &self.rasterizer.font_count())
185            .field("texts", &self.entries.len())
186            .field("layouts", &self.layouts.len())
187            .finish_non_exhaustive()
188    }
189}
190
191impl Default for TextTextures {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197impl TextTextures {
198    /// No fonts and no texts.
199    #[must_use]
200    pub fn new() -> Self {
201        Self {
202            rasterizer: TextRasterizer::empty(),
203            font_set: NEXT_FONT_SET.fetch_add(1, Ordering::Relaxed),
204            entries: HashMap::new(),
205            layouts: HashMap::new(),
206            shaped: HashMap::new(),
207            resolves: 0,
208            frame: 0,
209        }
210    }
211
212    /// Appends an `OpenType` font to the fallback stack and drops rasterized texts.
213    ///
214    /// # Errors
215    /// Returns [`TextError::Raster`] for malformed font bytes.
216    pub fn add_font(
217        &mut self,
218        family: impl Into<String>,
219        bytes: impl Into<Arc<[u8]>>,
220        face_index: u32,
221    ) -> Result<(), TextError> {
222        self.rasterizer
223            .add_font(TextFont {
224                family: family.into(),
225                bytes: bytes.into(),
226                face_index,
227            })
228            .map_err(TextError::Raster)?;
229        self.entries.clear();
230        self.layouts.clear();
231        self.shaped.clear();
232        self.font_set = NEXT_FONT_SET.fetch_add(1, Ordering::Relaxed);
233        Ok(())
234    }
235
236    /// Fonts in the fallback stack.
237    #[must_use]
238    pub fn font_count(&self) -> usize {
239        self.rasterizer.font_count()
240    }
241
242    /// Requested families no registered font has, sorted
243    /// ([`alpha2_text::TextRasterizer::unmatched_families`]).
244    #[must_use]
245    pub fn unmatched_font_families(&self) -> Vec<String> {
246        self.rasterizer.unmatched_families()
247    }
248
249    /// Rasterizes and uploads every text and resolves every layout `frame` shows at `size` that is
250    /// not already held, evicting the least recently shown beyond a small number.
251    ///
252    /// # Errors
253    /// Returns [`TextError`] when a text cannot be rasterized or uploaded;
254    /// with no fonts registered, only if the frame shows one.
255    pub fn prepare(
256        &mut self,
257        renderer: &dyn TextUpload,
258        frame: &FrameDesc,
259        size: RenderSize,
260    ) -> Result<(), TextError> {
261        self.frame += 1;
262        let picture = picture(size);
263        for text in frame_texts(frame) {
264            let key = animated_text_key(text.content, text.style, picture, text.time);
265            if let Some(entry) = self.entries.get_mut(&key) {
266                entry.last_used = self.frame;
267                continue;
268            }
269            let content = alpha2_layout::TextAt::new(text.content, text.time);
270            let frame_number = self.frame;
271            let fitted = alpha2_layout::fit_text(&content, text.style, picture, |request| {
272                self.shape(request, frame_number)
273            })
274            .map_err(TextError::Raster)?;
275            let mut draw = text_draw(&content, text.style, picture, key, fitted.font_pixels);
276            if !text.style.animators.is_empty() {
277                draw.animation = Some(TextAnimation {
278                    animators: alpha2_eval::sample_text_animators(&text.style.animators, text.time),
279                    runs: text.content.runs().to_vec(),
280                    time: text.time,
281                });
282            }
283            self.rasterize(renderer, key, &draw)?;
284        }
285        for (plan, time) in frame_layouts(frame) {
286            self.prepare_layout(renderer, plan, time, size)?;
287        }
288        while self.layouts.len() > RETAINED_LAYOUTS {
289            let Some(oldest) = self
290                .layouts
291                .iter()
292                .filter(|(_, entry)| entry.last_used < self.frame)
293                .min_by_key(|(_, entry)| entry.last_used)
294                .map(|(key, _)| *key)
295            else {
296                break;
297            };
298            self.layouts.remove(&oldest);
299        }
300        while self.entries.len() > RETAINED_TEXTS {
301            let Some(oldest) = self
302                .entries
303                .iter()
304                .filter(|(_, entry)| entry.last_used < self.frame)
305                .min_by_key(|(_, entry)| entry.last_used)
306                .map(|(key, _)| *key)
307            else {
308                break;
309            };
310            self.entries.remove(&oldest);
311        }
312        Ok(())
313    }
314
315    fn rasterize(
316        &mut self,
317        renderer: &dyn TextUpload,
318        key: u64,
319        draw: &TextDraw,
320    ) -> Result<(), TextError> {
321        let request = &draw.request;
322        let states = draw.states(&self.rasterizer).map_err(TextError::Raster)?;
323        let content = match &states {
324            // Identical animation moments share pixels; an all-identity state (hash 0) matches the
325            // static text.
326            Some((_, hash)) => {
327                let content = match *hash {
328                    0 => text_key_of(request),
329                    hash => mix_key(text_key_of(request), hash),
330                };
331                if let Some(held) = self.entries.values().find(|entry| entry.content == content) {
332                    let shared = TextEntry {
333                        texture: Arc::clone(&held.texture),
334                        background: held.background.clone(),
335                        shadows: draw.shadows.clone(),
336                        content,
337                        width: held.width,
338                        height: held.height,
339                        margin: held.margin,
340                        corner: held.corner,
341                        last_used: self.frame,
342                    };
343                    self.entries.insert(key, shared);
344                    return Ok(());
345                }
346                content
347            }
348            None => key,
349        };
350        let raster = match &states {
351            Some((states, hash)) if *hash != 0 => self
352                .rasterizer
353                .rasterize_animated(request, states)
354                .map_err(TextError::Raster)?,
355            _ => self
356                .rasterizer
357                .rasterize(request)
358                .map_err(TextError::Raster)?,
359        };
360        // Each text is rasterized once per key; keep no copy.
361        self.rasterizer.invalidate(key);
362        let texture_size = &raster.descriptor.texture;
363        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
364        let corner =
365            [raster.descriptor.layout_x, raster.descriptor.layout_y].map(|corner| corner as u32);
366        // The margin holds only overflowing ink and takes no part in placement.
367        let decoration = request.decoration_margin();
368        let margin = [0, 1].map(|axis| corner[axis].saturating_sub(decoration[axis]));
369        let size =
370            RenderSize::new(texture_size.width, texture_size.height).map_err(TextError::Render)?;
371        let texture = renderer
372            .upload_text(size, &raster.pixels.rgba8)
373            .map_err(TextError::Render)?;
374        let background = raster
375            .background
376            .as_deref()
377            .map(|rgba8| renderer.upload_text(size, rgba8))
378            .transpose()
379            .map_err(TextError::Render)?;
380        // Pixels are `Send` on native targets, where hosts move the store between threads; wasm
381        // is single-threaded.
382        #[cfg_attr(target_arch = "wasm32", allow(clippy::arc_with_non_send_sync))]
383        let (texture, background) = (Arc::new(texture), background.map(Arc::new));
384        self.entries.insert(
385            key,
386            TextEntry {
387                texture,
388                background,
389                shadows: draw.shadows.clone(),
390                content,
391                width: texture_size.width,
392                height: texture_size.height,
393                margin,
394                corner,
395                last_used: self.frame,
396            },
397        );
398        Ok(())
399    }
400
401    /// Resolves `plan` at `time` and `size` and rasterizes its texts. A held layout only
402    /// re-rasterizes evicted texts.
403    fn prepare_layout(
404        &mut self,
405        renderer: &dyn TextUpload,
406        plan: &LayoutPlan,
407        time: alpha2_time::MediaTime,
408        size: RenderSize,
409    ) -> Result<(), TextError> {
410        let evaluated = plan.evaluate(time);
411        let key = layout_key(evaluated.key, size);
412        if let Some(entry) = self.layouts.get_mut(&key) {
413            entry.last_used = self.frame;
414            let requests = entry.requests.clone();
415            for (text, request) in &requests {
416                match self.entries.get_mut(text) {
417                    Some(held) => held.last_used = self.frame,
418                    None => self.rasterize(renderer, *text, request)?,
419                }
420            }
421            return Ok(());
422        }
423        self.resolves += 1;
424        let frame = self.frame;
425        let picture = picture(size);
426        let shaped =
427            alpha2_layout::shape_texts(&evaluated, picture, |request| self.shape(request, frame))
428                .map_err(TextError::Raster)?;
429        let mut resolved = alpha2_layout::resolve(&evaluated, picture, &shaped);
430        alpha2_layout::fit_texts(&evaluated, &mut resolved, picture, |request| {
431            self.shape(request, frame)
432        })
433        .map_err(TextError::Raster)?;
434        let (texts, requests) = alpha2_layout::layout_texts(&evaluated, &resolved, picture);
435        let mut boxes = Vec::with_capacity(texts.len());
436        for text in &texts {
437            boxes.push(match text {
438                None => None,
439                Some(text_key) => {
440                    let draw = &requests
441                        .iter()
442                        .find(|(key, _)| key == text_key)
443                        .expect("a request per text")
444                        .1;
445                    match self.entries.get_mut(text_key) {
446                        Some(held) => held.last_used = self.frame,
447                        None => self.rasterize(renderer, *text_key, draw)?,
448                    }
449                    let entry = &self.entries[text_key];
450                    Some(crate::layout::paint::TextBox {
451                        corner: entry.corner,
452                        size: [entry.width, entry.height],
453                    })
454                }
455            });
456        }
457        let items = crate::layout::paint::paint_list(&evaluated, &resolved, size, &boxes);
458        self.layouts.insert(
459            key,
460            LayoutEntry {
461                prepared: Arc::new(PreparedLayout { items, texts }),
462                requests,
463                last_used: self.frame,
464            },
465        );
466        Ok(())
467    }
468
469    fn shape(
470        &mut self,
471        request: &TextRasterRequest,
472        frame: u64,
473    ) -> Result<Arc<ShapedText>, TextRasterError> {
474        let key = shaped_key(request);
475        if let Some(entry) = self.shaped.get_mut(&key) {
476            entry.last_used = frame;
477            return Ok(Arc::clone(&entry.shaped));
478        }
479        let shaped = Arc::new(self.rasterizer.shape(request)?);
480        if self.shaped.len() >= RETAINED_SHAPED
481            && let Some(oldest) = self
482                .shaped
483                .iter()
484                .min_by_key(|(_, entry)| entry.last_used)
485                .map(|(key, _)| *key)
486        {
487            self.shaped.remove(&oldest);
488        }
489        self.shaped.insert(
490            key,
491            ShapedEntry {
492                shaped: Arc::clone(&shaped),
493                last_used: frame,
494            },
495        );
496        Ok(shaped)
497    }
498
499    /// Layout resolutions so far, held or not.
500    #[cfg(test)]
501    #[must_use]
502    pub(crate) const fn layout_resolves(&self) -> u64 {
503        self.resolves
504    }
505
506    /// The prepared layout with `key`, as [`layout_key`] names it.
507    #[must_use]
508    pub fn layout(&self, key: u128) -> Option<Arc<PreparedLayout>> {
509        self.layouts
510            .get(&key)
511            .map(|entry| Arc::clone(&entry.prepared))
512    }
513
514    /// [`crate::measure_layout`] with these fonts.
515    ///
516    /// # Errors
517    /// Returns [`TextError::Raster`] as [`Self::prepare`] would.
518    pub fn measure_layout(
519        &self,
520        root: &alpha2_model::LayoutNode,
521        time: alpha2_time::MediaTime,
522        size: RenderSize,
523        canvas: (u32, u32),
524    ) -> Result<crate::LayoutBounds, TextError> {
525        crate::measure_layout(&self.rasterizer, root, time, picture(size), canvas)
526            .map_err(TextError::Raster)
527    }
528
529    /// [`Self::prepare`] for `project` at `time`; skips evaluation when the project draws no text
530    /// ([`crate::EngineProject::draws_text`]).
531    ///
532    /// # Errors
533    /// Returns [`crate::EngineError::Evaluate`] or
534    /// [`crate::EngineError::Text`].
535    pub fn prepare_at(
536        &mut self,
537        renderer: &dyn TextUpload,
538        project: &crate::EngineProject,
539        time: alpha2_time::MediaTime,
540        size: RenderSize,
541    ) -> Result<(), crate::EngineError> {
542        if !project.draws_text() {
543            return Ok(());
544        }
545        let frame = project.evaluate(time)?;
546        self.prepare(renderer, &frame, size)
547            .map_err(crate::EngineError::Text)
548    }
549
550    /// [`crate::measure_text`] with these fonts.
551    ///
552    /// # Errors
553    /// Returns [`TextError::Raster`] as [`Self::prepare`] would for the text.
554    pub fn measure(
555        &self,
556        text: &alpha2_layout::TextAt<'_>,
557        style: &TextStyle,
558        size: RenderSize,
559    ) -> Result<TextBounds, TextError> {
560        crate::measure_text(&self.rasterizer, text, style, picture(size)).map_err(TextError::Raster)
561    }
562
563    /// The prepared text with `key`, as [`crate::text_key`] names it.
564    #[must_use]
565    pub fn get(&self, key: u64) -> Option<TextTexture<'_>> {
566        self.entries.get(&key).map(|entry| TextTexture {
567            texture: entry.texture.view(),
568            width: entry.width,
569            height: entry.height,
570            margin: entry.margin,
571            cache_key: Some(self.cache_key(entry.content)),
572            background: entry.background.as_ref().map(|background| {
573                (
574                    background.view(),
575                    Some(self.background_cache_key(entry.content)),
576                )
577            }),
578            shadows: &entry.shadows,
579        })
580    }
581
582    /// Result cache key of text `key`: font set and domain in the high half, text in the low.
583    fn cache_key(&self, key: u64) -> RenderCacheKey {
584        let high = TEXT_CACHE_DOMAIN ^ self.font_set;
585        RenderCacheKey::from_value((u128::from(high) << 64) | u128::from(key))
586    }
587
588    /// [`Self::cache_key`] in a separate domain for the background plane.
589    fn background_cache_key(&self, key: u64) -> RenderCacheKey {
590        let high = (TEXT_CACHE_DOMAIN ^ self.font_set) ^ (1 << 62);
591        RenderCacheKey::from_value((u128::from(high) << 64) | u128::from(key))
592    }
593}
594
595/// A text a frame may draw, with the time its animators are keyed in.
596#[derive(Copy, Clone, Debug)]
597pub(crate) struct FrameText<'f> {
598    pub(crate) content: &'f TextContent,
599    pub(crate) style: &'f TextStyle,
600    pub(crate) time: alpha2_time::MediaTime,
601}
602
603/// Every text `frame` may draw: captions, then text generators of drawn clips. Duplicates repeat.
604pub(crate) fn frame_texts<'f>(frame: &'f FrameDesc<'_>) -> impl Iterator<Item = FrameText<'f>> {
605    let captions = frame.captions.iter().map(|caption| FrameText {
606        content: caption.text,
607        style: caption.style,
608        time: caption.local_time,
609    });
610    let generators = frame
611        .visual
612        .iter()
613        .filter(|clip| frame.draws(clip))
614        .flat_map(|clip| {
615            let own = clip
616                .generator
617                .map(|generator| (generator, clip.source_time));
618            let steps = clip
619                .composition
620                .iter()
621                .chain(&clip.source_composition)
622                .flat_map(|composition| {
623                    let time = composition.time();
624                    composition
625                        .plan()
626                        .steps
627                        .iter()
628                        .filter_map(move |step| match &step.op {
629                            StepOp::Generator {
630                                generator, start, ..
631                            } => Some((generator, generator_time(step.time(time), *start))),
632                            _ => None,
633                        })
634                });
635            own.into_iter().chain(steps)
636        })
637        .filter_map(|(generator, time)| match generator {
638            Generator::Text { text, style } => Some(FrameText {
639                content: text,
640                style,
641                time,
642            }),
643            _ => None,
644        });
645    captions.chain(generators)
646}
647
648/// A composition generator step's picture time: step time plus start.
649pub(crate) const fn generator_time(
650    step: alpha2_time::MediaTime,
651    start: alpha2_time::MediaTime,
652) -> alpha2_time::MediaTime {
653    alpha2_time::MediaTime(step.ticks().saturating_add(start.ticks()))
654}
655
656/// `key` mixed with an animation's state `hash`: FNV-1a, never zero.
657fn mix_key(key: u64, hash: u64) -> u64 {
658    let mut mixed = key;
659    for byte in hash.to_le_bytes() {
660        mixed = (mixed ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
661    }
662    mixed.max(1)
663}
664
665/// Key for `request` without animators, from every field but the content version.
666fn text_key_of(request: &TextRasterRequest) -> u64 {
667    alpha2_layout::layout_text_key(
668        &TextRasterRequest {
669            content_version: 1,
670            ..request.clone()
671        },
672        &[],
673        &[],
674    )
675}
676
677/// A host's frame provider combined with its text store.
678pub struct FramesWithText<'a> {
679    frames: &'a dyn crate::FrameProvider,
680    texts: &'a TextTextures,
681}
682
683impl<'a> FramesWithText<'a> {
684    /// `frames` with the texts `texts` holds.
685    #[must_use]
686    pub fn new(frames: &'a dyn crate::FrameProvider, texts: &'a TextTextures) -> Self {
687        Self { frames, texts }
688    }
689}
690
691impl crate::FrameProvider for FramesWithText<'_> {
692    fn texture_for(
693        &self,
694        source: &alpha2_media::SourceId,
695        time: alpha2_time::MediaTime,
696    ) -> Option<SourceView<'_>> {
697        self.frames.texture_for(source, time)
698    }
699
700    fn pending_source_work(
701        &self,
702        source: &alpha2_media::SourceId,
703        time: alpha2_time::MediaTime,
704    ) -> Option<&alpha2_render::PendingSourceWork> {
705        self.frames.pending_source_work(source, time)
706    }
707
708    fn source_key(
709        &self,
710        source: &alpha2_media::SourceId,
711        time: alpha2_time::MediaTime,
712    ) -> Option<alpha2_render::RenderCacheKey> {
713        self.frames.source_key(source, time)
714    }
715
716    fn text(&self, key: u64) -> Option<TextTexture<'_>> {
717        self.texts.get(key)
718    }
719
720    fn layout(&self, key: u128) -> Option<Arc<PreparedLayout>> {
721        self.texts.layout(key)
722    }
723}
724
725/// Every layout `frame` may draw, with its picture time.
726pub(crate) fn frame_layouts<'f>(
727    frame: &'f FrameDesc<'_>,
728) -> impl Iterator<Item = (&'f LayoutPlan, alpha2_time::MediaTime)> {
729    frame
730        .visual
731        .iter()
732        .filter(|clip| frame.draws(clip))
733        .flat_map(|clip| {
734            let own = clip
735                .plan
736                .and_then(GeneratorPlan::layout)
737                .map(|plan| (plan, clip.source_time));
738            let steps = clip
739                .composition
740                .iter()
741                .chain(&clip.source_composition)
742                .flat_map(|composition| {
743                    let time = composition.time();
744                    composition
745                        .plan()
746                        .steps
747                        .iter()
748                        .filter_map(move |step| match &step.op {
749                            StepOp::Generator {
750                                plan: Some(plan),
751                                start,
752                                ..
753                            } => plan.layout().map(|plan| {
754                                (
755                                    plan,
756                                    alpha2_time::MediaTime(
757                                        step.time(time).ticks().saturating_add(start.ticks()),
758                                    ),
759                                )
760                            }),
761                            _ => None,
762                        })
763                });
764            own.into_iter().chain(steps)
765        })
766}
767
768/// A layout's identity at a render size. Equal keys draw alike with the same fonts.
769#[must_use]
770pub fn layout_key(evaluated: u128, size: RenderSize) -> u128 {
771    let mut hash = alpha2_geometry::StableHash::new();
772    hash.bytes(b"layout");
773    hash.bytes(&evaluated.to_le_bytes());
774    hash.u32(size.width);
775    hash.u32(size.height);
776    hash.finish()
777}