#!/usr/bin/perl -w
use strict;

BEGIN {
	use Shout qw{};
}


###############################################################################
###	C O N F I G U R A T I O N
###############################################################################
use vars qw{$Debug $Lame};

$Debug		= 1;
$Bitrate	= 64;
$Server		= 'icecast.server.somewhere';
$Port		= 8000;
$MountPoint	= 'testing';
$Password	= 't3rs/\ge';
chomp( $Lame = `which lame` );



###############################################################################
###	M A I N   P R O G R A M
###############################################################################

### Create a new streaming object
my $streamer = new Shout
	ip			=> $Server,
	port		=> $Port,
	mount		=> $MountPoint,
	password	=> $Password,
	bitrate		=> $Bitrate;


### Try to connect, aborting on failure
if ( $streamer->connect ) {
	printf "Connected to %s port %d...\n", $streamer->ip, $streamer->port;
	printf "Will stream to mountpoint '%s'.\n", $streamer->mount;
} else {
	printf "couldn't connect: %s\n", $streamer->error;
	exit $streamer->shout_error;
}

### Stream each file specified on the command line
for my $file ( @ARGV ) {

	print STDERR "Can't read '$file': $!" unless -r $file;
	print "Sending $file...\n";

	### Run lame in downsampling mode on the file we're going to send
	open( LAME, "-|" ) || exec $Lame, qw{--mp3input -b}, $Bitrate, qw{-m j -f -S}, $file, "-";

	my $buff;
	READ: while ((my $len = sysread(LAME, $buff, 4096)) > 0) {
		print STDERR "Read $len bytes...\n" if $Debug;
		$streamer->sendData( $buff ) && next;

		warn( "send failed: ", $streamer->error, "\n" );
		last READ;
	} continue {
		$streamer->sleep;
	}

	close LAME;
}

### Disconnect from the server
$streamer->disconnect;

