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