/*
 * Copyright 2021 MindMotion Microelectronics Co., Ltd.
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include "board_init.h"
#include "mp3_decode.h"
#include "audio_i2s_dma.h"

/*
 * Macros.
 */

#define APP_PCM_BUF_SIZE        (MP3_DECODE_FRAME_SAMPLES * 4 * sizeof(int16_t))
#define APP_PCM_BUF_LEN         (MP3_DECODE_FRAME_SAMPLES * 4)
#define APP_PCM_BUF_HALF_LEN    (APP_PCM_BUF_LEN / 2)

/*
 * Variables.
 */

int16_t pcm_buf[APP_PCM_BUF_LEN];

extern const mp3_decode_if_t mp3_dec_if;
mp3_decode_obj_t mp3_dec_obj;

/*
 * Declerations.
 */

void app_i2s_master_tx_dma_init(void);

/*
 * Functions.
 */
int main(void)
{
    BOARD_Init();

    printf("audio_rom_i2s_mp3_player_basic example.\r\n");

    mp3_decode_init(&mp3_dec_obj, (mp3_decode_if_t*)&mp3_dec_if);

    while(1)
    {
        /* open a mp3 file. */
        mp3_decode_open(&mp3_dec_obj, NULL);

        /* fill the pcm buf. */
        mp3_decode(&mp3_dec_obj, pcm_buf, APP_PCM_BUF_LEN);

        /* init audio. */
        Audio_ClearStatus(AUDIO_STATUS_XFER_HALF | AUDIO_STATUS_XFER_DONE);
        Audio_Setup(mp3_decode_get_sample_rate(&mp3_dec_obj), (uint16_t*)pcm_buf, APP_PCM_BUF_LEN);

        /* play. */
        Audio_Enable(true);
        while (1)
        {
            uint32_t audio_flags = Audio_GetStatus();
            if (0 != (audio_flags & AUDIO_STATUS_XFER_HALF) )
            {
                /* fill the first half pcm buf. */
                if (0 == mp3_decode(&mp3_dec_obj, &pcm_buf[0], APP_PCM_BUF_HALF_LEN) )
                {
                    /* mp3 play done. */
                    break;
                }
                Audio_ClearStatus(AUDIO_STATUS_XFER_HALF);
            }
            else if (0 != (audio_flags & AUDIO_STATUS_XFER_DONE) )
            {
                /* fill the sencond half pcm buf. */
                if (0 == mp3_decode(&mp3_dec_obj, &pcm_buf[APP_PCM_BUF_HALF_LEN], APP_PCM_BUF_HALF_LEN) )
                {
                    /* mp3 play done. */
                    break;
                }
                Audio_ClearStatus(AUDIO_STATUS_XFER_DONE);
            }
            else
            {
                /* dummy loop. */
            }
        }
        /* close the audio. */
        Audio_Enable(false);
        printf("press any key to play audio again.");
        getchar();
    }
}


/* EOF. */
