/*
 *               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 <sc/ios.h>
#include <ioslibc.h>
#include <sc/iostypes.h>
#include <fs.h>

#include "mp3utils.h"

/* #define MP3U_DEBUG */

#ifdef MP3U_DEBUG
 #define MP3U_LOG(...) printf("MP3U: " __VA_ARGS__)
 #define MP3U_LOG_CONT(...) printf(__VA_ARGS__)
 #define MP3U_ERROR(msg) printf("MP3U: Error: %s failed\n", msg)
#else
 #define MP3U_LOG(...)
 #define MP3U_LOG_CONT(...)
 #ifdef MP3U_DEBUG_ERROR
  #define MP3U_ERROR(msg) printf("MP3U: Error: %s failed\n", msg)
 #else
  #define MP3U_ERROR(msg) /* printf("MP3U: Error: %s failed\n", msg) */
 #endif
#endif

#define SWAP_ENDIAN(i) (((i)<<24) | ((i)&0xff00)<<8 | ((i)&0xff0000)>>8 | ((i)>>24))

#define ID3_GET_SYNCSAFE(a,b,c,d) (((a&0x7f)<<21) | ((b&0x7f)<<14) | ((c&0x7f)<<7) | ((d&0x7f)<<0))

#define BYTES_TO_INT16(msb,lsb)     (((msb)<<8)|(lsb))
#define BYTES_TO_INT32(msb,a,b,lsb) (((msb)<<24)|((a)<<16)|((b)<<8)|(lsb))

static s16 bitrates[2][3][16] = 
{
    { /* MPEG 1 */
        /* layer 1 */
        { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1 },
        /*  layer 2 */
        { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1 },
        /* layer 3 */
        { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1 },
    },
    { /* MPEG 2 */
        /* layer 1 */
        { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, -1 },
        /* layer 2 */
        { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1 },
        /* layer 3 */
        { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1 },
    },
};

static s32 sampleRates[2][4] =
{
    { 44100, 48000, 32000, -1 }, /* MPEG 1 */
    { 22050, 24000, 16000, -1 }  /* MPEG 2 */
};

int
mp3FrameTime(Mp3Info *mp3i) 
{
    u32 t;  /* 10's of microseconds = milliseconds*100 */

    /* bitrate is in Kbits/sec */
    t = (mp3FrameSize(mp3i) * 8 * 100)/ mp3i->bitrate;
    
    return t;
}

int
mp3FrameSize(Mp3Info *mp3i) {
    s32 size;

    MP3U_LOG("bitrate=%d, samplerate=%d, id=%d, pad=%d\n",mp3i->bitrate,mp3i->freq,mp3i->id,mp3i->pad);
    
    if ( mp3i->id == MPEG_VERSION_1 ) {
        if ( mp3i->layer == MPEG_LAYER_1 ) {
            size = ((12000*mp3i->bitrate) / mp3i->freq + mp3i->pad) * 4;
        } else {
            size = ((144000*mp3i->bitrate) / mp3i->freq + mp3i->pad);
        }
    } else {  /* MPEG_VERSION_2 */
         if ( mp3i->layer == MPEG_LAYER_1 ) {
            size = ((6000*mp3i->bitrate) / mp3i->freq + mp3i->pad) * 4;
        } else {
            size = ((72000*mp3i->bitrate) / mp3i->freq + mp3i->pad);
        }
    }
    return size;
};

int
mp3IsValid(Mp3Info *mp3i) {
    return 0;
}

int
mp3IsSupported(Mp3Info *mp3i) {
    int supported = 0;

    /* currently only MPEG 1.0, Layer III files are supported
     *
     * restrictions --
     * 1. MPEG 1.0, Layer I and II -- support could be added;
     *    need to check calculations involving number of samples
     *    per frame and bit rate; also since number of samples
     *    per frame changes, structure of playback loop may
     *    have to change
     * 2. MPEG 2.0 all Layers and MPEG 2.5 Layers I and II --
     *    no point in adding this because the NC's audio codec
     *    can't handle the associated sampling rates
     * 3. MPEG 2.5, Layer III -- support could be added; need
     *    to check calculations involving number of samples
     *    per frame and bit rate; also since number of samples
     *    per frame changes, structure of playback loop may
     *    have to change; MPEG utility routines must be updated
     *    to recognize version 2.5 headers
     */
    if ( mp3i->valid &&
         mp3i->id == MPEG_VERSION_1 &&
         mp3i->layer == MPEG_LAYER_3 )
        supported = 1;
    
    return supported;
}

/*
 * mp3ParseHeader -- parse a 32-bit integer and determine whether
 *                   it's a valid MP3 header; populate Mp3Info
 *                   structure; return 1 if valid, else 0;
 */
int
mp3ParseHeader(u32 header, Mp3Info *mp3i)
{
    u32 head = header;
    s32 b;
    u32 id_ndx, layer_ndx, bitrate_ndx, freq_ndx;

    mp3i->valid= 0;
    mp3i->head = head;

    MP3U_LOG("header = 0x%08x (swapped=0x%08x)\n",header,head);

    if ( (mp3i->sync = GET_FIELD(head,MP3_HEADER_SYNC)) != 0xfff )
        return 0;
    if ( (layer_ndx = GET_FIELD(head,MP3_HEADER_LAYER)) == 0 )
        return 0;
    if ( (bitrate_ndx = GET_FIELD(head,MP3_HEADER_BITRATE)) == 0xf )
        return 0;
    if ( (freq_ndx = GET_FIELD(head,MP3_HEADER_FREQ)) == 0x3 )
        return 0;
    if ( (mp3i->emphasis = GET_FIELD(head,MP3_HEADER_EMPHASIS)) == 0x2 )
        return 0;
    
    id_ndx = GET_FIELD(head,MP3_HEADER_ID);
    mp3i->id = !id_ndx;
    mp3i->layer = 3 - layer_ndx;
    mp3i->bitrate = bitrates[mp3i->id][mp3i->layer][bitrate_ndx];
    mp3i->freq = sampleRates[mp3i->id][freq_ndx];
    b = mp3i->bitrate;

    if ( mp3i->layer == MPEG_LAYER_2 &&
         ((mp3i->mode == MPEG_MODE_MONO && (b == 224 || b == 256 || b == 320 || b == 384)) ||
          (mp3i->mode != MPEG_MODE_MONO && (b == 32 || b == 48 || b == 56 || b == 80))) )
        return 0;
    
    mp3i->valid = 1;
    
    mp3i->prot = GET_FIELD(head,MP3_HEADER_PROT);
    mp3i->pad = GET_FIELD(head,MP3_HEADER_PAD);
    mp3i->privacy = GET_FIELD(head,MP3_HEADER_PRIVACY);
    mp3i->mode = GET_FIELD(head,MP3_HEADER_MODE);
    mp3i->modeExt = GET_FIELD(head,MP3_HEADER_MODEEXT);
    mp3i->copy = GET_FIELD(head,MP3_HEADER_COPY);
    mp3i->home = GET_FIELD(head,MP3_HEADER_HOME);

    if ( b == 0 ) {
        mp3i->len = 0;
    } else {
        mp3i->len = mp3FrameSize(mp3i);
    }
        
    mp3PrintHeader(mp3i);

    return mp3i->valid;
}

void
mp3PrintHeader(Mp3Info *mp3i)
{
    MP3U_LOG("header:\n");
    MP3U_LOG_CONT("\thead      0x%08x\n",mp3i->head);
    MP3U_LOG_CONT("\tvalid     %d\n",mp3i->valid);
    MP3U_LOG_CONT("\tsync      0x%x\n",mp3i->sync);
    MP3U_LOG_CONT("\tid ndx    %d -> MPEG %d\n",mp3i->id,
                  mp3i->id==MPEG_VERSION_1?1:
                  (mp3i->id==MPEG_VERSION_2?2:
                   -1));
    MP3U_LOG_CONT("\tlayer ndx %d -> layer %d\n",mp3i->layer,
                  mp3i->layer==MPEG_LAYER_1?1:
                  (mp3i->layer==MPEG_LAYER_2?2:
                   (mp3i->layer==MPEG_LAYER_3?3:
                    -1)));
    MP3U_LOG_CONT("\tprot      %d\n",mp3i->prot);
    MP3U_LOG_CONT("\tbitrate   %d kbps\n",mp3i->bitrate);
    MP3U_LOG_CONT("\tlen       %d bytes\n",mp3i->len);
    MP3U_LOG_CONT("\tfreq      %d Hz\n",mp3i->freq);
    MP3U_LOG_CONT("\tpad       %d\n",mp3i->pad);
    MP3U_LOG_CONT("\tprivacy   %d\n",mp3i->privacy);
    MP3U_LOG_CONT("\tmode      %d -> %s\n",mp3i->mode,
                  mp3i->mode==MPEG_MODE_STEREO?"stereo":
                  (mp3i->mode==MPEG_MODE_JOINT?"joint":
                  (mp3i->mode==MPEG_MODE_DUAL?"dual":
                  (mp3i->mode==MPEG_MODE_MONO?"mono":
                   "unknown"))));
    MP3U_LOG_CONT("\tmodeExt   %d\n",mp3i->modeExt);
    MP3U_LOG_CONT("\tcopy      %d\n",mp3i->copy);
    MP3U_LOG_CONT("\thome      %d\n",mp3i->home);
    MP3U_LOG_CONT("\temphasis  %d\n",mp3i->emphasis);
}

/*
 * mp3FindId3v1 -- look for an ID3V1 tag, returning new effective eof
 *                 or an error code
 *
 * tag must lie between offsets "start" and "end"
 * 
 * new effective eof is "end" - sizeof(tag), if tag found;
 * otherwise new effective eof is "end"
 */
static IOSError
mp3FindId3v1(IOSFd fd, s32 start, s32 end)
{
    s32 pos;
    IOSError rv;
    u8 buf[3];

    /* check for ID3V1 */
    if ( end - start < 128 ) {
        rv = end;
        goto out;
    }
    
    if ( (pos = rv = IOS_Seek(fd, end-128, SEEK_SET)) < 0 ) {
        MP3U_ERROR("seek for ID3V1 tag");
        goto out;
    }
    /* MP3U_LOG("checking for ID3V1 tag at offset %d\n",pos); */
    if ( (rv = IOS_Read(fd, &buf[0], 3*sizeof(u8))) != 3*sizeof(u8) ) {
        MP3U_ERROR("ID3V1 tag header read");
        if ( rv >= 0 )
            rv = IOS_ERROR_MAX;
        goto out;
    }
    if ( buf[0] == 'T' && buf[1] == 'A' && buf[2] == 'G' ) {
        /* found ID3V1 or ID3V1.1 */
        MP3U_LOG("ID3V1 tag found at %d\n",pos);
    } else {
        /* MP3U_LOG("ID3V1 tag NOT found at %d\n",pos); */
        pos += 128;
    }

    rv = pos;
out:
    return rv;
}

/*
 * mp3FindId3v2Pre -- look for an ID3V2 tag at start of file,
 *                    returning new effective start-of-file
 *                    (sof) or an error code
 *
 * tag must lie between offsets "start" and "end"
 * 
 * new effective sof is "start" + sizeof(tag), if tag found;
 * otherwise new effective eof is "start"
 */
static IOSError
mp3FindId3v2Pre(IOSFd fd, s32 start, s32 end)
{
    s32 pos = start;
    IOSError rv;
    u8 buf[10];
    
    /* check for ID3V2 */
    while ( end - pos > 10 ) {
        /* MP3U_LOG("checking for leading ID3V2 tag at offset %d\n",pos); */
        if ( (rv = IOS_Seek(fd, pos, IOS_SEEK_SET)) < 0 ) {
            MP3U_ERROR("seek for ID3V2 tag");
            goto out;
        }
        /* read candidate header */
        if ( (rv = IOS_Read(fd, &buf[0], 10*sizeof(u8))) != 10*sizeof(u8) ) {
            MP3U_ERROR("ID3V2 tag header read");
            if ( rv >= 0 )
                rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
        
        /* check for valid ID3V2 header fingerprint */
        if ( buf[0] == 'I' && buf[1] == 'D' && buf[2] == '3' &&
             buf[3] < 0xff && buf[4] < 0xff &&
             buf[6] < 0x80 && buf[7] < 0x80 && buf[8] < 0x80 && buf[9] < 0x80 ) {
            /* found a valid ID3V2 header, compute length in bytes */
            u32 l = ID3_GET_SYNCSAFE(buf[6],buf[7],buf[8],buf[9]);
            l += 10; /* for header */
            if ( buf[5] & 0x10 )
                l += 10; /* for footer */
            /* check for valid tag length */
            pos += l;
            if ( pos > end ) {
                MP3U_ERROR("ID3V2 tag length too long");
                rv = IOS_ERROR_INVALID_FORMAT;
                goto out;
            }
            MP3U_LOG("leading ID3V2 tag found at %d\n",pos);
        } else {
            /* MP3U_LOG("leading ID3V2 tag NOT found at %d\n",pos); */
            break;
        }
    }

    /* file offset for first trailing ID3 tag or, if no tags, eof */
    rv = pos;
out:
    return rv;
}

/*
 * mp3FindId3v2Post -- look for an ID3V2 tag at end of file,
 *                     returning new effective eof or an
 *                     error code
 *
 * tag must lie between offsets "start" and "end"
 * 
 * new effective eof is "end" - sizeof(tag), if tag found;
 * otherwise new effective eof is "end"
 */
static IOSError
mp3FindId3v2Post(IOSFd fd, s32 start, s32 end)
{
    s32 pos = end;
    IOSError rv;
    u8 buf[10];
    
    /* check for ID3V2 */
    while ( pos - start > 10 ) {
        /* MP3U_LOG("checking for trailing ID3V2 tag at offset %d\n",pos-10); */
        if ( (rv = IOS_Seek(fd, pos - 10, IOS_SEEK_SET)) < 0 ) {
            MP3U_ERROR("seek for ID3V2 tag");
            goto out;
        }
        /* read candidate footer */
        if ( (rv = IOS_Read(fd, &buf[0], 10*sizeof(u8))) != 10*sizeof(u8) ) {
            MP3U_ERROR("ID3V2 tag footer read");
            if ( rv >= 0 )
                rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
        
        /* check for valid ID3V2 footer fingerprint */
        if ( buf[0] == '3' && buf[1] == 'D' && buf[2] == 'I' &&
             buf[3] < 0xff && buf[4] < 0xff &&
             (buf[5] & 0x10) != 0 &&
             buf[6] < 0x80 && buf[7] < 0x80 && buf[8] < 0x80 && buf[9] < 0x80 ) {
            /* found a valid ID3V2 footer, compute length in bytes */
            u32 l = ID3_GET_SYNCSAFE(buf[6],buf[7],buf[8],buf[9]);
            l += 10; /* for header */
            if ( buf[5] & 0x10 )
                l += 10; /* for footer */
            /* check for valid tag length */
            if ( pos < l ) {
                MP3U_ERROR("ID3V2 tag length too long");
                rv = IOS_ERROR_INVALID_FORMAT;
                goto out;
            }
            pos -= l;
            MP3U_LOG("trailing ID3V2 tag found at %d\n",pos);
        } else {
            /* MP3U_LOG("trailing ID3V2 tag NOT found at %d\n",pos); */
            break;
        }
    }

    /* file offset for first trailing ID3 tag or, if no tags, eof */
    rv = pos;
out:
    return rv;
}

/*
 * mp3FindLyrics3 -- look for a LYRIC3 tag, returning new effective eof
 *                   or an error code
 *
 * tag must lie between offsets "start" and "end"
 * 
 * new effective eof is "end" - sizeof(tag), if tag found;
 * otherwise new effective eof is "end"
 */
static IOSError
mp3FindLyrics3(IOSFd fd, s32 start, s32 end)
{
    u8 buf[11];
    IOSError rv;
    s32 pos;
    u32 i;

    /* short circuit if not enough data */
    if ( end - start < 20 ) {  /* min Lyrics3v1 tag size */
        rv = end;
        goto out;
    }

    /* look for Lyrics3 trailer */
    if ( (pos = rv = IOS_Seek(fd, end-9, SEEK_SET)) < 0 ) {
        MP3U_ERROR("seek for LYRICS3 tag");
        goto out;
    }

    /* MP3U_LOG("checking for LYRICS3 tag at offset %d\n",pos); */
    
    if ( (rv = IOS_Read(fd, &buf[0], 9*sizeof(u8))) != 9*sizeof(u8) ) {
        MP3U_ERROR("LYRICS3 tag header read");
        if ( rv >= 0 )
            rv = IOS_ERROR_MAX;
        goto out;
    }
    
    if ( ! strncmp(buf,"LYRICSEND",9) ) {
        /* found LYRICS3V1 tag trailer */

        /* LYRICS3V1 tags don't include a length field,
           so the header must be manually located */
        pos -= 5100;  /* earliest possible header location */
        if ( pos < start )
            pos = start;
        if ( (pos = rv = IOS_Seek(fd, pos, SEEK_SET)) < 0 ) {
            MP3U_ERROR("seek for LYRICS3v1 header");
            goto out;
        }
        u32 j = 0;
        u8 head[] = "LYRICSBEGIN";
        for ( i=0; i<pos-start && j<sizeof(head); i++ ) {
            if ( (rv = IOS_Read(fd, &buf[0], sizeof(u8))) != sizeof(u8) ) {
                MP3U_ERROR("LYRICS3v1 header read");
                if ( rv >= 0 )
                    rv = IOS_ERROR_MAX;
                goto out;
            }
            if ( buf[0] == head[j] ) 
                j++;
            else
                j=0;
        }
        if ( j == sizeof(head) ) {
            pos = i - j + 1; /* actual tag header location */
            MP3U_LOG("found LYRICS3V1 tag at %d\n",pos);
        } else {
            MP3U_ERROR("LYRICS3v1 header not found");
            rv = IOS_ERROR_INVALID_FORMAT;
                goto out;
        }
        
    } else if ( ! strncmp(buf,"LYRICS200",9) ) {
        /* found LYRICS3V2 tag trailer */
        u32 size = 0;
        
        /* read tag size field, a 6-character string representing a decimal number */
        pos -= 6;  /* locn of tag size */
        if ( (pos = rv = IOS_Seek(fd, pos, SEEK_SET)) < 0 ) {
            MP3U_ERROR("seek for LYRICS3v2 size");
            goto out;
        }
        if ( (rv = IOS_Read(fd, &buf[0], 6*sizeof(u8))) != 6*sizeof(u8) ) {
            MP3U_ERROR("LYRICS3v2 tag size read");
            if ( rv >= 0 )
                rv = IOS_ERROR_MAX;
            goto out;
        }

        /* convert tag size from a string to a number */
        for (i=0; i<6; i++) {
            if (buf[i] == ' ')
                continue;
            if (buf[i] < '0' || buf[i] > '9') {
                MP3U_ERROR("LYRICS3V2 tag invalid length");
                rv = IOS_ERROR_INVALID_FORMAT;
                goto out;
            }
            size = size * 10 + buf[i] - '0';
        }
        pos -= size;  /* location of tag header */
        /* using tag size, locate header */
        if ( pos < start ) {
            MP3U_ERROR("LYRICS3V2 tag too long");
            rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
        if ( (pos = rv = IOS_Seek(fd, pos, SEEK_SET)) < 0 ) {
            MP3U_ERROR("seek for LYRICS3v2 header");
            goto out;
        }
        if ( (rv = IOS_Read(fd, &buf[0], 11*sizeof(u8))) != 11*sizeof(u8) ) {
            MP3U_ERROR("LYRICS3v2 tag header read");
            if ( rv >= 0 )
                rv = IOS_ERROR_MAX;
            goto out;
        }
        if ( ! strncmp(buf,"LYRICSBEGIN",11) ) {
            MP3U_LOG("found LYRICS3v2 tag at %d\n",pos);
        } else {
            MP3U_ERROR("LYRICS3V2 header missing");
            rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
    } else {
        /* MP3U_LOG("LYRICS3 tag NOT found at %d\n",pos); */
        rv = end;
        goto out;
    }

    rv = pos;
out:
    return rv;
}

/*
 * mp3FindApePost -- look for an APE tag at end of file,
 *                   returning new effective eof or an
 *                   error code
 *
 * tag must lie between offsets "start" and "end"
 * 
 * new effective eof is "end" - sizeof(tag), if tag found;
 * otherwise new effective eof is "end"
 */
static IOSError
mp3FindApePost(IOSFd fd, s32 start, s32 end)
{
    u8 buf[32];
    IOSError rv;
    s32 pos;
    u32 version;
    u32 size;
    
    /* short circuit if not enough data */
    if ( end - start < 32 ) {  /* min APE tag size */
        rv = end;
        goto out;
    }

    /* look for APE trailer */
    if ( (pos = rv = IOS_Seek(fd, end-32, SEEK_SET)) < 0 ) {
        MP3U_ERROR("seek for APE tag");
        goto out;
    }

    /* MP3U_LOG("checking for trailing APE tag at offset %d\n",pos); */
    
    if ( (rv = IOS_Read(fd, &buf[0], 32)) != 32 ) {
        MP3U_ERROR("APE tag trailer read");
        if ( rv >= 0 )
            rv = IOS_ERROR_MAX;
        goto out;
    }

    if ( buf[0] == 'A' &&   /* APE trailer fingerprint */
         buf[1] == 'P' &&
         buf[2] == 'E' &&
         buf[3] == 'T' &&
         buf[4] == 'A' &&
         buf[5] == 'G' &&
         buf[6] == 'E' &&
         buf[7] == 'X' &&
         buf[24] == 0 &&
         buf[25] == 0 &&
         buf[26] == 0 &&
         buf[27] == 0 &&
         buf[28] == 0 &&
         buf[29] == 0 &&
         buf[30] == 0 &&
         buf[31] == 0
        ) {
        /* found APE trailer */
        version = BYTES_TO_INT32(buf[11],buf[10],buf[9],buf[8]);
        if ( version != 1000 && version != 2000 ) {
            MP3U_ERROR("APE footer version");
            rv = IOS_ERROR_FAIL_INTERNAL;
            goto out;
        }
        size = BYTES_TO_INT32(buf[15],buf[14],buf[13],buf[12]);
        pos = end - size;
        if ( version == 2000 ) {
            /* check flags */
            u32 flags = BYTES_TO_INT32(buf[23],buf[22],buf[21],buf[20]);
            if ( GET_FIELD(flags,APE_FLAGS_HEADER_PRESENT) )
                pos -= 32;  /* account for header (32 bytes) */
            if ( GET_FIELD(flags,APE_FLAGS_FOOTER_ABSENT) ||
                 GET_FIELD(flags,APE_FLAGS_IS_HEADER) ) {
                /* error, we're looking for a trailing APE
                 * tag which, by definition, must have a
                 * footer; but none was found
                 */
                MP3U_ERROR("APEV2 footer missing");
                rv  = IOS_ERROR_FAIL_INTERNAL;
                goto out;
            }
        }
        if ( pos < start ) {
            MP3U_ERROR("APE tag length");
            rv = IOS_ERROR_FAIL_INTERNAL;
            goto out;
        }
        if ( version == 1000 ) {
            MP3U_LOG("trailing APEv1 tag found at %d\n",pos);
        } else {
            MP3U_LOG("trailing APEv2 tag found at %d\n",pos);
        }
    } else {
        /* MP3U_LOG("trailing APE tag NOT found at %d\n",pos); */
        pos = end;
    }
    
    rv = pos;
out:
    return rv;
}


/*
 * mp3FindApePre -- look for an APE tag at start of file,
 *                  returning new effective start-of-file
 *                  (sof) or an error code
 *
 * tag must lie between offsets "start" and "end"
 * 
 * new effective sof is "start" + sizeof(tag), if tag found;
 * otherwise new effective eof is "start"
 */
static IOSError
mp3FindApePre(IOSFd fd, s32 start, s32 end)
{
    u8 buf[32];
    IOSError rv;
    s32 pos;
    u32 version;
    u32 size;

    /* short circuit if not enough data */
    if ( end - start < 32 ) {  /* min APE tag size */
        rv = start;
        goto out;
    }

    /* look for APE trailer */
    if ( (pos = rv = IOS_Seek(fd, start, SEEK_SET)) < 0 ) {
        MP3U_ERROR("seek for APE tag");
        goto out;
    }

    /* MP3U_LOG("checking for leading APE tag at offset %d\n",pos); */
    
    if ( (rv = IOS_Read(fd, &buf[0], 32)) != 32 ) {
        MP3U_ERROR("APE tag header read");
        if ( rv >= 0 )
            rv = IOS_ERROR_MAX;
        goto out;
    }

    if ( buf[0] == 'A' &&   /* APE trailer fingerprint */
         buf[1] == 'P' &&
         buf[2] == 'E' &&
         buf[3] == 'T' &&
         buf[4] == 'A' &&
         buf[5] == 'G' &&
         buf[6] == 'E' &&
         buf[7] == 'X' &&
         buf[24] == 0 &&
         buf[25] == 0 &&
         buf[26] == 0 &&
         buf[27] == 0 &&
         buf[28] == 0 &&
         buf[29] == 0 &&
         buf[30] == 0 &&
         buf[31] == 0
        ) {
        pos += 32; /* header size */
        /* found APE header */
        version = BYTES_TO_INT32(buf[11],buf[10],buf[9],buf[8]);
        if ( version != 1000 && version != 2000 ) {
            MP3U_ERROR("APE header version");
            rv = IOS_ERROR_FAIL_INTERNAL;
            goto out;
        }
        if ( version == 2000 ) {
            /* double-check that we're found a header and not a footer */
            u32 flags = BYTES_TO_INT32(buf[23],buf[22],buf[21],buf[20]);
            if ( GET_FIELD(flags,APE_FLAGS_IS_HEADER) == 0 ) {
                MP3U_ERROR("APEV2 header missing");
                rv  = IOS_ERROR_FAIL_INTERNAL;
                goto out;
            }
        }
        size = BYTES_TO_INT32(buf[15],buf[14],buf[13],buf[12]);
        pos += size; /* tag size does not including header */
        if ( pos > end ) {
            MP3U_ERROR("APE tag length");
            rv = IOS_ERROR_FAIL_INTERNAL;
            goto out;
        }
        if ( version == 1000 ) {
            MP3U_LOG("leading APEv1 tag found at %d\n",pos);
        } else {
            MP3U_LOG("leading APEv2 tag found at %d\n",pos);
        }
    } else {
        /* MP3U_LOG("leading APE tag NOT found at %d\n",pos); */
    }
    
    rv = pos;
out:
    return rv;
}

/*
 * mp3FindEnd -- find end of MP3 data in file
 */
IOSError
mp3FindEnd(IOSFd fd, Mp3Info *mp3i)
{
    IOSError rv;
    s32 pos;
    s32 end;
    
    if ( (end = rv = IOS_Seek(fd, 0, SEEK_END)) < 0 ) {
        MP3U_ERROR("seek for eof");
        goto out;
    }

    /* look for trailing tags */
    MP3U_LOG("looking for trailing tags\n");
    do {
        pos = end;
        if ( (end = rv = mp3FindId3v1(fd, 0, end)) < 0 ) {
            goto out;
        }
        if ( (end = rv = mp3FindId3v2Post(fd, 0, end)) < 0 ) {
            goto out;
        }
        if ( (end = rv = mp3FindLyrics3(fd, 0, end)) < 0 ) {
            goto out;
        }
        if ( (end = rv = mp3FindApePost(fd, 0, end)) < 0 ) {
            goto out;
        }
    } while ( pos != end );
    
    MP3U_LOG("end of MP3 data found at offset %d\n",pos);
    rv = pos;
out:
    return rv;
}

/*
 * mp3FindStart -- find beginning of MP3 data in file
 */
int
mp3FindStart(IOSFd fd, Mp3Info *mp3i)
{
    IOSError rv;
    s32 pos;
    s32 end;
    s32 start;
    u8 h[4];
    u32 head;
    
    if ( (end = rv = IOS_Seek(fd, 0, SEEK_END)) < 0 ) {
        MP3U_ERROR("seek for eof");
        goto out;
    }

    if ( (start = rv = IOS_Seek(fd, 0, SEEK_SET)) < 0 ) {
        MP3U_ERROR("seek for sof");
        goto out;
    }

    /* look for leading tags */
    MP3U_LOG("looking for leading tags\n");
    do {
        pos = start;
        if ( (start = rv = mp3FindId3v2Pre(fd, start, end)) < 0 ) {
            goto out;
        }
        if ( (start = rv = mp3FindApePre(fd, start, end)) < 0 ) {
            goto out;
        }
    } while ( pos != start );
    
    MP3U_LOG("end of tags found at offset %d\n",pos);

    /* look for MP3 header */
    if ( (rv = IOS_Seek(fd, start, SEEK_SET)) < 0 ) {
        MP3U_ERROR("seek for MP3 header");
        goto out;
    }
    if ( (rv = IOS_Read(fd, &h[0], sizeof(u32))) != sizeof(u32) ) {
        /* unexpected eof */
        MP3U_LOG ("mp3FindStart: bad full header read\n");
        if ( rv >= 0 )
            rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
    
    head = BYTES_TO_INT32(h[0],h[1],h[2],h[3]);
    
    if ( ! mp3ParseHeader(head,mp3i) ) {
        MP3U_ERROR("find MP3 start");
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
    
    MP3U_LOG("mp3FindStart: found header at %d\n",pos);
    if ( (rv = IOS_Seek(fd, pos, SEEK_SET)) < 0 ) {
        rv = IOS_ERROR_FAIL_INTERNAL;
        MP3U_LOG("mp3FindStart: bad found seek\n");
        goto out;
    }

    rv = pos;
out:
    return rv;
}

int
mp3ReadFrame(IOSFd fd, Mp3Info *mp3i, u32 *buf)
{
    IOSError rv = IOS_ERROR_OK;
    Mp3Info mp3il;
    
    if ( (rv = IOS_Read(fd, &buf[0], sizeof(u32))) != sizeof(u32) ) {
        MP3U_LOG ("mp3ReadFrame: bad header read\n");
        return IOS_ERROR_UNKNOWN; /* XXX */
    }
    if ( mp3ParseHeader(buf[0], mp3i) == 0 ) {
        MP3U_LOG ("mp3ReadFrame: bad parse header\n");
        return IOS_ERROR_UNKNOWN; /* XXX */
    }
    s32 l = mp3FrameSize(mp3i) - 4;
    if ( (rv = IOS_Read(fd, &buf[1], l)) != l ) {
        MP3U_LOG ("mp3ReadFrame: bad data read\n");
        return IOS_ERROR_UNKNOWN; /* XXX */
    }
    MP3U_LOG ("mp3ReadFrame: exiting OK\n");
    {
        u32 h;
        if ( (rv = IOS_Read(fd, &h, sizeof(u32))) != sizeof(u32) ) {
            MP3U_LOG ("mp3ReadFrame: bad 2nd header read\n");
        }
        if ( mp3ParseHeader(h, &mp3il) == 0 ) {
            MP3U_LOG ("mp3ReadFrame: bad parse 2nd header\n");
        }
    }
    
    return IOS_ERROR_OK;
}

/*
 * mp3FindFrame -- look for valid MP3 header in the byte interval
 *                 [start,end]; return header (via *header) and
 *                 location where found (via return value), if
 *                 found; return IOS_ERROR_NOEXISTS if not found;
 *                 else return error
 *
 * only headers "matching" the template are considered, where
 * "matching" means (template&mask) == (header&mask).
 * 
 * Note that setting mask=0 forces all headers to "match"
 */
IOSError
mp3FindFrame(IOSFd fd, s32 start, s32 end, u32 template, u32 mask, u32 *header)
{
    IOSError rv = IOS_ERROR_NOEXISTS;
    u8 buf[128];
    u32 found = 0;
    s32 pos;
    s32 len;
    s32 i = 0;
    s32 offset;
    Mp3Info mp3il;
    
    MP3U_LOG("mp3FindFrame: starting at %d\n",start);
    
    /* seek to start point */
    if ( start > end ) {
        rv = IOS_ERROR_NOEXISTS;
        MP3U_LOG("mp3FindFrame: short circuit\n");
        goto out;
    }
    
    if ( (rv = IOS_Seek(fd, start, IOS_SEEK_SET)) < 0 ) {
        rv = IOS_ERROR_FAIL_INTERNAL;
        MP3U_LOG("mp3FindFrame: bad seek\n");
        goto out;
    }

    /* search until 'end' reached
     *
     * since header is 4 bytes long, we can only search up to end-3
     */
    for (pos=start; pos<end-3; pos+=sizeof(buf)-3) {

        /* compute amount of data in buffer */
        len = end - pos;
        if ( len > sizeof(buf) )
            len = sizeof(buf);
        offset = i ? 3 : 0; /* after 1st iter, fill buffer at offset 3 */

        /* read data into buffer */
        if ( (rv = IOS_Read(fd, buf+offset, len-offset)) != len-offset ) {
            rv = IOS_ERROR_FAIL_INTERNAL;
            MP3U_LOG("mp3FindFrame: bad read\n");
            goto out;
        }

        /* look for MP3 header */
        for ( i=0; i<len-3; i++) {
            /* MP3U_LOG(" 0x%08x (%d) addr -> buf[%d] = 0x%02x (%d)\n",pos+i,pos+i,i,buf[i],buf[i]); */
            if ( buf[i] == 0xff ) {
                *header = BYTES_TO_INT32(buf[i],buf[i+1],buf[i+2],buf[i+3]);
                /* only bother to parse header if it matches the template */
                if ( (template&mask) == ((*header)&mask) ) {
                    if ( mp3ParseHeader(*header, &mp3il) ) {
                        found = 1;
                        MP3U_LOG("mp3FindFrame: found valid header 0x%08x at %d\n",*header,pos+i);
                        break;
                    }
                }
            }
        }

        if ( found )
            break;
    
        /* copy last 3 bytes of buffer from tail to head */
        buf[0] = buf[len-3];
        buf[1] = buf[len-2];
        buf[2] = buf[len-1];
    }

    if (found)
        rv = pos+i;
    else
        rv = IOS_ERROR_NOEXISTS;
    
out:
    return rv;
}

/*
 * mp3FindXing -- check whether an Xing header exists in the first
 *                MP3 frame; decode it, if present;
 *
 * return 0 if not found
 *        1 if found
 *        IOS_ERROR_FAIL_INTERNAL if file operation fails
 *        IOS_ERROR_INVALID_FORMAT if Xing header is munged
 */
IOSError
mp3FindXing(IOSFd fd, s32 start, s32 end, Mp3Info *mp3i, XingInfo *xi)
{
    IOSError rv = 0; /* Xing not found */
    s32 offset;

    xi->valid = 0;
    
    /* compute xing location relative to header */
    if ( mp3i->mode == MPEG_MODE_MONO )
        offset = (mp3i->id == MPEG_VERSION_1) ? 17 : 9;
    else
        offset = (mp3i->id == MPEG_VERSION_1) ? 32 : 17;

    /* not enough data for an Xing header */
    /* min Xing header length is 8 bytes, 4 for header ID and 4 for flags */
    if ( (start+4+offset)+8 > end ) {
        MP3U_LOG("mp3FindXing: file too short\n");
        rv = 0;
        goto out;
    }

    /* read Xing header id */
    rv = IOS_Seek(fd, start+4+offset, IOS_SEEK_SET);
    if ( rv < 0 ) {
        MP3U_LOG("error %d when seeking to Xing header\n",rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    if ( (rv = IOS_Read(fd, &xi->id, sizeof(xi->id))) != sizeof(xi->id) ) {
        MP3U_LOG ("mp3FindXing: bad header read\n");
        if ( rv >= 0 )
            rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    xi->id = SWAP_ENDIAN(xi->id);

#define isXing(id)   ((id) == ('X'<<24) + ('i'<<16) + ('n'<<8) + 'g')
#define isInfo(id)   ((id) == ('I'<<24) + ('n'<<16) + ('f'<<8) + 'o')
    
    if ( isXing(xi->id) || isInfo(xi->id) ) {
        MP3U_LOG("mp3FindXing: found legal id\n");
    } else {
        MP3U_LOG("mp3FindXing: header not found\n");
        rv = 0;
        goto out;
    }
    
    /* read Xing flags */
    if ( (rv = IOS_Read(fd, &xi->flags, sizeof(xi->flags))) != sizeof(xi->flags) ) {
        MP3U_LOG ("mp3FindXing: bad flags read\n");
        if ( rv >= 0 )
            rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
    xi->flags = SWAP_ENDIAN(xi->flags);
    MP3U_LOG("mp3FindXing: flags = 0x%x\n",xi->flags);
    
    /* read Xing frames */
    if ( xi->flags & XING_FRAMES_FLAG ) {
        if ( (rv = IOS_Read(fd, &xi->nFrames, sizeof(xi->nFrames))) != sizeof(xi->nFrames) ) {
            MP3U_LOG ("mp3FindXing: bad frames read\n");
            if ( rv >= 0 )
                rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
        xi->nFrames = SWAP_ENDIAN(xi->nFrames);
        MP3U_LOG("mp3FindXing: frames = %d\n",xi->nFrames);
    }
    
    /* read Xing bytes */
    if ( xi->flags & XING_BYTES_FLAG ) {
        if ( (rv = IOS_Read(fd, &xi->nBytes, sizeof(xi->nBytes))) != sizeof(xi->nBytes) ) {
            MP3U_LOG ("mp3FindXing: bad bytes read\n");
            if ( rv >= 0 )
                rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
        xi->nBytes = SWAP_ENDIAN(xi->nBytes);
        MP3U_LOG("mp3FindXing: bytes = %d\n",xi->nBytes);
    }
    
    /* read Xing toc */
    if ( xi->flags & XING_TOC_FLAG ) {
        if ( (rv = IOS_Read(fd, &xi->toc, sizeof(xi->toc))) != sizeof(xi->toc) ) {
            MP3U_LOG ("mp3FindXing: bad toc read\n");
            if ( rv >= 0 )
                rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
#ifdef MP3U_DEBUG
        int i=0;
        for ( i=0; i<100; i++ ) {
            MP3U_LOG("mp3FindXing: toc[%d] = %d\n",i,xi->toc[i]);
        }
#endif    
    }
    
    /* read Xing quality indicator */
    if ( xi->flags & XING_QUALITY_FLAG ) {
        if ( (rv = IOS_Read(fd, &xi->quality, sizeof(xi->quality))) != sizeof(xi->quality) ) {
            MP3U_LOG ("mp3FindXing: bad quality read\n");
            if ( rv >= 0 )
                rv = IOS_ERROR_INVALID_FORMAT;
            goto out;
        }
        xi->quality = SWAP_ENDIAN(xi->quality);
    }
    MP3U_LOG("mp3FindXing: quality = %d\n",xi->quality);

    xi->valid = 1;
    rv = 1;  /* Xing header found */
    
out:
    return rv;
}

/*
 * mp3FindVBRI -- check whether an VBRI header exists in the first
 *                MP3 frame; decode it, if present;
 *
 * return 0 if not found
 *        1 if found
 *        IOS_ERROR_FAIL_INTERNAL if file operation fails
 *        IOS_ERROR_INVALID_FORMAT if VBRI header is munged
 */
IOSError
mp3FindVbri(IOSFd fd, s32 start, s32 end, Mp3Info *mp3i, VbriInfo *vi)
{
    IOSError rv = 0; /* VBRI not found */
    s32 offset;
    u8 buf[26];

    vi->valid = 0;
    
    /* VBRI is located 32 bytes after MP3 frame header */
    offset = 32;
    offset += 4;   /* MP3 frame header length */

    /* not enough data for an VBRI header */
    /* min VBRI header length is 26 bytes */
    if ( (start+offset)+26 > end ) {
        MP3U_LOG("mp3FindVBRI: file too short\n");
        rv = 0;
        goto out;
    }

    /* read VBRI header id */
    rv = IOS_Seek(fd, start+offset, IOS_SEEK_SET);
    if ( rv < 0 ) {
        MP3U_LOG("error %d when seeking to VBRI header\n",rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    if ( (rv = IOS_Read(fd, buf, sizeof(buf))) != sizeof(buf) ) {
        MP3U_LOG ("mp3FindVBRI: bad header read\n");
        if ( rv >= 0 )
            rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    
    vi->id = BYTES_TO_INT32(buf[0],buf[1],buf[2],buf[3]);
    
#define isVBRI(id)   ((id) == BYTES_TO_INT32('V','B','R','I'))
    
    if ( isVBRI(vi->id) ) {
        MP3U_LOG("mp3FindVBRI: found legal id\n");
    } else {
        MP3U_LOG("mp3FindVBRI: header not found\n");
        rv = 0;
        goto out;
    }

    /* parse remainder of VBRI fixed fields */
    
    vi->version = BYTES_TO_INT16(buf[4],buf[5]);
    vi->delay = BYTES_TO_INT16(buf[6],buf[7]);
    vi->quality = BYTES_TO_INT16(buf[8],buf[9]);
    vi->nBytes = BYTES_TO_INT32(buf[10],buf[11],buf[12],buf[13]);
    vi->nFrames = BYTES_TO_INT32(buf[14],buf[15],buf[16],buf[17]);
    vi->tocEntries = BYTES_TO_INT16(buf[18],buf[19]);
    vi->tocScale = BYTES_TO_INT16(buf[20],buf[21]);
    vi->tocEntrySize = BYTES_TO_INT16(buf[22],buf[23]);
    vi->tocEntryFrames = BYTES_TO_INT16(buf[24],buf[25]);

    if ( vi->tocEntrySize < 1 || vi->tocEntrySize > 4 ) {
        rv = IOS_ERROR_INVALID_FORMAT;
        MP3U_ERROR("illegal VBRI TOC entry size");
        goto out;
    }

    MP3U_LOG("mp3FindVBRI: frames = %d, bytes = %d\n",vi->nFrames,vi->nBytes);
    MP3U_LOG("mp3FindVBRI: toc = %d x %d-byte entries, scale = %d, frames/entry = %d\n",
             vi->tocEntries, vi->tocEntrySize, vi->tocScale, vi->tocEntryFrames);
    
    /* read table of contents (toc) entries */
    /* VBRI toc description
     * 1. there are vi->tocEntries entries in the table
     * 2. each entry is vi->tocEntrySize bytes in size
     * 3. each entry must be multiplied by vi->tocScale to get its final value
     * 4. each entry covers an interval of vi->tocEntryFrames MP3 frames
     *
     * if 'i' is an index into the toc,
     * then the corresponding time is
     *    t=(i+1)*vi->tocEntryFrames/vi->nFrames*duration,
     * and the corresponding byte location in the MP3 file is
     *    nb = sum(toc(k), k=-1,...,i) where toc(-1)=0
     * where duration in seconds is
     *    duration = vi->nFrames * samplesPerFrame / playbackFrequency
     * and samplesPerFrame is 1152 for MPEG 1 Layer III and
     * playbackFrequency is 48000Hz, 44100Hz, 32000Hz, etc.
     *
     * Note that the 0th entry (i=0) does not represent time=0!
     */

    /* The VBRI toc can be up to 2^16 entries * 4-byte/entries = 256Kbytes in
     * size!  This is too large for our purposes, so we'll compress it in to
     * (at most) 100 1-byte entries.  The compressed toc (ctoc) will be in
     * the same format at an Xing header (index represents the time expressed
     * as percentage of the total duration, and entries represent byte location
     * within the file expressed in units of (total MP3 data bytes)/255. Note
     * the for Xing, the 0th entry (i=0) represents time=0.
     *
     * compress table (ctoc) description
     * 1. to ensure ctoc has at most 100 entries, 'ratio' toc entries
     *    are combined into a single ctoc entry, where
     *    ratio = ceiling(vi->tocEntries/99)
     *    Note: actually we compress in to 99 entries, then add a new
     *          0th entry and set the 0th entry to represent time=0.
     * 2. ctoc has nEntries = ceiling(vi->tocEntries/ratio) entries
     * 3. each entry is one byte
     */
    u32 l = vi->tocEntries * vi->tocEntrySize; /* VBRI toc size in bytes */
    u32 ratio = (vi->tocEntries+98) / 99; /* ceiling(vi->tocEntries/99) */
    u32 rem = vi->tocEntries % ratio;
    u32 nEntries = vi->tocEntries/ratio;
    if ( rem )
        nEntries++;                       /* number of entries in ctoc */

    if ( nEntries == 0 ) {
        MP3U_ERROR("mp3FindVBRI: toc is empty");
        rv = IOS_ERROR_INVALID_FORMAT;
        goto out;
    }
        
    u32 duration = ((u64)vi->nFrames * 1152 * 100000) / mp3i->freq; /* 10's usec */
    MP3U_LOG("mp3FindVBRI: duration = %d, frames = %d, freq = %d\n",
             duration,vi->nFrames,mp3i->freq);

    /* use u64 to avoid loss of precision in tracking time and in
     * calculating fractions of duration and fractions of MP3 data
     * length in bytes
     * */
    u64 duration64 = (u64)duration;
    u64 deltaTSrc = (duration64<<32) / vi->tocEntries; /* time between VBRI toc entries */
    u64 deltaTDst = (duration64<<32) / nEntries;       /* time between ctoc entries */
    MP3U_LOG("mp3FindVBRI: duration = %u, deltaTSrc = %u, deltaTDst = %u\n",
             duration,(u32)deltaTSrc,(u32)deltaTDst);
    
    u64 tSrc = 0;          /* time corresponding to VBRI toc entry */
    u64 tDst = deltaTDst;  /* time corresponding to ctoc entry */
    u32 e;                 /* VBRI toc entry value */
    u32 nb = 0;            /* cumulative total byte offset from VBRI toc */
    u32 i;                 /* current VBRI toc index */
    u32 j=1;               /* current ctoc index */

    if ( start >= end ) {
        rv = IOS_ERROR_FAIL_INTERNAL;
        MP3U_ERROR("zero-length MP3 data");
        goto out;
    }
    MP3U_LOG("mp3FindVBRI: start = %d, end = %d\n");
    
    for ( i=0; i<l && j<nEntries; i++ ) {
        /* read a VRBI toc entry */
        if ( (rv = IOS_Read(fd, buf, vi->tocEntrySize)) != vi->tocEntrySize ) {
            MP3U_LOG ("mp3FindVBRI: bad toc read\n");
            if ( rv >= 0 )
                rv = IOS_ERROR_FAIL_INTERNAL;
            goto out;
        }
        /* convert entry value to u32 size */
        switch (vi->tocEntrySize) {
        case 1: e = buf[0]; break;
        case 2: e = BYTES_TO_INT16(buf[0],buf[1]); break;
        case 3: e = ((buf[0]<<16)|(buf[1]<<8)|buf[2]); break;
        case 4: e = BYTES_TO_INT32(buf[0],buf[1],buf[2],buf[3]); break;
        default: rv = IOS_ERROR_FAIL_INTERNAL; goto out; break;
        }
        /* scale and accumlate entries, i.e., incremental byte offsets */
        tSrc += deltaTSrc;
        e *= vi->tocScale;
        nb += e;
        MP3U_LOG("mp3FindVBRI: toc[%d=%d] = %d\n",i,(u32)(tSrc>>32),nb);
        
        /* populate a new ctoc entry */
        if ( tSrc >= tDst ) {
            /* interpolate to find byte offset corresponding to tDst
             * given the byte offset at tSrc (i.e., offset = nb)
             * and the byte offset at tSrc-deltaTSrc (i.e., offset = nb - e)
             */
            u64 dt = (tSrc - tDst)>>32;
            u64 nbDst = nb - (e * dt)/(deltaTSrc>>32);
            vi->toc[j] = (nbDst * 255) / (end - start); /* calculation done in u64 */
            MP3U_LOG("mp3FindVBRI: ctoc[%d=%d] = %d -> %d -> %d\n",j,(u32)(tDst>>32),
                     vi->toc[j],(u32)nbDst,((u64)vi->toc[j]*(end-start))/255);
            j++;
            tDst += deltaTDst;
        }
        if ( nb > end ) {
            rv = IOS_ERROR_INVALID_FORMAT;
            MP3U_ERROR("VBRI offset too large");
            goto out;
        }
        
    }

    /* ensure the first entry points to beginning of MP3 data
     * and the last entry points to the end of MP3 data
     */
    vi->toc[0] = 0;
    vi->toc[nEntries-1] = 255;

    /* update toc parameters to correspond to the new ctoc */
    vi->tocEntries = nEntries;
    vi->tocEntrySize = 1;
    vi->tocScale = 1;
    vi->valid = 1;
    
    rv = 1;  /* VBRI header found */
    
out:
    return rv;
}

/*
 * mp3XingTimeToOffset -- convert from time to byte-offset using Xing header info
 */
s32
mp3XingTimeToOffset(u32 time, u32 duration, s32 start, s32 end, XingInfo *xi)
{
    s32 offset;
    
    /* use Xing table of contents to compute new byte location */
    u32 ndx = (((u64)time) * 100) / duration;
    u32 rem = (((u64)time) * 100) % duration;
    if ( ndx >= 100 ) {
        offset = end;
        MP3U_LOG("mp3XingTimeToOffset: %d msec => %d bytes (ndx = %d)\n",
                time,offset,ndx);
    } else {
        /* Xing table of contents (TOC) contains 100 entries;
         * each entry maps from "percentage of time" to "fraction of bytes";
         * percentage of time is an 8-bit unsigned integer between 0 and 99, inclusive;
         * fraction of bytes is an 8-bit unsigned integer between 0 and 255, inclusive;
         * target byte location = "fraction of bytes"/255 * "file length in bytes"
         */
        u32 byteFrac = xi->toc[ndx] +
            ( (xi->toc[ndx+1] - xi->toc[ndx]) * ((u64)rem) ) / duration;
        offset = start + ( byteFrac * ((u64)(end - start)) ) / 255;
        MP3U_LOG("mp3XingTimeToOffset: %d msec => %d bytes (ndx = %d, toc=[%d,%d], frac = %d)\n",
                time,offset,ndx,xi->toc[ndx],xi->toc[ndx+1],byteFrac);
    }
    return offset;
}

/*
 * mp3VbriTimeToOffset -- convert from time to byte-offset using VBRI header info
 */
s32
mp3VbriTimeToOffset(u32 time, u32 duration, s32 start, s32 end, VbriInfo *vi)
{
    s32 offset;
    
    /* use VBRI table of contents to compute new byte location */
    u32 ndx = (((u64)time) * vi->tocEntries) / duration;
    u32 rem = (((u64)time) * vi->tocEntries) % duration;
    if ( ndx >= vi->tocEntries ) {
        offset = end;
        MP3U_LOG("mp3VbriTimeToOffset: %d msec => %d bytes (ndx = %d, #entries = %d)\n",
                time,offset,ndx,vi->tocEntries);
    } else {
        /* Compressed VBRI table of contents (CTOC) contains tocEntries entries,
         * where tocEntries <= 100;
         * each entry maps from "fraction of time" to "fraction of bytes";
         * fraction of time is an 8-bit unsigned integer between 0 and tocEntries, inclusive;
         * fraction of time is in units of tocEntries / duration;
         * fraction of bytes is an 8-bit unsigned integer between 0 and 255, inclusive;
         * target byte location = "fraction of bytes"/255 * "file length in bytes"
         */
        u32 byteFrac = vi->toc[ndx] +
            ((vi->toc[ndx+1] - vi->toc[ndx]) * ((u64)rem)) / duration;
        offset = start + ( byteFrac * ((u64)(end - start)) ) / 255;
        MP3U_LOG("mp3VbriTimeToOffset: %d msec => %d bytes (ndx = %d, toc=[%d,%d], frac = %d)\n",
                time,offset,ndx,vi->toc[ndx],vi->toc[ndx+1],byteFrac);
    }
    return offset;
}

/*
 * mp3GetFreeBitrate -- determine bitrate for freeformat encoding;
 *                      return bitrate in kbps if successful,
 *                      IOS_ERROR_NOEXISTS if matching header
 *                      not found, else an error code
 *
 * if successful, also populate bitrate and len fields in mp3i
 * 
 * assumes MPEG v1, layer 3
 */
IOSError
mp3GetFreeBitrate(IOSFd fd, Mp3Info *mp3i, s32 start, s32 end)
{
    IOSError rv;
    u32 header1, header2;
    s32 pos1, pos2;
    s32 length, l;
    u8 buf[4];
    u8 found = 0;
    s32 bitrate = 0;
    
    /* for MPEG v1, layer 3,
     *   
     *   frame size = ((144*bitrate)/freq)+pad), bytes
     *   
     * where bitrate is in bits/sec and freq is in Hz.
     * 
     * max(frame size) corresponds to max(bitrate)=640kbps,
     * min(freq)=32000Hz, and padding --
     * 
     *   max(frame size) = ((144*640000) / 32000 + 1)
     *                   = 2881 bytes
     *
     * min(frame size) corresponds to min(bitrate)=8kbps,
     * max(freq)=48000Hz, and no padding --
     * 
     *   min(frame size) = ((144*8000) / 48000)
     *                   = 24 bytes
     */
#define MAX_MPEG1_LAYER3_FRAME_SIZE ((144*640000) / 32000 + 1)
#define MIN_MPEG1_LAYER3_FRAME_SIZE ((144*8000) / 48000)
    
/* check that MPEG version, layer, and sampling frequency haven't
 * changed mid-stream
 */
#define MP3U_HEADER_FINGERPRINT_MASK (MP3_HEADER_SYNC_MASK |  \
                                      MP3_HEADER_ID_MASK |    \
                                      MP3_HEADER_LAYER_MASK | \
                                      MP3_HEADER_FREQ_MASK)
#define MP3U_HEADER_FINGERPRINT(h)  ((h)&MP3U_HEADER_FINGERPRINT_MASK)
    
    /* look for 3 consecutive MP3 headers to (1) ensure
     * sync with the bitstream and to (2) compute bitrate
     */
    pos1 = start + MIN_MPEG1_LAYER3_FRAME_SIZE + 4;
    if ( pos1 > end ) {
        /* not enough data remaining */
        rv = IOS_ERROR_NOEXISTS;
        MP3U_ERROR("mp3GetFreeBitrate: short circuit");
        goto out;
    }
    pos2 = start + MAX_MPEG1_LAYER3_FRAME_SIZE + 4;
    if ( pos2 > end )
        pos2 = end;
    
    do {
        /* look for an mp3 header */
        MP3U_LOG("pos1 = %d\n",pos1);
        MP3U_LOG("template = 0x%08x, 0x%08x\n",mp3i->head,MP3U_HEADER_FINGERPRINT_MASK);
        
        if ( (rv = mp3FindFrame(fd,pos1,pos2,mp3i->head,MP3U_HEADER_FINGERPRINT_MASK,&header1)) < 0 ) {
            MP3U_ERROR("mp3GetFreeBitrate: header seek #1");
            goto out;
        }
        pos1 = rv;
        MP3U_LOG("mp3GetFreeBitrate: candidate header #1 found at %d, header = 0x%08x\n",pos1,header1);

        /* compute frame length */
        length = pos1 - start;

        /* check for header match #1 */
        MP3U_LOG("mp3GetFreeBitrate: header #1 match found at %d\n",pos1);
        /* found first matching header, now look for a second */
        l = length;
        if ( mp3i->pad )
            l--;
        if ( GET_FIELD(header1,MP3_HEADER_PAD) )
            l++;
        if ( pos1 + l + 4 > end ) {
            /* file ends before 2nd match can be made */
            /* compute bitrate based on the one match that was made */
            MP3U_LOG("mp3GetFreeBitrate: eof before header #2\n");
            bitrate = (length * mp3i->freq * 8) / 1152 / 1000; /* kbits/sec */
            if ( bitrate >= 8 && bitrate < 640 )
                found = 1;
        } else {
            MP3U_LOG("mp3GetFreeBitrate: header #2 sought at %d\n",pos1+l);
            /* seek to expected locn of next header */
            if ( (rv = IOS_Seek(fd, pos1+l, IOS_SEEK_SET)) < 0 ) {
                rv = IOS_ERROR_FAIL_INTERNAL;
                MP3U_LOG("mp3GetFreeBitrate: bad seek\n");
                goto out;
            }
            /* read data into buffer */
            if ( (rv = IOS_Read(fd, buf, 4)) != 4 ) {
                rv = IOS_ERROR_FAIL_INTERNAL;
                MP3U_LOG("mp3GetFreeBitrate: bad read\n");
                goto out;
            }
            header2 = BYTES_TO_INT32(buf[0],buf[1],buf[2],buf[3]);
            if ( MP3U_HEADER_FINGERPRINT(mp3i->head) == MP3U_HEADER_FINGERPRINT(header2) ) {
                MP3U_LOG("mp3GetFreeBitrate: header #2 match at %d\n",pos1+l);
                bitrate = (length * mp3i->freq * 8) / 1152 / 1000; /* kbits/sec */
                if ( bitrate >= 8 && bitrate < 640 )
                    found = 1;
            }
        }

        pos1++;  /* continue searching after the last-found header */
        
    } while ( ! found );

    MP3U_LOG("mp3GetFreeBitrate: frame length = %d bytes, bitrate = %d kbps\n",length,bitrate);

    rv = bitrate;

    mp3i->bitrate = bitrate;
    mp3i->len = length;
    
out:
    return rv;
}

/*
 * mp3Resync -- resync MP3 stream by finding 3 consistent
 *              headers; return address of first header
 *              on success, IOS_ERROR_NOEXISTS if 
 *              consistent headers not found, else an
 *              error code
 *
 * if 'start' is close to 'end', then only 1 or 2 headers
 * are required;
 * only "matching" headers are considered, where "matching"
 * means (mp3i->head&mask) == (header&mask).
 * 
 * Note that setting mask=0 forces all headers to "match"
 *
 * return address of first header on success
 *        IOS_ERROR_NOEXISTS if consistent headers not found
 *           and end-start>max(frame length)
 *        IOS_ERROR_FAIL_INTERNAL if file operation fails
 */
IOSError
mp3Resync(IOSFd fd, Mp3Info *mp3i, s32 start, s32 end, u32 mask)
{
    IOSError rv = IOS_ERROR_NOEXISTS;
    u32 h;        /* header */
    s32 s, e, p;  /* start, end, current offsets */
    s32 l;        /* frame length */
    u8 buf[4];    /* read buffer for header bytes */
    u8 found = 0; /* number of consecutive matches found */
    s32 i;
    Mp3Info mp3il;
    
    /* look for 3 consecutive MP3 headers to (1) ensure
     * sync with the bitstream and to (2) compute bitrate
     */
    s = start;
    if ( s + 4 > end ) {
        /* not enough data remaining, skip to eof */
        rv = end;
        MP3U_LOG("mp3GetFreeBitrate: eof before 1st header, skip to eof\n");
        goto out;
    }
    e = start + MAX_MPEG1_LAYER3_FRAME_SIZE + 4;
    if ( e > end )
        e = end;
    
    do {
        /* look for first mp3 header */
        MP3U_LOG("s = %d\n",s);
        MP3U_LOG("template = 0x%08x, mask = 0x%08x\n",mp3i->head,mask);
        
        if ( (rv = mp3FindFrame(fd,s,e,mp3i->head,mask,&h)) < 0 ) {
            if ( rv == IOS_ERROR_NOEXISTS && e == end ) {
                MP3U_LOG("mp3GetFreeBitrate: eof before any header, skip to eof\n");
                rv = end;
            } else {
                MP3U_ERROR("mp3Resync: header seek #1");
            }
            goto out;
        }
        p = s = rv;
        MP3U_LOG("mp3Resync: candidate header #1 found at %d, header = 0x%08x\n",s,h);

        found = 1;
        for ( i=1; i<3; i++ ) {
            
            /* get frame length */
            mp3ParseHeader(h,&mp3il);
            if ( mp3il.bitrate == 0 ) {
                /* if freeformat, take length from XXX */
                l = mp3i->len;
                if ( mp3i->pad )
                    l--;
                if ( mp3il.pad )
                    l++;
            } else {
                l = mp3FrameSize(&mp3il);
            }
            p += l;
            
            /* check for next matching header */
            if ( p + 4 > end ) {
                /* file ends before match can be made, skip to eof */
                MP3U_LOG("mp3Resync: eof before #%d header, skip to eof\n",i+1);
                found++;
            } else {
                MP3U_LOG("mp3Resync: header #%d sought at %d\n",i+1,p);
                /* seek to expected locn of next header */
                if ( (rv = IOS_Seek(fd, p, IOS_SEEK_SET)) < 0 ) {
                    rv = IOS_ERROR_FAIL_INTERNAL;
                    MP3U_LOG("mp3Resync: bad seek\n");
                    goto out;
                }
                /* read data into buffer */
                if ( (rv = IOS_Read(fd, buf, 4)) != 4 ) {
                    rv = IOS_ERROR_FAIL_INTERNAL;
                    MP3U_LOG("mp3Resync: bad read\n");
                    goto out;
                }
                h = BYTES_TO_INT32(buf[0],buf[1],buf[2],buf[3]);
                if ( (mp3i->head&mask) == (h&mask) && mp3ParseHeader(h,&mp3il) == 1 ) {
                    MP3U_LOG("mp3Resync: header #%d match at %d\n",i+1,p);
                    found++;
                } else {
                    /* matching header not found,
                     * look for next candidate 1st header
                     */
                    MP3U_LOG("mp3Resync: no header #%d match at %d\n",i+1,p);
                    break;
                }
            }

        }

        if ( found != 3  )
            s++;  /* continue searching after the current 1st header */
        
    } while ( found != 3 );

    rv = s;

out:
    if ( rv >= 0 ) {
        MP3U_LOG("mp3Resync: sync at %d\n",s);
    }
        
    return rv;
}

/*
 * mp3FindStandaloneFrame
 *
 * find a stand-alone MP3 frame, i.e., one which contains its own
 * Main Data and doesn't refer back to any previous frames; return
 * address of frame and number of frames skipped on success,
 * IOS_ERROR_NOEXISTS if no such frame is found, else an error code
 *
 * on entry, start must point to a valid frame header
 * mp3i->len must be a valid frame length, if freeformat MP3 stream
 * 
 * only "matching" headers are considered, where "matching" means
 * (mp3i->head&mask) == (header&mask).
 * 
 * Note that setting mask=0 forces all headers to "match"
 *
 * return address of standalone frame on success
 *        IOS_ERROR_NOEXISTS if no standalone frame is found
 *        IOS_ERROR_FAIL_INTERNAL if file operation fails
 *        IOS_ERROR_INVALID_FORMAT if an MP3 stream error occurs
 */
IOSError
mp3FindStandaloneFrame(IOSFd fd, Mp3Info *mp3i, s32 start, s32 end, u32 mask, u32 *skipped)
{
    IOSError rv = IOS_ERROR_NOEXISTS;
    u32 h;        /* header */
    s32 p;        /* current MP3 stream offsets */
    s32 l = 0;    /* frame length */
    u8 buf[6];    /* read buffer for header and main_data_begin */
    u32 n = 0;    /* number of frames skipped */
    u16 main_data_begin; /* locn of decode data, counting backward */
    Mp3Info mp3il;
    
    p = start;

    while ( 1 ) {

        /* check for remaining MP3 stream data */
        if ( p+MIN_MPEG1_LAYER3_FRAME_SIZE > end ) {
            MP3U_LOG("mp3FindStandaloneFrame: reached eof\n");
            rv = IOS_ERROR_NOEXISTS;
            break;
        }
        
        /* seek to frame location */
        if ( (rv = IOS_Seek(fd, p, IOS_SEEK_SET)) < 0 ) {
            MP3U_ERROR("mp3FindStandaloneFrame: header seek");
            rv = IOS_ERROR_FAIL_INTERNAL;
            break;
        }

        /* read header and main_data_begin */
        if ( (rv = IOS_Read(fd, &buf[0], sizeof(buf))) != sizeof(buf) ) {
            MP3U_ERROR("mp3FindStandaloneFrame: header read");
            rv = IOS_ERROR_FAIL_INTERNAL;
            break;
        }

        /* check for valid, matching header */
        h = BYTES_TO_INT32(buf[0],buf[1],buf[2],buf[3]);
        MP3U_LOG("header = 0x%08x\n",h);
        if ( (mp3i->head&mask) != (h&mask) || mp3ParseHeader(h,&mp3il) != 1 ) {
            MP3U_ERROR("mp3FindStandaloneFrame: missing header");
            rv = IOS_ERROR_INVALID_FORMAT;
            break;
        }

        /* check main_data_begin to see if frame is standalone */
        if ( mp3i->id == MPEG_VERSION_2 ) {
            main_data_begin = buf[4];
        } else {
            main_data_begin = (buf[4]<<1) | (buf[5]>>7);
        }
        MP3U_LOG("mp3FindStandaloneFrame: main_data_begin = %d @ 0x%08x\n",
                 main_data_begin,(u32)p);
        if ( main_data_begin == 0 ) {
            /* found standalone frame */
            MP3U_LOG("mp3FindStandaloneFrame: found at %d, skipped %d\n",(u32)p,n);
            rv = (IOSError)p;
            if ( skipped )
                *skipped = n;
            break;
        }
        /* not standalone; prepare to look for next frame */
        if ( mp3il.bitrate == 0 ) {
            /* if freeformat, take length from XXX */
            l = mp3i->len;
            if ( mp3i->pad )
                l--;
            if ( mp3il.pad )
                l++;
        } else {
            l = mp3FrameSize(&mp3il);
        }

        if ( l == 0 ) {
            /* sanity check; ensure against infinite loop */
            MP3U_ERROR("mp3FindStandaloneFrame: invalid length");
            rv = IOS_ERROR_INVALID_FORMAT;
            break;
        }

        p += l;
        n++;
    }

    return rv;
}

/*
 * mp3ResyncMainData
 *
 * an MP3 frame can require Main Data from previous frames in
 * order to be decoded.  After skipping to a new location in the
 * MP3 stream, the decoder will not have access to the frames
 * that sequentially preceeded the new frame and therefore the
 * Main Data needed to decode the new frame may be missing,
 * causing it to be decoded improperly. This routine computes
 * the number of new frames that will be decoded improperly.
 *
 * the number of new frames that will be decoded improperly
 * is returned on success, IOS_ERROR_NOEXISTS is returned if no
 * frame can be properly decoded, else an error code is returned
 *
 * on entry, start must point to a valid frame header
 * mp3i->len must be a valid frame length, if freeformat MP3 stream
 * 
 * only "matching" headers are considered, where "matching" means
 * (mp3i->head&mask) == (header&mask).
 * 
 * Note that setting mask=0 forces all headers to "match"
 *
 * return number of frames that will decode improperly
 *        IOS_ERROR_NOEXISTS if no standalone frame is found
 *        IOS_ERROR_FAIL_INTERNAL if file operation fails
 *        IOS_ERROR_INVALID_FORMAT if an MP3 stream error occurs
 */
IOSError
mp3ResyncMainData(IOSFd fd, Mp3Info *mp3i, s32 start, s32 end, u32 mask)
{
    IOSError rv = IOS_ERROR_NOEXISTS;
    u32 h;        /* header */
    s32 p;        /* current MP3 stream offsets */
    s32 l = 0;    /* frame length */
    u8 buf[6];    /* read buffer for header and main_data_begin */
    u32 n = 0;    /* number of frames skipped */
    u16 main_data_begin; /* locn of decode data, counting backward */
    u32 mdTotal = 0;/* cumulative main data available */
    u32 mdFrame;       /* main data size for current frame */
    
    
    Mp3Info mp3il;
    
    p = start;

    while ( 1 ) {

        /* check for remaining MP3 stream data */
        if ( p+MIN_MPEG1_LAYER3_FRAME_SIZE > end ) {
            MP3U_LOG("mp3ResyncMainData: reached eof\n");
            rv = IOS_ERROR_NOEXISTS;
            break;
        }
        
        /* seek to frame location */
        if ( (rv = IOS_Seek(fd, p, IOS_SEEK_SET)) < 0 ) {
            MP3U_ERROR("mp3ResyncMainData: header seek");
            rv = IOS_ERROR_FAIL_INTERNAL;
            break;
        }

        /* read header and main_data_begin */
        if ( (rv = IOS_Read(fd, &buf[0], sizeof(buf))) != sizeof(buf) ) {
            MP3U_ERROR("mp3ResyncMainData: header read");
            rv = IOS_ERROR_FAIL_INTERNAL;
            break;
        }

        /* check for valid, matching header */
        h = BYTES_TO_INT32(buf[0],buf[1],buf[2],buf[3]);
        MP3U_LOG("header = 0x%08x\n",h);
        if ( (mp3i->head&mask) != (h&mask) || mp3ParseHeader(h,&mp3il) != 1 ) {
            MP3U_ERROR("mp3ResyncMainData: missing header");
            rv = IOS_ERROR_INVALID_FORMAT;
            break;
        }

        /* check main_data_begin to see if frame is standalone */
        if ( mp3i->id == MPEG_VERSION_2 ) {
            main_data_begin = buf[4];
        } else {
            main_data_begin = (buf[4]<<1) | (buf[5]>>7);
        }
        MP3U_LOG("mp3ResyncMainData: need = %d @ %d, avail = %d\n",
                 main_data_begin,(u32)p,mdTotal);
        if ( main_data_begin <= mdTotal ) {
            /* found standalone frame */
            MP3U_LOG("mp3ResyncMainData: found at %d, skipped %d\n",(u32)p,n);
            rv = (IOSError)n;
            break;
        }
        
        /* not standalone */

        /* find size of main data in this frame */
        if ( mp3il.bitrate == 0 ) {
            /* if freeformat, take length from XXX */
            l = mp3i->len;
            if ( mp3i->pad )
                l--;
            if ( mp3il.pad )
                l++;
        } else {
            l = mp3FrameSize(&mp3il);
        }

        if ( l == 0 ) {
            /* sanity check; ensure against infinite loop */
            MP3U_ERROR("mp3ResyncMainData: invalid length");
            rv = IOS_ERROR_INVALID_FORMAT;
            break;
        }
        
        mdFrame = l;
        mdFrame -= 4;  // for header
        
        if ( mp3il.prot )
            mdFrame -= 2; // for crc
        if ( mp3il.mode == MPEG_MODE_MONO )
            mdFrame -= 17;  // 17 bytes of side data for 1 channel
        else
            mdFrame -= 32;  // 32 bytes of side data for 2 channels

        /* find new amount of main data available */
        mdTotal += mdFrame;
        
        MP3U_LOG("mp3ResyncMainData: frame = %d, total = %d\n",mdFrame,mdTotal);
        /* advance to next frame */
        p += l;  // advance to next frame
        n++;     // update bad-decode counter
    }

    return rv;
}
