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

/**
 * FSAudioData is used to define sounds for a Flash Video (flv) file. It is
 * similar in function to the FSDefineSound class.
 * 
 * <table class="datasheet">
 * <tr>
 * <th align="left" colspan="2">Attributes</th>
 * </tr>
 * 
 * <tr>
 * <td>timestamp</td>
 * <td>The time in milliseconds at which the sound will be played. The
 * timestamp is used exclusively for determining when sound or video will be
 * played. Any internal timing information in the audio or video data is
 * ignored.</td>
 * </tr>
 * 
 * <tr>
 * <td>format</td>
 * <td>The format of the sound data - NATIVE_PCM, ADPCM, MP3, NELLYMOSER_8K or
 * NELLYMOSER.</td>
 * </tr>
 * 
 * <tr>
 * <td>playbackRate</td>
 * <td>The rate the sound will be played in Hertz: 5512, 11025, 22050 or 44100.
 * Note: sounds encoded using the Nellymoser have a fixed playback rate of 8KHz.</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>sound</td>
 * <td>The sampled sound data.</td>
 * </tr>
 * 
 * </table>
 * 
 * Five encoded formats for the sound data are supported:
 * 
 * <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>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 or MP3 whenever possible.</li>
 * 
 * <li>MP3 - compressed MPEG Audio Layer-3.</li>
 * 
 * <li>NELLYMOSER_8K - compressed Nellymoser Asao format at 8KHz supporting low 
 * bit-rate sound for improved synchronisation between the sound and frame rate of
 * movies. This format is not supported in SWF files.</li>
 * 
 * <li>NELLYMOSER - compressed Nellymoser Asao format supporting low bit-rate
 * sound for improved synchronisation between the sound and frame rate of
 * movies.</li>
 * </ul>
 * 
 * <h1 class="datasheet">History</h1<
 * 
 * <p>
 * The FSAudioData class represents the FLV Tag with the Audio Data section from
 * Macromedia's Flash (SWF) File Format Specification. It was added in Flash
 * Video 1.
 * </p>
 */
public final class FSAudioData extends FSVideoObject
{
	private int format = 0;
	private int playbackRate = 5512;
	private int playbackChannels = 1;
	private int playbackSampleSize = 1;
	private byte[] soundData = null;

	/**
	 * Construct an FSAudioData object and initialise it from encoded data.
	 * 
	 * @param coder
	 *            an FSCoder object containing an FSAudioData encoded as binary
	 *            data.
	 */
	public FSAudioData(FSCoder coder)
	{
		super(FSVideoObject.AudioData, 0);
		decode(coder);
	}

	/**
	 * Constructs an FSAudioData object specifying the parameters required to
	 * describe the sound.
	 * 
	 * @param timestamp
	 *            time in milliseconds from the start of the file that the sound
	 *            will be played..
	 * @param aFormat
	 *            the encoding format for the sound, either FSDefineSound.NATIVE_PCM,
	 *            FSDefineSound.ADPCM, FSDefineSound.MP3, FSDefineSound.NELLYMOSER_8K 
	 *            or FSDefineSound.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 bytes, either 1 or
	 *            2.
	 * @param bytes
	 *            the sound data.
	 */
	public FSAudioData(int timestamp, int aFormat, int rate, int channels, int sampleSize, byte[] bytes)
	{
		super(FSVideoObject.AudioData, timestamp);
		setFormat(aFormat);
		setPlaybackRate(rate);
		setPlaybackChannels(channels);
		setPlaybackSampleSize(sampleSize);
		setSoundData(bytes);
	}

	/**
	 * Gets the compression format used, either FSDefineSound.NATIVE_PCM, FSDefineSound.ADPCM, 
	 * FSDefineSound.MP3, FSDefineSound.NELLYMOSER_8K or FSDefineSound.NELLYMOSER.
	 * 
	 * @return a constant defining the type of compression.
	 */
	public int getFormat()
	{
		return format;
	}

	/**
	 * Sets the encoding format used, either FSDefineSound.NATIVE_PCM, FSDefineSound.ADPCM,
	 * FSDefineSound.MP3, FSDefineSound.NELLYMOSER_8K or FSDefineSound.NELLYMOSER.
	 * 
	 * @param encoding
	 *            the format for the sound.
	 */
	public void setFormat(int encoding)
	{
		format = encoding;
	}

	/**
	 * Gets the rate at which the sound will be played, in Hertz: 5512, 11025,
	 * 22050 or 44100. Note that the playback rate for NELLYMOSER_8K encoded audio
	 * is fixed at 8Khz so the playback rate attribute has no effect.
	 * 
	 * @return the rate at which the sound was sampled.
	 */
	public int getPlaybackRate()
	{
		return playbackRate;
	}

	/**
	 * 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)
	{
		playbackRate = rate;
	}

	/**
	 * Gets the number of sound channels, 1 (Mono) or 2 (Stereo). Both 
	 * NELLYMOSER_8K and NELLYMOSER are encoded as mono so the playbackChannels
	 * attribute has no effect.
	 * 
	 * @return the number of channels.
	 */
	public int getPlaybackChannels()
	{
		return playbackChannels;
	}

	/**
	 * 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;
	}

	/**
	 * 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;
	}

	/**
	 * 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;
	}

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

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

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

		anObject.soundData = Transform.clone(soundData);

		return anObject;
	}

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

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

			result = format == typedObject.format;
			result = result && playbackRate == typedObject.playbackRate;
			result = result && playbackChannels == typedObject.playbackChannels;
			result = result
							&& playbackSampleSize == typedObject.playbackSampleSize;
			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, "format", format);
			Transform.append(buffer, "playbackRate", playbackRate);
			Transform.append(buffer, "playbackChannels", playbackChannels);
			Transform.append(buffer, "playbackSampleSize", playbackSampleSize);
			buffer.append("}");
		} else
		{
			buffer.append(name());
		}
	}

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

		length += 1 + soundData.length;

		return length;
	}

	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.writeBytes(soundData);
	}

	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;
		soundData = new byte[length - 1];
		coder.readBytes(soundData);
	}
}