/*
    Copyright (C) 2003-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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <clthreads.h>
#include <clalsadrv.h>


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


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


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

private:

    float *buf0;
    float *buf1;

};


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

    buf0 = new float [frsize];
    buf1 = 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, buf0, frsize);
            D->capt_chan (1, buf1, frsize);              
            D->capt_done (frsize);

            D->play_init (frsize);
            D->play_chan (0, buf0, frsize);
            D->play_chan (1, buf1, frsize);              
            D->play_done (frsize);

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

    delete D;
}


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


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

    if (ac < 6)
    {
	fprintf (stderr, "alsa-loopback <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;
	}
    }

    sleep (1000000);

    return 0;
}


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