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

#include "wav_decode.h"
#include <stdio.h>

/* open fatfs file. */
bool wav_decode_open(wav_decode_obj_t * obj,char * file_name, uint8_t * buf, uint32_t buf_size)
{
     UINT fatfs_br = 0u;
     uint8_t offset = 0u;

     if (FR_OK != f_open(&(obj->fatfs_file), file_name, FA_READ) )
     {
         return false;
     }

     obj->fatfs_buf = buf;
     obj->fatfs_buf_size = buf_size;

     if (FR_OK != f_read(&(obj->fatfs_file), obj->fatfs_buf, WAV_DECODE_HEAD_BUFFER_SIZE, &fatfs_br))
     {
         return false;
     }

    chunk_riff_def_t *chunk_riff;
    chunk_fmt_def_t  *chunk_fmt;
    chunk_fact_def_t *chunk_fact;
    chunk_data_def_t *chunk_data;

    chunk_riff = (chunk_riff_def_t *)(obj->fatfs_buf);
    chunk_fmt  = (chunk_fmt_def_t  *)(obj->fatfs_buf + 12);
    chunk_fact = (chunk_fact_def_t *)(obj->fatfs_buf + 12 + 8 + chunk_fmt->sub_chunk1_size);

    if((chunk_fact->chunk_id == 0x74636166) || (chunk_fact->chunk_id == 0x5453494C))
    {
        chunk_data = (chunk_data_def_t *)(obj->fatfs_buf + 12 + 8 + chunk_fmt->sub_chunk1_size + 8 + chunk_fact->chunk_size);

        offset = 12 + 8 + chunk_fmt->sub_chunk1_size + 8 + chunk_fact->chunk_size;
    }
    else
    {
        chunk_data = (chunk_data_def_t *)(obj->fatfs_buf + 12 + 8 + chunk_fmt->sub_chunk1_size);

        offset = 12 + 8 + chunk_fmt->sub_chunk1_size;
    }

    if(chunk_riff->format == 0x45564157 && chunk_data->sub_chunk2_id == 0x61746164)
    {
         obj->audio_format    = chunk_fmt->audio_format;
         obj->channel         = chunk_fmt->num_of_channels;
         obj->sample_rate     = chunk_fmt->sample_rate;
         obj->bits_per_sample = chunk_fmt->bits_per_sample;
         obj->bit_rate        = chunk_fmt->byte_rate * 8;
         obj->block_align     = chunk_fmt->block_align;

         obj->data_size  = chunk_data->sub_chunk2_size;
         obj->data_start_offset = offset;
         obj->total_second = obj->data_size;
    }
    else
    {
        return false;
    }
     return true;
}

/* read fatfs file. */
bool wav_decode_read(wav_decode_obj_t * obj, uint16_t * buf, uint32_t buf_size)
{
    UINT fat_br = 0u;

    if (FR_OK != f_read(&(obj->fatfs_file), buf, buf_size, &fat_br) )
    {
        return false;
    }

    //obj->current_second += fat_br;

    if ( (fat_br <= 0) || (fat_br < buf_size))
    {
        return false; /* reach to the end of file. */
    }
    
    return true;
}

/* close fatfs file. */
void wav_decode_close(wav_decode_obj_t * obj)
{
    f_close(&(obj->fatfs_file) );
}

/* EOF. */
