// ----------------------------------------------------------------------------
//
//  Copyright (C) 2008-2017 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/>.
//
// ----------------------------------------------------------------------------


#ifndef __DPLIMIT1_H
#define __DPLIMIT1_H


#include <stdint.h>
#include "global.h"


class Histmin
{
public:

    Histmin (void) {}
    ~Histmin (void) {}

    void  init (int hlen);
    float write (float v);
    float vmin (void) { return _vmin; }

private:

    enum { SIZE = 32, MASK = SIZE - 1 };

    int    _hlen;
    int    _hold;
    int    _wind;
    float  _vmin;
    float  _hist [SIZE];
};


class Dplimit1
{
public:

    Dplimit1 (void);
    ~Dplimit1 (void);
    
    void init (float fsamp, int nchan, float threshd, float reltime);
    void fini (void);

    void set_threshd (float v);
    void set_reltime (float v);

    void get_stats (float *peak, float *gmax, float *gmin)
    {
	*peak = _peak;
	*gmax = _gmax;
	*gmin = _gmin;
	_rstat = true;
    }

    void prepare (int nsamp);
    void process (int nsamp, float *data[])
    {
	if (_state != BYPASS) process1 (nsamp, data); 
    }

private:

    enum { BYPASS, ACTIVE };

    void process1 (int nsamp, float *data[]);

    int               _state;
    float             _fsamp;
    int               _nchan;
    int               _div1;
    int               _div2;
    int               _len1;
    int               _len2;
    int               _delay;
    int               _dsize;
    int               _dmask;
    int               _delri;
    float            *_dbuff [MAXCHAN];
    int               _c1;
    int               _c2;
    float             _gt;
    float             _m1;
    float             _m2;
    float             _wlf;
    float             _w1;
    float             _w2;
    float             _w3;
    float             _z1;
    float             _z2;
    float             _z3;
    float             _zlf [MAXCHAN];
    volatile bool     _rstat;
    volatile float    _peak;
    volatile float    _gmax;
    volatile float    _gmin;
    Histmin           _hist1;
    Histmin           _hist2;
};


#endif
