use super::descriptor::{Descriptor, Direction, VideoFormat};
use super::session::{
AudioInput, Delivery, Emit, ExtractSession, Need, RunContext, SessionError, Step,
SuppliedAudio, SuppliedFrame, VideoInput,
};
use alpha2_model::{DataInterval, DataSet, DataWord};
use alpha2_time::MediaTime;
use std::fmt;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct PassInfo {
pub pass: usize,
pub direction: Direction,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExtractorError {
pub message: String,
pub code: Option<&'static str>,
pub details: Option<serde_json::Map<String, serde_json::Value>>,
}
impl ExtractorError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
code: None,
details: None,
}
}
pub fn with_code(code: &'static str, message: impl Into<String>) -> Self {
Self {
message: message.into(),
code: Some(code),
details: None,
}
}
#[must_use]
pub fn with_details(mut self, details: serde_json::Map<String, serde_json::Value>) -> Self {
self.details = Some(details);
self
}
}
impl fmt::Display for ExtractorError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for ExtractorError {}
#[derive(Debug, Default)]
pub struct Emitter {
emits: Vec<Emit>,
}
impl Emitter {
pub fn sample(&mut self, output: &str, time: MediaTime, values: &[Option<f32>]) {
self.emits.push(Emit::Sample {
output: output.to_owned(),
time,
values: values.to_vec(),
});
}
pub fn word(&mut self, output: &str, word: DataWord) {
self.emits.push(Emit::Word {
output: output.to_owned(),
word,
});
}
pub fn interval(&mut self, output: &str, interval: DataInterval) {
self.emits.push(Emit::Interval {
output: output.to_owned(),
interval,
});
}
pub fn push(&mut self, emit: Emit) {
self.emits.push(emit);
}
#[must_use]
pub fn emits(&self) -> &[Emit] {
&self.emits
}
fn take(&mut self) -> Vec<Emit> {
std::mem::take(&mut self.emits)
}
}
pub trait Extractor {
fn describe(&self) -> &Descriptor;
fn begin(&mut self, context: &RunContext) -> Result<(), ExtractorError>;
fn pass(&mut self, pass: &PassInfo) -> Result<(), ExtractorError>;
fn video(&mut self, frame: &VideoInput, out: &mut Emitter) -> Result<(), ExtractorError>;
fn frame_buffer(&mut self, len: usize) -> Option<&mut [u8]> {
let _ = len;
None
}
fn audio(&mut self, block: &AudioInput, out: &mut Emitter) -> Result<(), ExtractorError>;
fn end(&mut self, out: &mut Emitter) -> Result<(), ExtractorError>;
}
pub trait Supplier {
fn frame(&mut self, need: &Need) -> Result<Option<SuppliedFrame>, String>;
fn frame_into(
&mut self,
need: &Need,
place: &mut FramePlace<'_>,
) -> Result<Option<SuppliedFrame>, String> {
let _ = place;
self.frame(need)
}
fn audio(&mut self, need: &Need) -> Result<SuppliedAudio, String>;
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum DriveError {
Extractor(ExtractorError),
Supplier(String),
Session(SessionError),
}
impl fmt::Display for DriveError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Extractor(error) => write!(formatter, "extractor failed: {error}"),
Self::Supplier(error) => write!(formatter, "supplier failed: {error}"),
Self::Session(error) => error.fmt(formatter),
}
}
}
impl std::error::Error for DriveError {}
impl From<SessionError> for DriveError {
fn from(error: SessionError) -> Self {
Self::Session(error)
}
}
pub struct FramePlace<'a> {
extractor: &'a mut dyn Extractor,
placed: Option<usize>,
}
impl FramePlace<'_> {
pub fn buffer(&mut self, len: usize) -> Option<&mut [u8]> {
let buffer = self.extractor.frame_buffer(len)?;
self.placed = Some(len);
Some(buffer)
}
}
pub fn supply_frame(
session: &mut ExtractSession,
need: &Need,
extractor: &mut dyn Extractor,
supplier: &mut dyn Supplier,
) -> Result<(), DriveError> {
let rgba = matches!(
need,
Need::SourceFrame {
format: VideoFormat::Rgba8,
..
} | Need::TimelineFrame {
format: VideoFormat::Rgba8,
..
}
);
if !rgba {
let Some(frame) = supplier.frame(need).map_err(DriveError::Supplier)? else {
return Ok(session.supply_end()?);
};
let luma = usize::try_from(u64::from(frame.width) * u64::from(frame.height)).ok();
return match luma.and_then(|len| extractor.frame_buffer(len)) {
Some(buffer) => Ok(session.supply_video_into(frame, buffer)?),
None => Ok(session.supply_video(frame)?),
};
}
let mut place = FramePlace {
extractor,
placed: None,
};
let frame = supplier
.frame_into(need, &mut place)
.map_err(DriveError::Supplier)?;
match (frame, place.placed) {
(None, _) => Ok(session.supply_end()?),
(Some(frame), None) => Ok(session.supply_video(frame)?),
(Some(frame), Some(len)) => {
let packed = u64::from(frame.width) * u64::from(frame.height) * 4;
if u64::try_from(len).ok() != Some(packed) {
return Err(DriveError::Supplier(format!(
"a frame of {}x{} placed in {len} bytes",
frame.width, frame.height
)));
}
Ok(session.supply_placed_video(frame)?)
}
}
}
pub fn drive(
mut session: ExtractSession,
extractor: &mut dyn Extractor,
supplier: &mut dyn Supplier,
) -> Result<Vec<DataSet>, DriveError> {
let mut out = Emitter::default();
extractor
.begin(&session.context())
.map_err(DriveError::Extractor)?;
loop {
match session.next() {
Step::Need(need) => match &need {
Need::SourceFrame { .. } | Need::TimelineFrame { .. } => {
supply_frame(&mut session, &need, extractor, supplier)?;
}
Need::SourceAudio { .. } | Need::TimelineAudio { .. } => {
let block = supplier.audio(&need).map_err(DriveError::Supplier)?;
session.supply_audio(block)?;
}
},
Step::Deliver(delivery) => {
match &delivery {
Delivery::Video(frame) => extractor.video(frame, &mut out),
Delivery::Audio(block) => extractor.audio(block, &mut out),
}
.map_err(DriveError::Extractor)?;
session.emit(&out.take())?;
}
Step::PassBoundary { pass, direction } => {
extractor
.pass(&PassInfo { pass, direction })
.map_err(DriveError::Extractor)?;
}
Step::Done => break,
}
}
extractor.end(&mut out).map_err(DriveError::Extractor)?;
session.emit(&out.take())?;
Ok(session.finish()?)
}