/*
 *  playsnd_sgi.c - audio driver for SGI platform
 *
 *  $Revision: 1.18 $  $Date: 2000/06/19 13:17:54 $
 *  Copyright 1984-2000 The MathWorks, Inc.
 *
 * Must be linked against -laudio
 */

#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mex.h"
#include "audio.h"

void play(ffinput,len,out_rate)
     short *ffinput;
     unsigned int len;
     double out_rate;
{
  ALport *audport;
  ALconfig *audconfig;
  long pbuf[2], buflen;
  
  audport = mxCalloc(1,sizeof(ALport));
  audconfig = mxCalloc(1,sizeof(ALconfig));

/* Configure audio port*/
  *audconfig = ALnewconfig();
  ALsetwidth(*audconfig,AL_SAMPLE_16);
  ALsetchannels(*audconfig,AL_MONO);
  *audport = ALopenport("audstuff","w",*audconfig);

/* Set audio parameters */
  pbuf[0] = (long)AL_OUTPUT_RATE;
  pbuf[1] = (long)out_rate; 
  buflen = 2;
  ALsetparams(AL_DEFAULT_DEVICE,pbuf,buflen);

  ALwritesamps(*audport, ffinput, len);
  while(ALgetfilled(*audport)>0)
    {
      sginap(2);
    }
  ALfreeconfig(*audconfig);
  mxFree(audconfig);
  ALcloseport(*audport);
  mxFree(audport);
}

void mexFunction(
        int             nlhs,
        mxArray  *plhs[],
        int             nrhs,
        const mxArray  *prhs[]
        )
{
  unsigned int len;
  int a, w, h, i;
  double *finput, out_rate;
  short *ffinput, *ffstart;

  /* Leave gracefully if this Iris has no audio capabilities */
  if ((a = open("/dev/hdsp/hdsp0master",O_RDWR))<0){
      mexErrMsgTxt("This hardware doen't have audio capabilities");
  }
  close(a);

  /* check input args */
  if (nrhs < 1)
    /*mexErrMsgTxt("");*/
    /* This return here takes us back to matlab prompt.  The reason
       why I do this is because playsound with no args on sun returns
       without saying anything so I want the sgi to behave the same -pax*/
    return;
  if (nrhs > 3)
    mexErrMsgTxt("Too many input arguments.");
  
  w = mxGetM(prhs[0]);
  h = mxGetN(prhs[0]);
  finput = (double *)mxGetPr(prhs[0]);
  if (nrhs >= 2){
    out_rate = *((double *)mxGetPr(prhs[1]));
  }else{
    out_rate = 8000.0;   /* Default Output rate*/
  }	
  if(w>h) len = w;
  else len = h;
  ffinput = ffstart = (short *)mxCalloc(len,sizeof(short));
  for(i=1;i<=len;i++)
    {
      *ffinput = (short)(*finput*10000);  /*input range is [-1 1] so amplify*/
      *ffinput = ~(*ffinput) + 1;         /* two's complement */
      ffinput++;finput++;
    }
  play(ffstart,len,out_rate);
  mxFree(ffstart);
}

/* [EOF] playsnd_sgi.c */
