alpha2-engine 0.10.0

Player and exporter facade for alpha2.
Documentation
//! Where each clip a frame places lies on the canvas, without rendering.

use alpha2_eval::{EvalError, EvaluatedVisual, contained_picture};
use alpha2_media::SourceId;
use alpha2_model::{ClipId, TrackId};
use alpha2_time::MediaTime;
use serde_json::{Value, json};

use crate::EngineProject;
use crate::frame::layer_transform;

/// Four points on the canvas in pixels, `[x, y]` each: where the top left, top right, bottom left
/// and bottom right of a rectangle land.
pub type Corners = [[f64; 2]; 4];

/// One clip a frame places, as the compositor places it.
#[derive(Clone, Debug, PartialEq)]
pub struct EvaluatedLayer<'a> {
    /// The clip.
    pub clip: &'a ClipId,
    /// The track holding the clip.
    pub track: &'a TrackId,
    /// The clip's source.
    pub source: &'a SourceId,
    /// Whether the frame draws the clip ([`alpha2_eval::FrameDesc::draws`]) above zero opacity.
    pub draws: bool,
    /// The clip's transform and opacity at the frame's time.
    pub visual: EvaluatedVisual,
    /// Where the corners of the clip's canvas-shaped layer land on the canvas.
    pub corners: Corners,
    /// Where the source's picture, contain-fitted into the layer, lands; `None` unless the clip
    /// shows a media source whose fingerprint records its displayed size.
    pub picture: Option<Corners>,
    /// Whether the clip is an adjustment clip, which has no picture of its own.
    pub adjustment: bool,
    /// Whether the clip is another clip's matte, drawn only into that matte.
    pub matte: bool,
}

fn on_layer(corners: &Corners, (u, v): (f64, f64)) -> [f64; 2] {
    let [top_left, top_right, bottom_left, _] = corners;
    [0, 1].map(|axis| {
        top_left[axis]
            + u * (top_right[axis] - top_left[axis])
            + v * (bottom_left[axis] - top_left[axis])
    })
}

impl EngineProject {
    /// Every clip the frame at `time` places, in drawing order.
    ///
    /// Corners come from the clip's own transform, without compositions, masks, corrections or
    /// a shutter.
    ///
    /// # Errors
    /// Returns an error if the immutable index and project disagree.
    pub fn layers_at(&self, time: MediaTime) -> Result<Vec<EvaluatedLayer<'_>>, EvalError> {
        let frame = self.evaluate(time)?;
        let settings = &self.project().settings;
        let (width, height) = (f64::from(settings.width), f64::from(settings.height));
        let picture_size = |source: &SourceId| {
            self.project()
                .sources
                .iter()
                .find(|candidate| &candidate.id == source)
                .and_then(|source| source.fingerprint.as_ref())
                .and_then(|fingerprint| fingerprint.streams.as_ref())
                .and_then(|streams| streams.video.as_ref())
                .filter(|video| video.width > 0 && video.height > 0)
                .map(|video| (video.width, video.height))
        };
        Ok(frame
            .visual
            .iter()
            .filter_map(|clip| {
                let visual = clip.visual?;
                let corners = layer_transform(visual).corners(width, height);
                let picture = clip
                    .has_host_picture()
                    .then(|| picture_size(clip.source_id))
                    .flatten()
                    .map(|size| {
                        let share = contained_picture(size, width / height);
                        let (low_u, high_u) = (
                            0.5 - f64::from(share.x) / 2.0,
                            0.5 + f64::from(share.x) / 2.0,
                        );
                        let (low_v, high_v) = (
                            0.5 - f64::from(share.y) / 2.0,
                            0.5 + f64::from(share.y) / 2.0,
                        );
                        [
                            on_layer(&corners, (low_u, low_v)),
                            on_layer(&corners, (high_u, low_v)),
                            on_layer(&corners, (low_u, high_v)),
                            on_layer(&corners, (high_u, high_v)),
                        ]
                    });
                Some(EvaluatedLayer {
                    clip: clip.clip_id,
                    track: clip.track_id,
                    source: clip.source_id,
                    draws: frame.draws(clip) && visual.opacity > 0.0,
                    visual,
                    corners,
                    picture,
                    adjustment: clip.adjustment,
                    matte: clip.is_matte,
                })
            })
            .collect())
    }

    /// [`Self::layers_at`] as JSON `{ time, canvas: { width, height }, layers }`, each layer
    /// `{ clip, track, source, draws, opacity, transform: { position, anchor, scale,
    /// rotationDegrees }, corners, picture, adjustment, matte }` with `position`, `anchor` and
    /// `scale` as `{ x, y }`, and `corners` and `picture` (or `null`) as four `[x, y]` canvas
    /// pixels: top left, top right, bottom left, bottom right.
    ///
    /// # Errors
    /// Returns an error if the immutable index and project disagree.
    pub fn layers_json(&self, time: MediaTime) -> Result<String, EvalError> {
        let point = |value: alpha2_model::Vec2| json!({ "x": value.x, "y": value.y });
        let layers: Vec<Value> = self
            .layers_at(time)?
            .into_iter()
            .map(|layer| {
                json!({
                    "clip": layer.clip.as_str(),
                    "track": layer.track.as_str(),
                    "source": layer.source.as_str(),
                    "draws": layer.draws,
                    "opacity": layer.visual.opacity,
                    "transform": {
                        "position": point(layer.visual.position),
                        "anchor": point(layer.visual.anchor),
                        "scale": point(layer.visual.scale),
                        "rotationDegrees": layer.visual.rotation_degrees,
                    },
                    "corners": layer.corners,
                    "picture": layer.picture,
                    "adjustment": layer.adjustment,
                    "matte": layer.matte,
                })
            })
            .collect();
        let settings = &self.project().settings;
        Ok(json!({
            "time": time.ticks(),
            "canvas": { "width": settings.width, "height": settings.height },
            "layers": layers,
        })
        .to_string())
    }
}

#[cfg(test)]
#[path = "layers_tests.rs"]
mod tests;