#include <Arduino.h>
#include "driver/i2s.h"

#define I2S_PORT I2S_NUM_0
#define SAMPLE_RATE 16000
#define BUFFER_SIZE 256
#define BLOCK_FRAMES 128   // 128 stereo frames = 512 bytes
const uint16_t MAGIC = 0xABCD;  // 2‑byte header marker


void setup() {
  Serial.begin(1500000);

  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_32BIT,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
    .communication_format = I2S_COMM_FORMAT_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 4,
    .dma_buf_len = BUFFER_SIZE,
    .use_apll = false,
    .tx_desc_auto_clear = false,
    .fixed_mclk = 0
  };

  i2s_pin_config_t pin_config = {
    .bck_io_num = 6,
    .ws_io_num = 7,
    .data_out_num = I2S_PIN_NO_CHANGE,
    .data_in_num = 8
  };

  i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_PORT, &pin_config);

  Serial.println("I2S microphone initialized!");
}

void loop() {
  int32_t buffer[BUFFER_SIZE];
  size_t bytes_read;

  // Collect one I2S DMA buffer
  i2s_read(I2S_PORT, (void*)buffer, sizeof(buffer), &bytes_read, portMAX_DELAY);

  int samples = bytes_read / 4;  // 32-bit words
  static int16_t block[BLOCK_FRAMES * 2]; // stereo frames
  static int blockIndex = 0;

  for (int i = 0; i < samples; i += 2) {
    int32_t right32 = buffer[i];
    int32_t left32  = buffer[i + 1];

    int16_t right16 = (int16_t)(right32 >> 14);
    int16_t left16  = (int16_t)(left32 >> 14);

    block[blockIndex++] = left16;
    block[blockIndex++] = right16;

    if (blockIndex >= BLOCK_FRAMES * 2) {
      // Send header
      Serial.write((uint8_t*)&MAGIC, sizeof(MAGIC));
      // Send block
      Serial.write((uint8_t*)block, BLOCK_FRAMES * 4);
      blockIndex = 0;
    }
  }
}
