// Copyright 2011-2023 XMOS LIMITED.
//
// This Software is subject to the terms of the XMOS Public Licence: Version 1.

#if UART_DEBUG || DEBUG_MEMORY_LOG_ENABLED
#define DEBUG_PRINT_ENABLE 1
#endif

#include <xs1.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <platform.h>
#include <string.h>
#include "dnr_dsp_buf.h"
#include "aizip_dnr.h"
#include "debug_print.h"
#include "flash.h"
#include "swlock.h"

// Global flash lock defined in lfs_services.c — protects all flash hardware access
extern swlock_t flash_lock;

//for AGC
//static agc_stage_ctx_t DWORD_ALIGNED agc_stage_state = {};

#if DNR_ENABLE == 1
static unsigned __attribute__((aligned (4))) dsp_dnr_frame_buf[BUF_SLOT_NUM][DSP_CH_NUM][DNR_DSP_FRAME_SIZE];

unsigned sample_in_buf_slot=0;
unsigned processing_buf_slot=2;
unsigned sample_out_buf_slot=1;


void dsp_buf_init()
{
    sample_in_buf_slot=0;
    sample_out_buf_slot=1;
    processing_buf_slot=2;
}

static void buf_slot_inc(unsigned* buf_slot_input)
{
    if(*buf_slot_input == BUF_SLOT_NUM-1){
        *buf_slot_input = 0;
    }
    else{
        *buf_slot_input = *buf_slot_input+1;
    }
}

void buf_slot_rotate()
{
    buf_slot_inc(&sample_in_buf_slot);
    buf_slot_inc(&sample_out_buf_slot);
    buf_slot_inc(&processing_buf_slot);
}

void write_to_sample_in_buf(unsigned data, unsigned index, unsigned ch)
{
    dsp_dnr_frame_buf[sample_in_buf_slot][ch][index]=data;
}

void read_from_sample_out_buf(unsigned* read_data, unsigned index, unsigned ch)
{
    *read_data = dsp_dnr_frame_buf[sample_out_buf_slot][ch][index];
}
#if DNR_11MS
int8_t buffer[4208] __attribute__((aligned(4)));
int8_t buffer2[31136] __attribute__((aligned(4)));
#else
int8_t buffer[21416] __attribute__((aligned(4)));
int8_t buffer2[31712] __attribute__((aligned(4)));
#endif
azp_dnr_param_t pram = {
    .buffer1 = buffer,
    .buffer1_size = sizeof(buffer),
    .buffer2 = buffer2,
    .buffer2_size = sizeof(buffer2),
    .sample_rate = 48000};

unsigned g_dnr_init_flag = 0;
void Aizip_DNR_init(void)
{
    delay_microseconds(10000);
   // setFlashPortPins(XS1_PORT_1B,XS1_PORT_1C,XS1_PORT_4B, XS1_CLKBLK_3);

    swlock_acquire(&flash_lock);
    int sta = AI_DNR_init(&pram);
    swlock_release(&flash_lock);
    g_dnr_init_flag = 1;
    debug_printf("AI_DNR_init status %d\n", sta);
}

float g_dnr_level = -200;

void dnr_set_mode(unsigned char mode)
{
    if(mode == 0)
        g_dnr_level = 0;
    else
        g_dnr_level = -200;
}

// 按HID强度值（0=关，2-100步进2）设置降噪深度：strength * 2 → dB（100→-200dB）
void dnr_set_strength_level(unsigned char strength)
{
    if (strength == 0)
        g_dnr_level = 0;
    else
        g_dnr_level = -(float)(strength * 2);
}

void start_dsp_processing(void)
{
    setNoisy_mix_factor(g_dnr_level);
    AI_DNR_Processing((int32_t *)&dsp_dnr_frame_buf[processing_buf_slot][0][0]);
}

#endif