use std::collections::VecDeque;
use std::fs::File;
use std::future::{Future, ready};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use latkit::host::{Host, Job, Native};
use latkit::{Encoding, Error, Image, ImageFormat, Mp4, Pending, Pixels, Sink};
use crate::Failure;
use crate::args::{is_stdio, pattern};
const ENCODING: usize = 4;
fn written(error: &io::Error, path: &Path) -> Error {
Error::Io(format!("{}: {error}", path.display()).into())
}
pub(crate) enum Output {
Stdout(BufWriter<io::Stdout>),
File { path: PathBuf, file: BufWriter<File>, temporary: tempfile::TempPath },
}
impl Output {
pub(crate) fn create(path: &Path) -> Result<Output, Failure> {
if is_stdio(path) {
return Ok(Output::Stdout(BufWriter::new(io::stdout())));
}
let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
let suffix = path.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
let temporary =
tempfile::Builder::new().suffix(&suffix).tempfile_in(parent).map_err(|e| Failure::io(&e, path))?;
let (file, temporary) = temporary.into_parts();
Ok(Output::File { path: path.to_path_buf(), file: BufWriter::new(file), temporary })
}
pub(crate) fn commit(self) -> Result<(), Failure> {
match self {
Output::Stdout(mut out) => out.flush().map_err(|e| Failure::io(&e, Path::new("-"))),
Output::File { path, file, temporary } => {
drop(file.into_inner().map_err(|e| Failure::io(e.error(), &path))?);
temporary.persist(&path).map_err(|e| Failure::io(&e.error, &path))
}
}
}
fn path(&self) -> &Path {
match self {
Output::Stdout(_) => Path::new("-"),
Output::File { path, .. } => path,
}
}
fn put(&mut self, bytes: &[u8]) -> latkit::Result<()> {
self.write_all(bytes).map_err(|e| written(&e, self.path()))
}
}
impl Write for Output {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match self {
Output::Stdout(out) => out.write(bytes),
Output::File { file, .. } => file.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match self {
Output::Stdout(out) => out.flush(),
Output::File { file, .. } => file.flush(),
}
}
}
pub(crate) trait Commit {
fn commit(self) -> Result<(), Failure>;
}
impl Commit for Mp4<Output> {
fn commit(self) -> Result<(), Failure> {
self.into_inner().commit()
}
}
pub(crate) struct Images {
to: To,
format: ImageFormat,
host: Native,
size: [u32; 2],
writing: VecDeque<(u64, Option<Pending<Vec<u8>>>)>,
last: Vec<u8>,
}
enum To {
Numbered(PathBuf),
One(Output),
}
impl Images {
pub(crate) fn numbered(pattern: PathBuf, format: ImageFormat, host: Native) -> Images {
Images::new(To::Numbered(pattern), format, host)
}
pub(crate) fn one(out: Output, format: ImageFormat, host: Native) -> Images {
Images::new(To::One(out), format, host)
}
fn new(to: To, format: ImageFormat, host: Native) -> Images {
Images { to, format, host, size: [0, 0], writing: VecDeque::new(), last: Vec::new() }
}
fn path(names: &Path, index: u64) -> PathBuf {
let text = names.to_string_lossy();
let (range, width) = pattern(names).expect("a pattern");
format!("{}{index:0width$}{}", &text[..range.start], &text[range.end..]).into()
}
async fn write_oldest(&mut self) -> latkit::Result<()> {
let Some((index, file)) = self.writing.pop_front() else { return Ok(()) };
if let Some(file) = file {
self.last = file.await?;
if self.last.is_empty() {
return Err(Error::invalid(format!("the picture could not be written as {}", self.format)));
}
}
match &mut self.to {
To::Numbered(names) => {
let path = Images::path(names, index);
let mut out = Output::create(&path).map_err(|f| f.error)?;
out.put(&self.last)?;
out.commit().map_err(|f| f.error)
}
To::One(out) => out.put(&self.last),
}
}
}
impl Sink for Images {
const PIXELS: Pixels = Pixels::Rgba;
fn begin(&mut self, encoding: &Encoding, _: Option<&dyn Host>) -> latkit::Result<()> {
self.size = encoding.size;
Ok(())
}
async fn frame(&mut self, index: u64, pixels: Option<Vec<u8>>) -> latkit::Result<()> {
if index > 0 && matches!(self.to, To::One(_)) {
return Err(Error::invalid("an image file is one frame; a %d pattern in the output writes one a frame"));
}
let file = match pixels {
Some(rgba) => Some(self.host.spawn(Job::encode(&Image::new(self.size, rgba)?, self.format))),
None => None,
};
self.writing.push_back((index, file));
while self.writing.len() > ENCODING {
self.write_oldest().await?;
}
Ok(())
}
async fn finish(&mut self, end: u64) -> latkit::Result<()> {
if end == 0 {
return Err(Error::invalid("the frames are empty"));
}
while !self.writing.is_empty() {
self.write_oldest().await?;
}
Ok(())
}
}
impl Commit for Images {
fn commit(self) -> Result<(), Failure> {
match self.to {
To::Numbered(_) => Ok(()),
To::One(out) => out.commit(),
}
}
}
pub(crate) struct Raw {
out: Output,
last: Vec<u8>,
}
impl Raw {
pub(crate) fn new(out: Output) -> Raw {
Raw { out, last: Vec::new() }
}
}
impl Sink for Raw {
const PIXELS: Pixels = Pixels::Rgba;
fn frame(&mut self, _: u64, pixels: Option<Vec<u8>>) -> impl Future<Output = latkit::Result<()>> {
if let Some(rgba) = pixels {
self.last = rgba;
}
ready(self.out.put(&self.last))
}
fn finish(&mut self, _: u64) -> impl Future<Output = latkit::Result<()>> {
ready(self.out.flush().map_err(|e| written(&e, self.out.path())))
}
}
impl Commit for Raw {
fn commit(self) -> Result<(), Failure> {
self.out.commit()
}
}
pub(crate) struct Y4m {
out: Output,
size: [u32; 2],
last: Vec<u8>,
}
impl Y4m {
pub(crate) fn new(out: Output) -> Y4m {
Y4m { out, size: [0, 0], last: Vec::new() }
}
}
impl Sink for Y4m {
const PIXELS: Pixels = Pixels::Nv12;
fn begin(&mut self, encoding: &Encoding, _: Option<&dyn Host>) -> latkit::Result<()> {
self.size = encoding.size;
let ([width, height], [num, den]) = (encoding.size, encoding.rate());
let header = format!("YUV4MPEG2 W{width} H{height} F{num}:{den} Ip A1:1 C420jpeg XCOLORRANGE=LIMITED\n");
self.out.put(header.as_bytes())
}
fn frame(&mut self, _: u64, pixels: Option<Vec<u8>>) -> impl Future<Output = latkit::Result<()>> {
if let Some(nv12) = pixels {
let luma = (self.size[0] * self.size[1]) as usize;
self.last.clear();
self.last.extend_from_slice(b"FRAME\n");
self.last.extend_from_slice(&nv12[..luma]);
let chroma = &nv12[luma..];
self.last.extend(chroma.iter().step_by(2));
self.last.extend(chroma.iter().skip(1).step_by(2));
}
ready(self.out.put(&self.last))
}
fn finish(&mut self, _: u64) -> impl Future<Output = latkit::Result<()>> {
ready(self.out.flush().map_err(|e| written(&e, self.out.path())))
}
}
impl Commit for Y4m {
fn commit(self) -> Result<(), Failure> {
self.out.commit()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn patterns_number_files() {
assert_eq!(Images::path(Path::new("out/frame-%04d.png"), 7), PathBuf::from("out/frame-0007.png"));
assert_eq!(Images::path(Path::new("%d.jpg"), 12), PathBuf::from("12.jpg"));
}
}