#if defined(__FreeBSD__)
# include <machine/soundcard.h>
#else
# include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include "common.h"
#include "sound.h"

/*
 * Sound-specific stuff for VOXware compatible audio devices.
 */

int sound_init(int audiofd, layer *info, int stereo) {
    int		samplefrq = (int)
		    (s_freq[info->version]
		    [info->sampling_frequency] * 1000.0);
    int		tmp;

    /* Sample size/precision? */
    tmp = AFMT_S16_LE;
    if (ioctl(audiofd, SNDCTL_DSP_SETFMT, &tmp) == -1) {
	perror("SNDCTL_DSP_SETFMT");
	return(1);
    }
    if (tmp != AFMT_S16_LE) {
	perror("Soundcard doesn't support 16 bit sound!");
	return(1);
    }

    /* Mono/stereo */
    tmp = stereo;
#if defined(__FreeBSD__)
#define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
#endif
    if (ioctl(audiofd, SNDCTL_DSP_CHANNELS, &tmp) == -1) {
	perror("SNDCTL_DSP_CHANNELS");
	return(1);
    }

    /*
     * Frequency, this has to be set after the number of channels
     * is selected otherwise SBPros fuck up
     */
    if (ioctl(audiofd, SNDCTL_DSP_SPEED, &samplefrq) == -1) {
	perror("SNDCTL_DSP_SPEED");
	return(1);
    }

    /*
     * Improves transport of sample data to audio device
     */
    tmp=12;
    ioctl(audiofd, SNDCTL_DSP_SETFRAGMENT, &tmp);
     /*
      * Raise the priority of audio device operations. This
      * only works if mpeg3play runs as root.
      */
    nice(-11);

    return(0);
}

int sound_open() {
    return(open("/dev/dsp", O_WRONLY));
}

int sound_close(int audiofd) {
    return(close(audiofd));
}

int sound_write(int audiofd, const void *buffer, size_t count) {
    return(write(audiofd, buffer, count));
}
