<?php
// sc-custom-waveform.php
/**
Generate a custom waveform image for the SoundCloud Custom Player.

This version simply changes the waveform background color.

Example Usage:
http://example.com/sc-custom-waveform.php?r=64&g=0&b=128&a=64&src=http://w1.sndcdn.com/nuSXXYh62P7v_m.png

JavaScript to auto-replace in the player:
<script type="text/javascript">
$(document).bind('onPlayerTrackSwitch.scPlayer', function(event, track){
	$('.sc-player .sc-waveform-container img').each(function(){
		$(this).attr('src', 'http://example.com/sc-custom-waveform.php?r=64&g=0&b=128&a=64&src='+$(this).attr('src'));
	});
});
</script>

Author: plong0 [at] spiralsense.com
Date: Nov. 4, 2012
*/

$src = $_REQUEST['src'];
$r = isset($_REQUEST['r'])?$_REQUEST['r']:0;
$g = isset($_REQUEST['g'])?$_REQUEST['g']:0;
$b = isset($_REQUEST['b'])?$_REQUEST['b']:0;
$a = isset($_REQUEST['a'])?(($_REQUEST['a']/255.0)*127):0; // normalize 0-255 alpha channel to 0-127

$debug = !TRUE;

// load the source image
$img_size = getimagesize($src);
$img = imagecreatefrompng($src);
imagealphablending($img, TRUE);
imagesavealpha($img, TRUE);

// replace the boundary color
if(version_compare(PHP_VERSION, '5.4.0', '>=')){
	imagecolorset($img, 1, $r, $g, $b, $a);
}
else{
	// can't set alpha channel PHP < 5.4.0
	//imagecolorset($img, 1, $r, $g, $b);
	
	// instead, fill the wave boundaries
	$color = imagecolorallocatealpha($img, $r, $g, $b, $a);
	imagefill($img, 0, 0, $color);
	imagefill($img, 0, $img_size[1]-1, $color);	
}

if(!$debug){
	header('Content-Type: image/png');
	imagepng($img);
	imagedestroy($img);
}
?>