Skip to main content

alpha2_engine/extract/
session.rs

1//! The host-driven step machine one run goes through.
2
3use super::descriptor::{
4    AudioChannels, BLOCK_FRAMES_RANGE, Descriptor, Direction, ExtractRequest, InputFrom, InputSpec,
5    MAX_EXTRACTOR_OUTPUTS, MAX_EXTRACTOR_PASSES, OutputSpec, Pass, VideoFormat,
6};
7use super::pixels::luma8_from_rgba8;
8use alpha2_media::SourceId;
9use alpha2_model::{
10    DataAnchor, DataInterval, DataKind, DataSamples, DataSet, DataSetId, DataValues, DataWord,
11    MadeBy, MediaKind, Project,
12};
13use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
14use std::collections::{BTreeMap, HashSet};
15use std::fmt;
16
17/// Where a source frame is asked for, relative to what the pass has seen.
18#[derive(Copy, Clone, Debug, Eq, PartialEq)]
19pub enum FrameFrom {
20    /// The frame shown at this time, the last with pts at or before it, else the first frame.
21    Start(MediaTime),
22    /// The next frame after the one with this pts, in the pass direction.
23    After(MediaTime),
24}
25
26/// What the host must supply next.
27#[derive(Clone, Debug, Eq, PartialEq)]
28pub enum Need {
29    /// A source frame; [`ExtractSession::supply_video`] or [`ExtractSession::supply_end`] answers.
30    SourceFrame {
31        /// The source.
32        source: SourceId,
33        /// Which frame.
34        from: FrameFrom,
35        /// The pass direction `from` is relative to.
36        direction: Direction,
37        /// The longest edge of the delivered frame ([`super::delivered_size`]).
38        size: u32,
39        /// Always supplied as `rgba8`; the session converts.
40        format: VideoFormat,
41    },
42    /// Source audio, answered by [`ExtractSession::supply_audio`]: exactly `frames` frames,
43    /// silence past the end of the stream.
44    SourceAudio {
45        /// The source.
46        source: SourceId,
47        /// Its audio stream ordinal.
48        stream: u32,
49        /// The first frame, in samples at `rate` from source time zero.
50        start_sample: i64,
51        /// How many frames.
52        frames: u32,
53        /// The sample rate.
54        rate: u32,
55        /// The channel layout.
56        channels: AudioChannels,
57    },
58    /// A rendered timeline frame, answered by [`ExtractSession::supply_video`].
59    TimelineFrame {
60        /// The frame's timeline time.
61        time: MediaTime,
62        /// The longest edge of the delivered frame.
63        size: u32,
64        /// Always supplied as `rgba8`; the session converts.
65        format: VideoFormat,
66    },
67    /// Timeline mix audio, answered like [`Need::SourceAudio`].
68    TimelineAudio {
69        /// The first frame, in samples at `rate` from timeline time zero.
70        start_sample: i64,
71        /// How many frames.
72        frames: u32,
73        /// The sample rate.
74        rate: u32,
75        /// The channel layout.
76        channels: AudioChannels,
77    },
78}
79
80/// A supplied video frame: tightly packed straight-alpha sRGB RGBA8 at its delivered size.
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct SuppliedFrame {
83    /// The frame's presentation time on the input's clock.
84    pub pts: MediaTime,
85    /// Width in pixels.
86    pub width: u32,
87    /// Height in pixels.
88    pub height: u32,
89    /// `width * height * 4` bytes, rows top to bottom.
90    pub rgba: Vec<u8>,
91}
92
93/// A supplied audio block: planar f32, channel after channel.
94#[derive(Clone, Debug, PartialEq)]
95pub struct SuppliedAudio {
96    /// The channel count.
97    pub channels: u32,
98    /// `channels * frames` samples.
99    pub samples: Vec<f32>,
100}
101
102/// A frame handed to the extractor.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct VideoInput {
105    /// Presentation time on the input's clock.
106    pub time: MediaTime,
107    /// Width in pixels.
108    pub width: u32,
109    /// Height in pixels.
110    pub height: u32,
111    /// The pixel format of `bytes`.
112    pub format: VideoFormat,
113    /// Tightly packed pixels, rows top to bottom.
114    pub bytes: Vec<u8>,
115}
116
117/// An audio block handed to the extractor.
118#[derive(Clone, Debug, PartialEq)]
119pub struct AudioInput {
120    /// The block's first sample, at `rate` from the clock's zero.
121    pub start_sample: i64,
122    /// The block's first sample time, the tick at or before it.
123    pub start: MediaTime,
124    /// Frames in the block.
125    pub frames: u32,
126    /// The sample rate.
127    pub rate: u32,
128    /// The channel count.
129    pub channels: u32,
130    /// `channels * frames` planar samples, channel after channel.
131    pub samples: Vec<f32>,
132}
133
134/// An input handed to the extractor.
135#[derive(Clone, Debug, PartialEq)]
136pub enum Delivery {
137    /// A video frame.
138    Video(VideoInput),
139    /// An audio block.
140    Audio(AudioInput),
141}
142
143/// What the session asks for or hands over next.
144#[derive(Clone, Debug, PartialEq)]
145pub enum Step {
146    /// The host supplies this.
147    Need(Need),
148    /// The extractor reads this and emits through [`ExtractSession::emit`].
149    Deliver(Delivery),
150    /// A pass begins.
151    PassBoundary {
152        /// The pass's position in the request.
153        pass: usize,
154        /// Its direction.
155        direction: Direction,
156    },
157    /// Every pass ended; the extractor's end and [`ExtractSession::finish`] follow.
158    Done,
159}
160
161/// One value an extractor emits.
162#[derive(Clone, Debug, PartialEq)]
163pub enum Emit {
164    /// A sample of a `points`, `scalars` or `similarity` output.
165    Sample {
166        /// The output's name.
167        output: String,
168        /// The sample time on the input's clock.
169        time: MediaTime,
170        /// The sample's numbers, `None` for a lost channel.
171        values: Vec<Option<f32>>,
172    },
173    /// A word of a `words` output.
174    Word {
175        /// The output's name.
176        output: String,
177        /// The word.
178        word: DataWord,
179    },
180    /// An interval of an `intervals` output.
181    Interval {
182        /// The output's name.
183        output: String,
184        /// The interval.
185        interval: DataInterval,
186    },
187}
188
189impl Emit {
190    fn output(&self) -> &str {
191        match self {
192            Self::Sample { output, .. }
193            | Self::Word { output, .. }
194            | Self::Interval { output, .. } => output,
195        }
196    }
197}
198
199/// Why a session could not start.
200#[derive(Clone, Debug, Eq, PartialEq)]
201#[non_exhaustive]
202pub enum RequestError {
203    /// The request names another extractor or version than the descriptor.
204    WrongExtractor,
205    /// The descriptor breaks a rule (outputs, block size, size).
206    InvalidDescriptor(String),
207    /// The request reads an input the descriptor does not, or a source the project lacks or
208    /// that cannot feed the input.
209    InvalidInput(String),
210    /// The range is empty or negative, or a pass starts outside it.
211    InvalidRange,
212    /// The range ends past the source's fingerprinted duration, in ticks.
213    RangePastSource(i64),
214    /// `size` is zero or above the descriptor's `max_size`.
215    InvalidSize,
216    /// The audio rate or channels conflict with the descriptor's fixed ones, or are invalid.
217    InvalidAudio,
218    /// The outputs map names an undeclared output, or repeats a data set id.
219    InvalidOutputs(String),
220}
221
222impl fmt::Display for RequestError {
223    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
224        match self {
225            Self::WrongExtractor => {
226                formatter.write_str("the request names another extractor or version")
227            }
228            Self::InvalidDescriptor(why) => write!(formatter, "invalid descriptor: {why}"),
229            Self::InvalidInput(why) => write!(formatter, "invalid input: {why}"),
230            Self::InvalidRange => {
231                formatter.write_str("the range is empty or negative, or a pass starts outside it")
232            }
233            Self::RangePastSource(duration) => write!(
234                formatter,
235                "the range ends past the source's duration of {duration} ticks"
236            ),
237            Self::InvalidSize => {
238                formatter.write_str("size is zero or above the descriptor's max_size")
239            }
240            Self::InvalidAudio => formatter.write_str(
241                "the audio rate or channels are invalid or conflict with the descriptor",
242            ),
243            Self::InvalidOutputs(why) => write!(formatter, "invalid outputs: {why}"),
244        }
245    }
246}
247
248impl std::error::Error for RequestError {}
249
250/// Why the session refused something.
251#[derive(Clone, Debug, PartialEq)]
252#[non_exhaustive]
253pub enum SessionError {
254    /// A supply that does not answer the outstanding need.
255    UnexpectedSupply(String),
256    /// An emit that breaks a rule.
257    InvalidEmit {
258        /// Its position among the emits handed over at once.
259        index: usize,
260        /// The rule broken.
261        reason: String,
262    },
263    /// `finish` before the run is done, or a time emitted twice.
264    InvalidResult(String),
265}
266
267impl fmt::Display for SessionError {
268    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self {
270            Self::UnexpectedSupply(why) => write!(formatter, "unexpected supply: {why}"),
271            Self::InvalidEmit { index, reason } => {
272                write!(formatter, "invalid emit {index}: {reason}")
273            }
274            Self::InvalidResult(why) => write!(formatter, "invalid result: {why}"),
275        }
276    }
277}
278
279impl std::error::Error for SessionError {}
280
281/// Completed and total deliveries of one pass; the total is unknown for source frames.
282#[derive(Copy, Clone, Debug, Eq, PartialEq)]
283pub struct PassProgress {
284    /// Deliveries handed over.
285    pub completed: u64,
286    /// Deliveries the pass will hand over, when known.
287    pub total: Option<u64>,
288}
289
290/// What the extractor is told when the run begins.
291#[derive(Clone, Debug, PartialEq)]
292pub struct RunContext {
293    /// The interval read.
294    pub range: TimeRange,
295    /// The passes, in order.
296    pub passes: Vec<Pass>,
297    /// The clock read.
298    pub from: InputFrom,
299    /// For video, the longest edge of delivered frames and their format.
300    pub video: Option<(u32, VideoFormat)>,
301    /// For audio, the rate, channel layout and block size.
302    pub audio: Option<(u32, AudioChannels, u32)>,
303    /// For timeline frames, their rate.
304    pub frame_rate: Option<FrameRate>,
305}
306
307#[derive(Clone, Debug)]
308enum Input {
309    SourceVideo {
310        source: SourceId,
311        size: u32,
312        format: VideoFormat,
313    },
314    TimelineVideo {
315        size: u32,
316        format: VideoFormat,
317        rate: FrameRate,
318    },
319    SourceAudio {
320        source: SourceId,
321        stream: u32,
322        rate: u32,
323        channels: AudioChannels,
324        block: u32,
325    },
326    TimelineAudio {
327        rate: u32,
328        channels: AudioChannels,
329        block: u32,
330    },
331}
332
333/// Where the session is.
334#[derive(Clone, Debug)]
335enum Phase {
336    /// The next pass begins with a boundary.
337    BeforePass(usize),
338    /// In a pass, asking for its next input.
339    Running(Cursor),
340    /// A need is outstanding.
341    Waiting(Cursor, Need),
342    /// A supplied input waits to be handed over; the cursor continues after it.
343    Delivering(Cursor, Delivery),
344    /// All passes ended.
345    Done,
346    /// The result was taken.
347    Finished,
348}
349
350#[derive(Clone, Copy, Debug)]
351struct Cursor {
352    pass: usize,
353    /// The last delivered pts for source frames, the next frame index for timeline frames, and the
354    /// next block's first sample (forward) or exclusive end (backward) for audio.
355    position: Option<i64>,
356}
357
358/// The emits of one output, gathered across passes.
359#[derive(Default, Debug)]
360struct Gathered {
361    samples: Vec<(MediaTime, Vec<Option<f32>>)>,
362    words: Vec<DataWord>,
363    intervals: Vec<DataInterval>,
364}
365
366impl Gathered {
367    /// Items of the one kind an output gathers.
368    fn len(&self) -> usize {
369        self.samples.len() + self.words.len() + self.intervals.len()
370    }
371}
372
373/// Why an emit to `output` was refused at its data limit.
374fn over_limit(output: &OutputSpec) -> String {
375    let (limit, what) = match output.kind {
376        DataKind::Points | DataKind::Scalars | DataKind::Similarity => {
377            (alpha2_model::MAX_DATA_VALUES, "values")
378        }
379        DataKind::Words => (alpha2_model::MAX_DATA_WORDS, "words"),
380        DataKind::Intervals => (alpha2_model::MAX_DATA_INTERVALS, "intervals"),
381    };
382    format!("output {} would hold more than {limit} {what}", output.name)
383}
384
385/// One run of an extractor over a range, driven by the host.
386///
387/// The host loops on [`Self::next`]: it supplies each [`Need`], hands each [`Delivery`] to the
388/// extractor and passes the extractor's [`Emit`]s to [`Self::emit`], and stops at
389/// [`Step::Done`]. Cancelling is not calling `next` again. [`Self::finish`] returns validated
390/// data sets. The session never decodes, renders or reads files.
391#[derive(Debug)]
392pub struct ExtractSession {
393    descriptor: Descriptor,
394    request: ExtractRequest,
395    input: Input,
396    anchor: DataAnchor,
397    passes: Vec<Pass>,
398    phase: Phase,
399    progress: Vec<PassProgress>,
400    /// The latest delivery's bound in the current pass, a frame pts or a block's edge.
401    delivered: Option<MediaTime>,
402    /// The pts of every frame delivered, which emits may name even before the range.
403    delivered_pts: HashSet<MediaTime>,
404    /// Per output, the latest emitted time in the current pass.
405    last_time: BTreeMap<String, MediaTime>,
406    gathered: BTreeMap<String, Gathered>,
407}
408
409pub(super) fn validate_descriptor(descriptor: &Descriptor) -> Result<(), RequestError> {
410    let invalid = |why: &str| Err(RequestError::InvalidDescriptor(why.to_owned()));
411    if descriptor.id.is_empty() {
412        return invalid("empty id");
413    }
414    if descriptor.outputs.is_empty() || descriptor.outputs.len() > MAX_EXTRACTOR_OUTPUTS {
415        return invalid("needs 1 to 32 outputs");
416    }
417    let mut names = HashSet::new();
418    for output in &descriptor.outputs {
419        if output.name.is_empty() || !names.insert(&output.name) {
420            return invalid("an output name is empty or repeated");
421        }
422        let sampled = matches!(output.kind, DataKind::Points | DataKind::Scalars);
423        if sampled == output.channels.is_empty() {
424            return invalid("points and scalars outputs need channels; others take none");
425        }
426        if output.channels.len() > alpha2_model::MAX_DATA_CHANNELS {
427            return invalid("an output has too many channels");
428        }
429        let mut channels = HashSet::new();
430        if output.channels.iter().any(|channel| {
431            channel.is_empty()
432                || channel.len() > alpha2_model::MAX_DATA_LABEL_BYTES
433                || !channels.insert(channel)
434        }) {
435            return invalid("a channel name is empty, too long or repeated");
436        }
437        if output.interpolation.is_some() && output.kind.arity().is_none() {
438            return invalid("only sampled outputs take an interpolation");
439        }
440    }
441    if descriptor.input.from().is_empty() {
442        return invalid("reads no input");
443    }
444    match &descriptor.input {
445        InputSpec::Video { max_size, .. } if *max_size == 0 => invalid("max_size is zero"),
446        InputSpec::Audio {
447            block_frames,
448            sample_rate,
449            ..
450        } if !BLOCK_FRAMES_RANGE.contains(block_frames)
451            || sample_rate.is_some_and(|rate| !alpha2_model::SAMPLE_RATE_RANGE.contains(&rate)) =>
452        {
453            invalid("block_frames or sample_rate out of range")
454        }
455        _ => Ok(()),
456    }
457}
458
459impl ExtractSession {
460    /// Starts a run of the extractor `descriptor` describes, as `request` asks, over `project`.
461    ///
462    /// # Errors
463    /// [`RequestError`] when the descriptor or request breaks a rule.
464    #[allow(clippy::too_many_lines)]
465    pub fn new(
466        project: &Project,
467        descriptor: &Descriptor,
468        request: ExtractRequest,
469    ) -> Result<Self, RequestError> {
470        validate_descriptor(descriptor)?;
471        if request.extractor != descriptor.id || request.version != descriptor.version {
472            return Err(RequestError::WrongExtractor);
473        }
474        let read = &request.input;
475        if !descriptor.input.from().contains(&read.from) {
476            return Err(RequestError::InvalidInput(
477                "the descriptor does not read this input".to_owned(),
478            ));
479        }
480        let range = read.range;
481        if range.is_empty() || range.start().ticks() < 0 {
482            return Err(RequestError::InvalidRange);
483        }
484        if read.passes.len() > MAX_EXTRACTOR_PASSES
485            || read.passes.iter().any(|pass| !range.contains(pass.start))
486        {
487            return Err(RequestError::InvalidRange);
488        }
489        let source = match read.from {
490            InputFrom::Source => {
491                let id = read.source_id.as_ref().ok_or_else(|| {
492                    RequestError::InvalidInput("source input needs source_id".to_owned())
493                })?;
494                let source = project
495                    .sources
496                    .iter()
497                    .find(|source| &source.id == id)
498                    .ok_or_else(|| RequestError::InvalidInput(format!("unknown source {id}")))?;
499                let fits = match &descriptor.input {
500                    InputSpec::Video { .. } => {
501                        matches!(source.kind, MediaKind::Video | MediaKind::Image)
502                    }
503                    InputSpec::Audio { .. } => source.kind == MediaKind::Audio || source.has_audio,
504                };
505                if !fits {
506                    return Err(RequestError::InvalidInput(format!(
507                        "source {id} cannot feed this input"
508                    )));
509                }
510                let duration = source
511                    .fingerprint
512                    .as_ref()
513                    .and_then(|fingerprint| fingerprint.duration_ticks);
514                if let Some(duration) = duration
515                    && range.end().ticks() > duration
516                {
517                    return Err(RequestError::RangePastSource(duration));
518                }
519                Some(id.clone())
520            }
521            InputFrom::Timeline => {
522                if read.source_id.is_some() {
523                    return Err(RequestError::InvalidInput(
524                        "timeline input takes no source_id".to_owned(),
525                    ));
526                }
527                None
528            }
529        };
530        let input = match (&descriptor.input, source.clone()) {
531            (
532                InputSpec::Video {
533                    format, max_size, ..
534                },
535                source,
536            ) => {
537                if read.stream.is_some() || read.sample_rate.is_some() || read.channels.is_some() {
538                    return Err(RequestError::InvalidInput(
539                        "video input takes no audio fields".to_owned(),
540                    ));
541                }
542                let size = read.size.unwrap_or(*max_size);
543                if size == 0 || size > *max_size {
544                    return Err(RequestError::InvalidSize);
545                }
546                match source {
547                    Some(source) => {
548                        if read.frame_rate.is_some() {
549                            return Err(RequestError::InvalidInput(
550                                "source input takes no frame_rate".to_owned(),
551                            ));
552                        }
553                        Input::SourceVideo {
554                            source,
555                            size,
556                            format: *format,
557                        }
558                    }
559                    None => Input::TimelineVideo {
560                        size,
561                        format: *format,
562                        rate: read.frame_rate.unwrap_or(project.settings.frame_rate),
563                    },
564                }
565            }
566            (
567                InputSpec::Audio {
568                    sample_rate,
569                    channels,
570                    block_frames,
571                    ..
572                },
573                source,
574            ) => {
575                if read.size.is_some() || read.frame_rate.is_some() {
576                    return Err(RequestError::InvalidInput(
577                        "audio input takes no video fields".to_owned(),
578                    ));
579                }
580                let rate = match (sample_rate, read.sample_rate) {
581                    (Some(fixed), Some(asked)) if *fixed != asked => {
582                        return Err(RequestError::InvalidAudio);
583                    }
584                    (Some(fixed), _) => *fixed,
585                    (None, Some(asked)) => asked,
586                    (None, None) => project.settings.sample_rate,
587                };
588                if !alpha2_model::SAMPLE_RATE_RANGE.contains(&rate) {
589                    return Err(RequestError::InvalidAudio);
590                }
591                let layout = match (channels, read.channels) {
592                    (Some(fixed), Some(asked)) if *fixed != asked => {
593                        return Err(RequestError::InvalidAudio);
594                    }
595                    (Some(fixed), _) => *fixed,
596                    (None, Some(asked)) => asked,
597                    (None, None) => AudioChannels::Mono,
598                };
599                if let Some(source) = source {
600                    Input::SourceAudio {
601                        source,
602                        stream: read.stream.unwrap_or(0),
603                        rate,
604                        channels: layout,
605                        block: *block_frames,
606                    }
607                } else {
608                    if read.stream.is_some() {
609                        return Err(RequestError::InvalidInput(
610                            "timeline input takes no stream".to_owned(),
611                        ));
612                    }
613                    Input::TimelineAudio {
614                        rate,
615                        channels: layout,
616                        block: *block_frames,
617                    }
618                }
619            }
620        };
621        let mut ids = HashSet::new();
622        for (name, id) in &request.outputs {
623            if !descriptor.outputs.iter().any(|output| &output.name == name) {
624                return Err(RequestError::InvalidOutputs(format!(
625                    "undeclared output {name}"
626                )));
627            }
628            if !ids.insert(id) {
629                return Err(RequestError::InvalidOutputs(format!(
630                    "data set id {id} repeated"
631                )));
632            }
633        }
634        let passes = if read.passes.is_empty() {
635            vec![Pass {
636                start: range.start(),
637                direction: Direction::Forward,
638            }]
639        } else {
640            read.passes.clone()
641        };
642        let anchor = source.map_or(DataAnchor::Timeline, |source_id| DataAnchor::Source {
643            source_id,
644        });
645        let mut session = Self {
646            descriptor: descriptor.clone(),
647            request,
648            input,
649            anchor,
650            progress: Vec::new(),
651            passes,
652            phase: Phase::BeforePass(0),
653            delivered: None,
654            delivered_pts: HashSet::new(),
655            last_time: BTreeMap::new(),
656            gathered: BTreeMap::new(),
657        };
658        session.progress = (0..session.passes.len())
659            .map(|pass| PassProgress {
660                completed: 0,
661                total: session.pass_total(pass),
662            })
663            .collect();
664        Ok(session)
665    }
666
667    /// The run's context, for the extractor's `begin`.
668    #[must_use]
669    pub fn context(&self) -> RunContext {
670        let (video, audio, frame_rate) = match &self.input {
671            Input::SourceVideo { size, format, .. } => (Some((*size, *format)), None, None),
672            Input::TimelineVideo { size, format, rate } => {
673                (Some((*size, *format)), None, Some(*rate))
674            }
675            Input::SourceAudio {
676                rate,
677                channels,
678                block,
679                ..
680            }
681            | Input::TimelineAudio {
682                rate,
683                channels,
684                block,
685            } => (None, Some((*rate, *channels, *block)), None),
686        };
687        RunContext {
688            range: self.request.input.range,
689            passes: self.passes.clone(),
690            from: self.request.input.from,
691            video,
692            audio,
693            frame_rate,
694        }
695    }
696
697    /// The descriptor the session runs.
698    #[must_use]
699    pub const fn descriptor(&self) -> &Descriptor {
700        &self.descriptor
701    }
702
703    /// The request the session runs.
704    #[must_use]
705    pub const fn request(&self) -> &ExtractRequest {
706        &self.request
707    }
708
709    /// Completed and total deliveries of each pass.
710    #[must_use]
711    pub fn progress(&self) -> &[PassProgress] {
712        &self.progress
713    }
714
715    fn range(&self) -> TimeRange {
716        self.request.input.range
717    }
718
719    /// Samples of the audio grid at `rate` whose start lies in the range: `[first, last)`.
720    fn sample_span(&self, rate: u32) -> (i64, i64) {
721        let range = self.range();
722        (
723            samples_ceil(range.start(), rate),
724            samples_ceil(range.end(), rate),
725        )
726    }
727
728    fn pass_total(&self, pass: usize) -> Option<u64> {
729        let Pass { start, direction } = self.passes[pass];
730        match &self.input {
731            Input::SourceVideo { .. } => None,
732            Input::TimelineVideo { rate, .. } => {
733                let (first, last) = timeline_frames(self.range(), *rate)?;
734                let at = start_frame(start, *rate, first, last)?;
735                let count = match direction {
736                    Direction::Forward => last - at,
737                    Direction::Backward => at - first + 1,
738                };
739                u64::try_from(count).ok()
740            }
741            Input::SourceAudio { rate, block, .. } | Input::TimelineAudio { rate, block, .. } => {
742                let (first, last) = self.sample_span(*rate);
743                let at = samples_ceil(start, *rate).clamp(first, last);
744                let span = match direction {
745                    Direction::Forward => last - at,
746                    Direction::Backward => at - first,
747                };
748                u64::try_from(span)
749                    .ok()
750                    .map(|span| span.div_ceil(u64::from(*block)))
751            }
752        }
753    }
754
755    /// The next step. Calling it again before supplying an outstanding need repeats the need.
756    #[allow(clippy::should_implement_trait)]
757    pub fn next(&mut self) -> Step {
758        loop {
759            match std::mem::replace(&mut self.phase, Phase::Done) {
760                Phase::BeforePass(pass) if pass >= self.passes.len() => {
761                    self.phase = Phase::Done;
762                    self.last_time.clear();
763                    self.delivered = None;
764                    return Step::Done;
765                }
766                Phase::BeforePass(pass) => {
767                    self.phase = Phase::Running(Cursor {
768                        pass,
769                        position: None,
770                    });
771                    self.delivered = None;
772                    self.last_time.clear();
773                    return Step::PassBoundary {
774                        pass,
775                        direction: self.passes[pass].direction,
776                    };
777                }
778                Phase::Running(cursor) => match self.need_at(cursor) {
779                    Some(need) => {
780                        self.phase = Phase::Waiting(cursor, need.clone());
781                        return Step::Need(need);
782                    }
783                    None => self.phase = Phase::BeforePass(cursor.pass + 1),
784                },
785                Phase::Waiting(cursor, need) => {
786                    self.phase = Phase::Waiting(cursor, need.clone());
787                    return Step::Need(need);
788                }
789                Phase::Delivering(cursor, delivery) => {
790                    self.progress[cursor.pass].completed += 1;
791                    self.phase = Phase::Running(cursor);
792                    return Step::Deliver(delivery);
793                }
794                Phase::Done => {
795                    self.phase = Phase::Done;
796                    return Step::Done;
797                }
798                Phase::Finished => {
799                    self.phase = Phase::Finished;
800                    return Step::Done;
801                }
802            }
803        }
804    }
805
806    /// The need at `cursor`, or `None` when its pass has ended.
807    fn need_at(&self, cursor: Cursor) -> Option<Need> {
808        let Pass { start, direction } = self.passes[cursor.pass];
809        match &self.input {
810            Input::SourceVideo {
811                source,
812                size,
813                format,
814            } => {
815                if cursor.position == Some(i64::MIN) {
816                    return None;
817                }
818                let from = cursor.position.map_or(FrameFrom::Start(start), |pts| {
819                    FrameFrom::After(MediaTime(pts))
820                });
821                Some(Need::SourceFrame {
822                    source: source.clone(),
823                    from,
824                    direction,
825                    size: *size,
826                    format: *format,
827                })
828            }
829            Input::TimelineVideo { size, format, rate } => {
830                let (first, last) = timeline_frames(self.range(), *rate)?;
831                let frame = match cursor.position {
832                    Some(frame) => frame,
833                    None => start_frame(start, *rate, first, last)?,
834                };
835                if frame < first || frame >= last {
836                    return None;
837                }
838                Some(Need::TimelineFrame {
839                    time: rate.frame_start(frame)?,
840                    size: *size,
841                    format: *format,
842                })
843            }
844            Input::SourceAudio {
845                rate,
846                block,
847                channels,
848                ..
849            }
850            | Input::TimelineAudio {
851                rate,
852                block,
853                channels,
854            } => {
855                let (first, last) = self.sample_span(*rate);
856                let at = cursor
857                    .position
858                    .unwrap_or_else(|| samples_ceil(start, *rate).clamp(first, last));
859                let block = i64::from(*block);
860                let (start_sample, end_sample) = match direction {
861                    Direction::Forward => (at, (at + block).min(last)),
862                    Direction::Backward => ((at - block).max(first), at),
863                };
864                if start_sample >= end_sample {
865                    return None;
866                }
867                let frames = u32::try_from(end_sample - start_sample).ok()?;
868                Some(match &self.input {
869                    Input::SourceAudio { source, stream, .. } => Need::SourceAudio {
870                        source: source.clone(),
871                        stream: *stream,
872                        start_sample,
873                        frames,
874                        rate: *rate,
875                        channels: *channels,
876                    },
877                    _ => Need::TimelineAudio {
878                        start_sample,
879                        frames,
880                        rate: *rate,
881                        channels: *channels,
882                    },
883                })
884            }
885        }
886    }
887
888    /// Answers an outstanding frame need.
889    ///
890    /// # Errors
891    /// [`SessionError::UnexpectedSupply`] when no frame is asked for, or the frame's size, buffer
892    /// or pts does not answer the need.
893    pub fn supply_video(&mut self, frame: SuppliedFrame) -> Result<(), SessionError> {
894        let Phase::Waiting(cursor, need) = &self.phase else {
895            return Err(SessionError::UnexpectedSupply(
896                "no frame is asked for".to_owned(),
897            ));
898        };
899        let (cursor, need) = (*cursor, need.clone());
900        let (size, format, expected_pts, from) = match &need {
901            Need::SourceFrame {
902                size, format, from, ..
903            } => (*size, *format, None, Some(*from)),
904            Need::TimelineFrame { time, size, format } => (*size, *format, Some(*time), None),
905            _ => {
906                return Err(SessionError::UnexpectedSupply(
907                    "audio is asked for".to_owned(),
908                ));
909            }
910        };
911        if frame.width == 0 || frame.height == 0 || frame.width.max(frame.height) > size {
912            return Err(SessionError::UnexpectedSupply(
913                "the frame's size breaks the asked size".to_owned(),
914            ));
915        }
916        let pixels = u64::from(frame.width) * u64::from(frame.height);
917        if u64::try_from(frame.rgba.len()).ok() != pixels.checked_mul(4) {
918            return Err(SessionError::UnexpectedSupply(
919                "the buffer is not width * height * 4 bytes".to_owned(),
920            ));
921        }
922        if expected_pts.is_some_and(|time| time != frame.pts) {
923            return Err(SessionError::UnexpectedSupply(
924                "the frame is not the asked time".to_owned(),
925            ));
926        }
927        let Pass { direction, .. } = self.passes[cursor.pass];
928        if let Some(FrameFrom::After(previous)) = from {
929            let ordered = match direction {
930                Direction::Forward => frame.pts > previous,
931                Direction::Backward => frame.pts < previous,
932            };
933            if !ordered {
934                return Err(SessionError::UnexpectedSupply(
935                    "the frame does not follow the last in the pass direction".to_owned(),
936                ));
937            }
938        }
939        let range = self.range();
940        // Which frames are shown inside the range, and when a pass ends.
941        let (deliver, next) = match &self.input {
942            Input::SourceVideo { .. } => match direction {
943                Direction::Forward => {
944                    if frame.pts >= range.end() {
945                        (false, Some(i64::MIN))
946                    } else {
947                        (true, Some(frame.pts.ticks()))
948                    }
949                }
950                Direction::Backward => {
951                    let last = frame.pts <= range.start();
952                    (true, Some(if last { i64::MIN } else { frame.pts.ticks() }))
953                }
954            },
955            Input::TimelineVideo { rate, .. } => {
956                let frame_index = rate.frame_at_or_before(frame.pts);
957                let step = match direction {
958                    Direction::Forward => 1,
959                    Direction::Backward => -1,
960                };
961                (true, frame_index.map(|index| index + step))
962            }
963            _ => unreachable!("a frame need comes only from video input"),
964        };
965        if !deliver {
966            self.phase = Phase::Running(Cursor {
967                pass: cursor.pass,
968                position: next,
969            });
970            return Ok(());
971        }
972        self.delivered = Some(frame.pts);
973        self.delivered_pts.insert(frame.pts);
974        let bytes = match format {
975            VideoFormat::Rgba8 => frame.rgba,
976            VideoFormat::Luma8 => luma8_from_rgba8(&frame.rgba),
977        };
978        let delivery = Delivery::Video(VideoInput {
979            time: frame.pts,
980            width: frame.width,
981            height: frame.height,
982            format,
983            bytes,
984        });
985        self.phase = Phase::Delivering(
986            Cursor {
987                pass: cursor.pass,
988                position: next,
989            },
990            delivery,
991        );
992        Ok(())
993    }
994
995    /// Answers an outstanding source-frame need: no such frame exists, so the pass ends.
996    ///
997    /// # Errors
998    /// [`SessionError::UnexpectedSupply`] when no source frame is asked for.
999    pub fn supply_end(&mut self) -> Result<(), SessionError> {
1000        match &self.phase {
1001            Phase::Waiting(cursor, Need::SourceFrame { .. }) => {
1002                self.phase = Phase::Running(Cursor {
1003                    pass: cursor.pass,
1004                    position: Some(i64::MIN),
1005                });
1006                Ok(())
1007            }
1008            _ => Err(SessionError::UnexpectedSupply(
1009                "no source frame is asked for".to_owned(),
1010            )),
1011        }
1012    }
1013
1014    /// Answers an outstanding audio need with exactly the asked frames.
1015    ///
1016    /// # Errors
1017    /// [`SessionError::UnexpectedSupply`] when no audio is asked for, or the block's channel
1018    /// count or length does not answer the need.
1019    pub fn supply_audio(&mut self, block: SuppliedAudio) -> Result<(), SessionError> {
1020        let Phase::Waiting(cursor, need) = &self.phase else {
1021            return Err(SessionError::UnexpectedSupply(
1022                "no audio is asked for".to_owned(),
1023            ));
1024        };
1025        let (cursor, need) = (*cursor, need.clone());
1026        let (Need::SourceAudio {
1027            start_sample,
1028            frames,
1029            rate,
1030            channels,
1031            ..
1032        }
1033        | Need::TimelineAudio {
1034            start_sample,
1035            frames,
1036            rate,
1037            channels,
1038        }) = need
1039        else {
1040            return Err(SessionError::UnexpectedSupply(
1041                "a frame is asked for".to_owned(),
1042            ));
1043        };
1044        if block.channels == 0
1045            || (channels == AudioChannels::Mono && block.channels != 1)
1046            || block.channels > u32::try_from(alpha2_media::MAX_AUDIO_CHANNELS).unwrap_or(u32::MAX)
1047        {
1048            return Err(SessionError::UnexpectedSupply(
1049                "the block's channel count does not answer the need".to_owned(),
1050            ));
1051        }
1052        if block.samples.len()
1053            != usize::try_from(block.channels).unwrap_or(0) * usize::try_from(frames).unwrap_or(0)
1054        {
1055            return Err(SessionError::UnexpectedSupply(
1056                "the block is not channels * frames samples".to_owned(),
1057            ));
1058        }
1059        if block.samples.iter().any(|sample| !sample.is_finite()) {
1060            return Err(SessionError::UnexpectedSupply(
1061                "the block holds a sample that is not finite".to_owned(),
1062            ));
1063        }
1064        let end_sample = start_sample + i64::from(frames);
1065        let direction = self.passes[cursor.pass].direction;
1066        self.delivered = Some(MediaTime(match direction {
1067            Direction::Forward => samples_to_ticks_ceil(end_sample, rate),
1068            Direction::Backward => alpha2_media::sample_ticks_floor(start_sample, rate),
1069        }));
1070        let next = match direction {
1071            Direction::Forward => end_sample,
1072            Direction::Backward => start_sample,
1073        };
1074        let delivery = Delivery::Audio(AudioInput {
1075            start_sample,
1076            start: MediaTime(alpha2_media::sample_ticks_floor(start_sample, rate)),
1077            frames,
1078            rate,
1079            channels: block.channels,
1080            samples: block.samples,
1081        });
1082        self.phase = Phase::Delivering(
1083            Cursor {
1084                pass: cursor.pass,
1085                position: Some(next),
1086            },
1087            delivery,
1088        );
1089        Ok(())
1090    }
1091
1092    /// Validates and records emits; on a refusal nothing of `emits` is recorded.
1093    ///
1094    /// During a pass, times lie inside the range (or are a delivered frame's pts), go no further
1095    /// than what the pass has delivered, and move in the pass direction per output. After
1096    /// [`Step::Done`] any time inside the range is accepted. A requested output holds at most
1097    /// [`OutputSpec::max_items`]; emits to a declared output the request does not name are
1098    /// checked and dropped.
1099    ///
1100    /// # Errors
1101    /// [`SessionError::InvalidEmit`] naming the first offending emit and the rule.
1102    pub fn emit(&mut self, emits: &[Emit]) -> Result<(), SessionError> {
1103        let mut last = self.last_time.clone();
1104        let mut added = BTreeMap::<&str, usize>::new();
1105        for (index, emit) in emits.iter().enumerate() {
1106            let invalid = |reason| SessionError::InvalidEmit { index, reason };
1107            self.check_emit(emit, &mut last).map_err(invalid)?;
1108            let name = emit.output();
1109            if !self.request.outputs.contains_key(name) {
1110                continue;
1111            }
1112            let count = added.entry(name).or_default();
1113            *count += 1;
1114            let held = self.gathered.get(name).map_or(0, Gathered::len);
1115            if let Some(output) = self.output(name)
1116                && held + *count > output.max_items()
1117            {
1118                return Err(invalid(over_limit(output)));
1119            }
1120        }
1121        self.last_time = last;
1122        for emit in emits {
1123            if !self.request.outputs.contains_key(emit.output()) {
1124                continue;
1125            }
1126            let gathered = self.gathered.entry(emit.output().to_owned()).or_default();
1127            match emit {
1128                Emit::Sample { time, values, .. } => gathered.samples.push((*time, values.clone())),
1129                Emit::Word { word, .. } => gathered.words.push(word.clone()),
1130                Emit::Interval { interval, .. } => gathered.intervals.push(interval.clone()),
1131            }
1132        }
1133        Ok(())
1134    }
1135
1136    fn output(&self, name: &str) -> Option<&OutputSpec> {
1137        self.descriptor
1138            .outputs
1139            .iter()
1140            .find(|output| output.name == name)
1141    }
1142
1143    #[allow(clippy::too_many_lines)]
1144    fn check_emit(
1145        &self,
1146        emit: &Emit,
1147        latest: &mut BTreeMap<String, MediaTime>,
1148    ) -> Result<(), String> {
1149        let output = self
1150            .output(emit.output())
1151            .ok_or_else(|| format!("undeclared output {}", emit.output()))?;
1152        let range = self.range();
1153        let in_pass = match &self.phase {
1154            Phase::Running(cursor) | Phase::Waiting(cursor, _) | Phase::Delivering(cursor, _) => {
1155                Some(cursor.pass)
1156            }
1157            Phase::Done => None,
1158            Phase::BeforePass(_) | Phase::Finished => {
1159                return Err("no input has been delivered".to_owned());
1160            }
1161        };
1162        let direction = in_pass.map(|pass| self.passes[pass].direction);
1163        let delivered = self.delivered;
1164        if in_pass.is_some() && delivered.is_none() {
1165            return Err("nothing has been delivered in this pass".to_owned());
1166        }
1167        let reached = |time: MediaTime| match (direction, delivered) {
1168            (Some(Direction::Forward), Some(bound)) => time <= bound,
1169            (Some(Direction::Backward), Some(bound)) => time >= bound,
1170            _ => true,
1171        };
1172        let (time, key) = match emit {
1173            Emit::Sample { time, values, .. } => {
1174                if output.kind.arity().is_none() {
1175                    return Err(format!(
1176                        "output {} takes {} items, not samples",
1177                        output.name, output.kind
1178                    ));
1179                }
1180                if values.len() != output.sample_width() {
1181                    return Err(format!(
1182                        "output {} takes {} numbers a sample",
1183                        output.name,
1184                        output.sample_width()
1185                    ));
1186                }
1187                let arity = output.kind.arity().unwrap_or(1);
1188                for (group, chunk) in values.chunks(arity).enumerate() {
1189                    let lost = chunk[0].is_none();
1190                    for (component, value) in chunk.iter().enumerate() {
1191                        let ok = match value {
1192                            None => lost,
1193                            Some(number) => {
1194                                !lost
1195                                    && alpha2_model::value_in_bounds(
1196                                        output.kind,
1197                                        component,
1198                                        *number,
1199                                    )
1200                            }
1201                        };
1202                        if !ok {
1203                            return Err(format!(
1204                                "value {} is lost in part, not finite or out of bounds",
1205                                group * arity + component
1206                            ));
1207                        }
1208                    }
1209                }
1210                let inside = (range.contains(*time) || self.delivered_pts.contains(time))
1211                    && time.ticks() >= 0;
1212                if !inside {
1213                    return Err("the time is outside the range".to_owned());
1214                }
1215                if !reached(*time) {
1216                    return Err("the time is beyond what this pass has delivered".to_owned());
1217                }
1218                (*time, true)
1219            }
1220            Emit::Word { word, .. } => {
1221                if output.kind != DataKind::Words {
1222                    return Err(format!("output {} takes no words", output.name));
1223                }
1224                if !alpha2_model::valid_word(word) {
1225                    return Err(
1226                        "the word is empty, too long, or does not end after it starts".to_owned(),
1227                    );
1228                }
1229                if word.start < range.start() || word.end > range.end() {
1230                    return Err("the word lies outside the range".to_owned());
1231                }
1232                if !reached(word.start) || !reached(word.end) {
1233                    return Err("the word is beyond what this pass has delivered".to_owned());
1234                }
1235                (word.start, false)
1236            }
1237            Emit::Interval { interval, .. } => {
1238                if output.kind != DataKind::Intervals {
1239                    return Err(format!("output {} takes no intervals", output.name));
1240                }
1241                if !alpha2_model::valid_interval(interval) {
1242                    return Err(
1243                        "the interval ends before it starts, or its label or score breaks a limit"
1244                            .to_owned(),
1245                    );
1246                }
1247                if interval.start < range.start() || interval.end > range.end() {
1248                    return Err("the interval lies outside the range".to_owned());
1249                }
1250                if !reached(interval.start) || !reached(interval.end) {
1251                    return Err("the interval is beyond what this pass has delivered".to_owned());
1252                }
1253                (interval.start, false)
1254            }
1255        };
1256        if let Some(direction) = direction
1257            && let Some(previous) = latest.get(&output.name)
1258        {
1259            // Samples move strictly; items by their starts, ties allowed.
1260            let ordered = match (direction, key) {
1261                (Direction::Forward, true) => time > *previous,
1262                (Direction::Backward, true) => time < *previous,
1263                (Direction::Forward, false) => time >= *previous,
1264                (Direction::Backward, false) => time <= *previous,
1265            };
1266            if !ordered {
1267                return Err("times do not move in the pass direction".to_owned());
1268            }
1269        }
1270        if direction.is_some() {
1271            latest.insert(output.name.clone(), time);
1272        }
1273        Ok(())
1274    }
1275
1276    /// The recorded outputs as data sets: merged across passes, sorted, with `made_by` set and
1277    /// `made_from` left for the surface helper.
1278    ///
1279    /// # Errors
1280    /// [`SessionError::InvalidResult`] before [`Step::Done`], for a time emitted twice, or for a
1281    /// set that breaks a data limit.
1282    pub fn finish(&mut self) -> Result<Vec<DataSet>, SessionError> {
1283        if !matches!(self.phase, Phase::Done) {
1284            return Err(SessionError::InvalidResult(
1285                "the run is not done".to_owned(),
1286            ));
1287        }
1288        self.phase = Phase::Finished;
1289        let made_by = MadeBy {
1290            extractor: self.descriptor.id.clone(),
1291            version: self.descriptor.version,
1292            params: self.request.params.clone(),
1293            plugin: None,
1294        };
1295        let mut sets = Vec::new();
1296        for (name, id) in &self.request.outputs {
1297            let output = self
1298                .output(name)
1299                .cloned()
1300                .ok_or_else(|| SessionError::InvalidResult(format!("undeclared output {name}")))?;
1301            let gathered = self.gathered.remove(name).unwrap_or_default();
1302            let values = Self::values_of(&output, id, gathered)?;
1303            let set = DataSet {
1304                id: id.clone(),
1305                anchor: self.anchor.clone(),
1306                values,
1307                made_by: Some(made_by.clone()),
1308                made_from: None,
1309            };
1310            set.validate().map_err(|problem| {
1311                SessionError::InvalidResult(format!("data set {id} {problem}"))
1312            })?;
1313            sets.push(set);
1314        }
1315        Ok(sets)
1316    }
1317
1318    fn values_of(
1319        output: &OutputSpec,
1320        id: &DataSetId,
1321        mut gathered: Gathered,
1322    ) -> Result<DataValues, SessionError> {
1323        Ok(match output.kind {
1324            DataKind::Points | DataKind::Scalars | DataKind::Similarity => {
1325                gathered.samples.sort_by_key(|(time, _)| *time);
1326                if let Some(pair) = gathered
1327                    .samples
1328                    .windows(2)
1329                    .find(|pair| pair[0].0 == pair[1].0)
1330                {
1331                    return Err(SessionError::InvalidResult(format!(
1332                        "output {} has time {} twice (data set {id})",
1333                        output.name,
1334                        pair[0].0.ticks()
1335                    )));
1336                }
1337                let samples = DataSamples {
1338                    interpolation: output.interpolation.unwrap_or_default(),
1339                    channels: output.channels.clone(),
1340                    times: gathered.samples.iter().map(|(time, _)| *time).collect(),
1341                    values: gathered
1342                        .samples
1343                        .into_iter()
1344                        .flat_map(|(_, values)| values)
1345                        .collect(),
1346                };
1347                match output.kind {
1348                    DataKind::Points => DataValues::Points(samples),
1349                    DataKind::Scalars => DataValues::Scalars(samples),
1350                    _ => DataValues::Similarity(samples),
1351                }
1352            }
1353            DataKind::Words => {
1354                gathered.words.sort_by_key(|word| (word.start, word.end));
1355                DataValues::Words(gathered.words)
1356            }
1357            DataKind::Intervals => {
1358                gathered
1359                    .intervals
1360                    .sort_by_key(|interval| (interval.start, interval.end));
1361                DataValues::Intervals(gathered.intervals)
1362            }
1363        })
1364    }
1365}
1366
1367/// The first sample starting at or after `time` at `rate`.
1368fn samples_ceil(time: MediaTime, rate: u32) -> i64 {
1369    let numerator = i128::from(time.ticks()) * i128::from(rate);
1370    let denominator = i128::from(TICKS_PER_SECOND);
1371    let samples =
1372        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
1373    i64::try_from(samples).unwrap_or(i64::MAX)
1374}
1375
1376/// The first tick at or after sample `sample` at `rate`.
1377fn samples_to_ticks_ceil(sample: i64, rate: u32) -> i64 {
1378    let numerator = i128::from(sample) * i128::from(TICKS_PER_SECOND);
1379    let denominator = i128::from(rate.max(1));
1380    let ticks =
1381        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
1382    i64::try_from(ticks).unwrap_or(i64::MAX)
1383}
1384
1385/// The frames of `rate` whose start lies in `range`: `[first, last)`.
1386fn timeline_frames(range: TimeRange, rate: FrameRate) -> Option<(i64, i64)> {
1387    let first_at_or_before = rate.frame_at_or_before(range.start())?;
1388    let first = if rate.frame_start(first_at_or_before)? < range.start() {
1389        first_at_or_before + 1
1390    } else {
1391        first_at_or_before
1392    };
1393    let last = rate.frame_at_or_before(MediaTime(range.end().ticks() - 1))? + 1;
1394    Some((first, last.max(first)))
1395}
1396
1397/// The frame a pass starting at `start` begins with, the one shown there, kept in `[first, last)`.
1398fn start_frame(start: MediaTime, rate: FrameRate, first: i64, last: i64) -> Option<i64> {
1399    let frame = rate.frame_at_or_before(start)?;
1400    (first < last).then(|| frame.clamp(first, last - 1))
1401}