#
# MythWeb Streaming/Download module
#
# @url       $URL: http://svn.mythtv.org/svn/branches/release-0-20-fixes/mythplugins/mythweb/modules/stream/handler.pl $
# @date      $Date: 2006-09-16 19:27:26 -0500 (Sat, 16 Sep 2006) $
# @version   $Revision: 11220 $
# @author    $Author: xris $
#

$SIG{CHLD} = "IGNORE";

our $host = "localhost";
our $height = '320';
our $width  = '320';
# Video Bit Rate
our $vbr    = '256';

# Which show are we streaming?
    our $chanid    = url_param('chanid');
    our $starttime = url_param('starttime');
    if ($Path[1]) {
        $chanid    = $Path[1];
        $starttime = $Path[2];
        $starttime =~ s/\.\w+$//;
    }

# Get the basename from the database
    my $sh = $dbh->prepare('SELECT basename, title, subtitle FROM recorded WHERE chanid=? AND starttime=FROM_UNIXTIME(?)');
    $sh->execute($chanid, $starttime);
    my ($basename, $title, $subtitle) = $sh->fetchrow_array();
    $sh->finish;

# No match?
    unless ($basename =~ /\w/) {
        print header(),
              "Unknown recording requested.\n";
        exit;
    }

# Filename on disk
    my $filename = "/media/mythtv/recordings/$basename";


# Make sure the file exists
    unless (-e $filename) {
        print header(),
              "$basename does not exist in the recordings directory.";
        exit;
    }

# kill any existing stream...

    print STDERR "Kill vlc: " . `killall vlc` . "\n";

# Create new stream...

if(!defined (my $childpid=fork()))
{
  print header(), "Cannot fork vlc.";
  exit;
}
elsif($childpid == 0)
{

     close STDIN;
     close STDOUT;
     close STDERR;

    my $cmd = "vlc -I dummy --ttl 3 $filename --sout  '#transcode{vcodec=mp4v,vb=$vbr,width=$width,height=$height,ab=32,channels=1,audio-sync}:std{access=http,mux=ts,dst=:8080}'";
    exec($cmd);
    exit();
}

print header(), "Your stream is available at <a href=\"http://$host:8080/\">http://$host:8080/</a>";

# Return true
    1;

