//Audio driver - STUB VERSION (no audio for ESP-IDF 4.4 compatibility)
//Original code used I2S PDM which requires ESP-IDF 5.x
/*
 * ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * Jeroen Domburg <jeroen@spritesmods.com> wrote this file. As long as you retain
 * this notice you can do whatever you want with this stuff. If we meet some day,
 * and you think this stuff is worth it, you can buy me a beer in return.
 * ----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include <driver/gpio.h>
#include "esp_log.h"
#include "sndhw.h"

//Implement a lock, as we don't want to run the sound callback while
//the main code is sending commands to it as well.
static SemaphoreHandle_t audio_mux;

#define TAG "audio"

snd_cb_t audio_cb;

void sndhw_lock() {
	if (audio_mux) {
		xSemaphoreTake(audio_mux, portMAX_DELAY);
	}
}

void sndhw_unlock() {
	if (audio_mux) {
		xSemaphoreGive(audio_mux);
	}
}

//make this equal to the imf tick rate so the music sounds good
#define SND_CHUNKSZ 560

void audio_task(void *arg) {
	int16_t snd_in[SND_CHUNKSZ]={0};
	while (1) {
		//Get a chunk of audio data from the source...
		if (audio_mux) {
			xSemaphoreTake(audio_mux, portMAX_DELAY);
		}
		if (audio_cb) {
			audio_cb((uint8_t*)snd_in, sizeof(snd_in)/2);
		}
		if (audio_mux) {
			xSemaphoreGive(audio_mux);
		}
		// Simulate audio timing (11025 Hz sample rate, mono 16-bit)
		vTaskDelay(pdMS_TO_TICKS(SND_CHUNKSZ * 1000 / 11025));
	}
}


void sndhw_init(int samprate, snd_cb_t cb) {
	audio_mux=xSemaphoreCreateMutex();
	audio_cb=cb;
	xTaskCreatePinnedToCore(&audio_task, "snd", 8*1024, NULL, 3, NULL, 1);
	ESP_LOGI(TAG, "Audio stub initialized (no sound output - ESP-IDF 4.4 compatibility).");
}
