/*                                               RTAUDIO.C for Linux  */

/*  This module is included when RTAUDIO is defined at compile time.
    It provides an interface between Csound realtime record/play calls
    and the device-driver code that controls the actual hardware.
 */

#include "cs.h"
#include "soundio.h"

#include <unistd.h>
#include <fcntl.h>
#define DSP_NAME    "/dev/dsp"
static int dspfd_in = -1, dspfd_out = -1;
void setsndparms(int, int, int, float, unsigned);
void setvolume(unsigned);

static  int     ishift = 0, oshift = 0, oMaxLag;
extern  OPARMS  O;
#ifdef PIPES
#  define _pclose pclose
#endif

static int getshift(int dsize)  /* turn sample- or frame-size into shiftsize */
{
    switch(dsize) {
    case 1:  return(0);
    case 2:  return(1);
    case 4:  return(2);
    case 8:  return(3);
    default: die(Str(X_1169,"rtaudio: illegal dsize"));
      return(-1);           /* Not reached */
    }
}

void recopen_(int nchanls, int dsize, float sr, int scale)
                                /* open for audio input */
{
    oMaxLag = O.oMaxLag;        /* import DAC setting from command line   */
    if (oMaxLag <= 0)           /* if DAC sampframes ndef in command line */
      oMaxLag = IODACSAMPS;   /*    use the default value               */
    /* Jonathan Mohr  1995 Oct 17 */
    /* open DSP device for reading */
    if ((dspfd_in = open(DSP_NAME, O_RDONLY)) == -1 )
      die(Str(X_1307,"unable to open soundcard for audio input"));

    /* initialize data format, channels, sample rate, and buffer size */
    setsndparms(dspfd_in, O.informat, nchanls, sr, oMaxLag * O.insampsiz);
    ishift = getshift(dsize);
}

void playopen_(int nchanls, int dsize, float sr, int scale)
                                /* open for audio output */
{
    oMaxLag = O.oMaxLag;        /* import DAC setting from command line   */
    if (oMaxLag <= 0)           /* if DAC sampframes ndef in command line */
      oMaxLag = IODACSAMPS;   /*    use the default value               */
    /*  J. Mohr  1995 Oct 17 */
/* The following code not only opens the DSP device (soundcard and driver)
   for writing and initializes it for the proper sample size, rate, and
   channels, but allows the user to set the output volume.                  */
    {
      /* open DSP device for writing */
      if ((dspfd_out = open(DSP_NAME, O_WRONLY)) == -1 )
        die(Str(X_1308,"unable to open soundcard for audio output"));

      /* set sample size/format, rate, channels, and DMA buffer size */
      setsndparms(dspfd_out, O.outformat, nchanls, sr,
                  O.outbufsamps * O.outsampsiz);

      /* check if volume was specified as command line parameter */
      if (O.Volume) {
        /* check range of value specified */
        if (O.Volume > 100 || O.Volume < 0)
          die(Str(X_524,"Volume must be between 0 and 100"));
        setvolume( O.Volume );
      }

      /* 'oshift' is not currently used by the Linux driver, but ... */
      oshift = getshift(nchanls * dsize);
    }
}

int rtrecord_(char *inbuf, int nbytes) /* get samples from ADC */
{
    /*  J. Mohr  1995 Oct 17 */
    if ( (nbytes = read(dspfd_in, inbuf, nbytes)) == -1 )
      die(Str(X_736,"error while reading DSP device for audio input"));
    return(nbytes);
}

void rtplay_(char *outbuf, int nbytes) /* put samples to DAC  */
    /* N.B. This routine serves as a THROTTLE in Csound Realtime Performance, */
    /* delaying the actual writes and return until the hardware output buffer */
    /* passes a sample-specific THRESHOLD.  If the I/O BLOCKING functionality */
    /* is implemented ACCURATELY by the vendor-supplied audio-library write,  */
    /* that is sufficient.  Otherwise, requires some kind of IOCTL from here. */
    /* This functionality is IMPORTANT when other realtime I/O is occurring,  */
    /* such as when external MIDI data is being collected from a serial port. */
    /* Since Csound polls for MIDI input at the software synthesis K-rate     */
    /* (the resolution of all software-synthesized events), the user can      */
    /* eliminate MIDI jitter by requesting that both be made synchronous with */
    /* the above audio I/O blocks, i.e. by setting -b to some 1 or 2 K-prds.  */
{
        /*  J. Mohr  1995 Oct 17 */
    if (write(dspfd_out, outbuf, nbytes) < nbytes)
      printf(Str(X_177,"/dev/dsp: could not write all bytes requested\n"));
    nrecs++;
}

void rtclose_(void)              /* close the I/O device entirely  */
{                               /* called only when both complete */
    /*  J. Mohr  1995 Oct 17 */
    if (dspfd_in >= 0 && (close(dspfd_in) == -1))
      die(Str(X_1306,"unable to close DSP device"));
    if (dspfd_out >= 0 && (close(dspfd_out) == -1))
      die(Str(X_1306,"unable to close DSP device"));
    dspfd_in = dspfd_out = -1;
    if (O.Linein) {
#ifdef PIPES
      if (O.Linename[0]=='|') _pclose(Linepipe);
      else
#endif
        if (strcmp(O.Linename, "stdin")!=0) close(Linefd);
    }
}
