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