/*
 *               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.
 *
 */

/* TO DO --
 * XXX 1. add VBR support for seeking -- Xing and VBRI
 * 2. add interface for querying/reading ID3 tags?
 * XXX 3. detect trailing ID3V2 tags
 * 4. re-check all error codes
 * 5. verify that all header info comes from the decoder (so the MP3
 *    device can't get out of sync with the decoder)
 * 6. test with various input files
 * XXX   - MPEG 1, 2, 2.5  <-- only MPEG 1 tested; MPEG 2 & 2.5 not supported
 *    - all CBR data rates
 * XXX   - free format
 * XXX   - VBR file
 * XXX   - ID3V1, ID3V1.1, ID3V2 trailing tags
 * XXX   - ID3V2 leading tags
 * XXX   - APEV1, APEV2 trailing tags
 *    - APEV2 leading tags
 * XXX   - LYRICS3V2 trailing tags
 *    - LYRICS3V2 leading tags
 *    - stereo, mono, joint, etc.
 * XXX   - with and without padding
 *    - seeking and time accuracy, CBR & VBR
 *    - error conditions
 * XXX 7. clean up mp3utils
 * 8. move audMq open/close from mp3Play/mp3Stop to mp3Open/mp3Close?
 * XXX 9. detect and fail if MP3 version, layer, or sampling rate changes
 *    within a file
 * 10. test interspersed read/play operations
 * 
 */

#include <sc/sc.h>
#include <sc/addr_map.h>
#include <sc/ios.h>
#include <ioslibc.h>
#include <fs.h>
#include <sc/aud.h>
#include <sc/mp3.h>

#include "mp3dec.h"
#include "mp3utils.h"

/* max number of devices supported */
#define MP3_NUM_DEV 1

/* device states */
#define MP3_STATE_CLOSED   1  /* device is closed */
#define MP3_STATE_OPEN     2  /* device has been opened, but is not playing */

/* audio underflow errors
 *
 * audio underflow errors occur when the MP3 device allows the
 * audio codec to run out of data.  For production builds, these
 * errors should be ignored as it's deemed better to hear an
 * audible glitch than for playback to stop unexpectedly.  For
 * development builds, though, these errors should be reported
 * so that the failure cases can be debugged.
 */
/* #define MP3_IGNORE_UNDERFLOW */

/* playing silent audio
 *
 * debugging audible artifacts is sometimes easier if there is no audio
 * present; set MP3_PLAY_SILENCE to force the decode buffer to be over-
 * written with zeroes before it is played.
 */
/* #define MP3_PLAY_SILENCE */

/* keep audio open
 *
 * opening/closing the audio device may cause audible artifacts; set 
 * MP3_AUDIO_KEEP_OPEN to keep the audio device open until the MP3 device
 * is closed; otherwise the audio device is closed whenever playback is
 * stopped.
 */
#define MP3_AUDIO_KEEP_OPEN

/* resyncing MP3 stream after seek
 *
 * an MP3 frame may depend on data in previous frames in order to be
 * decoded properly; after seeking to a new location in the MP3
 * stream, the decoder will not have access to data from sequentially-
 * previous MP3 frames and therefore may decode the new frame
 * incorrectly.
 *
 * Use MP3_RESYNC_MANUAL to arbitrarily ignore the first two frames
 * decoded after a seek; this is a brute-force attempt to ignore
 * incorrectly-decoded frames, but it may ignore too many or too
 * few frames.
 *
 * Use MP3_RESYNC_STANDALONE to skip forward to the first frame that 
 * doesn't depend on any previous frames; but this can easily skip a
 * large number of frames.
 *
 * Use MP3_RESYNC_MAINDATA to parse the MP3 stream and determine
 * how many frames will (theoretically) be decoded improperly.  How
 * this information is used to ignore improperly-decoded frames
 * depends on the internal implementation of the decoder.
 *
 * Only use one of these defines at a time.
 */
/* #define MP3_RESYNC_MANUAL */
/* #define MP3_RESYNC_STANDALONE */
#define MP3_RESYNC_MAINDATA

/* number of decode buffers */
 #define MP3_NUM_DECBUF     4  /* number of decode buffers */

/* IOS_OPEN flags -- should be in stdio.h, fcntl.h, or similar */
#define O_ACCMODE 0x3
#define O_RDONLY  0x0
#define O_WRONLY  0x1
#define O_RDWR    0x2

/*
 * time info is given to the user in units of milliseconds; internally,
 * timing info is tracked with greater accuracy to minimize rounding
 * errors.
 */
#define MP3_TICKS_PER_MSEC  100

/*
 * the MPEG version, layer, and sampling frequency information in
 * the MP3 frame header shouldn't change mid-stream; the following
 * macros are used to verify that they haven't changed
 */
#define MP3_HEADER_FINGERPRINT_MASK (MP3_HEADER_SYNC_MASK |  \
                                     MP3_HEADER_ID_MASK |    \
                                     MP3_HEADER_LAYER_MASK | \
                                     MP3_HEADER_FREQ_MASK)
#define MP3_HEADER_FINGERPRINT(h) ((h)&MP3_HEADER_FINGERPRINT_MASK)

/*
 * local IOSError state values; must be >0 to avoid conflict with
 * OS-defined values (which are all <= 0)
 */
#define MP3_STATUS_EOF  1  /* end of MP3 file reached */

/* internal device info */
typedef struct {
    u8 state;                  /* device state, see MP3_STATE_* */
    u32 volume;                /* current volume */
    u8 muted;                  /* 0 if audio on and not muted, else 1 */
    u8 flags;                  /* flags passed with open command */
    u32 mp3Duration;           /* file duration in 10's of usecs */
    s32 mp3Start;              /* MP3 data start byte location */
    s32 mp3End;                /* MP3 data end byte location */
    u32 mp3CurrTime;           /* current MP3 time in 10's of usecs */
    u8 mp3NeedSeek;            /* 1 if a seek is needed to correct for decode-ahead skid */
    u32 mp3Reading;            /* 1 if frame decoding is in progress for mp3Read */
    u32 mp3Playing;            /* 1 if MP3_PLAY is in progress */
    IOSError mp3PlayStatus;    /* last error status reported by playback operation */
    u32 mp3SampleRate;         /* sample rate for mp3 file, Hz */
    Mp3Info mp3i;              /* MP3 header info */
    u8 hasXing;                /* 1 if Xing header is present */
    u8 hasVbri;                /* 1 if VBRI header is present */
    union {                    /* at most one VBR header is parsed per file */
        XingInfo xingInfo;         /* Xing header contents */
        VbriInfo vbriInfo;         /* VBRI header contents */
    };
    IOSFd mp3Fd;               /* MP3 file being played */
    IOSFd audFd;               /* audio device */
    u32 encBuf[MP3DEC_INPUT_SIZE] __attribute__((aligned(16))); /* encoded samples */
    /* round up to multiple of 16, so both buffers are 16-byte aligned for audio driver */
    u8 decBuf[MP3_NUM_DECBUF][(((MP3DEC_OUTPUT_SIZE+15)/16)*16)] __attribute__((aligned(16))); /* decoded samples */
    u8 *nextPlayBuf;           /* pointer to decoded buffer to be played next */
    u16 readNdx;               /* location in current decBuf where mp3Read will begin */
    Mp3DecoderInfo di;         /* mp3 decoder information, defined by the decoder being used */
    u8 decoderInit;            /* 1 if decoder has been initialized, else 0 */
    Mp3DtInfo dti;             /* mp3 decoder thread info */
    u8 dtInit;                 /* 1 if decoder thread has been initialized, else 0 */
    IOSMessageQueueId audMq;   /* message queue for async audio operations */
    IOSMessage audMsgArray[2]; /* message array for async audio operations */
    u8 nAudWrites;             /* number of outstanding async audio writes */
#if defined(MP3_RESYNC_MANUAL) || defined(MP3_RESYNC_MAINDATA)
    u32 nIgnoreFrames;         /* number of decoded frames to ignore after a seek */
#endif
} Mp3Context;

Mp3Context mp3Context[MP3_NUM_DEV];

/*
 * since this task runs as an application on NC, test code must
 * either be executed on the GBA or in a separate thread within
 * the task.  To implement the latter approach, define TEST_PROC;
 * the file testProc.c will be included and a separate thread
 * created to run the testProc routine.
 */

#ifdef TEST_PROC
 u8 _testStack[STACK_SIZE];
 IOSThreadId testTid = -1;
 #include "testProc.c"
#endif

/*
 * mp3StopDecoder -- stop the decoder
 */
static IOSError
mp3StopDecoder(Mp3Context *ac)
{
    IOSError rv;
    
    if ( (rv = mp3DtStopDecode(&ac->dti)) != IOS_ERROR_OK ) {
        MP3_ERROR("stop decoder");
        goto out;
    }

    ac->mp3NeedSeek = 1;
out:
    return rv;
}

/*
 * mp3StartDecoder -- prime the decoder to start it running
 */
static IOSError mp3Seek(IOSResourceRequest *req);

static IOSError
mp3StartDecoder(Mp3Context *ac)
{
    int i;
    IOSError rv = IOS_ERROR_OK;
    
    /* since decoder reads ahead, the file position may be
     * out of sync with current playback time; ideally,
     * a seek to the current time should be performed before
     * the decoder is re-started
     *
     * really, this is only needed for playback since time
     * sync is always maintained for reading (because for
     * reading, decode never stops except for an explicit
     * seek)
     */

    if ( ac->mp3Playing && ac->mp3NeedSeek ) {
        IOSResourceRequest req;
        req.handle = (IOSResourceHandle) ac;
        req.args.seek.offset = ac->mp3CurrTime / MP3_TICKS_PER_MSEC;
        req.args.seek.whence = IOS_SEEK_SET;
        MP3_LOG("mp3StartDecoder: alignment seek\n");
        if ( (rv = mp3Seek(&req)) < 0 ) {
            /* report error, but don't fail */
            MP3_ERROR("mp3StartDecoder alignment seek");
            rv = IOS_ERROR_OK;
            /* fall through */
        }
    }
    
    /* prime decode buffer */
    for (i=0; i<MP3_NUM_DECBUF; i++) {
        if ( (rv = mp3DtReleaseFrame(&ac->dti, i, ac->decBuf[i])) != IOS_ERROR_OK ) {
            MP3_ERROR("priming decode buffers");
            goto out;
        }
    }

out:
    if ( rv != IOS_ERROR_OK )
        mp3StopDecoder(ac);

    return rv;
}


/*
 * mp3Stop -- stop playback of an MP3 file
 */
static IOSError
mp3Stop(Mp3Context *ac)
{
    IOSError rv = IOS_ERROR_OK;
    IOSError rv2;
    IOSMessage m;

    ac->mp3Playing = 0;

    /* mute audio to avoid audible noise in case of underflow */
    if ( ac->audFd >= 0 ) {
        u32 mute = MP3_VOLUME_MUTE;
        if ( (rv2 = IOS_Ioctl(ac->audFd,AUD_SET_VOLUME,&mute,sizeof(mute),0,0)) != IOS_ERROR_OK ) {
            MP3_ERROR("audio volume mute");
            /* ignore error */
        }
        ac->muted = 1;
    }

    /* stop decoding frames */
    if ( ac->dtInit ) {
        MP3_LOG("stopping decoder\n");
        if ( (rv = mp3StopDecoder(ac)) != IOS_ERROR_OK ) {
            MP3_ERROR("stop decoder");
        }
    }
    
    /* clean up any outstanding writes */
    while (ac->nAudWrites) {
        MP3_LOG("cleanup outstanding write responses\n");
        if ( (rv2 = IOS_ReceiveMessage(ac->audMq, &m, IOS_MESSAGE_BLOCK)) == IOS_ERROR_OK ) {
            ac->nAudWrites--;
            if ( (rv2 = ((IOSResourceRequest*)m)->status) <= 0) {
                MP3_ERROR("IOS_WriteAsync cleanup status");
            }
        } else {
            MP3_ERROR("IOS_WriteAsync cleanup receive");
        }
    }
    
    /* clean up audio queue */
#ifndef MP3_AUDIO_KEEP_OPEN
    if ( ac->audMq >= 0 ) {
        MP3_LOG("destroying audio queue\n");
        if ( (rv2 = IOS_DestroyMessageQueue(ac->audMq)) == IOS_ERROR_OK ) {
            ac->audMq = -1;
        } else {
            MP3_ERROR("IOS_DestroyMessageQueue audio");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
        }
    }
    
    /* close audio device */
    if ( ac->audFd >= 0 ) {
        MP3_LOG("closing audio device\n");
        if ( (rv2 = IOS_Close(ac->audFd)) == IOS_ERROR_OK ) {
            ac->audFd = -1;
        } else {
            MP3_ERROR("closing audio");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
        }
    }
#endif        

#ifdef PERF
    /* print performance statistics */
    if ( ac->decoderInit )
        mp3DecoderPrintPerf(&ac->di);
    if ( ac->dtInit )
        mp3DtPrintPerf(&ac->dti);
    printf("\n"); /* for ease of reading, print blank line after stats */
    /* clear performance counters for next time */
    mp3DecoderResetPerf(&ac->di);
    mp3DtResetPerf(&ac->dti);
#endif
    
    return rv;
}

/*
 * mp3DecodeFrame -- decode one MP3 frame
 *
 * return IOS_ERROR_OK if success
 *        MP3_STATUS_EOF if eof encountered
 *        IOS_ERROR_INVALID_FORMAT if unexpected data
 *
 * updates ac->nextPlayBuf and ac->readNdx
 */
static IOSError
mp3DecodeFrame(Mp3Context *ac)
{
    IOSError rv = IOS_ERROR_OK;
    u32 header;
    
    /* decode an MP3 frame */
    MP3_LOG("decoding MP3 frame\n");

    /* reset read pointer */
    ac->readNdx = 0;

#if defined(MP3_RESYNC_MANUAL) || defined(MP3_RESYNC_MAINDATA)
    while ( 1 ) {
#endif
    /* decode the MP3 frame */
    MP3_LOG("decode MP3 frame\n");
    rv = mp3DtGetFrame(&ac->dti,&ac->nextPlayBuf,&header);
    
#ifdef MP3_PLAY_SILENCE
    /* return a buffer filled with zeroes */
    memset(ac->nextPlayBuf,0,sizeof(ac->decBuf[0]));
#endif
    
    if ( rv < 0 ) {
        /* error occurred */
        MP3_ERROR("decoding MP3 frame");
        rv = IOS_ERROR_INVALID_FORMAT; /* XXX */
        goto out;
    } else if ( rv == 0 ) {
        /* eof found */
        rv = MP3_STATUS_EOF; /* eof marker */
        goto out;
    } else {
        rv = IOS_ERROR_OK;
        /* check that MPEG version, layer, and sampling frequency haven't
         * changed mid-stream
         */
#if MP3_DECODER != MP3_DECODER_ITTIAM
        if ( MP3_HEADER_FINGERPRINT(header) != MP3_HEADER_FINGERPRINT(ac->mp3i.head) ) {
            MP3_LOG("MP3 fingerprint was 0x%08x, now 0x%08x\n",
                    MP3_HEADER_FINGERPRINT(ac->mp3i.head),
                    MP3_HEADER_FINGERPRINT(header));
            MP3_ERROR("MPEG fingerprint check");
            rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
#endif
    }
#if defined(MP3_RESYNC_MANUAL) || defined(MP3_RESYNC_MAINDATA)
    if ( ac->nIgnoreFrames == 0 ) {
        break;
    } else {
        MP3_LOG("ignoring decoded frame (%d)\n",ac->nIgnoreFrames);
        ac->nIgnoreFrames--;
        /* update time index to account for ignored frames */
        ac->mp3CurrTime += (1152UL*1000UL*MP3_TICKS_PER_MSEC)/ac->mp3SampleRate; /* 10's usec */
        /* release frame */
        u32 ndx = ( (u32)ac->nextPlayBuf - (u32)ac->decBuf) / sizeof(ac->decBuf[0]);
        if ( (rv = mp3DtReleaseFrame(&ac->dti, ndx, ac->nextPlayBuf)) != IOS_ERROR_OK ) {
            MP3_ERROR("ignore release frame");
            goto out;
        }
    }
    }
#endif

out:
    if ( rv != IOS_ERROR_OK )
        ac->nextPlayBuf = 0x0;
    
    MP3_LOG("mp3DecodeFrame: nextPlayBuf = 0x%08x (ndx = %d)\n",
            (u32)ac->nextPlayBuf,((u32)ac->nextPlayBuf-(u32)ac->decBuf)/sizeof(ac->decBuf[0]));
    
    return rv;
}

/*
 * mp3PlaybackFrame -- decode and playback one MP3 frame through the
 * NC's headset jack; audio device must have been previously opened
 * and configured by mp3StartPlayback;
 *
 * return IOS_ERROR_OK on success
 *        MP3_STATUS_EOF if eof reached without error
 *        IOS_ERROR_INVALID_FORMAT if decoding error
 *        IOS_ERROR_NOTREADY if audio underflow
 *        other errors if problem receiving messages or calling mp3Stop
 */
static IOSError
mp3PlaybackFrame(Mp3Context *ac)
{
    IOSError rv = IOS_ERROR_OK;
    IOSError rvDec = IOS_ERROR_OK;
    int firstTime;
    u8 *prevBuf = 0x0;
    
    IOSMessage m;
    static IOSResourceRequest reply[2];

    MP3_LOG("decoding next frame\n");
    if ( (rvDec = mp3DecodeFrame(ac)) != IOS_ERROR_OK ) {
        goto out;
    }

    /* first time through ? */
    if ( ! ac->nAudWrites ) 
        firstTime = 1;
    else
        firstTime = 0;
    
    /* wait for first write to complete */
    if ( !firstTime ) {
        MP3_LOG("first recv\n");
        if ( (rv = IOS_ReceiveMessage(ac->audMq, &m, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
            MP3_ERROR("IOS_WriteAsync #1 receive");
            goto out;
        }
        ac->nAudWrites--;
        if ( (rv = ((IOSResourceRequest*)m)->status) == 4096 ) {
            /* no error, fall through */
#ifdef MP3_AUDIO_KEEP_OPEN
        } else if ( ac->muted && rv == IOS_ERROR_NOTREADY ) {
            /* ignore first underflow when keeping audio open */
            MP3_LOG("IOS_WriteAsync #1 ignoring first underflow\n");
#endif
#ifdef MP3_IGNORE_UNDERFLOW
        } else if ( rv == IOS_ERROR_NOTREADY ) { /* ignore underflow */
            MP3_LOG("IOS_WriteAsync #1 ignoring underflow\n");
#endif
        } else {
            MP3_ERROR("IOS_WriteAsync #1 status");
            MP3_LOG("IOS_WriteAsync #1 status failed, rv = %d\n", rv);
            goto out;
        }
        prevBuf = ((IOSResourceRequest*)m)->args.write.inPtr;
    }
    /* write first buffer */
    MP3_LOG("first write, buf = 0x%08x (ndx = %d)\n",
        (u32)ac->nextPlayBuf,
        ((u32)ac->nextPlayBuf-(u32)ac->decBuf)/sizeof(ac->decBuf[0]));
    reply[0].args.write.inPtr = &ac->nextPlayBuf[0];
    if ( (rv = IOS_WriteAsync(ac->audFd, &ac->nextPlayBuf[0], 1024*4, ac->audMq, &reply[0])) != IOS_ERROR_OK ) {
        MP3_ERROR("IOS_WriteAsync #1 submit");
        goto out;
    }
    ac->nAudWrites++;

    /* unmute volume now that audio has begun */
    if ( !firstTime && ac->muted ) {
        if ( (rv = IOS_Ioctl(ac->audFd,AUD_SET_VOLUME,&ac->volume,sizeof(ac->volume),0,0)) != IOS_ERROR_OK ) {
            MP3_ERROR("audio volume restore");
            /* XXX error code? */
            goto out;
        }
        ac->muted = 0;
    }

    /* wait for second write to complete */
    if ( !firstTime ) {
        MP3_LOG("second recv\n");
        if ( (rv = IOS_ReceiveMessage(ac->audMq, &m, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
            MP3_ERROR("IOS_WriteAsync #2 receive");
            goto out;
        }
        ac->nAudWrites--;
        if ( (rv = ((IOSResourceRequest*)m)->status) == 512 ) {
            /* no error, fall through */
#ifdef MP3_IGNORE_UNDERFLOW
        } else if ( rv == IOS_ERROR_NOTREADY ) { /* ignore underflow */
            MP3_LOG("IOS_WriteAsync #2 ignoring underflow\n");
#endif
        } else {
            MP3_ERROR("IOS_WriteAsync #2 status");
            MP3_LOG("IOS_WriteAsync #2 status failed, rv = %d\n", rv);
            goto out;
        }
    }
    /* write second buffer */
    MP3_LOG("second write, buf = 0x%08x (ndx = %d)\n",
        (u32)ac->nextPlayBuf,
        ((u32)ac->nextPlayBuf-(u32)ac->decBuf)/sizeof(ac->decBuf[0]));
    if ( (rv = IOS_WriteAsync(ac->audFd, &ac->nextPlayBuf[1024*4], 128*4, ac->audMq, &reply[1])) != IOS_ERROR_OK ) {
        MP3_ERROR("IOS_WriteAsync #2 submit");
        goto out;
    }
    ac->nAudWrites++;

    /* release buffer once write is completed */
    if ( ! firstTime ) {
        u32 ndx = ( (u32)prevBuf - (u32)ac->decBuf) / sizeof(ac->decBuf[0]);
        if ( (rv = mp3DtReleaseFrame(&ac->dti, ndx, prevBuf)) != IOS_ERROR_OK ) {
            MP3_ERROR("release frame");
            goto out;
        }
    }

    /* update time index */
    ac->mp3CurrTime += (1152UL*1000UL*MP3_TICKS_PER_MSEC)/ac->mp3SampleRate; /* 10's usec */

out:
    if ( rv == IOS_ERROR_OK )
        rv = rvDec;
    if ( rv != IOS_ERROR_OK ) {
        IOSError rv2 = mp3Stop(ac);
        if ( rv == IOS_ERROR_OK || rv == MP3_STATUS_EOF )
            rv = rv2;
    }
    
    ac->mp3PlayStatus = rv;

    return rv;
}
        
/*
 * mp3StartPlayback -- play an MP3 file
 */
static IOSError
mp3StartPlayback(Mp3Context *ac)
{
    IOSError rv = IOS_ERROR_OK;
    
    MP3_LOG("in mp3StartPlayback\n");

    ac->mp3Playing = 1;
    
    /* start decoder */
    if ( ac->mp3Reading ) {
        /* decoder already running */
        ac->mp3Reading = 0;
    } else {
        if ( (rv = mp3StartDecoder(ac)) != IOS_ERROR_OK ) {
            MP3_ERROR("playback starting decoder");
            goto out;
        }
    }

    ac->nextPlayBuf = 0x0;
    ac->readNdx = 0;

    /* open audio device */
#ifdef MP3_AUDIO_KEEP_OPEN
    if ( ac->audFd < 0 ) {
#endif        
    if ( (ac->audFd = rv = IOS_Open(AUD_DEV "0", O_WRONLY)) < 0 ) {
        MP3_ERROR("audio open");
        goto out;
    }

    /* mute audio volume until playback begins */
    u32 mute = MP3_VOLUME_MUTE;
    if ( (rv = IOS_Ioctl(ac->audFd,AUD_SET_VOLUME,&mute,sizeof(mute),0,0)) != IOS_ERROR_OK ) {
        MP3_ERROR("initial audio mute");
        /* XXX error code? */
        goto out;
    }
    ac->muted = 1;
    
    /* config audio device */
    u32 cfg;
    switch( ac->mp3SampleRate ) {
    case 44100: cfg = AUD_CONFIG_ADC_44P1_DAC_44P1; break;
    case 48000: cfg = AUD_CONFIG_ADC_48_DAC_48; break;
    case 32000: cfg = AUD_CONFIG_ADC_32_DAC_32; break;
    case  8000: cfg = AUD_CONFIG_ADC_8_DAC_8; break;
    default:
        MP3_ERROR("sample rate");
        MP3_LOG("MP3: unknown sample rate = %d\n",ac->mp3SampleRate);
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }

    MP3_LOG("mp3Play: config audio for %d Hz operation\n",ac->mp3SampleRate);
    if ( (rv = IOS_Ioctl(ac->audFd,AUD_SET_CONFIG,&cfg,sizeof(cfg),0,0)) != IOS_ERROR_OK ) {
        MP3_ERROR("audio config");
        /* XXX error code? */
        goto out;
    }

    /* create message queue */
    ac->audMq = rv = IOS_CreateMessageQueue(ac->audMsgArray, sizeof(ac->audMsgArray)/sizeof(ac->audMsgArray[0]));
    if ( rv < 0 ) {
        MP3_ERROR("IOS_CreateMessageQueue audio");
        goto out;
    }
#ifdef MP3_AUDIO_KEEP_OPEN
    }
#endif
    rv = IOS_ERROR_OK;

out:
    /* close audio device, if open */
    if ( rv != IOS_ERROR_OK ) {
        IOSError rv2;
        if ( (rv2 = mp3Stop(ac)) != IOS_ERROR_OK ) {
            MP3_ERROR("closing audio");
            if ( rv == IOS_ERROR_OK || rv == MP3_STATUS_EOF )
                rv = rv2;
        }
    }
    
    ac->mp3PlayStatus = rv;
    
    return rv;
}

/*
 * mp3Init -- initialized device for decoding mp3 file
 */
static IOSError
mp3Init(Mp3Context *ac)
{
    IOSError rv = IOS_ERROR_OK;
    
    /* find start of MP3 data, skipping header tags, if any */
    ac->mp3Start = rv = mp3FindStart(ac->mp3Fd, &ac->mp3i);
    if ( rv < 0 ) {
        MP3_ERROR("find MP3 start");
        goto out;
    }
    MP3_LOG("mp3Init: found start of MP3 data at offset = %d (0x%08x)\n",ac->mp3Start);
    mp3PrintHeader(&ac->mp3i); /* XXX */

    /* check if MP3 file type is supported for playback */
    MP3_LOG("mp3Init: check is supported\n");
    if ( ! mp3IsSupported(&ac->mp3i) ) {
        MP3_ERROR("support check");
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
    
    /* find end of MP3 data */
    ac->mp3End = rv = mp3FindEnd(ac->mp3Fd, &ac->mp3i);
    if ( rv < 0 ) {
        MP3_ERROR("find MP3 end");
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
    MP3_LOG("mp3Init: found end of MP3 data at offset = %d (0x%08x)\n",ac->mp3End);

    /* check that start < end */
    if ( ac->mp3Start >= ac->mp3End ) {
        MP3_ERROR("no MP3 data");
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }

    /* if freeformat encoding, determine frame length and bitrate */
    if ( ac->mp3i.bitrate == 0 ) { /* free format */
#if MP3_DECODER == MP3_DECODER_VSOFTS
        /* vsofts decoder does not support freeformat MP3 streams */
        rv = IOS_ERROR_INVALID_FORMAT;
        MP3_ERROR("freeformat bitrate");
        goto out;
#else
        if ( (rv = mp3GetFreeBitrate(ac->mp3Fd,&ac->mp3i,ac->mp3Start,ac->mp3End)) < 0 ) {
            if ( rv == IOS_ERROR_NOEXISTS ) /* no matching header found */
                rv = IOS_ERROR_INVALID_FORMAT;
            MP3_ERROR("freeformat bitrate");
            goto out;
        }
        rv = IOS_ERROR_OK;
        MP3_LOG("freeformat bitrate = %d kbps, length = %d\n",ac->mp3i.bitrate,ac->mp3i.len);
#endif
    }
    
    /* check for XING header */
    rv = mp3FindXing(ac->mp3Fd, ac->mp3Start, ac->mp3End, &ac->mp3i, &ac->xingInfo);
    if ( rv < 0 ) {
        MP3_ERROR("xing check");
        goto out;
    }
    MP3_LOG("mp3Init: Xing %s\n", rv==0 ? "not found" : "found");
    ac->hasXing = rv;
    
    /* check for VBRI header */
    if ( ! ac->hasXing ) {
        rv = mp3FindVbri(ac->mp3Fd, ac->mp3Start, ac->mp3End, &ac->mp3i, &ac->vbriInfo);
        if ( rv < 0 ) {
            MP3_ERROR("vbri check");
            goto out;
        }
        MP3_LOG("mp3Init: VBRI %s\n", rv==0 ? "not found" : "found");
        ac->hasVbri = rv;
    }

    /* seek back to beginning of MP3 data */
    rv = IOS_Seek(ac->mp3Fd, ac->mp3Start, SEEK_SET);
    if ( rv < 0 ) {
        MP3_ERROR("MP3 seek to start");
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

    /* set playback time index to start of track */
    ac->mp3CurrTime = 0;
    
    /* compute duration, use long long math to avoid overflows */
    if ( ac->hasXing ) {
        /* max freq = 48000 (i.e., 48KHz for MPEG v1,v2) ~= 2^16
         * max duration = (2^32 / MP3_TICKS_PER_MSEC) msec ~= 10 hours
         * max (ac->xingInfo.nFrames * 1152 * 1000 * MP3_TICKS_PER_MSEC)
         *     = max duration * max freq ~= 2^32 * 2^16 = 2^48
         */
        ac->mp3Duration = ( (u64)ac->xingInfo.nFrames * 1152 * 1000 * MP3_TICKS_PER_MSEC) / ac->mp3i.freq;
    } else if ( ac->hasVbri ) {
        /* max freq = 48000 (i.e., 48KHz for MPEG v1,v2) ~= 2^16
         * max duration = (2^32 / MP3_TICKS_PER_MSEC) msec ~= 10 hours
         * max (ac->vbriInfo.nFrames * 1152 * 1000 * MP3_TICKS_PER_MSEC)
         *     = max duration * max freq ~= 2^32 * 2^16 = 2^48
         */
        ac->mp3Duration = ( (u64)ac->vbriInfo.nFrames * 1152 * 1000 * MP3_TICKS_PER_MSEC) / ac->mp3i.freq;
    } else {
        /* max duration = (2^32 / MP3_TICKS_PER_MSEC) msec ~= 10 hours
         * max bitrate = 640 (Kbits/sec) ~= 2^10 Kbits/sec = 2^10 bits/msec
         * actual bits = nb * 8 ~= 2^13
         * actual duration (msec) = actual bits / max bitrate (bits/msec)
         * actual duration, ticks = actual bits / max bitrate (bits/msec) * (ticks/msec)
         *                        = actual bits / max bitrate (bits/msec) * MP3_TICKS_PER_MSEC
         *                        = (actual bits * MP3_TICKS_PER_MSEC) / max bitrate (bits/msec)
         * max(nb * 8 * MP3_TICKS_PER_MSEC) = max duration * max bitrate ~= 2^32 * 2^10 = 2^42
         * max # bytes ~= 2^42 / (8 * MP3_TICKS_PER_MSEC) ~= 2^33
         */
        u64 nb = ac->mp3End - ac->mp3Start;
        ac->mp3Duration = (nb * 8 * MP3_TICKS_PER_MSEC) / ac->mp3i.bitrate;  /* in 10's usec */
    }
    MP3_LOG("mp3Init: duration = %d\n",ac->mp3Duration);
    if ( ac->mp3Duration == 0 ) {
        MP3_ERROR("MP3 duration check");
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
    
    /* initialize MP3 decoder */
    MP3_LOG("mp3Init: initializing MP3 decoder\n");
    rv = mp3DecoderInit(&ac->di, ac->mp3Fd, ac->mp3Start, ac->mp3End, (u8 *)ac->encBuf);
    if ( rv ) {
        MP3_ERROR("initialize MP3 decoder");
        rv = IOS_ERROR_UNKNOWN;
        goto out;
    }
    ac->dtInit = 1;

    /* initialize MP3 decoder thread */
    MP3_LOG("mp3Init: initializing MP3 decoder thread\n");
    rv = mp3DtInit(&ac->dti,&ac->di);
    if ( rv ) {
        MP3_ERROR("initialize MP3 decoder thread");
        rv = IOS_ERROR_UNKNOWN;
        goto out;
    }
    ac->decoderInit = 1;
    
    /* read MP3 header */
    MP3_LOG("read MP3 header\n");
    u32 header;
    Mp3Info mp3il;

#if MP3_DECODER == MP3_DECODER_ITTIAM
    if ( (rv = mp3DecoderGetHeader(&ac->di, ac->decBuf[0], &header)) < 0 ) {
#else
    if ( (rv = mp3DecoderGetHeader(&ac->di, &header)) < 0 ) {
#endif
        MP3_ERROR("calling mp3DecoderGetHeader");
        MP3_LOG("ERROR calling mp3DecoderGetHeader, rv = %d\n",rv);
        goto out;
    }
    
    if ( ! mp3ParseHeader(header, &mp3il) ) {
        MP3_ERROR("parse MP3 header");
        rv = IOS_ERROR_INVALID_FORMAT;
    }
    mp3PrintHeader(&mp3il);

    ac->mp3SampleRate = mp3il.freq;
    MP3_LOG("mp3Init: sample rate = %d Hz, %d Hz\n",ac->mp3SampleRate,ac->mp3i.freq);

out:    
    return rv;
}

/*
 * mp3Shutdown -- close MP3 file and de-initialize mp3 decoder
 */
static IOSError
mp3Shutdown(Mp3Context *ac)
{
    IOSError rv = IOS_ERROR_OK, rv2;
    
    /* close MP3 file */
    if ( ac->mp3Fd >= 0 ) {
        if ( (rv = IOS_Close(ac->mp3Fd)) == IOS_ERROR_OK ) {
            ac->mp3Fd = -1;
        } else {
            MP3_ERROR("close MP3 file");
            /* fall through */
        }
    }

    /* shut down the decoder thread */
    if ( ac->dtInit ) {
        if ( (rv2 = mp3DtDeinit(&ac->dti)) == IOS_ERROR_OK ) {
            ac->dtInit = 0;
        } else {
            MP3_ERROR("shut down MP3 decoder thread");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
            /* fall through */
        }
    }
             
    /* shut down decoder */
    if ( ac->decoderInit ) {
        if ( mp3DecoderDeinit(&ac->di) == IOS_ERROR_OK ) {
            ac->decoderInit = 0;
        } else {
            MP3_ERROR("shut down MP3 decoder");
            if ( rv == IOS_ERROR_OK )
                rv = IOS_ERROR_UNKNOWN;
            /* fall through */
        }
    }
        
    return rv;
}

/*
 * mp3ResetContext -- reset device context to initial/unused state
 */
static void
mp3ResetContext(Mp3Context *ac)
{
    ac->state = MP3_STATE_CLOSED;
    ac->volume = MP3_VOLUME_DEFAULT;
    ac->muted = 1;
    ac->flags = 0;
    ac->mp3Duration = 0;
    ac->mp3Start = 0;
    ac->mp3End = 0;
    ac->mp3CurrTime = 0;
    ac->mp3NeedSeek = 0;
    ac->mp3Reading = 0;
    ac->mp3Playing = 0;
    ac->mp3PlayStatus = IOS_ERROR_OK;  /* stopped */
    ac->mp3SampleRate = 0;
    ac->mp3i.valid = 0;
    ac->hasXing = 0;
    ac->hasVbri = 0;
    /* xingInfo/vbriInfo */
    ac->mp3Fd = -1;
    ac->audFd = -1;
    /* encBuf */
    /* decBuf */
    ac->nextPlayBuf = 0x0; /* no buffers have valid data */
    ac->readNdx = 0;
    /* di */
    ac->decoderInit = 0;
    /* dti */
    ac->dtInit = 0;
    ac->audMq = -1;
    /* audMsgArray */
    ac->nAudWrites = 0;
#if defined(MP3_RESYNC_MANUAL) || defined(MP3_RESYNC_MAINDATA)
    ac->nIgnoreFrames = 0;
#endif
}

/*
 * mp3Open -- open the MP3 device
 */
static IOSError
mp3Open(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    u32 dev = 0;
    IOSResourceOpen *args = &req->args.open;
    Mp3Context *ac = (Mp3Context *)NULL;
    int i;

    MP3_LOG("in mp3Open: '%s', f=%d, u=%d, g=%d\n", args->path, args->flags, args->uid, args->gid);
    MP3_LOG("in mp3Open: sizeof(MP3_DEV=\"%s\") = %d\n",MP3_DEV,sizeof(MP3_DEV));

    /* check whether we handle the requested device name */
    if (!strncmp(args->path, MP3_DEV "/", sizeof(MP3_DEV))) {
        MP3_LOG("mp3Open: strncmp(%s,%s,%d)\n",args->path, MP3_DEV "/", sizeof(MP3_DEV));
        dev = 0;
    } else {
        rv = IOS_ERROR_NOEXISTS;
        goto out;
    }

    /* determine whether there's a device available */
    for (i = 0; i < MP3_NUM_DEV; ++i) {
        if (mp3Context[i].state == MP3_STATE_CLOSED) {
            break;
        }
    }

    /* error out if not device available */
    if (i == MP3_NUM_DEV) {
        rv = IOS_ERROR_MAX;
        goto out;
    }

    /* device context to use for this request */
    ac = &mp3Context[i];

    /* check for valid flags */
    switch ( args->flags & O_ACCMODE ) {
    case O_RDONLY:
    case O_WRONLY:
    case O_RDWR:
        ac->flags = args->flags;
        break;
    default:
        rv = IOS_ERROR_INVALID_FLAG;
        goto out;
        break;
    }

    /* open MP3 file */
    MP3_LOG("opening: %s\n",args->path+sizeof(MP3_DEV)-1);
    rv = ac->mp3Fd = ISFS_Open(args->path+sizeof(MP3_DEV)-1, 1);
    if ( rv < 0 ) {
        MP3_ERROR("opening MP3 file");
        goto out;
    }

    /* initialize device context */
    ac->state = MP3_STATE_OPEN;
    
    /* finish initialization */
    if ( (rv = mp3Init(ac)) != IOS_ERROR_OK ) {
        MP3_ERROR("initializing");
        goto out;
    }
    
    rv = (IOSError) &mp3Context[i];
    
out:
    if ( rv < 0 && ac != NULL ) {
        /* clear device context state if the open failed */
        mp3Shutdown(ac);
        mp3ResetContext(ac);
    }
    
    return rv;
}

/*
 * mp3Close -- close the MP3 device
 */
static IOSError
mp3Close(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID, rv2;
    Mp3Context *ac = (Mp3Context *) req->handle;

    MP3_LOG("in mp3Close\n");

    /* check if ok to close */
    ac->state = MP3_STATE_CLOSED;

    /* stop playback, if in progress */
    if ( ac->mp3Playing ) {
        if ( (rv = mp3Stop(ac)) != IOS_ERROR_OK ) {
            MP3_ERROR("mp3 stop");
        }
    }

    /* stop decode-ahead, if read in progress */
    if ( ac->mp3Reading ) {
        MP3_LOG("mp3Close: read in progress, stop decoder\n");
        if ( (rv2 = mp3StopDecoder(ac)) != IOS_ERROR_OK ) {
            MP3_ERROR("mp3Close: stop decoder");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
        }
        ac->mp3Reading = 0;
    }
        
    /* close MP3 file and de-initialize mp3 decoder */
    if ( (rv2 = mp3Shutdown(ac)) != IOS_ERROR_OK ) {
        MP3_ERROR("mp3 shutdown");
        if ( rv == IOS_ERROR_OK )
            rv = rv2;
    }

#ifdef MP3_AUDIO_KEEP_OPEN
    /* clean up audio queue */
    if ( ac->audMq >= 0 ) {
        MP3_LOG("destroying audio queue\n");
        if ( (rv2 = IOS_DestroyMessageQueue(ac->audMq)) == IOS_ERROR_OK ) {
            ac->audMq = -1;
        } else {
            MP3_ERROR("IOS_DestroyMessageQueue audio");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
        }
    }
    
    /* close audio device */
    if ( ac->audFd >= 0 ) {
        MP3_LOG("closing audio device\n");
        if ( (rv2 = IOS_Close(ac->audFd)) == IOS_ERROR_OK ) {
            ac->audFd = -1;
        } else {
            MP3_ERROR("closing audio");
            if ( rv == IOS_ERROR_OK )
                rv = rv2;
        }
    }
#endif

    if ( rv == IOS_ERROR_OK )
        mp3ResetContext(ac);
    
    return rv;
}

/*
 * mp3Read -- read decoded MP3 samples
 */
static IOSError
mp3Read(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    Mp3Context *ac = (Mp3Context *) req->handle;
    IOSResourceRead *args = &req->args.read;
    u32 nb = 0;
#ifdef MP3_READ_8BIT_SAMPLES
    s8 *p = (s8 *)args->outPtr;
#else
    s16 *p = (s16 *)args->outPtr;
#endif
    
    MP3_LOG("mp3Read: in=(0x%08x,%d)\n", args->outPtr, args->outLen);

    /* reads can't be performed while playback is in progress */
    if ( ac->mp3Playing ) {
        rv = IOS_ERROR_NOTREADY;
        goto out;
    }
    /* check that request is for an even number of samples, so there's
       always one sample for each of the two stereo channels */
    if ( args->outLen % 4 != 0 ) {
        rv = IOS_ERROR_INVALID_SIZE;
        goto out;
    }
    /* check that request buffer is word aligned */
    if ( (u32)(args->outPtr) % 4 != 0 ) {
        rv = IOS_ERROR_INVALID;
        goto out;
    }
    /* shortcut if no samples are requested */
    if ( args->outLen == 0 ) {
        rv = (IOSError) 0;
        goto out;
    }

#ifdef MP3_AUDIO_KEEP_OPEN
    /* a valid read request has been received, indicating that
     * the user wants to use decode-only mode; if audio is open,
     * then assume the user is converting from NC audio to GBA
     * audio; in this case, it should be ok to power down the
     * NC audio (to save power) even though it'll cause an
     * audible pop because (presumably) the headset is already
     * disconnected.
     */
    if ( ac->audFd >= 0 ) {
        MP3_LOG("closing audio device\n");
        if ( (rv = IOS_Close(ac->audFd)) == IOS_ERROR_OK ) {
            ac->audFd = -1;
        } else {
            MP3_ERROR("closing audio");
            goto out;
        }
    }
#endif
    
    /* loop, decoding MP3 frames and copying the decoded samples into
       the user's data buffer */
    s16 *buf;
    
    while ( nb < args->outLen ) {
        if ( ac->nextPlayBuf == 0x0 ) {
            /* read new frame */
            if ( ! ac->mp3Reading ) {
                /* start decoder */
                if ( (rv = mp3StartDecoder(ac)) != IOS_ERROR_OK ) {
                    MP3_ERROR("read start decoder");
                    break;
                }
                ac->mp3Reading = 1;
            }
            MP3_LOG("decoding more MP3 data (read)\n");
            if ( (rv = mp3DecodeFrame(ac)) < 0 ) {
                MP3_ERROR("decoding MP3 frame (read)");
                break;
            } else if ( rv == MP3_STATUS_EOF ) {
                rv = nb;
                break;
            }
        }

        buf =  (s16 *)ac->nextPlayBuf;
        
        if ( ac->readNdx < 1152 ) {
            /* copy decoded samples to user's data buffer */
#ifdef MP3_READ_8BIT_SAMPLES
            *p++ = buf[2*ac->readNdx]/256; /* convert samples from 16-bit to 8-bit */
            *p++ = buf[2*ac->readNdx+1]/256;
#else
            *p++ = buf[2*ac->readNdx];
            *p++ = buf[(2*ac->readNdx)+1];
#endif
/*
            MP3_LOG("mp3Read: readNdx = %d (0x%0x), buf[%d (0x%0x)] = %d (0x%04x) -> %d (0x%02x, 0x%02x)\n",
                    2*ac->readNdx, 2*ac->readNdx, nb, nb, 
                    buf[2*ac->readNdx], buf[2*ac->readNdx],
                    buf[2*ac->readNdx]/256, buf[2*ac->readNdx]/256, p[-2]);
            MP3_LOG("mp3Read: readNdx = %d (0x%0x), buf[%d (0x%0x)] = %d (0x%04x) -> %d (0x%02x, 0x%02x)\n",
                    2*ac->readNdx+1, 2*ac->readNdx+1, nb+1, nb+1, 
                    buf[2*ac->readNdx+1], buf[2*ac->readNdx+1],
                    buf[2*ac->readNdx+1]/256, buf[2*ac->readNdx+1]/256, p[-1]);
*/
            ac->readNdx++;
#ifdef MP3_READ_8BIT_SAMPLES
            nb += 2;
#else
            nb += 4;
#endif
        }
        if ( ac->readNdx == 1152 ) {
            ac->readNdx = 0;
            u32 ndx = ( (u32)ac->nextPlayBuf - (u32)ac->decBuf) / sizeof(ac->decBuf[0]);
            if ( (rv = mp3DtReleaseFrame(&ac->dti, ndx, ac->nextPlayBuf)) != IOS_ERROR_OK ) {
                MP3_ERROR("read release frame");
                goto out;
            }
            ac->nextPlayBuf = 0x0;
            /* update time index */
            ac->mp3CurrTime += (1152UL*1000UL*MP3_TICKS_PER_MSEC)/ac->mp3SampleRate; /* 10's usec */
        }
        
    }
    
    rv = nb;
    
out:
    return rv;
}


/*
 * mp3Seek -- seek to a new position within the MP3 file
 *
 * file position is specified in units of milliseconds
 */
static IOSError
mp3Seek(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID;

    Mp3Context *ac = (Mp3Context *) req->handle;
    IOSResourceSeek *args = &req->args.seek;
    u32 offset;
    s32 argsOffset;

    MP3_LOG("mp3Seek: offset = %d, whence = %d\n",args->offset,args->whence);

#define MAX_S32 (s32)(0x7FFFFFFF)
#define MIN_S32 (s32)(-MAX_S32-1)
#define IN_BOUNDS(v,min,max)  ( (v) >= (s32)(min) && (v) <= (s32)(max) )
        
    if ( ! IN_BOUNDS(args->offset, MIN_S32/MP3_TICKS_PER_MSEC, MAX_S32/MP3_TICKS_PER_MSEC) ) {
        MP3_ERROR("mp3Seek: absolute bounds check");
        rv = IOS_ERROR_INVALID;
        goto out;
    }
    argsOffset = args->offset * MP3_TICKS_PER_MSEC; /* convert units to 10's usec */
    MP3_LOG("mp3Seek: scaled offset argument = %d\n",argsOffset);
     
    switch (args->whence) {
    case IOS_SEEK_SET:
        if ( ! IN_BOUNDS(argsOffset, 0, ac->mp3Duration) ) {
            MP3_ERROR("mp3Seek: seek set bounds check");
            rv = IOS_ERROR_INVALID;
            goto out;
        }
        offset = argsOffset;
        break;
    case IOS_SEEK_CURRENT:
        if ( ! IN_BOUNDS(argsOffset, -ac->mp3CurrTime, ac->mp3Duration-ac->mp3CurrTime) ) {
            MP3_ERROR("mp3Seek: seek current bounds check");
            rv = IOS_ERROR_INVALID;
            goto out;
        }
        offset = ac->mp3CurrTime + argsOffset;
        break;
    case IOS_SEEK_END:
        if ( ! IN_BOUNDS(argsOffset, -ac->mp3Duration, 0) ) {
            MP3_ERROR("mp3Seek: seek end bounds check");
            rv = IOS_ERROR_INVALID;
            goto out;
        }
        offset = ac->mp3Duration + argsOffset;
        break;
    default:
        rv = IOS_ERROR_INVALID;
        goto out;
        break;
    }

    MP3_LOG("mp3Seek: offset = %d\n",offset);
    if ( offset < 0 || offset > ac->mp3Duration ) {
        rv = IOS_ERROR_INVALID;
        goto out;
    }

    if ( args->whence == IOS_SEEK_CURRENT && args->offset == 0 ) {
        /* shortcut if seeking to current position */
        /* when seeking thru a file, especially a VBR file, time errors
         * could add up such that the estimated current time would
         * exceed the file duration.  This isn't a problem for the
         * MP3 decoder, but would be confusing to the user, so cap
         * the current time reported to the user to be less than
         * of equal to the duration
         */
        if ( ac->mp3CurrTime <= ac->mp3Duration )
            rv = ac->mp3CurrTime / MP3_TICKS_PER_MSEC;
        else
            rv = ac->mp3Duration / MP3_TICKS_PER_MSEC;
    } else {
        s32 nb;

        /* convert to byte location by linear interpolation */
        MP3_LOG("mp3Seek: converting from time to bytes: start=%d, end=%d, duration = %d\n",
                ac->mp3Start,ac->mp3End,ac->mp3Duration);
        if ( ac->mp3Duration == 0 ) {
            nb = ac->mp3Start;
        } else if ( ac->hasXing ) {
            /* use Xing table of contents to compute new byte location */
            nb = mp3XingTimeToOffset(offset, ac->mp3Duration,
                                     ac->mp3Start, ac->mp3End,
                                     &ac->xingInfo);
            MP3_LOG("mp3Seek: xing: %d msec => %d bytes\n",offset/MP3_TICKS_PER_MSEC,nb);
        } else if ( ac->hasVbri ) {
            /* use VBRI table of contents to compute new byte location */
            nb = mp3VbriTimeToOffset(offset, ac->mp3Duration,
                                     ac->mp3Start, ac->mp3End,
                                     &ac->vbriInfo);
            MP3_LOG("mp3Seek: vbri: %d msec => %d bytes\n",offset/MP3_TICKS_PER_MSEC,nb);
        } else {
            /* compute new byte location by linear interpolation */
            /* note that this only works for CBR files */
            nb = ac->mp3Start + (((u64)offset) * (ac->mp3End - ac->mp3Start)) / ac->mp3Duration;
            MP3_LOG("mp3Seek: linear: %d msec => %d bytes [%d + %d * (%d - %d) / %d]\n",
                    offset/MP3_TICKS_PER_MSEC,nb,
                    ac->mp3Start,offset/MP3_TICKS_PER_MSEC,
                    ac->mp3End,ac->mp3Start,
                    ac->mp3Duration/MP3_TICKS_PER_MSEC);
        }

        /* stop decode-ahead, if reading */
        if ( ac->mp3Reading ) {
            MP3_LOG("mp3Seek: read in progress, stop decoder\n");
            if ( (rv = mp3StopDecoder(ac)) != IOS_ERROR_OK ) {
                MP3_ERROR("mp3Seek: stop decoder");
                goto out;
            }
            ac->mp3Reading = 0;
        }
        
        /* attempt to resync MP3 stream at new file location */
        MP3_LOG("mp3Seek: resyncing at offset = %d\n",nb);
        if ( (rv = mp3Resync(ac->mp3Fd, &ac->mp3i, nb, ac->mp3End,
                             MP3_HEADER_FINGERPRINT_MASK)) < 0 ) {
            rv = IOS_ERROR_INVALID_FORMAT;
            MP3_ERROR("mp3Seek: resync\n");
            goto out;
        }
        nb = rv;
        
#ifdef MP3_RESYNC_STANDALONE
        /* try to skip to a standalone MP3 frame, i.e., one that
         * doesn't depend on data in previous frames.  Because,
         * in general, we can't guarantee that the decoder won't
         * try to use pre-skip data when attempting to decode
         * post-skip frames
         */
        u32 nskip = 0; /* number of frames until standalone */
        
        rv = mp3FindStandaloneFrame(ac->mp3Fd, &ac->mp3i,
                                    nb, ac->mp3End,
                                    MP3_HEADER_FINGERPRINT_MASK,
                                    &nskip);
        if ( rv >= 0 ) {
            /* found standalone frame, skip forward to it */
            MP3_LOG("mp3Seek: found standalone, skipped %d frames\n",nskip);
            nb = rv;
        } else if ( rv == IOS_ERROR_INVALID_FORMAT ||
                    rv == IOS_ERROR_NOEXISTS ) {
            /* didn't find standalone frame, start at non-standalone frame */
            MP3_LOG("mp3Seek: using non-standalone frame\n");
        } else {
            MP3_ERROR("mp3FindStandaloneFrame call");
            goto out;
        }
#endif
#ifdef MP3_RESYNC_MAINDATA
        /* the target frame may use Main Data from previous frames
         * and therefore decode improperly; compute the number of
         * frames that will decode improperly, then ignore that
         * number of frames when decoding recommences.
         */
        rv = mp3ResyncMainData(ac->mp3Fd, &ac->mp3i,
                               nb, ac->mp3End,
                               MP3_HEADER_FINGERPRINT_MASK);
        if ( rv >= 0 ) {
            /* resync possible, need to ignore initial frames when decoding */
            MP3_LOG("mp3Seek: resync Main Data, ignore %d frames\n",rv);
        } else if ( rv == IOS_ERROR_INVALID_FORMAT ||
                    rv == IOS_ERROR_NOEXISTS ) {
            /* resync not possible, or invalid file format;
             * go ahead and use the improperly decoded frames;
             * this will probably cause audible artifacts, but
             * is insurance in case the resync algorithm is
             * broken
             */
            MP3_LOG("mp3Seek: resync not found, continuing any way\n");
            rv = 0;
            /* fall through */
        } else {
            MP3_ERROR("mp3FindStandaloneFrame call");
            goto out;
        }

        ac->nIgnoreFrames = rv; /* number of frames to ignore */
        if ( ac->nIgnoreFrames )
            ac->nIgnoreFrames++; /* XXX hack, is this needed? why? */
#endif
#ifdef MP3_RESYNC_MANUAL
        /* decode and ignore 2 frames to try and ensure that the
         * ensuing frame doesn't use data from the previous playback
         */
        ac->nIgnoreFrames = 2;
#endif

        /* seek to byte location */
        MP3_LOG("mp3Seek: bytes offset = %d\n",nb);
        if ( (rv = IOS_Seek(ac->mp3Fd,nb,IOS_SEEK_SET)) != nb ) {
            rv = IOS_ERROR_FAIL_INTERNAL;
            goto out;
        }

        /* update current time index */
        ac->mp3CurrTime = offset;
        rv = ac->mp3CurrTime / MP3_TICKS_PER_MSEC;
        /* flush decoder's input buffer, so it'll start decoding at the current file posn */
        mp3DecoderFlushInputBuffer(&ac->di,nb);
        /* reset read pointer, so next IOS_Read() will start at the current file posn */
        if ( ! ac->mp3Playing )
            ac->nextPlayBuf = 0x0;
        ac->readNdx = 0;
        ac->mp3NeedSeek = 0;
    }
    
out:
    return rv;
}

/*
 * mp3Ioctl
 */
static IOSError
mp3Ioctl(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID, rv2;
    Mp3Context *ac = (Mp3Context *) req->handle;
    s32 audFdOrig;
    
    MP3_LOG("in mp3Ioctl: cmd=%d, in=(%d,%d), out=(%d,%d)\n",
            req->args.ioctl.cmd,
            req->args.ioctl.inPtr, req->args.ioctl.inLen,
            req->args.ioctl.outPtr, req->args.ioctl.outLen);

    switch ( req->args.ioctl.cmd ) {
    case MP3_PLAY:
        MP3_LOG("mp3Ioctl: MP3_PLAY\n");
        if ( ac->mp3Playing ) {
            /* MP3_PLAY already in progress */
            rv = IOS_ERROR_NOTREADY;
        } else {
            /* start playing stream */
            rv = mp3StartPlayback(ac);
        }
        break;
    case MP3_STOP:
        /* stop playing stream */
        MP3_LOG("mp3Ioctl: MP3_STOP\n");
        if ( ac->mp3Playing ) {
            rv = mp3Stop(ac);
        } else {
            rv = IOS_ERROR_NOTREADY;
        }
        break;
    case MP3_SET_VOLUME:
        /* set volume */
        MP3_LOG("mp3Ioctl: MP3_SET_VOLUME\n");
        if ( ac->audFd >= 0 && ! ac->muted ) {
            /* pass the request to the audio device is it's open; 
               mirror the new volume setting, if successful */
            rv = IOS_Ioctl(ac->audFd,AUD_SET_VOLUME,
                           (void *)req->args.ioctl.inPtr,req->args.ioctl.inLen,
                           (void *)req->args.ioctl.outPtr,req->args.ioctl.outLen);
            if ( rv == IOS_ERROR_OK )
                ac->volume = *((u32 *)req->args.ioctl.inPtr);
        } else {
            /* check the arguments and store the new volume locally,
               if the audio device isn't open */
            if (req->args.ioctl.inPtr && req->args.ioctl.inLen == sizeof(u32) ) {
                u32 v = *((u32 *)req->args.ioctl.inPtr);
                /* check for legal bounds */
                if ( (v < MP3_VOLUME_MIN || v > MP3_VOLUME_MAX) && (v != MP3_VOLUME_MUTE) ) {
                    rv = IOS_ERROR_INVALID_FLAG;
                    break;
                }
                if ( req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
                    /* return the old value if outPtr & outLen are valid */
                    *((u32*)req->args.ioctl.outPtr) = ac->volume;
                }
                /* set volume */
                ac->volume = v;
                rv = IOS_ERROR_OK;
            }
        }
        break;
    case MP3_GET_VOLUME:
        /* get volume */
        MP3_LOG("mp3Ioctl: MP3_GET_VOLUME\n");
        if ( ac->audFd >= 0 && ! ac->muted ) {
            rv = IOS_Ioctl(ac->audFd,AUD_GET_VOLUME,
                           (void *)req->args.ioctl.inPtr,req->args.ioctl.inLen,
                           (void *)req->args.ioctl.outPtr,req->args.ioctl.outLen);
        } else {
            if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
                *((u32 *)req->args.ioctl.outPtr) = ac->volume;
                rv = IOS_ERROR_OK;
            } 
        }
        break;
    case MP3_GET_HEADSET:
        MP3_LOG("mp3Ioctl: MP3_GET_HEADSET\n");
        audFdOrig = ac->audFd;
        /* open audio device, if not already open */
        if ( audFdOrig < 0 && (ac->audFd = rv = IOS_Open(AUD_DEV "0", O_WRONLY)) < 0 ) {
            MP3_ERROR("headset audio open");
            rv = IOS_ERROR_NOTREADY;
            break;
        }
        /* check for headset */
        rv = IOS_Ioctl(ac->audFd,AUD_GET_HEADSET,
                       (void *)req->args.ioctl.inPtr,req->args.ioctl.inLen,
                       (void *)req->args.ioctl.outPtr,req->args.ioctl.outLen);
        /* close audio device, if it was originally closed */
        if ( audFdOrig < 0 && (rv2 = IOS_Close(ac->audFd)) != IOS_ERROR_OK ) {
            MP3_ERROR("headset audio close");
            if ( rv >= 0 )
                rv = IOS_ERROR_NOTREADY;
            break;
        }
        ac->audFd = audFdOrig;
        break;
    case MP3_GET_SAMPLE_RATE:
        /* get sample rate */
        MP3_LOG("mp3Ioctl: MP3_GET_SAMPLE_RATE\n");
        if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
            *((u32 *)req->args.ioctl.outPtr) = ac->mp3SampleRate;
            rv = IOS_ERROR_OK;
        } 
        break;
    case MP3_GET_STATUS:
        /* get playback status */
        MP3_LOG("mp3Ioctl: MP3_GET_STATUS\n");
        if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
            IOSError v;
            if ( ac->mp3Playing )
                v = MP3_PLAYING;  /* still playing */
            else if ( ac->mp3PlayStatus == MP3_STATUS_EOF )
                v = MP3_STOPPED;  /* stopped at eof */
            else
                v = ac->mp3PlayStatus; /* exit status */
            *((IOSError *)req->args.ioctl.outPtr) = v;
            rv = IOS_ERROR_OK;
        }
        break;
    default:
        rv = IOS_ERROR_INVALID;
        break;
    }
    
    return rv;
}

/*
 * mp3DispatchMsg -- dispatch a command message
 */
static void
mp3DispatchMsg(IOSMessage msg, s32 playing)
{
    IOSError rv;

    /* Check for shutdown request */
    if (msg == (IOSMessage) mp3LibStopRm) {
        printf("mp3DispatchMsg: Shutdown request");
        IOS_DestroyThread(0, (void *)0x42);
        /* should not return */
    }

    MP3_LOG("mp3DispatchMsg: Received resource request: %08x\n", msg);
    IOSResourceRequest *req = (IOSResourceRequest *) msg;

    switch (req->cmd) {
    case IOS_OPEN:
        MP3_LOG("  IOS_OPEN %08x\n", msg);
        if ( playing ) 
            rv = IOS_ERROR_NOTREADY;
        else
            rv = mp3Open(req);
        MP3_LOG("  IOS_OPEN %08x Returning = %d (%s)\n", msg, rv, rv < 0 ? "fail" : "pass");
        break;
    case IOS_CLOSE:
        MP3_LOG("  IOS_CLOSE %08x\n", msg);
        if ( playing )
            rv = IOS_ERROR_NOTREADY;
        else
            rv = mp3Close(req);
        MP3_LOG("  IOS_CLOSE %08x Returning = %d\n", msg, rv);
        break;
    case IOS_READ:
        MP3_LOG("  IOS_READ %08x\n", msg);
        rv = mp3Read(req);
        MP3_LOG("  IOS_READ %08x Returning = %d\n", msg, rv);
        break;
    case IOS_WRITE:
        MP3_LOG("  IOS_WRITE %08x (unsupported)\n", msg);
        rv = IOS_ERROR_INVALID;
        MP3_LOG("  IOS_WRITE %08x Returning = %d\n", msg, rv);
        break;
    case IOS_SEEK:
        MP3_LOG("  IOS_SEEK %08x\n", msg);
        rv = mp3Seek(req);
        MP3_LOG("  IOS_SEEK %08x Returning = %d\n", msg, rv);
        break;
    case IOS_IOCTL:
        MP3_LOG("  IOS_IOCTL %08x\n", msg);
        rv = mp3Ioctl(req);
        MP3_LOG("  IOS_IOCTL %08x Returning = %d\n", msg, rv);
        break;
    case IOS_IOCTLV:
        MP3_LOG("  IOS_IOCTLV %08x (unsupported)\n", msg);
        rv = IOS_ERROR_INVALID;
        MP3_LOG("  IOS_IOCTLV %08x Returning = %d\n", msg, rv);
        break;
    default:
        MP3_LOG("  Unsupported %08x\n", msg);
        rv = IOS_ERROR_INVALID;
        MP3_LOG("  Unsupported %08x Returning = %d\n", msg, rv);
        break;
    } /* switch */

    IOS_ResourceReply(req, rv);
    
}

/*
 * main dispatch loop for MP3 RM
 */
int
mp3LibRmLoop(void *arg)
{
    IOSError rv;
    IOSMessageQueueId mq = (IOSMessageQueueId) arg;
    IOSMessage msg;
    u32 i;
   
    /* initialize private data structures */
    for (i=0; i<MP3_NUM_DEV; i++) {
        mp3ResetContext(&mp3Context[i]);
    }

#ifdef TEST_PROC
    MP3_LOG("Starting testProc\n");
    testTid = IOS_CreateThread((IOSEntryProc)testProc, 0, _testStack+STACK_SIZE, STACK_SIZE, 10, IOS_THREAD_CREATE_DETACHED);
    IOS_StartThread(testTid);
#endif

    MP3_LOG("Starting RM loop\n");

    while (1) {
        MP3_LOG("waiting for msg\n");
        
        /* Receive a command, don't block if actively playing */

        if (mp3Context[0].mp3Playing) {
            /* don't block */
            MP3_LOG("ReceiveMessage (nonblocking)\n");
            rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_NOBLOCK);
            if (rv == IOS_ERROR_OK) {
                MP3_LOG("dispatching message 0x%08x (nonblocking)\n",(u32)msg);
                mp3DispatchMsg(msg,1);
            } else if (rv != IOS_ERROR_QEMPTY) {
                MP3_ERROR("IOS_ReceiveMessage (nonblocking)");
                goto out;
            }
        } else {
            /* block */
            MP3_LOG("ReceiveMessage (blocking)\n");
            if ((rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
                MP3_ERROR("IOS_ReceiveMessage (blocking)");
                goto out;
            }
            MP3_LOG("dispatching message 0x%08x (blocking)\n",(u32)msg);
            mp3DispatchMsg(msg,0);
        }

        /* if actively playing, decode and play next MP3 frame */
        if (mp3Context[0].mp3Playing) {
            /* mp3PlaybackFrame blocks internally, waiting for the
               previous set of audio writes to complete */
            MP3_LOG("mp3PlaybackFrame: playing = %d\n",mp3Context[0].mp3Playing);
            rv = mp3PlaybackFrame(&mp3Context[0]);
            MP3_LOG("mp3PlaybackFrame: exit status %d\n",rv);
        }
        
    } /* while */

out:
    MP3_LOG("RM Exiting\n");
    return 0;
}

int
mp3LibStopRm(IOSMessageQueueId mq)
{
    IOSError rv = IOS_ERROR_OK;
    int i;

    /* if device currently open, fail the request */
    for (i = 0; i < MP3_NUM_DEV; ++i) {
        if (mp3Context[i].state != MP3_STATE_CLOSED) {
            return IOS_ERROR_NOTREADY;
        }
    }

#ifdef TEST_PROC
    if (testTid >= 0) {
        MP3_LOG("Killing testProc\n");
        rv = IOS_StopThread(testTid);
        rv = IOS_DestroyThread(testTid, 0);
        testTid = -1;
    }
#endif

    /* send shutdown message to the RM thread */
    rv = IOS_SendMessage(mq, (IOSMessage) mp3LibStopRm, IOS_MESSAGE_BLOCK);

    return rv;
}
