/*****************************************************************************
Copyright(c) 2005 Analog Devices, Inc.  All Rights Reserved. This software is 
proprietary and confidential to Analog Devices, Inc. and its licensors.
******************************************************************************

$RCSfile: MJPEG_AVI_FileReader.c,v $
$Revision: 1.1 $
$Date: 2008/03/25 05:45:17 $

Project:	MJPEG Decoder
Title:		AVI File reader
Author(s):	P.V.R.B
Revised by: 

Description : Header file of AVI File Reader.

References:
	
******************************************************************************
Tab Setting:			4
Target Processor:		Blackfin
Target Tools Revision:	VDSP++ 4.0
******************************************************************************

Modification History:
====================
$Log: MJPEG_AVI_FileReader.c,v $
Revision 1.1  2008/03/25 05:45:17  randreol
Moved files for new directry structure

Revision 1.2  2007/11/14 03:18:34  randreol
Port to new USB driver, remove setvbuf, port to VDSP 5.0

Revision 1.1  2006/07/17 07:44:02  bmk
JPEG-MJPEG User access files


******************************************************************************/

#include <stdlib.h>
#include "MJPEG_AVI_Common.h"
#include "MJPEG_AVI_FileReader.h"



// Changed to smaller size to work better with the post June update tools    
#pragma align 4
section ("sdram0_bank1_cache")
static char fileiobuff[16384];	// fileio buffer (in  cached SDRAM)


/**/
/* Evaluation version limiting 								*/
/* Limit evaluation version to encoding/decoding 100 frames */
/* Define ISEVALUATION in project to activate 				*/
#ifdef ISEVALUATION
#define EVALUATIONMAXFRAMES		100			
#warning *** EVALUATION MODE - Number of encoding/decoding frames is limited ***
#endif

#ifdef MJPEGREWIND
#include <string.h> 
#define MAXINDEXBUFFERSIZE 10
#pragma align 4
section ("sdram0_bank1_cache")
static MJPEG_AVI_INDEXENTRY *FrameIndex;
#pragma align 4
section ("sdram0_bank1_cache")
static int FrameCount;
#pragma align 4
section ("sdram0_bank1_cache")
static uint32 frameheader[2];
#endif

/*
*******************************************************************************
Name        	: fseek_workaround
Description 	: Seeks to a specified point in file by doing freads
				: This function is used to get around the fseek problem in VDSP
				: 4 (June and Sept updates). Call this function only when using
				: SEEK_CUR option.
Parameter   	: pFile				  : file pointer to the file to do the seek
            	: bytes				  : number of bytes to seek from current 
            	: 						position
				: origin              : same as that of normal fseek
Return Value	: returns 0 if successful, -1 if failed
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int fseek_workaround(FILE *pFile,int bytes,int origin)
{
	long pos;
	
	if (origin != SEEK_CUR)
		return(fseek(pFile,bytes,origin));
	
	pos = ftell(pFile);
	
	if (pos == -1)
		return -1;
		
	bytes += pos;
	
	return (fseek(pFile,bytes,SEEK_SET));
}


/*
*******************************************************************************
Name        	: MJPEG_AVI_OpenFileRead
Description 	: Opens the MJPEG AVI file for reading 
				: The index table (i.e. idx1 chunk) is assumed to be present in
				: the file.
Parameter   	: pAVIFileHandle      : pointer to receive the AVI File Handle.
            	: fileName            : Name of the AVI file to be opened.
Return Value	: MJPEG_AVI_RETURN_OK if file opened OK
	`			  MJPEG_AVI_RETURN_OUTOFMEMORY 
							if memory could not be allocated when opening the file
				  MJPEG_AVI_RETURN_FILEOPENFAIL
				  			if the input file could not be opened
				  MJPEG_AVI_RETURN_FILEREADFAIL
				  			if the input file could not be read
				  MJPEG_AVI_RETURN_FILEINCORRECTFORMAT
				  			if the input file was not in MJPEG AVI format
				  MJPEG_AVI_RETURN_FILESEEKFAIL
				  			if the seek operation on the input file failed			  
				  MJPEG_AVI_RETURN_ERROR otherwise
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_OpenFileRead(uint32 *pAVIFileHandleParam, int8 *fileName)
{
    FILE *fp;
    uint32 ListhdrlChunkLength, avihChunkLength, ListmoviChunkLength;
    tMJPEG_AVI_FILEHANDLEREAD *pAVIFileHandle 
        = (tMJPEG_AVI_FILEHANDLEREAD *)pAVIFileHandleParam;
    tMJPEG_AVI_RIFFHEADER lAviRiff;
    uint32 fileLength, lChunkId;
    int32 lResult;

    *pAVIFileHandle = (tMJPEG_AVI_FILEHANDLEREAD) malloc(sizeof(tMJPEG_AVI_FileRead));
    if(*pAVIFileHandle == NULL)
    {
        return MJPEG_AVI_RETURN_OUTOFMEMORY;
    }
    
    fp = fopen((const char *)fileName,"rb");
    if( fp == NULL)
    {
        lResult = MJPEG_AVI_RETURN_FILEOPENFAIL;
        goto RETURN_ERROR;
    }

    //setvbuf((FILE*)fp, fileiobuff, _IOLBF, sizeof(fileiobuff));
    
    (*pAVIFileHandle)->filePtr = fp;
    fseek(fp, 0, SEEK_END);
    fileLength = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    if(fread(&lAviRiff, 1, 12, fp) != 12)
    {
        lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
        goto RETURN_ERROR;
    }

    if(lAviRiff.riffCkid != MJPEG_AVI_FOURCC('R','I','F','F')
        || lAviRiff.aviCkid != MJPEG_AVI_FOURCC('A','V','I',' ')
        || lAviRiff.chunkLength != (fileLength - 8))
    {
        lResult = MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
        goto RETURN_ERROR;
    }

    /* Getting the ListhdrlChunkOffset */
    while(1)
    {
        if(fread(&lChunkId, 1, 4, fp) != 4
            || fread(&ListhdrlChunkLength, 1, 4, fp) != 4)
        {
            lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
            goto RETURN_ERROR;
        }
        if(lChunkId != MJPEG_AVI_FOURCC('L','I','S','T'))
        {
            // workaround for fseek issues
            if(fseek_workaround(fp, ListhdrlChunkLength, SEEK_CUR) != 0)
            {
                lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
                goto RETURN_ERROR;
            }
            continue;
        }

        if(fread(&lChunkId, 1, 4, fp) != 4)
        {
            lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
            goto RETURN_ERROR;
        }
        if(lChunkId != MJPEG_AVI_FOURCC('h','d','r','l'))
        {
        	// workaround for fseek issues
		    if(fseek_workaround(fp, ListhdrlChunkLength-4, SEEK_CUR) != 0)
            {
                lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
                goto RETURN_ERROR;
            }
            continue;
        }

        (*pAVIFileHandle)->ListhdrlChunkOffset = ftell(fp) - 12;
        break;
    }

    (*pAVIFileHandle)->avihChunkOffset = ftell(fp);
    if(fread(&lChunkId, 1, 4, fp) != 4)
    {
        lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
        goto RETURN_ERROR;
    }
    if(lChunkId != MJPEG_AVI_FOURCC('a','v','i','h'))
    {
        lResult = MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
        goto RETURN_ERROR;
    }
    if(fread(&avihChunkLength, 1, 4, fp) != 4)
    {
        lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
        goto RETURN_ERROR;
    }
    
    if(avihChunkLength != sizeof(MJPEG_AVI_MainAVIHeader))
    {
        lResult = MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
        goto RETURN_ERROR;
    }
    if(fread(&((*pAVIFileHandle)->avih),1,sizeof(MJPEG_AVI_MainAVIHeader),fp)
        != sizeof(MJPEG_AVI_MainAVIHeader))
    {
        lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
        goto RETURN_ERROR;
    }


    /* Getting the ListmoviChunkOffset */
    if(fseek(fp, (*pAVIFileHandle)->ListhdrlChunkOffset+ListhdrlChunkLength+8,
        SEEK_SET) != 0)
    {
        lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
        goto RETURN_ERROR;
    }

    while(1)
    {
        if(fread(&lChunkId, 1, 4, fp) != 4
            || fread(&ListmoviChunkLength, 1, 4, fp) != 4)
        {
            lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
            goto RETURN_ERROR;
        }
        if(lChunkId != MJPEG_AVI_FOURCC('L','I','S','T'))
        {
        	// workaround for fseek issues
		    if(fseek_workaround(fp, ListmoviChunkLength, SEEK_CUR) != 0)
            {
                lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
                goto RETURN_ERROR;
            }
            continue;
        }

        if(fread(&lChunkId, 1, 4, fp) != 4)
        {
            lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
            goto RETURN_ERROR;
        }
        if(lChunkId != MJPEG_AVI_FOURCC('m','o','v','i'))
        {
        	// workaround for fseek issues
		    if(fseek_workaround(fp, ListmoviChunkLength-4, SEEK_CUR) != 0)
            {
                lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
                goto RETURN_ERROR;
            }
            continue;
        }

        (*pAVIFileHandle)->ListmoviChunkOffset = ftell(fp) - 12;
        break;
    }

    // workaround for fseek issues    
    if(fseek_workaround(fp, ListmoviChunkLength-4, SEEK_CUR) != 0)
    {
        lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
        goto RETURN_ERROR;
    }
    
    /* Getting idx1 chunk offset */
    while(1)
    {
        if(fread(&lChunkId, 1, 4, fp) != 4
            || fread(&(*pAVIFileHandle)->indexChunkLength, 1, 4, fp) != 4)
        {
            lResult = MJPEG_AVI_RETURN_FILEREADFAIL;
            goto RETURN_ERROR;
        }
        if(lChunkId != MJPEG_AVI_FOURCC('i','d','x','1'))
        {
        	// workaround for fseek issues
        	if(fseek_workaround(fp, (*pAVIFileHandle)->indexChunkLength, SEEK_CUR) != 0)
            {
                lResult = MJPEG_AVI_RETURN_FILESEEKFAIL;
                goto RETURN_ERROR;
            }
            continue;
        }
        (*pAVIFileHandle)->indexChunkOffset = ftell(fp) - 8;
#ifdef	MJPEGREWIND		
		
        if(((*pAVIFileHandle)->indexChunkLength/sizeof(MJPEG_AVI_INDEXENTRY)) < MAXINDEXBUFFERSIZE) {
        	FrameIndex=(MJPEG_AVI_INDEXENTRY *) malloc((*pAVIFileHandle)->indexChunkLength);
        	if(fread(FrameIndex,1,(*pAVIFileHandle)->indexChunkLength,fp) != ((*pAVIFileHandle)->indexChunkLength))       
        	{ free(FrameIndex); lResult = MJPEG_AVI_RETURN_FILEREADFAIL; goto RETURN_ERROR; }            
        	for(FrameCount=1;FrameCount < ((*pAVIFileHandle)->indexChunkLength / sizeof(MJPEG_AVI_INDEXENTRY)); FrameCount++){        		             
        		if(FrameIndex[0].dwChunkLength<FrameIndex[FrameCount].dwChunkLength) 
        		FrameIndex[0].dwChunkLength=FrameIndex[FrameCount].dwChunkLength;
        	}
        } else {
        	FrameIndex=(MJPEG_AVI_INDEXENTRY *) malloc(sizeof(MJPEG_AVI_INDEXENTRY) * 2);                	
        	if(fread(FrameIndex,1,sizeof(MJPEG_AVI_INDEXENTRY) * 2,fp) != (sizeof(MJPEG_AVI_INDEXENTRY) * 2))       
        	{ free(FrameIndex); lResult = MJPEG_AVI_RETURN_FILEREADFAIL; goto RETURN_ERROR; }                        
        	if(FrameIndex[0].dwChunkLength<FrameIndex[1].dwChunkLength) FrameIndex[0].dwChunkLength=FrameIndex[1].dwChunkLength;
        	for(FrameCount=2; FrameCount < ((*pAVIFileHandle)->indexChunkLength / sizeof(MJPEG_AVI_INDEXENTRY)); FrameCount++){
        		if(fread(&FrameIndex[1],1,sizeof(MJPEG_AVI_INDEXENTRY) ,fp) != sizeof(MJPEG_AVI_INDEXENTRY))       
        		{ free(FrameIndex); lResult = MJPEG_AVI_RETURN_FILEREADFAIL; goto RETURN_ERROR; }                
        		if(FrameIndex[0].dwChunkLength < FrameIndex[1].dwChunkLength) 
        		FrameIndex[0].dwChunkLength = FrameIndex[1].dwChunkLength;
        	}
        }
        FrameCount=0;
        FrameIndex[0].dwChunkLength += 8;// maximum stream size
        
#endif        
        break;
    }

    (*pAVIFileHandle)->openStreamCount = 0;
    return MJPEG_AVI_RETURN_OK;

RETURN_ERROR :

    if(fp != NULL)
    {
        fclose(fp);
    }
    free(*pAVIFileHandle);
    *pAVIFileHandle = NULL;
    return lResult;
}

/*
*******************************************************************************
Name         : MJPEG_AVI_CloseFileRead
Description  : Closes the AVI file.
Parameter    : AVI File Handle.
Return Value : MJPEG_AVI_RETURN_OK if file closed OK 
			   MJPEG_AVI_RETURN_ERROR otherwise.
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_CloseFileRead(uint32 AVIFileHandleParam)
{
    tMJPEG_AVI_FILEHANDLEREAD AVIFileHandle = (tMJPEG_AVI_FILEHANDLEREAD) AVIFileHandleParam;
    if(AVIFileHandle == NULL
        || AVIFileHandle->openStreamCount != 0
        || fclose(AVIFileHandle->filePtr) != 0)
    {
        return MJPEG_AVI_RETURN_ERROR;
    }

    free(AVIFileHandle);

    return MJPEG_AVI_RETURN_OK;
}

/*
*******************************************************************************
Name         : MJPEG_AVI_OpenStreamRead 
Description  : Opens a AVI Stream for read mode.
Parameter    : 
            AVIFileHandleParam    : AVI File Handle.
            pAVIStreamHandleParam : pointer to receive, opened stream handle.
            fccTypeParam          : fcc type of the stream to be opened.
            index                 : index of the stream to be opened.
Return Value	: MJPEG_AVI_RETURN_OK if stream opened OK
	`			  MJPEG_AVI_RETURN_OUTOFMEMORY 
							if memory could not be allocated when opening the stream
				  MJPEG_AVI_RETURN_FILEOPENFAIL
				  			if the input stream could not be opened
				  MJPEG_AVI_RETURN_FILEREADFAIL
				  			if the input stream could not be read
				  MJPEG_AVI_RETURN_FILEINCORRECTFORMAT
				  			if the input stream was not in MJPEG AVI format
				  MJPEG_AVI_RETURN_FILESEEKFAIL
				  			if the seek operation on the input stream failed			  
				  MJPEG_AVI_RETURN_ERROR otherwise
Limitations  : 
    1. index is supported only for value 0.
    2. fccTypeParam is supported for values "MJPEG_AVI_StreamTypeVIDEO" and 
        "MJPEG_AVI_StreamTypeAUDIO"
Assumptions  : 
    1. The strl chunk index in the avih header is same as the corresponding
        stream's stream identifier.
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_OpenStreamRead (uint32 AVIFileHandleParam,
                          uint32 *pAVIStreamHandleParam,
                          uint32 fccTypeParam,
                          int32 index)
{
    uint32 lListstrlOffset, lListstrlChunkLength, lstrhChunkLength, lStreamId;
    uint32 lChunkId, lTemp;
    MJPEG_AVI_StreamHeader lStrHeader;
    FILE *fp;

    tMJPEG_AVI_STREAMHANDLEREAD *pAVIStreamHandle 
        = (tMJPEG_AVI_STREAMHANDLEREAD *)pAVIStreamHandleParam;
    tMJPEG_AVI_FILEHANDLEREAD AVIFileHandle = (tMJPEG_AVI_FILEHANDLEREAD) AVIFileHandleParam;
    
    if(AVIFileHandle == NULL
        || index != 0
        || (fccTypeParam != MJPEG_AVI_StreamTypeVIDEO 
            && fccTypeParam != MJPEG_AVI_StreamTypeAUDIO))
    {
        return MJPEG_AVI_RETURN_ERROR;
    }

    lStreamId = 0;
    lListstrlOffset = AVIFileHandle->avihChunkOffset + sizeof(MJPEG_AVI_MainAVIHeader)
                        + 8;

    fp = AVIFileHandle->filePtr;

CHECK_NEXT_LIST_STRL :
    if(fseek(fp, lListstrlOffset, SEEK_SET) != 0)
    {
        return MJPEG_AVI_RETURN_FILESEEKFAIL;
    }
    if(fread(&lChunkId, 1, 4, fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
    if(lChunkId != MJPEG_AVI_FOURCC('L','I','S','T'))
    {
        return MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
    }
    
    if(fread(&lListstrlChunkLength, 1, 4, fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
    
    if(fread(&lChunkId, 1, 4, fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
    if(lChunkId != MJPEG_AVI_FOURCC('s','t','r','l'))
    {
        return MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
    }

    if(fread(&lChunkId, 1, 4, fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
    if(lChunkId != MJPEG_AVI_FOURCC('s','t','r','h'))
    {
        return MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
    }
    
    if(fread(&lstrhChunkLength,1,4,fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
    
    if(fread(&lStrHeader,1,sizeof(MJPEG_AVI_StreamHeader),fp) 
        != sizeof(MJPEG_AVI_StreamHeader))
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }

    if(lStrHeader.fccType != fccTypeParam)
    {
        lStreamId++;
        if(lStreamId == AVIFileHandle->avih.dwStreams)
        {
            return MJPEG_AVI_RETURN_ERROR;
        }
        lListstrlOffset += (lListstrlChunkLength+8);
        goto CHECK_NEXT_LIST_STRL;
    }

    (*pAVIStreamHandle) = (tMJPEG_AVI_STREAMHANDLEREAD) malloc(sizeof(tMJPEG_AVI_Stream_Read));
    if((*pAVIStreamHandle) == NULL)
    {
        return MJPEG_AVI_RETURN_OUTOFMEMORY;
    }
    (*pAVIStreamHandle)->AVIFileHandle = AVIFileHandle;
    (*pAVIStreamHandle)->streamId = lStreamId;
    lTemp = lStreamId + 0x3030;

    if(fccTypeParam == MJPEG_AVI_StreamTypeVIDEO)
    {
        (*pAVIStreamHandle)->streamChunkId = (lTemp << 16) + 0x6462; 
    }
    else 
    {
        /* Means this is of type MJPEG_AVI_StreamTypeAUDIO */
        (*pAVIStreamHandle)->streamChunkId = (lTemp << 16) + 0x7762;
    }
    (*pAVIStreamHandle)->streamChunkId 
        = SWAP_BYTE((*pAVIStreamHandle)->streamChunkId);

    /* Create the tMJPEG_AVI_STREAMINFO structure. */
    (*pAVIStreamHandle)->AVIStreamInfo.dwFlags = lStrHeader.dwFlags;
    (*pAVIStreamHandle)->AVIStreamInfo.dwInitialFrames 
        = lStrHeader.dwInitialFrames;
    (*pAVIStreamHandle)->AVIStreamInfo.dwLength = lStrHeader.dwLength;
    (*pAVIStreamHandle)->AVIStreamInfo.dwQuality = lStrHeader.dwQuality;
    (*pAVIStreamHandle)->AVIStreamInfo.dwRate = lStrHeader.dwRate;
    (*pAVIStreamHandle)->AVIStreamInfo.dwSampleSize = lStrHeader.dwSampleSize;
    (*pAVIStreamHandle)->AVIStreamInfo.dwScale = lStrHeader.dwScale;
    (*pAVIStreamHandle)->AVIStreamInfo.dwStart = lStrHeader.dwStart;
    (*pAVIStreamHandle)->AVIStreamInfo.dwSuggestedBufferSize 
        = lStrHeader.dwSuggestedBufferSize;
    (*pAVIStreamHandle)->AVIStreamInfo.fccHandler = lStrHeader.fccHandler;
    (*pAVIStreamHandle)->AVIStreamInfo.fccType = lStrHeader.fccType;
    (*pAVIStreamHandle)->AVIStreamInfo.rcFrame = lStrHeader.rcFrame;
    (*pAVIStreamHandle)->AVIStreamInfo.wLanguage = lStrHeader.wLanguage;
    (*pAVIStreamHandle)->AVIStreamInfo.wPriority = lStrHeader.wPriority;
    
    (*pAVIStreamHandle)->AVIStreamInfo.dwCaps = 0;
    (*pAVIStreamHandle)->AVIStreamInfo.dwEditCount = 0;
    (*pAVIStreamHandle)->AVIStreamInfo.dwFormatChangeCount = 0;
    (*pAVIStreamHandle)->AVIStreamInfo.szName[0] = '\0';

    (*pAVIStreamHandle)->indexOffset = AVIFileHandle->indexChunkOffset + 8;
    AVIFileHandle->openStreamCount++;

    return MJPEG_AVI_RETURN_OK;
}

/*
*******************************************************************************
Name         : MJPEG_AVI_CloseStreamRead
Description  : Closes the AVI stream.
Parameter    : 
            AVIStreamHandleParam: Handle of the AVI Stream Handle to be closed.
Return Value : MJPEG_AVI_RETURN_OK if stream closed OK,  
				MJPEG_AVI_RETURN_ERROR otherwise.
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_CloseStreamRead(uint32 AVIStreamHandleParam)
{
    tMJPEG_AVI_STREAMHANDLEREAD AVIStreamHandle 
        = (tMJPEG_AVI_STREAMHANDLEREAD)AVIStreamHandleParam;
    if(AVIStreamHandle == NULL)
    {
        return MJPEG_AVI_RETURN_ERROR;
    }
    AVIStreamHandle->AVIFileHandle->openStreamCount--;
    free(AVIStreamHandle);
    return MJPEG_AVI_RETURN_OK;
}

/*
*******************************************************************************
Name         : MJPEG_AVI_ReadStreamInfo
Description  : Returns the AVI Stream info of the stream.
Parameter    : 
            AVIStreamHandleParam: Handle of the open AVI Stream Handle.
            pStreamInfo         : pointer to receive the stream information.
            size                : size of the structure receiving the 
                                    stream information.
Return Value : returns MJPEG_AVI_RETURN_OK on Success, else the E_FAILURE code.
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_ReadStreamInfo(uint32 AVIStreamHandleParam,
                       tMJPEG_AVI_STREAMINFO *pStreamInfo,
                       int32 size)
{
#ifndef	MJPEGREWIND	
    tMJPEG_AVI_STREAMHANDLEREAD AVIStreamHandle 
        = (tMJPEG_AVI_STREAMHANDLEREAD)AVIStreamHandleParam;
    if(AVIStreamHandle == NULL
        || pStreamInfo == NULL
        || size != sizeof(tMJPEG_AVI_STREAMINFO))
    {
        return MJPEG_AVI_RETURN_ERROR;
    }
    *pStreamInfo = AVIStreamHandle->AVIStreamInfo;
#endif    
    return MJPEG_AVI_RETURN_OK;
}





/*
*******************************************************************************
Name         : MJPEG_AVI_ReadToNextFrame
Description  : 	Reads the AVI stream up to the start of the JPEG image
				Returns the number of bytes in the subsequent JPEG image in pBufLength.
Parameter    : 
            AVIStreamHandleParam: Handle of the open AVI Stream Handle.
            pBufLength          : pointer to the current length of the buffer.
Return Value	: MJPEG_AVI_RETURN_OK if stream opened OK
	`			  MJPEG_AVI_RETURN_OUTOFMEMORY 
							if memory could not be allocated when opening the stream
				  MJPEG_AVI_RETURN_FILEOPENFAIL
				  			if the input stream could not be opened
				  MJPEG_AVI_RETURN_FILEREADFAIL
				  			if the input stream could not be read
				  MJPEG_AVI_RETURN_FILEINCORRECTFORMAT
				  			if the input stream was not in MJPEG AVI format
				  MJPEG_AVI_RETURN_FILESEEKFAIL
				  			if the seek operation on the input stream failed
				  MJPEG_AVI_RETURN_NOMORESAMPLES 
				            if no more frames are available to read
				  MJPEG_AVI_RETURN_EVALUATIONLIMITREACHED
				  			if evaluation limit reached				  						  
				  MJPEG_AVI_RETURN_ERROR otherwise
*******************************************************************************
*/
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_ReadToNextFrame(uint32 AVIStreamHandleParam, uint32 *pBufLength)
{
#ifdef	MJPEGREWIND
#else
    FILE *fp;
    MJPEG_AVI_INDEXENTRY lIndexEntry;
    uint32 lTemp;
#ifdef ISEVALUATION
	/* Limit evaluation version to a given number of decoded frames */
	static unsigned int _Axx = 0;
	if (++_Axx > EVALUATIONMAXFRAMES)
	{
		return MJPEG_AVI_RETURN_EVALUATIONLIMITREACHED; 
	}
#endif

    tMJPEG_AVI_STREAMHANDLEREAD AVIStreamHandle 
        = (tMJPEG_AVI_STREAMHANDLEREAD)AVIStreamHandleParam;
    if(AVIStreamHandle == NULL)
    {
        return MJPEG_AVI_RETURN_STREAMINVALID;
    }

    fp = AVIStreamHandle->AVIFileHandle->filePtr;
    if(fseek(fp, AVIStreamHandle->indexOffset, SEEK_SET) != 0)
    {
        return MJPEG_AVI_RETURN_FILESEEKFAIL;
    }

	/* Revised V3.0.1 - if (offset > calculated offset) ...*/
    if(AVIStreamHandle->indexOffset >
        (AVIStreamHandle->AVIFileHandle->indexChunkOffset
            + AVIStreamHandle->AVIFileHandle->indexChunkLength + 8 
            - sizeof(MJPEG_AVI_INDEXENTRY)))
    {
        return MJPEG_AVI_RETURN_NOMORESAMPLES;
    }

    while(1)
    {
        if(fread(&lIndexEntry, 1, sizeof(MJPEG_AVI_INDEXENTRY), fp) 
            != sizeof(MJPEG_AVI_INDEXENTRY))
        {
            return MJPEG_AVI_RETURN_FILEREADFAIL;
        }

        if((lIndexEntry.ckid & 0xFEFFFFFF) != AVIStreamHandle->streamChunkId)
        {
            if(ftell(fp) 
                >= (int32) (AVIStreamHandle->AVIFileHandle->indexChunkOffset
                        + AVIStreamHandle->AVIFileHandle->indexChunkLength + 8
                        - sizeof(MJPEG_AVI_INDEXENTRY)))
            {
                return MJPEG_AVI_RETURN_NOMORESAMPLES;
            }
            continue;
        }
        
        break;
    }

    AVIStreamHandle->indexOffset = ftell(fp);

    if(fseek(fp, lIndexEntry.dwChunkOffset, SEEK_SET) != 0)
    {
        return MJPEG_AVI_RETURN_FILESEEKFAIL;
    }

    if(fread(&lTemp, 1, 4, fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }

    if((lTemp & 0xFEFFFFFF) != AVIStreamHandle->streamChunkId)
    {
        return MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
    }

    if(fread(&lTemp, 1, 4, fp) != 4)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
    if(lTemp != lIndexEntry.dwChunkLength)
    {
        return MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;
    }

    *pBufLength = lIndexEntry.dwChunkLength;
#endif    
    return MJPEG_AVI_RETURN_OK;
}

/*
******************************************************************************
Name         : MJPEG_AVI_ReadNextFrame
Description  : Reads the next image frame into the supplied buffer.  Assumes that
			   MJPEG_AVI_ReadToNextFrame has been called immediately before.
Parameter    : 
            AVIStreamHandleParam: Handle of the open AVI Stream Handle.
            pBuffer             : buffer pointer to receive the next sample.
            pBufLength          : The length of the buffer.
Return Value : returns MJPEG_AVI_RETURN_OK on Success, else the E_FAILURE code.

Return Value	: MJPEG_AVI_RETURN_OK if stream opened OK
	`			  MJPEG_AVI_RETURN_STREAMINVALID if the stream handle is invalid
				  MJPEG_AVI_RETURN_FILEREADFAIL	if the input stream could not be read
*******************************************************************************
*/
#ifdef	MJPEGREWIND
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_ReadNextFrame(uint32 AVIStreamHandleParam, void* pBuffer,
                                    uint32 * pBufLength)
{
#else
section ("MJPEGDEC_P0") // All code
int32 MJPEG_AVI_ReadNextFrame(uint32 AVIStreamHandleParam, void* pBuffer,
                                    uint32 pBufLength)
{
#endif	
    FILE *fp;
    MJPEG_AVI_INDEXENTRY lIndexEntry;

    uint32 lTemp;

    /* Valid stream? */
    tMJPEG_AVI_STREAMHANDLEREAD AVIStreamHandle 
        = (tMJPEG_AVI_STREAMHANDLEREAD)AVIStreamHandleParam;
    if(AVIStreamHandle == NULL)
    {
        return MJPEG_AVI_RETURN_STREAMINVALID;
    }
    fp = AVIStreamHandle->AVIFileHandle->filePtr;
    
	/* Enough samples? 
    if(AVIStreamHandle->indexOffset >=
        (AVIStreamHandle->AVIFileHandle->indexChunkOffset
            + AVIStreamHandle->AVIFileHandle->indexChunkLength + 8 
            - sizeof(MJPEG_AVI_INDEXENTRY)))
    {
        return MJPEG_AVI_RETURN_NOMORESAMPLES;
    }
*/
    /* Read the frame */
#ifdef	MJPEGREWIND
	char * Bufptr = (char *)pBuffer;
	*pBufLength = lTemp = frameheader[1];           	    
    if(FrameCount >= (AVIStreamHandle->AVIFileHandle->indexChunkLength / sizeof(MJPEG_AVI_INDEXENTRY)))
    return MJPEG_AVI_RETURN_NOMORESAMPLES;     		
	if((AVIStreamHandle->AVIFileHandle->indexChunkLength/sizeof(MJPEG_AVI_INDEXENTRY)) < MAXINDEXBUFFERSIZE) {
	if (fseek(fp, FrameIndex[FrameCount].dwChunkOffset, SEEK_SET) != 0) return MJPEG_AVI_RETURN_FILESEEKFAIL; }    	
    if ((frameheader[0] & 0xFEFFFFFF) != AVIStreamHandle->streamChunkId) return MJPEG_AVI_RETURN_FILEINCORRECTFORMAT;            
    FrameCount++;
    if (fread(pBuffer, 1, lTemp + 8, fp) != (lTemp + 8)) return MJPEG_AVI_RETURN_FILEREADFAIL;   
    memcpy(frameheader, &Bufptr[lTemp], 8);     
#else    
    if(fread(pBuffer, 1, pBufLength, fp) 
        != pBufLength)
    {
        return MJPEG_AVI_RETURN_FILEREADFAIL;
    }
#endif    
    return MJPEG_AVI_RETURN_OK;
}
#ifdef	MJPEGREWIND
/*
*******************************************************************************
Name         : MJPEG_AVI_RewindToFirstFrame
Description  : 	Rewind file pointer to the start of the first frame of the AVI stream,
				Returns the number of bytes in the subsequent JPEG image in pBufLength.
Parameter    : 
            AVIStreamHandleParam: Handle of the open AVI Stream Handle.
            pBufLength          : pointer to the maximum length of the frame buffer.
Return Value	: MJPEG_AVI_RETURN_OK 
							if stream opened OK			  				  
				  MJPEG_AVI_RETURN_FILEREADFAIL
				  			if the input stream could not be read				  
				  MJPEG_AVI_RETURN_FILESEEKFAIL
				  			if the seek operation on the input stream failed
				  MJPEG_AVI_RETURN_NOMORESAMPLES 
				            if no more frames are available to read				  					  
				  MJPEG_AVI_RETURN_STREAMINVALID 
				  			if stream handle is invalid
*******************************************************************************
*/
section ("MJPEGDEC_P0") 
int32 MJPEG_AVI_RewindToFirstFrame(uint32 AVIStreamHandleParam, uint32 *pBufLength) {         
    tMJPEG_AVI_STREAMHANDLEREAD AVIStreamHandle = (tMJPEG_AVI_STREAMHANDLEREAD)AVIStreamHandleParam;
    if(AVIStreamHandle == NULL) return MJPEG_AVI_RETURN_STREAMINVALID; 
    FILE *fp = AVIStreamHandle->AVIFileHandle->filePtr;
	FrameCount=0;
    if (fseek(fp, FrameIndex[0].dwChunkOffset, SEEK_SET) != 0) 
    return MJPEG_AVI_RETURN_FILESEEKFAIL;  
    *pBufLength = FrameIndex[0].dwChunkLength;    
    if (fread(frameheader, 1, 8, fp) != 8)	 return MJPEG_AVI_RETURN_FILEREADFAIL;   
    return MJPEG_AVI_RETURN_OK;
}

#endif

