
#include <NDS.h>
#include <stdio.h>
#include <stdlib.h>
#include "strpcm.h"

static int strpcmVolume64;

u32 audio_Samples;
u32 audio_len;
u32 audio_Rate;
u32 audio_Channels;
EstrpcmFormat audio_Format;
u32 strpcmRequestStop;

static u32 fillvar;

void InitAudio(void)
{

  fillvar = 0; 
  int i;
  int j;
  for (i=0;i<strpcmRingBufCount ;i++ )
  {
      swiCopy(&fillvar,(char*)audio_buf[i],COPY_MODE_FILL | COPY_MODE_WORD | ((strpcmbufmaxlen)>>2));
  }
  strpcmSetVolume64(64);
}

void strpcmStart(void)
{
    fillvar = 0; 
  switch(audio_Format){
    case SPF_PCMx1: case SPF_PCMx2: case SPF_PCMx4:  {
      for (int i=0;i<strpcmRingBufCount ;i++ )
      {
          swiCopy(&fillvar,(char*)audio_buf[i],COPY_MODE_FILL | COPY_MODE_WORD | ((audio_len )>>2));
      }

      IPC6->strpcmFreq=audio_Rate;
      IPC6->strpcmSamples=audio_Samples;
      IPC6->strpcmChannels=audio_Channels;
      IPC6->strpcmFormat=audio_Format;
      
      //IPC6->strpcmLBuf=NULL;
      //IPC6->strpcmRBuf=NULL;
    } break;
  }
  IPC6->strpcmControl=ESC_Play;
  #ifdef ENABLE_DEBUG  
    printf("audio_Samples=%x,audio_len=%x,audio_Rate=%d,audio_Channels=%x,audio_Format=%x,audio_enable=%d\n",
        audio_Samples,audio_len,audio_Rate,audio_Channels,audio_Format,audio_enable);

    printf("audio_buf=%x,%x,%x,%x\n",audio_buf[0],audio_buf[1],audio_buf[2],audio_buf[3]);
#endif
strpcmRequestStop=false;

}

void strpcmStop(void)
{

strpcmRequestStop=true;
  while(IPC6->strpcmControl!=ESC_NOP){
      swiDelay(1);
  }
  //fillvar =0;
  //for (int i=0;i<strpcmRingBufCount ;i++ )
  //{
  //    swiCopy(&fillvar,(char*)audio_buf[i],COPY_MODE_FILL | COPY_MODE_WORD | ((strpcmbufmaxlen)>>2));
  //}



  IPC6->strpcmControl=ESC_Stop;
  while(IPC6->strpcmControl!=ESC_NOP){
      swiDelay(1);
  }
 
  switch(IPC6->strpcmFormat){
    case SPF_PCMx1: case SPF_PCMx2: case SPF_PCMx4: {
    } break;
  }
  
}

void strpcmSetVolume64(int v)
{
  if(v<0) v=0;
  if(128<v) v=128;
  
  strpcmVolume64=v;
  
  IPC6->strpcmVolume64=strpcmVolume64;
}

int strpcmGetVolume64(void)
{
  return(strpcmVolume64);
}

