Skip to main content

alpha2_engine/
layers.rs

1//! Where each clip a frame places lies on the canvas, without rendering.
2
3use alpha2_eval::{EvalError, EvaluatedVisual, contained_picture};
4use alpha2_media::SourceId;
5use alpha2_model::{ClipId, TrackId};
6use alpha2_time::MediaTime;
7use serde_json::{Value, json};
8
9use crate::EngineProject;
10use crate::frame::layer_transform;
11
12/// Four points on the canvas in pixels, `[x, y]` each: where the top left, top right, bottom left
13/// and bottom right of a rectangle land.
14pub type Corners = [[f64; 2]; 4];
15
16/// One clip a frame places, as the compositor places it.
17#[derive(Clone, Debug, PartialEq)]
18pub struct EvaluatedLayer<'a> {
19    /// The clip.
20    pub clip: &'a ClipId,
21    /// The track holding the clip.
22    pub track: &'a TrackId,
23    /// The clip's source.
24    pub source: &'a SourceId,
25    /// Whether the frame draws the clip ([`alpha2_eval::FrameDesc::draws`]) above zero opacity.
26    pub draws: bool,
27    /// The clip's transform and opacity at the frame's time.
28    pub visual: EvaluatedVisual,
29    /// Where the corners of the clip's canvas-shaped layer land on the canvas.
30    pub corners: Corners,
31    /// Where the source's picture, contain-fitted into the layer, lands; `None` unless the clip
32    /// shows a media source whose fingerprint records its displayed size.
33    pub picture: Option<Corners>,
34    /// Whether the clip is an adjustment clip, which has no picture of its own.
35    pub adjustment: bool,
36    /// Whether the clip is another clip's matte, drawn only into that matte.
37    pub matte: bool,
38}
39
40fn on_layer(corners: &Corners, (u, v): (f64, f64)) -> [f64; 2] {
41    let [top_left, top_right, bottom_left, _] = corners;
42    [0, 1].map(|axis| {
43        top_left[axis]
44            + u * (top_right[axis] - top_left[axis])
45            + v * (bottom_left[axis] - top_left[axis])
46    })
47}
48
49impl EngineProject {
50    /// Every clip the frame at `time` places, in drawing order.
51    ///
52    /// Corners come from the clip's own transform, without compositions, masks, corrections or
53    /// a shutter.
54    ///
55    /// # Errors
56    /// Returns an error if the immutable index and project disagree.
57    pub fn layers_at(&self, time: MediaTime) -> Result<Vec<EvaluatedLayer<'_>>, EvalError> {
58        let frame = self.evaluate(time)?;
59        let settings = &self.project().settings;
60        let (width, height) = (f64::from(settings.width), f64::from(settings.height));
61        let picture_size = |source: &SourceId| {
62            self.project()
63                .sources
64                .iter()
65                .find(|candidate| &candidate.id == source)
66                .and_then(|source| source.fingerprint.as_ref())
67                .and_then(|fingerprint| fingerprint.streams.as_ref())
68                .and_then(|streams| streams.video.as_ref())
69                .filter(|video| video.width > 0 && video.height > 0)
70                .map(|video| (video.width, video.height))
71        };
72        Ok(frame
73            .visual
74            .iter()
75            .filter_map(|clip| {
76                let visual = clip.visual?;
77                let corners = layer_transform(visual).corners(width, height);
78                let picture = clip
79                    .has_host_picture()
80                    .then(|| picture_size(clip.source_id))
81                    .flatten()
82                    .map(|size| {
83                        let share = contained_picture(size, width / height);
84                        let (low_u, high_u) = (
85                            0.5 - f64::from(share.x) / 2.0,
86                            0.5 + f64::from(share.x) / 2.0,
87                        );
88                        let (low_v, high_v) = (
89                            0.5 - f64::from(share.y) / 2.0,
90                            0.5 + f64::from(share.y) / 2.0,
91                        );
92                        [
93                            on_layer(&corners, (low_u, low_v)),
94                            on_layer(&corners, (high_u, low_v)),
95                            on_layer(&corners, (low_u, high_v)),
96                            on_layer(&corners, (high_u, high_v)),
97                        ]
98                    });
99                Some(EvaluatedLayer {
100                    clip: clip.clip_id,
101                    track: clip.track_id,
102                    source: clip.source_id,
103                    draws: frame.draws(clip) && visual.opacity > 0.0,
104                    visual,
105                    corners,
106                    picture,
107                    adjustment: clip.adjustment,
108                    matte: clip.is_matte,
109                })
110            })
111            .collect())
112    }
113
114    /// [`Self::layers_at`] as JSON `{ time, canvas: { width, height }, layers }`, each layer
115    /// `{ clip, track, source, draws, opacity, transform: { position, anchor, scale,
116    /// rotationDegrees }, corners, picture, adjustment, matte }` with `position`, `anchor` and
117    /// `scale` as `{ x, y }`, and `corners` and `picture` (or `null`) as four `[x, y]` canvas
118    /// pixels: top left, top right, bottom left, bottom right.
119    ///
120    /// # Errors
121    /// Returns an error if the immutable index and project disagree.
122    pub fn layers_json(&self, time: MediaTime) -> Result<String, EvalError> {
123        let point = |value: alpha2_model::Vec2| json!({ "x": value.x, "y": value.y });
124        let layers: Vec<Value> = self
125            .layers_at(time)?
126            .into_iter()
127            .map(|layer| {
128                json!({
129                    "clip": layer.clip.as_str(),
130                    "track": layer.track.as_str(),
131                    "source": layer.source.as_str(),
132                    "draws": layer.draws,
133                    "opacity": layer.visual.opacity,
134                    "transform": {
135                        "position": point(layer.visual.position),
136                        "anchor": point(layer.visual.anchor),
137                        "scale": point(layer.visual.scale),
138                        "rotationDegrees": layer.visual.rotation_degrees,
139                    },
140                    "corners": layer.corners,
141                    "picture": layer.picture,
142                    "adjustment": layer.adjustment,
143                    "matte": layer.matte,
144                })
145            })
146            .collect();
147        let settings = &self.project().settings;
148        Ok(json!({
149            "time": time.ticks(),
150            "canvas": { "width": settings.width, "height": settings.height },
151            "layers": layers,
152        })
153        .to_string())
154    }
155}
156
157#[cfg(test)]
158#[path = "layers_tests.rs"]
159mod tests;