/*
    Copyright (C) 2010 Fons Adriaensen <fons@kokkinizita.net>
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/


#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <clthreads.h>
#include <clalsadrv.h>


// --------------------------------------------------------------------------------


class Freq
{
public:

    int   p;
    int   f;
    float a;
    float xa;
    float ya;
    float xf;
    float yf;
};


class MTDM
{
public:

    MTDM (void);
    int process (size_t len, float *inp, float *out);
    int resolve (void);
    void invert (void) { _inv ^= 1; }
    int    inv (void) { return _inv; }
    double del (void) { return _del; }
    double err (void) { return _err; }

private:

    double  _del;
    double  _err;
    int     _cnt;
    int     _inv;
    Freq    _freq [5];
};


MTDM::MTDM (void) : _cnt (0), _inv (0)
{
    int   i;
    Freq  *F;

    _freq [0].f = 4096;
    _freq [1].f =  512;
    _freq [2].f = 1088;
    _freq [3].f = 1544;
    _freq [4].f = 2049;

    _freq [0].a = 0.2f;
    _freq [1].a = 0.1f;
    _freq [2].a = 0.1f;
    _freq [3].a = 0.1f;
    _freq [4].a = 0.1f;

    for (i = 0, F = _freq; i < 5; i++, F++)
    {
	F->p = 128;
	F->xa = F->ya = 0.0f;
	F->xf = F->yf = 0.0f;
    }
}


int MTDM::process (size_t len, float *ip, float *op)
{
    int    i;
    float  vip, vop, a, c, s;
    Freq   *F;

    while (len--)
    {
        vop = 0.0f;
	vip = *ip++;
	for (i = 0, F = _freq; i < 5; i++, F++)
	{
	    a = 2 * (float) M_PI * (F->p & 65535) / 65536.0; 
	    F->p += F->f;
	    c =  cosf (a); 
	    s = -sinf (a); 
	    vop += F->a * s;
	    F->xa += s * vip;
	    F->ya += c * vip;
	} 
	*op++ = vop;
	if (++_cnt == 16)
	{
	    for (i = 0, F = _freq; i < 5; i++, F++)
	    {
		F->xf += 1e-3f * (F->xa - F->xf + 1e-20);
		F->yf += 1e-3f * (F->ya - F->yf + 1e-20);
		F->xa = F->ya = 0.0f;
	    }
            _cnt = 0;
	}
    }

    return 0;
}


int MTDM::resolve (void)
{
    int     i, k, m;
    double  d, e, f0, p;
    Freq    *F = _freq;

    if (hypot (F->xf, F->yf) < 0.01) return -1;
    d = atan2 (F->yf, F->xf) / (2 * M_PI);
    if (_inv) d += 0.5f;
    if (d > 0.5f) d -= 1.0f;
    f0 = _freq [0].f;
    m = 1;
    _err = 0.0;
    for (i = 0; i < 4; i++)
    {
	F++;
	p = atan2 (F->yf, F->xf) / (2 * M_PI) - d * F->f / f0;
        if (_inv) p += 0.5f;
	p -= floor (p);
	p *= 8;
	k = (int)(floor (p + 0.5));
	e = fabs (p - k);
        if (e > _err) _err = e;
        if (e > 0.4) return 1; 
	d += m * (k & 7);
	m *= 8;
    }  
    _del = 16 * d;

    return 0;
}


// --------------------------------------------------------------------------------


static char          playdev [256];
static char          captdev [256];
static unsigned long fsamp;
static unsigned long frsize;
static unsigned long nfrags;
static MTDM          mtdm;

 
class Audiothr : public P_thread
{
public:
 
    virtual void thr_main (void);

private:

    float *ipbuf;
    float *opbuf;
};


void Audiothr::thr_main (void)
{
    Alsa_driver *D;
    unsigned long k;

    ipbuf = new float [frsize];
    opbuf = new float [frsize];

    D = new Alsa_driver (playdev, captdev, 0, fsamp, frsize, nfrags);
    if (D->stat ()) 
    {
	fprintf (stderr, "Can't open ALSA device\n");
        delete D;
        return;
    }
    D->printinfo ();

    D->pcm_start ();
    while (1)
    {
	k = D->pcm_wait ();  
        while (k >= frsize)
       	{
            D->capt_init (frsize);
            D->capt_chan (0, ipbuf, frsize);
            D->capt_done (frsize);

	    mtdm.process (frsize, ipbuf, opbuf);

            D->play_init (frsize);
            D->play_chan (0, opbuf, frsize);              
            D->play_done (frsize);

            k -= frsize;
	}
    }
    D->pcm_stop ();

    delete D;
}


// --------------------------------------------------------------------------------


int main (int ac, char *av [])
{
    Audiothr  A;
    float     t;

    if (ac < 6)
    {
	fprintf (stderr, "alsa-latency <playdev><captdev><fsamp><frsize><nfrags>\n");
        return 1;
    }

    strcpy (playdev, av [1]);
    strcpy (captdev, av [2]);
    fsamp  = atoi (av [3]);
    frsize = atoi (av [4]);
    nfrags = atoi (av [5]);

    if (A.thr_start (SCHED_FIFO, -50, 0x20000))
    {
 	fprintf (stderr, "Can't run in RT mode, trying normal scheduling.\n");
        if (A.thr_start (SCHED_OTHER, 0, 0x20000))
        {
 	    fprintf (stderr, "Can't start audio thread.\n");
	    return 1;
	}
    }

    t = 1000.0f / fsamp;
    while (1)
    {
	usleep (250000);

	if (mtdm.resolve () < 0) printf ("Signal below threshold...\n");
	else 
	{
	    if (mtdm.err () > 0.3) 
	    {
		mtdm.invert ();
		mtdm.resolve ();
	    }
	    printf ("%10.3lf frames %10.3lf ms", mtdm.del (), mtdm.del () * t);
	    if (mtdm.err () > 0.2) printf (" ??");
            if (mtdm.inv ()) printf (" Inv");
	    printf ("\n");
	}
    }

    return 0;
}


// --------------------------------------------------------------------------------

