[dancer-users] Detecting disconnected HTTP clients during streamed output

Nicola Worthington nicolaw at tfb.net
Fri Dec 20 18:40:17 GMT 2013


I have a handler that transcodes video files using ffmpeg which all works
fine. However, if the web client disconnects or otherwise stops reading
from the socket, my handler will continue reading from the ffmpeg
filehandle and writing out to the writer object until ffmpeg has completed
the transcode.

This wouldn't be a problem is we lived in a perfect world where every web
client would send a single request to a URL and not make additional
requests until the first one had been completed, but of course we don't
live in an ideal world,.. and I would prefer my webapp not kill the server
it is running on my spawning off more CPU intensive processes than
necessary.

Is there any way for me to determine how much data is sat waiting to be
flushed to the web client so that if it exceeded a predetermined number of
bytes I can assume that I should kill my ffmpeg file handle and exit the
handler prematurely,.. or any other way to determine if the web client has
gone away?

Apologies if I haven't explained myself especially articulately.

This is the handler in question:

*get '/stream/:file/:format' => sub {*
*    my $file = params->{file};*
*    my $format = params->{format};*

*    return send_file(*
*        'favicon.ico',*
*        streaming => 1,*
*        callbacks => {*
*            override => sub {*
*                my ($respond, $response) = @_;*

*                my $mime = 'video/mp4';*
*                my @ffmpeg_args = qw(-threads 0 -i $file);*

*                if (exists $ffmpeg_formats{$format}) {*
*                    $mime = 'video/' . $format;*
*                    push @ffmpeg_args, @{$ffmpeg_formats{$format}};*
*                } else {*
*                    push @ffmpeg_args, @{$ffmpeg_formats{mp4}};*
*                }*
*                push @ffmpeg_args, '-';*

*                my $writer = $respond->([200, ['Content-Type' => $mime]]);*
*                open(my $fh, '-|', join(' ', '/usr/bin/ffmpeg',
@ffmpeg_args));*
*                my $buffer;*
*                while (read($fh, $buffer, 1024) ) {*
*                    $writer->write($buffer);*
*                }*
*                close($fh);*
*            },*
*        },*
*    );*
*};*


-- 
Nicola Worthington
nicolaw at tfb.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.preshweb.co.uk/pipermail/dancer-users/attachments/20131220/88573d16/attachment.html>


More information about the dancer-users mailing list