/*
* audio.h
* DIN Is Noise is copyright (c) 2006-2024 Jagannathan Sampath
* DIN Is Noise is released under GNU Public License 2.0
* For more information, please visit https://dinisnoise.org/
*/


#ifndef __AUDIO
#define __AUDIO

#include <RtAudio.h>

#include <vector>
#include <string>

typedef float sample_t;

struct audio_out {

	enum {INVALID=-1};

	// audio devices
	RtAudio dac;
	std::vector<RtAudio::DeviceInfo> infos;
	std::vector<std::string> names; // use @ settings screen
	int num_devices, default_device, current_device, next_device, last_device;

	// sample rate vars
	int sample_rate;
	int samples_per_buffer; // buffer has all channels
	int samples_channel_size, samples_buffer_size; // in bytes
	void set_sample_rate (int s);
	void set_samples_per_channel (int spc);

	// for settings ui
	int i_sample_rate;
	void find_sample_rate_id (unsigned int sr);
	int goto_next_device (int i);
	int goto_next_sample_rate_id (int i);

  std::string prefs_name;
  void load_prefs ();
  void save_prefs ();
  void defaults ();

  audio_out ();
  ~audio_out ();

  void alloc ();
	void probe ();
	int open ();
  int open (int id, unsigned int sr, unsigned int spc);
	int start ();
	int close ();
	void list ();


  // written by the main thread
  //
  // a multi buffer scheme
  //
  // main thread writes a buffer, while audio thread streams another to audio card
  //

	int num_samples_buffers;
  sample_t * samples_buffers; // a bunch of sample buffers
  int* available; // buffer available for streaming?

  sample_t *readp, *writep;
  int readi, writei;
  inline int can_write () {return !available [writei];}

	// reuseable buffers
	// result, AM, FM, gater, volume, mix, mix alpha, buffer L,R , fader 1,2
	sample_t *result, *ams, *fms, *gatr, *vol, *mix, *mixa, *bufL, *bufR, *fdr1, *fdr2;

	int num_channels;
	int samples_per_channel;
	int last_sample;

  static int audio_wanted (void *ob, void *ib, unsigned int spc, double t, RtAudioStreamStatus status, void *data);


};

extern audio_out aout;
extern int SAMPLE_RATE;
extern float SAMPLE_DURATION;

#endif
