// Copyright (c) 2019 Giorgos Vougioukas
//
// The license can be found in the LICENSE file.

#include "rsi_waveout/audio_streamer_waveout.h"
#include "rsi_waveout/waveout_entry_point.h"

#include <math.h>
#include <string.h>

#include "WDL/fpcmp.h"
#include "WDL/db2val.h"
#include "WDL/pcmfmtcvt.h"
#include "WDL/ptrlist.h"

RSI_WaveOut::RSI_WaveOut()
  : m_error(paNoError)
  , m_stream(NULL)
  , m_running(false)
  , m_callback(NULL)
  , m_sample_fmt(0)
  , m_samplerate(44100)
  , m_output_nch(2)
  , m_output_dev(0)
{}

RSI_WaveOut::~RSI_WaveOut()
{}

bool RSI_WaveOut::Open()
{
  m_error = Pa_Initialize();
  if (WDL_NOT_NORMALLY(m_error != paNoError)) { return false; }

  m_sample_fmt = RSI_GetAudioDeviceBitDepth();
  m_samplerate = (int)RSI_GetAudioDeviceSamplerate();
  m_output_nch = RSI_GetAudioDeviceOutputChannels();
  m_output_dev = Pa_GetHostApiInfo(Pa_HostApiTypeIdToHostApiIndex(paMME))->defaultOutputDevice;

  PaSampleFormat sf;
  if (m_sample_fmt == 0) sf = paInt16;
  else if (m_sample_fmt == 1) sf = paInt24;
  else if (m_sample_fmt == 2) sf = paInt32;
  else if (m_sample_fmt == 3) sf = paFloat32;

  PaStreamParameters output_param;
  output_param.channelCount = m_output_nch;
  output_param.device = m_output_dev;
  output_param.sampleFormat = sf;
  output_param.suggestedLatency = Pa_GetDeviceInfo(output_param.device)->defaultLowOutputLatency;
  output_param.hostApiSpecificStreamInfo = NULL;

  PaWinMmeStreamInfo mme_stream_info;

  mme_stream_info.hostApiType = paMME;
  mme_stream_info.size = sizeof(PaWinMmeStreamInfo);
  mme_stream_info.version = 1;
  mme_stream_info.flags = 0;
  //mme_stream_info.flags = paWinMmeUseLowLevelLatencyParameters;
  //mme_stream_info.flags = paWinMmeDontThrottleOverloadedProcessingThread;
  //mme_stream_info.bufferCount = 8;
  //mme_stream_info.framesPerBuffer = 1024;
  mme_stream_info.channelMask = PAWIN_SPEAKER_STEREO;
  output_param.hostApiSpecificStreamInfo = &mme_stream_info;

  m_buffer.Resize(16384); // 8192, 16384, 32768
  m_pcm.Resize(16384 * sizeof(int));

  memset(m_buffer.Get(), 0, 16384 * sizeof(SAM));
  memset(m_pcm.Get(), 0, 16384 * sizeof(int));

  m_error = Pa_OpenStream(&m_stream, 0, &output_param, m_samplerate,
    paFramesPerBufferUnspecified, paDitherOff, pa_callback, this);
    //1024, paNoFlag, pa_callback, this);

  if (WDL_NOT_NORMALLY(m_error != paNoError))
  {
    wdl_log("cannot open stream | %s\n", Pa_GetErrorText(m_error));
    return false;
  }

  return true;
}

void RSI_WaveOut::Start(RSI_AudioCallback callback)
{
  m_error = Pa_StartStream(m_stream);

  if (WDL_NOT_NORMALLY(m_error != paNoError))
  {
    wdl_log("cannot start waveout output stream\n");
    return;
  }

  m_callback = callback;

  m_running = true;
}

void RSI_WaveOut::Stop()
{
  m_error = Pa_StopStream(m_stream);

  if (WDL_NOT_NORMALLY(m_error != paNoError))
  {
    wdl_log("cannot stop waveout output stream\n");
    return;
  }

  m_callback = NULL;

  m_running = false;
}

void RSI_WaveOut::Close()
{
  m_error = Pa_CloseStream(m_stream);

  if (WDL_NOT_NORMALLY(m_error != paNoError))
  {
    wdl_log("cannot close waveout output stream\n");
  }

  m_error = Pa_Terminate();

  if (WDL_NOT_NORMALLY(m_error != paNoError))
  {
    wdl_log("cannot terminate waveout output\n");
  }
}

bool RSI_WaveOut::IsRunning() const
{
  return m_running;
}

double RSI_WaveOut::GetSampleRate() const
{
  return (double)m_samplerate;
}

int RSI_WaveOut::pa_callback(const void *input, void *output,
  unsigned long frame_count, const PaStreamCallbackTimeInfo *time_info,
  PaStreamCallbackFlags status_flags, void *user_data)
{
  RSI_WaveOut *ud = (RSI_WaveOut *)user_data;

  if (!ud) { return 0; }
  if (!ud->m_callback) { return 0; }

  //if (status_flags & (paOutputOverflow | paOutputUnderflow))
  //{
  //  Sleep(1);
  //}

  //if (status_flags & (paOutputOverflow | paOutputUnderflow))
  //{
  //  WDL_ASSERT(1);
  //}

  short *out_16_bit = (short *)output;
  unsigned char *out_24_bit = (unsigned char *)output;
  float *out_32_bit_fp = (float *)output;
  int *out_32_bit = (int *)output;

  int fc = (int)frame_count * ud->m_output_nch;

  while (ud->m_buffer.GetSize() < fc)
  {
    ud->m_buffer.Resize(ud->m_buffer.GetSize() * 2);
    ud->m_pcm.Resize(ud->m_pcm.GetSize() * 2);
  }

  SAM *sam = ud->m_buffer.Get();

  //wdl_log("portaudio fc: %d\n", fc);

  ud->m_callback(&ud->m_buffer, fc, ud->m_output_nch);

  if (ud->m_sample_fmt == 0)
  {
    //ud->m_pcm.Resize(fc * sizeof(short));
#if (RSI_SAMPLE_PRECISION == 8)
    doublesToPcm(sam, 1, fc, ud->m_pcm.Get(), 16, 1);
#else
    floatsToPcm(sam, 1, fc, ud->m_pcm.Get(), 16, 1);
#endif
    short *pcm = (short *)ud->m_pcm.Get();

    for (int i = 0; i < fc; i++)
    {
      *out_16_bit++ = pcm[i];
    }
  }
  else if (ud->m_sample_fmt == 1)
  {
    //ud->m_pcm.Resize(fc * sizeof(char) * 3);
#if (RSI_SAMPLE_PRECISION == 8)
    doublesToPcm(sam, 1, fc, ud->m_pcm.Get(), 24, 1);
#else
    floatsToPcm(sam, 1, fc, ud->m_pcm.Get(), 24, 1);
#endif
    unsigned char *pcm = (unsigned char *)ud->m_pcm.Get();

    for (int i = 0; i < fc * 3; i += 3)
    {
      *out_24_bit++ = pcm[i];
      *out_24_bit++ = pcm[i + 1];
      *out_24_bit++ = pcm[i + 2];
    }
  }
  else if (ud->m_sample_fmt == 2)
  {
    //ud->m_pcm.Resize(fc * sizeof(int));
#if (RSI_SAMPLE_PRECISION == 8)
    doublesToPcm(sam, 1, fc, ud->m_pcm.Get(), 32, 1);
#else
    floatsToPcm(sam, 1, fc, ud->m_pcm.Get(), 32, 1);
#endif
    int *pcm = (int *)ud->m_pcm.Get();

    for (int i = 0; i < fc; i++)
    {
      *out_32_bit++ = pcm[i];
    }
  }
  else if (ud->m_sample_fmt == 3)
  {
    float *pcm = (float *)ud->m_pcm.Get();

    for (int i = 0; i < fc; i++)
    {
      *out_32_bit_fp++ = (float)sam[i];
    }
  }

  //Sleep(1);

  return paContinue;
}
