Skip to main content

alpha2_engine/
frame.rs

1//! Rendering of evaluated timeline frames.
2//!
3//! The renderer knows render graphs, not timelines. This module checks that every source frame
4//! of an evaluated [`FrameDesc`] has arrived, compiles it into a [`RenderGraph`] and submits it.
5
6use alpha2_eval::{
7    ActiveClip, ActiveComposition, ActiveEffect, ActiveTransition, EvaluatedVisual, FrameDesc,
8    GeneratorPlan, SampleContext, ShapesPlan, StepOp, sample_scalar, sample_visual,
9};
10use alpha2_media::{PixelLayout, SourceId, YuvEncoding};
11use alpha2_model::{
12    ClipBlendMode, EffectValue, Generator, MaskMode, MatteMode, Rgb, ShapeMask, TextStyle,
13};
14use alpha2_render::{
15    BlendMode, CacheIntent, Color, CpuImage, CpuRenderer, EffectCatalog, EffectId, EffectInputs,
16    EffectParams, EffectResources, EffectRuntime, FrameSubmitTimings, GENERATOR_EFFECT_ID,
17    GraphError, GraphLayer, LayerTransform, MASK_COMBINE_EFFECT_IDS, MASK_COMBINE_NAMES,
18    MAX_SHAPE_MASKS, Nv12PlaneTargets, ParamSpec, ParamType, ParamValue, PendingSourceWork,
19    PlaneTarget, RenderCacheKey, RenderControls, RenderError, RenderGraph, RenderNodeId,
20    RenderNodeKind, RenderSize, RenderedTexture, Renderer, SourceView, TRACK_MATTE_EFFECT_ID,
21    Yuv420pReadback, Yuv420pTargets,
22};
23use alpha2_time::MediaTime;
24
25use crate::TextTexture;
26use crate::layout::draw::LaidOut;
27use std::collections::{HashMap, HashSet};
28use std::sync::Arc;
29use std::time::Duration;
30use web_time::Instant;
31
32/// Supplies decoded source frames as GPU textures to the renderer.
33///
34/// Implementations own decode caches and texture lifetimes and lend textures as
35/// [`SourceView`]s. Textures must hold premultiplied, sRGB-encoded RGBA in a non-sRGB GPU
36/// format, as returned by `Renderer::upload_rgba8` or `Renderer::render_yuv420p`.
37pub trait FrameProvider {
38    /// Returns a texture for `source` at the requested source timestamp.
39    ///
40    /// The frame presented at `time`, resolved as [`alpha2_media::Decoder::seek`] does (last
41    /// timestamp at or before `time` plus the presentation slack, clamped to the stream).
42    ///
43    /// `None` means the frame has not arrived; players may hold the previous output while
44    /// exporters wait and retry.
45    fn texture_for(&self, source: &SourceId, time: MediaTime) -> Option<SourceView<'_>>;
46
47    /// A key for the texture [`Self::texture_for`] returns, promising its pixels depend on
48    /// nothing outside the key (content, frame, decode and conversion). Keyed sources let drawn
49    /// results be reused ([`alpha2_render::Renderer::set_result_cache_budget`]); the default
50    /// `None` disables reuse.
51    fn source_key(&self, _source: &SourceId, _time: MediaTime) -> Option<RenderCacheKey> {
52        None
53    }
54
55    /// Returns presentation work that has not yet been submitted for this
56    /// physical source texture. The default covers already-ready textures.
57    fn pending_source_work(
58        &self,
59        _source: &SourceId,
60        _time: MediaTime,
61    ) -> Option<&PendingSourceWork> {
62        None
63    }
64
65    /// Returns the prepared text [`crate::text_key`] names. With the default (none), a frame
66    /// showing text fails with [`RenderError::MissingText`].
67    fn text(&self, _key: u64) -> Option<TextTexture<'_>> {
68        None
69    }
70
71    /// Returns the prepared layout [`crate::layout_key`] names. With the default (none), a frame
72    /// showing a layout fails with [`RenderError::MissingText`].
73    fn layout(&self, _key: u128) -> Option<std::sync::Arc<crate::PreparedLayout>> {
74        None
75    }
76}
77
78/// Outcome of one render attempt when sources may arrive asynchronously.
79#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct RenderReport {
81    /// Sources whose requested frame was unavailable.
82    pub missing_sources: Vec<SourceId>,
83}
84
85impl RenderReport {
86    /// Returns whether every requested source frame was available.
87    #[must_use]
88    pub fn is_complete(&self) -> bool {
89        self.missing_sources.is_empty()
90    }
91}
92
93/// Result of attempting to render one evaluated timeline frame.
94#[derive(Debug)]
95pub struct FrameRender<I = RenderedTexture> {
96    /// Availability information collected before anything is drawn.
97    pub report: RenderReport,
98    /// Rendered output, absent when one or more source frames are unavailable.
99    pub texture: Option<I>,
100}
101
102impl<I> FrameRender<I> {
103    /// Returns whether a texture was rendered from a complete source set.
104    #[must_use]
105    pub fn is_complete(&self) -> bool {
106        self.texture.is_some()
107    }
108}
109
110/// Result of rendering and scheduling one frame for planar YUV420 readback.
111#[derive(Debug)]
112pub struct FrameYuv420pRender {
113    /// Availability information collected before any GPU work is submitted.
114    pub report: RenderReport,
115    /// Submitted readback, absent when source frames are unavailable.
116    pub readback: Option<Yuv420pReadback>,
117}
118
119impl FrameYuv420pRender {
120    /// Returns whether a complete frame was submitted for readback.
121    #[must_use]
122    pub fn is_complete(&self) -> bool {
123        self.readback.is_some()
124    }
125}
126
127/// Result of rendering one frame into caller-owned NV12 plane textures.
128#[derive(Debug)]
129#[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
130pub struct FrameNv12Render {
131    /// Availability information collected before any GPU work is submitted.
132    pub report: RenderReport,
133    /// Whether the pack was submitted; false when a source was missing.
134    pub submitted: bool,
135}
136
137/// One evaluated frame compiled into a render graph, not yet submitted.
138#[derive(Debug)]
139pub struct FrameGraph<'a> {
140    /// Availability information collected before the graph was built.
141    pub report: RenderReport,
142    /// The frame's graph, absent when source frames are unavailable.
143    pub graph: Option<RenderGraph<'a>>,
144    /// Unsubmitted presentation work behind the source textures, folded into the submission.
145    pub pending: Vec<&'a PendingSourceWork>,
146}
147
148/// Timeline-frame rendering on the GPU [`Renderer`] or the [`alpha2_render::CpuRenderer`].
149/// GPU-only readback and encoder paths are in [`GpuFrameRenderer`].
150pub trait FrameRenderer: EffectCatalog + RenderControls {
151    /// A [`RenderedTexture`] on the GPU, an [`alpha2_render::CpuImage`] on the CPU.
152    type Image;
153
154    /// Resolves the textures required by an evaluated frame.
155    ///
156    /// Performs no fallback; players and exporters apply their own policy.
157    #[must_use]
158    fn inspect_frame(&self, frame: &FrameDesc, frames: &dyn FrameProvider) -> RenderReport {
159        available_textures(frame, frames).0
160    }
161
162    /// Compiles one evaluator result into a render graph without drawing.
163    ///
164    /// An incomplete source set returns its report and no graph.
165    ///
166    /// # Errors
167    /// Returns [`RenderError`] when an effect is unknown or a visual or
168    /// caption is invalid.
169    fn build_frame_graph<'a>(
170        &self,
171        size: RenderSize,
172        frame: &'a FrameDesc<'a>,
173        frames: &'a dyn FrameProvider,
174    ) -> Result<FrameGraph<'a>, RenderError>;
175
176    /// Draws a graph from [`Self::build_frame_graph`] with its pending source work.
177    ///
178    /// # Errors
179    /// Returns [`RenderError`] when a pass fails.
180    fn render_frame_graph(
181        &self,
182        graph: &RenderGraph<'_>,
183        pending: &[&PendingSourceWork],
184    ) -> Result<Self::Image, RenderError>;
185
186    /// Renders one pure evaluator result using sources supplied by the host.
187    ///
188    /// An incomplete source set returns its report and draws nothing.
189    ///
190    /// # Errors
191    /// Returns [`RenderError`] when a visual or render target is invalid.
192    fn render_frame(
193        &self,
194        size: RenderSize,
195        frame: &FrameDesc,
196        frames: &dyn FrameProvider,
197    ) -> Result<FrameRender<Self::Image>, RenderError> {
198        let FrameGraph {
199            report,
200            graph,
201            pending,
202        } = self.build_frame_graph(size, frame, frames)?;
203        let texture = match graph {
204            Some(graph) => Some(self.render_frame_graph(&graph, &pending)?),
205            None => None,
206        };
207        Ok(FrameRender { report, texture })
208    }
209
210    /// Renders one evaluator result into caller-owned planar YUV420 `targets`.
211    ///
212    /// An incomplete source set writes nothing. The output size must be even.
213    ///
214    /// # Errors
215    /// Returns [`RenderError`] for an invalid graph or a target too small.
216    fn render_frame_into_yuv420p(
217        &self,
218        size: RenderSize,
219        frame: &FrameDesc,
220        frames: &dyn FrameProvider,
221        encoding: YuvEncoding,
222        targets: &mut Yuv420pTargets<'_>,
223    ) -> Result<RenderReport, RenderError>;
224
225    /// [`Self::render_frame_into_yuv420p`] for any `layout`, one target per plane in
226    /// [`PixelLayout::planes`] order.
227    ///
228    /// # Errors
229    /// Returns [`RenderError`] for an invalid graph, a picture the layout
230    /// cannot subsample, or a target too small.
231    fn render_frame_into_planes(
232        &self,
233        size: RenderSize,
234        frame: &FrameDesc,
235        frames: &dyn FrameProvider,
236        encoding: YuvEncoding,
237        layout: PixelLayout,
238        targets: &mut [PlaneTarget<'_>],
239    ) -> Result<RenderReport, RenderError>;
240}
241
242fn yuv420p_targets<'a>(
243    targets: &'a mut [PlaneTarget<'_>],
244) -> Result<Yuv420pTargets<'a>, RenderError> {
245    let [y, u, v] = targets else {
246        return Err(RenderError::TextureReadback(
247            alpha2_render::ReadbackFailure::Layout,
248        ));
249    };
250    Ok(Yuv420pTargets {
251        y: y.reborrow(),
252        u: u.reborrow(),
253        v: v.reborrow(),
254    })
255}
256
257/// GPU frame paths that end on the GPU: an unmapped YUV420 readback or encoder NV12 planes.
258pub trait GpuFrameRenderer: FrameRenderer<Image = RenderedTexture> {
259    /// Renders and converts to YUV420 in one command buffer.
260    ///
261    /// An incomplete source set submits nothing. The output size must be even.
262    ///
263    /// # Errors
264    /// Returns [`RenderError`] for invalid graph, target, or YUV layout data.
265    fn render_frame_yuv420p(
266        &self,
267        size: RenderSize,
268        frame: &FrameDesc,
269        frames: &dyn FrameProvider,
270        encoding: YuvEncoding,
271    ) -> Result<FrameYuv420pRender, RenderError>;
272
273    /// Renders one frame for YUV420 readback and reports where the call went.
274    ///
275    /// Same output as [`GpuFrameRenderer::render_frame_yuv420p`], with stage spans written to
276    /// `timings`.
277    ///
278    /// # Errors
279    /// Returns [`RenderError`] for invalid graph, target, or YUV layout data.
280    fn render_frame_yuv420p_timed(
281        &self,
282        size: RenderSize,
283        frame: &FrameDesc,
284        frames: &dyn FrameProvider,
285        encoding: YuvEncoding,
286        timings: &mut FrameSubmitTimings,
287    ) -> Result<FrameYuv420pRender, RenderError>;
288
289    /// Renders one frame and packs it straight into caller-owned NV12 plane
290    /// textures, with no readback.
291    ///
292    /// [`GpuFrameRenderer::render_frame_yuv420p_timed`] ending in two textures for a hardware
293    /// encoder instead of a staging buffer. An incomplete source set submits nothing.
294    ///
295    /// # Errors
296    /// Returns [`RenderError`] for invalid graph or plane-target data.
297    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
298    fn render_frame_nv12_timed(
299        &self,
300        size: RenderSize,
301        frame: &FrameDesc,
302        frames: &dyn FrameProvider,
303        planes: Nv12PlaneTargets<'_>,
304        encoding: YuvEncoding,
305        timings: &mut FrameSubmitTimings,
306    ) -> Result<FrameNv12Render, RenderError>;
307}
308
309/// [`FrameRenderer::build_frame_graph`] for any renderer; only the effect catalog differs.
310fn build_frame_graph<'a>(
311    catalog: &dyn EffectCatalog,
312    size: RenderSize,
313    frame: &'a FrameDesc<'a>,
314    frames: &'a dyn FrameProvider,
315) -> Result<FrameGraph<'a>, RenderError> {
316    validate_project_effects(catalog, frame)?;
317    let (report, mut available) = available_textures(frame, frames);
318    if !report.is_complete() {
319        return Ok(FrameGraph {
320            report,
321            graph: None,
322            pending: Vec::new(),
323        });
324    }
325    attach_texts(&mut available, frames, size);
326    let captions = caption_layers(frame, frames, size)?;
327    let graph = frame_graph(catalog, size, frame, &available, &captions)?;
328    Ok(FrameGraph {
329        report,
330        graph: Some(graph),
331        pending: pending_source_work(&available, frames),
332    })
333}
334
335impl FrameRenderer for Renderer {
336    type Image = RenderedTexture;
337
338    fn build_frame_graph<'a>(
339        &self,
340        size: RenderSize,
341        frame: &'a FrameDesc<'a>,
342        frames: &'a dyn FrameProvider,
343    ) -> Result<FrameGraph<'a>, RenderError> {
344        build_frame_graph(self, size, frame, frames)
345    }
346
347    fn render_frame_graph(
348        &self,
349        graph: &RenderGraph<'_>,
350        pending: &[&PendingSourceWork],
351    ) -> Result<RenderedTexture, RenderError> {
352        self.render_graph(graph, pending)
353    }
354
355    fn render_frame_into_yuv420p(
356        &self,
357        size: RenderSize,
358        frame: &FrameDesc,
359        frames: &dyn FrameProvider,
360        encoding: YuvEncoding,
361        targets: &mut Yuv420pTargets<'_>,
362    ) -> Result<RenderReport, RenderError> {
363        let render = self.render_frame_yuv420p(size, frame, frames, encoding)?;
364        if let Some(readback) = render.readback {
365            // A browser maps buffers only on its event loop, which a blocking call never yields to.
366            #[cfg(target_arch = "wasm32")]
367            {
368                drop((readback, targets));
369                return Err(RenderError::TextureReadback(
370                    alpha2_render::ReadbackFailure::NotMapped,
371                ));
372            }
373            #[cfg(not(target_arch = "wasm32"))]
374            {
375                readback.wait_ready()?;
376                readback.finish_into(targets)?;
377            }
378        }
379        Ok(render.report)
380    }
381
382    fn render_frame_into_planes(
383        &self,
384        size: RenderSize,
385        frame: &FrameDesc,
386        frames: &dyn FrameProvider,
387        encoding: YuvEncoding,
388        layout: PixelLayout,
389        targets: &mut [PlaneTarget<'_>],
390    ) -> Result<RenderReport, RenderError> {
391        if layout.is_yuv420p() {
392            let mut planes = yuv420p_targets(targets)?;
393            return self.render_frame_into_yuv420p(size, frame, frames, encoding, &mut planes);
394        }
395        let render = self.render_frame(size, frame, frames)?;
396        if let Some(texture) = render.texture {
397            let readback = self.begin_layout_readback(&texture, encoding, layout)?;
398            // A browser cannot block on a mapping.
399            #[cfg(target_arch = "wasm32")]
400            {
401                drop((readback, targets));
402                return Err(RenderError::TextureReadback(
403                    alpha2_render::ReadbackFailure::NotMapped,
404                ));
405            }
406            #[cfg(not(target_arch = "wasm32"))]
407            {
408                readback.wait_ready()?;
409                readback.finish_into_planes(targets)?;
410            }
411        }
412        Ok(render.report)
413    }
414}
415
416impl FrameRenderer for CpuRenderer {
417    type Image = Arc<CpuImage>;
418
419    fn build_frame_graph<'a>(
420        &self,
421        size: RenderSize,
422        frame: &'a FrameDesc<'a>,
423        frames: &'a dyn FrameProvider,
424    ) -> Result<FrameGraph<'a>, RenderError> {
425        build_frame_graph(self, size, frame, frames)
426    }
427
428    fn render_frame_graph(
429        &self,
430        graph: &RenderGraph<'_>,
431        _pending: &[&PendingSourceWork],
432    ) -> Result<Arc<CpuImage>, RenderError> {
433        self.execute_graph(graph)
434            .map_err(GraphError::into_render_error)
435    }
436
437    fn render_frame_into_yuv420p(
438        &self,
439        size: RenderSize,
440        frame: &FrameDesc,
441        frames: &dyn FrameProvider,
442        encoding: YuvEncoding,
443        targets: &mut Yuv420pTargets<'_>,
444    ) -> Result<RenderReport, RenderError> {
445        let FrameGraph { report, graph, .. } = self.build_frame_graph(size, frame, frames)?;
446        if let Some(graph) = graph {
447            self.render_graph_into_yuv420p(&graph, encoding, targets)?;
448        }
449        Ok(report)
450    }
451
452    fn render_frame_into_planes(
453        &self,
454        size: RenderSize,
455        frame: &FrameDesc,
456        frames: &dyn FrameProvider,
457        encoding: YuvEncoding,
458        layout: PixelLayout,
459        targets: &mut [PlaneTarget<'_>],
460    ) -> Result<RenderReport, RenderError> {
461        if layout.is_yuv420p() {
462            let mut planes = yuv420p_targets(targets)?;
463            return self.render_frame_into_yuv420p(size, frame, frames, encoding, &mut planes);
464        }
465        let render = self.render_frame(size, frame, frames)?;
466        if let Some(image) = render.texture {
467            self.pack_image(&image, encoding, layout, targets)?;
468        }
469        Ok(render.report)
470    }
471}
472
473impl GpuFrameRenderer for Renderer {
474    fn render_frame_yuv420p(
475        &self,
476        size: RenderSize,
477        frame: &FrameDesc,
478        frames: &dyn FrameProvider,
479        encoding: YuvEncoding,
480    ) -> Result<FrameYuv420pRender, RenderError> {
481        render_frame_yuv420p_measured(self, size, frame, frames, encoding, None)
482    }
483
484    fn render_frame_yuv420p_timed(
485        &self,
486        size: RenderSize,
487        frame: &FrameDesc,
488        frames: &dyn FrameProvider,
489        encoding: YuvEncoding,
490        timings: &mut FrameSubmitTimings,
491    ) -> Result<FrameYuv420pRender, RenderError> {
492        render_frame_yuv420p_measured(self, size, frame, frames, encoding, Some(timings))
493    }
494
495    #[cfg_attr(not(feature = "wgpu-interop"), doc(hidden))]
496    fn render_frame_nv12_timed(
497        &self,
498        size: RenderSize,
499        frame: &FrameDesc,
500        frames: &dyn FrameProvider,
501        planes: Nv12PlaneTargets<'_>,
502        encoding: YuvEncoding,
503        timings: &mut FrameSubmitTimings,
504    ) -> Result<FrameNv12Render, RenderError> {
505        let mut clock = StageClock::start(true);
506        let mut collected = FrameSubmitTimings::default();
507        let FrameGraph {
508            report,
509            graph,
510            pending,
511        } = self.build_frame_graph(size, frame, frames)?;
512        collected.graph_build = clock.lap();
513        let submitted = graph.is_some();
514        if let Some(graph) = graph {
515            self.render_graph_nv12_timed(&graph, &pending, planes, encoding, &mut collected)?;
516        }
517        *timings = collected;
518        Ok(FrameNv12Render { report, submitted })
519    }
520}
521
522fn render_frame_yuv420p_measured(
523    renderer: &Renderer,
524    size: RenderSize,
525    frame: &FrameDesc,
526    frames: &dyn FrameProvider,
527    encoding: YuvEncoding,
528    timings: Option<&mut FrameSubmitTimings>,
529) -> Result<FrameYuv420pRender, RenderError> {
530    let measure = timings.is_some();
531    let mut clock = StageClock::start(measure);
532    let mut collected = FrameSubmitTimings::default();
533    let FrameGraph {
534        report,
535        graph,
536        pending,
537    } = renderer.build_frame_graph(size, frame, frames)?;
538    collected.graph_build = clock.lap();
539    let readback = match graph {
540        Some(graph) if measure => {
541            Some(renderer.render_graph_yuv420p_timed(&graph, &pending, encoding, &mut collected)?)
542        }
543        Some(graph) => Some(renderer.render_graph_yuv420p(&graph, &pending, encoding)?),
544        None => None,
545    };
546    if let Some(timings) = timings {
547        *timings = collected;
548    }
549    Ok(FrameYuv420pRender { report, readback })
550}
551
552/// A lap timer that reads no clock unless a caller asked for timings.
553#[derive(Copy, Clone)]
554struct StageClock(Option<Instant>);
555
556impl StageClock {
557    fn start(enabled: bool) -> Self {
558        Self(enabled.then(Instant::now))
559    }
560
561    fn lap(&mut self) -> Duration {
562        let Some(mark) = self.0 else {
563            return Duration::ZERO;
564        };
565        let now = Instant::now();
566        self.0 = Some(now);
567        now.duration_since(mark)
568    }
569}
570
571fn validate_project_effects(
572    renderer: &dyn EffectCatalog,
573    frame: &FrameDesc,
574) -> Result<(), RenderError> {
575    require_effects(renderer, frame_effects(frame)).map_err(|_| RenderError::UnknownEffect)
576}
577
578/// Every effect `frame` draws, by id and version.
579fn frame_effects<'a>(frame: &'a FrameDesc) -> impl Iterator<Item = (&'a str, u32)> {
580    let composition_effects = frame
581        .visual
582        .iter()
583        .flat_map(|clip| clip.composition.into_iter().chain(clip.source_composition))
584        .flat_map(|composition| composition.plan().effects())
585        .map(|effect| (effect.id.as_str(), effect.version));
586    let transition_effects = frame
587        .transitions
588        .iter()
589        .map(|transition| (transition.effect.id(), transition.effect.version()));
590    composition_effects.chain(transition_effects)
591}
592
593/// Checks that `renderer` draws every effect `frame` uses, naming the first missing one
594/// (unlike the [`RenderError`] that [`FrameRenderer`] returns).
595///
596/// # Errors
597/// Returns [`crate::EngineError::UnregisteredEffect`].
598pub fn check_frame_effects<C: EffectCatalog + ?Sized>(
599    renderer: &C,
600    frame: &FrameDesc,
601) -> Result<(), crate::EngineError> {
602    require_effects(renderer, frame_effects(frame))
603}
604
605pub(crate) fn require_effects<'a, C: EffectCatalog + ?Sized>(
606    renderer: &C,
607    effects: impl IntoIterator<Item = (&'a str, u32)>,
608) -> Result<(), crate::EngineError> {
609    for (effect, version) in effects {
610        if renderer.project_effect_id(effect, version).is_none() {
611            return Err(crate::EngineError::UnregisteredEffect {
612                effect: effect.to_owned(),
613                version,
614            });
615        }
616    }
617    Ok(())
618}
619
620fn pending_source_work<'a>(
621    available: &[(&ActiveClip, ClipFrames<'_>)],
622    frames: &'a dyn FrameProvider,
623) -> Vec<&'a PendingSourceWork> {
624    let mut work = Vec::new();
625    for (clip, textures) in available {
626        if textures.source.is_some() {
627            work.extend(frames.pending_source_work(clip.source_id, clip.source_time));
628        }
629        for composition in clip.composition.iter().chain(&clip.source_composition) {
630            for (_, source, time) in composition.media() {
631                work.extend(frames.pending_source_work(source, time));
632            }
633        }
634    }
635    work
636}
637
638#[derive(Copy, Clone, Debug)]
639struct Frame<'t> {
640    view: SourceView<'t>,
641    key: Option<RenderCacheKey>,
642}
643
644impl<'t> Frame<'t> {
645    fn add_to(self, graph: &mut RenderGraph<'t>) -> RenderNodeId {
646        match self.key {
647            Some(key) => graph.add_source_with_key(self.view, key),
648            None => graph.add_source(self.view),
649        }
650    }
651}
652
653/// A text generator's prepared texture, placed on a transparent canvas-sized picture.
654#[derive(Copy, Clone, Debug)]
655struct PlacedText<'t> {
656    texture: TextTexture<'t>,
657    visual: LayerTransform,
658}
659
660impl<'t> PlacedText<'t> {
661    fn add_to(self, graph: &mut RenderGraph<'t>) -> Result<RenderNodeId, RenderError> {
662        let layer = text_layer(graph, self.texture, self.visual)?;
663        graph
664            .add_composite(vec![layer])
665            .map_err(GraphError::into_render_error)
666    }
667}
668
669fn keyed_source<'t>(
670    graph: &mut RenderGraph<'t>,
671    view: SourceView<'t>,
672    key: Option<RenderCacheKey>,
673) -> RenderNodeId {
674    match key {
675        Some(key) => graph.add_source_with_key(view, key),
676        None => graph.add_source(view),
677    }
678}
679
680/// A prepared text placed on the graph's picture by `visual`, as one layer.
681///
682/// Without shadows the layer is the keyed texture itself. With shadows it is a new picture:
683/// background boxes, then shadows (last listed lowest), then glyphs. Shadows are cast by the
684/// placed glyphs, so offset and blur are in picture pixels.
685pub(crate) fn text_layer<'t>(
686    graph: &mut RenderGraph<'t>,
687    texture: TextTexture<'t>,
688    visual: LayerTransform,
689) -> Result<GraphLayer, RenderError> {
690    let glyphs = keyed_source(graph, texture.texture, texture.cache_key);
691    if texture.shadows.is_empty() {
692        return Ok(GraphLayer {
693            source: glyphs,
694            visual,
695            blend_mode: BlendMode::Normal,
696        });
697    }
698    let placed = graph
699        .add_composite(vec![GraphLayer {
700            source: glyphs,
701            visual,
702            blend_mode: BlendMode::Normal,
703        }])
704        .map_err(GraphError::into_render_error)?;
705    let mut layers = Vec::with_capacity(texture.shadows.len() + 2);
706    if let Some((background, key)) = texture.background {
707        layers.push(GraphLayer {
708            source: keyed_source(graph, background, key),
709            visual,
710            blend_mode: BlendMode::Normal,
711        });
712    }
713    for shadow in texture.shadows.iter().rev() {
714        let cast = graph
715            .add_shadow(placed, shadow.offset, shadow.sigma, shadow.color)
716            .map_err(GraphError::into_render_error)?;
717        layers.push(identity_layer(cast));
718    }
719    layers.push(identity_layer(placed));
720    let look = graph
721        .add_composite(layers)
722        .map_err(GraphError::into_render_error)?;
723    Ok(identity_layer(look))
724}
725
726#[derive(Clone, Debug)]
727enum StepFrame<'t> {
728    Media(Frame<'t>),
729    Text(PlacedText<'t>),
730    Layout(LaidOut<'t>),
731}
732
733/// The host-supplied frames one visual clip draws.
734#[derive(Clone, Debug, Default)]
735struct ClipFrames<'t> {
736    /// Index in [`FrameDesc::visual`], which [`alpha2_eval::ActiveCaption::layers_below`]
737    /// counts in (drawn clips are only a subset).
738    layer: usize,
739    /// The clip's own source frame; `None` when the source is generated or not shown.
740    source: Option<Frame<'t>>,
741    /// The text of the clip's text generator source, once prepared.
742    text: Option<PlacedText<'t>>,
743    /// The clip's layout generator source, once prepared.
744    layout: Option<LaidOut<'t>>,
745    /// Per-step frame or text by step index; `None` for other steps.
746    media: Vec<Option<StepFrame<'t>>>,
747    /// The same for the clip's composition source.
748    source_media: Vec<Option<StepFrame<'t>>>,
749}
750
751/// Each visual clip with its source frames. A missing frame is reported and its clip left out.
752fn available_textures<'frame, 'eval, 'texture>(
753    frame: &'frame FrameDesc<'eval>,
754    frames: &'texture dyn FrameProvider,
755) -> (
756    RenderReport,
757    Vec<(&'frame ActiveClip<'eval>, ClipFrames<'texture>)>,
758) {
759    let mut report = RenderReport::default();
760    let mut available = Vec::with_capacity(frame.visual.len());
761    let mut lookup = |source: &SourceId, time| {
762        let texture = frames.texture_for(source, time);
763        if texture.is_none() && !report.missing_sources.contains(source) {
764            report.missing_sources.push(source.clone());
765        }
766        texture.map(|view| Frame {
767            view,
768            key: frames.source_key(source, time),
769        })
770    };
771    // A matte no active clip names is drawn nowhere; it needs no frame.
772    for (layer, clip) in frame.visual.iter().enumerate() {
773        if !frame.draws(clip) {
774            continue;
775        }
776        let mut textures = ClipFrames {
777            layer,
778            ..ClipFrames::default()
779        };
780        let mut complete = true;
781        if clip.needs_source() {
782            textures.source = lookup(clip.source_id, clip.source_time);
783            complete &= textures.source.is_some();
784        }
785        for (composition, media) in [
786            (clip.composition, &mut textures.media),
787            (clip.source_composition, &mut textures.source_media),
788        ] {
789            let Some(composition) = composition else {
790                continue;
791            };
792            *media = vec![None; composition.plan().steps.len()];
793            for (step, source, time) in composition.media() {
794                media[step] = lookup(source, time).map(StepFrame::Media);
795                complete &= media[step].is_some();
796            }
797        }
798        if complete {
799            available.push((clip, textures));
800        }
801    }
802    (report, available)
803}
804
805/// Attaches prepared text and layouts to each available clip. Missing ones are left for the
806/// graph to report.
807fn attach_texts<'t>(
808    available: &mut [(&ActiveClip<'_>, ClipFrames<'t>)],
809    frames: &'t dyn FrameProvider,
810    size: RenderSize,
811) {
812    let laid_out = |plan: Option<&GeneratorPlan>, time: MediaTime| {
813        let plan = plan?.layout()?;
814        let layout = frames.layout(crate::layout_key(plan.evaluate(time).key, size))?;
815        LaidOut::attach(layout, frames)
816    };
817    let lookup = |generator: &Generator, time: MediaTime| match generator {
818        Generator::Text { text, style } => frames
819            .text(alpha2_layout::animated_text_key(
820                text,
821                style,
822                crate::text::picture(size),
823                time,
824            ))
825            .map(|texture| PlacedText {
826                texture,
827                visual: text_placement(texture, style, size),
828            }),
829        _ => None,
830    };
831    for (clip, textures) in available {
832        textures.text = clip
833            .generator
834            .and_then(|generator| lookup(generator, clip.source_time));
835        textures.layout = laid_out(clip.plan, clip.source_time);
836        for (composition, media) in [
837            (clip.composition, &mut textures.media),
838            (clip.source_composition, &mut textures.source_media),
839        ] {
840            let Some(composition) = composition else {
841                continue;
842            };
843            for (step, slot) in composition.plan().steps.iter().zip(media.iter_mut()) {
844                match &step.op {
845                    StepOp::Generator {
846                        generator: Generator::Layout { .. },
847                        start,
848                        plan,
849                    } => {
850                        let time = MediaTime(
851                            step.time(composition.time())
852                                .ticks()
853                                .saturating_add(start.ticks()),
854                        );
855                        *slot = laid_out(plan.as_deref(), time).map(StepFrame::Layout);
856                    }
857                    StepOp::Generator {
858                        generator, start, ..
859                    } => {
860                        let time =
861                            crate::text::generator_time(step.time(composition.time()), *start);
862                        *slot = lookup(generator, time).map(StepFrame::Text);
863                    }
864                    _ => {}
865                }
866            }
867        }
868    }
869}
870
871/// Places prepared text at its pixel size with its anchor at the style position.
872fn text_placement(texture: TextTexture<'_>, style: &TextStyle, size: RenderSize) -> LayerTransform {
873    #[allow(clippy::cast_precision_loss)]
874    let scale = [
875        texture.width as f32 / size.width as f32,
876        texture.height as f32 / size.height as f32,
877    ];
878    LayerTransform {
879        position: [style.position.x, style.position.y],
880        anchor: [
881            box_anchor(style.anchor.x, texture.width, texture.margin[0]),
882            box_anchor(style.anchor.y, texture.height, texture.margin[1]),
883        ],
884        scale,
885        rotation_degrees: 0.0,
886        opacity: 1.0,
887    }
888}
889
890/// A prepared caption and where it goes in the layer stack.
891struct CaptionLayer<'a> {
892    /// Visual clips under it, drawn or not.
893    layers_below: usize,
894    texture: TextTexture<'a>,
895    visual: LayerTransform,
896}
897
898fn caption_graph_layer<'a>(
899    graph: &mut RenderGraph<'a>,
900    caption: &CaptionLayer<'a>,
901) -> Result<GraphLayer, RenderError> {
902    text_layer(graph, caption.texture, caption.visual)
903}
904
905fn caption_layers<'a>(
906    frame: &FrameDesc,
907    frames: &'a dyn FrameProvider,
908    size: RenderSize,
909) -> Result<Vec<CaptionLayer<'a>>, RenderError> {
910    frame
911        .captions
912        .iter()
913        .map(|caption| {
914            let texture = frames
915                .text(alpha2_layout::animated_text_key(
916                    caption.text,
917                    caption.style,
918                    crate::text::picture(size),
919                    caption.local_time,
920                ))
921                .ok_or(RenderError::MissingText)?;
922            Ok(CaptionLayer {
923                layers_below: caption.layers_below,
924                visual: text_placement(texture, caption.style, size),
925                texture,
926            })
927        })
928        .collect()
929}
930
931/// Maps a text anchor into texture space, past a `margin` reserved for ink overflow so accents
932/// and descenders never move the text.
933#[allow(clippy::cast_precision_loss)]
934fn box_anchor(anchor: f32, extent: u32, margin: u32) -> f32 {
935    if margin == 0 {
936        return anchor;
937    }
938    let inner = extent.saturating_sub(margin * 2) as f32;
939    (margin as f32 + anchor * inner) / extent as f32
940}
941
942#[allow(clippy::cast_precision_loss)]
943fn frame_runtime(frame: &FrameDesc, size: RenderSize) -> EffectRuntime {
944    let ratio = size.width as f32 / size.height as f32;
945    let scale = frame.canvas.map_or(1.0, |(width, height)| {
946        size.width.min(size.height) as f32 / width.min(height).max(1) as f32
947    });
948    EffectRuntime {
949        time: frame.time,
950        ratio,
951        scale,
952        ..EffectRuntime::default()
953    }
954}
955
956fn frame_graph<'a>(
957    renderer: &dyn EffectCatalog,
958    size: RenderSize,
959    frame: &'a FrameDesc<'a>,
960    available: &[(&'a ActiveClip<'a>, ClipFrames<'a>)],
961    captions: &[CaptionLayer<'a>],
962) -> Result<RenderGraph<'a>, RenderError> {
963    let mut graph = RenderGraph::new(size);
964    graph.set_blend_space(match frame.blend_space {
965        alpha2_model::BlendSpace::LinearLight => alpha2_render::BlendSpace::LinearLight,
966        alpha2_model::BlendSpace::SrgbEncoded => alpha2_render::BlendSpace::SrgbEncoded,
967    });
968    let mut nodes = HashMap::with_capacity(available.len());
969    let mut inputs = Vec::with_capacity(available.len() + frame.transitions.len());
970    // Each matte's coverage is drawn once however many clips it mattes.
971    let mut coverages = HashMap::new();
972    let runtime = frame_runtime(frame, size);
973    for (clip, textures) in available {
974        if clip.is_matte {
975            continue;
976        }
977        let mut layer = clip_layer(renderer, &mut graph, clip, textures, frame.time, runtime)?;
978        if let Some(matte) = clip.matte {
979            layer = apply_matte(
980                renderer,
981                &mut graph,
982                layer,
983                matte,
984                available,
985                (frame.time, runtime),
986                &mut coverages,
987            )?;
988        }
989        nodes.insert(clip.clip_id, inputs.len());
990        inputs.push(FrameInput {
991            kind: FrameInputKind::Layer(layer),
992            uses_backdrop: clip.blend_mode != ClipBlendMode::Normal,
993        });
994    }
995    let background = background_color(frame.background);
996    let suppressed = fold_transitions(frame, available, &mut nodes, &mut inputs)?;
997    let mut layers = Vec::with_capacity(available.len() + captions.len());
998    let mut captions = captions.iter().peekable();
999    for (clip, textures) in available {
1000        // Captions on earlier tracks; undrawn clips do not move them.
1001        while let Some(caption) = captions.next_if(|caption| caption.layers_below <= textures.layer)
1002        {
1003            layers.push(caption_graph_layer(&mut graph, caption)?);
1004        }
1005        if clip.is_matte || suppressed.contains(clip.clip_id) {
1006            continue;
1007        }
1008        let index = *nodes.get(clip.clip_id).ok_or(RenderError::InvalidGraph)?;
1009        if let FrameInputKind::Layer(layer) = inputs[index].kind {
1010            layers.push(layer);
1011            continue;
1012        }
1013        // Normal transitions operate on isolated, transformed layers. Artistic modes need the
1014        // same backdrop on both sides: transition their composed scenes, then replace that
1015        // backdrop exactly once.
1016        let uses_backdrop = inputs[index].uses_backdrop;
1017        let backdrop = if uses_backdrop {
1018            layers.as_slice()
1019        } else {
1020            &[]
1021        };
1022        // The background is part of that backdrop, so blending matches outside transitions.
1023        let source = compile_frame_input(
1024            &mut graph,
1025            &inputs,
1026            index,
1027            backdrop,
1028            uses_backdrop.then_some(background),
1029            runtime,
1030            renderer,
1031        )?;
1032        if uses_backdrop {
1033            layers.clear();
1034        }
1035        layers.push(identity_layer(source));
1036    }
1037    for caption in captions {
1038        layers.push(caption_graph_layer(&mut graph, caption)?);
1039    }
1040    let output = graph
1041        .add_composite_over(layers, background)
1042        .map_err(GraphError::into_render_error)?;
1043    graph
1044        .set_output(output)
1045        .map_err(GraphError::into_render_error)?;
1046    graph
1047        .set_cache_intent(output, CacheIntent::Auto)
1048        .map_err(GraphError::into_render_error)?;
1049    Ok(graph)
1050}
1051
1052/// Adds a node per transition of `frame`, each replacing its `to` clip's node, and returns the
1053/// `from` clips, which are drawn only through a transition.
1054fn fold_transitions<'a>(
1055    frame: &'a FrameDesc<'a>,
1056    available: &[(&'a ActiveClip<'a>, ClipFrames<'a>)],
1057    nodes: &mut HashMap<&'a alpha2_model::ClipId, usize>,
1058    inputs: &mut Vec<FrameInput<'a>>,
1059) -> Result<HashSet<&'a alpha2_model::ClipId>, RenderError> {
1060    let mut suppressed = HashSet::new();
1061    let mut fold = |transition: &'a ActiveTransition<'a>| {
1062        let from = *nodes
1063            .get(transition.from_clip)
1064            .ok_or(RenderError::InvalidGraph)?;
1065        let to = *nodes
1066            .get(transition.to_clip)
1067            .ok_or(RenderError::InvalidGraph)?;
1068        let output = inputs.len();
1069        inputs.push(FrameInput {
1070            kind: FrameInputKind::Transition {
1071                from,
1072                to,
1073                transition,
1074            },
1075            uses_backdrop: inputs[from].uses_backdrop || inputs[to].uses_backdrop,
1076        });
1077        nodes.insert(transition.to_clip, output);
1078        suppressed.insert(transition.from_clip);
1079        Ok::<_, RenderError>(())
1080    };
1081    if frame.transitions.len() > 1 {
1082        for index in tournament_order(&frame.transitions, available)? {
1083            fold(&frame.transitions[index])?;
1084        }
1085    } else {
1086        for transition in &frame.transitions {
1087            fold(transition)?;
1088        }
1089    }
1090    Ok(suppressed)
1091}
1092
1093/// Indices of `transitions` in the order the fold applies them.
1094///
1095/// A clip receives all of its incoming transitions, in the order of their `from` clips, before it
1096/// feeds another, so overlaps of three or more clips draw one picture whatever the list order.
1097/// Clips are ordered topologically over the edges `from -> to`, ties by frame order.
1098fn tournament_order(
1099    transitions: &[ActiveTransition<'_>],
1100    available: &[(&ActiveClip<'_>, ClipFrames<'_>)],
1101) -> Result<Vec<usize>, RenderError> {
1102    let position = |id: &alpha2_model::ClipId| {
1103        available
1104            .iter()
1105            .position(|(clip, _)| clip.clip_id == id)
1106            .ok_or(RenderError::InvalidGraph)
1107    };
1108    let edges = transitions
1109        .iter()
1110        .map(|transition| {
1111            Ok((
1112                position(transition.from_clip)?,
1113                position(transition.to_clip)?,
1114            ))
1115        })
1116        .collect::<Result<Vec<_>, RenderError>>()?;
1117    let mut clips = edges
1118        .iter()
1119        .flat_map(|&(from, to)| [from, to])
1120        .collect::<Vec<_>>();
1121    clips.sort_unstable();
1122    clips.dedup();
1123    let mut incoming = clips
1124        .iter()
1125        .map(|clip| edges.iter().filter(|(_, to)| to == clip).count())
1126        .collect::<Vec<_>>();
1127    let mut rank = vec![usize::MAX; available.len()];
1128    for step in 0..clips.len() {
1129        // A cycle leaves no clip without pending incoming transitions.
1130        let next = incoming
1131            .iter()
1132            .position(|&count| count == 0)
1133            .ok_or(RenderError::InvalidGraph)?;
1134        incoming[next] = usize::MAX;
1135        rank[clips[next]] = step;
1136        let feeds = edges.iter().filter(|(from, _)| *from == clips[next]);
1137        for target in feeds.filter_map(|(_, to)| clips.binary_search(to).ok()) {
1138            incoming[target] -= 1;
1139        }
1140    }
1141    let mut order = (0..transitions.len()).collect::<Vec<_>>();
1142    order.sort_by_key(|&index| (rank[edges[index].1], rank[edges[index].0]));
1143    Ok(order)
1144}
1145
1146const fn cache_intent(intent: alpha2_model::CacheIntent) -> CacheIntent {
1147    match intent {
1148        alpha2_model::CacheIntent::Auto => CacheIntent::Auto,
1149        alpha2_model::CacheIntent::Pin => CacheIntent::Pin,
1150        alpha2_model::CacheIntent::Bypass => CacheIntent::Bypass,
1151    }
1152}
1153
1154/// `layer` kept where `matte` says, the matte clip drawn only into it.
1155fn apply_matte<'a, 'c>(
1156    renderer: &dyn EffectCatalog,
1157    graph: &mut RenderGraph<'a>,
1158    mut layer: GraphLayer,
1159    matte: &'c alpha2_model::Matte,
1160    available: &[(&'a ActiveClip<'a>, ClipFrames<'a>)],
1161    (time, runtime): (MediaTime, EffectRuntime),
1162    coverages: &mut HashMap<&'c alpha2_model::ClipId, RenderNodeId>,
1163) -> Result<GraphLayer, RenderError> {
1164    let source = available
1165        .iter()
1166        .find(|(candidate, _)| candidate.clip_id == &matte.source);
1167    match source {
1168        Some((source, textures)) => {
1169            let coverage = if let Some(coverage) = coverages.get(&matte.source) {
1170                *coverage
1171            } else {
1172                let matte_layer = clip_layer(renderer, graph, source, textures, time, runtime)?;
1173                let coverage = alone(graph, matte_layer)?;
1174                coverages.insert(&matte.source, coverage);
1175                coverage
1176            };
1177            layer = matted_layer(graph, layer, coverage, matte.mode, runtime)?;
1178        }
1179        // An inactive matte hides the clip (or shows it fully when inverted). A hidden clip keeps
1180        // its node so a transition can still name it.
1181        None if is_inverted(matte.mode) => {}
1182        None => layer.visual.opacity = 0.0,
1183    }
1184    Ok(layer)
1185}
1186
1187fn background_color(background: Option<Rgb>) -> Color {
1188    background.map_or(Color::rgba(0.0, 0.0, 0.0, 0.0), |background| {
1189        Color::rgba(
1190            f64::from(background.red),
1191            f64::from(background.green),
1192            f64::from(background.blue),
1193            1.0,
1194        )
1195    })
1196}
1197
1198struct FrameInput<'a> {
1199    kind: FrameInputKind<'a>,
1200    uses_backdrop: bool,
1201}
1202
1203fn clip_layer<'a>(
1204    renderer: &dyn EffectCatalog,
1205    graph: &mut RenderGraph<'a>,
1206    clip: &'a ActiveClip<'a>,
1207    textures: &ClipFrames<'a>,
1208    time: MediaTime,
1209    runtime: EffectRuntime,
1210) -> Result<GraphLayer, RenderError> {
1211    let mut source = match clip.composition {
1212        None => clip_picture(renderer, graph, clip, textures, runtime)?,
1213        Some(composition) => plan_node(
1214            renderer,
1215            graph,
1216            composition,
1217            &textures.media,
1218            Some((clip, textures)),
1219            runtime,
1220        )?,
1221    };
1222    if !clip.masks.is_empty() {
1223        source = mask_node(graph, source, clip.masks, time, runtime, &clip.data)?;
1224    }
1225    // Cache the finished clip picture: layers above change often and everything below is in its
1226    // key. A bare source frame is already the host's, so only a bypass applies to it.
1227    let intent = cache_intent(clip.cache);
1228    if intent == CacheIntent::Bypass || graph.node_kind(source) != Some(RenderNodeKind::Source) {
1229        graph
1230            .set_cache_intent(source, intent)
1231            .map_err(GraphError::into_render_error)?;
1232    }
1233    if let Some(correction) = clip.correction {
1234        source = graph
1235            .add_composite(vec![GraphLayer {
1236                source,
1237                visual: correction_transform(correction),
1238                blend_mode: BlendMode::Normal,
1239            }])
1240            .map_err(GraphError::into_render_error)?;
1241    }
1242    Ok(GraphLayer {
1243        source,
1244        visual: layer_transform(clip.visual.ok_or(RenderError::InvalidVisual)?),
1245        blend_mode: blend_mode(clip.blend_mode),
1246    })
1247}
1248
1249fn clip_picture<'a>(
1250    renderer: &dyn EffectCatalog,
1251    graph: &mut RenderGraph<'a>,
1252    clip: &'a ActiveClip<'a>,
1253    textures: &ClipFrames<'a>,
1254    runtime: EffectRuntime,
1255) -> Result<RenderNodeId, RenderError> {
1256    if let Some(source) = clip.source_composition {
1257        // A composition source's plan has no clip steps.
1258        return plan_node(
1259            renderer,
1260            graph,
1261            source,
1262            &textures.source_media,
1263            None,
1264            runtime,
1265        );
1266    }
1267    match (clip.generator, textures.source) {
1268        (Some(Generator::Text { .. }), _) => {
1269            textures.text.ok_or(RenderError::MissingText)?.add_to(graph)
1270        }
1271        (Some(Generator::Layout { .. }), _) => textures
1272            .layout
1273            .as_ref()
1274            .ok_or(RenderError::MissingText)?
1275            .add_to(graph),
1276        (Some(Generator::Shapes { .. }), _) => {
1277            let plan = clip
1278                .plan
1279                .and_then(GeneratorPlan::shapes)
1280                .ok_or(RenderError::InvalidGraph)?;
1281            Ok(shapes_node(graph, plan, clip.source_time))
1282        }
1283        (Some(generator), _) => Ok(generator_node(graph, generator, runtime)),
1284        (None, Some(frame)) => Ok(frame.add_to(graph)),
1285        (None, None) => Err(RenderError::InvalidGraph),
1286    }
1287}
1288
1289/// A shapes generator's picture at picture time `time`, drawn as a vector scene at graph size.
1290fn shapes_node(graph: &mut RenderGraph<'_>, plan: &ShapesPlan, time: MediaTime) -> RenderNodeId {
1291    let size = graph.size();
1292    let canvas = alpha2_geometry::CanvasSize::new(size.width, size.height);
1293    let aspect = f64::from(size.width) / f64::from(size.height);
1294    let items = plan.evaluate(time, aspect);
1295    graph.add_vector(std::sync::Arc::new(alpha2_geometry::build_scene(
1296        &items, canvas,
1297    )))
1298}
1299
1300/// A fill is timeless, so its node has the same cache key in every frame.
1301fn generator_node(
1302    graph: &mut RenderGraph<'_>,
1303    generator: &alpha2_model::Generator,
1304    runtime: EffectRuntime,
1305) -> RenderNodeId {
1306    graph.add_generator(
1307        EffectId::from_static(GENERATOR_EFFECT_ID, 1),
1308        crate::generated::generator_params(generator),
1309        timeless(runtime),
1310    )
1311}
1312
1313/// Draws a compiled composition's steps in order, each sampled at the composition time plus its
1314/// offset. Clip steps draw `clip`'s picture.
1315fn plan_node<'a>(
1316    renderer: &dyn EffectCatalog,
1317    graph: &mut RenderGraph<'a>,
1318    composition: ActiveComposition<'a>,
1319    media: &[Option<StepFrame<'a>>],
1320    clip: Option<(&'a ActiveClip<'a>, &ClipFrames<'a>)>,
1321    runtime: EffectRuntime,
1322) -> Result<RenderNodeId, RenderError> {
1323    let plan = composition.plan();
1324    let time = composition.time();
1325    let mut built: Vec<RenderNodeId> = Vec::with_capacity(plan.steps.len());
1326    let mut picture = None;
1327    for (index, step) in plan.steps.iter().enumerate() {
1328        let at = step.time(time);
1329        let step_runtime = EffectRuntime {
1330            time: at,
1331            ..runtime
1332        };
1333        let node = match &step.op {
1334            // Every clip step draws the same picture.
1335            StepOp::Clip => {
1336                if let Some(node) = picture {
1337                    node
1338                } else {
1339                    let (clip, textures) = clip.ok_or(RenderError::InvalidGraph)?;
1340                    *picture.insert(clip_picture(renderer, graph, clip, textures, runtime)?)
1341                }
1342            }
1343            StepOp::Media { .. } => match media.get(index).and_then(Option::as_ref) {
1344                Some(StepFrame::Media(frame)) => frame.add_to(graph),
1345                _ => return Err(RenderError::InvalidGraph),
1346            },
1347            StepOp::Generator {
1348                generator: Generator::Text { .. },
1349                ..
1350            } => match media.get(index).and_then(Option::as_ref) {
1351                Some(StepFrame::Text(text)) => text.add_to(graph)?,
1352                _ => return Err(RenderError::MissingText),
1353            },
1354            StepOp::Generator {
1355                generator: Generator::Layout { .. },
1356                ..
1357            } => match media.get(index).and_then(Option::as_ref) {
1358                Some(StepFrame::Layout(layout)) => layout.add_to(graph)?,
1359                _ => return Err(RenderError::MissingText),
1360            },
1361            op => step_node(
1362                renderer,
1363                graph,
1364                op,
1365                &built,
1366                at,
1367                step_runtime,
1368                composition.step_data(index),
1369            )?,
1370        };
1371        built.push(node);
1372    }
1373    step_input(&built, plan.output)
1374}
1375
1376// A node names at most as many inputs as an effect may declare.
1377const _: () = assert!(alpha2_model::MAX_EFFECT_INPUTS == alpha2_render::MAX_EFFECT_INPUTS);
1378
1379fn step_input(built: &[RenderNodeId], step: usize) -> Result<RenderNodeId, RenderError> {
1380    built.get(step).copied().ok_or(RenderError::InvalidGraph)
1381}
1382
1383#[allow(clippy::too_many_lines)]
1384fn step_node<'a>(
1385    renderer: &dyn EffectCatalog,
1386    graph: &mut RenderGraph<'a>,
1387    op: &'a StepOp,
1388    built: &[RenderNodeId],
1389    time: MediaTime,
1390    runtime: EffectRuntime,
1391    context: SampleContext<'a>,
1392) -> Result<RenderNodeId, RenderError> {
1393    let input = |step: usize| step_input(built, step);
1394    let node = match op {
1395        StepOp::Clip | StepOp::Media { .. } => return Err(RenderError::InvalidGraph),
1396        StepOp::Generator {
1397            generator: Generator::Shapes { .. },
1398            start,
1399            plan,
1400        } => {
1401            let plan = plan
1402                .as_deref()
1403                .and_then(GeneratorPlan::shapes)
1404                .ok_or(RenderError::InvalidGraph)?;
1405            let at = MediaTime(time.ticks().saturating_add(start.ticks()));
1406            shapes_node(graph, plan, at)
1407        }
1408        StepOp::Generator { generator, .. } => generator_node(graph, generator, runtime),
1409        StepOp::Effect {
1410            input: from,
1411            inputs,
1412            effect,
1413        } => {
1414            let id = project_effect_id(renderer, &effect.id, effect.version)?;
1415            let active = ActiveEffect::new(effect, time, context);
1416            let params = effect_params(renderer, &id, active);
1417            let runtime = effect_runtime(renderer, &id, runtime);
1418            let mut named = EffectInputs::new();
1419            for (name, step) in inputs {
1420                named.insert(name.as_str(), input(*step)?);
1421            }
1422            graph.add_effect_with_inputs(
1423                id,
1424                input(*from)?,
1425                named,
1426                params,
1427                effect_resources(active),
1428                runtime,
1429            )
1430        }
1431        .map_err(GraphError::into_render_error)?,
1432        StepOp::Transition {
1433            from,
1434            to,
1435            effect,
1436            progress,
1437        } => {
1438            let id = project_effect_id(renderer, &effect.id, effect.version)?;
1439            let active = ActiveEffect::new(effect, time, context);
1440            let params = effect_params(renderer, &id, active);
1441            let runtime = EffectRuntime {
1442                progress: sample_scalar(progress, time, &context).clamp(0.0, 1.0),
1443                ..effect_runtime(renderer, &id, runtime)
1444            };
1445            graph.add_transition_with_resources(
1446                id,
1447                input(*from)?,
1448                input(*to)?,
1449                params,
1450                effect_resources(active),
1451                runtime,
1452            )
1453        }
1454        .map_err(GraphError::into_render_error)?,
1455        StepOp::Transform {
1456            input: from,
1457            transform,
1458        } => graph
1459            .add_composite(vec![GraphLayer {
1460                source: input(*from)?,
1461                visual: layer_transform(sample_visual(
1462                    transform,
1463                    time,
1464                    graph_aspect(graph),
1465                    &context,
1466                )),
1467                blend_mode: BlendMode::Normal,
1468            }])
1469            .map_err(GraphError::into_render_error)?,
1470        StepOp::Merge { layers } => {
1471            let layers = layers
1472                .iter()
1473                .map(|layer| {
1474                    let mut placed = identity_layer(input(layer.input)?);
1475                    placed.visual.opacity =
1476                        sample_scalar(&layer.opacity, time, &context).clamp(0.0, 1.0);
1477                    placed.blend_mode = blend_mode(layer.blend_mode);
1478                    Ok(placed)
1479                })
1480                .collect::<Result<Vec<_>, RenderError>>()?;
1481            graph
1482                .add_composite(layers)
1483                .map_err(GraphError::into_render_error)?
1484        }
1485        StepOp::Matte {
1486            input: from,
1487            matte,
1488            mode,
1489        } => matte_node(graph, input(*from)?, input(*matte)?, *mode, runtime)?,
1490        StepOp::ShapeMask { input: from, masks } => {
1491            mask_node(graph, input(*from)?, masks, time, runtime, &context)?
1492        }
1493    };
1494    Ok(node)
1495}
1496
1497/// Graph width over height, for motion along spatial curves.
1498fn graph_aspect(graph: &RenderGraph<'_>) -> f64 {
1499    let size = graph.size();
1500    f64::from(size.width) / f64::from(size.height)
1501}
1502
1503/// `source` kept inside `masks` at `time`. Each outline is drawn as opaque white; feathering is
1504/// a Gaussian with deviation `0.3125 * feather` (of the shorter side), giving a 10-90 percent
1505/// ramp `0.8 * feather` wide. One pass combines the masks in order.
1506fn mask_node(
1507    graph: &mut RenderGraph<'_>,
1508    source: RenderNodeId,
1509    masks: &[ShapeMask],
1510    time: MediaTime,
1511    runtime: EffectRuntime,
1512    context: &SampleContext<'_>,
1513) -> Result<RenderNodeId, RenderError> {
1514    let size = graph.size();
1515    let canvas = alpha2_geometry::CanvasSize::new(size.width, size.height);
1516    let aspect = graph_aspect(graph);
1517    let unit = size.width.min(size.height);
1518    let white = alpha2_model::Paint::Solid {
1519        color: alpha2_model::Rgba::new(1.0, 1.0, 1.0, 1.0),
1520    };
1521    let shown = &masks[..masks.len().min(MAX_SHAPE_MASKS)];
1522    if shown.is_empty() {
1523        return Ok(source);
1524    }
1525    let mut coverages = Vec::with_capacity(shown.len());
1526    for mask in shown {
1527        let outline = alpha2_eval::evaluate_geometry(&mask.shape, time, aspect, context);
1528        let items = [
1529            alpha2_geometry::EvaluatedItem::Geometry(outline),
1530            alpha2_geometry::EvaluatedItem::Fill {
1531                paint: white.clone(),
1532                opacity: 1.0,
1533                rule: mask.fill_rule,
1534            },
1535        ];
1536        let coverage = graph.add_vector(std::sync::Arc::new(alpha2_geometry::build_scene(
1537            &items, canvas,
1538        )));
1539        #[allow(clippy::cast_precision_loss)]
1540        let sigma = 0.3125 * sample_scalar(&mask.feather, time, context).max(0.0) * unit as f32;
1541        let coverage = graph
1542            .add_gaussian_pixels(coverage, sigma, timeless(runtime))
1543            .map_err(GraphError::into_render_error)?;
1544        coverages.push((coverage, mask.invert, mask.mode));
1545    }
1546    coverage_mask(graph, source, &coverages)
1547}
1548
1549/// `source` kept by the alpha of up to [`MAX_SHAPE_MASKS`] `coverages`, combined in one pass.
1550pub(crate) fn coverage_mask(
1551    graph: &mut RenderGraph<'_>,
1552    source: RenderNodeId,
1553    coverages: &[(RenderNodeId, bool, MaskMode)],
1554) -> Result<RenderNodeId, RenderError> {
1555    if coverages.is_empty() || coverages.len() > MAX_SHAPE_MASKS {
1556        return Err(RenderError::InvalidGraph);
1557    }
1558    let size = graph.size();
1559    #[allow(clippy::cast_precision_loss)]
1560    let runtime = EffectRuntime {
1561        ratio: size.width as f32 / size.height as f32,
1562        ..EffectRuntime::default()
1563    };
1564    let mut inputs = EffectInputs::new();
1565    let mut params = EffectParams::with_capacity(coverages.len() * 2);
1566    for (&(coverage, invert, mode), names) in coverages.iter().zip(MASK_COMBINE_NAMES) {
1567        inputs.insert(names.input, coverage);
1568        params.insert(names.invert, ParamValue::Bool(invert));
1569        params.insert(
1570            names.mode,
1571            ParamValue::Enum(match mode {
1572                MaskMode::Add => 0,
1573                MaskMode::Subtract => 1,
1574                MaskMode::Intersect => 2,
1575            }),
1576        );
1577    }
1578    graph
1579        .add_effect_with_inputs(
1580            EffectId::from_static(MASK_COMBINE_EFFECT_IDS[coverages.len() - 1], 1),
1581            source,
1582            inputs,
1583            params,
1584            EffectResources::new(),
1585            runtime,
1586        )
1587        .map_err(GraphError::into_render_error)
1588}
1589
1590const fn is_inverted(mode: MatteMode) -> bool {
1591    matches!(mode, MatteMode::AlphaInverted | MatteMode::LumaInverted)
1592}
1593
1594/// `layer` kept by `matte`. Both are drawn onto the canvas first, so the matte applies where
1595/// they land regardless of transforms.
1596fn matted_layer(
1597    graph: &mut RenderGraph<'_>,
1598    layer: GraphLayer,
1599    coverage: RenderNodeId,
1600    mode: MatteMode,
1601    runtime: EffectRuntime,
1602) -> Result<GraphLayer, RenderError> {
1603    let picture = alone(graph, layer)?;
1604    let matted = matte_node(graph, picture, coverage, mode, runtime)?;
1605    Ok(GraphLayer {
1606        blend_mode: layer.blend_mode,
1607        ..identity_layer(matted)
1608    })
1609}
1610
1611fn alone(graph: &mut RenderGraph<'_>, layer: GraphLayer) -> Result<RenderNodeId, RenderError> {
1612    graph
1613        .add_composite(vec![GraphLayer {
1614            blend_mode: BlendMode::Normal,
1615            ..layer
1616        }])
1617        .map_err(GraphError::into_render_error)
1618}
1619
1620/// Drops the frame time from `runtime` when `effect` cannot read it
1621/// ([`Renderer::effect_reads_time`]), so its cache key holds across frames.
1622fn effect_runtime(
1623    renderer: &dyn EffectCatalog,
1624    effect: &EffectId,
1625    runtime: EffectRuntime,
1626) -> EffectRuntime {
1627    if renderer.effect_reads_time(effect) {
1628        runtime
1629    } else {
1630        EffectRuntime {
1631            time: MediaTime::ZERO,
1632            ..runtime
1633        }
1634    }
1635}
1636
1637/// `runtime` without the frame time, for timeless engine passes so their cache key holds.
1638fn timeless(runtime: EffectRuntime) -> EffectRuntime {
1639    EffectRuntime {
1640        ratio: runtime.ratio,
1641        ..EffectRuntime::default()
1642    }
1643}
1644
1645fn matte_node(
1646    graph: &mut RenderGraph<'_>,
1647    picture: RenderNodeId,
1648    coverage: RenderNodeId,
1649    mode: MatteMode,
1650    runtime: EffectRuntime,
1651) -> Result<RenderNodeId, RenderError> {
1652    graph
1653        .add_transition_with_resources(
1654            EffectId::from_static(TRACK_MATTE_EFFECT_ID, 1),
1655            picture,
1656            coverage,
1657            EffectParams::new()
1658                .with(
1659                    "luma",
1660                    ParamValue::Bool(matches!(mode, MatteMode::Luma | MatteMode::LumaInverted)),
1661                )
1662                .with("inverted", ParamValue::Bool(is_inverted(mode))),
1663            EffectResources::new(),
1664            // The matte ignores progress and time; an interior progress runs its body.
1665            EffectRuntime {
1666                progress: 0.5,
1667                ..timeless(runtime)
1668            },
1669        )
1670        .map_err(GraphError::into_render_error)
1671}
1672
1673#[derive(Copy, Clone)]
1674enum FrameInputKind<'a> {
1675    Layer(GraphLayer),
1676    Transition {
1677        from: usize,
1678        to: usize,
1679        transition: &'a ActiveTransition<'a>,
1680    },
1681}
1682
1683fn compile_frame_input<'a>(
1684    graph: &mut RenderGraph<'a>,
1685    inputs: &[FrameInput<'a>],
1686    index: usize,
1687    backdrop: &[GraphLayer],
1688    background: Option<Color>,
1689    runtime: EffectRuntime,
1690    renderer: &dyn EffectCatalog,
1691) -> Result<RenderNodeId, RenderError> {
1692    if index >= inputs.len() {
1693        return Err(RenderError::InvalidGraph);
1694    }
1695    let mut compiled = vec![None; inputs.len()];
1696    let mut pending = vec![(index, false)];
1697    while let Some((current, expanded)) = pending.pop() {
1698        if compiled[current].is_some() {
1699            continue;
1700        }
1701        match inputs[current].kind {
1702            FrameInputKind::Layer(layer) => {
1703                let mut layers = Vec::with_capacity(backdrop.len() + 1);
1704                layers.extend_from_slice(backdrop);
1705                layers.push(layer);
1706                let composite = match background {
1707                    Some(background) => graph.add_composite_over(layers, background),
1708                    None => graph.add_composite(layers),
1709                };
1710                compiled[current] = Some(composite.map_err(GraphError::into_render_error)?);
1711            }
1712            FrameInputKind::Transition {
1713                from,
1714                to,
1715                transition,
1716            } => {
1717                if from >= inputs.len() || to >= inputs.len() {
1718                    return Err(RenderError::InvalidGraph);
1719                }
1720                if !expanded {
1721                    pending.push((current, true));
1722                    if compiled[to].is_none() {
1723                        pending.push((to, false));
1724                    }
1725                    if compiled[from].is_none() {
1726                        pending.push((from, false));
1727                    }
1728                    continue;
1729                }
1730                let from = compiled[from].ok_or(RenderError::InvalidGraph)?;
1731                let to = compiled[to].ok_or(RenderError::InvalidGraph)?;
1732                let id = project_effect_id(
1733                    renderer,
1734                    transition.effect.id(),
1735                    transition.effect.version(),
1736                )?;
1737                let params = effect_params(renderer, &id, transition.effect);
1738                let runtime = EffectRuntime {
1739                    progress: transition.progress,
1740                    ..effect_runtime(renderer, &id, runtime)
1741                };
1742                compiled[current] = Some(
1743                    graph
1744                        .add_transition_with_resources(
1745                            id,
1746                            from,
1747                            to,
1748                            params,
1749                            effect_resources(transition.effect),
1750                            runtime,
1751                        )
1752                        .map_err(GraphError::into_render_error)?,
1753                );
1754            }
1755        }
1756    }
1757    compiled[index].ok_or(RenderError::InvalidGraph)
1758}
1759
1760fn identity_layer(source: RenderNodeId) -> GraphLayer {
1761    GraphLayer {
1762        source,
1763        visual: LayerTransform {
1764            position: [0.5, 0.5],
1765            anchor: [0.5, 0.5],
1766            scale: [1.0, 1.0],
1767            rotation_degrees: 0.0,
1768            opacity: 1.0,
1769        },
1770        blend_mode: BlendMode::Normal,
1771    }
1772}
1773
1774/// A correction as a layer transform: turned and scaled about the layer's centre, then moved by
1775/// its translation in fractions of the displayed picture, as `Correction::apply` maps points.
1776fn correction_transform(correction: alpha2_eval::Correction) -> LayerTransform {
1777    LayerTransform {
1778        position: [
1779            0.5 + correction.translate.x * correction.picture.x,
1780            0.5 + correction.translate.y * correction.picture.y,
1781        ],
1782        anchor: [0.5, 0.5],
1783        scale: [correction.scale, correction.scale],
1784        rotation_degrees: correction.rotation_degrees,
1785        opacity: 1.0,
1786    }
1787}
1788
1789const fn layer_transform(visual: EvaluatedVisual) -> LayerTransform {
1790    LayerTransform {
1791        position: [visual.position.x, visual.position.y],
1792        anchor: [visual.anchor.x, visual.anchor.y],
1793        scale: [visual.scale.x, visual.scale.y],
1794        rotation_degrees: visual.rotation_degrees,
1795        opacity: visual.opacity,
1796    }
1797}
1798
1799/// The invocation's parameters at the frame's time.
1800///
1801/// Interpolated values are clamped to the parameter range since overshoot is intended motion.
1802/// Authored values pass as written, and the renderer rejects out-of-range ones.
1803fn effect_params<'a>(
1804    renderer: &dyn EffectCatalog,
1805    id: &EffectId,
1806    effect: ActiveEffect<'a>,
1807) -> EffectParams<'a> {
1808    let mut params = EffectParams::with_capacity(effect.authored().params.len());
1809    let definition = renderer.effect_definition(id);
1810    for (name, sample) in effect.params() {
1811        let mut value = param_value(sample.value);
1812        let spec = definition
1813            .as_ref()
1814            .and_then(|definition| definition.params.iter().find(|spec| spec.name == name));
1815        if let Some(spec) = spec {
1816            // A scalar data set feeding a Vec2 parameter sets both components.
1817            if let (ParamType::Vec2, ParamValue::Float(scalar)) = (spec.param_type, &value) {
1818                value = ParamValue::Vec2([*scalar, *scalar]);
1819            }
1820            if sample.interpolated {
1821                value = clamp_to_range(spec, value);
1822            }
1823        }
1824        params.insert(name, value);
1825    }
1826    params
1827}
1828
1829fn project_effect_id(
1830    renderer: &dyn EffectCatalog,
1831    id: &str,
1832    version: u32,
1833) -> Result<EffectId, RenderError> {
1834    renderer
1835        .project_effect_id(id, version)
1836        .ok_or(RenderError::UnknownEffect)
1837}
1838
1839fn clamp_to_range(spec: &ParamSpec, value: ParamValue) -> ParamValue {
1840    let clamp = |value: f32| {
1841        let value = spec.min.map_or(value, |minimum| value.max(minimum));
1842        spec.max.map_or(value, |maximum| value.min(maximum))
1843    };
1844    match value {
1845        ParamValue::Float(value) => ParamValue::Float(clamp(value)),
1846        ParamValue::Vec2([x, y]) => ParamValue::Vec2([clamp(x), clamp(y)]),
1847        ParamValue::Vec4(values) => ParamValue::Vec4(values.map(clamp)),
1848        other => other,
1849    }
1850}
1851
1852fn effect_resources(effect: ActiveEffect<'_>) -> EffectResources {
1853    effect
1854        .resources()
1855        .fold(EffectResources::new(), |resources, (name, id)| {
1856            resources.with(name, id.as_str())
1857        })
1858}
1859
1860const fn param_value(value: EffectValue) -> ParamValue {
1861    match value {
1862        EffectValue::Float(value) => ParamValue::Float(value),
1863        EffectValue::Vec2(value) => ParamValue::Vec2(value),
1864        EffectValue::Vec4(value) => ParamValue::Vec4(value),
1865        EffectValue::Color(value) => ParamValue::Color(value),
1866        EffectValue::Enum(value) => ParamValue::Enum(value),
1867        EffectValue::Bool(value) => ParamValue::Bool(value),
1868    }
1869}
1870
1871const fn blend_mode(mode: ClipBlendMode) -> BlendMode {
1872    match mode {
1873        ClipBlendMode::Normal => BlendMode::Normal,
1874        ClipBlendMode::Multiply => BlendMode::Multiply,
1875        ClipBlendMode::Screen => BlendMode::Screen,
1876        ClipBlendMode::Overlay => BlendMode::Overlay,
1877        ClipBlendMode::Darken => BlendMode::Darken,
1878        ClipBlendMode::Lighten => BlendMode::Lighten,
1879        ClipBlendMode::ColorDodge => BlendMode::ColorDodge,
1880        ClipBlendMode::ColorBurn => BlendMode::ColorBurn,
1881        ClipBlendMode::HardLight => BlendMode::HardLight,
1882        ClipBlendMode::SoftLight => BlendMode::SoftLight,
1883        ClipBlendMode::Difference => BlendMode::Difference,
1884        ClipBlendMode::Exclusion => BlendMode::Exclusion,
1885        ClipBlendMode::Hue => BlendMode::Hue,
1886        ClipBlendMode::Saturation => BlendMode::Saturation,
1887        ClipBlendMode::Color => BlendMode::Color,
1888        ClipBlendMode::Luminosity => BlendMode::Luminosity,
1889        ClipBlendMode::PlusLighter => BlendMode::PlusLighter,
1890    }
1891}
1892
1893#[cfg(test)]
1894mod tests;