alpha2-host-core 0.10.0

FFmpeg-free native host logic for alpha2: the policies, audio timelines, cursor rules, providers, plugin runtime, protocol frames and request parsing native hosts share, and the decode, export and still pipeline the mobile hosts run.
Documentation
//! Which frames an export cursor reads next, and when a decoder keeps decoding instead of seeking.
//!
//! A cursor is one reader of one source: a clip, or a composition step inside it, so two clips of
//! one file decode independently.

use std::collections::HashMap;

use alpha2_engine::ExportFrameNeeds;
use alpha2_eval::FrameNeed;
use alpha2_media::SourceId;
use alpha2_model::{ClipId, NodeId};
use alpha2_time::{MediaTime, TimeRange};

#[derive(Debug, Eq, PartialEq)]
/// The times a cursor asks for while its source time does not increase.
pub struct BackwardRun {
    /// Distinct, non-increasing, in the order the cursor asks for them.
    pub times: Vec<MediaTime>,
    /// The last export frame index of the run.
    pub until: u64,
}

/// Times while they do not increase and every frame asks for the cursor.
#[must_use]
pub fn backward_run(
    frames: &[ExportFrameNeeds],
    start: u64,
    cursor: &DecodeCursorKey,
) -> BackwardRun {
    let mut times = Vec::<MediaTime>::new();
    let mut until = start;
    for frame in frames.iter().skip_while(|frame| frame.index < start) {
        let Some(time) = cursor_time(frame, cursor) else {
            break;
        };
        match times.last() {
            Some(last) if time > *last => break,
            Some(last) if time == *last => {}
            _ => times.push(time),
        }
        until = frame.index;
    }
    BackwardRun { times, until }
}

/// The source time `frame` asks `cursor` for, if it reads it.
#[must_use]
pub fn cursor_time(frame: &ExportFrameNeeds, cursor: &DecodeCursorKey) -> Option<MediaTime> {
    frame
        .needs
        .iter()
        .find(|need| decode_cursor_key(need) == *cursor)
        .map(|need| need.media_time)
}

/// Two seconds, as the browser's video adapters use. Further ahead, a seek from the preceding
/// keyframe decodes less than every frame between.
pub const MAX_SEQUENTIAL_DECODE_GAP: MediaTime =
    MediaTime::from_ticks(2 * alpha2_time::TICKS_PER_SECOND);

/// Not backward, and at most [`MAX_SEQUENTIAL_DECODE_GAP`] ahead. Either way the frame presented at
/// `requested` is the one answered.
#[must_use]
pub fn decodes_on(previous: MediaTime, requested: MediaTime) -> bool {
    requested >= previous
        && requested.ticks().saturating_sub(previous.ticks()) <= MAX_SEQUENTIAL_DECODE_GAP.ticks()
}

/// The source, the clip, and the composition step reading it (none for the clip's own source).
pub type DecodeCursorKey = (SourceId, ClipId, Option<NodeId>);

/// The cursor a need reads through.
#[must_use]
pub fn decode_cursor_key(need: &FrameNeed) -> DecodeCursorKey {
    (
        need.source_id.clone(),
        need.clip_id.clone(),
        need.reader.clone(),
    )
}

/// What an export reads at once over its range, from one [`alpha2_eval::ActiveIndex`].
#[derive(Debug)]
pub struct VisualDecodeReads {
    /// Peak decoder cursors reading at once, at least 1. Provider sources and stills open none.
    pub decoder_peak: usize,
    /// Peak cursors of `video` sources reading at once, providers included; at least `decoder_peak`.
    pub frame_peak: usize,
    /// Peak cursors of `video` provider sources reading at once; may be 0.
    pub provider_peak: usize,
    /// Peak cursors of image sequences reading at once; may be 0.
    pub sequence_peak: usize,
    /// When each decoder cursor reads.
    pub reads: CursorReads,
}

/// [`VisualDecodeReads`] over `export_range`.
#[must_use]
pub fn visual_decode_reads(
    project: &alpha2_model::Project,
    export_range: TimeRange,
) -> VisualDecodeReads {
    let frame_by_frame = |provider: Option<bool>| {
        project
            .sources
            .iter()
            .filter(|source| {
                source.kind == alpha2_model::MediaKind::Video
                    && provider.is_none_or(|provider| source.provider.is_some() == provider)
            })
            .map(|source| &source.id)
            .collect::<std::collections::HashSet<_>>()
    };
    let decoded = frame_by_frame(Some(false));
    let provided = frame_by_frame(Some(true));
    let framed = frame_by_frame(None);
    let sequences = project
        .sources
        .iter()
        .filter(|source| {
            matches!(
                source.provider,
                Some(alpha2_model::ProviderSource::ImageSequence { .. })
            )
        })
        .map(|source| &source.id)
        .collect::<std::collections::HashSet<_>>();
    // An export validated the project already; an index it cannot build reads nothing.
    let Ok(index) = alpha2_eval::ActiveIndex::build(project) else {
        return VisualDecodeReads {
            decoder_peak: 1,
            frame_peak: 1,
            provider_peak: 0,
            sequence_peak: 0,
            reads: CursorReads::default(),
        };
    };
    let decoder_peak = index
        .peak_source_reads(export_range, |source| decoded.contains(source))
        .max(1);
    VisualDecodeReads {
        decoder_peak,
        frame_peak: index
            .peak_source_reads(export_range, |source| framed.contains(source))
            .max(decoder_peak),
        provider_peak: index.peak_source_reads(export_range, |source| provided.contains(source)),
        sequence_peak: index.peak_source_reads(export_range, |source| sequences.contains(source)),
        reads: CursorReads::new(
            index.source_reads(export_range, |source| decoded.contains(source)),
        ),
    }
}

/// Where each cursor may read ([`alpha2_eval::ActiveIndex::source_reads`]), which tells a shard
/// which session it can close and which one is read last. An unknown cursor is taken to be read
/// now, so it is never closed early and is evicted only by recency.
#[derive(Debug, Default)]
pub struct CursorReads {
    /// By start.
    spans: HashMap<DecodeCursorKey, Vec<TimeRange>>,
}

impl CursorReads {
    /// The spans every cursor reads, from the active index.
    #[must_use]
    pub fn new(reads: Vec<alpha2_eval::SourceRead>) -> Self {
        let mut spans = HashMap::<DecodeCursorKey, Vec<TimeRange>>::new();
        for read in reads {
            spans
                .entry((read.source_id, read.clip_id, read.reader))
                .or_default()
                .push(read.span);
        }
        for cursor_spans in spans.values_mut() {
            cursor_spans.sort_unstable_by_key(|span| span.start());
        }
        Self { spans }
    }

    /// Whether `cursor` has spans.
    #[must_use]
    pub fn knows(&self, cursor: &DecodeCursorKey) -> bool {
        self.spans.contains_key(cursor)
    }

    /// `time` itself inside a span, else the next span's start; `None` when nothing is read from
    /// `time` on or the cursor is unknown.
    #[must_use]
    pub fn next_read(&self, cursor: &DecodeCursorKey, time: MediaTime) -> Option<MediaTime> {
        self.spans
            .get(cursor)?
            .iter()
            .find(|span| span.end() > time)
            .map(|span| span.start().max(time))
    }

    /// Whether `cursor` reads nothing from `time` on.
    #[must_use]
    pub fn finished(&self, cursor: &DecodeCursorKey, time: MediaTime) -> bool {
        self.knows(cursor) && self.next_read(cursor, time).is_none()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn range(start: i64, end: i64) -> TimeRange {
        TimeRange::new(MediaTime::from_ticks(start), MediaTime::from_ticks(end)).expect("range")
    }

    #[test]
    fn decode_parallelism_counts_what_compositions_read() {
        use serde_json::json;
        let span = |start, end| json!({"start": start, "end": end});
        let video = |id: &str| json!({"id": id, "kind": "video", "locator": format!("{id}.mp4")});
        let media = |id: &str| json!({"id": id, "op": {"type": "media", "source_id": id}});
        let quad = json!({"id": "quad", "nodes": [
            media("a"), media("b"), media("c"), media("d"),
            {"id": "mix", "op": {"type": "merge", "layers": [
                {"input": "a"}, {"input": "b"}, {"input": "c"}, {"input": "d"}
            ]}}
        ], "output": "mix"});
        let project = |clip: serde_json::Value| {
            alpha2_model::Project::from_json(
                &json!({
                    "schema_version": 1, "id": "p", "name": "p",
                    "settings": {"width": 64, "height": 36, "frame_rate": {"num": 30, "den": 1}, "sample_rate": 48_000},
                    "sources": [video("a"), video("b"), video("c"), video("d"),
                        {"id": "split", "kind": "composition", "composition": "quad"}],
                    "compositions": [quad],
                    "timeline": {"tracks": [{"id": "t", "name": "V", "kind": "video", "clips": [clip]}]}
                })
                .to_string(),
            )
            .expect("valid")
        };
        let composed = project(json!({
            "id": "c", "source_id": "a", "composition": {"id": "quad"},
            "timeline_range": span(0, 120_000), "source_range": span(0, 120_000)
        }));
        assert_eq!(
            visual_decode_reads(&composed, range(0, 120_000)).decoder_peak,
            4
        );
        let source = project(json!({
            "id": "c", "source_id": "split",
            "timeline_range": span(0, 120_000), "source_range": span(0, 120_000)
        }));
        assert_eq!(
            visual_decode_reads(&source, range(0, 120_000)).decoder_peak,
            4
        );
    }

    #[test]
    fn peaks_count_the_provider_sources_that_play_frame_by_frame() {
        use serde_json::json;
        let span = |start, end| json!({"start": start, "end": end});
        let sequence = |id: &str| {
            json!({"id": id, "kind": "video", "locator": format!("sequence://{id}"),
                "provider": {"format": "image_sequence", "frames": ["f1", "f2"],
                    "frame_rate": {"num": 10, "den": 1}, "start_number": 1}})
        };
        let clip = |id: &str, source: &str, start: i64, end: i64| {
            json!({"id": id, "source_id": source,
                "timeline_range": span(start, end), "source_range": span(0, end - start)})
        };
        let track = |id: &str, clips: Vec<serde_json::Value>| json!({"id": id, "name": id, "kind": "video", "clips": clips});
        let project = |tracks: Vec<serde_json::Value>| {
            alpha2_model::Project::from_json(
                &json!({
                    "schema_version": 1, "id": "p", "name": "p",
                    "settings": {"width": 64, "height": 36, "frame_rate": {"num": 30, "den": 1}, "sample_rate": 48_000},
                    "sources": [
                        {"id": "video", "kind": "video", "locator": "video.mp4"},
                        sequence("s1"), sequence("s2"), sequence("s3"), sequence("s4"),
                        {"id": "anim", "kind": "video", "locator": "asset://anim",
                            "provider": {"format": "animated_image"}},
                        {"id": "logo", "kind": "image", "locator": "asset://logo",
                            "provider": {"format": "svg"}},
                        {"id": "layered", "kind": "composition", "composition": "over"}
                    ],
                    "compositions": [{"id": "over", "nodes": [
                        {"id": "m", "op": {"type": "media", "source_id": "s4"}}
                    ], "output": "m"}],
                    "timeline": {"tracks": tracks}
                })
                .to_string(),
            )
            .expect("valid")
        };
        let overlapping = project(vec![
            track("v", vec![clip("a", "video", 0, 120_000)]),
            track("s1", vec![clip("b", "s1", 0, 120_000)]),
            track("s2", vec![clip("c", "s2", 0, 120_000)]),
            track("s3", vec![clip("d", "s3", 0, 120_000)]),
            track("svg", vec![clip("e", "logo", 0, 120_000)]),
        ]);
        let reads = visual_decode_reads(&overlapping, range(0, 120_000));
        assert_eq!(
            (reads.decoder_peak, reads.frame_peak, reads.provider_peak),
            (1, 4, 3)
        );
        assert_eq!(reads.sequence_peak, 3);
        let composed = project(vec![
            track("v", vec![clip("a", "video", 0, 120_000)]),
            track("c", vec![clip("b", "layered", 0, 120_000)]),
        ]);
        let reads = visual_decode_reads(&composed, range(0, 120_000));
        assert_eq!(
            (reads.decoder_peak, reads.frame_peak, reads.provider_peak),
            (1, 2, 1)
        );
        assert_eq!(reads.sequence_peak, 1);
        let following = project(vec![track(
            "s",
            vec![
                clip("a", "s1", 0, 40_000),
                clip("b", "s2", 40_000, 80_000),
                clip("c", "s3", 80_000, 120_000),
            ],
        )]);
        let reads = visual_decode_reads(&following, range(0, 120_000));
        assert_eq!(
            (reads.decoder_peak, reads.frame_peak, reads.provider_peak),
            (1, 1, 1)
        );
        assert_eq!(reads.sequence_peak, 1);
        let beside_an_animation = project(vec![
            track("s", vec![clip("a", "s1", 0, 120_000)]),
            track("g", vec![clip("b", "anim", 0, 120_000)]),
        ]);
        let reads = visual_decode_reads(&beside_an_animation, range(0, 120_000));
        assert_eq!((reads.provider_peak, reads.sequence_peak), (2, 1));
        let none = project(vec![track("v", vec![clip("a", "video", 0, 120_000)])]);
        assert_eq!(
            visual_decode_reads(&none, range(0, 120_000)).sequence_peak,
            0
        );
    }
}