Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: consume stderr on wait #71

Merged
merged 4 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/child.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
//! Wrapper around `std::process::Child` containing a spawned FFmpeg command.

use crate::iter::FfmpegIterator;
use anyhow::Context;
use std::{
io::{self, Write},
io::{self, copy, sink, Write},
process::{Child, ChildStderr, ChildStdin, ChildStdout, ExitStatus},
};

use anyhow::Context;

use crate::iter::FfmpegIterator;

/// A wrapper around [`std::process::Child`] containing a spawned FFmpeg command.
/// Provides interfaces for reading parsed metadata, progress updates, warnings and errors, and
/// piped output frames if applicable.
Expand Down Expand Up @@ -100,6 +98,12 @@ impl FfmpegChild {
///
/// Identical to `wait` in [`std::process::Child`].
pub fn wait(&mut self) -> io::Result<ExitStatus> {
// If stderr hasn't already been consumed by a method like `iter()`,
// we need to run it to completion to avoid a deadlock.
if let Some(mut stderr) = self.take_stderr() {
copy(&mut stderr, &mut sink())?;
};

self.inner.wait()
}

Expand Down
56 changes: 56 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,35 @@ fn spawn_with_timeout(command: &mut FfmpegCommand, timeout: u64) -> anyhow::Resu
}
}

/// Returns `Err` if the timeout thread finishes before the FFmpeg process
/// Note: this variant leaves behind a hung FFmpeg child process + thread until
/// the test suite exits.
fn wait_with_timeout(command: &mut FfmpegCommand, timeout: u64) -> anyhow::Result<()> {
let (sender, receiver) = mpsc::channel();

// Thread 1: Waits for 1000ms and sends a message
let timeout_sender = sender.clone();
thread::spawn(move || {
thread::sleep(Duration::from_millis(timeout));
timeout_sender.send("timeout").ok();
});

// Thread 2: Wait for the child to exit in another thread
let mut ffmpeg_child = command.spawn()?;
thread::spawn(move || {
ffmpeg_child.wait().unwrap();
sender.send("ffmpeg").ok();
});

// Race the two threads
let finished_first = receiver.recv()?;
match finished_first {
"timeout" => anyhow::bail!("Timeout thread expired before FFmpeg"),
"ffmpeg" => Ok(()),
_ => anyhow::bail!("Unknown message received"),
}
}

#[test]
fn test_installed() {
assert!(ffmpeg_is_installed());
Expand Down Expand Up @@ -715,3 +744,30 @@ fn test_no_empty_events() -> anyhow::Result<()> {

Ok(())
}

/// This command generates an warning on every frame, e.g.:
///
/// ```txt
/// [Parsed_palettegen_4 @ 0x600001574bb0] [warning] The input frame is not in sRGB, colors may be off
///```
///
/// When used in combination with `.wait()`, these error messages can completely
/// fill the stderr buffer and cause a deadlock. The solution is to
/// automatically drop the stderr channel when `.wait()` is called.
///
/// <https://github.com/nathanbabcock/ffmpeg-sidecar/issues/70>
#[test]
fn test_wait() -> anyhow::Result<()> {
let mut command = FfmpegCommand::new();
command
.args("-color_primaries 1".split(' '))
.args("-color_trc 1".split(' '))
.args("-colorspace 1".split(' '))
.format("lavfi")
.input("yuvtestsrc=size=64x64:rate=60:duration=60")
.args("-vf palettegen=max_colors=164".split(' '))
.codec_video("gif")
.format("null")
.output("-");
wait_with_timeout(&mut command, 5000)
}
Loading