#include "WebRtcAecm.h"
#include "BoostLog.h"
#include "modules/audio_processing/aecm/echo_control_mobile.h"

WebRtcAecm::~WebRtcAecm() {
    close();
}

void WebRtcAecm::close() {
    if (m_hanlde != nullptr) {
        webrtc::WebRtcAecm_Free(m_hanlde);
        m_hanlde = nullptr;
    }
}

void WebRtcAecm::echoPlayback(const int16_t *play, int samples) {
    if (webrtc::WebRtcAecm_BufferFarend(m_hanlde, play, samples) != 0) {
        LOG(warning) << "failed to buffer farend signal.";
    }
}

void WebRtcAecm::echoCancellation(const int16_t *nearendNoisy, const int16_t *nearendClean, int16_t *out, int samples) {
    if (webrtc::WebRtcAecm_Process(m_hanlde, nearendNoisy, nearendClean, out, samples, 60) != 0) {
        LOG(warning) << "WebRtcAecm_Process() failed.";
    }
}

bool WebRtcAecm::start(int sampleRate, int channels, int period) {
    close();
    m_hanlde = webrtc::WebRtcAecm_Create();
    if (m_hanlde == nullptr) {
        LOG(error) << "WebRtcAecm_Create() failed.";
        return false;
    }
    if (webrtc::WebRtcAecm_Init(m_hanlde, sampleRate) != 0) {
        LOG(error) << "WebRtcAecm_Init() failed.";
        close();
        return false;
    }

    webrtc::AecmConfig config;
    config.cngMode = webrtc::AecmTrue; // 启用舒适噪声生成
    config.echoMode = 3;               // 回声消除模式，范围是 0-4
    if (WebRtcAecm_set_config(m_hanlde, config) != 0) {
        LOG(error) << "WebRtcAecm_set_config() failed.";
        close();
        return false;
    }
    return true;
}