/*
 * energy.c
 *
 *  Created on: 2024年12月6日
 *      Author: yongchaoz
 */

#include "platform.h"
#include "hal_headfile.h"
#include "noise_gate.h"

static audio_noise_gate_def    audio_noise_gate;

void noise_gate_init(audio_noise_gate_def temp)
{
	audio_noise_gate.audio_fram_len = temp.audio_fram_len;
	audio_noise_gate.down_threshold = temp.down_threshold;
	audio_noise_gate.up_threshold = temp.up_threshold;
}

/**
 * 静噪门，根据声音的大小，给型号一个增益
 *
 * @param: audio:音频数据buff地址
 *         num_samples:音频数据的点数
 * @return: 信号增益.
 */
float noise_gate_deal(int16_t *audio,uint32_t num_samples)
{

	static float signal_gain = 0;
	uint16_t less_thresh_count = 0;
	uint16_t over_thresh_count = 0;
	for(uint16_t i=0;i<num_samples;i++)
	{
	   if(audio[i] < audio_noise_gate.down_threshold && audio[i] > -audio_noise_gate.down_threshold )
	   {
		   less_thresh_count++;
	   }
	   if(audio[i] > audio_noise_gate.up_threshold || audio[i] < -audio_noise_gate.up_threshold )
	   {
		   over_thresh_count++;
	   }
	}
	if(less_thresh_count > (audio_noise_gate.audio_fram_len - 5))
	{
		signal_gain -= 0.2;
		if(signal_gain < 0)
		{
			signal_gain = 0;
		}
	}
	else if(over_thresh_count > 20)
	{
		signal_gain += 0.1;
		if(signal_gain > 1)
		{
			signal_gain = 1;
		}
	}
	else
	{
		signal_gain += 0.1;
		if(signal_gain > 1)
		{
			signal_gain = 1;
		}
	}
	return signal_gain;
}
