/*
 *  Some utilities for writing and reading AVI files.
 *  These are not intended to serve for a full blown
 *  AVI handling software (this would be much too complex)
 *  The only intention is to write out MJPEG encoded
 *  AVIs with sound and to be able to read them back again.
 *  These utilities should work with other types of codecs too, however.
 *
 *  Copyright (C) 1999 Rainer Johanni <Rainer@Johanni.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *  Copyright (C) 2003 Vladimir A. Smirnov <kkatarn@rambler.ru>
 *   13.01.2003
 *   - UN*X I/O replaced by LibV I/O;
 *   - removed ftruncate() (fileOpenWrite() truncates it anyway);
 *   - malloc()/free() replaced by memAlloc() / memFree();
 *   - fprintf(stderr,...) replaced by conlPrintf(LOG_ERROR,...);
 *   - memset(ptr,0,size) replaced by memZero(ptr,size);
 *   - references to 'errno' removed (LibV complains about I/O errors);
 *   - signed/unsigned cleanups;
 *   - memcpy(dst,src,4) replaced by *((u32_t*)(dst)) = *((u32_t*)(src)).
 *	09.06.2003
 *   - error flag moved inside context, code is completely thread-safe now;
 *   - numerous signed/unsigned and conversion cleanups to prevent MSVC warnings.
 *  15.06.2003
 *   - fixes in AVI_read_data (non-zero 'len' upon successful return only)
 */

#include <v_lib.h>
#include "avilib.h"

#define CPLONG(destptr32,srcptr32) \
   *((u32_t*)(destptr32)) = *((u32_t*)(srcptr32));

#define avi_ustrncasecmp(str1,str2,n) \
   strncasecmp((const char*)(str1),(const char*)(str2),(n))

#define AVI_set_errno(AVI,val) (AVI)->err_no = (val)
#define AVI_get_errno(AVI) (AVI)->err_no

/*******************************************************************
 *                                                                 *
 *    Utilities for writing an AVI File                            *
 *                                                                 *
 *******************************************************************/

/* AVI_MAX_LEN: The maximum length of an AVI file, we stay a bit below
    the 2GB limit (Remember: 2*10^9 is smaller than 2 GB) */

#define AVI_MAX_LEN 2000000000

/* HEADERBYTES: The number of bytes to reserve for the header */

#define HEADERBYTES 2048

#define PAD_EVEN(x) ( ((x)+1) & ~1 )

/* Copy n into dst as a 4 byte, little endian number.
   Should also work on big endian machines */

static void avi_long2str(unsigned char *dst, int n)
{
   dst[0] = (unsigned char)((n    )&0xff);
   dst[1] = (unsigned char)((n>> 8)&0xff);
   dst[2] = (unsigned char)((n>>16)&0xff);
   dst[3] = (unsigned char)((n>>24)&0xff);
}

/* Convert a string of 4 or 2 bytes to a number,
   also working on big endian machines */

static unsigned long avi_str2ulong(unsigned char *str)
{
   return ( str[0] | (str[1]<<8) | (str[2]<<16) | (str[3]<<24) );
}

static unsigned long avi_str2ushort(unsigned char *str)
{
   return ( str[0] | (str[1]<<8) );
}

/* Calculate audio sample size from number of bits and number of channels.
   This may have to be adjusted for eg. 12 bits and stereo */

static int avi_sampsize(avi_t *AVI)
{
   int s;
   s = ((AVI->a_bits+7)/8)*AVI->a_chans;
   if(s==0) s=1; /* avoid possible zero divisions */
   return s;
}

/* Add a chunk (=tag and data) to the AVI file,
   returns -1 on write error, 0 on success */

static int avi_add_chunk(avi_t *AVI,char *tag,unsigned char *data, int length)
{
   unsigned char c[8];

   /* Copy tag and length int c, so that we need only 1 write system call
      for these two values */

   CPLONG(c,tag);

   avi_long2str(c+4,length);

   /* Output tag, length and data, restore previous position
      if the write fails */

   length = PAD_EVEN(length);

   if( fileWrite(AVI->fdes,c,8) != 8 ||
       (int)fileWrite(AVI->fdes,data,length) != length )
   {
      fileSeek(AVI->fdes,AVI->pos,SEEK_SET);
      AVI_set_errno(AVI,AVI_ERR_WRITE);
      return -1;
   }

   /* Update file position */

   AVI->pos += 8 + length;

   return 0;
}

static int avi_add_index_entry(avi_t *AVI,char *tag, long flags, long pos, long len)
{
   void *ptr;

   if(AVI->n_idx>=AVI->max_idx)
   {
      ptr = memRealloc((void *)AVI->idx,(AVI->max_idx+4096)*16);
      if(ptr == 0)
      {
         AVI_set_errno(AVI,AVI_ERR_NO_MEM);
         return -1;
      }
      AVI->max_idx += 4096;
      AVI->idx = (unsigned char((*)[16]) ) ptr;
   }

   /* Add index entry */
   /* VS: DEBUGME */
   /* memcpy(AVI->idx[AVI->n_idx],tag,4); */

   *((u32_t*)(AVI->idx[AVI->n_idx])) = *((u32_t*)tag);
   
   avi_long2str(AVI->idx[AVI->n_idx]+ 4,flags);
   avi_long2str(AVI->idx[AVI->n_idx]+ 8,pos);
   avi_long2str(AVI->idx[AVI->n_idx]+12,len);

   /* Update counter */

   AVI->n_idx++;

   return 0;
}

/*
   AVI_open_output_file: Open an AVI File and write a bunch
                         of zero bytes as space for the header.

   returns a pointer to avi_t on success, a zero pointer on error
*/

avi_t* AVI_open_output_file(char * filename)
{
   avi_t *AVI;
   int i;
   unsigned char AVI_header[HEADERBYTES];

   /* Allocate the avi_t struct and zero it */

   AVI = (avi_t *) memAlloc(sizeof(avi_t));
   if(AVI == NULL)
   {
      return NULL;
   }
   memZero((void *)AVI,sizeof(avi_t));

   AVI->fdes = fileOpenWrite(filename);
   if (AVI->fdes == LIBV_INVALID_HANDLE)
   {
      memFree(AVI);
      return NULL;
   }

   /* Write out HEADERBYTES bytes, the header will go here
      when we are finished with writing */

   for (i=0;i<HEADERBYTES;i++) AVI_header[i] = 0;
   i = fileWrite(AVI->fdes,AVI_header,HEADERBYTES);
   if (i != HEADERBYTES)
   {
      fileClose(AVI->fdes);
      memFree(AVI);
      return NULL;
   }

   AVI->pos  = HEADERBYTES;
   AVI->mode = AVI_MODE_WRITE; /* open for writing */

   return AVI;
}

void AVI_set_video(avi_t *AVI, int width, int height, double fps, char *compressor)
{
   /* may only be called if file is open for writing */

   if(AVI->mode==AVI_MODE_READ) return;

   AVI->width  = width;
   AVI->height = height;
   AVI->fps    = fps;
   CPLONG(AVI->compressor,compressor);
   AVI->compressor[4] = 0;
}

void AVI_set_audio(avi_t *AVI, int channels, long rate, int bits, int format)
{
   /* may only be called if file is open for writing */

   if(AVI->mode==AVI_MODE_READ) return;

   AVI->a_chans = channels;
   AVI->a_rate  = rate;
   AVI->a_bits  = bits;
   AVI->a_fmt   = format;

}

#define OUT4CC(s) \
   if(nhb<=HEADERBYTES-4) CPLONG(AVI_header+nhb,s); nhb += 4

#define OUTLONG(n) \
   if(nhb<=HEADERBYTES-4) avi_long2str(AVI_header+nhb,n); nhb += 4

#define OUTSHRT(n) \
   if(nhb<=HEADERBYTES-2) { \
      AVI_header[nhb  ] = (unsigned char)((n)&0xff); \
      AVI_header[nhb+1] = (unsigned char)(((n)>>8)&0xff); \
   } \
   nhb += 2

/*
  Write the header of an AVI file and close it.
  returns 0 on success, -1 on write error.
*/

static int avi_close_output_file(avi_t *AVI)
{

   int ret, njunk, sampsize, hasIndex, ms_per_frame, idxerror, flag;
   int movi_len, hdrl_start, strl_start;
   unsigned char AVI_header[HEADERBYTES];
   long nhb;

   /* Calculate length of movi list */

   movi_len = AVI->pos - HEADERBYTES + 4;

   /* Try to ouput the index entries. This may fail e.g. if no space
      is left on device. We will report this as an error, but we still
      try to write the header correctly (so that the file still may be
      readable in the most cases */

   idxerror = 0;
   ret = avi_add_chunk(AVI,"idx1",(void*)AVI->idx,AVI->n_idx*16);
   hasIndex = (ret==0);
   if(ret)
   {
      idxerror = 1;
      AVI_set_errno(AVI,AVI_ERR_WRITE_INDEX);
   }

   /* Calculate Microseconds per frame */

   if(AVI->fps < 0.001)
      ms_per_frame = 0;
   else
      ms_per_frame = (int)(1000000.0/AVI->fps + 0.5);

   /* Prepare the file header */

   nhb = 0;

   /* The RIFF header */

   OUT4CC ("RIFF");
   OUTLONG(AVI->pos - 8);    /* # of bytes to follow */
   OUT4CC ("AVI ");

   /* Start the header list */

   OUT4CC ("LIST");
   OUTLONG(0);        /* Length of list in bytes, don't know yet */
   hdrl_start = nhb;  /* Store start position */
   OUT4CC ("hdrl");

   /* The main AVI header */

   /* The Flags in AVI File header */

#define AVIF_HASINDEX           0x00000010      /* Index at end of file */
#define AVIF_MUSTUSEINDEX       0x00000020
#define AVIF_ISINTERLEAVED      0x00000100
#define AVIF_TRUSTCKTYPE        0x00000800      /* Use CKType to find key frames */
#define AVIF_WASCAPTUREFILE     0x00010000
#define AVIF_COPYRIGHTED        0x00020000

   OUT4CC ("avih");
   OUTLONG(56);                 /* # of bytes to follow */
   OUTLONG(ms_per_frame);       /* Microseconds per frame */
   OUTLONG(10000000);           /* MaxBytesPerSec, I hope this will never be used */
   OUTLONG(0);                  /* PaddingGranularity (whatever that might be) */
                                /* Other sources call it 'reserved' */
   flag = AVIF_WASCAPTUREFILE;
   if(hasIndex) flag |= AVIF_HASINDEX;
   if(hasIndex && AVI->must_use_index) flag |= AVIF_MUSTUSEINDEX;
   OUTLONG(flag);               /* Flags */
   OUTLONG(AVI->video_frames);  /* TotalFrames */
   OUTLONG(0);                  /* InitialFrames */
   if (AVI->audio_bytes)
      { OUTLONG(2); }           /* Streams */
   else
      { OUTLONG(1); }           /* Streams */
   OUTLONG(0);                  /* SuggestedBufferSize */
   OUTLONG(AVI->width);         /* Width */
   OUTLONG(AVI->height);        /* Height */
                                /* MS calls the following 'reserved': */
   OUTLONG(0);                  /* TimeScale:  Unit used to measure time */
   OUTLONG(0);                  /* DataRate:   Data rate of playback     */
   OUTLONG(0);                  /* StartTime:  Starting time of AVI data */
   OUTLONG(0);                  /* DataLength: Size of AVI data chunk    */


   /* Start the video stream list ---------------------------------- */

   OUT4CC ("LIST");
   OUTLONG(0);        /* Length of list in bytes, don't know yet */
   strl_start = nhb;  /* Store start position */
   OUT4CC ("strl");

   /* The video stream header */

   OUT4CC ("strh");
   OUTLONG(64);                 /* # of bytes to follow */
   OUT4CC ("vids");             /* Type */
   OUT4CC (AVI->compressor);    /* Handler */
   OUTLONG(0);                  /* Flags */
   OUTLONG(0);                  /* Reserved, MS says: wPriority, wLanguage */
   OUTLONG(0);                  /* InitialFrames */
   OUTLONG(ms_per_frame);       /* Scale */
   OUTLONG(1000000);            /* Rate: Rate/Scale == samples/second */
   OUTLONG(0);                  /* Start */
   OUTLONG(AVI->video_frames);  /* Length */
   OUTLONG(0);                  /* SuggestedBufferSize */
   OUTLONG(-1);                 /* Quality */
   OUTLONG(0);                  /* SampleSize */
   OUTLONG(0);                  /* Frame */
   OUTLONG(0);                  /* Frame */
   OUTLONG(0);                  /* Frame */
   OUTLONG(0);                  /* Frame */

   /* The video stream format (uncompressed 24 bit RGB) */

   OUT4CC ("strf");
   OUTLONG(40);                 /* # of bytes to follow */
   OUTLONG(40);                 /* Size */
   OUTLONG(AVI->width);         /* Width */
   OUTLONG(AVI->height);        /* Height */
   OUTSHRT(1); OUTSHRT(24);     /* Planes, Count */
   OUT4CC (AVI->compressor);    /* Compression */
   OUTLONG(AVI->width*AVI->height);  /* SizeImage (in bytes?) */
   OUTLONG(0);                  /* XPelsPerMeter */
   OUTLONG(0);                  /* YPelsPerMeter */
   OUTLONG(0);                  /* ClrUsed: Number of colors used */
   OUTLONG(0);                  /* ClrImportant: Number of colors important */

   /* Finish stream list, i.e. put number of bytes in the list to proper pos */

   avi_long2str(AVI_header+strl_start-4,nhb-strl_start);

   if (AVI->a_chans && AVI->audio_bytes)
   {

   sampsize = avi_sampsize(AVI);

   /* Start the audio stream list ---------------------------------- */

   OUT4CC ("LIST");
   OUTLONG(0);        /* Length of list in bytes, don't know yet */
   strl_start = nhb;  /* Store start position */
   OUT4CC ("strl");

   /* The audio stream header */

   OUT4CC ("strh");
   OUTLONG(64);            /* # of bytes to follow */
   OUT4CC ("auds");
   OUT4CC ("\0\0\0\0");
   OUTLONG(0);             /* Flags */
   OUTLONG(0);             /* Reserved, MS says: wPriority, wLanguage */
   OUTLONG(0);             /* InitialFrames */
   OUTLONG(sampsize);      /* Scale */
   OUTLONG(sampsize*AVI->a_rate); /* Rate: Rate/Scale == samples/second */
   OUTLONG(0);             /* Start */
   OUTLONG(AVI->audio_bytes/sampsize);   /* Length */
   OUTLONG(0);             /* SuggestedBufferSize */
   OUTLONG(-1);            /* Quality */
   OUTLONG(sampsize);      /* SampleSize */
   OUTLONG(0);             /* Frame */
   OUTLONG(0);             /* Frame */
   OUTLONG(0);             /* Frame */
   OUTLONG(0);             /* Frame */

   /* The audio stream format */

   OUT4CC ("strf");
   OUTLONG(16);                   /* # of bytes to follow */
   OUTSHRT(AVI->a_fmt);           /* Format */
   OUTSHRT(AVI->a_chans);         /* Number of channels */
   OUTLONG(AVI->a_rate);          /* SamplesPerSec */
   OUTLONG(sampsize*AVI->a_rate); /* AvgBytesPerSec */
   OUTSHRT(sampsize);             /* BlockAlign */
   OUTSHRT(AVI->a_bits);          /* BitsPerSample */

   /* Finish stream list, i.e. put number of bytes in the list to proper pos */

   avi_long2str(AVI_header+strl_start-4,nhb-strl_start);

   }

   /* Finish header list */

   avi_long2str(AVI_header+hdrl_start-4,nhb-hdrl_start);

   /* Calculate the needed amount of junk bytes, output junk */

   njunk = HEADERBYTES - nhb - 8 - 12;

   /* Safety first: if njunk <= 0, somebody has played with
      HEADERBYTES without knowing what (s)he did.
      This is a fatal error */

   if(njunk<=0)
   {
      fprintf(stderr,"AVI_close_output_file: # of header bytes too small\n");
      exit(1);
   }

   OUT4CC ("JUNK");
   OUTLONG(njunk);
   memZero(AVI_header+nhb,njunk);
   nhb += njunk;

   /* Start the movi list */

   OUT4CC ("LIST");
   OUTLONG(movi_len); /* Length of list in bytes */
   OUT4CC ("movi");

   /* Output the header */
   fileSeek(AVI->fdes,0,SEEK_SET);
   fileWrite(AVI->fdes,AVI_header,HEADERBYTES);

   if(idxerror) return -1;

   return 0;
}
/*
   AVI_write_data:
   Add video or audio data to the file;

   Return values:
    0    No error;
   -1    Error, AVI_errno is set appropriatly;

*/

static int
avi_write_data(avi_t *AVI,unsigned char *data, long length, int audio)
{
   int n;

   /* Check for maximum file length */

   if ( (AVI->pos + 8 + length + 8 + (AVI->n_idx+1)*16) > AVI_MAX_LEN )
   {
      AVI_set_errno(AVI,AVI_ERR_SIZELIM);
      return -1;
   }

   /* Add index entry */

   if(audio)
      n = avi_add_index_entry(AVI,"01wb",0x00,AVI->pos,length);
   else
      n = avi_add_index_entry(AVI,"00db",0x10,AVI->pos,length);

   if(n) return -1;

   /* Output tag and data */

   if(audio)
      n = avi_add_chunk(AVI,"01wb",data,length);
   else
      n = avi_add_chunk(AVI,"00db",data,length);

   if (n) return -1;

   return 0;
}

int AVI_write_frame(avi_t *AVI,unsigned char *data, long bytes)
{
   long pos;

   if(AVI->mode==AVI_MODE_READ)
   {
      AVI_set_errno(AVI,AVI_ERR_NOT_PERM);
      return -1;
   }
   pos = AVI->pos;
   if( avi_write_data(AVI,data,bytes,0) ) return -1;
   AVI->last_pos = pos;
   AVI->last_len = bytes;
   AVI->video_frames++;
   return 0;
}

int AVI_dup_frame(avi_t *AVI)
{
   if(AVI->mode==AVI_MODE_READ)
   {
      AVI_set_errno(AVI,AVI_ERR_NOT_PERM);
      return -1;
   }
   if(AVI->last_pos==0) return 0; /* No previous real frame */
   if(avi_add_index_entry(AVI,"00db",0x10,AVI->last_pos,AVI->last_len))
      return -1;
   AVI->video_frames++;
   AVI->must_use_index = 1;
   return 0;
}

int AVI_write_audio(avi_t *AVI,unsigned char *data, long bytes)
{
   if(AVI->mode==AVI_MODE_READ)
   {
      AVI_set_errno(AVI,AVI_ERR_NOT_PERM);
      return -1;
   }

   if( avi_write_data(AVI,data,bytes,1) ) return -1;
   AVI->audio_bytes += bytes;
   return 0;
}

long AVI_bytes_remain(avi_t *AVI)
{
   if(AVI->mode==AVI_MODE_READ) return 0;

   return ( AVI_MAX_LEN - (AVI->pos + 8 + 16*AVI->n_idx));
}

/*******************************************************************
 *                                                                 *
 *    Utilities for reading video and audio from an AVI File       *
 *                                                                 *
 *******************************************************************/

int AVI_close(avi_t *AVI)
{
   int ret;

   /* If the file was open for writing, the header and index still have
      to be written */

   if(AVI->mode == AVI_MODE_WRITE)
      ret = avi_close_output_file(AVI);
   else
      ret = 0;

   /* Even if there happened a error, we first clean up */

   fileClose(AVI->fdes);
   if(AVI->idx) memFree(AVI->idx);
   if(AVI->video_index) memFree(AVI->video_index);
   if(AVI->audio_index) memFree(AVI->audio_index);
   memFree(AVI);

   return ret;
}

#define ERR_EXIT(x) \
   { \
      AVI_close(AVI); \
      AVI_set_errno(AVI,x); \
      return 0; \
   }

avi_t *AVI_open_input_file(char *filename, int getIndex)
{
   avi_t *AVI;
   long i, n, rate, scale, idx_type;
   unsigned char *hdrl_data;
   long hdrl_len = 0;
   long nvi, nai, ioff;
   long tot;
   int lasttag = 0;
   int vids_strh_seen = 0;
   int vids_strf_seen = 0;
   int auds_strh_seen = 0;
   int auds_strf_seen = 0;
   int num_stream = 0;
   unsigned char data[256];

   /* Create avi_t structure */

   AVI = (avi_t *) memAlloc(sizeof(avi_t));

   if(AVI==NULL)
   {
      return NULL;
   }
   memZero((void *)AVI,sizeof(avi_t));

   AVI->mode = AVI_MODE_READ; /* open for reading */

   /* Open the file */

   AVI->fdes = fileOpenRead(filename);
   if(AVI->fdes == LIBV_INVALID_HANDLE)
   {
      memFree(AVI);
      return NULL;
   }
   /* Read first 12 bytes and check that this is an AVI file */

   if( fileRead(AVI->fdes,data,12) != 12 ) ERR_EXIT(AVI_ERR_READ)

   if( avi_ustrncasecmp(data  ,"RIFF",4) !=0 ||
       avi_ustrncasecmp(data+8,"AVI ",4) !=0 ) ERR_EXIT(AVI_ERR_NO_AVI)
   
   /* Go through the AVI file and extract the header list,
      the start position of the 'movi' list and an optionally
      present idx1 tag */

   hdrl_data = 0;

   for(;;)
   {
      if( fileRead(AVI->fdes,data,8) != 8 ) break; /* We assume it's EOF */

      n = avi_str2ulong(data+4);
      n = PAD_EVEN(n);

      if(avi_ustrncasecmp(data,"LIST",4) == 0)
      {
         if( fileRead(AVI->fdes,data,4) != 4 ) ERR_EXIT(AVI_ERR_READ)
         n -= 4;
         if(avi_ustrncasecmp(data,"hdrl",4) == 0)
         {
            hdrl_len = n;
            hdrl_data = (unsigned char *) memAlloc(n);
            if(hdrl_data==0) ERR_EXIT(AVI_ERR_NO_MEM)
            if( (int)fileRead(AVI->fdes,hdrl_data,n) != n ) ERR_EXIT(AVI_ERR_READ)
         }
         else if(avi_ustrncasecmp(data,"movi",4) == 0)
         {
            AVI->movi_start = fileSeek(AVI->fdes,0,SEEK_CUR);
            fileSeek(AVI->fdes,n,SEEK_CUR);
         }
         else
            fileSeek(AVI->fdes,n,SEEK_CUR);
      }
      else if(avi_ustrncasecmp(data,"idx1",4) == 0)
      {
         /* n must be a multiple of 16, but the reading does not
            break if this is not the case */

         AVI->n_idx = AVI->max_idx = n/16;
         AVI->idx = (unsigned  char((*)[16]) ) memAlloc(n);
         if(AVI->idx==0) ERR_EXIT(AVI_ERR_NO_MEM)
         if((int)fileRead(AVI->fdes,AVI->idx,n) != n ) ERR_EXIT(AVI_ERR_READ)
      }
      else
         fileSeek(AVI->fdes,n,SEEK_CUR);
   }

   if(!hdrl_data      ) ERR_EXIT(AVI_ERR_NO_HDRL)
   if(!AVI->movi_start) ERR_EXIT(AVI_ERR_NO_MOVI)

   /* Interpret the header list */

   for(i=0;i<hdrl_len;)
   {
      /* List tags are completly ignored */

      if(avi_ustrncasecmp(hdrl_data+i,"LIST",4)==0) { i+= 12; continue; }

      n = avi_str2ulong(hdrl_data+i+4);
      n = PAD_EVEN(n);

      /* Interpret the tag and its args */

      if(avi_ustrncasecmp(hdrl_data+i,"strh",4)==0)
      {
         i += 8;
		 /* FIXME: implement multiple video stream handling */
         if(avi_ustrncasecmp(hdrl_data+i,"vids",4) == 0 && !vids_strh_seen)
         {
            CPLONG(AVI->compressor,hdrl_data+i+4);
            AVI->compressor[4] = 0;
            scale = avi_str2ulong(hdrl_data+i+20);
            rate  = avi_str2ulong(hdrl_data+i+24);
            if(scale!=0) AVI->fps = (double)rate/(double)scale;
            AVI->video_frames = avi_str2ulong(hdrl_data+i+32);
            AVI->video_strn = num_stream;
            vids_strh_seen = 1;
            lasttag = 1; /* vids */
         }
		 /* FIXME: implement multiple audio stream handling */
         else if (avi_ustrncasecmp (hdrl_data+i,"auds",4) ==0 && ! auds_strh_seen)
         {
            AVI->audio_bytes = avi_str2ulong(hdrl_data+i+32)*avi_sampsize(AVI);
            AVI->audio_strn = num_stream;
            auds_strh_seen = 1;
            lasttag = 2; /* auds */
         }
         else
            lasttag = 0;
         num_stream++;
      }
      else if(avi_ustrncasecmp(hdrl_data+i,"strf",4)==0)
      {
         i += 8;
         if(lasttag == 1)
         {
            AVI->width  = avi_str2ulong(hdrl_data+i+4);
            AVI->height = avi_str2ulong(hdrl_data+i+8);
            vids_strf_seen = 1;
         }
         else if(lasttag == 2)
         {
            AVI->a_fmt   = avi_str2ushort(hdrl_data+i  );
            AVI->a_chans = avi_str2ushort(hdrl_data+i+2);
            AVI->a_rate  = avi_str2ulong (hdrl_data+i+4);
            AVI->a_bits  = avi_str2ushort(hdrl_data+i+14);
            auds_strf_seen = 1;
         }
         lasttag = 0;
      }
      else
      {
         i += 8;
         lasttag = 0;
      }

      i += n;
   }

   memFree(hdrl_data);

   if(!vids_strh_seen || !vids_strf_seen || AVI->video_frames==0) ERR_EXIT(AVI_ERR_NO_VIDS)

   AVI->video_tag[0] = (unsigned char)(AVI->video_strn / 10 + '0');
   AVI->video_tag[1] = (unsigned char)(AVI->video_strn % 10 + '0');
   AVI->video_tag[2] = 'd';
   AVI->video_tag[3] = 'b';

   /* Audio tag is set to "99wb" if no audio present */
   if(!AVI->a_chans) AVI->audio_strn = 99;

   AVI->audio_tag[0] = (unsigned char)(AVI->audio_strn / 10 + '0');
   AVI->audio_tag[1] = (unsigned char)(AVI->audio_strn % 10 + '0');
   AVI->audio_tag[2] = 'w';
   AVI->audio_tag[3] = 'b';

   fileSeek(AVI->fdes,AVI->movi_start,SEEK_SET);

   /* get index if wanted */

   if(!getIndex) return AVI;

   /* if the file has an idx1, check if this is relative
      to the start of the file or to the start of the movi list */

   idx_type = 0;

   if(AVI->idx)
   {
      long pos;
	  unsigned long len;

      /* Search the first videoframe in the idx1 and look where
         it is in the file */

      for(i=0;i<AVI->n_idx;i++)
         if( avi_ustrncasecmp(AVI->idx[i],AVI->video_tag,3)==0 ) break;
      if(i>=AVI->n_idx) ERR_EXIT(AVI_ERR_NO_VIDS)

      pos = avi_str2ulong(AVI->idx[i]+ 8);
      len = avi_str2ulong(AVI->idx[i]+12);

      fileSeek(AVI->fdes,pos,SEEK_SET);
      if(fileRead(AVI->fdes,data,8)!=8) ERR_EXIT(AVI_ERR_READ)
      if( avi_ustrncasecmp(data,AVI->idx[i],4)==0 && avi_str2ulong(data+4)==len )
      {
         idx_type = 1; /* Index from start of file */
      }
      else
      {
         fileSeek(AVI->fdes,pos+AVI->movi_start-4,SEEK_SET);
         if(fileRead(AVI->fdes,data,8)!=8) ERR_EXIT(AVI_ERR_READ)
         if( avi_ustrncasecmp(data,AVI->idx[i],4)==0 && avi_str2ulong(data+4)==len )
         {
            idx_type = 2; /* Index from start of movi list */
         }
      }
      /* idx_type remains 0 if neither of the two tests above succeeds */
   }

   if(idx_type == 0)
   {
      /* we must search through the file to get the index */

      fileSeek(AVI->fdes, AVI->movi_start, SEEK_SET);

      AVI->n_idx = 0;

      for(;;)
      {
         if( fileRead(AVI->fdes,data,8) != 8 ) break;
         n = avi_str2ulong(data+4);

         /* The movi list may contain sub-lists, ignore them */

         if(avi_ustrncasecmp(data,"LIST",4)==0)
         {
            fileSeek(AVI->fdes,4,SEEK_CUR);
            continue;
         }

         /* Check if we got a tag ##db, ##dc or ##wb */

         if( ( (data[2]=='d' || data[2]=='D') &&
               (data[3]=='b' || data[3]=='B' || data[3]=='c' || data[3]=='C') )
          || ( (data[2]=='w' || data[2]=='W') &&
               (data[3]=='b' || data[3]=='B') ) )
         {
            avi_add_index_entry(AVI,(char*)data,0,(long)fileTell(AVI->fdes)-8,n);
         }

         fileSeek(AVI->fdes,PAD_EVEN(n),SEEK_CUR);
      }
      idx_type = 1;
   }

   /* Now generate the video index and audio index arrays */

   nvi = 0;
   nai = 0;

   for(i=0;i<AVI->n_idx;i++)
   {
      if(avi_ustrncasecmp(AVI->idx[i],AVI->video_tag,3) == 0) nvi++;
      if(avi_ustrncasecmp(AVI->idx[i],AVI->audio_tag,4) == 0) nai++;
   }

   AVI->video_frames = nvi;
   AVI->audio_chunks = nai;

   if(AVI->video_frames==0) ERR_EXIT(AVI_ERR_NO_VIDS)
   AVI->video_index = (video_index_entry *) memAlloc(nvi*sizeof(video_index_entry));
   if(AVI->video_index==0) ERR_EXIT(AVI_ERR_NO_MEM)
   if(AVI->audio_chunks)
   {
      AVI->audio_index = (audio_index_entry *) memAlloc(nai*sizeof(audio_index_entry));
      if(AVI->audio_index==0) ERR_EXIT(AVI_ERR_NO_MEM)
   }

   nvi = 0;
   nai = 0;
   tot = 0;
   ioff = idx_type == 1 ? 8 : AVI->movi_start+4;

   for(i=0;i<AVI->n_idx;i++)
   {
      if(avi_ustrncasecmp(AVI->idx[i],AVI->video_tag,3) == 0)
      {
         AVI->video_index[nvi].pos = avi_str2ulong(AVI->idx[i]+ 8)+ioff;
         AVI->video_index[nvi].len = avi_str2ulong(AVI->idx[i]+12);
         nvi++;
      }
      if(avi_ustrncasecmp(AVI->idx[i],AVI->audio_tag,4) == 0)
      {
         AVI->audio_index[nai].pos = avi_str2ulong(AVI->idx[i]+ 8)+ioff;
         AVI->audio_index[nai].len = avi_str2ulong(AVI->idx[i]+12);
         AVI->audio_index[nai].tot = tot;
         tot += AVI->audio_index[nai].len;
         nai++;
      }
   }

   AVI->audio_bytes = tot;

   /* Reposition the file */

   fileSeek(AVI->fdes,AVI->movi_start,SEEK_SET);
   AVI->video_pos = 0;

   return AVI;
}

long AVI_video_frames(avi_t *AVI)
{
   return AVI->video_frames;
}
int  AVI_video_width(avi_t *AVI)
{
   return AVI->width;
}
int  AVI_video_height(avi_t *AVI)
{
   return AVI->height;
}
double AVI_video_frame_rate(avi_t *AVI)
{
   return AVI->fps;
}
char* AVI_video_compressor(avi_t *AVI)
{
   return AVI->compressor;
}

int AVI_audio_channels(avi_t *AVI)
{
   return AVI->a_chans;
}
int AVI_audio_bits(avi_t *AVI)
{
   return AVI->a_bits;
}
int AVI_audio_format(avi_t *AVI)
{
   return AVI->a_fmt;
}
long AVI_audio_rate(avi_t *AVI)
{
   return AVI->a_rate;
}
long AVI_audio_bytes(avi_t *AVI)
{
   return AVI->audio_bytes;
}

long AVI_frame_size(avi_t *AVI, long frame)
{
   if(AVI->mode==AVI_MODE_WRITE) { AVI_set_errno(AVI,AVI_ERR_NOT_PERM); return -1; }
   if(!AVI->video_index)         { AVI_set_errno(AVI,AVI_ERR_NO_IDX);   return -1; }

   if(frame < 0 || frame >= AVI->video_frames) return 0;
   return(AVI->video_index[frame].len);
}

int AVI_seek_start(avi_t *AVI)
{
   if(AVI->mode==AVI_MODE_WRITE) { AVI_set_errno(AVI,AVI_ERR_NOT_PERM); return -1; }

   fileSeek(AVI->fdes,AVI->movi_start,SEEK_SET);
   AVI->video_pos = 0;
   AVI->audio_posc = 0;
   AVI->audio_posb = 0;
   return 0;
}

int AVI_set_video_position(avi_t *AVI, long frame, long *frame_len)
{
   if(AVI->mode==AVI_MODE_WRITE) { AVI_set_errno(AVI,AVI_ERR_NOT_PERM); return -1; }
   if(!AVI->video_index)         { AVI_set_errno(AVI,AVI_ERR_NO_IDX);   return -1; }

   if (frame < 0 ) frame = 0;
   AVI->video_pos = frame;
   if (frame_len != NULL)
     *frame_len = AVI->video_index[frame].len;
   return 0;
}
      

long AVI_read_frame(avi_t *AVI,unsigned char *vidbuf)
{
   long n;

   if(AVI->mode==AVI_MODE_WRITE) { AVI_set_errno(AVI,AVI_ERR_NOT_PERM); return -1; }
   if(!AVI->video_index)         { AVI_set_errno(AVI,AVI_ERR_NO_IDX);   return -1; }

   if(AVI->video_pos < 0 || AVI->video_pos >= AVI->video_frames) return 0;
   n = AVI->video_index[AVI->video_pos].len;

   fileSeek(AVI->fdes, AVI->video_index[AVI->video_pos].pos, SEEK_SET);
   if ((int)fileRead(AVI->fdes,vidbuf,n) != n)
   {
      AVI_set_errno(AVI,AVI_ERR_READ);
      return -1;
   }

   AVI->video_pos++;

   return n;
}

int AVI_set_audio_position(avi_t *AVI, long byte)
{
   long n0, n1, n;

   if(AVI->mode==AVI_MODE_WRITE) { AVI_set_errno(AVI,AVI_ERR_NOT_PERM); return -1; }
   if(!AVI->audio_index)         { AVI_set_errno(AVI,AVI_ERR_NO_IDX);   return -1; }

   if(byte < 0) byte = 0;

   /* Binary search in the audio chunks */

   n0 = 0;
   n1 = AVI->audio_chunks;

   while(n0<n1-1)
   {
      n = (n0+n1)/2;
      if(AVI->audio_index[n].tot>byte)
         n1 = n;
      else
         n0 = n;
   }

   AVI->audio_posc = n0;
   AVI->audio_posb = byte - AVI->audio_index[n0].tot;

   return 0;
}

int AVI_set_audio_frame (avi_t *AVI, long frame, long *frame_len)
{
  if (AVI->audio_posc >= AVI->audio_chunks - 1) { return -1; }
  AVI->audio_posc = frame;
  AVI->audio_posb = 0;
  if (frame_len != NULL)
    *frame_len = AVI->audio_index[frame].len;
  return 0;
}

long AVI_read_audio(avi_t *AVI,unsigned char *audbuf, long bytes)
{
   long nr, pos, left, todo;

   if(AVI->mode==AVI_MODE_WRITE) { AVI_set_errno(AVI,AVI_ERR_NOT_PERM); return -1; }
   if(!AVI->audio_index)         { AVI_set_errno(AVI,AVI_ERR_NO_IDX);   return -1; }

   nr = 0; /* total number of bytes read */

   while(bytes>0)
   {
      left = AVI->audio_index[AVI->audio_posc].len - AVI->audio_posb;
      if(left==0)
      {
         if(AVI->audio_posc>=AVI->audio_chunks-1) return nr;
         AVI->audio_posc++;
         AVI->audio_posb = 0;
         continue;
      }
      if(bytes<left)
         todo = bytes;
      else
         todo = left;
      pos = AVI->audio_index[AVI->audio_posc].pos + AVI->audio_posb;
      fileSeek(AVI->fdes, pos, SEEK_SET);
      if ((int)fileRead(AVI->fdes,audbuf+nr,todo) != todo)
      {
         AVI_set_errno(AVI,AVI_ERR_READ);
         return -1;
      }
      bytes -= todo;
      nr    += todo;
      AVI->audio_posb += todo;
   }

   return nr;
}

/* AVI_read_data: Special routine for reading the next audio or video chunk
                  without having an index of the file. */

/*
 * TODO: split into 2 routines:
 * AVI_read_taglen
 * AVI_read_block_for_taglen
 * in struct avi_t:
 * ...
 * vboolean got_taglen;
 * ...
 */
 
int AVI_read_data(avi_t *AVI,unsigned char *vidbuf, long max_vidbuf,
                             unsigned char *audbuf, long max_audbuf,
                              long *len)
{

/*
 * Return codes:
 *
 *    1 = video data read
 *    2 = audio data read
 *    0 = reached EOF
 *   -1 = video buffer too small
 *   -2 = audio buffer too small
 */

   long n;
   unsigned char data[8];

   if(AVI->mode==AVI_MODE_WRITE) return 0;

   for(;;)
   {
      /* Read tag and length */

      if( fileRead(AVI->fdes,data,8) != 8 ) return 0;

      /* if we got a list tag, ignore it */

      if(avi_ustrncasecmp(data,"LIST",4) == 0)
      {
         fileGetLittleLong(AVI->fdes);
         continue;
      }

      n = PAD_EVEN(avi_str2ulong(data+4));

      if(avi_ustrncasecmp(data,AVI->video_tag,3) == 0)
      {
         AVI->video_pos++;
         if(n > max_vidbuf)
         {
		 	/* FIXME: shouldn't do this; TODO: AVI_read_again(avi,buf) */
            fileSeek(AVI->fdes,n,SEEK_CUR);
			/*
			read_again = true;
			read_again_stream = 1; // video
			*required_len = read_again_len = n;
			*/
         	*len = 0;
            return -1;
         }
         *len = (long)fileRead(AVI->fdes,vidbuf,n);
         return (*len == n) ? 1 : 0;
      }
      else if(avi_ustrncasecmp(data,AVI->audio_tag,4) == 0)
      {
         if(n > max_audbuf)
         {
		 	/* FIXME: shouldn't do this; TODO: AVI_read_again(avi,buf) */
			/*
			read_again = true;
			read_again_stream = 2; // audio
			*required_len = read_again_len = n;
			*/
            fileSeek(AVI->fdes,n,SEEK_CUR);
            *len = 0;
            return -2;
         }
         *len = (long)fileRead(AVI->fdes,audbuf,n);
         return (*len == n) ? 2 : 0;
         break;
      }
      else
         if(fileSeek(AVI->fdes,n,SEEK_CUR)<0)  return 0;
   }
}

char *(avi_errors[]) =
{
  /*  0 */ "No Error",
  /*  1 */ "AVI file size limit reached",
  /*  2 */ "Error opening AVI file",
  /*  3 */ "Error reading from AVI file",
  /*  4 */ "Error writing to AVI file",
  /*  5 */ "Error writing index (file may still be useable)",
  /*  6 */ "Error closing AVI file",
  /*  7 */ "I/O Operation not permitted",
  /*  8 */ "Out of memory (memAlloc failed)",
  /*  9 */ "Not an AVI file",
  /* 10 */ "AVI file has no header list (corrupted?)",
  /* 11 */ "AVI file has no MOVI list (corrupted?)",
  /* 12 */ "AVI file has no video data",
  /* 13 */ "operation needs an index",
  /* 14 */ "Unkown Error"
};

#define	num_avi_errors	(sizeof(avi_errors) / sizeof(char*))

char *AVI_strerror(avi_t *AVI)
{
   int aerrno = AVI_get_errno(AVI);
   if (aerrno < 0 || aerrno >= num_avi_errors)
      aerrno = num_avi_errors - 1;
   return avi_errors[aerrno];
}

/* AVI_print_error: Print most recent error (similar to perror) */

void AVI_print_error(avi_t *AVI,char *str)
{
	conlPrintf(LOG_ERROR,"AVILIB: %s: %s\n",str,AVI_strerror(AVI));
}
