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