#!/usr/bin/perl

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

# gdplaytmsim.pl: GiantDisc play time simulator
# 
# This little program coninuously (about once per second) writes the current 
# playtime to the database.
#
# This routine is used if
# - the mp3-player app can't generate the current playtime
# - when the player is in FastForward- or Rewind-state


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

use DBI;

### Parameters
if(scalar(@ARGV) != 3){print("gdplaytmsim.pl needs three parameters (db-host, id and nb)\n");}
my $dbhost   = $ARGV[0]; 
my $playerid = $ARGV[1];
my $audiochannel = $ARGV[2]; 


### 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} = 
sub { 
  # Kill event handler
  print "gdplaytmsim.pl killed\n"; 
  $dbh->disconnect; 
  exit;
}; 


### get player state and current time
my ($trackind, $state, $frame) = gdgentools::pll_get_playstate($dbh, $playerid, $audiochannel);
my ($frmplayed, $frmtotal) = gdgentools::pll_get_playtime($dbh, $playerid, $audiochannel);
my $tracklogged = 0;

### set winding speed (factor 5)
my $frmincrement = gdgentools::frames_per_second();
if ($state eq "ff") {
  $frmincrement = (5 * gdgentools::frames_per_second())
}
if ($state eq "rw") {
  $frmincrement = -(5 * gdgentools::frames_per_second())
}

print "played=$frmplayed, total=$frmtotal\n";

### set playtime once per second
while((0 <= $frmplayed) && ($frmplayed < $frmtotal)){
  sleep (1);
  $frmplayed += $frmincrement;
  #print ("actual time is ".time()." writing $frmplayed frames\n");

  gdgentools::pll_write_playtime($dbh, $playerid, $audiochannel, $frmplayed, $frmtotal);
  
#  if (($state eq "pl") && ($tracklogged == 0) && ($frmplayed > ($frmtotal/2))){
#    gdgentools::log_current_track($dbh, $playerid, $audiochannel);
#    $tracklogged = 1;
#  }
}

### set extreme values
if ($state eq "ff") {
  gdgentools::pll_write_playtime ($dbh, $playerid, $audiochannel, $frmtotal, $frmtotal);
  gdgentools::pll_write_playstate($dbh, $playerid, $audiochannel, $trackind, "in");
}

if ($state eq "rw") {
  gdgentools::pll_write_playtime ($dbh, $playerid, $audiochannel, 0, $frmtotal);
  gdgentools::pll_write_playstate($dbh, $playerid, $audiochannel, $trackind, "st");
}


print ("Terminated: Playtime simulator (end reached)\n");
$dbh->disconnect;

#
