/*
 * FSDefineJPEGImage3.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;

/**
 * FSDefineJPEGImage3 is used to define a transparent JPEG encoded image.
 * 
 * <p>
 * It extends the FSDefineJPEGImage3 class by including a separate zlib
 * compressed table of alpha channel values. This allows the transparency of
 * existing JPEG encoded images to be changed without re-encoding the original
 * image.
 * </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. The type attribute is
 * read-only and may be used when iterating through the objects in an FSMovie
 * object to identify the object class without using run-time type checking.</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.</td>
 * </tr>
 * 
 * <tr>
 * <td>alpha</td>
 * <td>An array of bytes containing the zlib encoded alpha channel data for
 * each pixel in the image.</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>
 * 
 * <p>
 * The simplest way to use the FSDefineJPEGImage3 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()];
 * byte[] alpha = new byte[width * height];
 * byte[] compressedAlpha = null;
 * 
 * try
 * {
 * 	FileInputStream imageContents = new FileInputStream(aFile);
 * 	imageContents.read(bytes);
 * 	imageContents.close();
 * 
 * 	// Set the level of transparency;
 * 
 * 	for (int i = 0; i &lt; bytes.length; i++)
 * 		alpha[i] = (byte) 128;
 * 
 * 	Deflater deflater = new Deflater();
 * 
 * 	byte[] tmp = new byte[alpha.length];
 * 
 * 	deflater.setInput(alpha);
 * 	deflater.finish();
 * 
 * 	int bytesCompressed = deflater.deflate(tmp);
 * 
 * 	compressedAlpha = new byte[bytesCompressed];
 * 
 * 	for (int i = 0; i &lt; bytesCompressed; i++)
 * 		compressedAlpha[i] = tmp[i];
 * } catch (FileNotFoundException e)
 * {
 * 	throw new FileNotFoundException(filename);
 * } catch (IOException e)
 * {
 * 	throw new IOException(filename);
 * }
 * 
 * movie.add(new FSDefineJPEGImage3(movie.newIdentifier(), bytes, null,
 * 				compressedAlpha));
 * </pre>
 * 
 * <p>
 * This generates an object with an empty encoding table, however the image will
 * still be displayed correctly. The empty encoding table is not a null object.
 * The alpha channel data is set so the image is completely opaque.
 * </P>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSDefineJPEGImage3 class represents the DefineBitsJPEG3 tag from the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 3.
 * </p>
 */
public class FSDefineJPEGImage3 extends FSDefineObject
{
	private int width;
	private int height;
	private byte[] image = null;
	private byte[] encodingTable = null;
	private byte[] alpha = null;

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

	/**
	 * Constructs an FSDefineJPEGImage3 object with the specified image data,
	 * encoding table and alpha channel data.
	 * 
	 * @param anIdentifier
	 *            the unique identifier for this object
	 * @param imageBytes
	 *            byte array containing the image data
	 * @param encodingBytes
	 *            byte array containing the encoding table
	 * @param alphaBytes
	 *            byte array containing the zlib compressed alpha channel data
	 */
	public FSDefineJPEGImage3(int anIdentifier, byte[] imageBytes,
								byte[] encodingBytes, byte[] alphaBytes)
	{
		super(DefineJPEGImage3, anIdentifier);
		setImage(imageBytes);
		setEncodingTable(encodingBytes);
		setCompressedAlpha(alphaBytes);
	}

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

	/**
	 * Gets the encoding table.
	 * 
	 * @return the array of bytes containing the encoding table.
	 */
	public byte[] getEncodingTable()
	{
		return 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 alpha channel data.
	 * 
	 * @return the array of bytes containing the zlib compressed alpha data.
	 */
	public byte[] getCompressedAlpha()
	{
		return alpha;
	}

	/**
	 * Sets the encoding table.
	 * 
	 * @param bytes
	 *            byte array 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;
	}

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

	/**
	 * Sets the alpha channel data with the zlib compressed data.
	 * 
	 * @param bytes
	 *            array of bytes containing zlib encoded alpha channel.
	 */
	public void setCompressedAlpha(byte[] bytes)
	{
		alpha = bytes;
	}

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

		anObject.image = Transform.clone(image);
		anObject.encodingTable = Transform.clone(encodingTable);
		anObject.alpha = Transform.clone(alpha);

		return anObject;
	}

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

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

			result = Transform.equals(image, typedObject.image);
			result = result
							&& Transform.equals(encodingTable,
											typedObject.encodingTable);
			result = result && Transform.equals(alpha, typedObject.alpha);
		}
		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>");
			Transform.append(buffer, "alpha", "<data>");
			buffer.append("}");
		}
	}

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

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

		length += (alpha == null) ? 0 : alpha.length;

		return length;
	}

	public void encode(FSCoder coder)
	{
		super.encode(coder);

		coder.writeWord(encodingTable.length + image.length, 4);
		coder.writeBytes(encodingTable);
		coder.writeBytes(image);

		if (alpha != null)
			coder.writeBytes(alpha);

		coder.endObject(name());
	}

	public void decode(FSCoder coder)
	{
		super.decode(coder);

		int offset = coder.readWord(4, false);

		setEncodingTable(readJPEGStream(coder));
		byte[] imageIn = new byte[offset - encodingTable.length];
		coder.readBytes(imageIn);
		setImage(imageIn);
		byte[] alphaIn = new byte[length - offset - 6];
		coder.readBytes(alphaIn);
		setCompressedAlpha(alphaIn);

		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);
			}
		}
	}
}