package ru.r2cloud.jradio.source;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import ru.r2cloud.jradio.FloatInput;

public class WavFileSource implements FloatInput {

	private final AudioInputStream ais;
	private final byte[] buf;
	private int currentBufIndex = 0;

	public WavFileSource(InputStream is) throws UnsupportedAudioFileException, IOException {
		ais = AudioSystem.getAudioInputStream(is);
		if (ais.getFormat().getSampleSizeInBits() != 16) {
			throw new UnsupportedAudioFileException("unsupported sample size in bits: " + ais.getFormat().getSampleSizeInBits());
		}
		buf = new byte[ais.getFormat().getFrameSize()];
	}

	@Override
	public float readFloat() throws IOException {
		if (currentBufIndex == 0 || currentBufIndex >= buf.length) {
			currentBufIndex = 0;
			int bytesRead = ais.read(buf, 0, buf.length);
			if (bytesRead == -1) {
				throw new EOFException();
			}
		}
		short s = (short) ((buf[currentBufIndex + 1] << 8) | (buf[currentBufIndex] & 0xff));
		currentBufIndex += 2;
		return ((float) s / Short.MAX_VALUE);
	}

	public AudioFormat getFormat() {
		return ais.getFormat();
	}

	public long getFrameLength() {
		return ais.getFrameLength();
	}

	@Override
	public void close() throws IOException {
		ais.close();
	}
}

@@ -671,16 +671,62 @@
 () != 16
+ && ais.getFormat().getSampleSizeInBits() != 8
 ) %7B%0A%09%09%09t
@@ -1159,16 +1159,70 @@
 %09%09%7D%0A%09%09%7D%0A
+%09%09if (ais.getFormat().getSampleSizeInBits() == 16) %7B%0A%09
 %09%09short 
@@ -1302,16 +1302,17 @@
 ff));%0A%09%09
+%09
 currentB
@@ -1325,16 +1325,17 @@
 x += 2;%0A
+%09
 %09%09return
@@ -1366,16 +1366,130 @@
 VALUE);%0A
+%09%09%7D else %7B%0A%09%09%09byte s = buf%5BcurrentBufIndex%5D;%0A%09%09%09currentBufIndex += 1;%0A%09%09%09return ((float) s / Byte.MAX_VALUE);%0A%09%09%7D%0A
 %09%7D%0A%0A%09pub

support 8bit .wav