#include "driver/i2s_pdm.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_timer.h"

static const char *TAG = "MIC";

// 定义引脚
#define PDM_RX_CLK_IO  GPIO_NUM_5
#define PDM_RX_DIN_IO  GPIO_NUM_6

i2s_chan_handle_t rx_handle;

void i2s_pdm_rx_init(void)
{
    /* 1. 分配 I2S RX 通道 */
    i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
    ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, NULL, &rx_handle));

    /* 2. 初始化通道为 PDM RX 原始格式模式 */
    i2s_pdm_rx_config_t pdm_rx_cfg = {
        .clk_cfg  = I2S_PDM_RX_CLK_DEFAULT_CONFIG(1024000),
        .slot_cfg = I2S_PDM_RX_SLOT_RAW_FMT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO),
        .gpio_cfg = {
            .clk = PDM_RX_CLK_IO,
            .din = PDM_RX_DIN_IO,
            .invert_flags = {
                .clk_inv = false,
            },
        },
    };
    ESP_ERROR_CHECK(i2s_channel_init_pdm_rx_mode(rx_handle, &pdm_rx_cfg));

    /* 3. 启用通道 */
    ESP_ERROR_CHECK(i2s_channel_enable(rx_handle));
}

void i2s_pdm_rx_read(void)
{
    // 读取 20ms 的数据
    // 1,024,000 bits/s ÷ 16 bits per unit = 64,000 units/s
    // 20ms × 64,000 = 1,280 个 16-bit 数据单元 = 2,560 bytes
    int16_t buf[1280];
    size_t bytes_to_read = sizeof(buf); // 2560 bytes
    size_t bytes_read = 0;

    ESP_ERROR_CHECK(i2s_channel_read(rx_handle, buf, bytes_to_read, &bytes_read, portMAX_DELAY));
    if (bytes_read != bytes_to_read) {
	    ESP_LOGW(TAG, "Partial read: %d/%d bytes", bytes_read, bytes_to_read);
    }
}

static void i2s_reader_task(void *arg)
{
	while (1) {
		int64_t t1 = esp_timer_get_time();
		i2s_pdm_rx_read();
		int64_t t2 = esp_timer_get_time();
		ESP_LOGI(TAG, "dt=%lld us", t2 - t1);
	}
}

void pdm_mic_init(void)
{
	i2s_pdm_rx_init();

	xTaskCreate(i2s_reader_task, "i2s_reader", 4096, rx_handle, 15, NULL);
}
