/* 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.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.spi.AudioFileReader;

/**
 * Waveファイルからサウンドデータを読み込むクラス。
 */
public class WaveFileReader extends AudioFileReader implements WaveFileConstants {
	
	/**
	 * ヘッダサイズの最大値
	 */
	private static int MAX_HEADER_SIZE = 120;
	
	public AudioFileFormat getAudioFileFormat(InputStream stream)
												throws UnsupportedAudioFileException,
														IOException {
		if (! stream.markSupported()) {
			throw new IOException("stream.markSupported() returns false");
		}
		stream.mark(MAX_HEADER_SIZE);
		
		AudioFileFormat format;
		try {
			format = readWaveHeader(stream);
		} finally {
			stream.reset();
		}
		return format;
	}

	public AudioFileFormat getAudioFileFormat(URL url)
                                            throws UnsupportedAudioFileException,
                                                   IOException {
		InputStream ins = url.openConnection().getInputStream();
		ins = new BufferedInputStream(ins, MAX_HEADER_SIZE);
 		AudioFileFormat format = readWaveHeader(ins);
 		ins.close();
		
		return format;
	}

	public AudioFileFormat getAudioFileFormat(File file)
                                            throws UnsupportedAudioFileException,
                                                   IOException {
		InputStream ins = new FileInputStream(file);
		ins = new BufferedInputStream(ins, MAX_HEADER_SIZE);
 		AudioFileFormat format = readWaveHeader(ins);
		ins.close();
		
		return format;
	}
	
	public AudioInputStream getAudioInputStream(InputStream stream)
                                              throws UnsupportedAudioFileException,
                                                     IOException {
		
		if (! stream.markSupported()) {
			throw new IOException("stream.markSupported() returns false");
		}
		stream.mark(MAX_HEADER_SIZE);
		
		AudioFileFormat format;
		try {
			format = readWaveHeader(stream);
		} catch (UnsupportedAudioFileException e) {
			stream.reset();
			throw e;
		} catch (IOException e) {
			stream.reset();
			throw e;
		}
		
		return new AudioInputStream(stream,
									format.getFormat(),
									format.getFrameLength());
	}

	public AudioInputStream getAudioInputStream(URL url)
                                              throws UnsupportedAudioFileException,
                                                     IOException {
		InputStream ins = url.openConnection().getInputStream();
		return getAudioInputStream(new BufferedInputStream(ins, MAX_HEADER_SIZE));
	}

	public AudioInputStream getAudioInputStream(File file)
                                              throws UnsupportedAudioFileException,
                                                     IOException {
		InputStream ins = new FileInputStream(file);
		return getAudioInputStream(new BufferedInputStream(ins, MAX_HEADER_SIZE));
	}

	private static int readLE32(InputStream ins) throws IOException {
		int result = 0;
		for (int i = 0; i < 4; ++i) {
			int data = ins.read();
			if (data == -1) {
				throw new EOFException();
			}
			result |= ((data << (i * 8)) & (0xff << (i * 8)));
		}
		return result;
	}
	
	private static short readLE16(InputStream ins) throws IOException {
		short result = 0;
		for (int i = 0; i < 2; ++i) {
			int data = ins.read();
			if (data == -1) {
				throw new EOFException();
			}
			result |= ((data << (i * 8)) & (0xff << (i * 8)));
		}
		return result;
	}
	
	private static int readFully(InputStream ins, byte[] buff) throws IOException {
		int remains = buff.length;
		int bytesRead = 0;
		while ((bytesRead = ins.read(buff, bytesRead, remains - bytesRead)) != -1) {
			remains -= bytesRead;
			if (remains <= 0) {
				break;
			}
		}
		
		if (remains > 0) {
			throw new EOFException();
		}
		return buff.length;
	}

	private static AudioFileFormat readWaveHeader(InputStream ins)
													throws IOException,
															UnsupportedAudioFileException {
		// RIFFヘッダを読み込む
		byte[] tag = new byte[4];
		readFully(ins, tag);
		if (! Arrays.equals(tag, RIFF_TAG)) {
			throw new UnsupportedAudioFileException("RIFF tag not found in header");
		}
		
		// ファイルサイズ
		int fileSize = readLE32(ins);
		
		// WAVEタグ
		readFully(ins, tag);
		if (! Arrays.equals(tag, WAVE_TAG)) {
			throw new UnsupportedAudioFileException("WAVE tag not found in header");
		}
		
		// 'fmt ' タグ
		readFully(ins, tag);
		if (! Arrays.equals(tag, FMT_TAG)) {
			throw new UnsupportedAudioFileException("fmt tag not found in header");
		}
		
		// フォーマットチャンクのバイト数
		if (readLE32(ins) != 16) {
			throw new UnsupportedAudioFileException("Unsupported fmt chunk size");
		}
		
		// フォーマットID
		int formatID = readLE16(ins);
		if (formatID != 1) {
			throw new UnsupportedAudioFileException("format id=" + formatID);
		}
		
		// チャンネル数
		int channels = readLE16(ins);
		
		// サンプリング周波数
		int sampleRate = readLE32(ins);
		
		// 1秒あたりの転送バイト数
		int bytesPerSec = readLE32(ins);
		
		// フレームサイズ
		int frameSize = (int) readLE16(ins) & 0xffff;
		
		// 量子化ビット数
		int sampleSizeInBits = readLE16(ins);
		if (sampleSizeInBits != 8 && sampleSizeInBits != 16) {
			throw new UnsupportedAudioFileException("Sample size in bits=" + sampleSizeInBits);
		}
		
		readFully(ins, tag);
		if (Arrays.equals(tag, FACT_TAG)) {
			// factタグ
			int chunkSize = readLE32(ins);
			
			// 読み飛ばす
			ins.skip(chunkSize);
			
			// 次のタグを読み込む
			readFully(ins, tag);
		}
		
		// dataタグ
		if (! Arrays.equals(tag, DATA_TAG)) {
			throw new UnsupportedAudioFileException("No data tag");
		}

		// WAVEデータサイズ
		int waveDataSize = readLE32(ins);
	
		AudioFormat format = new AudioFormat((sampleSizeInBits == 8) ? AudioFormat.Encoding.PCM_UNSIGNED
																	 : AudioFormat.Encoding.PCM_SIGNED,
											 (float) sampleRate,
											 sampleSizeInBits,
											 channels,
											 frameSize,
											 bytesPerSec / frameSize,
											 false);
											 
		return new AudioFileFormat(AudioFileFormat.Type.WAVE,
								   format,
								   waveDataSize / frameSize);
	}

}
