/* resampling module 
 *
 * The audio data has been read. Here are the
 * functions to ensure a correct continuation
 * of the output stream and to convert to a
 * lower sample rate.
 *
 */

#define SYNC_OFF	150L
#undef    DEBUG_SHIFTS		/* simulate bad cdrom drives */
#undef SHOW_JITTER

#include <stdio.h>
#include <stdlib.h>
#if defined (HAVE_UNISTD_H) && (HAVE_UNISTD_H == 1)
#include <sys/types.h>
#include <unistd.h>
#endif
#include <stddef.h>
#include <string.h>
#include <limits.h>
#include <assert.h>

#include "mycdrom.h"
#include "readall.h"
#include "interface.h"
#include "byteorder.h"
#include "ringbuff.h"
#include "resample.h"
#include "global.h"



static unsigned char *pStart;	/* running ptr defining end of output buffer */
static unsigned char *pDst;	/* start of output buffer */

long 
SaveBuffer (unsigned char *p,
	    unsigned long SamplesToDo, 
	    unsigned long *TotSamplesDone)
{
  char *pSrc;                   /* start of cdrom buffer */
  char *pSrcStop;               /* end of cdrom buffer */

  pSrc = ( char * ) p;
  pDst = ( unsigned char * ) pSrc;
  pStart = ( unsigned char * ) pSrc;
  pSrcStop = pSrc + SamplesToDo*4;

  /* code for subsampling and output stage */

  /* optimize the case of no conversion */
  if ( 1 ) {
    /* output format is the original cdda format ->
     * just forward the buffer 
     */
      
    pDst = (unsigned char *) pSrcStop;		/* set pDst to end */
  }
  global.SkippedSamples += (pSrcStop - (char *)p)/4;

  if ( 1) {
    int retval = 0;
    unsigned outlen;

    assert(pDst >= pStart);
    outlen = (size_t) (pDst - pStart);

    if (outlen <= 0) return 0;

    if ( global.no_file != 0 ) {
        return 0;
    }
    if ((unsigned)(retval = write ( global.audio, pStart, outlen )) == outlen) {
	return 0;
    } else {
        fprintf(stderr, "write(audio, 0x%p, %u) = %d\n",pStart,outlen,retval);
        perror("Probably disk space exhausted");
        return 1;
    }
  } else return 0;
}


