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