#include <driver/i2s.h>

i2s_port_t i2s_num = I2S_NUM_0; // i2s port number (Built-in DAC functions are only supported on I2S0 for current ESP32 chip, purportedly)
i2s_config_t i2s_config;
unsigned char i2s_running = 0;
static unsigned char audioBufferFilled=0;

void configure_i2s(int newSampleRate, uint16_t newDmaBufLen)
{

    ESP_LOGE(TAG, "Setup I2S hardware");
    ESP_LOGE(TAG, "Sample rate: %d", newSampleRate);
    ESP_LOGE(TAG, "noSamples per packet %d", newDmaBufLen);
    static const i2s_pin_config_t pin_config = {
        .bck_io_num = 15,
        .ws_io_num = 13,
        .data_out_num = 2,
        .mck_io_num = I2S_PIN_NO_CHANGE,
        .data_in_num = I2S_PIN_NO_CHANGE};

    i2s_config.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
    i2s_config.sample_rate = newSampleRate;                 // This must match VBAN Outgoing Stream SampleRate parameter
    i2s_config.bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT; // apparently built-in DAC only enabled on I2S0 which only allows 16bit?
    i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
    i2s_config.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_MSB);
    i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; // default interrupt priority
    i2s_config.dma_buf_count = DMA_BUFF_COUNT;
    i2s_config.dma_buf_len = newDmaBufLen;
    i2s_config.use_apll = false;
    // i2s_config.tx_desc_auto_clear = true;

    if (i2s_running == 255)
    {
        ESP_ERROR_CHECK(i2s_stop(i2s_num));
        ESP_ERROR_CHECK(i2s_driver_uninstall(i2s_num));
    }

    ESP_ERROR_CHECK(i2s_driver_install(i2s_num, &i2s_config, 0, NULL)); // install and start i2s driver
    ESP_ERROR_CHECK(i2s_set_pin(i2s_num, &pin_config));
    // ESP_ERROR_CHECK( i2s_set_dac_mode(I2S_DAC_CHANNEL_LEFT_EN)  );  // RIGHT=GPIO25, LEFT=GPIO26
    ESP_ERROR_CHECK(i2s_zero_dma_buffer(i2s_num));
    i2s_set_clk(i2s_num, newSampleRate, 32, I2S_CHANNEL_STEREO);
    i2s_running = 255;
    audioBufferFilled = 0;
}