/*
 *
 *
 *    dec_card.cc
 *
 *    Sound card-based NOAA NWS / EAS data decoder.
 *
 *    Copyright (C) 2018 by Matt Roberts.
 *    License: GNU GPL3 (www.gnu.org)
 *
 *
 */

#include "dec_card.h"
#include "nlimits.h"

using namespace KK5JY::DSP;

//
//  SoundCardWX::ctor
//
SoundCardWX::SoundCardWX(int id, const detector_t::Config &c, int win)
	: SoundCard(id, CARD_FS, SoundCard::S16, win),
	  demod(c),
	  decoder(c.fs / c.bps),
	  #if CARD_FS != MODEM_FS
	  m_DecFilter(fir_filter_t::Types::LowPass, FILTER_LEN, FILTER_COF, CARD_FS),
	  dec_ctr(0),
	  #endif
	  clipping(false) {
	// nop
}


//
//  SoundCardWX::event
//
void SoundCardWX::event(int16_t *in, int16_t *out, size_t count) {
	const uint16_t ci = channelsIn();

	// for each sample
	for (size_t i = 0; i != count; ++i) {
		sample_t sample = *in;
		in += ci; // step to next sample, stepping over any other channels

		// detect clipping
		if (abs(sample) >= (CLIP_LIMIT * norm_limits<sample_t>::maximum)) {
			clipping = true;
		}

		#if CARD_FS != MODEM_FS
		// LPF the sample prior to decimation
		sample = m_DecFilter.filter(sample);

		// decimate
		if (++dec_ctr == (CARD_FS / MODEM_FS)) {
			dec_ctr = 0;
			#endif

			// run the discriminator
			bool output = demod.run(sample);

			// and process it
			decoder.process_sample(output);
		#if CARD_FS != MODEM_FS
		}
		#endif
	}
}
