
#include "csound.h"
#include "logger.h"

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>

void csound::setRate(int rate)
{
  if (ioctl(fd, SOUND_PCM_WRITE_RATE, &rate) == -1)
    logger(error("SOUND_PCM_WRITE_WRITE ioctl failed"));
  frate = rate;
}

void csound::setSize(int size)
{
  int tmpsize=size;
  if (ioctl(fd, SOUND_PCM_WRITE_BITS, &tmpsize) == -1)
    logger(error("SOUND_PCM_WRITE_BITS ioctl failed"));
  if (tmpsize != size)
    logger(error("unable to set sample size"));
  fsize = tmpsize;
}

void csound::setChannels(int channels)
{
  int tmpchannels = channels;  /* mono or stereo */
  if (ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &tmpchannels) == -1)
    logger(error("SOUND_PCM_WRITE_CHANNELS ioctl failed"));
  if (tmpchannels != channels)
    logger(error("unable to set number of channels"));
  fchannels = tmpchannels;
}

int csound::read(char *buf,int buflen)
{
  return(::read(fd,buf,buflen));
}

int csound::write(char *buf,int buflen)
{
  return(::write(fd,buf,buflen));
}

csound::csound(): frate(11000),fchannels(1),fsize(8)
{
  fd = open("/dev/dsp", O_RDWR);
  if (fd < 0)
    logger(error("open of /dev/dsp failed"));

  setRate(frate);
  setChannels(fchannels);
  setSize(fsize);
}

csound::~csound()
{
  close(fd);
}


csnd_mixer::csnd_mixer()
{
  fd = open("/dev/mixer", O_RDONLY);
  if (fd < 0)
    logger(error("open of /dev/mixer failed"));
}

csnd_mixer::~csnd_mixer()
{
  close(fd);
}



void csnd_mixer::setRecordingSource(int source)
{
  int recmask=(0x01 << source);
  if (ioctl(fd, SOUND_MIXER_WRITE_RECSRC, &recmask) == -1)
    logger(error("SOUND_MIXER_WRITE_RECSRC ioctl failed"));
}

int csnd_mixer::getRecordingSource()
{
  int recmask;
  if (ioctl(fd, SOUND_MIXER_READ_RECSRC, &recmask) == -1)
    logger(error("SOUND_MIXER_READ_RECSRC ioctl failed"));
  return(recmask);
}


