use std::io::{self, Read};
use std::process::{Child, ChildStdout, Command, Stdio};
use std::time::Duration;
use crate::{Error, FrameSource, FrameView, PixelFormat, Result};
pub struct FfmpegSource {
child: Child,
stdout: ChildStdout,
buffer: Vec<u8>,
width: usize,
height: usize,
frame_duration: Duration,
}
impl FfmpegSource {
pub fn new<I, S>(input: I, width: usize, height: usize, fps: u32) -> Result<Self>
where
I: IntoIterator<Item = S>,
S: AsRef<std::ffi::OsStr>,
{
if width == 0 || height == 0 || fps == 0 {
return Err(Error::InvalidTargetSize);
}
let frame_size = width
.checked_mul(height)
.and_then(|size| size.checked_mul(3))
.ok_or(Error::DimensionOverflow)?;
let mut command = Command::new("ffmpeg");
command
.arg("-i")
.args(input)
.args(["-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
let mut child = command.spawn().map_err(|error| Error::Io {
kind: error.kind(),
message: format!("failed to start ffmpeg: {error}"),
})?;
let stdout = child
.stdout
.take()
.ok_or_else(|| Error::Unsupported("ffmpeg stdout pipe was not created".to_string()))?;
Ok(Self {
child,
stdout,
buffer: vec![0; frame_size],
width,
height,
frame_duration: Duration::from_nanos(1_000_000_000 / u64::from(fps)),
})
}
pub fn finish(mut self) -> Result<()> {
let status = self.child.wait()?;
if status.success() {
Ok(())
} else {
Err(Error::Unsupported(format!(
"ffmpeg exited with status {status}"
)))
}
}
}
impl FrameSource for FfmpegSource {
fn next_frame(&mut self) -> Result<Option<(FrameView<'_>, Duration)>> {
match self.stdout.read_exact(&mut self.buffer) {
Ok(()) => {
let view = FrameView::new(
&self.buffer,
self.width,
self.height,
self.width * 3,
PixelFormat::Rgb8,
)?;
Ok(Some((view, self.frame_duration)))
}
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => {
let _ = self.child.wait();
Ok(None)
}
Err(error) => Err(error.into()),
}
}
}
impl Drop for FfmpegSource {
fn drop(&mut self) {
let _ = self.child.kill();
}
}