<?
class FlashHeader {
	var $version;
	var $filetype;
	var $bitpos;
	var $cur;
	var $pos;
	var $rect;
	var $framerate;
	var $length;
	var $compression = 0;
	var $point = 0;
	var $isValid = 0;

	function FlashHeader($buffer)	{
		$this->buffer = $buffer;
		$fp = @fopen($this->buffer,"rb");
		$head = @fread($fp, 3);

		if($head == "CWS") {
			/* zlib */
			fseek($fp,0);
			$data = fread($fp,8);
			$_data = gzuncompress(fread($fp, filesize($buffer)));
			$data = $data . $_data;
			$this->data = $data;
			$this->compression = 1;
			$this->isValid = 1;
		} else if ($head == "FWS") {
			fseek($fp,0);
			$this->data = fread($fp, filesize($buffer));
			$this->isValid = 1;
		} else {
			$this->isValid = 0;
		}
		@fclose($fp);
	}
	
	function getimagesize() {
		if(!$this->isValid) { return false; }
		$this->filetype = $this->read(3);
		$this->version =  $this->readbyte();
		$l = $this->read(4);
		$this->filelength = filesize($this->buffer);
		$this->rect = $this->readRect();
		$this->framerate = unpack('vrate',$this->read(2));
		$this->framerate = $this->framerate['rate']/256;
		$this->framecount = $this->readshort();
		return array("size"=>$this->filelength, "width" => $this->rect[width], "height"=>$this->rect[height], "fps"=>$this->framerate, "frames"=>$this->framecount);
	}
	
	function read($n) {
		$ret = substr($this->data, $this->point, $this->point + $n);
		$this->point += $n;
		return $ret;
	}	
	
	function readshort()	{
		$pack = unpack('vshort',$this->read(2));
		return $pack['short'];
	}
	
	function readByte() {
		$ret = unpack("Cbyte",$this->read(1));
		return $ret['byte'];
	}

	function readRect() {
		$this->begin();
		$l = $this->readbits(5);
		$xmin = $this->readbits($l)/20;
		$xmax = $this->readbits($l)/20;
		$ymin = $this->readbits($l)/20;
		$ymax = $this->readbits($l)/20;
		$rect = new Rect($xmax, $ymax);
		return $rect->__str__();
	}

	function incpos() {
		$this->pos += 1;
		if($this->pos>8) {
			$this->pos = 1;
			$this->cur = $this->readbyte();
		}
	}
	
	function readbits($nbits) {
		$n = 0;
		$r = 0;
		while($n < $nbits) {
			$r = ($r<<1) + $this->getbits($this->pos);
			$this->incpos();
			$n += 1;
		}
		return $r;
	}
	
	function getbits($n)	{
		return ($this->cur>>(8-$n))&1;
	}
	
	function begin() {
		$this->cur = $this->readbyte();
		$this->pos = 1;
	}
}


class Rect
{
	function Rect($x2,$y2) {
		$this->xmax = $x2;
		$this->ymax = $y2;
		$this->value = $this->__str__();
	}

	function __str__() {
		$ret = array($this->xmax, $this->ymax);
		$ret["width"] = $this->xmax;
		$ret["height"] = $this->ymax;
		return $ret;
	}
}
?>