#!/usr/pkg/bin/perl
#
# @(#)mstream-play.pl,v 1.4 2008/11/22 07:28:02 kim Exp
#
#
# Copyright (c) 2004 Kimmo Suominen
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer
#    in the documentation and/or other materials provided with the
#    distribution.
# 3. The name of the author may not be used to endorse or promote
#    products derived from this software without specific prior
#    written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Stream player for mserv
# 20040418  Kimmo Suominen

use strict;
use MP3::Info;
use POSIX qw(floor mkfifo);

my $zapit = 0;

sub zap_ices {
    $zapit++;
}
$SIG{TERM} = \&zap_ices;

my $gw = ".icesgw";

if ( $#ARGV != 0 ) {
    die "Usage: $0 mp3file\n";
}
my $f = $ARGV[0];
die "Cannot open $f\n" unless -r $ARGV[0];

$|=1;

my $info = get_mp3info($f);

print "Writing to IceS...\n";
if (mkfifo($gw, 0666) && open(ICESGW, ">.icesgw")) {
    print ICESGW $f, "\n";
    close(ICESGW);
    unlink($gw);
    print "Writing to IceS... done!\n";
}

my $secs = floor($info->{SECS} - 4);
if ($secs > 0) {
    print "Sleeping $secs seconds\n";
    sleep $secs;
}

if (($zapit > 0) && open(PIDFILE, "<.ices.pid")) {
    print "Interrupted!\n";
    my $icespid = <PIDFILE>;
    close(PIDFILE);
    if ($icespid) {
	kill USR1 => $icespid;
    }
}

exit 0;
