// --------------------------------------------------------------
// --------------------------------------------------------------
#ifndef _ENV_H_
#define	_ENV_H_

#include "synth_defs.h"

#define ENV_TOL			((synth_float_t)(1E-4))
#define ENV_KE			((synth_float_t)(1-exp(-1)))

#define ENV_MIN_A		(0.001)		// s
#define ENV_MIN_D		(0.005)		// s
#define ENV_MIN_R		(0.005)		// s

// --------------------------------------------------------------
// Types
// --------------------------------------------------------------
enum
{
	ENV_PARAM2_A,
	ENV_PARAM2_D,
	ENV_PARAM2_S,
	ENV_PARAM2_R,
	ENV_PARAM2_END
};

enum
{
	env_state_idle = 0,
	env_state_attack,
	env_state_attack_retrigger,
	env_state_decay,
	env_state_sustain,
	env_state_release
};

enum
{
	env_event_trigger = 0,
	env_event_retrigger,
	env_event_release,
};

typedef struct _senv_param_t
{
	synth_float_t Ta;
	synth_float_t Td;
	synth_float_t Vs;
	synth_float_t Tr;

} env_param_t;

typedef struct _senvgen_t
{
	synth_float_t fs;
	UINT32 bufsize;
	UINT32 state;
	env_param_t param;
	synth_float_t k, s, sr, sf;
	synth_float_t a_a, b_a;
	synth_float_t a_d, b_d;
	synth_float_t a_r, b_r;
	synth_float_t *pOut;

} envgen_t;

// --------------------------------------------------------------
#if defined(__cplusplus)
extern "C" {
#endif

// --------------------------------------------------------------
// Exported functions
// --------------------------------------------------------------
void ENV_Init(envgen_t *pObj, synth_float_t fs);
void ENV_Free(envgen_t *pObj);
void ENV_Reset(envgen_t *pObj);
void ENV_SetBufsize(envgen_t *pObj, UINT32 size);
void ENV_SetFS(envgen_t *pObj, synth_float_t fs);
void ENV_Event(envgen_t *pObj, UINT32 type);
void ENV_Param2Set(envgen_t *pObj, UINT32 type, synth_float_t value);
UINT32 ENV_ParamGet(envgen_t *pObj, UINT32 type);

INT32 ENV_IsIdle(envgen_t *pObj);
INT32 ENV_IsStage(envgen_t *pObj, UINT32 stage_num);
synth_float_t* ENV_ProcessDataV(envgen_t *pObj, UINT32 len);

#if defined(__cplusplus)
}

#endif
// --------------------------------------------------------------

#endif // _ENV_H_
