kitchen_views/video/
mod.rs1pub mod cache;
16pub mod ffmpeg;
17#[cfg(feature = "h264")]
18pub mod mp4;
19pub mod sequence;
20pub mod times;
21
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24
25pub use cache::FrameCache;
26pub use times::FrameTimes;
27
28#[derive(Clone, Debug, PartialEq)]
30pub struct Frame {
31 pub index: usize,
32 pub time: f64,
34 pub width: u32,
35 pub height: u32,
36 pub rgba: Arc<Vec<u8>>,
37}
38
39impl Frame {
40 pub fn bytes(&self) -> usize {
42 self.rgba.len()
43 }
44}
45
46#[derive(Clone, Debug, PartialEq)]
48pub struct VideoInfo {
49 pub path: PathBuf,
50 pub width: u32,
51 pub height: u32,
52 pub times: FrameTimes,
54 pub format: String,
56}
57
58impl VideoInfo {
59 pub fn frames(&self) -> usize {
60 self.times.len()
61 }
62}
63
64#[derive(Clone, Debug, PartialEq)]
66pub enum VideoError {
67 Io { path: PathBuf, message: String },
69 Unsupported { path: PathBuf, hint: String },
71 NoFrame { index: usize, frames: usize },
73 Decode(String),
75}
76
77impl std::fmt::Display for VideoError {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 match self {
80 VideoError::Io { path, message } => write!(f, "{}: {message}", path.display()),
81 VideoError::Unsupported { path, hint } => write!(f, "{}: {hint}", path.display()),
82 VideoError::NoFrame { index, frames } => write!(f, "frame {index} is past the end ({frames} frames)"),
83 VideoError::Decode(m) => write!(f, "decoding: {m}"),
84 }
85 }
86}
87
88impl std::error::Error for VideoError {}
89
90impl VideoError {
91 pub(crate) fn io(path: &Path, e: impl std::fmt::Display) -> Self {
92 Self::Io { path: path.to_path_buf(), message: e.to_string() }
93 }
94}
95
96pub type VideoResult<T> = Result<T, VideoError>;
97
98pub trait VideoSource: Send {
100 fn info(&self) -> &VideoInfo;
101
102 fn frame(&mut self, index: usize) -> VideoResult<Frame>;
104}
105
106pub fn open(path: &Path, rate: Option<f64>) -> VideoResult<Box<dyn VideoSource>> {
110 if path.is_dir() {
111 return Ok(Box::new(sequence::Sequence::open(path, rate)?));
112 }
113 let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default();
114 #[cfg(feature = "h264")]
115 if matches!(ext.as_str(), "mp4" | "m4v" | "mov") {
116 match mp4::Mp4H264::open(path) {
117 Ok(v) => return Ok(Box::new(v)),
118 Err(VideoError::Unsupported { .. }) => {}
120 Err(e) => return Err(e),
121 }
122 }
123 if ffmpeg::available() {
124 return Ok(Box::new(ffmpeg::Ffmpeg::open(path)?));
125 }
126 let hint = if matches!(ext.as_str(), "mp4" | "m4v" | "mov") && !cfg!(feature = "h264") {
127 "this build decodes MP4 only through ffmpeg, which was not found: install ffmpeg".to_string()
128 } else {
129 format!(
130 "{} video needs ffmpeg, which was not found: install it (ffmpeg.org), or export the frames as images",
131 if ext.is_empty() { "this".into() } else { ext.to_uppercase() }
132 )
133 };
134 Err(VideoError::Unsupported { path: path.to_path_buf(), hint })
135}