// Copyright 2024 XMOS LIMITED.
#define DEBUG_PRINT_ENABLE 0
#include "debug_print.h"
// This Software is subject to the terms of the XMOS Public Licence: Version 1.
#include <print.h>
#include <stdio.h>
#include <string.h>
#include <platform.h>
#include <xs1.h>
#include <xcore/chanend.h>
#include <xcore/channel.h>
#include "xc_ptr.h"

#include "xua_conf.h"

#include "share_buffer.h"

extern uint32_t init_eq_data(unsigned sample_freq);

void dnr_exchange_buffer(int32_t *data);

// sample_freq 作为首字发送给 tile[0] 的 dsp_main，用于采样率变化检测和 EQ 初始化
void buffer_exchange(chanend_t c_data, unsigned sampsFromUsbToAudio[], unsigned sampsFromAudioToUsb[], unsigned sample_freq) {
    chan_out_word(c_data, sample_freq);
    chan_out_buf_word (c_data, sampsFromUsbToAudio, 2);
    chan_in_buf_word  (c_data , sampsFromUsbToAudio, 2);
#if DNR_ENABLE == 1
    chan_out_buf_word (c_data, sampsFromAudioToUsb, 2);
    chan_in_buf_word  (c_data , sampsFromAudioToUsb, 2);
#endif
}


void dsp_main (chanend_t c_data) {
    int play_input[NUM_USB_CHAN_OUT];
    int play_output[I2S_CHANS_DAC];
    int mic_input[I2S_CHANS_ADC];
    int mic_output[I2S_CHANS_ADC];
    int count = 0;
    unsigned ch[1] = {2};
#if F1_MUSIC_UAC2 == 1
    unsigned current_sample_freq = 0;
#else
    unsigned current_sample_freq = 48000;
#endif
    while (1) {
        unsigned sample_freq = (unsigned)chan_in_word(c_data);
        chan_in_buf_word (c_data , play_input, 2);

        // 采样率变化：重新初始化 EQ 系数并清空 ring buffer，避免残留状态污染
        if (sample_freq != current_sample_freq && sample_freq != 0) {
            current_sample_freq = sample_freq;
            init_eq_data(sample_freq);
            clear_ring_buffer(0);
            clear_ring_buffer(1);
            clear_ring_buffer(2);
            clear_ring_buffer(3);
            play_output[0] = 0;
            play_output[1] = 0;
        }

        chan_out_buf_word (c_data , play_output, I2S_CHANS_DAC);
#if DNR_ENABLE == 1
        chan_in_buf_word (c_data , mic_input, 2) ;
        chan_out_buf_word (c_data , mic_output, I2S_CHANS_ADC);
#endif
        write_to_ring_buffer(0, play_input[0]);
        write_to_ring_buffer(1, play_input[1]);
        play_output[0] = read_from_ring_buffer(2);
        play_output[1] = read_from_ring_buffer(3);
#if DNR_ENABLE == 1
        dnr_exchange_buffer(mic_input);
        mic_output[0] = mic_input[0];
        mic_output[1] = mic_input[1];
#endif
    }
}
