// ----------------------------------------------------------------------------
//
//  Copyright (C) 2010-2021 Fons Adriaensen <fons@linuxaudio.org>
//    
//  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 3 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, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------


#include "jambpan.h"


Jambpan::Jambpan (const char *client_name, const char *server_name,
                  int degree, int ninput)
{
    int i, n;

    if (degree < 1) degree = 1;
    if (degree > MAXDEGR) degree = MAXDEGR;
    if (ninput < 1) ninput = 1;
    if (ninput > MAXINP) ninput = MAXINP;

    for (i = 0; i < ninp (); i++) _ambpan [i] = 0;
    n = (degree + 1) * (degree + 1);
    if (   open_jack (client_name, server_name, ninput, n)
        || create_inp_ports ("in_%d")
        || create_out_ports ("out.%d"))
    {
        _state = FAILED;
        return;
    }
    for (i = 0; i < ninp (); i++)
    {
        _ambpan [i] = new Ambpan8 (_jack_rate, degree, true);
    } 
    _state = PROCESS;
}


Jambpan::~Jambpan (void)
{
    _state = INITIAL;
    close_jack ();
    for (int i = 0; i < ninp (); i++)
    {
        delete _ambpan [i];
    }
}


void Jambpan::set_direction (int inp, float az, float el, float dt)
{
    if (_state < PROCESS) return;
    if ((inp < 0) || (inp > _ninp)) return;
    _ambpan [inp]->set_direction (az, el, dt);
}


int Jambpan::jack_process (int nframes)
{
    int    i;
    float  *inp;
    float  *out [MAXHARM];
    
    if (_state < PROCESS) return 0;
    for (i = 0; i < nout (); i++)
    {
        out [i] = (float *) jack_port_get_buffer (_out_ports [i], nframes);
    }
    for (i = 0; i < ninp (); i++)
    {
        inp = (float *) jack_port_get_buffer (_inp_ports [i], nframes);
        _ambpan [i]->process (nframes, inp, out, i > 0);
    }
    return 0;
}

