/* Copyright (c) 1991-2002 Doshita Lab. Speech Group, Kyoto University */
/* Copyright (c) 2000-2002 Speech and Acoustics Processing Lab., NAIST */
/*   All rights reserved   */

/* adin-na.c --- sub-routine for NetAudio */

/* $Id: adin_na.c,v 1.3 2002/09/11 22:01:50 ri Exp $ */

/* boolean define conflict in <sent/stddefs.h> and <dat_types.h>... */
/* so libsent library include should not be used here */
#include <stdio.h>
#include <stdlib.h>

/* sound header */
#include <netaudio.h>
#include <defaults.h>
#define TRUE 1
#define FALSE 0
typedef short SP16;

static NAport *port;		/* NetAudio port */
static int need_swap = FALSE;	/* incoming data is fixed to BIG ENDIAN */

/* initialize NetAudio device */
int
NA_standby(int sfreq, char *server_devname)
{
  NAinfo info;
  char *buf;
  int cnt;

  /* endian check --- incoming data is BE */
#ifdef WORDS_BIGENDIAN
  need_swap = FALSE;
#else  /* LITTLE ENDIAN */
  need_swap = TRUE;
#endif /* WORDS_BIGENDIAN */

  /* Initialize '.datlinkrc' processing */
  /*InitDefaults(argv[0]);*/

  /* Open connection to DAT-Link server on server_devname */
  /* if NULL, env AUDIO_DEVICE is used instead. */
  /* if AUDIO_DEVICE not specified, local port is used */
  port = NAOpen(server_devname);
  if (port == NULL) {
    j_printerr("failed to open netaudio server on %s\n", server_devname);
    return(FALSE);
  }

  /* setup parameters */
  NAGetDefaultInfo(&info);
  info.source            = DL_ISRC_ALL; /* input source: all */
  info.record.sampleRate = sfreq; /* DAT(48kHz)->some freq */
  info.record.precision  = 16;	/* bits per sample */
  info.record.encoding   = NA_ENCODING_LINEAR;
  info.record.channels   = NA_CHANNELS_LEFT; /* mono */
  NASetInfo(port, &info);

  /* open a data connection for recording */
  if (NAOpenData(port, NA_RECORD) == -1) {
    perror("cannot open data connection");
    return(FALSE);
  }

  j_printerr("connected to netaudio server\n");

  return(TRUE);
}

/* close port (actually never used, just for reference...) */
static void
NA_close()
{

  /* Flush (delete) any buffered data for recording */
  NAFlush(port, NA_RECORD);

  /* Close the data connection */
  NACloseData(port, 0);

  /* Close connection */
  NAClose(port);

}  

/* begin recording */
void
NA_start()
{
  NABegin(port, NA_RECORD);
}

/* stop recording */
void
NA_stop()
{
  NAPause(port, NA_RECORD, 1);
}

/* read samples from audio device */
/* try to read `sampnum' samples and returns actual sample num recorded */
int
NA_read(SP16 *buf, int sampnum)
{
  int cnt;
  cnt = NARead(port, (char *)buf, sampnum * sizeof(SP16)) / sizeof(SP16);
  if (need_swap) swap_sample_bytes(buf, cnt);
  return(cnt);
}
