#!/usr/bin/perl

##################################################
#
# GiantDisc mp3 Jukebox
# 
# © 2002, Rolf Brugger
#
##################################################

# gdplaycd.pl: GiantDisc play single audio cd track
# requires 'cdplay'
#
# - plays the specified track
# - writes the current playtime to the database once per second
# - exits when the track end is reached


use lib '/home/music/bin';
use gdgentools;
use DBI;

### Parameters
if(scalar(@ARGV) != 4){print("gdplaytimefilter.pl needs four parameters (db-host, player-id, player-type, track-number)\n");}
my $dbhost   = $ARGV[0]; 
my $playerid = $ARGV[1];
my $audiochannel = $ARGV[2]; 
my $tracknum = $ARGV[3]; 


### open DB connection
my $dbh = DBI->connect("DBI:mysql:GiantDisc:".$dbhost, "music", undef)
    or die "unable to connect to GiantDisc db";

### set termination handler
$SIG{TERM} = 'stopandexit'; # set Kill event handler
$SIG{INT}  = 'stopandexit'; # set Interrupt event handler


my ($line, $tracklen, $tracklen_frm, $played);

system ("cdplay play $tracknum");

$tracklen = 0;
foreach $line (split /\n/, `cdplay table`){
  if ($line =~ /.*\s+$tracknum\s*(\d*:\d*:\d*)\s*(\d*):(\d*)\s*/){
    #print $line;
    print "$2 min $3 sec\n";
    $tracklen = $2 * 60 + $3;
    $tracklen_frm = $tracklen * gdgentools::frames_per_second();
  }
}

$played = 1;
### Count seconds
while($played < $tracklen){

print "$played\n";
  sleep(1);
  gdgentools::pll_write_playtime($dbh, $playerid, $audiochannel, 
          $played * gdgentools::frames_per_second(), $tracklen_frm);
  $played++;
}

system ("cdplay stop");
#print ("Terminated: PlayCD track\n");
$dbh->disconnect;
#

sub stopandexit { 
  system ("cdplay stop"); 
  $dbh->disconnect; 
  exit;
}

#