#!/usr/bin/perl
#
use strict;
use warnings;
use File::Path;
use POSIX;
use Getopt::Long;

GetOptions(
    'r|reencode' => \my $reencodeonly,
);


if ($reencodeonly) {
    reencode(@ARGV);
} else {
    my $file = record(@ARGV) or do {
        die "No file recorded";
    };
    reencode($file);
}
exit 0;

sub RECDIR { '/net/tmp/video' }

sub record {
    my ($stream, $recordtime) = @_;

    my %streams;
    my $url = 'http://mafreebox.freebox.fr/freeboxtv/playlist.m3u';

    if (open(my $handle, "/usr/bin/wget -O - '$url' 2>/dev/null |")) {
        my $sname;
        while (my $line = <$handle>) {
            chomp($line);
            if ($line =~ /^#EXTINF:\d+,\d+ - +(.*)/) {
                $sname = $1;
                $sname =~ s/\s+$//;
            } elsif ($line =~ /^([^#].*)/) {
    #            print "$sname: $1\n";
                $streams{$sname} = $1 if($sname);
            }
        }
        close($handle);
    } else {
        die "Cannot open playlist url";
    }

    File::Path::mkpath(RECDIR()) if (!-d RECDIR());

    my $streamname = $stream;
    $streamname =~ s/[^\w]/_/g;

    my $OUTFILE = RECDIR() . '/' . join('_',
        POSIX::strftime("%Y%m%d_%H%M%S", localtime),
        $streamname,
    );

    $stream && $streams{$stream} or
        die "NO STREAM\n" . join('', map { "$_\n" } sort { $a cmp $b } keys %streams) . "\n";

        #warn $stream;
    my $rtpport = sprintf("%d", rand(500));
    $rtpport += 40000;
    my @vlc = (
        qw(
        /usr/bin/vlc
        --no-playlist-autostart
        -I dummy
        --rtp-client-port),
        $rtpport,
        '--extraintf', '',
        qw(--sout),
        "file/ts:$OUTFILE.mpeg",
        $streams{$stream},
    );
    #warn join(' ', map { "'$_'" } @vlc) . "\n";
    my $pid = fork;
    if (!defined($pid)) {
        die "Cannot fork $!";
    }
    if ($pid) {
        my $start = localtime;
        sleep($recordtime);
        kill 15, $pid;
        wait;
        print "'$stream' into $OUTFILE.mpeg\n";
        print "Start: $start\n";
        print "End:   " . localtime() . "\n";
    } else {
        $ENV{PATH} = '/usr/local/bin:/usr/bin:/bin';
        open(STDOUT, '>', '/dev/null');
        open(STDERR, '>', '/dev/null');
        exec(@vlc) or die "Cannot exec vlc";
        exit 1;
    }

    return "$OUTFILE.mpeg"
}

sub reencode {
    my ($OUTFILE) = @_;
    my $width;
    my $height;
    if (open(my $handle, "mplayer -vo null -frames 0 -v '$OUTFILE' 2>&1 |")) {
        while(my $line = <$handle>) {
            if ($line =~ /^VIDEO:\s+MPEG2\s+(\d+)x(\d+)\s+\(aspect (\d)\)/) {
                my $ratio = {
                    2 => 4/3,
                    3 => 16/9,
                }->{$3} or next;
                $width = $2 * $ratio;
                $height = $2;
            }
        }
        close($handle);
    }

    if (defined($width)) {
        if (open(my $handle, "| /usr/bin/batch")) {
            my $mencoder =
                  "mencoder -quiet -ofps 25 -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=1800 " .
                  "-vf crop=$width:$height,scale=$width:$height  -oac mp3lame " .
                  "-lameopts cbr:br=128 -o '$OUTFILE.avi' '$OUTFILE'";
            print "$mencoder\n";
            print $handle "date\n\n";
            print $handle "$mencoder\n";
            print $handle 'echo $?' . "\n\n";
            print $handle "date\n";
            close($handle);
        }
    }
}

__END__


