#include "common.h"
#include "sound.h"

int sound_init(int audiofd, layer *info, int stereo) {
    /* Initialize audio device */
    audio_init	  init;
    audio_control control;
    audio_change  change;
    int		  samplefrq = (int)(s_freq[info->version]
		     [info->sampling_frequency] * 1000.0);

    init.srate = samplefrq * 1000;
    init.bits_per_sample = 16;
    init.mode = PCM;
    init.channels = stereo;
    init.flags = BIG_ENDIAN | FIXED;
    init.operation = PLAY;
    if (ioctl(audiofd, AUDIO_INIT, &init)!= 0) {
	perror("Error initializing ACPA");
	exit(1);
    }
 
    control.ioctl_request = AUDIO_CHANGE;
    control.request_info = &change;
    control.position = 0;
 
    change.dev_info = 0;
    change.input = AUDIO_IGNORE;
    change.output = OUTPUT_1;
    change.monitor = AUDIO_IGNORE;
    /* change.volume = 0x7fff0000; */
    change.volume = 0x5fff0000;
    change.volume_delay = 0;
    change.balance = 0x3fff0000;
    change.balance_delay = 0;
    change.treble = AUDIO_IGNORE;
    change.bass = AUDIO_IGNORE;
    change.pitch = AUDIO_IGNORE;
         
    if (ioctl(audiofd, AUDIO_CONTROL, &control) != 0) {
	perror( "Error changing ACPA parameters");
	exit(1);
    }
 
    control.ioctl_request = AUDIO_START;
 
    if (ioctl(audiofd, AUDIO_CONTROL, &control) != 0) {
	perror("Error starting ACPA");
	exit(1);
    }
    return 0;
}

int sound_open() {
    return(open("/dev/paud0/1", 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));
}
