#include "AudioPlayer.h"

// ===== AudioPlayer Class =====
// This class handles I2S playback. It takes a reference to an AudioBuffer
// object, waits for new data (with a timeout), swaps the buffers, and writes
// the active buffer to I2S.

AudioPlayer::AudioPlayer(AudioBuffer &audioBuffer) : buffer(audioBuffer) {}

void AudioPlayer::start_task() {
  // Create the audio playback task on core 1.
  xTaskCreatePinnedToCore(
      [](void *param) { ((AudioPlayer *)param)->audioTask(); }, "AudioTask",
      4096, this, 1, NULL, AUDIO_TASK_CORE);
}

void AudioPlayer::audioTask() {
  size_t bytesWritten = 0;
  while (true) {
    // Wait up to AUDIO_FRAME_TIME_MS for new audio data.
    if (!buffer.waitForNewData(AUDIO_FRAME_TIME_MS)) {
      // If new data isn't available in time, fill the inactive buffer with
      // silence.
      buffer.fillInactiveBufferWithSilence();
    }
    // Swap the buffers so that the fresh (or silence-filled) data becomes
    // active.
    buffer.swapBuffers();
    // Write the active buffer to I2S (this call blocks until the DMA transfer
    // completes).
    esp_err_t result =
        i2s_write(I2S_NUM, (const char *)buffer.getActiveBuffer(),
                  STEREO_BUFFER_SIZE, &bytesWritten, portMAX_DELAY);
    if (result != ESP_OK) {
      Serial.printf("i2s_write error: %d\n", result);
    }
  }
}