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


#include "delay.h"
#include "utils.h"
#include "log.h"
#include <string.h>
#include <stdlib.h>
#include <string>
using namespace std;

extern int SAMPLE_RATE;

void delay::zero () {
  nsamples = 0;
  samples = 0;
  fbk = 0;
  vol = 0;
  id = 0;
}

delay::delay (float t, const string& fn, const string& vn) {
	fbk_fname = fn;
	vol_fname = vn;
	fbk_crv.load (fbk_fname);
	vol_crv.load (vol_fname);
  msecs = t;
	zero ();
}

void delay::setup () {
	dlog << "*** setup delay: " << fbk_fname << ' ' << vol_fname << " ***" << endl;
	fbk_sol (&fbk_crv);
  vol_sol (&vol_crv);
	fbk_lis (this, &fbk_sol, fbk);
	vol_lis (this, &vol_sol, vol);
  set (msecs);		
  dlog << "+++ setup delay +++" << endl;
}

delay::~delay() {

	dlog << "--- deleting delay buffers ---" << endl;

  float* bf [3] = {samples, fbk, vol};
	const char* nm [3] = {"samples", "feedback", "volume"};

  for (int i = 0; i < 3; ++i) if (bf[i]) {
		dlog << "  deleting: " << nm[i] << endl;
		free (bf[i]);
	}

  fbk_crv.save (fbk_fname);
  vol_crv.save (vol_fname);
	dlog << "+++ deleted delay buffers +++" << endl;

}

void delay::prep_buffer () {
	static const float thou_1 = 1.0f / 1000;
	static const int size_of_float = sizeof (float);
  int n = (int) (msecs * SAMPLE_RATE * thou_1 + 0.5);
  if (n < 1) n = 1;
  if (n > nsamples) {
    float** nbf[3] = {&samples, &fbk, &vol};
    for (int i = 0; i < 3; ++i) {
      if (*nbf[i]) free (*nbf[i]);
      *nbf[i] = (float *) calloc (n, size_of_float);
    }
  }
  nsamples = n;
  clamp<int>(0, id, nsamples-1);
}

void delay::set (float t) {
  msecs = t;
  prep_buffer ();
  float dx = 1.0f / (nsamples-1), x = -dx;
  fbk_sol (x, dx, nsamples, fbk);
  vol_sol (x, dx, nsamples, vol);
  fbk_lis.result = fbk;
  vol_lis.result = vol;
}

void delay::get (float& t) {
  t = msecs;
}

void delay::operator() (float* out, int n, float fdr) {
  float f;
  for (int i = 0; i < n; ++i) {
    f = out[i] + fbk[id] * samples[id];
    out[i] += (fdr * vol[id] * f);
    samples[id] = f;
    if (++id >= nsamples) id = 0;
  }
}
