#!/usr/bin/perl
#
# this wheel is reinvented by Rubber Duckie
# 2010 6/4
#
use lib 'C:\perlrtmp\lib';
use Time::Local;
use DBI;
use segwrapper;
require '..\OnesegWWW\http-doc\define.pl';
$ffmpeg = 'c:\bin\ffmpeg';
$packet_size = 4096; 

$ts_margin_pre = 5; 
$ts_margin_pos = 120; 
$thm_size = '100x56';

$tsoffset=110;
# if you want to create thumbnails for all programs in your database,
# set $all_in_db = 1;
$all_in_db = 0;
##########
my ($sec, $min, $hour, $mday, $mon, $year, undef, undef, undef)
    = localtime(time - 3600);
$stime=sprintf("%04d-%02d-%02d %02d:%",$year+1900,$mon+1,$mday,$hour);
my $dsn = 'DBI:SQLite:dbname='.$DBNAME;
my $dbh = DBI->connect($dsn, undef, undef,{RaiseError => 1, AutoCommit => 0});
my $sql = <<END;
select
    e.dv_start_time,
    c.dc_ch
    from
    da_event e inner join da_channel c
    on
    e.dv_service_id = c.dc_service_id
    where
    e.dv_start_time like ?
END
;#
if($all_in_db){
    my $ShotSM = -$ShotS;
    $sql =~ s/like \?/< datetime(?,'localtime','$ShotSM seconds')/;
    $stime='now';
}
my $sth = $dbh->prepare($sql);
my $rv  = $sth->execute($stime);
my @plist=();
while(my $ref=$sth->fetch()){
    push @plist, [@$ref];
}
undef $sth;
$dbh->disconnect();
for my $refp (@plist){
    @$refp[0] =~ /\d{2}(\d{2})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
    my $filename=$ThmDir."\\".$1.$2.$3.'-'.$4.$5.$6.'-xxxxxx-'.@$refp[1].'.jpg';
    if(-e $filename){
##	print "[no action]\n";
##	$log="[COM] no action. $filename was already made.";
    }else{
##	print "[make]";
	my $ShotSC = $ShotS - $tsoffset;
	my $sTime = timelocal($6,$5,$4,$3,$2-1,$1+100);
	($sec, $min, $hour, $mday, $mon, $year, $wday, undef, undef) = localtime( $sTime + $ShotSC-$ts_margin_pre);
	my $tsname = sprintf("%02d%02d%02d-%02d%02d%02d-",$year-100,$mon+1,$mday,$hour,$min,$sec);
	($sec, $min, $hour, undef, undef, undef, undef, undef, undef) = localtime( $sTime + $ShotSC+$ts_margin_pos);
	my $tsname = sprintf("%s%02d%02d%02d-%02d",$tsname,$hour,$min,$sec,@$refp[1]);
	my $opt = O_RDONLY | O_BINARY;
	eval { $opt |= O_LARGEFILE; };
	segwrapper::segopen(my $handle,$tsname,$opt);
	my $sOpen = 1;
	open(FFMPEG,"| $ffmpeg -y -f mpegts -acodec libfaad -vcodec h264 -i - -f image2 -vframes 1 -ss $ts_margin_pre -s $thm_size -an -deinterlace $filename");
	binmode(FFMPEG);
	local $SIG{PIPE}=sub{
	    segwrapper::segclose($handle);
	    close(FFMPEG);
	    $sOpen = 0;
	};
	while(segwrapper::segread($handle,my $buf,$packet_size)){
	    print FFMPEG $buf;
	}
	if($sOpen){
	    segwrapper::segclose($handle);
	    close(FFMPEG);
	    $sOpen = 0;
	}
	utime($sTime,$sTime,$filename); 
    }
}
