pub mod cache;
pub mod ffmpeg;
#[cfg(feature = "h264")]
pub mod mp4;
pub mod sequence;
pub mod times;
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub use cache::FrameCache;
pub use times::FrameTimes;
#[derive(Clone, Debug, PartialEq)]
pub struct Frame {
pub index: usize,
pub time: f64,
pub width: u32,
pub height: u32,
pub rgba: Arc<Vec<u8>>,
}
impl Frame {
pub fn bytes(&self) -> usize {
self.rgba.len()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct VideoInfo {
pub path: PathBuf,
pub width: u32,
pub height: u32,
pub times: FrameTimes,
pub format: String,
}
impl VideoInfo {
pub fn frames(&self) -> usize {
self.times.len()
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum VideoError {
Io { path: PathBuf, message: String },
Unsupported { path: PathBuf, hint: String },
NoFrame { index: usize, frames: usize },
Decode(String),
}
impl std::fmt::Display for VideoError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
VideoError::Io { path, message } => write!(f, "{}: {message}", path.display()),
VideoError::Unsupported { path, hint } => write!(f, "{}: {hint}", path.display()),
VideoError::NoFrame { index, frames } => write!(f, "frame {index} is past the end ({frames} frames)"),
VideoError::Decode(m) => write!(f, "decoding: {m}"),
}
}
}
impl std::error::Error for VideoError {}
impl VideoError {
pub(crate) fn io(path: &Path, e: impl std::fmt::Display) -> Self {
Self::Io { path: path.to_path_buf(), message: e.to_string() }
}
}
pub type VideoResult<T> = Result<T, VideoError>;
pub trait VideoSource: Send {
fn info(&self) -> &VideoInfo;
fn frame(&mut self, index: usize) -> VideoResult<Frame>;
}
pub fn open(path: &Path, rate: Option<f64>) -> VideoResult<Box<dyn VideoSource>> {
if path.is_dir() {
return Ok(Box::new(sequence::Sequence::open(path, rate)?));
}
let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();
#[cfg(feature = "h264")]
if matches!(ext.as_str(), "mp4" | "m4v" | "mov") {
match mp4::Mp4H264::open(path) {
Ok(v) => return Ok(Box::new(v)),
Err(VideoError::Unsupported { .. }) => {}
Err(e) => return Err(e),
}
}
if ffmpeg::available() {
return Ok(Box::new(ffmpeg::Ffmpeg::open(path)?));
}
let hint = if matches!(ext.as_str(), "mp4" | "m4v" | "mov") && !cfg!(feature = "h264") {
"this build decodes MP4 only through ffmpeg, which was not found: install ffmpeg".to_string()
} else {
format!("{} video needs ffmpeg, which was not found: install it (ffmpeg.org), or export the frames as images", if ext.is_empty() { "this".into() } else { ext.to_uppercase() })
};
Err(VideoError::Unsupported { path: path.to_path_buf(), hint })
}