
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>
#include "common.h"

#define AUDIO_DEV "/dev/dsp"

int audio_fd;

void init_audio()
{
	int fs=0x7fff0007,rate=FBASE,bits=16,stereo=0;

	if ((audio_fd=open(AUDIO_DEV, O_RDONLY)) == -1) {
		fprintf(stderr, "Cannot open sound device");
		exit(0);
	}

 	/* Set fragment size. (128 bytes @ 8000 Hz: one INT every 16 ms) */
 	fs=0x7fff0007;
        if (FS>=32000) fs=0x7fff0009;		/* 512 bytes */
        else if (FS>=16000) fs=0x7fff0008;	/* 256 bytes */

        if (ioctl(audio_fd, SNDCTL_DSP_SETFRAGMENT, &fs)) {
        	fprintf(stderr, "Cannot set fragment size\n");
        }
        /*--------------------------------------------------------*/
        if (ioctl(audio_fd, SNDCTL_DSP_SAMPLESIZE, &bits) == EOF) {
                fprintf(stderr, "Cannot set %d bits/sample\n",bits);
        }
        if (ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo) == EOF) {
                fprintf(stderr, "Cannot set %ld channel(s)\n",stereo+1);
        }
        if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &rate) == EOF) {
                fprintf(stderr, "Cannot set rate %d Hz\n",rate);
        }
}

#define NBUF 128

float get_audio_sample()
{
	static int bp=0,ns=0;
	static short audio_buf[NBUF*OSR];
        int i,a;

	if (bp>=ns) {
		ns=read(audio_fd,audio_buf,(NBUF*OSR)<<1)>>1;
		bp=0;
	}
        for (i=a=0;i<OSR;i++) a+=audio_buf[bp+i];
        bp+=OSR;
	return (float)(a/OSR)/32768.;
}
