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

import java.util.ArrayList;
import java.util.Iterator;

/**
 * FSDefineSound is used to define a sound that will be played when a given
 * event occurs.
 * 
 * <p>
 * Three different types of object are used to play an event sound:
 * </p>
 * 
 * <ul>
 * <li>The FSDefineSound object that contains the sampled sound.</li>
 * <li>A FSSound object that defines how the sound fades in and out, whether it
 * repeats and also defines an envelope for more sophisticated control over how
 * the sound is played.</li>
 * <li>A FSStartSound object that signals the Flash Player to begin playing the
 * sound.</li>
 * </ul>
 * 
 * <p>
 * An FSDefineSound object contains the following attributes:
 * </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>An unique identifier for this object in the range 1..65535.</td>
 * </tr>
 * 
 * <tr>
 * <td> format</a></td>
 * <td>The format of the sound data - FSDefineSound.NATIVE_PCM, FSDefineSound.ADPCM,
 * FSDefineSound.MP3, FSDefineSound.PCM or FSDefineSound.NELLYMOSER</td>
 * </tr>
 * 
 * <tr>
 * <td>playbackRate</td>
 * <td>The rate the sound will be played in Hertz: 5512, 11025, 22050 or 44100</td>
 * </tr>
 * 
 * <tr>
 * <td>playbackChannels</td>
 * <td>The number of channels in the sound, typically 1 (mono) or 2 (stereo).</td>
 * </tr>
 * 
 * <tr>
 * <td>playbackSampleSize</td>
 * <td>The number of bytes in a sample: 1 or 2.</td>
 * </tr>
 * 
 * <tr>
 * <td>sampleCount</td>
 * <td>The number of samples in the sound.</td>
 * </tr>
 * 
 * <tr>
 * <td>soundLength</td>
 * <td>The number of bytes in the sound data.</td>
 * </tr>
 * 
 * <tr>
 * <td>sound</td>
 * <td>The encoded sound data.</td>
 * </tr>
 * 
 * </table>
 * 
 * <p>
 * Five encoded formats for the sound data are supported:
 * </p>
 * 
 * <ul>
 * <li>NATIVE_PCM - uncompressed Pulse Code Modulated: samples are either 1 or
 * 2 bytes. For two-byte samples the byte order is dependent on the platform on
 * which the Flash Player is hosted. Sounds created on a platform which supports
 * big-endian byte order will not be played correctly when listened to on a
 * platform which supports little-endian byte order.</li>
 * <li>PCM - uncompressed Pulse Code Modulated: samples are either 1 or 2 bytes
 * with the latter presented in Little-Endian byte order. This ensures that
 * sounds can be played across different platforms.</li>
 * <li>ADPCM - compressed ADaptive Pulse Code Modulated: samples are encoded
 * and compressed by comparing the difference between successive sound sample
 * which dramatically reduces the size of the encoded sound when compared to the
 * uncompressed PCM formats. Use this format whenever possible.</li>
 * <li>MP3 - compressed MPEG Audio Layer-3.</li>
 * <li>NELLYMOSER - compressed Nellymoser Asao format supporting low bit-rate
 * sound for improving synchronisation between the sound and frame rate of
 * movies.</li>
 * </ul>
 * 
 * <p>
 * Constants representing the different formats are defined in the FSSound
 * class.
 * </p>
 * 
 * <h1 class="datasheet">History</h1>
 * 
 * <p>
 * The FSDefineSound class represents the DefineSound structure from the
 * Macromedia Flash (SWF) File Format Specification. It was introduced in Flash
 * 1. Flash 3 added support for MP3 and the Nellymoser Asao format was added in
 * Flash 6.
 * </p>
 */
public class FSDefineSound extends FSDefineObject
{
	private int format = 0;
	private int playbackRate = 5512;
	private int playbackChannels = 1;
	private int playbackSampleSize = 1;
	private int sampleCount = 0;
	private byte[] soundData = null;

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

	/**
	 * Constructs an FSDefineSound object specifying the unique identifier and
	 * all the parameters required to describe the sound.
	 * 
	 * @param anIdentifier
	 *            the unique identifier for this sound.
	 * @param aFormat
	 *            the encoding format for the sound. For Flash 1 the formats may
	 *            be FSSound.NATIVE_PCM, FSSound.PCM or FSSound.ADPCM. For Flash
	 *            4 or later include FSSound.MP3 and Flash 6 or later include
	 *            FSSound.NELLYMOSER.
	 * @param rate
	 *            the number of samples per second that the sound is played at ,
	 *            either 5512, 11025, 22050 or 44100.
	 * @param channels
	 *            the number of channels in the sound, either 1 (Mono) or 2
	 *            (Stereo).
	 * @param sampleSize
	 *            the size of an uncompressed sound sample in bits, either 8 or
	 *            16.
	 * @param count
	 *            the number of samples in the sound data.
	 * @param bytes
	 *            the sound data.
	 */
	public FSDefineSound(int anIdentifier, int aFormat, int rate, int channels,
							int sampleSize, int count, byte[] bytes)
	{
		super(FSMovieObject.DefineSound, anIdentifier);
		setFormat(aFormat);
		setPlaybackRate(rate);
		setPlaybackChannels(channels);
		setPlaybackSampleSize(sampleSize);
		setSampleCount(count);
		setSoundData(bytes);
	}

	/**
	 * Constructs an FSDefineSound object by copying values from an existing
	 * object.
	 * 
	 * @param obj
	 *            an FSDefineSound object.
	 */
	public FSDefineSound(FSDefineSound obj)
	{
		super(obj);
		format = obj.format;
		playbackRate = obj.playbackRate;
		playbackChannels = obj.playbackChannels;
		playbackSampleSize = obj.playbackSampleSize;
		sampleCount = obj.sampleCount;
		soundData = Transform.clone(obj.soundData);
	}

	/**
	 * Gets the compression format used, either FSSound.NATIVE_PCM, FSSound.PCM
	 * or FSSound.ADPCM (all Flash 1), FSSound.MP3 (Flash 4+) or
	 * FSSound.NELLYMOSER (Flash 6+).
	 * 
	 * @return a constant defining the type of compression.
	 */
	public int getFormat()
	{
		return format;
	}

	/**
	 * Gets the rate at which the sound will be played, in Hz: 5512, 11025,
	 * 22050 or 44100.
	 * 
	 * @return the rate at which the sound was sampled.
	 */
	public int getPlaybackRate()
	{
		return playbackRate;
	}

	/**
	 * Gets the number of sound channels, 1 (Mono) or 2 (Stereo).
	 * 
	 * @return the number of channels.
	 */
	public int getPlaybackChannels()
	{
		return playbackChannels;
	}

	/**
	 * Gets the size of an uncompressed sample in bytes.
	 * 
	 * @return the number of bytes per sample when the sound is uncompressed.
	 */
	public int getPlaybackSampleSize()
	{
		return playbackSampleSize;
	}

	/**
	 * Gets the number of samples in the sound data.
	 * 
	 * @return the number of sound samples.
	 */
	public int getSampleCount()
	{
		return sampleCount;
	}

	/**
	 * Gets the sound data.
	 * 
	 * @return an array of bytes containing the sampled sound.
	 */
	public byte[] getSoundData()
	{
		return soundData;
	}

	/**
	 * Sets the compression format used, either FSSound.NATIVE_PCM,
	 * FSSound.ADPCM or FSSound.PCM from Flash 1 onwards, FSSound.MP3 from Flash
	 * 4 onwards, or FSSound.NELLYMOSER from Flash 6 onwards.
	 * 
	 * @param encoding
	 *            the format for the sound.
	 */
	public void setFormat(int encoding)
	{
		format = encoding;
	}

	/**
	 * Sets the sampling rate in Hertz. Must be one of: 5512, 11025, 22050 or
	 * 44100.
	 * 
	 * @param rate
	 *            the rate at which the sounds is played in Hz.
	 */
	public void setPlaybackRate(int rate)
	{
	    if (rate != 5512 && rate != 11025 && rate != 22050 && rate != 44100) {
	        throw new IllegalArgumentException("Sample rate must be: 5512, 11025, 22050 or 44100");
	    }
		playbackRate = rate;
	}

	/**
	 * Sets the number of channels defined in the sound.
	 * 
	 * @param channels
	 *            the number of channels in the sound, either 1 (Mono) or 2
	 *            (Stereo).
	 */
	public void setPlaybackChannels(int channels)
	{
		playbackChannels = channels;
	}

	/**
	 * Sets the sample size in bytes. Must be either 1 or 2.
	 * 
	 * @param sampleSize
	 *            the size of sound samples in bytes.
	 */
	public void setPlaybackSampleSize(int sampleSize)
	{
		playbackSampleSize = sampleSize;
	}

	/**
	 * Sets the number of samples in the sound data.
	 * 
	 * @param count
	 *            the number of samples for the sound.
	 */
	public void setSampleCount(int count)
	{
		sampleCount = count;
	}

	/**
	 * Sets the sound data.
	 * 
	 * @param bytes
	 *            the sound data.
	 */
	public void setSoundData(byte[] bytes)
	{
		soundData = bytes;
	}

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

		anObject.soundData = Transform.clone(soundData);

		return anObject;
	}

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

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

			result = format == typedObject.format;
			result = result && playbackRate == typedObject.playbackRate;
			result = result && playbackChannels == typedObject.playbackChannels;
			result = result
							&& playbackSampleSize == typedObject.playbackSampleSize;
			result = result && sampleCount == typedObject.sampleCount;
			result = result
							&& Transform.equals(soundData,
											typedObject.soundData);
		}
		return result;
	}

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

		if (depth > 0)
		{
			buffer.append(": { ");
			Transform.append(buffer, "identifier", identifier);
			Transform.append(buffer, "format", format);
			Transform.append(buffer, "playbackRate", playbackRate);
			Transform.append(buffer, "playbackChannels", playbackChannels);
			Transform.append(buffer, "playbackSampleSize", playbackSampleSize);
			Transform.append(buffer, "sampleCount", sampleCount);
			buffer.append("}");
		}
	}

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

		length += 5;
		length += soundData.length;

		return length;
	}

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

		coder.writeBits(format, 4);

		switch (playbackRate)
		{
			case 5512:
				coder.writeBits(0, 2);
				break;
			case 11025:
				coder.writeBits(1, 2);
				break;
			case 22050:
				coder.writeBits(2, 2);
				break;
			case 44100:
				coder.writeBits(3, 2);
				break;
		}
		coder.writeBits(playbackSampleSize - 1, 1);
		coder.writeBits(playbackChannels - 1, 1);
		coder.writeWord(sampleCount, 4);

		coder.writeBytes(soundData);
		coder.endObject(name());
	}

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

		format = coder.readBits(4, false);

		switch (coder.readBits(2, false))
		{
			case 0:
				playbackRate = 5512;
				break;
			case 1:
				playbackRate = 11025;
				break;
			case 2:
				playbackRate = 22050;
				break;
			case 3:
				playbackRate = 44100;
				break;
		}

		playbackSampleSize = coder.readBits(1, false) + 1;
		playbackChannels = coder.readBits(1, false) + 1;
		sampleCount = coder.readWord(4, false);

		soundData = new byte[length - 7];
		coder.readBytes(soundData);
		coder.endObject(name());
	}
}