use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::audio::{Extract, extract};
use crate::error::{MediaError, Result};
use crate::ffmpeg::{Exec, Input, Job};
use crate::probe::{MediaInfo, ffprobe};
pub const DEDUP_MS: u64 = 250;
pub const JPEG_Q: u8 = 4;
pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "m4v", "mov", "webm", "mkv", "avi"];
pub fn is_video_path(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| VIDEO_EXTENSIONS.iter().any(|v| v.eq_ignore_ascii_case(e)))
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct VideoProbe {
pub duration_ms: u64,
pub width: u32,
pub height: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fps: Option<f32>,
pub has_audio: bool,
}
impl VideoProbe {
pub fn from_info(info: &MediaInfo) -> Result<VideoProbe> {
let v = info.video.as_ref().ok_or_else(|| MediaError::invalid("the file has no video stream"))?;
Ok(VideoProbe { duration_ms: info.duration_ms.unwrap_or(0), width: v.width, height: v.height, fps: v.fps, has_audio: info.audio.is_some() })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Frame {
pub mime: String,
pub bytes: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimedFrame {
pub at_ms: u64,
pub frame: Frame,
}
pub trait FrameSource {
fn probe(&self) -> Result<VideoProbe>;
fn frame_at(&self, at_ms: u64, width: u32, height: u32) -> Result<Frame>;
fn scenes(&self, threshold: f32) -> Result<Vec<(u64, f32)>>;
fn keyframes(&self) -> Result<Vec<u64>> {
Ok(Vec::new())
}
fn audio(&self, start_ms: u64, len_ms: u64) -> Result<Vec<u8>>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "mode")]
#[non_exhaustive]
pub enum Mode {
#[default]
Uniform,
Scene,
Hybrid,
Keyframes,
Every { ms: u64 },
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Marks {
pub scenes: Vec<(u64, f32)>,
pub keyframes: Vec<u64>,
}
pub fn uniform(start: u64, end: u64, n: u32) -> Vec<u64> {
let len = end.saturating_sub(start);
if n == 0 || len == 0 {
return if n == 0 { Vec::new() } else { vec![start] };
}
let n = u64::from(n).min(len);
(0..n).map(|i| start + (2 * i + 1) * len / (2 * n)).collect()
}
pub fn every(start: u64, end: u64, every_ms: u64, n: u32) -> Vec<u64> {
if n == 0 || every_ms == 0 {
return Vec::new();
}
(0..u64::from(n)).map(|i| start + i * every_ms).take_while(|t| *t < end.max(start + 1)).collect()
}
fn tidy(mut times: Vec<u64>, start: u64, end: u64) -> Vec<u64> {
times.retain(|t| *t >= start && *t < end.max(start + 1));
times.sort_unstable();
times.dedup();
times
}
fn top_up(mut times: Vec<u64>, start: u64, end: u64, n: u32) -> Vec<u64> {
let mut k = n;
while (times.len() as u32) < n && k <= n.saturating_mul(4).max(4) {
for t in uniform(start, end, k) {
if times.len() as u32 >= n {
break;
}
if !times.iter().any(|c| c.abs_diff(t) < DEDUP_MS) {
times.push(t);
}
}
k += 1;
}
tidy(times, start, end)
}
pub fn plan_frames(mode: Mode, range: (u64, u64), n: u32, marks: &Marks) -> Vec<u64> {
let (start, end) = range;
if n == 0 {
return Vec::new();
}
let strongest = |k: usize, near: &[u64]| -> Vec<u64> {
let mut hits: Vec<(u64, f32)> = marks.scenes.iter().copied().filter(|(t, _)| *t > start && *t < end).collect();
hits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal).then(a.0.cmp(&b.0)));
let mut out: Vec<u64> = Vec::new();
for (t, _) in hits {
if out.len() >= k {
break;
}
if !out.iter().chain(near).any(|c| c.abs_diff(t) < DEDUP_MS) {
out.push(t);
}
}
out
};
let times = match mode {
Mode::Uniform => uniform(start, end, n),
Mode::Scene => {
let mut t = vec![start];
t.extend(strongest(n as usize - 1, &[start]));
top_up(t, start, end, n)
}
Mode::Hybrid => {
let backbone = uniform(start, end, n.div_ceil(2));
let mut t = backbone.clone();
t.extend(strongest((n as usize).saturating_sub(backbone.len()), &backbone));
top_up(t, start, end, n)
}
Mode::Keyframes => {
let keys = tidy(marks.keyframes.clone(), start, end);
let picked: Vec<u64> = if keys.len() as u32 <= n {
keys
} else {
uniform(start, end, n).into_iter().filter_map(|slot| keys.iter().copied().min_by_key(|k| (k.abs_diff(slot), *k))).collect()
};
top_up(tidy(picked, start, end), start, end, n)
}
Mode::Every { ms } => every(start, end, ms, n),
};
let mut times = tidy(times, start, end);
times.truncate(n as usize);
times
}
pub fn fit(w: u32, h: u32, edge: Option<u32>) -> (u32, u32) {
let even = |x: u32| (x.max(2) / 2) * 2;
match edge {
Some(e) if w.max(h) > e && e > 0 => {
let (w, h, e) = (u64::from(w), u64::from(h), u64::from(e));
if w >= h { (even(e as u32), even((h * e / w).max(2) as u32)) } else { (even((w * e / h).max(2) as u32), even(e as u32)) }
}
_ => (even(w), even(h)),
}
}
pub fn label(ms: u64) -> String {
let s = ms / 1000;
format!("[{:02}:{:02}.{}]", s / 60, s % 60, (ms % 1000) / 100)
}
pub fn clip_range(probe: &VideoProbe, range: Option<(u64, u64)>) -> Result<(u64, u64)> {
let len = probe.duration_ms;
match range {
None => Ok((0, len.max(1))),
Some((a, b)) if a < b && a < len.max(1) => Ok((a, b.min(len.max(1)))),
Some((a, b)) => Err(MediaError::invalid(format!("range {}..{} is outside the clip ({} ms)", label(a), label(b), len))),
}
}
pub fn parse_scenes(text: &str) -> Vec<(u64, f32)> {
let mut out = Vec::new();
let mut at: Option<u64> = None;
for line in text.lines() {
if let Some(t) = line.split_whitespace().find_map(|w| w.strip_prefix("pts_time:")).and_then(|t| t.parse::<f64>().ok()) {
at = Some((t * 1000.0).round().max(0.0) as u64);
} else if let (Some(t), Some(score)) = (at, line.trim().strip_prefix("lavfi.scene_score=").and_then(|s| s.parse::<f32>().ok())) {
out.push((t, score));
at = None;
}
}
out
}
pub fn parse_keyframes(text: &str) -> Vec<u64> {
let mut out: Vec<u64> = text
.lines()
.filter_map(|l| {
let (t, flags) = l.trim().split_once(',')?;
flags.contains('K').then_some(())?;
t.parse::<f64>().ok().filter(|t| t.is_finite() && *t >= 0.0).map(|t| (t * 1000.0).round() as u64)
})
.collect();
out.sort_unstable();
out.dedup();
out
}
fn secs(ms: u64) -> String {
format!("{}.{:03}", ms / 1000, ms % 1000)
}
#[derive(Debug, Clone)]
pub struct FfmpegSource<E: Exec> {
exec: E,
input: Input,
pub max_frame_bytes: u64,
pub max_audio_ms: u64,
}
impl<E: Exec> FfmpegSource<E> {
pub fn new(exec: E, input: Input) -> Self {
FfmpegSource { exec, input, max_frame_bytes: 4 << 20, max_audio_ms: 10 * 60 * 1000 }
}
pub fn input(&self) -> &Input {
&self.input
}
pub fn exec(&self) -> &E {
&self.exec
}
pub fn info(&self) -> Result<MediaInfo> {
ffprobe(&self.exec, &self.input)
}
}
impl<E: Exec> FrameSource for FfmpegSource<E> {
fn probe(&self) -> Result<VideoProbe> {
VideoProbe::from_info(&self.info()?)
}
fn frame_at(&self, at_ms: u64, width: u32, height: u32) -> Result<Frame> {
let job = Job::ffmpeg(self.input.clone())
.before_input(["-ss".to_string(), secs(at_ms)])
.args(["-an", "-sn", "-dn", "-map_metadata", "-1", "-frames:v", "1"])
.args(["-vf".to_string(), format!("scale={width}:{height}")])
.args(["-c:v".to_string(), "mjpeg".into(), "-q:v".into(), JPEG_Q.to_string(), "-f".into(), "image2pipe".into(), "pipe:1".into()])
.max_output(self.max_frame_bytes);
let bytes = self.exec.exec(&job)?;
if !bytes.starts_with(&[0xFF, 0xD8]) {
return Err(MediaError::invalid(format!("no frame at {}", label(at_ms))));
}
Ok(Frame { mime: "image/jpeg".into(), bytes })
}
fn scenes(&self, threshold: f32) -> Result<Vec<(u64, f32)>> {
let threshold = threshold.clamp(0.0, 1.0);
let job = Job::ffmpeg(self.input.clone())
.args(["-an", "-sn", "-dn", "-vf"])
.args([format!("select='gt(scene,{threshold})',metadata=print:file=-")])
.args(["-f", "null", "-"])
.max_output(16 << 20);
Ok(parse_scenes(&String::from_utf8_lossy(&self.exec.exec(&job)?)))
}
fn keyframes(&self) -> Result<Vec<u64>> {
let job = Job::ffprobe(self.input.clone())
.args(["-select_streams", "v:0", "-show_entries", "packet=pts_time,flags", "-of", "csv=p=0"])
.max_output(64 << 20);
Ok(parse_keyframes(&String::from_utf8_lossy(&self.exec.exec(&job)?)))
}
fn audio(&self, start_ms: u64, len_ms: u64) -> Result<Vec<u8>> {
extract(&self.exec, &self.input, &Extract::transcribe(self.max_audio_ms).range(start_ms, len_ms.min(self.max_audio_ms)))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FrameRequest {
pub count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_edge: Option<u32>,
pub mode: Mode,
pub scene_threshold: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub range: Option<(u64, u64)>,
pub max_total_bytes: u64,
}
impl FrameRequest {
pub fn new(count: u32) -> Self {
FrameRequest { count, max_edge: None, mode: Mode::Uniform, scene_threshold: 0.3, range: None, max_total_bytes: 32 << 20 }
}
pub fn max_edge(mut self, edge: u32) -> Self {
self.max_edge = Some(edge);
self
}
pub fn mode(mut self, mode: Mode) -> Self {
self.mode = mode;
self
}
pub fn scene_threshold(mut self, t: f32) -> Self {
self.scene_threshold = t;
self
}
pub fn range(mut self, start_ms: u64, end_ms: u64) -> Self {
self.range = Some((start_ms, end_ms));
self
}
pub fn max_total_bytes(mut self, bytes: u64) -> Self {
self.max_total_bytes = bytes;
self
}
}
pub fn extract_frames(source: &dyn FrameSource, req: &FrameRequest) -> Result<(VideoProbe, Vec<TimedFrame>)> {
let probe = source.probe()?;
let range = clip_range(&probe, req.range)?;
let marks = match req.mode {
Mode::Scene | Mode::Hybrid => Marks { scenes: source.scenes(req.scene_threshold)?, keyframes: Vec::new() },
Mode::Keyframes => Marks { scenes: Vec::new(), keyframes: source.keyframes()? },
_ => Marks::default(),
};
let (w, h) = fit(probe.width, probe.height, req.max_edge);
let mut frames = Vec::new();
let mut total = 0u64;
for t in plan_frames(req.mode, range, req.count, &marks) {
let frame = source.frame_at(t, w, h)?;
total += frame.bytes.len() as u64;
if total > req.max_total_bytes {
return Err(MediaError::limit(format!("the frames come to over {} bytes; ask for fewer frames or a smaller edge", req.max_total_bytes)));
}
frames.push(TimedFrame { at_ms: t, frame });
}
Ok((probe, frames))
}
pub fn thumbnail(source: &dyn FrameSource, at_ms: Option<u64>, max_edge: Option<u32>) -> Result<TimedFrame> {
let probe = source.probe()?;
let at = at_ms.unwrap_or((probe.duration_ms / 10).min(10_000)).min(probe.duration_ms.saturating_sub(1));
let (w, h) = fit(probe.width, probe.height, max_edge);
Ok(TimedFrame { at_ms: at, frame: source.frame_at(at, w, h)? })
}
pub fn soundtrack(source: &dyn FrameSource, range: Option<(u64, u64)>) -> Result<Option<Vec<u8>>> {
let probe = source.probe()?;
if !probe.has_audio {
return Ok(None);
}
let (a, b) = clip_range(&probe, range)?;
source.audio(a, b - a).map(Some)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ClipFormat {
Mp4,
Matroska,
Webm,
}
impl ClipFormat {
pub fn mime(self) -> &'static str {
match self {
ClipFormat::Mp4 => "video/mp4",
ClipFormat::Matroska => "video/x-matroska",
ClipFormat::Webm => "video/webm",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ClipRequest {
pub start_ms: u64,
pub len_ms: u64,
pub format: ClipFormat,
pub audio: bool,
pub max_bytes: u64,
}
impl ClipRequest {
pub fn new(start_ms: u64, len_ms: u64, max_bytes: u64) -> Self {
ClipRequest { start_ms, len_ms, format: ClipFormat::Mp4, audio: true, max_bytes }
}
pub fn format(mut self, format: ClipFormat) -> Self {
self.format = format;
self
}
pub fn without_audio(mut self) -> Self {
self.audio = false;
self
}
}
pub fn clip(exec: &dyn Exec, input: &Input, req: &ClipRequest) -> Result<Vec<u8>> {
if req.len_ms == 0 {
return Err(MediaError::invalid("a clip needs a length"));
}
let mut job = Job::ffmpeg(input.clone()).before_input(["-ss".to_string(), secs(req.start_ms), "-t".to_string(), secs(req.len_ms)]);
job = job.args(["-map", "0:v:0"]);
if req.audio {
job = job.args(["-map", "0:a:0?"]);
}
job = job.args(["-sn", "-dn", "-map_metadata", "-1", "-c", "copy"]);
job = match req.format {
ClipFormat::Mp4 => job.args(["-movflags", "frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "pipe:1"]),
ClipFormat::Matroska => job.args(["-f", "matroska", "pipe:1"]),
ClipFormat::Webm => job.args(["-f", "webm", "pipe:1"]),
};
exec.exec(&job.max_output(req.max_bytes))
}
#[derive(Debug, Clone, PartialEq)]
pub struct FakeSource {
pub probe: VideoProbe,
pub scenes: Vec<(u64, f32)>,
pub keyframes: Vec<u64>,
}
impl FakeSource {
pub fn new(duration_ms: u64, has_audio: bool) -> Self {
FakeSource {
probe: VideoProbe { duration_ms, width: 1920, height: 1080, fps: Some(30.0), has_audio },
scenes: Vec::new(),
keyframes: (0..duration_ms).step_by(2000).collect(),
}
}
pub fn with_scenes(mut self, scenes: Vec<(u64, f32)>) -> Self {
self.scenes = scenes;
self
}
}
impl FrameSource for FakeSource {
fn probe(&self) -> Result<VideoProbe> {
Ok(self.probe)
}
fn frame_at(&self, at_ms: u64, width: u32, height: u32) -> Result<Frame> {
let mut bytes = vec![0xFF, 0xD8, 0xFF];
bytes.extend(format!("{at_ms}@{width}x{height}").into_bytes());
Ok(Frame { mime: "image/jpeg".into(), bytes })
}
fn scenes(&self, threshold: f32) -> Result<Vec<(u64, f32)>> {
Ok(self.scenes.iter().copied().filter(|(_, s)| *s > threshold).collect())
}
fn keyframes(&self) -> Result<Vec<u64>> {
Ok(self.keyframes.clone())
}
fn audio(&self, _start_ms: u64, len_ms: u64) -> Result<Vec<u8>> {
Ok(crate::pcm::encode_wav(&crate::pcm::Pcm::silence(crate::pcm::TRANSCRIBE_RATE, 1, len_ms)))
}
}