/*
 * @(#)Wave.java
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 2001 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDcreator.java for details.
 */

import java.io.File;
import java.io.FileInputStream;

class Wave {
	int format;
	int channels;
	long frequency;
	long bytesPerSecond;
	int bytesPerSample;
	long dataLength;

	public Wave(File file) throws Exception
	{
		this(file.getPath());
	}

	public Wave(String file) throws Exception
	{
		FileInputStream inStream = new FileInputStream(file);
		byte bs[] = new byte[44];
		if (inStream.read(bs) < 44
			|| bs[0] != 'R' || bs[1] != 'I'
			|| bs[2] != 'F' || bs[3] != 'F'
			|| bs[8] != 'W' || bs[9] != 'A'
			|| bs[10] != 'V' || bs[11] != 'E')
			throw new Exception(file + " is not a WAV");

		inStream.close();
		format = uint16(bs, 20);
		if (format != 1)
			throw new Exception(file + " has an invalid format");

		channels = uint16(bs, 22);
		frequency = uint32(bs, 24);
		bytesPerSecond = uint32(bs, 28);
		bytesPerSample = uint16(bs, 32);
		dataLength = uint32(bs, 40);
	}

	long getSeconds() {
		return dataLength / bytesPerSecond;
	}

	public static void main(String[] args) throws Exception {
		new Wave(args[0]).showInfo();
	}

	public void showInfo() {
		System.out.println("channels = " + channels);
		System.out.println("frequency = " + frequency);
		System.out.println("bytesPerSecond = " + bytesPerSecond);
		System.out.println("bytesPerSample = " + bytesPerSample);
		System.out.println("dataLength = " + dataLength);
		System.out.println("seconds = " + getSeconds());
	}

	public static int uint16(byte[] bs, int offset) {
		return
			((bs[offset + 1] & 0xff) << 8)
			| (bs[offset] & 0xff);
	}

	public static long uint32(byte[] bs, int offset) {
		return
			((bs[offset + 3] & 0xff) << 24)
			| ((bs[offset + 2] & 0xff) << 16)
			| ((bs[offset + 1] & 0xff) << 8)
			| (bs[offset] & 0xff);
	}
}
