/* WaveFileWriter.java
   Copyright (C) 2006 Mysaifu.com

This file is part of Mysaifu JVM.

Mysaifu JVM is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; the version 2.

Mysaifu JVM is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package gnu.javax.sound.sampled.wce;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.spi.AudioFileWriter;

/**
 * Wave file writer.
 */
public class WaveFileWriter extends AudioFileWriter implements WaveFileConstants {
	/**
	 * 書き込むことのできるファイルタイプを返す。
	 */
	public AudioFileFormat.Type[] getAudioFileTypes() {
		return new AudioFileFormat.Type[] { AudioFileFormat.Type.WAVE };
	}

	public AudioFileFormat.Type[] getAudioFileTypes(AudioInputStream ais) {
		AudioFormat format = ais.getFormat();
		if (! format.isBigEndian()) {
			AudioFormat.Encoding encoding = format.getEncoding();
			int sampleSizeInBits = format.getSampleSizeInBits();
			// ・8ビット符号なしPCM
			// ・16ビット符号付PCM
			// をサポートする
			if (((encoding == AudioFormat.Encoding.PCM_UNSIGNED)
						&& (sampleSizeInBits == 8))
					||
					((encoding == AudioFormat.Encoding.PCM_SIGNED)
						&& (sampleSizeInBits == 16))) {
				return new AudioFileFormat.Type[] { AudioFileFormat.Type.WAVE };
			}
		}
		return new AudioFileFormat.Type[0];
	}
	
	/**
	 * 指定されたファイルにオーディオデータを書き込む。
	 */
	public int write(AudioInputStream ais,
					 AudioFileFormat.Type type,
					 File out) throws IOException {
		
		if (getAudioFileTypes(ais).length == 0) {
			throw new IllegalArgumentException("Unsupported format");
		}
		FileOutputStream fos = new FileOutputStream(out);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		
		// System.err.println("Output wave header");
		
		// ヘッダを出力する
		int totalLength = writeWaveHeader(bos, ais);
		
		// System.err.println("Output wave data");

		// データの内容を転送する
		totalLength += writeData(bos, ais);
		bos.close();
		
		// 最後にヘッダの長さ部分を埋める
		// System.err.println("Update wave header");
		RandomAccessFile raf = new RandomAccessFile(out, "rw");

		// ヘッダ内のサイズフィールド（ファイルサイズ - 8 を設定する）
		raf.seek(4);
		writeLE32(raf, totalLength - 8);

		// 波形データのバイト数
		raf.seek(OUTPUT_HEADER_LENGTH - 4);
		writeLE32(raf, totalLength - OUTPUT_HEADER_LENGTH);
		raf.close();

		return totalLength;
	}

	/**
	 * 指定されたOutputStreamに音声データを出力する。
	 * ヘッダにファイルサイズを書き込む必要があるため、AudioInputStream.getFrameLength()
	 * は必ず有効な値を返す必要がある。もしAudioSystem.NOT_SPECIFIED が返ってきた場合には、
	 * IOExceptionがthrowされる。
	 */
	public int write(AudioInputStream ais,
					 AudioFileFormat.Type type,
					 OutputStream os)
					 	throws IOException {
		if (getAudioFileTypes(ais).length == 0) {
			throw new IllegalArgumentException("Unsupported format");
		}
		
		// データサイズが確定していない場合はIOExceptionをthrowする
		// （ヘッダに書き込めないため）
		if (ais.getFrameLength() == AudioSystem.NOT_SPECIFIED) {
			throw new IOException("Unknown frame length");
		}
		
		// ヘッダを書き込む
		int totalLength = writeWaveHeader(os, ais);

		// データを書き込む
		totalLength += writeData(os, ais);
		
		os.close();
		
		return totalLength;
	}
	
	private int writeData(OutputStream os, AudioInputStream ais) throws IOException {
		AudioFormat format = ais.getFormat();
		byte[] buff = new byte[(int) format.getFrameRate() * format.getFrameSize()];
		int totalLength = 0;
		int len;
		while ((len = ais.read(buff)) != -1) {
			// System.err.println("WaveFileWriter.writeData() len=" + len);
			os.write(buff, 0, len);
			totalLength += len;
		}
		
		return totalLength;
	}
	
	static void writeLE32(RandomAccessFile raf, int value)
									throws IOException {
		raf.write(value);
		raf.write((int) (value >> 8));
		raf.write((int) (value >> 16));
		raf.write((int) (value >> 24));
	}

	static void writeLE32(OutputStream os, int value)
									throws IOException {
		os.write(value);
		os.write((int) (value >> 8));
		os.write((int) (value >> 16));
		os.write((int) (value >> 24));
	}
   
	static void writeLE16(OutputStream os, int value)
									throws IOException {
		os.write(value);
		os.write((int) (value >> 8));
	}

	/**
	 * WAVEヘッダを出力する
	 */
	private int writeWaveHeader(OutputStream os, AudioInputStream ais)
									throws IOException {
		// 波形データサイズを計算する
		AudioFormat format = ais.getFormat();
		long frameLength = ais.getFrameLength();
		int waveDataSize = format.getFrameSize() * (int) frameLength;
		if (frameLength < 0) {
			waveDataSize = 0;
		}
		int fileSize = OUTPUT_HEADER_LENGTH + waveDataSize - 8;
		
		// RIFFタグ
		os.write(RIFF_TAG);
		
		// ファイルサイズ
		writeLE32(os, fileSize);
		
		// WAVEタグ
		os.write(WAVE_TAG);
		
		// 'fmt ' タグ
		os.write(FMT_TAG);
		
		// 'fmt ' チャンク長
		writeLE32(os, FMT_LENGTH);
		
		// フォーマットID(リニアPCM)
		writeLE16(os, 1);
		
		// チャンネル数
		writeLE16(os, format.getChannels());
		
		// サンプリング周波数
		writeLE32(os, (int) format.getSampleRate());
		
		// 1秒あたりの転送バイト数
		writeLE32(os, (int) format.getFrameRate() * format.getFrameSize());
		
		// フレームサイズ
		writeLE16(os, format.getFrameSize());
		
		// 量子化ビット数
		writeLE16(os, format.getSampleSizeInBits());
		
		// 'data' タグ
		os.write(DATA_TAG);
		
		// WAVEデータ長
		writeLE32(os, (int) waveDataSize);
		
		return OUTPUT_HEADER_LENGTH;	// ヘッダサイズは固定
	}
	
}
