1use 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
14pub struct PassInfo {
15 pub pass: usize,
17 pub direction: Direction,
19}
20
21#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct ExtractorError {
24 pub message: String,
26 pub code: Option<&'static str>,
28 pub details: Option<serde_json::Map<String, serde_json::Value>>,
30}
31
32impl ExtractorError {
33 pub fn new(message: impl Into<String>) -> Self {
35 Self {
36 message: message.into(),
37 code: None,
38 details: None,
39 }
40 }
41
42 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 #[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#[derive(Debug, Default)]
69pub struct Emitter {
70 emits: Vec<Emit>,
71}
72
73impl Emitter {
74 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 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 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 pub fn push(&mut self, emit: Emit) {
101 self.emits.push(emit);
102 }
103
104 #[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
115pub trait Extractor {
118 fn describe(&self) -> &Descriptor;
120
121 fn begin(&mut self, context: &RunContext) -> Result<(), ExtractorError>;
126
127 fn pass(&mut self, pass: &PassInfo) -> Result<(), ExtractorError>;
132
133 fn video(&mut self, frame: &VideoInput, out: &mut Emitter) -> Result<(), ExtractorError>;
138
139 fn frame_buffer(&mut self, len: usize) -> Option<&mut [u8]> {
144 let _ = len;
145 None
146 }
147
148 fn audio(&mut self, block: &AudioInput, out: &mut Emitter) -> Result<(), ExtractorError>;
153
154 fn end(&mut self, out: &mut Emitter) -> Result<(), ExtractorError>;
159}
160
161pub trait Supplier {
163 fn frame(&mut self, need: &Need) -> Result<Option<SuppliedFrame>, String>;
169
170 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 fn audio(&mut self, need: &Need) -> Result<SuppliedAudio, String>;
190}
191
192#[derive(Clone, Debug, PartialEq)]
194#[non_exhaustive]
195pub enum DriveError {
196 Extractor(ExtractorError),
198 Supplier(String),
200 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
222pub struct FramePlace<'a> {
224 extractor: &'a mut dyn Extractor,
225 placed: Option<usize>,
226}
227
228impl FramePlace<'_> {
229 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
238pub 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
294pub 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}