/*******************************************************************
File: waveplayer.c
Date: 29-September-2025
Author: Peter Spindler
Description: Functions to play a wave file. Requires functions from audio.c
 ********************************************************************/
#include "stm32f7xx_hal.h"
#include "audio.h"

#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"

#include "ff.h"
#include "fatfs.h"

#include "audio.h"
#include "gui.h"
#include "display.h"

FIL WaveFile;
#define AUDIO_BUFFER_SIZE_WORDS  (1024*8)
uint16_t Audio_Buffer[AUDIO_BUFFER_SIZE_WORDS];

void Player_Start( const char *Filename ) {
	FRESULT res;
	if( (res=f_open(&WaveFile, Filename , FA_READ )) != FR_OK) {
		printf("Error: Can't open audio file %s: %d\n", Filename, res);
		return;
	}
	printf("Open wavefile %s: successful\n", Filename );

	Audio_SetFrequency(22050);
	
    /* ToDo: Fill audio buffer completely */
    
	Audio_Play( (uint8_t*) Audio_Buffer, sizeof(Audio_Buffer)/2 );
}

void Player_Stop( void ) {
    Audio_Stop();
	f_close(&WaveFile);
}

// Player_HalfTransfer_CallBack: called from DMA2_Stream4-ISR if first half of audio buffer has been transferred to SAI2
void Player_HalfTransfer_CallBack( void ) {
    /* ToDo: Inform Player_Task about first half*/
}

// Player_CompleteTransfer_CallBack: called from DMA2_Stream4-ISR if second half of audio buffer has been transferred to SAI2
void Player_CompleteTransfer_CallBack( void ) {
    /* ToDo: Inform Player_Task about second half*/
}

static void Player_Task( void *arguments ) {
	/* ToDo */
}

void Player_Init( void ) {
	portENABLE_INTERRUPTS(); // Workaround to re-enable interrupts after FreeRTOS functions
    // 70: initial volume, 44100: initial sampling frequency
	if( Audio_Init(OUTPUT_DEVICE_AUTO,70,44100) != AUDIO_OK ) {
		printf("Error: Can't init audio!\n");
	}
	xTaskCreate(Player_Task,"Player", 512,NULL,0,NULL);
}
