mod install;
mod probe;
pub use install::install_on_start;
pub(crate) use install::installed;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tokio::process::Command;
use install::Binaries;
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
const FRAMES_TIMEOUT: Duration = Duration::from_secs(120);
const AUDIO_TIMEOUT: Duration = Duration::from_secs(300);
const PROBE_ENTRIES: &str = "format=duration:stream=codec_type,width,height,duration\
:stream_tags=rotate:stream_side_data=rotation\
:stream_disposition=attached_pic";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ClipInfo {
pub(crate) duration: Duration,
pub(crate) dimensions: Option<(u32, u32)>,
pub(crate) has_audio: bool,
pub(crate) picture: Option<Duration>,
pub(crate) sound: Option<Duration>,
pub(crate) bytes: u64,
}
impl ClipInfo {
#[must_use]
pub(crate) fn sound_length(&self) -> Duration {
self.sound.unwrap_or(self.duration)
}
#[must_use]
pub(crate) fn picture_length(&self) -> Duration {
self.picture.unwrap_or(self.duration)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum FfmpegError {
Unavailable(String),
NoVideoTrack,
NoAudioTrack,
Undecodable,
TimedOut,
InvalidOptions(&'static str),
}
#[derive(Debug)]
pub(crate) struct Frames {
_dir: tempfile::TempDir,
frames: Vec<(PathBuf, f64)>,
}
impl Frames {
#[must_use]
pub(crate) fn frames(&self) -> &[(PathBuf, f64)] {
&self.frames
}
}
#[derive(Debug)]
pub(crate) struct Audio {
_dir: tempfile::TempDir,
path: PathBuf,
}
impl Audio {
#[must_use]
pub(crate) fn path(&self) -> &Path {
&self.path
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct FrameOptions<'a> {
pub(crate) marks: &'a [f64],
pub(crate) max_side: u32,
}
pub(crate) const FRAME_QUALITY: u8 = 80;
const FRAME_QUANTISER: u32 = 31 - FRAME_QUALITY as u32 * 29 / 100;
pub(crate) async fn binaries() -> Result<Binaries, String> {
install::ensure_installed().await
}
pub(crate) async fn probe(path: &Path) -> Result<ClipInfo, FfmpegError> {
let bin = binaries().await.map_err(FfmpegError::Unavailable)?;
probe_with(&bin.ffprobe, path).await
}
pub(crate) async fn extract_frames(
input: &Path,
options: FrameOptions<'_>,
) -> Result<Frames, FfmpegError> {
if options.marks.is_empty() {
return Err(FfmpegError::InvalidOptions("no frames were asked for"));
}
if options.max_side < 2 {
return Err(FfmpegError::InvalidOptions(
"the longest side must be at least two pixels",
));
}
let bin = binaries().await.map_err(FfmpegError::Unavailable)?;
let dir = scratch()?;
let deadline = Instant::now() + FRAMES_TIMEOUT;
let mut frames = Vec::with_capacity(options.marks.len());
let mut ran_out = false;
for (index, at) in options.marks.iter().enumerate() {
let into = dir.path().join(format!("frame-{index:05}.jpg"));
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
ran_out = true;
break;
}
let args = frame_args(input, *at, Some(&into), options.max_side);
match run_tool(&bin.ffmpeg, &args, left).await {
Ok(output) if output.success && tokio::fs::try_exists(&into).await.unwrap_or(false) => {
frames.push((into, *at));
}
Ok(output) => {
tracing::debug!("ffmpeg wrote no frame at {at}: {}", output.stderr.trim());
}
Err(FfmpegError::TimedOut) => {
ran_out = true;
break;
}
Err(error) => return Err(error),
}
}
if ran_out {
return if frames.is_empty() {
Err(FfmpegError::TimedOut)
} else {
Ok(Frames { _dir: dir, frames })
};
}
if frames.is_empty() {
let replay = Decode::Frames {
at: options.marks[0],
side: options.max_side,
};
return Err(classify(&bin, input, replay).await);
}
Ok(Frames { _dir: dir, frames })
}
pub(crate) async fn extract_audio(
input: &Path,
window: Option<(Duration, Duration)>,
) -> Result<Audio, FfmpegError> {
let bin = binaries().await.map_err(FfmpegError::Unavailable)?;
audio_with(&bin, input, window).await
}
pub(crate) async fn convert_audio(input: &Path) -> Result<Audio, FfmpegError> {
let Some(bin) = installed() else {
return Err(FfmpegError::Unavailable(
"no copy of the product's media toolchain is installed".to_string(),
));
};
audio_with(&bin, input, None).await
}
async fn audio_with(
bin: &Binaries,
input: &Path,
window: Option<(Duration, Duration)>,
) -> Result<Audio, FfmpegError> {
tokio::time::timeout(AUDIO_TIMEOUT, async {
let dir = scratch()?;
let path = dir.path().join("audio.wav");
let args = audio_args(input, window, Some(&path));
let output = run_tool(&bin.ffmpeg, &args, AUDIO_TIMEOUT).await?;
if !output.success {
tracing::debug!("ffmpeg extracted no audio: {}", output.stderr.trim());
return Err(classify(bin, input, Decode::Audio(window)).await);
}
Ok(Audio { _dir: dir, path })
})
.await
.map_err(|_| FfmpegError::TimedOut)?
}
async fn probe_with(ffprobe: &Path, path: &Path) -> Result<ClipInfo, FfmpegError> {
let output = run_tool(ffprobe, &probe_args(path), PROBE_TIMEOUT).await?;
let Some(mut info) = probe::parse(&output.stdout) else {
tracing::debug!("ffprobe could not read the file: {}", output.stderr.trim());
return Err(FfmpegError::Undecodable);
};
info.bytes = tokio::fs::metadata(path)
.await
.map_err(|_| FfmpegError::Undecodable)?
.len();
Ok(info)
}
#[derive(Debug, Clone, Copy)]
enum Decode {
Frames { at: f64, side: u32 },
Audio(Option<(Duration, Duration)>),
}
async fn classify(bin: &Binaries, input: &Path, decode: Decode) -> FfmpegError {
let info = match probe_with(&bin.ffprobe, input).await {
Err(error) => return error,
Ok(info) => info,
};
let (replay, timeout) = match decode {
Decode::Frames { .. } if info.dimensions.is_none() => return FfmpegError::NoVideoTrack,
Decode::Audio(_) if !info.has_audio => return FfmpegError::NoAudioTrack,
Decode::Frames { at, side } => (frame_args(input, at, None, side), FRAMES_TIMEOUT),
Decode::Audio(window) => (audio_args(input, window, None), AUDIO_TIMEOUT),
};
match run_tool(&bin.ffmpeg, &replay, timeout).await {
Ok(output) if output.success => {
FfmpegError::Unavailable("the product's own output could not be written".to_string())
}
Ok(_) => FfmpegError::Undecodable,
Err(error) => error,
}
}
struct Output {
success: bool,
stdout: Vec<u8>,
stderr: String,
}
async fn run_tool(
program: &Path,
args: &[OsString],
timeout: Duration,
) -> Result<Output, FfmpegError> {
let mut command = Command::new(program);
#[cfg(target_os = "windows")]
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
command
.args(args)
.stdin(std::process::Stdio::null())
.kill_on_drop(true);
let finished = tokio::time::timeout(timeout, command.output())
.await
.map_err(|_| FfmpegError::TimedOut)?
.map_err(|e| {
FfmpegError::Unavailable(format!(
"the product's own {} could not be started ({})",
tool_name(program),
e.kind()
))
})?;
if finished.status.code().is_none() {
return Err(FfmpegError::Unavailable(format!(
"the product's own {} was stopped before it finished",
tool_name(program)
)));
}
Ok(Output {
success: finished.status.success(),
stdout: finished.stdout,
stderr: String::from_utf8_lossy(&finished.stderr).into_owned(),
})
}
fn tool_name(program: &Path) -> String {
program
.file_stem()
.and_then(std::ffi::OsStr::to_str)
.map_or_else(|| "tool".to_string(), str::to_owned)
}
fn scratch() -> Result<tempfile::TempDir, FfmpegError> {
tempfile::tempdir().map_err(|e| {
FfmpegError::Unavailable(format!(
"the product's own scratch directory could not be created ({})",
e.kind()
))
})
}
fn probe_args(input: &Path) -> Vec<OsString> {
vec![
"-v".into(),
"error".into(),
"-print_format".into(),
"json".into(),
"-show_entries".into(),
PROBE_ENTRIES.into(),
input.into(),
]
}
fn window_args(window: Option<(Duration, Duration)>) -> Vec<OsString> {
window.map_or_else(Vec::new, |(start, length)| {
vec![
"-ss".into(),
format!("{:.3}", start.as_secs_f64()).into(),
"-t".into(),
format!("{:.3}", length.as_secs_f64()).into(),
]
})
}
fn frame_args(input: &Path, at: f64, into: Option<&Path>, side: u32) -> Vec<OsString> {
let filter = format!(
"scale={side}:{side}:force_original_aspect_ratio=decrease,\
scale=trunc(iw/2)*2:trunc(ih/2)*2"
);
let mut args: Vec<OsString> = vec!["-v".into(), "error".into(), "-nostdin".into(), "-y".into()];
args.extend([
"-ss".into(),
format!("{at:.3}").into(),
"-i".into(),
input.into(),
"-vf".into(),
filter.into(),
"-frames:v".into(),
"1".into(),
]);
match into {
Some(path) => args.extend([
"-q:v".into(),
FRAME_QUANTISER.to_string().into(),
"-f".into(),
"image2".into(),
path.into(),
]),
None => args.extend(["-f".into(), "null".into(), "-".into()]),
}
args
}
fn audio_args(
input: &Path,
window: Option<(Duration, Duration)>,
into: Option<&Path>,
) -> Vec<OsString> {
let mut args: Vec<OsString> = vec!["-v".into(), "error".into(), "-nostdin".into(), "-y".into()];
args.extend(window_args(window));
args.extend([
"-i".into(),
input.into(),
"-vn".into(),
"-sn".into(),
"-dn".into(),
"-ac".into(),
"1".into(),
"-ar".into(),
"16000".into(),
"-c:a".into(),
"pcm_s16le".into(),
]);
match into {
Some(output) => args.extend(["-f".into(), "wav".into(), output.into()]),
None => args.extend(["-f".into(), "null".into(), "-".into()]),
}
args
}
#[cfg(test)]
pub(crate) use install::ROOT_ENV;
#[cfg(test)]
pub(crate) struct ReleasesHook(Option<std::ffi::OsString>);
#[cfg(test)]
impl ReleasesHook {
pub(crate) fn at(base: &str) -> Self {
let previous = std::env::var_os(install::RELEASES_URL_ENV);
unsafe { std::env::set_var(install::RELEASES_URL_ENV, base) };
install::forget_failed_attempt();
Self(previous)
}
}
#[cfg(test)]
impl Drop for ReleasesHook {
fn drop(&mut self) {
unsafe {
match self.0.take() {
Some(previous) => std::env::set_var(install::RELEASES_URL_ENV, previous),
None => std::env::remove_var(install::RELEASES_URL_ENV),
}
}
}
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command as Std;
use super::*;
#[test]
fn the_replay_is_the_whole_decode_with_nothing_to_write() {
let input = Path::new("/media/clip.mp4");
let marks = [2.0, 4.5];
let options = FrameOptions {
marks: &marks,
max_side: 320,
};
let at = |args: &[OsString], flag: &str| {
args.iter()
.position(|arg| arg.to_str() == Some(flag))
.unwrap_or_else(|| panic!("{flag} is missing from {args:?}"))
};
let frame = frame_args(
input,
marks[0],
Some(Path::new("/scratch/frame-00000.jpg")),
options.max_side,
);
let replay = frame_args(input, marks[0], None, options.max_side);
assert_eq!(&frame[..frame.len() - 5], &replay[..replay.len() - 3]);
for args in [frame.as_slice(), replay.as_slice()] {
assert!(
at(args, "-ss") < at(args, "-i"),
"the seek is an input option"
);
assert_eq!(args[at(args, "-ss") + 1].to_str(), Some("2.000"));
assert_eq!(args[at(args, "-frames:v") + 1].to_str(), Some("1"));
}
let audio = audio_args(input, None, Some(Path::new("/scratch/audio.wav")));
let replay = audio_args(input, None, None);
assert_eq!(&audio[..audio.len() - 3], &replay[..replay.len() - 3]);
let window = Some((Duration::from_secs(2), Duration::from_millis(1500)));
let audio = audio_args(input, window, Some(Path::new("/scratch/audio.wav")));
let replay = audio_args(input, window, None);
for args in [audio.as_slice(), replay.as_slice()] {
assert!(at(args, "-ss") < at(args, "-i"));
assert!(at(args, "-t") < at(args, "-i"));
assert_eq!(args[at(args, "-ss") + 1].to_str(), Some("2.000"));
assert_eq!(args[at(args, "-t") + 1].to_str(), Some("1.500"));
}
assert_eq!(&audio[..at(&audio, "-i")], &replay[..at(&replay, "-i")]);
}
struct Install {
_home: tempfile::TempDir,
host: Option<PathBuf>,
root: PathBuf,
bin: PathBuf,
_hook: ReleasesHook,
_env: crate::util::test::EnvVarGuard,
}
impl Install {
fn new(pair: bool) -> Self {
let home = tempfile::tempdir().expect("temp home");
let root = home.path().join(".mahbot/ffmpeg");
let bin = root.join("ffmpeg-v7.1-mahbot.2").join("bin");
let env = crate::util::test::set_env_var(install::ROOT_ENV, root.to_str());
let hook = ReleasesHook::at("http://127.0.0.1:1");
let host =
pair.then(|| {
PathBuf::from(std::env::var_os("MAHBOT_FFMPEG_LIVE_BIN").expect(
"MAHBOT_FFMPEG_LIVE_BIN names a directory holding ffmpeg and ffprobe",
))
});
if let Some(host) = &host {
std::fs::create_dir_all(&bin).expect("install directory");
for tool in ["ffmpeg", "ffprobe"] {
std::fs::copy(host.join(tool), bin.join(tool)).expect("copy the stand-in tool");
}
}
Self {
_home: home,
host,
root,
bin,
_hook: hook,
_env: env,
}
}
fn host(&self) -> &Path {
self.host.as_deref().expect("the host pair was copied in")
}
}
#[ignore = "requires MAHBOT_FFMPEG_LIVE_BIN: a directory holding a real ffmpeg and ffprobe"]
#[serial_test::serial(ffmpeg_live)] #[tokio::test]
async fn the_operations_on_real_files() {
let install = Install::new(true);
let host = install.host();
let found = install::ensure_installed()
.await
.expect("the copy in place is used");
assert_eq!(
found.ffmpeg,
install.bin.join("ffmpeg"),
"by path, not by origin"
);
assert_eq!(found.ffprobe, install.bin.join("ffprobe"));
let media = tempfile::tempdir().expect("media directory");
let good = media.path().join("good.mp4");
let silent = media.path().join("silent.mp4");
let rotated = media.path().join("rotated.mp4");
let broken = media.path().join("broken.mp4");
make(
host,
&good,
&[
"-f",
"lavfi",
"-i",
"testsrc=size=1280x720:rate=30:duration=2",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=2",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
"-shortest",
],
);
make(
host,
&silent,
&[
"-f",
"lavfi",
"-i",
"testsrc=size=640x480:rate=25:duration=2",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
],
);
let good_text = good.to_str().expect("utf8").to_string();
make(
host,
&rotated,
&["-display_rotation", "90", "-i", &good_text, "-c", "copy"],
);
std::fs::write(&broken, b"not a video at all").expect("broken file");
let info = probe(&good).await.expect("a good clip probes");
assert_eq!(info.duration.as_secs(), 2);
assert_eq!(info.dimensions, Some((1280, 720)));
assert!(info.has_audio);
let no_audio = probe(&silent).await.expect("a silent clip probes");
assert_eq!(no_audio.dimensions, Some((640, 480)));
assert!(!no_audio.has_audio);
let turned = probe(&rotated).await.expect("a rotated clip probes");
assert_eq!(
turned.dimensions,
Some((720, 1280)),
"a rotated clip reports its upright size"
);
assert_eq!(probe(&broken).await.err(), Some(FfmpegError::Undecodable));
let marks = [0.0, 0.5, 1.0];
let frames = extract_frames(
&good,
FrameOptions {
marks: &marks,
max_side: 320,
},
)
.await
.expect("frames come out");
assert_eq!(frames.frames().len(), 3, "one frame per mark");
assert!(
(frames.frames()[2].1 - 1.0).abs() < f64::EPSILON,
"each frame carries its mark"
);
let first = frames.frames()[0].0.clone();
for (path, _) in frames.frames() {
assert_eq!(path.extension(), Some(OsStr::new("jpg")));
let image = image::load_from_memory(&std::fs::read(path).expect("read a frame"))
.expect("a JPEG");
assert!(
image.width() <= 320 && image.height() <= 320,
"the side bound"
);
assert_eq!(image.width() * 9, image.height() * 16, "the aspect ratio");
}
drop(frames);
assert!(!first.exists(), "dropping the guard removes the frames");
let past_the_end = [0.0, 0.5, 1.0, 5.0];
let frames = extract_frames(
&good,
FrameOptions {
marks: &past_the_end,
max_side: 320,
},
)
.await
.expect("the frames before the missing mark come out");
assert_eq!(frames.frames().len(), 3, "the mark past the end is skipped");
let soundy = media.path().join("soundy.mp4");
make(
host,
&soundy,
&[
"-f",
"lavfi",
"-i",
"testsrc=size=320x240:rate=25:duration=2",
"-f",
"lavfi",
"-i",
"sine=frequency=440:duration=5",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-c:a",
"aac",
],
);
let uneven = probe(&soundy).await.expect("the uneven clip probes");
assert_eq!(uneven.duration.as_secs(), 5, "the container's own length");
assert_eq!(
uneven.picture.map(|picture| picture.as_secs()),
Some(2),
"the picture stream's own length"
);
assert_eq!(uneven.sound.map(|sound| sound.as_secs()), Some(5));
assert_eq!(
extract_frames(
&broken,
FrameOptions {
marks: &[0.0],
max_side: 320,
}
)
.await
.err(),
Some(FfmpegError::Undecodable)
);
let pair = binaries().await.expect("the copy in place is used");
let options = Decode::Frames { at: 0.0, side: 320 };
let product_side = classify(&pair, &good, options).await;
assert!(
matches!(product_side, FfmpegError::Unavailable(ref reason) if !reason.is_empty()),
"{product_side:?}"
);
assert_eq!(
classify(&pair, &broken, options).await,
FfmpegError::Undecodable,
"the same call still names the file that cannot be read"
);
let audio = extract_audio(&good, None).await.expect("audio comes out");
let wav = std::fs::read(audio.path()).expect("read the WAV");
assert_eq!(u16::from_le_bytes([wav[22], wav[23]]), 1, "mono");
assert_eq!(
u32::from_le_bytes([wav[24], wav[25], wav[26], wav[27]]),
16_000
);
assert_eq!(
probe(audio.path())
.await
.expect("the WAV probes")
.duration
.as_secs(),
2
);
assert_eq!(
extract_audio(&silent, None).await.err(),
Some(FfmpegError::NoAudioTrack)
);
assert_eq!(
extract_audio(&broken, None).await.err(),
Some(FfmpegError::Undecodable)
);
let window = |start: f64, length: f64| crate::media::Window::Span {
start,
length: Some(length),
};
let reading = crate::media::read(&silent, window(0.5, 1.0))
.await
.expect("a silent clip reads");
assert!(
reading.text.contains("0:00.5 [frame 1]"),
"{}",
reading.text
);
assert!(reading.text.contains("0:01 [frame 2]"), "{}", reading.text);
assert!(
reading.text.contains("This video has no sound track."),
"{}",
reading.text
);
let (model, attached) = crate::media::inline(&reading).await;
assert!(attached);
assert!(model.contains("picture 1: frames 1–2"), "{model}");
let (text, payloads) =
crate::tools::timeline_output(reading, crate::tools::TimelinePictures::Attached).await;
assert!(!text.contains("picture 1"), "{text}");
assert_eq!(payloads.len(), 1);
assert_eq!(
payloads[0].note.as_deref(),
Some("picture 1 of 1: frames 1–2")
);
let past = crate::media::read(&silent, window(5.0, 1.0))
.await
.expect("a window past the end still answers");
assert!(
past.pictures().await.is_empty(),
"there is no picture there"
);
assert!(
past.text
.contains("The read starts at 0:05, past the end of the 0:02 file."),
"{}",
past.text
);
std::fs::remove_dir_all(&install.root).expect("remove the copy");
let unavailable = probe(&good).await.expect_err("no copy, no answer");
assert!(
matches!(unavailable, FfmpegError::Unavailable(ref reason) if !reason.is_empty()),
"{unavailable:?}"
);
assert!(good.exists());
}
#[serial_test::serial(ffmpeg_live, ffmpeg_releases)] #[tokio::test]
async fn a_conversion_never_installs_the_toolchain() {
let install = Install::new(false);
let media = tempfile::tempdir().expect("media directory");
let recording = media.path().join("note.m4a");
std::fs::write(&recording, b"\0\0\0\x20ftypM4A \0\0\0\0").expect("a recording");
let error = crate::speech::decode::samples_of(&recording)
.await
.expect_err("no decoder here, and no toolchain to convert it");
assert!(format!("{error:#}").contains("cannot be read"), "{error:#}");
assert!(
installed().is_none(),
"a transcription must not install the pair"
);
assert!(!install.root.exists(), "nothing was installed");
}
#[ignore = "requires MAHBOT_FFMPEG_LIVE_BIN: a directory holding a real ffmpeg and ffprobe"]
#[serial_test::serial(ffmpeg_live)] #[tokio::test]
async fn every_recording_the_product_reads_reaches_the_recogniser() {
let install = Install::new(true);
install::ensure_installed()
.await
.expect("the copy in place is used");
let media = tempfile::tempdir().expect("media directory");
let sine = ["-f", "lavfi", "-i", "sine=frequency=440:duration=1"];
let cases: [(&str, &[&str]); 9] = [
("note.m4a", &["-c:a", "aac"]),
("note-alac.m4a", &["-c:a", "alac"]),
("note.flac", &["-c:a", "flac"]),
(
"note-vorbis.ogg",
&["-ac", "2", "-c:a", "vorbis", "-strict", "-2"],
),
("note.aac", &["-f", "adts", "-c:a", "aac"]),
("note-alaw.wav", &["-c:a", "pcm_alaw"]),
("note.aiff", &["-f", "aiff", "-c:a", "pcm_s16be"]),
("note.caf", &["-f", "caf", "-c:a", "pcm_s16le"]),
("plain.wav", &["-c:a", "pcm_s16le"]),
];
for (name, codec) in cases {
let path = media.path().join(name);
let mut args = sine.to_vec();
args.extend(codec);
make(install.host(), &path, &args);
let (samples, rate) = crate::speech::decode::samples_of(&path)
.await
.unwrap_or_else(|error| panic!("{name} does not reach the recogniser: {error:#}"));
assert!(!samples.is_empty(), "{name} produced no audio");
assert!(rate > 0, "{name} reported a rate of {rate}");
}
}
fn make(host: &Path, output: &Path, args: &[&str]) {
let mut command = Std::new(host.join("ffmpeg"));
command.args(["-v", "error", "-y"]).args(args).arg(output);
let status = command.status().expect("run the stand-in ffmpeg");
assert!(
status.success(),
"the stand-in ffmpeg failed for {output:?}"
);
}
}