Skip to main content

alpha2_engine/extract/
drive.rs

1//! Rust extractors, the inputs they are supplied, and the loop that runs them.
2
3use super::descriptor::{Descriptor, Direction};
4use super::session::{
5    AudioInput, Delivery, Emit, ExtractSession, Need, RunContext, SessionError, Step,
6    SuppliedAudio, SuppliedFrame, VideoInput,
7};
8use alpha2_model::{DataInterval, DataSet, DataWord};
9use alpha2_time::MediaTime;
10use std::fmt;
11
12/// A pass beginning, as an extractor is told.
13#[derive(Copy, Clone, Debug, Eq, PartialEq)]
14pub struct PassInfo {
15    /// The pass's position in the request.
16    pub pass: usize,
17    /// Its direction.
18    pub direction: Direction,
19}
20
21/// An extractor's own failure, carried to the caller as is.
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct ExtractorError {
24    /// Why it failed.
25    pub message: String,
26    /// The error code a host reports instead of `EXTRACTOR_FAILED`, such as `PLUGIN_TRAPPED`.
27    pub code: Option<&'static str>,
28}
29
30impl ExtractorError {
31    /// A failure the host reports as `EXTRACTOR_FAILED`.
32    pub fn new(message: impl Into<String>) -> Self {
33        Self {
34            message: message.into(),
35            code: None,
36        }
37    }
38
39    /// A failure the host reports with `code`.
40    pub fn with_code(code: &'static str, message: impl Into<String>) -> Self {
41        Self {
42            message: message.into(),
43            code: Some(code),
44        }
45    }
46}
47
48impl fmt::Display for ExtractorError {
49    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
50        formatter.write_str(&self.message)
51    }
52}
53
54impl std::error::Error for ExtractorError {}
55
56/// Collects what an extractor emits for one call; the session validates it afterwards.
57#[derive(Debug, Default)]
58pub struct Emitter {
59    emits: Vec<Emit>,
60}
61
62impl Emitter {
63    /// A sample of a `points`, `scalars` or `similarity` output; `None` marks a lost channel.
64    pub fn sample(&mut self, output: &str, time: MediaTime, values: &[Option<f32>]) {
65        self.emits.push(Emit::Sample {
66            output: output.to_owned(),
67            time,
68            values: values.to_vec(),
69        });
70    }
71
72    /// A word of a `words` output.
73    pub fn word(&mut self, output: &str, word: DataWord) {
74        self.emits.push(Emit::Word {
75            output: output.to_owned(),
76            word,
77        });
78    }
79
80    /// An interval of an `intervals` output.
81    pub fn interval(&mut self, output: &str, interval: DataInterval) {
82        self.emits.push(Emit::Interval {
83            output: output.to_owned(),
84            interval,
85        });
86    }
87
88    /// An emit as it is, such as one parsed from a client's JSON.
89    pub fn push(&mut self, emit: Emit) {
90        self.emits.push(emit);
91    }
92
93    /// The emits collected so far, in order.
94    #[must_use]
95    pub fn emits(&self) -> &[Emit] {
96        &self.emits
97    }
98
99    fn take(&mut self) -> Vec<Emit> {
100        std::mem::take(&mut self.emits)
101    }
102}
103
104/// A function that is supplied frames or audio and returns primitives. Runs ahead of time over
105/// a range; what it emits is recorded as data sets.
106pub trait Extractor {
107    /// What the extractor reads and emits.
108    fn describe(&self) -> &Descriptor;
109
110    /// The run begins; model loading belongs here.
111    ///
112    /// # Errors
113    /// The extractor's failure, which ends the run.
114    fn begin(&mut self, context: &RunContext) -> Result<(), ExtractorError>;
115
116    /// A pass begins.
117    ///
118    /// # Errors
119    /// The extractor's failure, which ends the run.
120    fn pass(&mut self, pass: &PassInfo) -> Result<(), ExtractorError>;
121
122    /// A video frame of the current pass.
123    ///
124    /// # Errors
125    /// The extractor's failure, which ends the run.
126    fn video(&mut self, frame: &VideoInput, out: &mut Emitter) -> Result<(), ExtractorError>;
127
128    /// An audio block of the current pass.
129    ///
130    /// # Errors
131    /// The extractor's failure, which ends the run.
132    fn audio(&mut self, block: &AudioInput, out: &mut Emitter) -> Result<(), ExtractorError>;
133
134    /// Every pass ended; whole-range work belongs here and may emit any time in the range.
135    ///
136    /// # Errors
137    /// The extractor's failure, which ends the run.
138    fn end(&mut self, out: &mut Emitter) -> Result<(), ExtractorError>;
139}
140
141/// Supplies the inputs a session asks for: decoded and presented frames, or audio.
142pub trait Supplier {
143    /// The frame a [`Need::SourceFrame`] or [`Need::TimelineFrame`] asks for, or `None` when no
144    /// such source frame exists.
145    ///
146    /// # Errors
147    /// A decode or render failure, which ends the run.
148    fn frame(&mut self, need: &Need) -> Result<Option<SuppliedFrame>, String>;
149
150    /// The block a [`Need::SourceAudio`] or [`Need::TimelineAudio`] asks for.
151    ///
152    /// # Errors
153    /// A decode or mix failure, which ends the run.
154    fn audio(&mut self, need: &Need) -> Result<SuppliedAudio, String>;
155}
156
157/// Why a run did not complete.
158#[derive(Clone, Debug, PartialEq)]
159#[non_exhaustive]
160pub enum DriveError {
161    /// The extractor failed.
162    Extractor(ExtractorError),
163    /// The supplier failed.
164    Supplier(String),
165    /// The session refused a supply or an emit, or the result.
166    Session(SessionError),
167}
168
169impl fmt::Display for DriveError {
170    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            Self::Extractor(error) => write!(formatter, "extractor failed: {error}"),
173            Self::Supplier(error) => write!(formatter, "supplier failed: {error}"),
174            Self::Session(error) => error.fmt(formatter),
175        }
176    }
177}
178
179impl std::error::Error for DriveError {}
180
181impl From<SessionError> for DriveError {
182    fn from(error: SessionError) -> Self {
183        Self::Session(error)
184    }
185}
186
187/// Runs `extractor` through `session`, supplying inputs from `supplier`, and returns the
188/// session's data sets.
189///
190/// # Errors
191/// [`DriveError`] for the first failure of the extractor, the supplier or the session.
192pub fn drive(
193    mut session: ExtractSession,
194    extractor: &mut dyn Extractor,
195    supplier: &mut dyn Supplier,
196) -> Result<Vec<DataSet>, DriveError> {
197    let mut out = Emitter::default();
198    extractor
199        .begin(&session.context())
200        .map_err(DriveError::Extractor)?;
201    loop {
202        match session.next() {
203            Step::Need(need) => match &need {
204                Need::SourceFrame { .. } | Need::TimelineFrame { .. } => {
205                    match supplier.frame(&need).map_err(DriveError::Supplier)? {
206                        Some(frame) => session.supply_video(frame)?,
207                        None => session.supply_end()?,
208                    }
209                }
210                Need::SourceAudio { .. } | Need::TimelineAudio { .. } => {
211                    let block = supplier.audio(&need).map_err(DriveError::Supplier)?;
212                    session.supply_audio(block)?;
213                }
214            },
215            Step::Deliver(delivery) => {
216                match &delivery {
217                    Delivery::Video(frame) => extractor.video(frame, &mut out),
218                    Delivery::Audio(block) => extractor.audio(block, &mut out),
219                }
220                .map_err(DriveError::Extractor)?;
221                session.emit(&out.take())?;
222            }
223            Step::PassBoundary { pass, direction } => {
224                extractor
225                    .pass(&PassInfo { pass, direction })
226                    .map_err(DriveError::Extractor)?;
227            }
228            Step::Done => break,
229        }
230    }
231    extractor.end(&mut out).map_err(DriveError::Extractor)?;
232    session.emit(&out.take())?;
233    Ok(session.finish()?)
234}