Ola
Ola

Reputation: 41

Recording live stream from IP camera (MJPEG Compression)

I have a live stream from a Tenvis IP camera through http live streaming and its in mjpeg compression.

I am trying to save it to a file, and I have tried using php to do this. my code looks like this:

<?php
$input = fopen("http://xxx.xxx.xxx.xxx:81/videostream.cgi?user=user&pwd=admin&resolution=8");
$output = fopen("video.mpg", "c+");
$end = time() + 60;
do {
    fwrite($output, (fread($input, 30000)), 30000);
} while (time() <= $end);
fclose($output);
fclose($input);
echo "<h1>Recording</h1>";
?>

The code I have creates the file but doesn't write anything to it. Any suggestions will be appreciated

Upvotes: 4

Views: 6274

Answers (2)

Michael M
Michael M

Reputation: 8733

Most of the time, when a camera supports mjpeg, it also supports rtsp and as such you might want to pursue that as a solution for what you are trying to accomplish. With that, its fairly simple to record using an app like VLC.

Upvotes: 0

dopeh
dopeh

Reputation: 46

According to the Wikipedia page about MJPEG (http://en.wikipedia.org/wiki/Motion_JPEG#M-JPEG_over_HTTP), the MJPEG stream over HTTP is basically a sequence of JPEG frames, accompanied by a special mime-type. In order to capture these and save them to a video file, I am not sure you can simply write the incoming data to an .mpg file and have a working video.

To be honest, I am not quite sure why your script does not write anything at all, but I came across the following page, which, although it is written for specific software, provides examples on how to capture an MJPEG stream and pass it on to a browser: http://www.lavrsen.dk/foswiki/bin/view/Motion/MjpegFrameGrabPHP

You could try one of their examples, and instead of passing it to the browser, save it to a file. You can see they read one image at a time:

while (substr_count($r,"Content-Length") != 2) $r.=fread($input,512);
$start = strpos($r,'ÿ');
$end   = strpos($r,$boundary,$start)-1;
$frame = substr("$r",$start,$end - $start);

If this does fix the stream capturing part but not saving it as a video, another option would be to save all frames individually as a JPEG file, then later stitch them together using a tool such as ffmpeg to create a video: Image sequence to video quality

Update If you decide to take the ffmpeg road, it is also possible to capture the stream using ffmpeg only. See this question for an example.

Hope this helps.

Upvotes: 1

Related Questions