#!/usr/bin/perl

use warnings;
use POSIX qw(tmpnam);

use constant DVBSTREAM  => '/usr/local/src/dvbstream/dvbstream';
use constant SZAP       => '/usr/local/src/DVB/apps/szap/szap';
use constant TS2PS      => '/usr/local/bin/ts2ps';

die 'usage' unless @ARGV == 3;
($card,$tp,$pid) = @ARGV;

if ($szap = fork) {
    # wait for lock
    sleep 3;

    # record 40s of TS
    $tsfile = tmpnam();
    print "starting measurement...\n";
    system DVBSTREAM . " -c $card -n 40 -o $pid > $tsfile 2> /dev/null";
    print STDERR "WARNING: no stream recorded\n" unless (-s $tsfile);

    kill 15,$szap;

    # use ts2ps to find errors
    $errorlog = tmpnam();
    system TS2PS . " 0 0 < $tsfile > /dev/null 2> $errorlog";
    unlink $tsfile;
    $errors = `grep --count "Error in TS" $errorlog`;
    unlink $errorlog;
    chop $errors;

    print "card $card, tp $tp, pid $pid: $errors errors in TS\n";
} else {
    exec SZAP . " -a $card -r $tp";
}
