use std::ffi::{OsStr, OsString};
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::error::{MediaError, Result};
pub const DEFAULT_FORMATS: &[&str] = &["wav", "mp3", "flac", "ogg", "aac", "mov", "mp4", "m4a", "matroska", "webm", "avi"];
pub const STDERR_KEEP: usize = 2048;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Input {
File(PathBuf),
Bytes(Arc<[u8]>),
}
impl Input {
pub fn file(path: impl Into<PathBuf>) -> Self {
Input::File(path.into())
}
pub fn bytes(bytes: impl Into<Arc<[u8]>>) -> Self {
Input::Bytes(bytes.into())
}
pub fn head(&self, n: usize) -> Result<Vec<u8>> {
match self {
Input::Bytes(b) => Ok(b[..n.min(b.len())].to_vec()),
Input::File(p) => {
let mut out = Vec::with_capacity(n);
std::fs::File::open(p)?.take(n as u64).read_to_end(&mut out)?;
Ok(out)
}
}
}
pub fn len(&self) -> Result<u64> {
match self {
Input::Bytes(b) => Ok(b.len() as u64),
Input::File(p) => Ok(std::fs::metadata(p)?.len()),
}
}
pub fn is_empty(&self) -> Result<bool> {
Ok(self.len()? == 0)
}
pub fn read_all(&self, max: u64) -> Result<Vec<u8>> {
let len = self.len()?;
if len > max {
return Err(MediaError::limit(format!("input is {len} bytes, over the {max}-byte limit")));
}
match self {
Input::Bytes(b) => Ok(b.to_vec()),
Input::File(p) => Ok(std::fs::read(p)?),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tool {
Ffmpeg,
Ffprobe,
}
impl Tool {
pub fn name(self) -> &'static str {
match self {
Tool::Ffmpeg => "ffmpeg",
Tool::Ffprobe => "ffprobe",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
pub tool: Tool,
pub input: Input,
pub before_input: Vec<String>,
pub args: Vec<String>,
pub max_output: Option<u64>,
pub timeout: Option<Duration>,
}
impl Job {
pub fn ffmpeg(input: Input) -> Self {
Job { tool: Tool::Ffmpeg, input, before_input: Vec::new(), args: Vec::new(), max_output: None, timeout: None }
}
pub fn ffprobe(input: Input) -> Self {
Job { tool: Tool::Ffprobe, ..Job::ffmpeg(input) }
}
pub fn before_input<S: Into<String>>(mut self, args: impl IntoIterator<Item = S>) -> Self {
self.before_input.extend(args.into_iter().map(Into::into));
self
}
pub fn args<S: Into<String>>(mut self, args: impl IntoIterator<Item = S>) -> Self {
self.args.extend(args.into_iter().map(Into::into));
self
}
pub fn max_output(mut self, bytes: u64) -> Self {
self.max_output = Some(bytes);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn has_arg(&self, needle: &str) -> bool {
self.before_input.iter().chain(&self.args).any(|a| a == needle)
}
pub fn arg_value(&self, name: &str) -> Option<&str> {
let all: Vec<&String> = self.before_input.iter().chain(&self.args).collect();
all.windows(2).find(|w| w[0] == name).map(|w| w[1].as_str())
}
pub fn validate(&self, limits: &Limits) -> Result<()> {
const OPTIONS_REFUSED: &[&str] = &[
"-i",
"-filter_script",
"-filter_complex_script",
"-/filter",
"-attach",
"-dump_attachment",
"-report",
"-protocol_whitelist",
"-protocol_blacklist",
"-format_whitelist",
"-safe",
"-reconnect",
"-headers",
"-user_agent",
"-stdin",
];
let protocol = |a: &str| {
let lower = a.to_ascii_lowercase();
lower.contains("://")
|| [
"file:", "pipe:", "fd:", "concat:", "concatf:", "subfile:", "data:", "crypto:", "async:", "cache:", "tee:", "http:", "https:",
"ftp:", "tcp:", "udp:", "rtp:", "rtmp", "rtsp:", "srt:", "tls:", "unix:", "gopher:", "sftp:", "smb:", "hls:", "ipfs",
]
.iter()
.any(|p| lower.starts_with(p))
};
let all: Vec<&String> = self.before_input.iter().chain(&self.args).collect();
for (i, a) in all.iter().enumerate() {
if OPTIONS_REFUSED.contains(&a.as_str()) {
return Err(MediaError::refused(format!("option {a} is not allowed in a job")));
}
let last_output = self.tool == Tool::Ffmpeg && i + 1 == all.len() && (a.as_str() == "pipe:1" || a.as_str() == "-");
if !last_output && protocol(a) {
return Err(MediaError::refused("URLs and protocol prefixes are not allowed in a job"));
}
}
let before: Vec<&String> = self.before_input.iter().collect();
for w in before.windows(2) {
if w[0] == "-f" && !limits.formats.iter().any(|f| f == w[1]) {
return Err(MediaError::refused(format!("input format {} is not allowed", w[1])));
}
}
if self.tool == Tool::Ffmpeg {
match self.args.last().map(String::as_str) {
Some("pipe:1") => {}
Some("-") if self.arg_value("-f") == Some("null") => {}
_ => return Err(MediaError::refused("ffmpeg output must be pipe:1 (or - with the null muxer)")),
}
}
if let Input::File(p) = &self.input
&& protocol(&p.to_string_lossy())
{
return Err(MediaError::refused("the input must be a local file path, not a URL"));
}
Ok(())
}
}
pub trait Exec {
fn exec(&self, job: &Job) -> Result<Vec<u8>>;
}
impl<T: Exec + ?Sized> Exec for &T {
fn exec(&self, job: &Job) -> Result<Vec<u8>> {
(**self).exec(job)
}
}
impl<T: Exec + ?Sized> Exec for Arc<T> {
fn exec(&self, job: &Job) -> Result<Vec<u8>> {
(**self).exec(job)
}
}
impl<T: Exec + ?Sized> Exec for Box<T> {
fn exec(&self, job: &Job) -> Result<Vec<u8>> {
(**self).exec(job)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
pub timeout: Duration,
pub address_space: Option<u64>,
pub max_output: u64,
pub max_input_bytes: u64,
pub nice: Option<i32>,
pub isolate_network: bool,
pub threads: Option<u32>,
pub formats: Vec<String>,
}
impl Default for Limits {
fn default() -> Self {
Limits {
timeout: Duration::from_secs(120),
address_space: Some(1 << 30),
max_output: 512 << 20,
max_input_bytes: 2 << 30,
nice: Some(10),
isolate_network: true,
threads: Some(2),
formats: DEFAULT_FORMATS.iter().map(|s| s.to_string()).collect(),
}
}
}
impl Limits {
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn with_address_space(mut self, bytes: Option<u64>) -> Self {
self.address_space = bytes;
self
}
pub fn with_max_output(mut self, bytes: u64) -> Self {
self.max_output = bytes;
self
}
pub fn with_max_input_bytes(mut self, bytes: u64) -> Self {
self.max_input_bytes = bytes;
self
}
pub fn with_nice(mut self, nice: Option<i32>) -> Self {
self.nice = nice;
self
}
pub fn with_isolate_network(mut self, on: bool) -> Self {
self.isolate_network = on;
self
}
pub fn with_threads(mut self, threads: Option<u32>) -> Self {
self.threads = threads;
self
}
pub fn with_formats<S: Into<String>>(mut self, formats: impl IntoIterator<Item = S>) -> Self {
self.formats = formats.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binaries {
pub ffmpeg: PathBuf,
pub ffprobe: PathBuf,
}
fn exe(name: &str) -> String {
if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }
}
impl Binaries {
pub fn new(ffmpeg: impl Into<PathBuf>, ffprobe: impl Into<PathBuf>) -> Self {
Binaries { ffmpeg: ffmpeg.into(), ffprobe: ffprobe.into() }
}
pub fn locate(env: Option<&str>) -> Option<Binaries> {
Self::locate_from(
env.and_then(std::env::var_os).map(PathBuf::from),
std::env::current_exe().ok().as_deref(),
std::env::var_os("PATH").as_deref(),
)
}
pub fn locate_from(ffmpeg: Option<PathBuf>, current_exe: Option<&Path>, path: Option<&OsStr>) -> Option<Binaries> {
let pair = |dir: &Path| {
let (f, p) = (dir.join(exe("ffmpeg")), dir.join(exe("ffprobe")));
(f.is_file() && p.is_file()).then_some(Binaries { ffmpeg: f, ffprobe: p })
};
if let Some(f) = ffmpeg.filter(|p| p.is_file()) {
let probe = f.parent().map(|d| d.join(exe("ffprobe"))).filter(|p| p.is_file())?;
return Some(Binaries { ffmpeg: f, ffprobe: probe });
}
if let Some(dir) = current_exe.and_then(Path::parent)
&& let Some(found) = pair(dir).or_else(|| pair(&dir.join("..").join("Helpers")))
{
return Some(found);
}
std::env::split_paths(path?).find_map(|d| pair(&d))
}
}
#[derive(Debug, Clone)]
pub struct Runner {
bin: Binaries,
limits: Limits,
}
impl Runner {
pub fn new(bin: Binaries) -> Self {
Runner { bin, limits: Limits::default() }
}
pub fn locate(env: Option<&str>) -> Result<Self> {
Binaries::locate(env).map(Runner::new).ok_or_else(|| {
MediaError::Unavailable(match env {
Some(var) => format!("ffmpeg and ffprobe were not found; install them, or set {var} to an ffmpeg binary with ffprobe beside it"),
None => "ffmpeg and ffprobe were not found; install them".to_string(),
})
})
}
pub fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn limits(&self) -> &Limits {
&self.limits
}
pub fn binaries(&self) -> &Binaries {
&self.bin
}
pub fn command_line(&self, job: &Job) -> Result<(PathBuf, Vec<OsString>)> {
job.validate(&self.limits)?;
let input: OsString = match &job.input {
Input::Bytes(b) => {
if b.len() as u64 > self.limits.max_input_bytes {
return Err(MediaError::limit(format!("input is {} bytes, over the {}-byte limit", b.len(), self.limits.max_input_bytes)));
}
"pipe:0".into()
}
Input::File(p) => {
let meta = std::fs::metadata(p)?;
if !meta.is_file() {
return Err(MediaError::refused("the input is not a regular file"));
}
if meta.len() > self.limits.max_input_bytes {
return Err(MediaError::limit(format!("input is {} bytes, over the {}-byte limit", meta.len(), self.limits.max_input_bytes)));
}
let canon = plain_path(std::fs::canonicalize(p)?);
let mut s = OsString::from("file:");
s.push(canon.as_os_str());
s
}
};
let formats = self.limits.formats.join(",");
let mut args: Vec<OsString> = Vec::new();
let mut push = |a: &str| args.push(a.into());
match job.tool {
Tool::Ffmpeg => {
for a in ["-nostdin", "-hide_banner", "-loglevel", "error"] {
push(a);
}
}
Tool::Ffprobe => {
for a in ["-hide_banner", "-loglevel", "error"] {
push(a);
}
}
}
for a in ["-protocol_whitelist", "file,pipe", "-format_whitelist", &formats] {
push(a);
}
if job.tool == Tool::Ffmpeg
&& let Some(t) = self.limits.threads
{
push("-threads");
push(&t.to_string());
}
for a in &job.before_input {
push(a);
}
match job.tool {
Tool::Ffmpeg => {
args.push("-i".into());
args.push(input);
args.extend(job.args.iter().map(OsString::from));
}
Tool::Ffprobe => {
args.extend(job.args.iter().map(OsString::from));
args.push(input);
}
}
let program = match job.tool {
Tool::Ffmpeg => self.bin.ffmpeg.clone(),
Tool::Ffprobe => self.bin.ffprobe.clone(),
};
Ok((program, args))
}
}
fn plain_path(p: PathBuf) -> PathBuf {
if cfg!(windows) {
let s = p.to_string_lossy();
if let Some(rest) = s.strip_prefix(r"\\?\")
&& rest.as_bytes().get(1) == Some(&b':')
{
return PathBuf::from(rest.to_string());
}
}
p
}
fn truncate(text: &str, max: usize) -> String {
if text.len() <= max {
return text.trim().to_string();
}
let mut end = max;
while !text.is_char_boundary(end) {
end -= 1;
}
format!("{}…", text[..end].trim())
}
impl Exec for Runner {
fn exec(&self, job: &Job) -> Result<Vec<u8>> {
let (program, args) = self.command_line(job)?;
let tool = job.tool.name();
let cap = job.max_output.unwrap_or(self.limits.max_output).min(self.limits.max_output);
let timeout = job.timeout.unwrap_or(self.limits.timeout).min(self.limits.timeout);
let mut cmd = Command::new(&program);
cmd.args(&args);
cmd.env("MALLOC_ARENA_MAX", "2");
cmd.stdin(if matches!(job.input, Input::Bytes(_)) { Stdio::piped() } else { Stdio::null() });
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt as _;
let nice = self.limits.nice;
let space = self.limits.address_space;
let isolate = self.limits.isolate_network;
unsafe {
cmd.pre_exec(move || {
if let Some(n) = nice {
libc::nice(n);
}
if let Some(bytes) = space {
let r = libc::rlimit { rlim_cur: bytes as libc::rlim_t, rlim_max: bytes as libc::rlim_t };
libc::setrlimit(libc::RLIMIT_AS, &r);
}
#[cfg(target_os = "linux")]
if isolate {
libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNET);
}
#[cfg(not(target_os = "linux"))]
let _ = isolate;
Ok(())
});
}
}
let mut child = cmd.spawn().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
MediaError::Unavailable(format!("{tool} is not installed where it was expected"))
} else {
MediaError::Unavailable(format!("couldn't start {tool}: {e}"))
}
})?;
let writer = match (&job.input, child.stdin.take()) {
(Input::Bytes(bytes), Some(mut stdin)) => {
let bytes = Arc::clone(bytes);
Some(std::thread::spawn(move || {
let _ = stdin.write_all(&bytes);
}))
}
_ => None,
};
let mut out = child.stdout.take().ok_or_else(|| MediaError::Unavailable(format!("{tool} gave no output pipe")))?;
let mut err = child.stderr.take().ok_or_else(|| MediaError::Unavailable(format!("{tool} gave no error pipe")))?;
let over = Arc::new(AtomicBool::new(false));
let over_r = Arc::clone(&over);
let reader = std::thread::spawn(move || {
let mut buf = Vec::new();
let mut chunk = [0u8; 64 * 1024];
loop {
match out.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => {
if buf.len() as u64 + n as u64 > cap {
over_r.store(true, Ordering::SeqCst);
break;
}
buf.extend_from_slice(&chunk[..n]);
}
}
}
buf
});
let err_reader = std::thread::spawn(move || {
let mut b = Vec::new();
let _ = (&mut err).take(64 * 1024).read_to_end(&mut b);
let _ = std::io::copy(&mut err, &mut std::io::sink());
b
});
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(s)) => break s,
Ok(None) if over.load(Ordering::SeqCst) => {
let _ = child.kill();
let _ = child.wait();
let _ = reader.join();
let _ = err_reader.join();
return Err(MediaError::limit(format!("{tool} output passed the {cap}-byte bound and was stopped")));
}
Ok(None) if Instant::now() >= deadline => {
let _ = child.kill();
let _ = child.wait();
let _ = reader.join();
let _ = err_reader.join();
return Err(MediaError::Timeout { seconds: timeout.as_secs() });
}
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
Err(e) => return Err(MediaError::Unavailable(format!("{tool}: {e}"))),
}
};
if let Some(w) = writer {
let _ = w.join();
}
let stdout = reader.join().unwrap_or_default();
let stderr = err_reader.join().unwrap_or_default();
if over.load(Ordering::SeqCst) {
return Err(MediaError::limit(format!("{tool} output passed the {cap}-byte bound and was stopped")));
}
if !status.success() {
return Err(MediaError::Failed { tool, status: status.to_string(), stderr: truncate(&String::from_utf8_lossy(&stderr), STDERR_KEEP) });
}
Ok(stdout)
}
}
#[derive(Debug)]
pub struct PrivateDir {
path: PathBuf,
}
impl PrivateDir {
pub fn new() -> Result<Self> {
Self::new_in(&std::env::temp_dir())
}
pub fn new_in(parent: &Path) -> Result<Self> {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
for _ in 0..16 {
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = parent.join(format!("weirdnet-media-{}-{nanos:x}-{n}", std::process::id()));
#[cfg(unix)]
let builder = {
use std::os::unix::fs::DirBuilderExt as _;
let mut b = std::fs::DirBuilder::new();
b.mode(0o700);
b
};
#[cfg(not(unix))]
let builder = std::fs::DirBuilder::new();
match builder.create(&path) {
Ok(()) => return Ok(PrivateDir { path }),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e.into()),
}
}
Err(MediaError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "couldn't create a private temp dir")))
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn write(&self, name: &str, bytes: &[u8]) -> Result<PathBuf> {
if name.is_empty() || name.contains(['/', '\\']) || name == "." || name == ".." {
return Err(MediaError::refused("a private file name must be a plain name"));
}
let path = self.path.join(name);
std::fs::write(&path, bytes)?;
Ok(path)
}
}
impl Drop for PrivateDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
type Matcher = Box<dyn Fn(&Job) -> bool + Send + Sync>;
type Responder = Box<dyn Fn(&Job) -> Result<Vec<u8>> + Send + Sync>;
#[derive(Debug, Clone, PartialEq)]
pub struct FakeMedia {
pub format: String,
pub duration_ms: u64,
pub video: Option<(u32, u32, f32)>,
pub audio: bool,
pub scenes: Vec<(u64, f32)>,
pub keyframes: Vec<u64>,
}
impl FakeMedia {
pub fn video(duration_ms: u64, audio: bool) -> Self {
FakeMedia {
format: "mov,mp4,m4a,3gp,3g2,mj2".into(),
duration_ms,
video: Some((1920, 1080, 30.0)),
audio,
scenes: Vec::new(),
keyframes: (0..duration_ms).step_by(2000).collect(),
}
}
pub fn audio(format: &str, duration_ms: u64) -> Self {
FakeMedia { format: format.into(), duration_ms, video: None, audio: true, scenes: Vec::new(), keyframes: Vec::new() }
}
pub fn with_scenes(mut self, scenes: Vec<(u64, f32)>) -> Self {
self.scenes = scenes;
self
}
pub fn ffprobe_json(&self) -> String {
let mut streams = Vec::new();
if let Some((w, h, fps)) = self.video {
streams.push(serde_json::json!({
"codec_type": "video", "codec_name": "h264", "width": w, "height": h,
"avg_frame_rate": format!("{}/1000", (fps * 1000.0).round() as u64),
"disposition": {"attached_pic": 0}
}));
}
if self.audio {
streams.push(serde_json::json!({"codec_type": "audio", "codec_name": "aac", "sample_rate": "48000", "channels": 2}));
}
serde_json::json!({
"format": {"format_name": self.format, "duration": format!("{:.3}", self.duration_ms as f64 / 1000.0)},
"streams": streams
})
.to_string()
}
fn respond(&self, job: &Job) -> Result<Vec<u8>> {
let secs = |v: Option<&str>| v.and_then(|s| s.parse::<f64>().ok()).map(|s| (s * 1000.0).round() as u64);
match job.tool {
Tool::Ffprobe if job.has_arg("-show_entries") => {
let mut out = String::new();
for k in &self.keyframes {
out.push_str(&format!("{:.6},K__\n", *k as f64 / 1000.0));
}
Ok(out.into_bytes())
}
Tool::Ffprobe => Ok(self.ffprobe_json().into_bytes()),
Tool::Ffmpeg => {
let start = secs(job.arg_value("-ss")).unwrap_or(0);
let fmt = job.args.windows(2).rev().find(|w| w[0] == "-f").map(|w| w[1].as_str()).unwrap_or("");
match fmt {
"image2pipe" => {
if self.video.is_none() {
return Err(MediaError::Failed { tool: "ffmpeg", status: "exit status: 1".into(), stderr: "no video stream".into() });
}
let scale = job.arg_value("-vf").unwrap_or("");
let mut b = vec![0xFF, 0xD8, 0xFF];
b.extend(format!("{start}@{scale}").into_bytes());
Ok(b)
}
"wav" => {
if !self.audio {
return Err(MediaError::Failed { tool: "ffmpeg", status: "exit status: 1".into(), stderr: "no audio stream".into() });
}
let rate: u32 = job.arg_value("-ar").and_then(|r| r.parse().ok()).unwrap_or(16_000);
let channels: u16 = job.arg_value("-ac").and_then(|r| r.parse().ok()).unwrap_or(1);
let len =
secs(job.arg_value("-t")).unwrap_or(self.duration_ms.saturating_sub(start)).min(self.duration_ms.saturating_sub(start));
let frames = (u64::from(rate) * len / 1000) as usize;
let pcm = crate::pcm::Pcm::new(rate, channels, vec![0; frames * channels as usize]);
Ok(crate::pcm::encode_wav(&pcm))
}
"null" => {
let mut out = String::new();
let threshold = job
.arg_value("-vf")
.and_then(|vf| vf.split("gt(scene,").nth(1))
.and_then(|r| r.split(')').next())
.and_then(|t| t.parse::<f32>().ok())
.unwrap_or(0.0);
for (i, (t, s)) in self.scenes.iter().enumerate().filter(|(_, (_, s))| *s > threshold) {
out.push_str(&format!("frame:{i} pts:{t} pts_time:{:.3}\nlavfi.scene_score={s:.6}\n", *t as f64 / 1000.0));
}
Ok(out.into_bytes())
}
other => {
let len = secs(job.arg_value("-t")).unwrap_or(0);
let input = job.input.len().unwrap_or(0);
Ok(format!("FAKE {other} ss={start} t={len} in={input}").into_bytes())
}
}
}
}
}
}
pub struct FakeRunner {
rules: Vec<(Matcher, Responder)>,
media: Option<FakeMedia>,
limits: Limits,
calls: Mutex<Vec<Job>>,
}
impl std::fmt::Debug for FakeRunner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FakeRunner").field("rules", &self.rules.len()).field("media", &self.media).finish()
}
}
impl Default for FakeRunner {
fn default() -> Self {
Self::new()
}
}
impl FakeRunner {
pub fn new() -> Self {
FakeRunner { rules: Vec::new(), media: None, limits: Limits::default(), calls: Mutex::new(Vec::new()) }
}
pub fn with_media(media: FakeMedia) -> Self {
FakeRunner { media: Some(media), ..Self::new() }
}
pub fn on(
mut self,
matches: impl Fn(&Job) -> bool + Send + Sync + 'static,
respond: impl Fn(&Job) -> Result<Vec<u8>> + Send + Sync + 'static,
) -> Self {
self.rules.push((Box::new(matches), Box::new(respond)));
self
}
pub fn on_ffprobe(self, output: impl Into<Vec<u8>>) -> Self {
let output = output.into();
self.on(|j| j.tool == Tool::Ffprobe, move |_| Ok(output.clone()))
}
pub fn on_arg(self, arg: &str, output: impl Into<Vec<u8>>) -> Self {
let (arg, output) = (arg.to_string(), output.into());
self.on(move |j| j.tool == Tool::Ffmpeg && j.has_arg(&arg), move |_| Ok(output.clone()))
}
pub fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn calls(&self) -> Vec<Job> {
self.calls.lock().map(|c| c.clone()).unwrap_or_default()
}
}
impl Exec for FakeRunner {
fn exec(&self, job: &Job) -> Result<Vec<u8>> {
job.validate(&self.limits)?;
if let Ok(mut c) = self.calls.lock() {
c.push(job.clone());
}
if let Some((_, respond)) = self.rules.iter().find(|(m, _)| m(job)) {
return respond(job);
}
match &self.media {
Some(media) => media.respond(job),
None => Err(MediaError::Unavailable(format!("FakeRunner has no rule for this {} job", job.tool.name()))),
}
}
}