Skip to main content

kitchen_views/video/
mod.rs

1//! Video, for research: every frame where it was, at the time it was taken. What matters is not
2//! smooth playback but **which frame** is shown at a given moment of the recording, so frames
3//! are addressed by index and carry their timestamp ([`FrameTimes`]), dropped frames are found,
4//! and the time is mapped onto the reference clock ([`crate::sync::Alignment`]).
5//!
6//! Sources ([`VideoSource`]), picked by [`open`]:
7//! - an image sequence (a folder of PNG, JPEG or TIFF frames: high-speed cameras) — [`sequence`];
8//! - MP4 with H.264, decoded in Rust (feature `h264`, OpenH264) — `mp4`;
9//! - anything else (AVI with MJPEG, Norpix, MKV…) through the system's `ffmpeg`, run as a separate
10//!   process: its licence stays outside this crate — [`ffmpeg`].
11//!
12//! In a browser the page decodes with WebCodecs (the hardware's decoder) and hands frames over;
13//! that source lives with the web app's loader.
14
15pub 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/// One decoded frame: RGBA, 8 bits a channel, rows top to bottom.
29#[derive(Clone, Debug, PartialEq)]
30pub struct Frame {
31    pub index: usize,
32    /// On the video's own clock, in seconds.
33    pub time: f64,
34    pub width: u32,
35    pub height: u32,
36    pub rgba: Arc<Vec<u8>>,
37}
38
39impl Frame {
40    /// Bytes it holds (for the cache's budget).
41    pub fn bytes(&self) -> usize {
42        self.rgba.len()
43    }
44}
45
46/// What a video is.
47#[derive(Clone, Debug, PartialEq)]
48pub struct VideoInfo {
49    pub path: PathBuf,
50    pub width: u32,
51    pub height: u32,
52    /// Each frame's timestamp, on the video's own clock.
53    pub times: FrameTimes,
54    /// The format, as people say it (`H.264 in MP4`, `PNG sequence`).
55    pub format: String,
56}
57
58impl VideoInfo {
59    pub fn frames(&self) -> usize {
60        self.times.len()
61    }
62}
63
64/// Why a video could not be read.
65#[derive(Clone, Debug, PartialEq)]
66pub enum VideoError {
67    /// A file could not be opened or read.
68    Io { path: PathBuf, message: String },
69    /// The file is not a video this build reads; how to read it.
70    Unsupported { path: PathBuf, hint: String },
71    /// A frame index past the end.
72    NoFrame { index: usize, frames: usize },
73    /// The decoder failed on a frame.
74    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
98/// A video's frames, by index. Decoding is blocking: views call it off the UI thread.
99pub trait VideoSource: Send {
100    fn info(&self) -> &VideoInfo;
101
102    /// Frame `index`, decoded.
103    fn frame(&mut self, index: usize) -> VideoResult<Frame>;
104}
105
106/// Opens the video at `path`: a folder of images, an MP4 (decoded in Rust when built with
107/// `h264`), or anything `ffmpeg` reads. `rate` is the frame rate of an image sequence without
108/// timestamps (ignored for files, which carry theirs).
109pub 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            // Not H.264 (HEVC, MJPEG in a MOV): ffmpeg below
119            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}