lasp/cpp_src/dsp/lasp_ppm.cpp

115 lines
2.7 KiB
C++
Raw Normal View History

/* #define DEBUGTRACE_ENABLED */
#include "debugtrace.hpp"
#include "lasp_ppm.h"
#include "lasp_daqdata.h"
#include "lasp_daq.h"
#include <mutex>
using std::cerr;
using std::endl;
using Lck = std::scoped_lock<std::mutex>;
using rte = std::runtime_error;
PPMHandler::PPMHandler(SmgrHandle mgr, const d decay_dBps)
: ThreadedInDataHandler<PPMHandler>(mgr), _decay_dBps(decay_dBps) {
DEBUGTRACE_ENTER;
startThread();
}
void PPMHandler::inCallback(const DaqData &d) {
DEBUGTRACE_ENTER;
Lck lck(_mtx);
dmat data = d.toFloat();
const us nchannels = d.nchannels;
assert(data.n_cols == nchannels);
if (nchannels != _cur_max.size()) {
DEBUGTRACE_PRINT("Resizing clip and cur max");
_cur_max = vd(nchannels, arma::fill::value(1e-80));
_clip_time = vd(nchannels, arma::fill::value(-1));
}
assert(_clip_time.size() == _cur_max.size());
/// Obtain max abs values for each column, convert this row-vec to a column
/// vector, and scale with the max-range for each channel
vd maxabs = arma::max(arma::abs(data), 0).as_col() / _max_range;
/// Find indices for channels that have a clip
arma::uvec clips = maxabs > clip_point;
/// Find channels where the new maximum is higher than the previous one
arma::uvec update_max = maxabs > _cur_max;
for (us i = 0; i < nchannels; i++) {
if (clips(i)) {
/// Reset clip counter
_clip_time(i) = 0;
} else if (_clip_time(i) > clip_indication_time) {
/// Reset to 'unclipped'
_clip_time(i) = -1;
} else if (_clip_time(i) >= 0) {
/// Add a bit of clip time
_clip_time(i) += _dt;
}
if (update_max(i)) {
_cur_max(i) = maxabs(i);
} else {
_cur_max(i) *= _alpha;
}
}
}
std::tuple<vd, arma::uvec> PPMHandler::getCurrentValue() const {
/* DEBUGTRACE_ENTER; */
Lck lck(_mtx);
arma::uvec clips(_clip_time.size(), arma::fill::zeros);
clips.elem(arma::find(_clip_time >= 0)).fill(1);
return {20 * arma::log10(_cur_max + arma::datum::eps).as_col(), clips};
}
void PPMHandler::reset(const Daq *daq) {
DEBUGTRACE_ENTER;
Lck lck(_mtx);
if (daq) {
DEBUGTRACE_PRINT("New daq found");
_cur_max.fill(1e-80);
const us nchannels = daq->neninchannels();
DEBUGTRACE_PRINT(nchannels);
_max_range.resize(nchannels);
dvec ranges = daq->inputRangeForEnabledChannels();
assert(ranges.size() == nchannels);
for(us i=0;i<daq->neninchannels();i++) {
_max_range[i] = ranges[i];
}
_clip_time.fill(-1);
const d fs = daq->samplerate();
/* DEBUGTRACE_PRINT(fs); */
_dt = daq->framesPerBlock() / fs;
_alpha = std::max<d>(d_pow(10, -_dt * _decay_dBps / (20)), 0);
/* DEBUGTRACE_PRINT(_alpha); */
}
}
PPMHandler::~PPMHandler() {
DEBUGTRACE_ENTER;
stopThread();
}