/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished proprietary information of BroadOn Communications Corp.,
 *  and are protected by federal copyright law. They may not be disclosed
 *  to third parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

#include <types.h>
#include <sc/sc.h>
#include <sc/dv_boot.h>
#include <ioslibc.h>
#include <apputils.h>
#include <fs.h>
#include <fl_ops.h>
#include <fs_ops.h>
#include <wa.h>
#include "audutil.h"

#define IRQ_STACK_SIZE          64
#define CACHE_LINE_SIZE         16
static u32 cpu0IRQStack[IRQ_STACK_SIZE>>2]                                  \
                    __attribute__ ((aligned (CACHE_LINE_SIZE))) = {0xff};

/* Maximum command line size including NULL character */
#define LINE_SIZE       256

/* Free memory available -- accounts for memory already used in current FS implementation */
#define FREE_MEM        ((64 * 1024) + (9 * 16384))
#define FREE_MEM_SIZE   (3*16384)

static u32 *audBuffer = (u32 *) MEM0_START + 0x100000;

/* Length in samples available in SDRAM */
#define AUD_LENGTH (0x1f00000 / 4)

/* Size of audio buffer used for playback and capture */
#define AUD_SIZE 4096

/* BCLK=MCLK/8, LRCLK=BCLK/32 => FS=48KHz */
#define DAC_CONFIG ((3<<AUD_DAC_CFG_BCLK_DIV_SHIFT) | AUD_DAC_CFG_MCLK_COM | 15)
#define ADC_CONFIG ((3<<AUD_ADC_CFG_BCLK_DIV_SHIFT) | 15)
/* FS=48KHz, I2S mode, BCLK=MCLK/8, LRCLK=BCLK/32 */
#define I2S_ADC_CONFIG (AUD_ADC_CFG_LR_INV | AUD_ADC_CFG_DI_DLY | (3<<AUD_ADC_CFG_BCLK_DIV_SHIFT) | 15)
#define I2S_DAC_CONFIG (AUD_DAC_CFG_LR_INV | AUD_DAC_CFG_DO_DLY | (3<<AUD_DAC_CFG_BCLK_DIV_SHIFT) | 15)

/* BCLK=MCLK/6, LRCLK=BCLK/48 => FS=48KHz */
#define DAC_CONFIG_24 ((2<<AUD_DAC_CFG_BCLK_DIV_SHIFT) | AUD_DAC_CFG_MCLK_COM | 23)
#define ADC_CONFIG_24 ((2<<AUD_ADC_CFG_BCLK_DIV_SHIFT) | 23)
/* FS=48KHz, I2S mode, BCLK=MCLK/6, LRCLK=BCLK/48 */
#define I2S_ADC_CONFIG_24 (AUD_ADC_CFG_LR_INV | AUD_ADC_CFG_DI_DLY | (2<<AUD_ADC_CFG_BCLK_DIV_SHIFT) | 23)
#define I2S_DAC_CONFIG_24 (AUD_DAC_CFG_LR_INV | AUD_DAC_CFG_DO_DLY | (2<<AUD_DAC_CFG_BCLK_DIV_SHIFT) | 23)

/* 0 = Left justified, 1 = I2S */
static int mode = 0;

/* Current directory */
static char     cur[ISFS_PATH_MAXLEN];

void initSdram(int cl3)
{
     u32 ctrl;
     int i;

     IO_WRITE(MC_CTRL_REG, 0);
     for (i=0; i<350; i++) IO_READ(MC_CTRL_REG);

     ctrl = MC_CTRL_ENA | MC_CTRL_PALL | (0x400);
     IO_WRITE(MC_CTRL_REG, ctrl);
     for (i=0; i<350; i++) IO_READ(MC_CTRL_REG);

     ctrl = MC_CTRL_ENA | MC_CTRL_MRS | 0x2A;
     IO_WRITE(MC_CTRL_REG,  ctrl);
     for (i=0; i<350; i++) IO_READ(MC_CTRL_REG);

     ctrl = MC_CTRL_ENA;
     IO_WRITE(MC_CTRL_REG,  ctrl);
     for (i=0; i<700; i++) IO_READ(MC_CTRL_REG);
     
     IO_WRITE(MC_CTRL_REG, MC_CTRL_ENA | MC_CTRL_DQM_ENA);

     for (i=0; i<700; i++) IO_READ(MC_CTRL_REG);
}

/*
 * Code cut and paste from SC mon to allow use of file system 
 */
int 
fscmd_init(void)
{
    int         rc = 0;
    IOSError     result = IOS_ERROR_OK;

    /* Set flash ID register */
    IO_WRITE(FL_ID_REG, 0x0);

    /* Enable flash interrupt */
    IO_WRITE(SYS_SMP_REG, SYS_SMP_SET_IMASK |
                        (SYS_FLASH_INTR << SYS_SMP_IMASK_SHIFT));

    result = flOpen();
    if (result != IOS_ERROR_OK) {
        rc = -1;
        goto fscmd_init_out;
    }

    result = isfsMount(1);
    if (result != IOS_ERROR_OK) {
        printf("Failed to mount, please reformat the flash\n");
        goto fscmd_init_out;
    }

    /* Set the current directory to the root directory */
    strncpy(cur, "/", ISFS_PATH_MAXLEN);

fscmd_init_out:

    if (rc < 0) {
        printf("Failed to initialize FS commands\n");
    }

    return (rc);
}


int
cd(char *args, char *d)
{
    int         rc = 0, len = 0, num = 0;
    IOSError     result = IOS_ERROR_OK;
    char        *name = NULL, temp[ISFS_PATH_MAXLEN];
    u8          *list = (u8 *) FREE_MEM;

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto cd_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Make sure the directory exists by doing a read */
    result = isfsReadDir(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, list, &num);
    if (result != IOS_ERROR_OK) {
        rc = -2;
        goto cd_out;
    }

    /* cd is successful, change the current directory */
    strncpy(cur, temp, ISFS_PATH_MAXLEN);

cd_out:

    if (rc == 0) {
        printf("Current directory is %s\n", cur);
    } else {
        printf("Failed to cd, rc=%d\n", rc);
    }

    return (rc);
}


int
ls(char *args, char *d)
{
    int         rc = 0, num = 0, count = 0;
    IOSError     result = IOS_ERROR_OK;
    u8          *list = (u8 *) FREE_MEM;

    result = isfsReadDir(IOS_ROOT_ID, IOS_ROOT_GROUP, cur, list, &num);
    if (result != IOS_ERROR_OK) {
        rc = -1;
        goto ls_out;
    }

    printf("List of files/directories under %s:\n", cur);
    for (count = 0; count < num; count++) {
        printf("%s\n", list);
        list += strnlen(list, ISFS_INODE_NAMELEN) + 1;
    }

ls_out:

    if (rc != 0) {
        printf("Failed to ls, rc=%d\n", rc);
    }

    return (rc);
}

/*
 * Generate a square wave into memory 
 */
int square(char *args, char *d)
{
    int ret = 0;
    char *str;
    int len, i, a;
    u32 v1 = 0x12120000;
    u32 v2 = 0x00003636;
    int period = 32;
    int nBlocks;

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    len = asciiToInt(str);
    printf("Length %d\n", len);

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    v1 = (asciiToInt(str) & 0xffff)<<16;
    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    v1 = v1 | (asciiToInt(str) & 0xffff);
    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    v2 = (asciiToInt(str) & 0xffff)<<16;
    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    v2 = v2 | (asciiToInt(str) & 0xffff);

    if (len <= AUD_LENGTH) {
	for (i=0; i<len; i++) {
	    a = i & (period-1);
	    if (a < period/2) {
		audBuffer[i] = v1;
	    } else {
		audBuffer[i] = v2;
	    }
	}
    } else {
	printf("Length exceeds audio buffer %d\n", len);
	ret = -1;
	goto errOut;
    }

    nBlocks = sizeof(int)*len / AUD_SIZE;
    printf("nBlock %d\n", nBlocks);

    /* Turn the audio on */
    WAWrite(WM_APATH_REG, WM_APATH_DACSEL);
    WAWrite(WM_DPATH_REG, 0);
    WAWrite(WM_ACTL_REG, WM_ACTL_ACTIVE);

    if (mode) {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_I2S);
	dacWrite(nBlocks, AUD_SIZE, (u32) audBuffer, I2S_DAC_CONFIG);
    } else {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_LEFTMSB);
	dacWrite(nBlocks, AUD_SIZE, (u32) audBuffer, DAC_CONFIG);
    }

errOut:
    return ret;
}

/*
 * Capture to memory
 */
int
capture(char *args, char *d)
{
    int ret = 0;
    char *str;
    int len;
    int nBlocks;

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    len = asciiToInt(str);
    nBlocks = sizeof(int)*len / AUD_SIZE;
    printf("nBlocks %d\n", nBlocks);
    WAWrite(WM_APATH_REG, WM_APATH_INSEL | WM_APATH_MICBOOST);
    WAWrite(WM_DPATH_REG, 0);
    WAWrite(WM_ACTL_REG, WM_ACTL_ACTIVE);

    if (mode) {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_I2S);
	adcRead(nBlocks, AUD_SIZE, (u32) audBuffer, I2S_ADC_CONFIG);
    } else {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_LEFTMSB);
	adcRead(nBlocks, AUD_SIZE, (u32) audBuffer, ADC_CONFIG);
    }

errOut:
    return ret;
}

/*
 * Play from memory
 */
int
play(char *args, char *d)
{
    int ret = 0;
    char *str;
    int len;
    int nBlocks;

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    len = asciiToInt(str);
    nBlocks = sizeof(int)*len / AUD_SIZE;
    printf("nBlocks %d\n", nBlocks);
    WAWrite(WM_APATH_REG, WM_APATH_DACSEL);
    WAWrite(WM_DPATH_REG, 0);
    WAWrite(WM_ACTL_REG, WM_ACTL_ACTIVE);

    if (mode) {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_I2S);
	dacWrite(nBlocks, AUD_SIZE, (u32) audBuffer, I2S_DAC_CONFIG);
    } else {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_LEFTMSB);
	dacWrite(nBlocks, AUD_SIZE, (u32) audBuffer, DAC_CONFIG);
    }

errOut:
    return ret;
}

/*
 * Capture to file
 */
int
cf(char *args, char *d)
{
    int ret = 0;
    int fd = -1;
    char *fname;
    char *str;
    int len;
    int nBlocks;
    char temp[ISFS_PATH_MAXLEN];
    u32 config;
    u32 addr;
    int bCount = 0;
    int total;
    int i;
    int oldAddr = -1;

    if (getNextToken(&fname, &args) == 0) {
        ret = -1;
        goto errOut;
    }

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    total = asciiToInt(str);

    len = strnlen(fname, ISFS_PATH_MAXLEN);
    if (fname[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, fname, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), fname, (len + 1));
        }
    }

    ret = isfsCreateFile(IOS_ROOT_ID, IOS_ROOT_GROUP, temp,
                    0, ISFS_RW_ACCESS, 0, 0);
    if (ret != IOS_ERROR_OK) {
        if (ret == IOS_ERROR_EXISTS) {
            printf("File already exists, please delete first\n");
        }

        ret = -3;
        goto errOut;
    }

    /* Open the file */
    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, ISFS_WRITE_ACCESS);
    if (fd < 0) {
        ret = -2;
        goto errOut;
    }

    WAWrite(WM_APATH_REG, WM_APATH_INSEL | WM_APATH_MICBOOST);
    WAWrite(WM_DPATH_REG, 0);
    WAWrite(WM_ACTL_REG, WM_ACTL_ACTIVE);

    if (mode) {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_I2S);
	config = I2S_ADC_CONFIG;
    } else {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_LEFTMSB);
	config = ADC_CONFIG;
    }

    addr = (u32) audBuffer;
    nBlocks = ISFS_BLOCK_SIZE / AUD_SIZE;
    startAdcRead(nBlocks, AUD_SIZE, addr, config, &bCount);
    for (i=0; i<total; i++) {
	for (; bCount<nBlocks-1; bCount++) {
	    adcWaitDone();
	    audWriteFifo(AUD_ADC_PTR_REG, AUD_SIZE, addr + bCount*AUD_SIZE);
	}

	/* Write previous File block */
	if (oldAddr != -1) {
	    ret = isfsWrite(fd, (void *) oldAddr, ISFS_BLOCK_SIZE);
	    if (ret != IOS_ERROR_OK) {
		if (ret == IOS_ERROR_INVALID) {
		    printf("End of file\n");
		    goto errOut;
		} else {
		    ret = -3;
		    goto errOut;
		}
	    }
	}
	oldAddr = addr;

	if (addr == (u32) audBuffer) {
	    addr = (u32) audBuffer + ISFS_BLOCK_SIZE;
	} else {
	    addr = (u32) audBuffer;
	}

	/* Last block */
	adcWaitDone();
	audWriteFifo(AUD_ADC_PTR_REG, AUD_SIZE, oldAddr + bCount*AUD_SIZE);
	bCount = 0;
    }

    isfsClose(fd);
	
errOut:
    return ret;

}

/*
 * Play from File
 */
int
pf(char *args, char *d)
{
    int ret = 0;
    int fd = -1;
    char *fname;
    int len;
    int nBlocks;
    char temp[ISFS_PATH_MAXLEN];
    u32 config;
    u32 addr;
    int bCount = 0;
    int total;
    ISFSFileStats fs;
    int oldAddr;

    if (getNextToken(&fname, &args) == 0) {
        ret = -1;
        goto errOut;
    }

    len = strnlen(fname, ISFS_PATH_MAXLEN);
    if (fname[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, fname, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), fname, (len + 1));
        }
    }

    /* Open the file */
    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, ISFS_READ_ACCESS);
    if (fd < 0) {
        ret = -2;
        goto errOut;
    }

    ret = isfsGetFileStats(fd, &fs);
    if (ret != IOS_ERROR_OK) {
	goto errOut;
    }
    total = fs.size / ISFS_BLOCK_SIZE;
    printf("File size %d\n", fs.size);

    /* Read the first FS block of file */
    addr = (u32) audBuffer;
    ret = isfsRead(fd, (void *) addr, ISFS_BLOCK_SIZE);
    if (ret != IOS_ERROR_OK) {
        if (ret == IOS_ERROR_INVALID) {
            printf("File is empty\n");
            goto errOut;
        } else {
            ret = -3;
            goto errOut;
        }
    }

    WAWrite(WM_APATH_REG, WM_APATH_DACSEL);
    WAWrite(WM_DPATH_REG, 0);
    WAWrite(WM_ACTL_REG, WM_ACTL_ACTIVE);
    if (mode) {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_I2S);
	config = I2S_DAC_CONFIG;
    } else {
	WAWrite(WM_DAFMT_REG, WM_DAFMT_LEFTMSB);
	config = DAC_CONFIG;
    }

    nBlocks = ISFS_BLOCK_SIZE / AUD_SIZE;
    startDacWrite(nBlocks, AUD_SIZE, (u32) audBuffer, config, &bCount);
    while (1) {
	oldAddr = addr;
	for (; bCount<nBlocks-1; bCount++) {
	    dacWaitDone();
	    audWriteFifo(AUD_DAC_PTR_REG, AUD_SIZE, oldAddr + bCount*AUD_SIZE);

	}

	/* Next flash block */
	if (addr == (u32) audBuffer) {
	    addr = (u32) audBuffer + ISFS_BLOCK_SIZE;
	} else {
	    addr = (u32) audBuffer;
	}
	ret = isfsRead(fd, (void *) addr, ISFS_BLOCK_SIZE);
	if (ret != IOS_ERROR_OK) {
	    if (ret == IOS_ERROR_INVALID) {
		printf("End of file\n");
		goto errOut;
	    } else {
		ret = -3;
		goto errOut;
	    }
	}

	/* Last block */
	dacWaitDone();
	audWriteFifo(AUD_DAC_PTR_REG, AUD_SIZE, oldAddr + bCount*AUD_SIZE);
	bCount = 0;
    }

    isfsClose(fd);

errOut:
    return ret;
}

/*
 * Write to a Wolfson register
 */
int
rwrite(char *args, char *d)
{
    int ret = 0;
    char *str;
    int addr, data;

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    addr = asciiToInt(str);
    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    data = asciiToInt(str);

    printf("Address 0x%x data 0x%x\n", addr, data);
    WAWrite(addr, data);

errOut:
    return ret;
}

#define WAIT(n) 	{ int i, j; for (i=0; i<n; i++) j = i+1; }

int
gpio(char *args, char *d)
{
    int ret = 0;
    char *str;
    int bit;
    
    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    bit = asciiToInt(str);

    IO_WRITE(AUD_GPIO_DIR_REG, 0xf);
    while (1) {
	IO_WRITE(AUD_GPIO_DATA_REG, bit);
	WAIT(100);
	IO_WRITE(AUD_GPIO_DATA_REG, ~bit);
	WAIT(100);
    }
errOut:
    return ret;
}

int
setmode(char *args, char *d)
{
    int ret = 0;
    char *str;

    if (getNextToken(&str, &args) == 0) {
        ret = -1;
        goto errOut;
    }
    mode = asciiToInt(str);

errOut:
    return ret;
}


/* Command blocks */
static Command commands[] = {
    {"cd", cd,
     "cd dir                 - change directory", 0},
    {"ls", ls,
     "ls                     - list contents of directory", 0},
    {"rwrite", rwrite,
     "rwrite addr data       - Write WM registers", 0},
    {"setmode", setmode,
     "setmode mode           - Set up i2s or MSB first mode", 0},
    {"square", square,
     "square len l0 r0 l1 r1 - Play square wave", 0},
    {"capture", capture,
     "capture len            - Capture audio to memory", 0},
    {"play", play,
     "play len               - Play audio from memory", 0},
    {"cf", cf,
     "cf file nBlocks        - Capture audio to file", 0},
    {"pf", pf,
     "pf                     - Play audio from file", 0},
    {"gpio", gpio,           
     "gpio bit               - toggle gpio bit", 0},
    {"help", help,
     "help                   - Print this message", commands},
    {0}
};

/* Interrupt handler */
extern u32                      irqHandler;
extern void                     flIrq(void);


/* Dispatch interrupt */
void irq(void)
{
    u32     ipend;

    ipend = SYS_SMP_IPEND(IO_READ(SYS_SMP_REG));
    if (ipend & SYS_FLASH_INTR) {
        flIrq();
    }
}


int
cpu0main(void)
{
    int rc = 0, count = 0;
    int r;
    char line[LINE_SIZE];
    int addr;

    printf("audmon - audio test jig \n");
    printf("built: " BUILD_TIME "\n\n");

    /* Configure an SC */
    for (addr = DAX_START+256*1024; addr < DAX_START+320*1024; addr+=16) {
	IO_WRITE(addr, 0);
    }

    r = IO_READ(SYS_CTRL_REG);
    IO_WRITE(SYS_CTRL_REG, r | SYS_CACHE_CONF_DA_192_CC_64_SC_64|SYS_CTRL_CFG_EN);

    /* Set RW permission for the rest of DA */
    for (count = (64 * 1024); count < (192 * 1024); count+=16) {
        IO_WRITE(DAX_START + count, PT_ACCESS_RW << PT_SC_PROT_SHIFT);
    }

    /*
     * Initialize SDRAM
     */
    initSdram(0);

    /* Allow RW access to all of SDRAM */
    for (count = 0; count <0x02000000; count+=0x4000) {
	IO_WRITE(PT_START+count, (PT_ACCESS_RW << PT_SC_PROT_SHIFT) << PT_ENTRY_SHIFT);
    }

    /* Invalidate the D-cache */
    for (count = 0; count < (4 * 1024); count+=16) {
        IO_WRITE(CPS_START | (CPS_CACHE_L1_DI << CPS_CACHE_SHIFT) | count, 1);
    }

    DVSetIRQStack((u32) cpu0IRQStack + sizeof(cpu0IRQStack));
    (void) DVSetExcHandler(ARM_EXC_IRQ, (u32) &irqHandler);
    __skEnableInt();
#if 0
    rc = fscmd_init();
#endif
    if (rc < 0) {
        goto cpu0main_out;
    }

    audInit();

    while (1) {
        printf("[audmon] Enter command: ");
        gets(line);
        if (parseCommand(line, commands) < 0) {
            help("", (void *)commands);
        }
    }

cpu0main_out:
    return (rc);
}

int cpu1main(void)
{
    int         rc = 0;

    return (rc);
}
