/*
 *
 *  Bluetooth low-complexity, subband codec (SBC) decoder
 *
 *  Copyright (C) 2004  Marcel Holtmann <marcel@holtmann.org>
 *  Copyright (C) 2005  Mayank Batra <mayankbatra@yahoo.co.in>
 *
 *
 *  This program 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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/soundcard.h>

#include "sbc.h"

#define BUF_SIZE 4096

static void decode(char *filename)
{
	unsigned char *stream;
	struct stat st;
	off_t filesize;
	sbc_t sbc;
	int fd, id, pos, streamlen, framelen;
	int format=AFMT_S16_LE;
	int audio_fd;
	unsigned char audio_buffer[BUF_SIZE];
	int count=0;

	if (stat(filename, &st) < 0) {
		fprintf(stderr, "Can't get size of file %s: %s\n",
						filename, strerror(errno));
		return;
	}

	filesize = st.st_size;
	stream = malloc(st.st_size);

	if (!stream) {
		fprintf(stderr, "Can't allocate memory for %s: %s\n",
						filename, strerror(errno));
		return;
	}

	fd = open(filename, O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "Can't open file %s: %s\n",
						filename, strerror(errno));
		goto free;
	}

	if (read(fd, stream, st.st_size) != st.st_size) {
		fprintf(stderr, "Can't read content of %s: %s\n",
						filename, strerror(errno));
		close(fd);
		goto free;
	}

	close(fd);

	pos = 0;
	streamlen = st.st_size;
	sbc_init(&sbc, SBC_NULL);
	framelen = sbc_decode(&sbc, stream, streamlen);
	printf("%d Hz, %d channels\n", sbc.rate, sbc.channels);	

	/* Open the audio device */
	if((audio_fd=open("/dev/dsp",O_WRONLY,0))==-1) {
		printf("\nCan't open the audio device\n");
		exit(1);
	}

	/* Set the Format to be used */
	if(ioctl(audio_fd,SNDCTL_DSP_SETFMT,&format)==-1) {
		perror("\nSNDCTL_DSP_SETFMT\n");
		exit(1);
	}

	/* Set the number of channels */
	if(ioctl(audio_fd,SNDCTL_DSP_CHANNELS,&sbc.channels)==-1) {
		perror("\nSNDCTL_DSP_CHANNELS\n");
		exit(1);
	}

	/* Set the speed */
	if(ioctl(audio_fd,SNDCTL_DSP_SPEED,&sbc.rate)==-1) {
		perror("\nSNDCTL_DSP_SPEED\n");
		exit(1);
	}

	while (framelen > 0) {
		/* Do not straight away write sbc.data to device,
		instead, wait for a sufficient number of samples */
		memcpy(audio_buffer+count, sbc.data, sbc.len);
		count += sbc.len;
		if(count == 4096) {
			/* Now write to the device */
			write(audio_fd, audio_buffer, BUF_SIZE);
			count = 0;
		}
		pos += framelen;
		framelen = sbc_decode(&sbc, stream + pos, streamlen - pos);		
	}

	/* Decoding over, close the audio device */
	if(close(audio_fd)<0) {
		perror("\nUnable to close the audio device");
		exit(1);
	}

	sbc_finish(&sbc);

free:
	free(stream);
}

static void usage(void)
{
	printf("SBC decoder utility ver %s\n", VERSION);
	printf("Copyright (c) 2004  Marcel Holtmann\n\n");
	printf("Copyright (c) 2005  Mayank Batra\n\n");

	printf("Usage:\n"
		"\tsbcdec [options] file(s)\n"
		"\n");

	printf("Options:\n"
		"\t-h, --help           Display help\n"
		"\t-v, --verbose        Verbose mode\n"
		"\n");
}

static struct option main_options[] = {
	{ "help",	0, 0, 'h' },
	{ "verbose",	0, 0, 'v' },
	{ 0, 0, 0, 0 }
};

int main(int argc, char *argv[])
{
	int i, opt, verbose = 0;

	while ((opt = getopt_long(argc, argv, "+hv", main_options, NULL)) != -1) {
		switch(opt) {
		case 'h':
			usage();
			exit(0);

		case 'v':
			verbose = 1;
			break;

		default:
			exit(1);
		}
	}

	argc -= optind;
	argv += optind;
	optind = 0;

	if (argc < 1) {
		usage();
		exit(1);
	}

	for (i = 0; i < argc; i++)
		decode(argv[i]);

	return 0;
}