/*
  MidiSynth, A MIDI synthesiser, a repacement for the Acorn MIDI module

  main.h - Common declarations and definitions

  created  19/01/10
  1.0      14/06/14
*/

#ifndef main_h
#define main_h

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "midi_spec.h"
#include "midi.h"
#include "instrument.h"

#ifndef FALSE
#define FALSE 0
#define TRUE !FALSE
#endif

#ifndef NULL
#define NULL 0
#endif

// Saturates 'x' to 'lo' or 'hi'
#define LIMIT(lo,x,hi) \
  if((x) < (lo)) (x) = (lo); \
  else if((x) > (hi)) (x) = (hi)

typedef unsigned long long int Uint64;
typedef signed long long int Int64;

// errors
enum
{
  NO_ERROR_,
  CANNOT_ALLOCATE_MEMORY,
  PROBLEM_OPENING_FILE,
  INVALID_DATA,
  INVALID_SIZE,
  PROBLEM_READING_FILE,
  INVALID_CRC
};

// shared sound audio buffer fill
typedef struct audio_s
{
  int size;                // length of circular buffer (samples not bytes)
  int read;                // read index (samples not bytes)
  int write;               // write index (samples not bytes)
  int rate_acc;            // fractional rate step accumulator (Q24)
  unsigned int *buffer;    // pointer to buffer of length 'size' samples (int's)
  int sys_base;            // system buffer base address
  int sys_end;             // system bufer end address
  int sys_rate;            // system sample rate (Q10)
  int sys_step;            // system fractional step (Q24)
  unsigned int sys_lr_vol; // system left/right volume (Q16 *2)
  int handler_id;          // shared sound handler id

} audio_t;

// general module data
#define AB_SIZE  2048 // audio buffer size in samples not bytes
typedef struct module_s
{
  int tx_chan;        // channel to use for Tx channel commands
  int fast_clk;       // true when fast clock enabled
  int callbacks;      // >0 if ticker callback pending
  int sleep_timer;    // sleep when sleep_timer reaches sleep_timeout
  int sleep_timeout;  // activity timeout in centiseconds
  FILE *log;          // debugging log file handle
  unsigned int debug; // bitfield, see below
  audio_t audio;      // audio data structure
  unsigned int buffer[AB_SIZE]; // audio buffer

} module_t;

// debug bitfield
#define DBG_SWI       0 // log swi calls
#define DBG_MSG       1 // log midi messages
#define DBG_CALLBACKS 2 // log ticker callbacks
#define DBG_SCHEDULER 3 // log scheduler calls

extern module_t mod;

#endif
