/*
 *               Copyright (C) 2006, 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 <ios.h>
#include <aud.h>
#include <ioslibc.h>

#include <audbuf.h>

/*
 * fifo variables
 */

typedef struct {
    u8 *buf;     /* circular buffer */
    u32 read;    /* read index */
    u32 write;   /* write index */
    u32 size;    /* size of fifo/buffer in bytes */
    u32 free;    /* number of unused bytes in buffer */
    u32 used;    /* number of used bytes in buffer */
    u8 ov;       /* overflow policy */
} Fifo;

/* wrap pointer for circular buffer */
#define WRAP(i, size)  if ( (i) >= (size) ) i -= size

/*
 * audio buffering variables
 */

#define AUDBUF_MAX_AUDIO_BUF_SIZE  4096  /* audio driver's max buffer size */
#define AUDBUF_MAX_AUDIO_OPS          2  /* max of 2 reads or writes at once */

static IOSMessageQueueId rMq;       /* message queue for async read operations */
static IOSMessageQueueId wMq;       /* message queue for async write operations */
static IOSMessage rMsgArray[4];     /* message array for async read operations */
static IOSMessage wMsgArray[4];     /* message array for async write operations */
static IOSResourceRequest rReply[AUDBUF_MAX_AUDIO_OPS];/* responses for completed async reads */
static IOSResourceRequest wReply[AUDBUF_MAX_AUDIO_OPS];/* responses for completed async writes */
static u8 wBuf[AUDBUF_MAX_AUDIO_OPS][4096] __attribute__((aligned(16))); /* audio write buffers */
static u8 rBuf[AUDBUF_MAX_AUDIO_OPS][4096] __attribute__((aligned(16))); /* audio read buffers */
static u8 nWrite = 0;               /* number of async writes in flight */
static u8 nRead = 0;                /* number of async reads in flight */
static u8 iWriteBuf = 0;            /* wBuf[] for next write operation */
static u8 iReadBuf = 0;             /* rBuf[] for next read operation */
static Fifo inFifo;                 /* fifo of data read from audio driver */
static Fifo outFifo;                /* fifo of data to write to audio driver */
static u32 readBytes;               /* buffer size for reads, controls input latency */
static IOSFd audFd = -1;            /* audio driver handle */

/*
 * debugging macros
 */

#define ADB_DEBUG
#ifdef ADB_DEBUG
#define ADB_LOG(...) printf("ADB: " __VA_ARGS__)
#define ADB_LOG_CONT(...) printf(__VA_ARGS__)
#define ADB_ERROR(msg) printf("ADB: Error: %s failed\n", msg)
#else
#define ADB_LOG(...)
#define ADB_LOG_CONT(...)
#define ADB_ERROR(msg) /* printf("ADB: Error: %s failed\n", msg) */
#endif

#define STEREO_TO_STEREO        0
#define STEREO_TO_MONO          1
#define MONO_TO_STEREO          2
static void*
my_memcpy(void *dst, const void *src, size_t n, int mode)
{
    // If not aligned on 16-bits, do nothing
    if (((int)dst & 0x1) || ((int)src & 0x1) || (n & 0x1)) {
        // error
        return dst;
    } else {
        u16 *d = dst;
        const u16 *s = src;
        n = n>>1;
        while (n--) {
            *d = *s;
            if (mode == MONO_TO_STEREO) {
                n--;
                d++;
                *d = *s;
            } else if (mode == STEREO_TO_MONO) {
                n--;
                s++;
            }
            d++;
            s++;
        }
        return dst;
    }
}

void
fifoPrint(Fifo *f, char *msg) 
{
    printf("fifo: %s\n",msg);
    printf("\tbuf = 0x%08x, size = %d, free = %d, used = %d\n",
           (u32)f->buf,f->size,f->free,f->used);
    printf("\twrite = %d, read = %d, ov = %d\n",
           f->write,f->read,f->ov);
}
    
void
fifoInit(Fifo *f, u8 *buf, u32 size, u8 ov)
{
    f->buf = buf;
    f->size = size;
    f->read = f->write = 0;
    f->free = size;
    f->used = 0;
    f->ov = ov;
#ifdef ADB_DEBUG
    fifoPrint(f, "init");
#endif
}

inline int
fifoUnused(Fifo *f)
{
    return f->free;
}

inline int
fifoUsed(Fifo *f)
{
    return f->used;
}

inline int
fifoPutContigSize(Fifo *f, u32 size)
{
    int t = f->size - f->write;
    if ( t > f->free )
        t = f->free;
    return t;
}

inline int
fifoGetContigSize(Fifo *f, u32 size)
{
    int t = f->size - f->read;
    if ( t > f->used )
        t = f->used;
    return t;
}

int
fifoPut(Fifo *f, u8 *buf, u32 size, int mode)
{
    ADB_LOG("fifoPut: size = %d\n",size);
    if ( mode != STEREO_TO_STEREO ) {
        size = size<<1;
    }
    if ( size > f->size )
        size = f->size;
    if ( size > f->free ) {
        ADB_LOG("fifoPut: overflow\n");
        // overflow
        if ( f->ov == AUDBUF_OVERFLOW_DISCARD_OLD ) {
            int d = size - f->free;  // amount of old data to discard
            f->used -= d;
            f->free += d;
            f->read += d;
            WRAP(f->read, f->size);
        } else  { // f->ov == AUDBUF_OVERFLOW_DISCARD_NEW
            // add data until fifo is full, discard the rest
            size = f->free;
        }
    }
    u32 s = fifoPutContigSize(f, size);
    if ( s > size )
        s = size;
    my_memcpy(f->buf+f->write, buf, s, mode);
    my_memcpy(f->buf, buf+s, size-s, mode);
    f->free -= size;
    f->used += size;
    f->write += size;
    WRAP(f->write, f->size);
#ifdef ADB_DEBUG
    fifoPrint(f,"after fifoPut");
#endif
    return size;
}

int
fifoGet(Fifo *f, u8 *buf, u32 size, int mode)
{
    ADB_LOG("fifoGet: size = %d\n",size);
    if ( mode != STEREO_TO_STEREO ) {
        size = size<<1;
    }
    if ( size > f->used ) {
        ADB_LOG("fifoGet: underflow, used = %d, size = %d\n",f->used,size);
        // underflow
        size = f->used;
    }
    u32 s = fifoGetContigSize(f, size);
    if ( s > size )
        s = size;
    my_memcpy(buf, f->buf+f->read, s, mode);
    my_memcpy(buf+s, f->buf, size-s, mode);
    f->free += size;
    f->used -= size;
    f->read += size;
    WRAP(f->read, f->size);
#ifdef ADB_DEBUG
    fifoPrint(f,"after fifoGet");
#endif
    return size;
}


/* audbufConvertSize -- given a buffer size, compute the maximum
 * number of bytes that the audio device can consume in a single
 * operaton
 *
 * size, bytes      return value
 * -----------      ------------
 * 0 - 31              0
 * 32 - 63            32
 * 64 - 127           64
 * 128 - 255         128
 * 256 - 511         256
 * 512 - 1023        512
 * 1024 - 2047      1024
 * 2048 - 4095      2048
 * >= 4096          4096
 */
static u32
audbufConvertSize(int size)
{
    u32 r;
    if ( size < 32 ) {
        r = 0;
    } else {
        for ( r=4096; r>size; r/=2 ) {}
    }
    return r;
}

/* audbufOpen
 *
 * 1. setup input and output buffers with user-specified overflow policies
 * 2. open and configure audio device, see aud.h for valid "config" settings
 *
 * Note:
 * A. to avoid input overflow (when reading from the microphone), be
 *    sure to specify --
 *       readSize > dt * (samples/sec) * (1 sample/4 bytes) / 2
 * B. also, readSize must be a power of 2 between 32 and 4096, inclusive
 * C. audio samples are always 2 channels wide at 2 bytes/sample/channel,
 *    and all sizes are specified in bytes
 *    
 * return value is
 * * IOS_ERROR_OK if no error
 * * IOS_ERROR_INVALID if an input argument is invalid
 * * IOS_ERROR_NOTREADY if audio device is already open
 * * other error if message queues cannot be created
 */

IOSError
audbufOpen(u8 flags, u32 config, u32 readSize,
           u8 *inbuf, u32 inbufSize, u32 inOverflowConfig,
           u8 *outbuf, u32 outbufSize, u32 outOverflowConfig)
{
    IOSError rv = IOS_ERROR_OK;
    u32 *params = NULL;

    ADB_LOG("audbufOpen: config=%d, readSize=%d, inbuf=0x%08x, inbufSize=%d, inOv=%d\n",
            config,readSize,(u32)inbuf,inbufSize,inOverflowConfig);
    ADB_LOG("            outbuf=0x%08x, outbufSize=%d, outOv=%d\n",
            (u32)outbuf,outbufSize,outOverflowConfig);

    /* check input parameters */

    if ( flags != O_RDONLY &&
         flags != O_WRONLY &&
         flags != O_RDWR ) {
        ADB_ERROR("flags");
        ADB_LOG("invalid flags = 0x%x\n",flags);
        rv = IOS_ERROR_INVALID;
        goto out;
    }
        
    if ( readSize != audbufConvertSize(readSize) ) {
        ADB_ERROR("read size");
        ADB_LOG("invalid readSize = %d\n",readSize);
        rv = IOS_ERROR_INVALID;
        goto out;
    }
        
    readBytes = readSize;

    // register input/output buffers

    fifoInit(&inFifo,inbuf,inbufSize,inOverflowConfig);
    fifoInit(&outFifo,outbuf,outbufSize,outOverflowConfig);

    // create read and write message queues

    rMq = rv = IOS_CreateMessageQueue(rMsgArray, sizeof(rMsgArray)/sizeof(rMsgArray[0]));
    if ( rv < 0 ) {
        ADB_ERROR("create read message queue");
        goto out;
    }

    wMq = rv = IOS_CreateMessageQueue(wMsgArray, sizeof(wMsgArray)/sizeof(wMsgArray[0]));
    if ( rv < 0 ) {
        ADB_ERROR("create write message queue");
        goto out;
    }

    // open audio device

    if ( (audFd = IOS_Open(AUD_DEV "0", flags)) < 0 ) {
        ADB_ERROR("headset audio open");
        rv = IOS_ERROR_NOTREADY;
        goto out;
    }

    // set configuration

    // allocate from shared arena to pass parameters to audio RM
    if ((params = IOS_Alloc(0, sizeof(*params))) == NULL) {
        ADB_ERROR("alloc");
        rv = IOS_ERROR_FAIL_ALLOC;
        goto out;
    }
    *params = config;

    if ( (rv = IOS_Ioctl(audFd,AUD_SET_CONFIG,params,sizeof(*params),0,0)) != IOS_ERROR_OK ) {
        ADB_ERROR("audio config");
        ADB_LOG("AUD_SET_CONFIG ret %d\n", rv);
        goto out;
    }

    // return open/config status
out:
    if (rv < 0 && audFd >= 0) {
        (void) IOS_Close(audFd);
        audFd = -1;
    }
    if (params != NULL) {
        (void) IOS_Free(0, params);
    }
    return rv;
}

/* audbufGetVolumeMin
 *
 * return lowest possible non-mute volume setting
 */

int audbufGetVolumeMin(void)
{
    return AUD_VOLUME_MIN;
}

/* audbufGetVolumeMax
 *
 * return highest possible volume setting
 */

int audbufGetVolumeMax(void)
{
    return AUD_VOLUME_MAX;
}

/* audbufGetVolumeMute
 *
 * return volume setting corresponding to mute
 */

int audbufGetVolumeMute(void)
{
    return AUD_VOLUME_MUTE;
}

/* audbufSetVolume
 *
 * set audio headset volume; legal volume setting can be found in
 * aud.h
 *
 * return value is IOS_ERROR_OK on success, negative value on error
 */
IOSError
audbufSetVolume(int volume)
{
    // ioctl to set volume
    IOSError rv;
    rv = IOS_Ioctl(audFd,AUD_SET_VOLUME,&volume,sizeof(volume),0,0);
    return rv;
}

/* audbufSetVolume
 *
 * get current audio headset volume setting; legal volume setting
 * can be found in aud.h
 *
 * return value is IOS_ERROR_OK on success, negative value on error
 */
IOSError
audbufGetVolume(int *volume)
{
    // ioctl to get volume
    IOSError rv;
    rv = IOS_Ioctl(audFd,AUD_GET_VOLUME,0,0,volume,sizeof(*volume));
    return rv;
}

/* audbufGetHeadset
 *
 * determine whether headset is connected to NC
 *
 * return value is 1 if connected, 0 if not connected, negative value
 * if error
 */
IOSError
audbufGetHeadset(int *headset)
{
    // ioctl to get headset
    IOSError rv;
    rv = IOS_Ioctl(audFd,AUD_GET_HEADSET,0,0,headset,sizeof(*headset));
    return rv;
}

/* audbufWrite
 *
 * write data to audio headset
 *
 * to avoid underflow, be sure to specify "size" such that
 * 1. "size" > dt * (samples/sec) * (1 sample/4 bytes)
 * AND
 * 2. "size" is a power of 2 between 32 and 4096, inclusive
 *
 * "dt" is the maximum time between successive calls to audbufWrite()
 *
 * For both audbufWrite and audbufRead, the "buf" format is 2 audio
 * channels with 2 bytes/sample/channel.  Thus,
 *
 *    buf[i*4+0] = sample i, left channel, high byte
 *    buf[i*4+1] = sample i, left channel, low byte
 *    buf[i*4+2] = sample i, right channel, high byte
 *    buf[i*4+3] = sample i, right channel, low byte
 * 
 * Specify MONO mode and input "buf" will be treated as 1 channel
 * wide, and will be copied into audbuf by replicating the single
 * channel into 2 channels.
 *
 * return value is the number of bytes of "buf" that were used, on
 * success; return value is a negative number on error
 * 
 * return value can be less than "size" if outbuf is full and
 * the overflow policy is AUDBUF_OVERFLOW_DISCARD_NEW;
 */

IOSError
audbufWrite(char *buf, int size, int mode)
{
    IOSError rv, rv2;
    u32 s;
    IOSMessage msg;
    u32 used = 0;

    ADB_LOG("audbufWrite: buf = 0x%08x, size = %d\n",(u32)buf, size);

    // check for any completed writes

    ADB_LOG("ReceiveMessage (nonblocking)\n");
    while ( (rv = IOS_ReceiveMessage(wMq, &msg, IOS_MESSAGE_NOBLOCK)) != IOS_ERROR_QEMPTY ) {
        if ( rv == IOS_ERROR_OK ) {
            nWrite--;
            if ( (rv2 = (((IOSResourceRequest*)msg)->status)) > 0 ) {
                // successful write
                ADB_LOG("successful write completion\n");
            } else {
                ADB_ERROR("IOS_WriteAsync");
            }
        } else {
            ADB_ERROR("IOS_ReceiveMessage (nonblocking)");
            ADB_LOG("IOS_ReceiveMessage failed, rv = %d\n",rv);
            goto out;
        }
    }

    // put new data in fifo
    ADB_LOG("putting new user data into buffer\n");
    used = fifoPut(&outFifo, buf, size,
                   (mode==MONO)?MONO_TO_STEREO:STEREO_TO_STEREO);
    ADB_LOG("done putting new user data into buffer\n");
    
    // foreach available write buffer
    //    copy data to temp buffer, if needed
    //    perform async write
    ADB_LOG("preparing to write, nWrite = %d, nbytes available = %d\n",nWrite,fifoUsed(&outFifo));
    if ( nWrite < 2 && (s = audbufConvertSize(fifoUsed(&outFifo))) != 0 ) {
        ADB_LOG("getting write data from fifo, %d bytes\n",s);
        fifoGet(&outFifo,wBuf[iWriteBuf],s,STEREO_TO_STEREO);

        ADB_LOG("attempting to write, %d bytes\n",s);
        if ( (rv = IOS_WriteAsync(audFd, wBuf[iWriteBuf], s, wMq, &wReply[iWriteBuf])) != IOS_ERROR_OK ) {
            ADB_ERROR("IOS_WriteAsync #1 submit");
            goto out;
        }
        ADB_LOG("successful write\n");

        nWrite++;
        iWriteBuf++;
        if ( iWriteBuf >= AUDBUF_MAX_AUDIO_OPS )
            iWriteBuf = 0;
    }

out:
    ADB_LOG("audbufWrite: returning %d\n",used);
    
    return used;
}

/* audbufRead
 *
 * read audio data from microphone
 *
 * "size" is the maximum number of data bytes to read; read
 * data is copied into buf
 *
 * For both audbufWrite and audbufRead, the "buf" format is 2 audio
 * channels with 2 bytes/sample/channel.  Thus,
 *
 *    buf[i*4+0] = sample i, left channel, high byte
 *    buf[i*4+1] = sample i, left channel, low byte
 *    buf[i*4+2] = sample i, right channel, high byte
 *    buf[i*4+3] = sample i, right channel, low byte
 * 
 * Specify MONO mode and data will be copied into "buf" 1 channel
 * wide, dropping the second channel.
 *
 * return value is the number of data bytes in "buf", on success;
 * return value is a negative number on error
 * 
 * return value can be less than "size" if inbuf has less than "size"
 * bytes of data available
 */

IOSError
audbufRead(char *buf, int size, int mode, int block)
{
    IOSMessage msg;
    IOSError rv, rv2;
    u32 s = 0;

    ADB_LOG("audbufRead: buf = 0x%08x, size = %d\n",(u32)buf, size);

    // check for any completed reads
    // copy received data into fifo

    ADB_LOG("ReceiveMessage (nonblocking)\n");
    while ( (rv = IOS_ReceiveMessage(rMq, &msg, (block)?IOS_MESSAGE_BLOCK:IOS_MESSAGE_NOBLOCK)) != IOS_ERROR_QEMPTY ) {
        if ( rv == IOS_ERROR_OK ) {
            nRead--;
            if ( (rv2 = (((IOSResourceRequest*)msg)->status)) > 0 ) {
                ADB_LOG("successful read completion\n");
                u32 ndx = (msg-(int)rReply)/sizeof(IOSResourceRequest);
                // put data in queue
                // if buffer full
                //    throw away data
                // else
                //    add data to buffer
                ADB_LOG("putting mic data into fifo, ndx = %d, bytes = %d\n",ndx,rv2);
                fifoPut(&inFifo,rBuf[ndx],rv2,STEREO_TO_STEREO); // XXX ((IOSResourceRequest*)msg)->args.read.outPtr,rv2);
            } else {
                ADB_ERROR("IOS_ReadAsync");
            }
            block = 0;
        } else if ( rv != IOS_ERROR_QEMPTY ) {
            ADB_ERROR("IOS_ReceiveMessage (nonblocking)");
            ADB_LOG("IOS_ReceiveMessage (nonblocking) failed, rv = %d\n",rv);
            goto out;
        }
    }

    // begin filling any available read buffers
    ADB_LOG("preparing to read, nRead = %d\n",nRead);
    while ( nRead < 2 ) {
        ADB_LOG("attempting to read, %d bytes\n",readBytes);
        if ( (rv = IOS_ReadAsync(audFd, rBuf[iReadBuf], readBytes, rMq, &rReply[iReadBuf])) != IOS_ERROR_OK ) {
            ADB_ERROR("IOS_ReadAsync #1 submit");
            goto out;
        }
        ADB_LOG("successful read\n");
        nRead++;
        iReadBuf++;
        if ( iReadBuf >= AUDBUF_MAX_AUDIO_OPS )
            iReadBuf = 0;
    }
    
    // return read data to user
    s = fifoGet(&inFifo,buf,size,
                (mode==MONO)?STEREO_TO_MONO:STEREO_TO_STEREO);

out:
    ADB_LOG("audbufRead: returning %d\n",s);

    return s;
}

/* audbufClose
 *
 * complete any pending audio reads/writes, release system resources,
 * and close audio device
 *
 * return value is IOS_ERROR_OK on success; return value is a negative
 * number in the case of an error
 */

IOSError audbufClose()
{
    IOSError rv = IOS_ERROR_OK, rv2;
    IOSMessage msg;

    /* wait for any in-progress reads/writes to complete */
    while ( rMq >=0 && nRead > 0 ) {
        rv = IOS_ReceiveMessage(rMq, &msg, IOS_MESSAGE_BLOCK);
        nRead--;
    }

    while ( wMq >=0 && nWrite > 0 ) {
        rv = IOS_ReceiveMessage(wMq, &msg, IOS_MESSAGE_BLOCK);
        nWrite--;
    }
    
    
    /* destroy message queue */
    if ( rMq >= 0 ) {
        ADB_LOG("destroying read queue\n");
        if ( (rv = IOS_DestroyMessageQueue(rMq)) == IOS_ERROR_OK ) {
            rMq = -1;
        } else {
            ADB_ERROR("destroy read queue");
        }
    }
    
    if ( wMq >= 0 ) {
        ADB_LOG("destroying write queue\n");
        if ( (rv = IOS_DestroyMessageQueue(wMq)) == IOS_ERROR_OK ) {
            wMq = -1;
        } else {
            ADB_ERROR("destroy write queue");
        }
    }
    
    /* close audio device */
    if ( audFd >= 0 ) {
        ADB_LOG("closing audio device\n");
        if ( (rv2 = IOS_Close(audFd)) == IOS_ERROR_OK ) {
            audFd = -1;
        } else {
            ADB_ERROR("closing audio");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
        }
    }

    return rv;
}
