/*
 * FSDefineJPEGImage2.java
 * Transform
 *
 * Copyright (c) 2001-2008 Flagstone Software Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *  * 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.
 *  * Neither the name of Flagstone Software Ltd. nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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.
 */

package com.flagstone.transform;

/**
 * FSDefineJPEGImage2 is used to define a JPEG encoded image with an integrated
 * encoding table.
 * 
 * <p>
 * It extends the FSDefineJPEGImage class by including a separate encoding
 * table, rather than using an FSJPEGEncodingTable object to store the encoding
 * table. This allows multiple JPEG images with different amounts of compression
 * to be included within a Flash file.
 * </p>
 * 
 * <table class="datasheet">
 * 
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>type</td>
 * <td>Identifies the data structure when it is encoded. Read-only.</td>
 * </tr>
 * 
 * <tr>
 * <td>identifier</td>
 * <td>A unique identifier, in the range 1..65535, that is used to reference
 * the image from other objects.</td>
 * </tr>
 * 
 * <tr>
 * <td>image</td>
 * <td>An array of bytes containing the JPEG compressed image.</td>
 * </tr>
 * 
 * <tr>
 * <td>encodingTable</td>
 * <td>An array of bytes containing the encoding table. May be set to null.</td>
 * </tr>
 * </table>
 * 
 * <p>
 * Although the encoding table defines how the image is compressed it is not
 * essential. If an FSDefineJPEGImage3 object is created with an empty encoding
 * table then the Flash Player will still display the JPEG image correctly. The
 * empty encoding table is not a null object. It contains four bytes: 0xFF,
 * 0xD8, 0xFF, 0xD9. For convenience passing a null reference to any of the
 * constructors or to the setEncodingTable method will create an empty table.
 * </p>
 * 
 * <h1 class="datasheet">Examples</h1>
 * 
 * <p>
 * The simplest way to use the FSDefineJPEGImage2 class is to use the
 * constructor that specifies the JPEG file to initialise the object:
 * </p>
 * 
 * <pre>
 * File aFile = new File(filename);
 * byte[] bytes = new byte[(int) aFile.length()];
 * 
 * try
 * {
 * 	FileInputStream imageContents = new FileInputStream(aFile);
 * 	imageContents.read(bytes);
 * 	imageContents.close();
 * } catch (FileNotFoundException e)
 * {
 * 	throw new FileNotFoundException(filename);
 * } catch (IOException e)
 * {
 * 	throw new IOException(filename);
 * }
 * 
 * movie.add(new FSDefineJPEGImage2(movie.newIdentifier(), bytes));
 * </pre>
 * 
 * <p>
 * This generates an object with an empty encoding table, however the image will
 * still be displayed correctly.
 * </p>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSDefineJPEGImage2 class represents the DefineBitsJPEG2 tag from the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 2.
 * </p>
 */
public class FSDefineJPEGImage2 extends FSDefineObject
{
	private int width;
	private int height;
	private byte[] image = null;
	private byte[] encodingTable = null;

	/**
	 * Construct an FSDefineJPEGImage2 object, initialising it with values
	 * decoded from an encoded object.
	 * 
	 * @param coder
	 *            an FSCoder containing the binary data.
	 */
	public FSDefineJPEGImage2(FSCoder coder)
	{
		super(DefineJPEGImage2, 0);
		decode(coder);
	}

	/**
	 * Constructs an FSDefineJPEGImage2 object with the identifier, JPEG image
	 * data and JPEG encoding table data.
	 * 
	 * @param anIdentifier
	 *            the unique identifier for this object
	 * @param imageBytes
	 *            the JPEG encoded image data.
	 * @param encodingBytes
	 *            the JPEG encoded encoding table.
	 */
	public FSDefineJPEGImage2(int anIdentifier, byte[] imageBytes,
								byte[] encodingBytes)
	{
		super(DefineJPEGImage2, anIdentifier);
		setImage(imageBytes);
		setEncodingTable(encodingBytes);
	}

	/**
	 * Constructs an FSDefineJPEGImage2 object with the identifier, JPEG image
	 * data and JPEG encoding table data.
	 * 
	 * @param anIdentifier
	 *            the unique identifier for this object
	 * @param imageBytes
	 *            the JPEG encoded image data.
	 */
	public FSDefineJPEGImage2(int anIdentifier, byte[] imageBytes)
	{
		super(DefineJPEGImage2, anIdentifier);
		setImage(imageBytes);
		setEncodingTable(null);
	}

	/**
	 * Constructs an FSDefineJPEGImage2 object by copying values from an
	 * existing object.
	 * 
	 * @param obj
	 *            an FSDefineJPEGImage2 object.
	 */
	public FSDefineJPEGImage2(FSDefineJPEGImage2 obj)
	{
		super(obj);
		image = Transform.clone(obj.image);
		width = obj.width;
		height = obj.height;
		encodingTable = Transform.clone(obj.encodingTable);
	}

	/**
	 * Gets the width of the image in pixels.
	 * 
	 * @return the width of the image.
	 */
	public int getWidth()
	{
		return width;
	}

	/**
	 * Gets the height of the image in pixels.
	 * 
	 * @return the height of the image in pixels.
	 */
	public int getHeight()
	{
		return height;
	}

	/**
	 * Gets the image data.
	 * 
	 * @return the array of bytes containing the image data.
	 */
	public byte[] getImage()
	{
		return image;
	}

	/**
	 * Gets the encoding table.
	 * 
	 * @return the array of bytes containing the encoding table.
	 */
	public byte[] getEncodingTable()
	{
		return encodingTable;
	}

	/**
	 * Sets the image data.
	 * 
	 * @param bytes
	 *            an array of bytes containing the image data.
	 */
	public void setImage(byte[] bytes)
	{
		image = bytes;
		decodeInfo();
	}

	/**
	 * Sets the encoding table.
	 * 
	 * @param bytes
	 *            an array of bytes containing the encoding table.
	 */
	public void setEncodingTable(byte[] bytes)
	{
		if (bytes == null)
		{
			bytes = new byte[]
			{
				(byte) 0xFF, (byte) 0xD9, (byte) 0xFF, (byte) 0xD8 };
		}
		encodingTable = bytes;
	}

	public Object clone()
	{
		FSDefineJPEGImage2 anObject = (FSDefineJPEGImage2) super.clone();

		anObject.image = Transform.clone(image);
		anObject.width = width;
		anObject.height = height;
		anObject.encodingTable = Transform.clone(encodingTable);

		return anObject;
	}

	public boolean equals(Object anObject)
	{
		boolean result = false;

		if (super.equals(anObject))
		{
			FSDefineJPEGImage2 typedObject = (FSDefineJPEGImage2) anObject;

			result = Transform.equals(image, typedObject.image);
			result = result
							&& Transform.equals(encodingTable,
											typedObject.encodingTable);
		}
		return result;
	}

	public void appendDescription(StringBuffer buffer, int depth)
	{
		buffer.append(name());

		if (depth > 0)
		{
			buffer.append(": { ");
			Transform.append(buffer, "encodingTable", "<data>");
			Transform.append(buffer, "image", "<data>");
			buffer.append("}");
		}
	}

	public int length(FSCoder coder)
	{
		super.length(coder);

		length += encodingTable.length;
		length += image.length;

		return length;
	}

	public void encode(FSCoder coder)
	{
		super.encode(coder);
		coder.writeBytes(encodingTable);
		coder.writeBytes(image);
		coder.endObject(name());
	}

	public void decode(FSCoder coder)
	{
		super.decode(coder);
		setEncodingTable(readJPEGStream(coder));
		byte[] data = new byte[length - encodingTable.length - 2];
		coder.readBytes(data);
		setImage(data);
		coder.endObject(name());
	}

	private byte[] readJPEGStream(FSCoder coder)
	{
		byte bytes[] = null;

		int start = coder.getPointer();
		int end = start + ((length - 2) << 3);
		int word = coder.readBits(16, false);
		int eoi = word == 0xFFD8 ? 0xFFD9 : 0xFFD8;

		do
		{
			word = coder.scanBits(16, false);

			if (word == eoi)
			{
				end = coder.getPointer() + 16;
				break;
			}
			coder.adjustPointer(8);
		} while (coder.getPointer() < end);

		int len = (end - start) >>> 3;

		coder.setPointer(start);
		bytes = new byte[len];
		coder.readBytes(bytes);

		return bytes;
	}

	private boolean decodeInfo()
	{
		FSCoder coder = new FSCoder(FSCoder.BIG_ENDIAN, image);

		if (coder.readWord(2, false) != 0xffd8)
			return false;

		while (true)
		{
			int marker = coder.readWord(2, false);
			int size = coder.readWord(2, false);

			if ((marker & 0xff00) != 0xff00)
				return false;

			if (marker >= 0xffc0 && marker <= 0xffcf && marker != 0xffc4
							&& marker != 0xffc8)
			{
				coder.readWord(1, false);
				height = coder.readWord(2, false);
				width = coder.readWord(2, false);
				return true;
			} else
			{
				coder.adjustPointer((size - 2) << 3);
			}
		}
	}
}
