Page 2 of 2

Re: Image Server Push - Memory Leak?

Posted: Wed Oct 08, 2008 2:46 pm
by jwatson
After trying many different things, I've found the culprit...

OLD CODE:

Code: Select all

$sep = "sOmErAnDoMsTrInGfOrBoUnDaRy";
$header = 'Content-Type: multipart/x-mixed-replace;boundary=' . $sep;
header($header);
header("pragma: no-store,no-cache");
header("cache-control: no-cache,no-store,must-revalidate,max-age=-1");
header("expires: -1");
$boundary = "\n" . $sep . "\n";
echo $boundary;
set_time_limit(0);
while (1) {
    $handle = fopen("image.jpg", "rb");
    if ($handle != false) {
        $imageContents = "";
        while (!feof($handle)) {
            $imageContents .= fread($handle, 4096);
        }
        fclose($handle);
        echo "Content-Type: image/jpeg\n\n";
        echo $imageContents;
        echo $boundary;
        ob_flush();
        flush();
        usleep($waitTime);      
    }           
}


NEW CODE:

Code: Select all

$sep = "sOmErAnDoMsTrInGfOrBoUnDaRy";
$header = 'Content-Type: multipart/x-mixed-replace;boundary=' . $sep;
header($header);
header("pragma: no-store,no-cache");
header("cache-control: no-cache,no-store,must-revalidate,max-age=-1");
header("expires: -1");
$boundary = "\n" . $sep . "\n";
echo $boundary;
set_time_limit(0);
while (1) {
    $handle = fopen("image.jpg", "rb");
    if ($handle != false) {
        echo "Content-Type: image/jpeg\n\n";
        while (!feof($handle)) {
            $imageContents = fread($handle, 1024);
            if ($imageContents != false) = echo $imageContents;
        }
        fclose($handle);
        echo $boundary;
        usleep($waitTime);      
    } else usleep($waitTime);
}
So I am sleeping now if the file doesn't exist (but that wasn't the solution). It seems apache buffers only a set amount of data then automatically flushes it, thus there is no need to explictly call ob_flush() and flush(). These functions are actually the culprits. For some reason a flush can allocate an 4-8K chunk of memory in apache (maybe to fit data ino a boundary or something?) Also reading/printing the chunks of data in 1K increments seemed to improve performance. It is possible still for a browser to get a partial image since you are letting apache determine when to send a chunk of data which may be incomplete. Since my application is not inside a browser (Internet Explorer still doesn't support server push), this approach works fine. If you need to explictly use flush(), you'll have to deal with this problem unless you edit apache itself.

Re: Image Server Push - Memory Leak?

Posted: Wed Oct 08, 2008 6:20 pm
by josh
I think the browser would not decode until it saw the end boundary. interesting problem... damn apache