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

#ifndef __WAV_DECODE_H__
#define __WAV_DECODE_H__

#include <stdint.h>
#include <stdbool.h>
#include <string.h>

#include "ff.h"

#define WAV_DECODE_HEAD_BUFFER_SIZE 512u

/* RIFF Chunk. */
typedef struct __attribute__ ((aligned (1)))
{
    /* fixed as RIFF. */
    uint32_t chunk_id;

    /* collection size. */
    uint32_t chunk_size;

    /* wav format 0x45564157 */
    uint32_t format;

} chunk_riff_def_t;

/* FMT Chunk. */
typedef struct __attribute__ ((aligned (1)))
{
    /* fixed as FMT. */
    uint32_t sub_chunk1_id;

    /* subcollection size. */
    uint32_t sub_chunk1_size;

    /* audio format. */
    uint16_t audio_format;

    /* channel numbers. */
    uint16_t num_of_channels;

    /* sample rate. */
    uint32_t sample_rate;

    /* byte rate. */
    uint32_t byte_rate;

    /* block alignment. */
    uint16_t block_align;

    /* single sample data size. */
    uint16_t bits_per_sample;

} chunk_fmt_def_t;

/* FACT Chunk. */
typedef struct __attribute__ ((aligned (1)))
{
    /* fixed as FACT. */
    uint32_t chunk_id;

    /* subcollection size. */
    uint32_t chunk_size;

    /* sample numbers. */
    uint32_t num_of_sample;

}chunk_fact_def_t;

/* DATA chunk. */
typedef struct __attribute__ ((aligned (1)))
{
    /* fixed as DATA. */
    uint32_t sub_chunk2_id;

    /* subcollection size. */
    uint32_t sub_chunk2_size;

}chunk_data_def_t;

/* WAVE header. */
typedef struct __attribute__ ((aligned (1)))
{
    /* RIFF chunk. */
    chunk_riff_def_t chunk_riff;

    /* FMT chunk. */
    chunk_fmt_def_t  chunk_fmt;

    /* DATA chunk. */
    chunk_data_def_t chunk_data;

} wav_header_def_t;

/* WAVE play control. */
typedef struct
{
    /* audio about */
    uint16_t audio_format;

    uint16_t channel;

    uint16_t block_align;

    uint32_t data_size;

    uint32_t bit_rate;

    uint32_t sample_rate;

    uint16_t bits_per_sample;

    /* audio time */
    uint32_t total_second;

    uint32_t current_second;

    /* fatfs about. */
    FIL      fatfs_file;

    /* buffer for fatfs. */
    uint8_t  *fatfs_buf;

    uint32_t fatfs_buf_size;

    /* wav header about. */
    wav_header_def_t wav_header;

    /* status about. */
    uint32_t data_start_offset;

} wav_decode_obj_t;

bool wav_decode_open(wav_decode_obj_t * obj, char * file_name, uint8_t * buf, uint32_t buf_size);
bool wav_decode_read(wav_decode_obj_t * obj, uint16_t * buf, uint32_t buf_len);
void wav_decode_close(wav_decode_obj_t * obj);

#endif /* __WAV_DECODE_H__ */
