Skip to main content

alpha2_render/cpu/
execute.rs

1//! Runs a render graph on the CPU with the GPU executor's walk (`graph_execute.rs`), drawing
2//! each node into a [`CpuImage`] by row bands.
3
4use std::sync::Arc;
5use std::sync::atomic::Ordering;
6
7use alpha2_media::YuvEncoding;
8use web_time::Instant;
9
10use super::CpuRenderer;
11use super::composite::{CompositeSettings, LayerInput, composite};
12use super::half;
13use super::image::{CpuImage, PixelBox};
14use super::kernels::{CpuLut, KernelContext};
15use super::renderer::add_elapsed;
16use crate::graph::{RenderGraph, RenderNode, RenderNodeId};
17use crate::graph_cache::renderer_node_key;
18use crate::{
19    CacheEligibility, CacheIntent, EffectId, EffectKind, EffectParams, EffectResources,
20    EffectRuntime, GraphError, RenderCacheKey, RenderError, Yuv420pTargets,
21};
22
23struct KernelNode<'a> {
24    effect: &'a EffectId,
25    kind: EffectKind,
26    source_a: Option<RenderNodeId>,
27    source_b: Option<RenderNodeId>,
28    inputs: Vec<(&'a str, RenderNodeId)>,
29    params: &'a EffectParams<'a>,
30    resources: &'a EffectResources,
31    runtime: EffectRuntime,
32}
33
34impl CpuRenderer {
35    /// Draws the reachable part of `graph` and returns its output.
36    ///
37    /// # Errors
38    /// A structural error or the first pass failure: [`RenderError::UnknownEffect`] for an effect
39    /// without a CPU kernel, [`RenderError::InvalidSource`] for a GPU source.
40    #[allow(clippy::too_many_lines)]
41    pub fn execute_graph(&self, graph: &RenderGraph<'_>) -> Result<Arc<CpuImage>, GraphError> {
42        self.frame_pool.next_frame();
43        let started = Instant::now();
44        let quality = self.quality_controls();
45        let plan = graph.compile()?;
46        if matches!(graph.nodes[plan.output.index], RenderNode::Source(_)) {
47            return Err(GraphError::SourceOutput);
48        }
49        let blend_space = graph.blend_space.unwrap_or(self.blend_space);
50        let cached =
51            self.cached_results(graph, &plan.order, plan.output, blend_space.shader_value());
52        let mut outputs: Vec<Option<Arc<CpuImage>>> = vec![None; graph.nodes.len()];
53        let mut inserts = Vec::new();
54        let mut drawn = 0_u64;
55        let mut high_water = 0_u64;
56        for (position, node) in plan.order.iter().copied().enumerate() {
57            if let Some(hit) = cached.hits[node.index].clone() {
58                outputs[node.index] = Some(hit);
59                release_inputs(graph, &plan.last_use, &mut outputs, node, position);
60                continue;
61            }
62            if !cached.needed[node.index] {
63                release_inputs(graph, &plan.last_use, &mut outputs, node, position);
64                continue;
65            }
66            let node_started = Instant::now();
67            let image = match &graph.nodes[node.index] {
68                RenderNode::Source(view) => {
69                    let source = view.cpu_source().ok_or(RenderError::InvalidSource)?;
70                    source.presented(self)
71                }
72                RenderNode::Effect {
73                    effect,
74                    source,
75                    inputs,
76                    params,
77                    resources,
78                    runtime,
79                } => Arc::new(self.draw_kernel(
80                    graph,
81                    &outputs,
82                    &KernelNode {
83                        effect,
84                        kind: EffectKind::Effect,
85                        source_a: Some(*source),
86                        source_b: None,
87                        inputs: inputs.iter().collect(),
88                        params,
89                        resources,
90                        runtime: *runtime,
91                    },
92                )?),
93                RenderNode::Transition {
94                    effect,
95                    from,
96                    to,
97                    params,
98                    resources,
99                    runtime,
100                } => Arc::new(self.draw_kernel(
101                    graph,
102                    &outputs,
103                    &KernelNode {
104                        effect,
105                        kind: EffectKind::Transition,
106                        source_a: Some(*from),
107                        source_b: Some(*to),
108                        inputs: Vec::new(),
109                        params,
110                        resources,
111                        runtime: *runtime,
112                    },
113                )?),
114                RenderNode::Generator {
115                    effect,
116                    params,
117                    resources,
118                    runtime,
119                } => Arc::new(self.draw_kernel(
120                    graph,
121                    &outputs,
122                    &KernelNode {
123                        effect,
124                        kind: EffectKind::Generator,
125                        source_a: None,
126                        source_b: None,
127                        inputs: Vec::new(),
128                        params,
129                        resources,
130                        runtime: *runtime,
131                    },
132                )?),
133                RenderNode::Vector { scene } => Arc::new(super::vector::draw(
134                    &self.workers,
135                    &self.frame_pool,
136                    &self.coverage,
137                    scene,
138                    graph.size,
139                    blend_space,
140                )?),
141                RenderNode::Composite { layers, background } => {
142                    let inputs = layers
143                        .iter()
144                        .map(|layer| LayerInput {
145                            image: output(&outputs, layer.source),
146                            visual: layer.visual,
147                            blend_mode: layer.blend_mode,
148                        })
149                        .collect::<Vec<_>>();
150                    Arc::new(composite(
151                        &self.workers,
152                        &self.frame_pool,
153                        &inputs,
154                        CompositeSettings {
155                            size: graph.size,
156                            background: *background,
157                            blend_space,
158                            max_filter_samples: quality.max_filter_samples,
159                        },
160                    )?)
161                }
162            };
163            let stage = match &graph.nodes[node.index] {
164                RenderNode::Source(_) => None,
165                RenderNode::Effect { .. }
166                | RenderNode::Transition { .. }
167                | RenderNode::Generator { .. } => Some(&self.stats.kernel_micros),
168                RenderNode::Vector { .. } => Some(&self.stats.vector_micros),
169                RenderNode::Composite { .. } => Some(&self.stats.composite_micros),
170            };
171            if let Some(counter) = stage {
172                add_elapsed(counter, node_started);
173                drawn += 1;
174            }
175            if let Some((key, pinned)) = cached.store[node.index] {
176                inserts.push((key, Arc::clone(&image), pinned));
177            }
178            outputs[node.index] = Some(image);
179            high_water = high_water.max(
180                outputs
181                    .iter()
182                    .flatten()
183                    .map(|image| image.retained_bytes())
184                    .sum(),
185            );
186            release_inputs(graph, &plan.last_use, &mut outputs, node, position);
187        }
188        let image = outputs[plan.output.index]
189            .take()
190            .ok_or(GraphError::SourceOutput)?;
191        self.keep_results(cached.clears, &inserts);
192        self.stats.graphs.fetch_add(1, Ordering::Relaxed);
193        self.stats.nodes.fetch_add(drawn, Ordering::Relaxed);
194        add_elapsed(&self.stats.render_micros, started);
195        self.stats
196            .image_high_water_bytes
197            .fetch_max(high_water, Ordering::Relaxed);
198        Ok(image)
199    }
200
201    /// Draws `graph` and packs it as YUV420 with `encoding` directly into the caller's planes; the
202    /// CPU counterpart of [`crate::Renderer::render_graph_yuv420p`].
203    ///
204    /// # Errors
205    /// [`Self::execute_graph`]'s errors, [`RenderError::TextureReadback`] for an odd size or a
206    /// target too small, and [`RenderError::UnsupportedOutputColor`] for an unpackable color.
207    pub fn render_graph_into_yuv420p(
208        &self,
209        graph: &RenderGraph<'_>,
210        encoding: YuvEncoding,
211        targets: &mut Yuv420pTargets<'_>,
212    ) -> Result<(), RenderError> {
213        let image = self
214            .execute_graph(graph)
215            .map_err(GraphError::into_render_error)?;
216        let started = Instant::now();
217        super::pack::pack_yuv420p(&self.workers, &image, encoding, targets)?;
218        add_elapsed(&self.stats.render_micros, started);
219        add_elapsed(&self.stats.pack_micros, started);
220        Ok(())
221    }
222
223    fn draw_kernel(
224        &self,
225        graph: &RenderGraph<'_>,
226        outputs: &[Option<Arc<CpuImage>>],
227        node: &KernelNode<'_>,
228    ) -> Result<CpuImage, GraphError> {
229        let entry = self.entry(node.effect).ok_or(RenderError::UnknownEffect)?;
230        let definition = &entry.definition;
231        if definition.kind != node.kind {
232            return Err(GraphError::EffectKindMismatch);
233        }
234        crate::runtime_effect::validate_runtime(node.runtime)?;
235        crate::runtime_effect::validate_params(&definition.params, node.params)?;
236        if node
237            .resources
238            .iter()
239            .any(|(name, _)| !definition.resources.iter().any(|spec| spec.name == name))
240        {
241            return Err(RenderError::InvalidEffectParams.into());
242        }
243        let mut held: Vec<(&str, std::sync::Arc<CpuLut>)> =
244            Vec::with_capacity(definition.resources.len());
245        for spec in &definition.resources {
246            let id = node
247                .resources
248                .get(&spec.name)
249                .ok_or(RenderError::MissingEffectResource)?;
250            let lut = self
251                .resource(id)
252                .ok_or(RenderError::MissingEffectResource)?;
253            held.push((spec.name.as_str(), lut));
254        }
255        let resources: Vec<(&str, &CpuLut)> =
256            held.iter().map(|(name, lut)| (*name, &**lut)).collect();
257        if node
258            .inputs
259            .iter()
260            .any(|(name, _)| !definition.inputs.iter().any(|spec| spec.name == *name))
261        {
262            return Err(RenderError::InvalidEffectParams.into());
263        }
264        let mut inputs = Vec::with_capacity(definition.inputs.len());
265        for spec in &definition.inputs {
266            let (_, input) = node
267                .inputs
268                .iter()
269                .find(|(name, _)| *name == spec.name)
270                .ok_or(RenderError::MissingEffectInput)?;
271            inputs.push((spec.name.as_str(), output(outputs, *input)));
272        }
273        let transparent = CpuImage::transparent(graph.size);
274        let source_a = node.source_a.map_or(&transparent, |id| output(outputs, id));
275        let source_b = node.source_b.map_or(source_a, |id| output(outputs, id));
276        let context = KernelContext {
277            size: graph.size,
278            definition,
279            params: node.params,
280            runtime: node.runtime,
281            max_filter_samples: self.quality_controls().max_filter_samples,
282            source_a,
283            source_b,
284            texels: [source_a.texels(), source_b.texels()],
285            inputs: &inputs,
286            resources: &resources,
287        };
288        let kernel = entry.kernel;
289        // Kernel bounds are in input pixels, which match the output only at output size. A source
290        // presented at another size is sampled in uv and can reach every pixel.
291        let matching = [source_a, source_b]
292            .into_iter()
293            .chain(inputs.iter().map(|(_, image)| *image))
294            .all(|image| image.size() == graph.size);
295        let bounds = if matching {
296            kernel.bounds(&context)
297        } else {
298            PixelBox::whole(graph.size)
299        }
300        .intersect(PixelBox::whole(graph.size));
301        if bounds.is_empty() {
302            return Ok(CpuImage::transparent(graph.size));
303        }
304        let width = bounds.width as usize;
305        let mut pixels = self.frame_pool.take(bounds.pixels());
306        self.workers.bands_with(
307            &mut pixels,
308            width,
309            || vec![[0.0_f32; 4]; width],
310            |row, first_row, band| {
311                row.fill([0.0; 4]);
312                for (index, line) in band.chunks_mut(width).enumerate() {
313                    #[allow(clippy::cast_possible_truncation)]
314                    let y = bounds.y + (first_row + index) as u32;
315                    kernel.row(&context, y, bounds.x, row);
316                    for (out, value) in line.iter_mut().zip(row.iter()) {
317                        *out = half::store4_nearest(*value);
318                    }
319                }
320            },
321        );
322        Ok(CpuImage::pooled(
323            graph.size,
324            bounds,
325            pixels,
326            &self.frame_pool,
327        ))
328    }
329
330    /// Stores drawn results unless the cache was cleared since `clears` was read with the lookups;
331    /// mirrors `Renderer::complete_graph_work`.
332    pub(crate) fn keep_results(
333        &self,
334        clears: u64,
335        inserts: &[(RenderCacheKey, Arc<CpuImage>, bool)],
336    ) {
337        if inserts.is_empty() {
338            return;
339        }
340        let mut cache = self.lock_cache();
341        if cache.clears() == clears {
342            for (key, image, pinned) in inserts {
343                cache.insert(*key, image, *pinned);
344            }
345        }
346    }
347
348    /// Result-cache lookups, as the GPU executor's `cached_results`.
349    fn cached_results(
350        &self,
351        graph: &RenderGraph<'_>,
352        order: &[RenderNodeId],
353        output: RenderNodeId,
354        blend_space: f32,
355    ) -> CachedResults {
356        let count = graph.nodes.len();
357        let mut cached = CachedResults {
358            hits: vec![None; count],
359            store: vec![None; count],
360            needed: vec![true; count],
361            clears: 0,
362        };
363        if graph.intents.iter().all(Option::is_none) {
364            return cached;
365        }
366        let mut cache = self.lock_cache();
367        if !cache.enabled() {
368            return cached;
369        }
370        cached.clears = cache.clears();
371        let eligibility = graph.eligibility();
372        let (mut hits, mut misses, mut ineligible) = (0, 0, 0);
373        cached.needed = vec![false; count];
374        cached.needed[output.index] = true;
375        for node in order.iter().rev() {
376            if !cached.needed[node.index] {
377                continue;
378            }
379            if let Some(intent) = graph.intents[node.index] {
380                if eligibility[node.index] == CacheEligibility::Eligible {
381                    let key = renderer_node_key(graph.cache_keys[node.index], blend_space);
382                    let pinned = intent == CacheIntent::Pin;
383                    if let Some(image) = cache.get(key, pinned) {
384                        cached.hits[node.index] = Some(image);
385                        hits += 1;
386                        continue;
387                    }
388                    cached.store[node.index] = Some((key, pinned));
389                    misses += 1;
390                } else if intent != CacheIntent::Bypass {
391                    ineligible += 1;
392                }
393            }
394            for input in graph.nodes[node.index].dependencies() {
395                cached.needed[input.index] = true;
396            }
397        }
398        let skipped = order
399            .iter()
400            .filter(|node| {
401                !cached.needed[node.index]
402                    && cached.hits[node.index].is_none()
403                    && !matches!(graph.nodes[node.index], RenderNode::Source(_))
404            })
405            .count() as u64;
406        cache.record(hits, misses, ineligible, skipped);
407        cached
408    }
409}
410
411struct CachedResults {
412    hits: Vec<Option<Arc<CpuImage>>>,
413    store: Vec<Option<(RenderCacheKey, bool)>>,
414    needed: Vec<bool>,
415    /// The cache's clear count read with the lookups.
416    clears: u64,
417}
418
419fn output(outputs: &[Option<Arc<CpuImage>>], node: RenderNodeId) -> &CpuImage {
420    outputs[node.index]
421        .as_deref()
422        .expect("compiled dependency has an output")
423}
424
425/// Drops the results `node` was the last to read.
426fn release_inputs(
427    graph: &RenderGraph<'_>,
428    last_use: &[Option<usize>],
429    outputs: &mut [Option<Arc<CpuImage>>],
430    node: RenderNodeId,
431    position: usize,
432) {
433    for dependency in graph.nodes[node.index].dependencies() {
434        if last_use[dependency.index] == Some(position) {
435            outputs[dependency.index] = None;
436        }
437    }
438}