/* ----------------------------------------------------------------------------
*         ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2012, 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:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: 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
* 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.
* ----------------------------------------------------------------------------
*/

/**
 *  \page Continuous_Capture Continuous Capture Demo
 *
 *  \section Purpose
 *
 *  This demo is for evaluating the performance when capturing and displaying
 *  are always on. Both monochrome mode and color mode are provided.
 *
 *  \section Requirements
 *
 *  This package can only be used with sam4s-wpir-rd.
 *
 *  \section Description
 *
 *  The demo continously captures from image sensor and displays to LCD if
 *  mounted.
 *
 *  BP1 is used to switch the mode between black/white and color mode.
 *  Each time switching from one mode to another, the system will be re-configured
 *  to support different output which mainly includes half sampling and color
 *  conversion from YUV to RGB for displaying.
 *
 *  \section Usage
 *
 *  -# Build the program and download it inside the evaluation board. Please
 *     refer to the
 *     <a href="http://www.atmel.com/dyn/resources/prod_documents/doc6224.pdf">
 *     SAM-BA User Guide</a>,
 *     application note or to the
 *     <a href="ftp://ftp.iar.se/WWWfiles/arm/Guides/EWARM_UserGuide.ENU.pdf">
 *     IAR EWARM User Guide</a>,
 *     depending on your chosen solution.
 *  -# After downloading through SAM-BA or IAR flash loader, run the application.
 *  -# Press BP1 to switch between b/w and clor mode.
 */

/** \file
 *
 *  This file contains all the specific code for the Continuous_Capture.
 */

/*----------------------------------------------------------------------------
*        Headers
*----------------------------------------------------------------------------*/

#include "board.h"

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

/*----------------------------------------------------------------------------
*        Local definitions
*----------------------------------------------------------------------------*/

/** lcd debug output support, uncomment to remove */
#define LCD_DEBUG_OUT

/*macro to measure Frame rate, comment if it's not used*/
#define FRAME_RATE_MEASURE

#define IMAGE_WIDTH     (320)
#define IMAGE_HEIGHT    (240)
/** the captured data length per line in different color mode,double the size
in YUV full output*/
#define IMAGE_LINE_COLORED    (IMAGE_WIDTH * 2)
#define IMAGE_LINE_MONO  (IMAGE_WIDTH)

#define PIO_PCMR_DSIZE_8 (0x0<<4)
#define PIO_PCMR_DSIZE_16 (0x1<<4)
#define PIO_PCMR_DSIZE_32 (0x2<<4)

#define SRAM_BASE (0x60000000)
#define CAP_DEST  (SRAM_BASE)

/** TWI clock frequency in Hz (400KHz) */
#define TWCK            100000

/** for power on or off*/
#define ON  true
#define OFF false

/** The output formats supported by the sensor*/
typedef enum {
    OUT_RGB,
    OUT_YUV
}OUT_FMT;

/** the default output mode is YUV422*/
#define DEFAULT_SENSOR_YUV422

/** uncomment for monochrome output*/
#define DEFAULT_MODE_COLORED

/*----------------------------------------------------------------------------
*        Local variables
*----------------------------------------------------------------------------*/
/** the output format of image sensor*/
OUT_FMT out_format = OUT_YUV;
/** the output color mode of image sensor*/
volatile PIO_OUT_MODE current_mode = PIO_OUT_COLOR;
volatile PIO_OUT_MODE next_mode = PIO_OUT_COLOR;

/** is displaying needed*/
bool isDisplayed = true;

/** capturing destination buffer*/
uint8_t *cap_dest_buf;

/** displaying destination buffer, RESERVED*/
uint8_t *disp_dest_buf;

/** cpaturing rows*/
uint16_t cap_rows = IMAGE_HEIGHT;

/** cap line length*/
uint16_t cap_line = IMAGE_LINE_COLORED;

/** VSYNC flag*/
volatile bool vsync_flag = false;

/** HSYNC flag RESERVED*/
bool hsync_flag = false;

/** TWI driver*/
static Twid twid;

/** BP1*/
const Pin pinBP1 = PIN_PUSHBUTTON_1;

/** use PIOA_5 for duration test*/
const Pin pinTest = { 1<<5,PIOA,ID_PIOA,PIO_OUTPUT_1,PIO_DEFAULT};

/*const Pin pinHSYNC = PIN_OV_HSYNC;*/

/** vsync pin*/
const Pin pinVSYNC = PIN_OV_VSYNC;

/*----------------------------------------------------------------------------
*        Local functions
*----------------------------------------------------------------------------*/
/**
 * \brief Set default master access for speed up.
 * Here assume code is put at flash, data is put at sram.
 * The PDC transfer target at SRAM
 */
static void _SetDefaultMaster( void )
{
    Matrix *pMatrix = MATRIX;

    /* Set default master: SRAM (slave 0)-> Cortex-M4 System (Master 1)*/
    pMatrix->MATRIX_SCFG[0] |= ((1 << 18) & MATRIX_SCFG_FIXED_DEFMSTR_Msk) | /* Master 1 */
                               ((2 << 16) & MATRIX_SCFG_DEFMSTR_TYPE_Msk);   /* Fixed Default Master */

    /* Set default master: Internal flash (slave 2) -> Cortex-M4 Instruction/Data (Master 0)*/
    pMatrix->MATRIX_SCFG[2] |= ((0 << 18) & MATRIX_SCFG_FIXED_DEFMSTR_Msk) | /* Master 0 */
                               ((2 << 16) & MATRIX_SCFG_DEFMSTR_TYPE_Msk);   /* Fixed Default Master */

    /* Set default master: EBI (slave 3) -> PDC (Master 2)*/
    pMatrix->MATRIX_SCFG[3] |= ((2 << 18) & MATRIX_SCFG_FIXED_DEFMSTR_Msk) | /* Master 2 */
                               ((2 << 16) & MATRIX_SCFG_DEFMSTR_TYPE_Msk);   /* Fixed Default Master */
}

/** reconfigure PIO for color or mono mode*/
static void _Capture_Reconfigure(void)
{
    PIO_Capture_Switch(PIOA,OFF);

    /* initialize PIODC*/
    PIODC_Capture_Init(PIOA, ID_PIOA, current_mode);

    /** intialize capturing line*/
    if(current_mode == PIO_OUT_COLOR)
    {
        cap_line = IMAGE_LINE_COLORED;
    }
    else if(current_mode == PIO_OUT_MONO)
    {
        cap_line = IMAGE_LINE_MONO;
    }
    else
    {
        cap_line = IMAGE_LINE_COLORED;
    }

    /* reset PDC channel*/
    PIO_RX_Disable(PIOA);
    PIO_RCR_Set(PIOA, 0);
    PIO_RNCR_Set(PIOA, 0);
}

/** entry for capturing*/
static void _DoCapture(void)
{
    uint8_t *buf;

    /* set capturing destination address*/
    cap_dest_buf = (uint8_t*)CAP_DEST;

    buf = cap_dest_buf;

    cap_rows = IMAGE_HEIGHT;

    /* enable vsync interrupt*/
    PIO_EnableIt(&pinVSYNC);

    /* sync with flag*/
    while(!vsync_flag);

    /* disable first*/
    PIO_DisableIt(&pinVSYNC);

    PIO_Capture_Switch(PIOA,ON);

    /* only using Vsync*/
    PIO_CaptureToBuffer(PIOA,buf, (cap_line * cap_rows)>>2);

    while(!PIO_Capture_BUFF(PIOA));

    PIO_Capture_Switch(PIOA,OFF);

    /* clear vsync flag*/
    vsync_flag = false;
}

/** intialize LCD for debugging output*/
static void _Init_LCD(void)
{
    /* Initialize LCD */
    LCDD_Initialize();
    LCD_On();
}


static void _DrawFrame_YUV_BW8( void )
{
    volatile uint32_t dwCursor ;
    uint8_t *pucData ;

    pucData=(uint8_t*)cap_dest_buf ;

    LCD_SetDisplayLandscape(0);

    LCD_SetWindow(0,0,IMAGE_HEIGHT,IMAGE_WIDTH);
    LCD_SetCursor(0,0) ;
    LCD_WriteRAM_Prepare() ;
    for ( dwCursor=IMAGE_WIDTH*IMAGE_HEIGHT ; dwCursor != 0 ; dwCursor-- ,pucData++)
    {
        // Black and White using Y
        LCD_WriteRAMByte( *pucData ) ;
        LCD_WriteRAMByte( *pucData ) ;
        LCD_WriteRAMByte( *pucData ) ;

    }
}
static inline uint8_t _clip( int32_t i )
{
    if ( i > 255 )
    {
        return 255 ;
    }

    if ( i < 0 )
    {
        return 0 ;
    }

    return (uint8_t)i ;
}



static void _DrawFrame_YUV_ColorInt( void )
{
    uint32_t dwCursor ;
    int32_t C ;
    int32_t D ;
    int32_t E ;
    int32_t dw1_1 ;
    int32_t dw1_2 ;
    int32_t dw1_3 ;
    uint8_t* pucData ;

    pucData=(uint8_t*)cap_dest_buf ;

    LCD_SetDisplayLandscape(0);
    LCD_SetWindow( 0, 0,IMAGE_HEIGHT ,IMAGE_WIDTH  ) ;

    LCD_SetCursor( 0,0 ) ;
    LCD_WriteRAM_Prepare() ;

    for ( dwCursor=IMAGE_WIDTH*IMAGE_HEIGHT ; dwCursor != 0 ; dwCursor-=2, pucData+=4 )
    {
        C=pucData[0] ; // Y1
        C-=16 ;
        D=pucData[3] ; // U
        D-=128 ;
        E=pucData[1] ; // V
        E-=128 ;

        dw1_1=516*D+128 ;
        dw1_2=-100*D-208*E+128 ;
        dw1_3=409*E+128 ;

        // BLUE
        LCD_WriteRAMByte( _clip(( 298 * C + dw1_1 ) >> 8) ) ;
        // GREEN
        LCD_WriteRAMByte( _clip(( 298 * C + dw1_2 ) >> 8) ) ;
        // RED
        LCD_WriteRAMByte( _clip(( 298 * C + dw1_3 ) >> 8) ) ;

        C=pucData[2] ; // Y2
        C-=16 ;
        LCD_WriteRAMByte( _clip(( 298 * C + dw1_1 ) >> 8) ) ;
        LCD_WriteRAMByte( _clip(( 298 * C + dw1_2 ) >> 8) ) ;
        LCD_WriteRAMByte( _clip(( 298 * C + dw1_3 ) >> 8) ) ;

    }
}

#ifdef LCD_DEBUG_OUT
static void _Display(void)
{
    if(current_mode == PIO_OUT_COLOR)
    {
        _DrawFrame_YUV_ColorInt();
    }
    else
    {
        _DrawFrame_YUV_BW8();
    }
}
#endif



/** turn on or off image sensor power*/
static void _ImageSensor_Switch(bool on)
{
    Pin pinsPower[]={ PINS_OV };
    PIO_Configure(pinsPower,PIO_LISTSIZE(pinsPower));

    if(on)
    {
        PIO_Clear(&pinsPower[0]);
    }
    else
    {
        PIO_Set(&pinsPower[0]);
    }
}

/** Initialize Image Sensor*/
static void _Init_Image_Sensor(const EOV7740_Format eFormat)
{
    static bool bInitialized = false;
    /* backup setting for future use*/
    static uint32_t bk_setting[2]={0};

    /* intitializ Master Clock to xvclk1*/
    Pin pinPCK = PIN_PCK0;
    const Pin pinsTWI[] = {PINS_TWI0};
    Pmc *pmc = (Pmc*) PMC;

    /* Power on*/
    _ImageSensor_Switch(ON);

    /* configure Master Clock*/
    PIO_Configure(&pinPCK,1);

    /* PLLA is 96MHz so that PCK0 is 96MHz/4 = 24MHz*/
    pmc->PMC_PCK[0] = (PMC_PCK_PRES_DIV4 | PMC_PCK_CSS_PLLACLOCK);

    pmc->PMC_SCER = PMC_SCER_PCK0;

    while(!( pmc->PMC_SCSR & PMC_SCSR_PCK0));

    /* twi*/
    PIO_Configure(pinsTWI,PIO_LISTSIZE(pinsTWI));

    PMC_EnablePeripheral(ID_TWI0);

    TWI_ConfigureMaster(TWI0, TWCK, BOARD_MCK);

    TWID_Initialize(&twid, TWI0);

    /* Configure TWI interrupts */
    NVIC_DisableIRQ(TWI0_IRQn);
    NVIC_ClearPendingIRQ(TWI0_IRQn);
    NVIC_SetPriority(TWI0_IRQn, 0);
    NVIC_EnableIRQ(TWI0_IRQn);

    while( ov_init(&twid) == 0 )
    {
        printf("-I- Retry init\n\r");
    }
    printf("-I- Init passed\n\r");

    /* OV7740 configuration */
    ov_configure(&twid, eFormat);

    /* first time*/
    if(!bInitialized)
    {
        Wait(3000);
        ov_sotre_manual(&twid,bk_setting,2);
        bInitialized = true;
    }
    else
    {
        ov_resotre_manual(bk_setting,2);
        ov_configure_manual(&twid);
    }
}

/** interrupt handler for vsync*/
static void _Vsync_Handler(const Pin *pin)
{
    vsync_flag = true;
}

/** intialize fram marker signal response*/
static void _Init_HVSync_Interrupts(void)
{
    PIO_Configure(&pinVSYNC,1);

    PIO_ConfigureIt(&pinVSYNC, _Vsync_Handler);

    /* Enable PIO controller IRQs. */
    NVIC_EnableIRQ(PIOA_IRQn);
}

/** button1 interrupt handler, handle different color mode*/
static void _Button1_Handler(const Pin *pin)
{
    if( PIO_OUT_COLOR == current_mode)
    {
        next_mode = PIO_OUT_MONO;
    }
    else
    {
        next_mode = PIO_OUT_COLOR;
    }

}

/** initialize pushbutton for state transition*/
static void _Init_Pushbutton_Trigger(void)
{
    /* Configure pios as inputs. */
    PIO_Configure( &pinBP1, 1 ) ;

    /* Adjust pio debounce filter patameters, uses 10 Hz filter. */
    PIO_SetDebounceFilter( &pinBP1, 10 ) ;

    /* Initialize pios interrupt handlers, see PIO definition in board.h.
           Interrupt on rising edge
       */
    PIO_ConfigureIt( &pinBP1, _Button1_Handler ) ;

    /* Enable PIO controller IRQs. */
    NVIC_EnableIRQ( (IRQn_Type)pinBP1.id ) ;

    /* Enable PIO line interrupts. */
    PIO_EnableIt( &pinBP1 ) ;
}


static void _Capture_Init(void)
{
    /* OUTPUT color mode*/
#ifdef DEFAULT_MODE_COLORED
    current_mode = PIO_OUT_COLOR;
#else
    current_mode = PIO_OUT_MONO;
#endif
    PIO_InitializeInterrupts(0);

    /* configure SRAM*/
    BOARD_ConfigureSRAM(SMC);

    /* initizale push botton for capturing trigger*/
    _Init_Pushbutton_Trigger();

    /* intialize Frame signal*/
    _Init_HVSync_Interrupts();

    /* initialize PIODC*/
    PIODC_Capture_Init(PIOA, ID_PIOA, current_mode);

    /** intialize capturing line*/
    if(current_mode == PIO_OUT_COLOR)
    {
        cap_line = IMAGE_LINE_COLORED;
    }
    else if(current_mode == PIO_OUT_MONO)
    {
        cap_line = IMAGE_LINE_MONO;
    }
    else
    {
        cap_line = IMAGE_LINE_COLORED;
    }

#ifdef DEFAULT_SENSOR_YUV422
    _Init_Image_Sensor(QVGA_YUV422);
#endif


}

/*----------------------------------------------------------------------------
*        Exported functions
*----------------------------------------------------------------------------*/

/** system systick handler*/
void SysTick_Handler( void )
{
    TimeTick_Increment() ;
}

/**
*  \brief Continuous_Capture Application entry point.
*
*  Initialize adc to 12bit,enable channel 15,turn on
*  temp sensor, pdc channel interrupt for temp sensor
*  and start conversion
*
*  \return Unused (ANSI-C compatibility).
*  \callgraph
*/
extern int main( void )
{
    /* Disable watchdkog */
    WDT_Disable( WDT ) ;

    /* Set default masters to promote speed*/
    _SetDefaultMaster();

    /* initialize 1ms systick*/
    TimeTick_Configure(BOARD_MCK);
    Wait(1000); // wait for 1s to be sure LCD is ready for initialization

#ifdef FRAME_RATE_MEASURE
    PIO_Configure(&pinTest,1);
#endif

    /* LCD for display*/
    _Init_LCD();

    LCDD_Fill(COLOR_TURQUOISE);
    LCDD_DrawString(0,10,"Continuous_Capture\ndemo(with Ext SRAM)",COLOR_BLACK);
    LCDD_DrawString( 0, 80, (uint8_t *)"Please Wait during\ninitializations", COLOR_BLACK );

    /* initialize image sensor and PIO parallel capture*/
    _Capture_Init();

    /* doing capture continuously*/
    while(1)
    {
        /* State: Is  out mode changed? (B/W or color) */
        if(current_mode != next_mode)
        {
            /* State: out mode is changed, re-configure PIO parallel capture mode */

            current_mode = next_mode;
            _Capture_Reconfigure();
        }

        /* State:  capture */

        _DoCapture();

        /* State: Display in current mode */

#ifdef FRAME_RATE_MEASURE
        PIO_Set(&pinTest);
#endif
        _Display();

#ifdef FRAME_RATE_MEASURE
        PIO_Clear(&pinTest);
#endif
    }
}

