/* mp3_decode.c */

#include <string.h>

#include "mp3_decode.h"

/* file system interface. */
static bool file_open(char * file_name);
static uint32_t file_read(uint8_t * buf, uint32_t buf_size);
static void file_close(void);

/* the location of file data in flash. */
extern const uint8_t mp3_raw[15264];
/* reocrd the file offset. */
static uint32_t file_offset = 0;
/* mp3 buffer for mp3_decode. */
static uint8_t mp3_buf[MP3_DECODE_BUF_MIN_SIZE];

/* the interface of mp3_deocde. */
mp3_decode_if_t mp3_dec_if =
{
    .mp3_buf = mp3_buf,
    .mp3_buf_size = sizeof(mp3_buf),
    .file_open = file_open,
    .file_read = file_read,
    .file_close = file_close,
};

/* open file. */
static bool file_open(char * file_name)
{
    (void)file_name;
    file_offset = 0;
    return true;
}

/* read file. */
static uint32_t file_read(uint8_t * buf, uint32_t buf_size)
{
    uint32_t file_remain = sizeof(mp3_raw) - file_offset;

    if (file_remain < buf_size)
    {
        uint8_t * raw_start = (uint8_t *)mp3_raw + file_offset;
        memcpy(buf, raw_start, file_remain);
        file_offset += file_remain;
        return file_remain;
    }
    else
    {
        uint8_t * raw_start = (uint8_t *)mp3_raw + file_offset;
        memcpy(buf, raw_start, buf_size);
        file_offset += buf_size;
        return buf_size;
    }
}

/* close file. */
static void file_close(void)
{
    file_offset = 0;
}

/* EOF. */
