/*  VolumeMeter.h

    flatzebra - SDL-based sound renderer
    Copyright (C) 2011 Pierre Sarrazin <http://sarrazip.com/>

    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., 51 Franklin Street, Fifth Floor,
    Boston, MA  02110-1301, USA.
*/

#pragma once

#include <flatzebra/roundbeetle/FrameSource.h>

#include <SDL2/SDL_mutex.h>

#include <assert.h>
#include <math.h>
#include <vector>


namespace roundbeetle {


class VolumeMeter : public FrameSource
{
public:

    // windowLengthInSeconds: period of time over which the RMS is computed
    // (typical value: .1f).
    // _src: must come from new. Destroyed by this object's destructor.
    //
    VolumeMeter(float _windowLengthInSeconds, FrameSource *_src);

    virtual ~VolumeMeter();

    // Returns stereo PCM-16 signal.
    //
    virtual size_t getFrames(Frame *frameBuffer, size_t numFramesToFill) override;

    void getCurrentRMSVolumes(float &leftLinVol, float &rightLinVol) const;

    virtual bool isFinished() const override;

    virtual bool rewind() override;

private:

    void computeVolumes();

    VolumeMeter(const VolumeMeter &);
    VolumeMeter &operator = (const VolumeMeter &);

private:

    SDL_mutex *mutex;
    std::vector<Frame> window;
    FrameSource *src;
    size_t frameCounter;
    float currentRMSLinVols[2];  // must be accessed under mutex

};


}  // namespace roundbeetle
