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                RenderNode::Sum { source, placements } => Arc::new(super::sum::sum(
163                    &self.workers,
164                    &self.frame_pool,
165                    output(&outputs, *source),
166                    placements,
167                    CompositeSettings {
168                        size: graph.size,
169                        background: None,
170                        blend_space,
171                        max_filter_samples: quality.max_filter_samples,
172                    },
173                )?),
174            };
175            let stage = match &graph.nodes[node.index] {
176                RenderNode::Source(_) => None,
177                RenderNode::Effect { .. }
178                | RenderNode::Transition { .. }
179                | RenderNode::Generator { .. } => Some(&self.stats.kernel_micros),
180                RenderNode::Vector { .. } => Some(&self.stats.vector_micros),
181                RenderNode::Composite { .. } | RenderNode::Sum { .. } => {
182                    Some(&self.stats.composite_micros)
183                }
184            };
185            if let Some(counter) = stage {
186                add_elapsed(counter, node_started);
187                drawn += 1;
188            }
189            if let Some((key, pinned)) = cached.store[node.index] {
190                inserts.push((key, Arc::clone(&image), pinned));
191            }
192            outputs[node.index] = Some(image);
193            high_water = high_water.max(
194                outputs
195                    .iter()
196                    .flatten()
197                    .map(|image| image.retained_bytes())
198                    .sum(),
199            );
200            release_inputs(graph, &plan.last_use, &mut outputs, node, position);
201        }
202        let image = outputs[plan.output.index]
203            .take()
204            .ok_or(GraphError::SourceOutput)?;
205        self.keep_results(cached.clears, &inserts);
206        self.stats.graphs.fetch_add(1, Ordering::Relaxed);
207        self.stats.nodes.fetch_add(drawn, Ordering::Relaxed);
208        add_elapsed(&self.stats.render_micros, started);
209        self.stats
210            .image_high_water_bytes
211            .fetch_max(high_water, Ordering::Relaxed);
212        Ok(image)
213    }
214
215    /// Draws `graph` and packs it as YUV420 with `encoding` directly into the caller's planes; the
216    /// CPU counterpart of [`crate::Renderer::render_graph_yuv420p`].
217    ///
218    /// # Errors
219    /// [`Self::execute_graph`]'s errors, [`RenderError::TextureReadback`] for an odd size or a
220    /// target too small, and [`RenderError::UnsupportedOutputColor`] for an unpackable color.
221    pub fn render_graph_into_yuv420p(
222        &self,
223        graph: &RenderGraph<'_>,
224        encoding: YuvEncoding,
225        targets: &mut Yuv420pTargets<'_>,
226    ) -> Result<(), RenderError> {
227        let image = self
228            .execute_graph(graph)
229            .map_err(GraphError::into_render_error)?;
230        let started = Instant::now();
231        super::pack::pack_yuv420p(&self.workers, &image, encoding, targets)?;
232        add_elapsed(&self.stats.render_micros, started);
233        add_elapsed(&self.stats.pack_micros, started);
234        Ok(())
235    }
236
237    fn draw_kernel(
238        &self,
239        graph: &RenderGraph<'_>,
240        outputs: &[Option<Arc<CpuImage>>],
241        node: &KernelNode<'_>,
242    ) -> Result<CpuImage, GraphError> {
243        let entry = self.entry(node.effect).ok_or(RenderError::UnknownEffect)?;
244        let definition = &entry.definition;
245        if definition.kind != node.kind {
246            return Err(GraphError::EffectKindMismatch);
247        }
248        crate::runtime_effect::validate_runtime(node.runtime)?;
249        crate::runtime_effect::validate_params(&definition.params, node.params)?;
250        if node
251            .resources
252            .iter()
253            .any(|(name, _)| !definition.resources.iter().any(|spec| spec.name == name))
254        {
255            return Err(RenderError::InvalidEffectParams.into());
256        }
257        let mut held: Vec<(&str, std::sync::Arc<CpuLut>)> =
258            Vec::with_capacity(definition.resources.len());
259        for spec in &definition.resources {
260            let id = node
261                .resources
262                .get(&spec.name)
263                .ok_or(RenderError::MissingEffectResource)?;
264            let lut = self
265                .resource(id)
266                .ok_or(RenderError::MissingEffectResource)?;
267            held.push((spec.name.as_str(), lut));
268        }
269        let resources: Vec<(&str, &CpuLut)> =
270            held.iter().map(|(name, lut)| (*name, &**lut)).collect();
271        if node
272            .inputs
273            .iter()
274            .any(|(name, _)| !definition.inputs.iter().any(|spec| spec.name == *name))
275        {
276            return Err(RenderError::InvalidEffectParams.into());
277        }
278        let mut inputs = Vec::with_capacity(definition.inputs.len());
279        for spec in &definition.inputs {
280            let (_, input) = node
281                .inputs
282                .iter()
283                .find(|(name, _)| *name == spec.name)
284                .ok_or(RenderError::MissingEffectInput)?;
285            inputs.push((spec.name.as_str(), output(outputs, *input)));
286        }
287        let transparent = CpuImage::transparent(graph.size);
288        let source_a = node.source_a.map_or(&transparent, |id| output(outputs, id));
289        let source_b = node.source_b.map_or(source_a, |id| output(outputs, id));
290        let context = KernelContext {
291            size: graph.size,
292            definition,
293            params: node.params,
294            runtime: node.runtime,
295            max_filter_samples: self.quality_controls().max_filter_samples,
296            source_a,
297            source_b,
298            texels: [source_a.texels(), source_b.texels()],
299            inputs: &inputs,
300            resources: &resources,
301        };
302        let kernel = entry.kernel;
303        // Kernel bounds are in input pixels, which match the output only at output size. A source
304        // presented at another size is sampled in uv and can reach every pixel.
305        let matching = [source_a, source_b]
306            .into_iter()
307            .chain(inputs.iter().map(|(_, image)| *image))
308            .all(|image| image.size() == graph.size);
309        let bounds = if matching {
310            kernel.bounds(&context)
311        } else {
312            PixelBox::whole(graph.size)
313        }
314        .intersect(PixelBox::whole(graph.size));
315        if bounds.is_empty() {
316            return Ok(CpuImage::transparent(graph.size));
317        }
318        let width = bounds.width as usize;
319        let mut pixels = self.frame_pool.take(bounds.pixels());
320        self.workers.bands_with(
321            &mut pixels,
322            width,
323            || vec![[0.0_f32; 4]; width],
324            |row, first_row, band| {
325                row.fill([0.0; 4]);
326                for (index, line) in band.chunks_mut(width).enumerate() {
327                    #[allow(clippy::cast_possible_truncation)]
328                    let y = bounds.y + (first_row + index) as u32;
329                    kernel.row(&context, y, bounds.x, row);
330                    for (out, value) in line.iter_mut().zip(row.iter()) {
331                        *out = half::store4_nearest(*value);
332                    }
333                }
334            },
335        );
336        Ok(CpuImage::pooled(
337            graph.size,
338            bounds,
339            pixels,
340            &self.frame_pool,
341        ))
342    }
343
344    /// Stores drawn results unless the cache was cleared since `clears` was read with the lookups;
345    /// mirrors `Renderer::complete_graph_work`.
346    pub(crate) fn keep_results(
347        &self,
348        clears: u64,
349        inserts: &[(RenderCacheKey, Arc<CpuImage>, bool)],
350    ) {
351        if inserts.is_empty() {
352            return;
353        }
354        let mut cache = self.lock_cache();
355        if cache.clears() == clears {
356            for (key, image, pinned) in inserts {
357                cache.insert(*key, image, *pinned);
358            }
359        }
360    }
361
362    /// Result-cache lookups, as the GPU executor's `cached_results`.
363    fn cached_results(
364        &self,
365        graph: &RenderGraph<'_>,
366        order: &[RenderNodeId],
367        output: RenderNodeId,
368        blend_space: f32,
369    ) -> CachedResults {
370        let count = graph.nodes.len();
371        let mut cached = CachedResults {
372            hits: vec![None; count],
373            store: vec![None; count],
374            needed: vec![true; count],
375            clears: 0,
376        };
377        if graph.intents.iter().all(Option::is_none) {
378            return cached;
379        }
380        let mut cache = self.lock_cache();
381        if !cache.enabled() {
382            return cached;
383        }
384        cached.clears = cache.clears();
385        let eligibility = graph.eligibility();
386        let (mut hits, mut misses, mut ineligible) = (0, 0, 0);
387        cached.needed = vec![false; count];
388        cached.needed[output.index] = true;
389        for node in order.iter().rev() {
390            if !cached.needed[node.index] {
391                continue;
392            }
393            if let Some(intent) = graph.intents[node.index] {
394                if eligibility[node.index] == CacheEligibility::Eligible {
395                    let key = renderer_node_key(graph.cache_keys[node.index], blend_space);
396                    let pinned = intent == CacheIntent::Pin;
397                    if let Some(image) = cache.get(key, pinned) {
398                        cached.hits[node.index] = Some(image);
399                        hits += 1;
400                        continue;
401                    }
402                    cached.store[node.index] = Some((key, pinned));
403                    misses += 1;
404                } else if intent != CacheIntent::Bypass {
405                    ineligible += 1;
406                }
407            }
408            for input in graph.nodes[node.index].dependencies() {
409                cached.needed[input.index] = true;
410            }
411        }
412        let skipped = order
413            .iter()
414            .filter(|node| {
415                !cached.needed[node.index]
416                    && cached.hits[node.index].is_none()
417                    && !matches!(graph.nodes[node.index], RenderNode::Source(_))
418            })
419            .count() as u64;
420        cache.record(hits, misses, ineligible, skipped);
421        cached
422    }
423}
424
425struct CachedResults {
426    hits: Vec<Option<Arc<CpuImage>>>,
427    store: Vec<Option<(RenderCacheKey, bool)>>,
428    needed: Vec<bool>,
429    /// The cache's clear count read with the lookups.
430    clears: u64,
431}
432
433fn output(outputs: &[Option<Arc<CpuImage>>], node: RenderNodeId) -> &CpuImage {
434    outputs[node.index]
435        .as_deref()
436        .expect("compiled dependency has an output")
437}
438
439/// Drops the results `node` was the last to read.
440fn release_inputs(
441    graph: &RenderGraph<'_>,
442    last_use: &[Option<usize>],
443    outputs: &mut [Option<Arc<CpuImage>>],
444    node: RenderNodeId,
445    position: usize,
446) {
447    for dependency in graph.nodes[node.index].dependencies() {
448        if last_use[dependency.index] == Some(position) {
449            outputs[dependency.index] = None;
450        }
451    }
452}