/**
   \file ftRev.c Reverb driver for VSOS
   \author Henrik Herranen, VLSI Solution Oy
*/

#include <vo_stdio.h>
#include <string.h>
#include <stdlib.h>
#include <apploader.h>
#include <ctype.h>
#include <vstypes.h>
#include <vs1005h.h>
#include <timers.h>
#include <vsos.h>
#include <sysmemory.h>
#include <ringbuf.h>
#include <aucommon.h>
#include <mutex.h>
#include "miscAsm.h"

extern FILE *audio_orig;

#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))

#if 0
void LimitSlew(register __i0 s_int16 *data, register __i2 *mem, register __d0 u_int16 limit, register s_int16 __a0 stereoSamples) {
  s_int16 limitPer2 = limit >> 1;
  int i;
  for (i=0; i<stereoSamples; i++) {
    s_int16 diff = *mem-(*data>>1);
    //    printf("%6d ", *data);
    if (abs(diff) > limitPer2) {
      if (diff < 0) {
	*data = 2 * *mem+limit;
      } else {
	*data = 2 * *mem-limit;
      }
    }
    //    printf("%6d\n", *data);
    *mem = *data>>1;
    data += 2;
  }
}
#endif

#ifdef USE_STDAUDIOIN
u_int16 AudioRead(register __i0 VO_FILE *self, u_int16 *buf,
		  u_int16 destinationIndex, u_int16 bytes) {
  u_int16 left = bytes>>1;

#if 0
  /* Removed, saving > 20 instruction words */
  /* Only whole samples are allowed. This is not a character device driver. */
  if (destinationIndex || (bytes&((bits==32) ? 7 : 3))) {
    return 0;
  }
#endif

  return fread(buf, 1, bytes>>1, audio_orig);
}
#endif /* USE_STDAUDIOIN */



#ifdef USE_STDAUDIOOUT
u_int16 AudioWrite(register __i0 VO_FILE *self, u_int16 *data,
		   u_int16 sourceIndex, u_int16 bytes) {
  static s_int16 mem[2];
#if 0
  /* Removed, saving > 20 instruction words */
  /* Only whole samples are allowed. This is not a character device driver. */
  if (sourceIndex || (bytes&((bits==32) ? 7 : 3))) {
    return 0;
  }
#endif

#if 0
  Sat16Buffer(data, 10000, bytes>>1);
#else
  LimitSlew(data+0, mem+0, 20000U, bytes>>2);
  LimitSlew(data+1, mem+1, 20000U, bytes>>2);
#endif
  fwrite(data, 2, bytes>>2, audio_orig);

  return bytes;
}
#endif /* USE_STDAUDIOOUT */

FILEOPS audioFileOps = {
  NULL, /* Open() */
  NULL, /* Close() */
  NULL, /* Ioctl() */
#ifdef USE_STDAUDIOIN
  AudioRead,  /* Read()  (if this is in the input path)  */
#else
  CommonOkResultFunction,
#endif
#ifdef USE_STDAUDIOOUT
  AudioWrite,  /* Write() (if this is in the output path) */
#else
  CommonOkResultFunction,
#endif
};

SIMPLE_FILE audioFile = {
#ifdef USE_STDAUDIOOUT
  __MASK_PRESENT|__MASK_OPEN|__MASK_WRITABLE|__MASK_FILE, /* Flags */
#else
  __MASK_PRESENT|__MASK_OPEN|__MASK_READABLE|__MASK_FILE, /* Flags */
#endif
  NULL, /* Identify() */
  &audioFileOps,
  0, /* pos */
  0, /* ungetc_buffer */
  NULL, /* dev */
};
