Using php to read an rtsp stream from an ffmpeg command utilizing image2pipe, I’m finding the images are truncated in some manner and only display a partial image. My task is to write unique jpg filenames at 30fps. Below is the php code. I’ve simplified the filename structure in this example for clarity. The script performs as expected with no obvious errors writing out 30fps consistently. I can’t figure out what extraneous or missing information in the content is causing the output images to appear corrupt.
$cmd = "ffmpeg -rtsp_transport tcp -framerate 30 -i rtsp://".$camera_url." -f image2pipe pipe:1";
$fp = popen($cmd, 'r');
if (!$fp)
{
die('Could not open ffmpeg process');
}
define('JPEG_START', "xFFxD8");
define('JPEG_END', "xFFxD9");
$buffer = '';
$jpeg = '';
$isReadingJpeg = false;
stream_set_blocking($fp, false); // Set non-blocking mode
while (!feof($fp))
{
$chunk = fread($fp, 4096);
if ($chunk === false)
{
usleep(100);
continue;
}
$buffer .= $chunk;
if (!$isReadingJpeg && ($startPos = strpos($buffer, JPEG_START)) !== false)
{
$isReadingJpeg = true;
$jpeg = substr($buffer, $startPos);
$buffer = substr($buffer, $startPos + 2); // Move past the start marker
}
if ($isReadingJpeg && ($endPos = strpos($buffer, JPEG_END)) !== false)
{
$jpeg .= substr($buffer, 0, $endPos + 2);
$buffer = substr($buffer, $endPos + 2); // Move past the end marker
file_put_contents(microtime(true),$jpeg);
$isReadingJpeg = false;
$jpeg = '';
}
if ($isReadingJpeg)
{
$jpeg .= $buffer;
$buffer = '';
}
}
pclose($fp);
seandoucette is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.