Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Live video streaming from recording files over HTTP based on PHP

I want to organize live streaming from recording files over HTTP based on PHP.

INTRODUCTION: On the streaming server I writing video to local file(local_file.mpg) and when received a request from client then start streaming to it from
$start_byte = filesize("local_file.mpg")-10MB; The local_file.mpg is still writing and PHP script continue reading it and flushing.

PROBLEM: I streaming it via HTTP Range with the following headers:

header('HTTP/1.1 206 Partial Content');
header("Content-Type: video/mpeg");
header('Content-Length: '.($seek_end - $seek_start));
header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);

And flushing as follows:

while(!feof($fp)){
    $buf_size = 1024*8;
    $pos = ftell($fp);
    if ($pos >= $item["to_byte"]){
            fclose($fp);
            break;
    }

    if ($pos + $buf_size > $item["to_byte"]){
        $buf_size = $item["to_byte"] - $pos;
    }

    if ($buf_size > 0){
        echo fread($fp, $buf_size);
    }

    flush();
    ob_flush();
}

I open it via VLC or FFplay, but it played until the time moment when the stream was requested. This is to be expected, because we determine the size of the file and provide it to requested side. But if we artificially increase a file size, for example
$size = filesize("local_file.mpg")+999999999999; it also not help, because video players requesting new data too early when it is not recorded. And also stopped play at the time moment when the stream was requested.

1. Please advice how to correct organize live streaming from recording files over HTTP based on PHP.
2. Is it possible to do it with HTTP RANGE mechanism or I should use another way?


UPDATE: Based on this question I tried the next code:

<?php

$file = "online.mpg";

function flush_buffers(){
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}

header('Content-Type: video/mpeg');
$stream = fopen( $file, "rb" );
fseek($stream, (filesize($file)-10000000), SEEK_SET);

while(1){
    $response = fread($stream, 8192); 
    echo $response;
    flush_buffers();
}

fclose( $stream );
exit();
?>

And it works well via ffplay, but via VLC it played no more then 1 minute and stoped then.
Please advice how to make it work on VLC also?

like image 934
Ivan Kolesnikov Avatar asked Mar 16 '17 14:03

Ivan Kolesnikov


People also ask

Can HTTP be used to stream video?

You can't stream live video, since the HTTP method only works with complete files stored on the server. You can't automatically detect the end user's connection speed using HTTP.


1 Answers

Do you have a time limit for php execution ? if yes , change it to unlimited with :

set_time_limit(0);
like image 63
Ehsan Chavoshi Avatar answered Sep 28 '22 06:09

Ehsan Chavoshi