I'm trying to call FFmpeg using proc_open and then I try to read the output of STDOUT but output is only ever sent to STDERR even when there is no error.
My code seems to be correct because when I use proc_open to call "ls -la" it sends the output to STDOUT. But I'm completely new to working with streams so I'm probably missing something.
I'd like to know if anyone knows what is happening or if I'm doing something wrong?
Here are three commands for test purposes:
$cmd = ['ls', '-la']; // sends to STDOUT
$cmd = ['ffmpeg', '-h']; // sends part of output to STDERR and some of it to STDOUT
$cmd = ['ffmpeg', '-i','in.mp4','-c:v','copy','out.mp4']; // sends all to STDERR
And here is my code:
// $cmd = ['ls', '-la'];
$cmd = ['ffmpeg', '-h'];
$descriptor_spec = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$proc = proc_open($cmd, $descriptor_spec, $pipes, dirname(__FILE__), null);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
echo PHP_EOL . "STDOUT: {$stdout}" . PHP_EOL;
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
echo PHP_EOL . "STDERR: {$stderr}" . PHP_EOL;
$exitCode = proc_close($proc);
var_dump($exitCode);
My Answer:
The reason why you are seeing the output from FFmpeg being sent to STDERR instead of STDOUT is because FFmpeg sends its output to STDERR by default. This is a common behavior for command-line tools like FFmpeg.
If you want to capture the output from FFmpeg, you can redirect STDERR to STDOUT by adding "2>&1" to your command. Here's how you can modify your code to capture the output from FFmpeg:
php
$cmd = ['ffmpeg', '-h', '2>&1'];
$descriptor_spec = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$proc = proc_open($cmd, $descriptor_spec, $pipes, dirname(__FILE__), null);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
echo PHP_EOL . "STDOUT: {$stdout}" . PHP_EOL;
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
echo PHP_EOL . "STDERR: {$stderr}" . PHP_EOL;
$exitCode = proc_close($proc);
var_dump($exitCode);
By adding '2>&1' to the command, you are telling FFmpeg to redirect its STDERR output to STDOUT, which allows you to capture all the output in the STDOUT stream.
This should now capture all the output from FFmpeg in the STDOUT stream instead of STDERR.
Rate this post
3 of 5 based on 9874 votesComments