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