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

#ifndef _THA_VORBIS_AUDIO_INPUT_H_
#define _THA_VORBIS_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 <vorbis/codec.h>
#include <vorbis/vorbisfile.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_VorbisInput : public THA_IFileInput
{
public:
  THA_VorbisInput();
  ~THA_VorbisInput();

  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();

  ogg_sync_state *m_oy; // sync and verify incoming physical bitstream
  ogg_stream_state *m_os; // take physical pages, weld into a logical stream of packets
  ogg_page *m_og; // one Ogg bitstream page. Vorbis packets are inside
  ogg_packet *m_op; // one raw packet of data for decode

  vorbis_info *m_vi; // struct that stores all the static vorbis bitstream settings
  vorbis_comment *m_vc; // struct that stores all the bitstream user comments
  vorbis_dsp_state *m_vd; // central working state for the packet->PCM decoder
  vorbis_block *m_vb; // local working space for packet->PCM decode

  WDL_FileRead *m_file;
  WDL_FastString m_fn;

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

  char *m_buffer;
  WDL_TypedQueue<SAM> m_samples;
  WDL_Resampler m_rs;

  double m_currentpos;

  double m_hwsamplerate;
  bool m_eof;

  OggVorbis_File m_vf;
};

#endif // _THA_VORBIS_AUDIO_INPUT_H_
