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, VideoFormat};
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    /// What a caller reads besides the code, such as the slot and reason of a refused resource.
29    pub details: Option<serde_json::Map<String, serde_json::Value>>,
30}
31
32impl ExtractorError {
33    /// A failure the host reports as `EXTRACTOR_FAILED`.
34    pub fn new(message: impl Into<String>) -> Self {
35        Self {
36            message: message.into(),
37            code: None,
38            details: None,
39        }
40    }
41
42    /// A failure the host reports with `code`.
43    pub fn with_code(code: &'static str, message: impl Into<String>) -> Self {
44        Self {
45            message: message.into(),
46            code: Some(code),
47            details: None,
48        }
49    }
50
51    /// The failure with `details`.
52    #[must_use]
53    pub fn with_details(mut self, details: serde_json::Map<String, serde_json::Value>) -> Self {
54        self.details = Some(details);
55        self
56    }
57}
58
59impl fmt::Display for ExtractorError {
60    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61        formatter.write_str(&self.message)
62    }
63}
64
65impl std::error::Error for ExtractorError {}
66
67/// Collects what an extractor emits for one call; the session validates it afterwards.
68#[derive(Debug, Default)]
69pub struct Emitter {
70    emits: Vec<Emit>,
71}
72
73impl Emitter {
74    /// A sample of a `points`, `scalars` or `similarity` output; `None` marks a lost channel.
75    pub fn sample(&mut self, output: &str, time: MediaTime, values: &[Option<f32>]) {
76        self.emits.push(Emit::Sample {
77            output: output.to_owned(),
78            time,
79            values: values.to_vec(),
80        });
81    }
82
83    /// A word of a `words` output.
84    pub fn word(&mut self, output: &str, word: DataWord) {
85        self.emits.push(Emit::Word {
86            output: output.to_owned(),
87            word,
88        });
89    }
90
91    /// An interval of an `intervals` output.
92    pub fn interval(&mut self, output: &str, interval: DataInterval) {
93        self.emits.push(Emit::Interval {
94            output: output.to_owned(),
95            interval,
96        });
97    }
98
99    /// An emit as it is, such as one parsed from a client's JSON.
100    pub fn push(&mut self, emit: Emit) {
101        self.emits.push(emit);
102    }
103
104    /// The emits collected so far, in order.
105    #[must_use]
106    pub fn emits(&self) -> &[Emit] {
107        &self.emits
108    }
109
110    fn take(&mut self) -> Vec<Emit> {
111        std::mem::take(&mut self.emits)
112    }
113}
114
115/// A function that is supplied frames or audio and returns primitives. Runs ahead of time over
116/// a range; what it emits is recorded as data sets.
117pub trait Extractor {
118    /// What the extractor reads and emits.
119    fn describe(&self) -> &Descriptor;
120
121    /// The run begins; model loading belongs here.
122    ///
123    /// # Errors
124    /// The extractor's failure, which ends the run.
125    fn begin(&mut self, context: &RunContext) -> Result<(), ExtractorError>;
126
127    /// A pass begins.
128    ///
129    /// # Errors
130    /// The extractor's failure, which ends the run.
131    fn pass(&mut self, pass: &PassInfo) -> Result<(), ExtractorError>;
132
133    /// A video frame of the current pass.
134    ///
135    /// # Errors
136    /// The extractor's failure, which ends the run.
137    fn video(&mut self, frame: &VideoInput, out: &mut Emitter) -> Result<(), ExtractorError>;
138
139    /// Memory of exactly `len` bytes for the next supplied frame's delivered pixels, for an
140    /// extractor that would otherwise copy them. When it gives some and the frame is written
141    /// there, the `video` call that delivers it gets empty [`VideoInput::bytes`]. `None`, the
142    /// default, keeps the pixels in `bytes`.
143    fn frame_buffer(&mut self, len: usize) -> Option<&mut [u8]> {
144        let _ = len;
145        None
146    }
147
148    /// An audio block of the current pass.
149    ///
150    /// # Errors
151    /// The extractor's failure, which ends the run.
152    fn audio(&mut self, block: &AudioInput, out: &mut Emitter) -> Result<(), ExtractorError>;
153
154    /// Every pass ended; whole-range work belongs here and may emit any time in the range.
155    ///
156    /// # Errors
157    /// The extractor's failure, which ends the run.
158    fn end(&mut self, out: &mut Emitter) -> Result<(), ExtractorError>;
159}
160
161/// Supplies the inputs a session asks for: decoded and presented frames, or audio.
162pub trait Supplier {
163    /// The frame a [`Need::SourceFrame`] or [`Need::TimelineFrame`] asks for, or `None` when no
164    /// such source frame exists.
165    ///
166    /// # Errors
167    /// A decode or render failure, which ends the run.
168    fn frame(&mut self, need: &Need) -> Result<Option<SuppliedFrame>, String>;
169
170    /// [`Self::frame`] for a [`Need`] of RGBA frames, writing the pixels into the memory
171    /// [`FramePlace::buffer`] gives for their length when it gives some; the returned frame's
172    /// `rgba` is then empty. The default supplies the frame as [`Self::frame`] does.
173    ///
174    /// # Errors
175    /// As [`Self::frame`].
176    fn frame_into(
177        &mut self,
178        need: &Need,
179        place: &mut FramePlace<'_>,
180    ) -> Result<Option<SuppliedFrame>, String> {
181        let _ = place;
182        self.frame(need)
183    }
184
185    /// The block a [`Need::SourceAudio`] or [`Need::TimelineAudio`] asks for.
186    ///
187    /// # Errors
188    /// A decode or mix failure, which ends the run.
189    fn audio(&mut self, need: &Need) -> Result<SuppliedAudio, String>;
190}
191
192/// Why a run did not complete.
193#[derive(Clone, Debug, PartialEq)]
194#[non_exhaustive]
195pub enum DriveError {
196    /// The extractor failed.
197    Extractor(ExtractorError),
198    /// The supplier failed.
199    Supplier(String),
200    /// The session refused a supply or an emit, or the result.
201    Session(SessionError),
202}
203
204impl fmt::Display for DriveError {
205    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
206        match self {
207            Self::Extractor(error) => write!(formatter, "extractor failed: {error}"),
208            Self::Supplier(error) => write!(formatter, "supplier failed: {error}"),
209            Self::Session(error) => error.fmt(formatter),
210        }
211    }
212}
213
214impl std::error::Error for DriveError {}
215
216impl From<SessionError> for DriveError {
217    fn from(error: SessionError) -> Self {
218        Self::Session(error)
219    }
220}
221
222/// Where a supplier may write a frame's pixels: memory the extractor offers.
223pub struct FramePlace<'a> {
224    extractor: &'a mut dyn Extractor,
225    placed: Option<usize>,
226}
227
228impl FramePlace<'_> {
229    /// The extractor's memory for a frame of `len` bytes, which the supplier then fills; `None`
230    /// when it offers none, and the frame goes in `rgba`.
231    pub fn buffer(&mut self, len: usize) -> Option<&mut [u8]> {
232        let buffer = self.extractor.frame_buffer(len)?;
233        self.placed = Some(len);
234        Some(buffer)
235    }
236}
237
238/// Answers a frame need of `session` from `supplier`, in memory `extractor` offers when it
239/// offers some: the supplier writes RGBA frames there, the session a frame's luma; [`drive`]
240/// does this for every frame need.
241///
242/// # Errors
243/// [`DriveError::Supplier`] for the supplier's failure, [`DriveError::Session`] for a frame the
244/// session refuses.
245pub fn supply_frame(
246    session: &mut ExtractSession,
247    need: &Need,
248    extractor: &mut dyn Extractor,
249    supplier: &mut dyn Supplier,
250) -> Result<(), DriveError> {
251    let rgba = matches!(
252        need,
253        Need::SourceFrame {
254            format: VideoFormat::Rgba8,
255            ..
256        } | Need::TimelineFrame {
257            format: VideoFormat::Rgba8,
258            ..
259        }
260    );
261    if !rgba {
262        let Some(frame) = supplier.frame(need).map_err(DriveError::Supplier)? else {
263            return Ok(session.supply_end()?);
264        };
265        let luma = usize::try_from(u64::from(frame.width) * u64::from(frame.height)).ok();
266        return match luma.and_then(|len| extractor.frame_buffer(len)) {
267            Some(buffer) => Ok(session.supply_video_into(frame, buffer)?),
268            None => Ok(session.supply_video(frame)?),
269        };
270    }
271    let mut place = FramePlace {
272        extractor,
273        placed: None,
274    };
275    let frame = supplier
276        .frame_into(need, &mut place)
277        .map_err(DriveError::Supplier)?;
278    match (frame, place.placed) {
279        (None, _) => Ok(session.supply_end()?),
280        (Some(frame), None) => Ok(session.supply_video(frame)?),
281        (Some(frame), Some(len)) => {
282            let packed = u64::from(frame.width) * u64::from(frame.height) * 4;
283            if u64::try_from(len).ok() != Some(packed) {
284                return Err(DriveError::Supplier(format!(
285                    "a frame of {}x{} placed in {len} bytes",
286                    frame.width, frame.height
287                )));
288            }
289            Ok(session.supply_placed_video(frame)?)
290        }
291    }
292}
293
294/// Runs `extractor` through `session`, supplying inputs from `supplier`, and returns the
295/// session's data sets.
296///
297/// # Errors
298/// [`DriveError`] for the first failure of the extractor, the supplier or the session.
299pub fn drive(
300    mut session: ExtractSession,
301    extractor: &mut dyn Extractor,
302    supplier: &mut dyn Supplier,
303) -> Result<Vec<DataSet>, DriveError> {
304    let mut out = Emitter::default();
305    extractor
306        .begin(&session.context())
307        .map_err(DriveError::Extractor)?;
308    loop {
309        match session.next() {
310            Step::Need(need) => match &need {
311                Need::SourceFrame { .. } | Need::TimelineFrame { .. } => {
312                    supply_frame(&mut session, &need, extractor, supplier)?;
313                }
314                Need::SourceAudio { .. } | Need::TimelineAudio { .. } => {
315                    let block = supplier.audio(&need).map_err(DriveError::Supplier)?;
316                    session.supply_audio(block)?;
317                }
318            },
319            Step::Deliver(delivery) => {
320                match &delivery {
321                    Delivery::Video(frame) => extractor.video(frame, &mut out),
322                    Delivery::Audio(block) => extractor.audio(block, &mut out),
323                }
324                .map_err(DriveError::Extractor)?;
325                session.emit(&out.take())?;
326            }
327            Step::PassBoundary { pass, direction } => {
328                extractor
329                    .pass(&PassInfo { pass, direction })
330                    .map_err(DriveError::Extractor)?;
331            }
332            Step::Done => break,
333        }
334    }
335    extractor.end(&mut out).map_err(DriveError::Extractor)?;
336    session.emit(&out.take())?;
337    Ok(session.finish()?)
338}