import java.io.IOException;

import javax.media.Buffer;
import javax.media.Format;
import javax.media.format.VideoFormat;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.PullBufferStream;

/**
 * The source stream to go along with ImageDataSource.
 */
class ImageSourceStream implements PullBufferStream
{
	private VideoFormat format;
	private int nextImage = 0;
	private boolean ended = false;
	private IActions actions;

	public ImageSourceStream(VideoFormat format, IActions actions)
	{
		this.format = format;
		this.actions = actions;
	}

	/**
	 * We should never need to block assuming data are read from files.
	 */
	public boolean willReadBlock()
	{
		return false;
	}

	/**
	 * This is called from the Processor to read a frame worth of video data.
	 */
	public void read(Buffer buf) throws IOException
	{	
		try
		{
			byte data[] = actions.getImageData(nextImage);
			System.out.println("Reading image: " + nextImage + ": " + data.length + " bytes.");
			nextImage++;
			
			buf.setData(data);		
			buf.setOffset(0);
			buf.setLength((int) data.length);
			buf.setFormat(format);
			buf.setFlags(buf.getFlags() | Buffer.FLAG_KEY_FRAME);
		}
		catch(Exception e)
		{
			System.out.println("Done reading images.");
			// We are done. Set EndOfMedia.
			buf.setEOM(true);
			buf.setOffset(0);
			buf.setLength(0);
			ended = true;
		}
	}

	/**
	 * Return the format of each video frame. That will be JPEG.
	 */
	public Format getFormat()
	{
		return format;
	}

	public ContentDescriptor getContentDescriptor()
	{
		return new ContentDescriptor(ContentDescriptor.RAW);
	}

	public long getContentLength()
	{
		return 0;
	}

	public boolean endOfStream()
	{
		return ended;
	}

	public Object[] getControls()
	{
		return new Object[0];
	}

	public Object getControl(String type)
	{
		return null;
	}
}
