/*This file is prepared for Doxygen automatic documentation generation.*/
/*! \file ******************************************************************
 *
 * \brief Audio player main file
 *
 * - Compiler:           IAR EWAVR32 and GNU GCC for AVR32
 * - Supported devices:  All AVR32 devices can be used.
 * - AppNote:
 *
 * \author               Atmel Corporation: http://www.atmel.com \n
 *                       Support and FAQ: http://support.atmel.no/
 *
 ***************************************************************************/

/* Copyright (c) 2009 Atmel Corporation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. The name of ATMEL may not be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an Atmel
 * AVR product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
 *
 */
#include <stddef.h>
#include <stdio.h>

#include <avr32/io.h>
#include "compiler.h"
#include "board.h"
#include "intc.h"
#include "pm.h"
#include "flashc.h"
#include "gpio.h"

#if (defined __AT32UC3A3256__) || (defined __AVR32_UC3A3256__)
#include "twim.h"
#else // use the standard TWI module on UC3A0x and UC3A1x
#include "twi.h"
#endif

#if (defined __GNUC__) && (defined __AVR32__)
# include "nlao_cpu.h"
# include "nlao_usart.h"
#elif __ICCAVR32__
# include "usart.h"
#endif

#include "com_task.h"
#include "audio_interface.h"
#include "audio_mixer.h"
#include "clocks.h"

#include "conf_audio_mixer.h"
#include "conf_audio_interface.h"
#include "conf_audio_player.h"

#if DEFAULT_DACS == AUDIO_MIXER_DAC_ABDAC
# include "tpa6130.h"
# include "conf_tpa6130.h"
#elif DEFAULT_DACS == AUDIO_MIXER_DAC_AIC23B
# include "tlv320aic23b.h"
#endif


#if (defined __GNUC__) && (defined __AVR32__)

/*! \brief Replaces Newlib's implementation of the standard \c wcstombs function
 *         because of portability issues with \c wchar_t.
 *
 * \warning This function must be used with the `-fshort-wchar' code generation
 *          option.
 */
size_t wcstombs(char *s, const wchar_t *pwcs, size_t n)
{
  size_t count = 0;

  while (n--)
  {
    if ((*s++ = (char)*pwcs++) == '\0')
      break;
    count++;
  }

  return count;
}

#endif


/*! \brief Initializes MCU exceptions.
 */
static void init_exceptions(void)
{
#if (defined __GNUC__) && (defined __AVR32__)
  // Import the Exception Vector Base Address.
  extern void _evba;

  // Load the Exception Vector Base Address in the corresponding system
  // register.
  Set_system_register(AVR32_EVBA, (int)&_evba);
#endif

  // Enable exceptions globally.
  Enable_global_exception();
}


/*! \brief Initializes the HSB bus matrix
 */
static void init_hmatrix(void)
{
  // For the internal-flash HMATRIX slave, use last master as default.
  union
  {
    unsigned long                 scfg;
    avr32_hmatrix_scfg_t          SCFG;
  } u_avr32_hmatrix_scfg = {AVR32_HMATRIX.scfg[AVR32_HMATRIX_SLAVE_FLASH]};
  u_avr32_hmatrix_scfg.SCFG.defmstr_type = AVR32_HMATRIX_DEFMSTR_TYPE_LAST_DEFAULT;
  AVR32_HMATRIX.scfg[AVR32_HMATRIX_SLAVE_FLASH] = u_avr32_hmatrix_scfg.scfg;
}

/*! \brief Initializes the heap.
 */
static void init_heap(void)
{
#ifdef _DEBUG
  #if __GNUC__ && __AVR32__

  // Import the location of the heap.
  extern void __heap_start__;
  extern void __heap_end__;

  U32 *p_heap_word;

  // Initialize the heap.
  for (p_heap_word = &__heap_start__; (void *)p_heap_word < &__heap_end__; p_heap_word++)
    *p_heap_word = DEFAULT_HEAP_INIT_WORD;

  #elif __ICCAVR32__

  // Import the location of the heap.
  #pragma segment = "HEAP"

  U32 *p_heap_word;

  // Initialize the heap.
  for (p_heap_word = __segment_begin("HEAP"); (void *)p_heap_word < __segment_end("HEAP"); p_heap_word++)
    *p_heap_word = DEFAULT_HEAP_INIT_WORD;

  #endif
#endif
}

/*! \brief Initializes MCU interrupts.
 */
static void init_interrupts(void)
{
  // Initialize interrupt handling.
  INTC_init_interrupts();
  // Enable interrupts globally.
  Enable_global_interrupt();
}


/*! \brief Low-level initialization routine called during startup, before the
 *         \ref main function.
 */
#if (defined __GNUC__) && (defined __AVR32__)
int _init_startup(void)
#elif (defined __ICCAVR32__)
int __low_level_init(void)
#endif
{
  init_exceptions();
  init_hmatrix();
  init_sys_clocks();
#if (defined __GNUC__) && (defined __AVR32__)
  // Give the used PBA clock frequency to Newlib Addon library, so it can work properly.
  set_cpu_hz(FPBA_HZ);
#endif
  init_heap();
  init_interrupts();

  // EWAVR32: Request initialization of data segments.
  // GCC: Don't-care value.
  return 1;
}

/*! \brief Initializes the two-wire interface.
 */
static void init_twi(void)
{
#if(DEFAULT_DACS == AUDIO_MIXER_DAC_ABDAC)
  const gpio_map_t TPA6130_TWI_GPIO_MAP =
  {
    {TPA6130_TWI_SCL_PIN, TPA6130_TWI_SCL_FUNCTION},
    {TPA6130_TWI_SDA_PIN, TPA6130_TWI_SDA_FUNCTION}
  };

  const twi_options_t TPA6130_TWI_OPTIONS =
  {
    .pba_hz = FPBA_HZ,
    .speed = TPA6130_TWI_MASTER_SPEED,
    .chip = TPA6130_TWI_ADDRESS
  };

  // Assign I/Os to TWI.
  gpio_enable_module(TPA6130_TWI_GPIO_MAP,
    sizeof(TPA6130_TWI_GPIO_MAP) / sizeof(TPA6130_TWI_GPIO_MAP[0]));

  // Initialize as master.
  twi_master_init(TPA6130_TWI, &TPA6130_TWI_OPTIONS);

#elif(DEFAULT_DACS == AUDIO_MIXER_DAC_AIC23B)
  static const gpio_map_t AIC23B_TWI_GPIO_MAP =
  {
    {AIC23B_TWI_SCL_PIN, AIC23B_TWI_SCL_FUNCTION},
    {AIC23B_TWI_SDA_PIN, AIC23B_TWI_SDA_FUNCTION}
  };

  static const twi_options_t AIC23B_TWI_OPTIONS =
  {
    .pba_hz = FPBA_HZ,
    .speed  = AIC23B_TWI_MASTER_SPEED,
    .chip   = AIC23B_TWI_ADDRESS
  };

  gpio_enable_module(AIC23B_TWI_GPIO_MAP,
                     sizeof(AIC23B_TWI_GPIO_MAP) / sizeof(AIC23B_TWI_GPIO_MAP[0]));
  twi_master_init(AIC23B_TWI, &AIC23B_TWI_OPTIONS);

#endif // end (DEFAULT_DACS == AUDIO_MIXER_DAC_AIC23B)
}

/*! \brief Main function of the audio player.
 * Refer to AVR32709: AVR32 UC3 Audio Decoder Over USB application note.
 */
int main(void)
{
  // Configure standard I/O streams as unbuffered.
#if (defined __GNUC__) && (defined __AVR32__)
  setbuf(stdin, NULL);
#endif
  setbuf(stdout, NULL);

  init_twi();
  audio_mixer_enable_dacs(DEFAULT_DACS);
  audio_mixer_dacs_start(DEFAULT_DAC_SAMPLE_RATE_HZ,
                         DEFAULT_DAC_NUM_CHANNELS,
                         DEFAULT_DAC_BITS_PER_SAMPLE,
                         DEFAULT_DAC_SWAP_CHANNELS); 
  task_init();
  ai_init();
  com_task_init();

  while (TRUE)
  {
    ai_task();
    com_task();
    task();
  }
}
