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

#ifndef _THA_WAVPACK_AUDIO_INPUT_H_
#define _THA_WAVPACK_AUDIO_INPUT_H_

#if defined(_WIN32)
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include <process.h>
#else
#include "WDL/swell/swell.h"
#include "WDL/swell/swell-functions.h"
#endif

#include <wavpack.h>

#if defined(__linux__)
#define NO_POSIX_FILEREAD
#include <sys/types.h>
#include <unistd.h>
#endif

#include "thalia/sample_format.h"
#include "thalia/thalia_plugin_public.h"

#include "WDL/wdlstring.h"
#include "WDL/fileread.h"
#include "WDL/filewrite.h"
#include "WDL/queue.h"
#include "WDL/resample.h"
#include "WDL/mutex.h"

class THA_WavPackInput : public THA_IFileInput
{
public:
  THA_WavPackInput();
  ~THA_WavPackInput();

  bool Open(const char *filename);

  const char *GetType() const;

  const char *GetFileName() const;

  int GetChannels() const;

  double GetSampleRate() const;

  double GetLength() const;

  int GetBitsPerSample() const;

  double GetPosition() const;

  void Seek(double time);

  int GetSamples(SAM *buffer, int length);

  bool IsStreaming() const;

  int Extended(int call, void *parm1, void *parm2, void *parm3);

private:
  void ReadNext();

  WDL_FileRead *m_file;
  WDL_FastString m_fn;

  int m_channels;
  int m_bitspersample;
  double m_samplerate;
  WDL_INT64 m_totallength;

  WDL_TypedBuf<int> m_buffer;
  WDL_TypedQueue<SAM> m_samples;
  WDL_Resampler m_rs;

  double m_currentpos;

  double m_hwsamplerate;
  bool m_eof;

  WavpackStreamReader64 m_sr;
  WavpackContext *m_wvctx;
};

#endif // _THA_WAVPACK_AUDIO_INPUT_H_
