I’m working on a C# project where I need to run FFmpeg commands to process videos. The FFmpeg command works perfectly fine when executed directly in the shell, but it hangs when run from my C# application. I suspect the issue is related to the output pipes getting full.
Here is the FFmpeg command I’m using:
shell
C:pathtoffmpeg.exe -f concat -safe 0 -i "C:pathtolist.txt" -vf "scale=1080x1920,setsar=1" -c:v libx264 -pix_fmt yuv420p -c:a aac -ar 44100 -ac 2 "C:pathtooutput.mp4"
And here is my C# code:
private static async Task _ExecuteFfmpegCommand(string arguments) {
const string EXECUTABLE_NAME = "ffmpeg.exe";
var executableFile = FfmpegPath.File(EXECUTABLE_NAME);
await DownloadSercvice.EnsureFileExist(executableFile, FfmpegURI);
arguments = $"-loglevel quiet {arguments}";
using var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = executableFile.FullName,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
var command = $"{process.StartInfo.FileName} {process.StartInfo.Arguments}";
Console.WriteLine($"This is my process command: {command}");
var outputTask = new TaskCompletionSource<string>();
var errorTask = new TaskCompletionSource<string>();
process.OutputDataReceived += (sender, e) => {
if (e.Data == null)
outputTask.SetResult(null);
else
Console.WriteLine(e.Data);
};
process.ErrorDataReceived += (sender, e) => {
if (e.Data == null)
errorTask.SetResult(null);
else
Console.WriteLine(e.Data);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await process.WaitForExitAsync();
var output = await outputTask.Task;
var error = await errorTask.Task;
if (process.ExitCode != 0 || !string.IsNullOrWhiteSpace(error)) {
throw new InvalidOperationException($"FFMPEG Error(0x{process.ExitCode:X8}): {error}") {
Data = {
{ "Output", output },
{ "Error", error },
{ "ExitCode", process.ExitCode }
}
};
}
}
Issue:
The process hangs and does not complete execution. I suspect the FFmpeg process’s output pipes (stdout and stderr) are getting full, causing the hang. I’ve tried setting the log level to error, but it didn’t resolve the issue.
I got that info from here: ffmpeg hangs when run in background
Solutions Tried:
Set -loglevel error in the FFmpeg command to reduce verbosity.
Set -loglever quiet in the FFmpeg command (to test if that may work)
Handled OutputDataReceived and ErrorDataReceived events to read the output asynchronously.
Questions:
How can I prevent the FFmpeg process from hanging due to full output pipes?
Are there better ways to handle the stdout and stderr of the FFmpeg process in C#?
Any help or suggestions on how to resolve this issue would be greatly appreciated!
Internal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.