/*
 * audioout.c - Output audio to the hardware
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <sys/audioio.h>

#include "audioout.h"

static int fd;
static audio_info_t ainf;
short * workbuf;

int audio_open(unsigned long maxlen) {
  if ((fd = open("/dev/audio", O_WRONLY)) == -1) {
    return -1;
  }

  AUDIO_INITINFO(&ainf);
  ainf.play.sample_rate = 44100;
  ainf.play.channels = 2;
  ainf.play.precision = 16;
  ainf.play.encoding = AUDIO_ENCODING_LINEAR;
  ainf.play.buffer_size = 1024;
  ioctl(fd, AUDIO_SETINFO, &ainf);

  workbuf = malloc(2 * maxlen * sizeof(short));

  return 0;
}

int audio_generate(long * left, long * right, unsigned long len) {
  int i;
 
  for (i=0; i<len; i++) {
    workbuf[(i<<1)    ] = (left[i] >> 2);
    workbuf[(i<<1) + 1] = (right[i] >> 2);
  } 

  write(fd, workbuf, len * 4);

  return 0;
}

int audio_close(void) {
  free(workbuf);
  close(fd);
 
  return 0;
}

