summaryrefslogtreecommitdiff
path: root/src/demuxers/demux_avi.c
blob: 20d49885713341f4001fcfd4dd12dd38ed5beedb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
/* 
 * Copyright (C) 2000, 2001 the xine project
 * 
 * This file is part of xine, a unix video player.
 * 
 * xine 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.
 * 
 * xine 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA
 *
 * $Id: demux_avi.c,v 1.53 2001/11/18 03:53:23 guenter Exp $
 *
 * demultiplexer for avi streams
 *
 * part of the code is taken from 
 * avilib (C) 1999 Rainer Johanni <Rainer@Johanni.de>
 *
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>

#include "xine_internal.h"
#include "xineutils.h"
#include "demux.h"

#define	WINE_TYPEDEFS_ONLY
#include "libw32dll/wine/avifmt.h"
#include "libw32dll/wine/windef.h"
#include "libw32dll/wine/vfw.h"

/* The following variable indicates the kind of error */

typedef struct
{
  long pos;
  long len;
  long flags;
} video_index_entry_t;

typedef struct
{
  long pos;
  long len;
  long tot;
} audio_index_entry_t;

typedef struct
{
  long   width;             /* Width  of a video frame */
  long   height;            /* Height of a video frame */
  long   dwScale, dwRate;
  long   dwScale_audio, dwRate_audio;
  long   dwSampleSize;
  double fps;               /* Frames per second */
  
  char   compressor[8];     /* Type of compressor, 4 bytes + padding for 0 byte */
  long   video_strn;        /* Video stream number */
  long   video_frames;      /* Number of video frames */
  char   video_tag[4];      /* Tag of video data */
  long   video_posf;        /* Number of next frame to be read
			       (if index present) */
  long   video_posb;        /* Video position: byte within frame */
  
  long   a_fmt;             /* Audio format, see #defines below */
  long   a_chans;           /* Audio channels, 0 for no audio */
  long   a_rate;            /* Rate in Hz */
  long   a_bits;            /* bits per audio sample */
  long   audio_strn;        /* Audio stream number */
  long   audio_bytes;       /* Total number of bytes of audio data */
  long   audio_chunks;      /* Chunks of audio data in the file */
  char   audio_tag[4];      /* Tag of audio data */
  long   audio_posc;        /* Audio position: chunk */
  long   audio_posb;        /* Audio position: byte within chunk */
  
  uint32_t video_type;      /* BUF_VIDEO_xxx type */
  uint32_t audio_type;      /* BUF_AUDIO_xxx type */

  long                   pos;      /* position in file */
  long                   n_idx;    /* number of index entries actually filled */
  long                   max_idx;  /* number of index entries actually allocated */
  unsigned char        (*idx)[16]; /* index entries (AVI idx1 tag) */
  video_index_entry_t   *video_index;
  audio_index_entry_t   *audio_index;
  BITMAPINFOHEADER       bih;
  char                   wavex[64];
  off_t                  movi_start;
} avi_t;

typedef struct demux_avi_s {
  demux_plugin_t       demux_plugin;

  fifo_buffer_t       *audio_fifo;
  fifo_buffer_t       *video_fifo;

  input_plugin_t      *input;

  avi_t               *avi;

  pthread_t            thread;

  int                  status;

  int                  no_audio;

  uint32_t             video_step;
  uint32_t             AVI_errno; 

  int                  send_end_buffers;

  char                 last_mrl[1024];
} demux_avi_t ;

#define AVI_ERR_SIZELIM      1     /* The write of the data would exceed
                                      the maximum size of the AVI file.
                                      This is more a warning than an error
                                      since the file may be closed safely */

#define AVI_ERR_OPEN         2     /* Error opening the AVI file - wrong path
                                      name or file nor readable/writable */

#define AVI_ERR_READ         3     /* Error reading from AVI File */

#define AVI_ERR_WRITE        4     /* Error writing to AVI File,
                                      disk full ??? */

#define AVI_ERR_WRITE_INDEX  5     /* Could not write index to AVI file
                                      during close, file may still be
                                      usable */

#define AVI_ERR_CLOSE        6     /* Could not write header to AVI file
                                      or not truncate the file during close,
                                      file is most probably corrupted */

#define AVI_ERR_NOT_PERM     7     /* Operation not permitted:
                                      trying to read from a file open
                                      for writing or vice versa */

#define AVI_ERR_NO_MEM       8     /* malloc failed */

#define AVI_ERR_NO_AVI       9     /* Not an AVI file */

#define AVI_ERR_NO_HDRL     10     /* AVI file has no header list,
                                      corrupted ??? */

#define AVI_ERR_NO_MOVI     11     /* AVI file has no MOVI list,
                                      corrupted ??? */

#define AVI_ERR_NO_VIDS     12     /* AVI file contains no video data */

#define AVI_ERR_NO_IDX      13     /* The file has been opened with
                                      getIndex==0, but an operation has been
                                      performed that needs an index */

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

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

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

static void AVI_close(avi_t *AVI)
{
  if(AVI->idx) free(AVI->idx);
  if(AVI->video_index) free(AVI->video_index);
  if(AVI->audio_index) free(AVI->audio_index);
  free(AVI);
}

#define ERR_EXIT(x)	\
do {			\
   this->AVI_errno = x; \
   return 0;		\
} while(0)

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

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;
}

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

  if(AVI->n_idx>=AVI->max_idx) {
    ptr = realloc((void *)AVI->idx,(AVI->max_idx+4096)*16);
    if(ptr == 0) {
      this->AVI_errno = AVI_ERR_NO_MEM;
      return -1;
    }
    AVI->max_idx += 4096;
    AVI->idx = (unsigned char((*)[16]) ) ptr;
  }
  
  /* Add index entry */

  memcpy(AVI->idx[AVI->n_idx],tag,4);
  long2str(AVI->idx[AVI->n_idx]+ 4,flags);
  long2str(AVI->idx[AVI->n_idx]+ 8,pos);
  long2str(AVI->idx[AVI->n_idx]+12,len);

  /* Update counter */

  AVI->n_idx++;

  return 0;
}

static avi_t *AVI_init(demux_avi_t *this)  {

  avi_t *AVI;
  long i, n, 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;
  char data[256];

  /* Create avi_t structure */

  AVI = (avi_t *) xine_xmalloc(sizeof(avi_t));
  if(AVI==NULL) {
    this->AVI_errno = AVI_ERR_NO_MEM;
    return 0;
  }
  memset((void *)AVI,0,sizeof(avi_t));

  /* Read first 12 bytes and check that this is an AVI file */

  this->input->seek(this->input, 0, SEEK_SET);
  if( this->input->read(this->input, data,12) != 12 ) ERR_EXIT(AVI_ERR_READ) ;
						
  if( strncasecmp(data  ,"RIFF",4) !=0 ||
      strncasecmp(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;
  
  while(1) {

    if (this->input->read(this->input, data,8) != 8 ) 
      break; /* We assume it's EOF */
    
    n = str2ulong(data+4);
    n = PAD_EVEN(n);
    
    if(strncasecmp(data,"LIST",4) == 0) {
      if( this->input->read(this->input, data,4) != 4 ) ERR_EXIT(AVI_ERR_READ);
      n -= 4;

      if(strncasecmp(data,"hdrl",4) == 0) {

	hdrl_len = n;
	hdrl_data = (unsigned char *) xine_xmalloc(n);
	if(hdrl_data==0) 
	  ERR_EXIT(AVI_ERR_NO_MEM);
	if (this->input->read(this->input, hdrl_data,n) != n ) 
	  ERR_EXIT(AVI_ERR_READ);

      } else if(strncasecmp(data,"movi",4) == 0)  {

	AVI->movi_start = this->input->seek(this->input, 0,SEEK_CUR);
	this->input->seek(this->input, n, SEEK_CUR);
      }	else
	  this->input->seek(this->input, n, SEEK_CUR);

    } else if(strncasecmp(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]) ) xine_xmalloc(n);
      if (AVI->idx==0) 
	ERR_EXIT(AVI_ERR_NO_MEM);

      if (this->input->read(this->input, (char *)AVI->idx, n) != n ) 
	ERR_EXIT(AVI_ERR_READ);

    } else
      this->input->seek(this->input, 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 (strncasecmp(hdrl_data+i,"LIST",4)==0) { 
      i+= 12; 
      continue; 
    }
    
    n = str2ulong(hdrl_data+i+4);
    n = PAD_EVEN(n);
    
    /* Interpret the tag and its args */
    
    if(strncasecmp(hdrl_data+i,"strh",4)==0) {

      i += 8;
      if(strncasecmp(hdrl_data+i,"vids",4) == 0 && !vids_strh_seen) {

	memcpy(AVI->compressor,hdrl_data+i+4,4);
	AVI->compressor[4] = 0;
	AVI->dwScale = str2ulong(hdrl_data+i+20);
	AVI->dwRate  = str2ulong(hdrl_data+i+24);
	
	if(AVI->dwScale!=0)
	  AVI->fps = (double)AVI->dwRate/(double)AVI->dwScale;

	this->video_step = (long) (90000.0 / AVI->fps);
	
	AVI->video_frames    = str2ulong(hdrl_data+i+32);
	AVI->video_strn = num_stream;
	vids_strh_seen = 1;
	lasttag = 1; /* vids */
      } else if (strncasecmp (hdrl_data+i,"auds",4) ==0 && ! auds_strh_seen) {
	AVI->audio_bytes   = str2ulong(hdrl_data+i+32)*avi_sampsize(AVI);
	AVI->audio_strn    = num_stream;
	AVI->dwScale_audio = str2ulong(hdrl_data+i+20);
	AVI->dwRate_audio  = str2ulong(hdrl_data+i+24);
	AVI->dwSampleSize  = str2ulong(hdrl_data+i+44);
	auds_strh_seen = 1;
	lasttag = 2; /* auds */
      } else
	lasttag = 0;
      num_stream++;
    } else if(strncasecmp(hdrl_data+i,"strf",4)==0) {
      i += 8;
      if(lasttag == 1) {
	/* printf ("size : %d\n",sizeof(AVI->bih)); */
	memcpy (&AVI->bih, hdrl_data+i, sizeof(AVI->bih));
	/* stream_read(demuxer->stream,(char*) &avi_header.bih,MIN(size2,sizeof(avi_header.bih))); */
	AVI->width  = str2ulong(hdrl_data+i+4);
	AVI->height = str2ulong(hdrl_data+i+8);
	
	/*
	  printf ("size : %d x %d (%d x %d)\n", AVI->width, AVI->height, AVI->bih.biWidth, AVI->bih.biHeight);
	  printf("  biCompression %d='%.4s'\n", AVI->bih.biCompression, 
	  &AVI->bih.biCompression);
	*/
	vids_strf_seen = 1;

      } else if(lasttag == 2) {

	memcpy (&AVI->wavex, hdrl_data+i, n);
	
	AVI->a_fmt   = str2ushort(hdrl_data+i  );
	AVI->a_chans = str2ushort(hdrl_data+i+2);
	AVI->a_rate  = str2ulong (hdrl_data+i+4);
	AVI->a_bits  = str2ushort(hdrl_data+i+14);
	
	auds_strf_seen = 1;
      }
      lasttag = 0;
    } else {
      i += 8;
      lasttag = 0;
    }
    
    i += n;
  }
  
  free(hdrl_data);
  
  /* somehow ffmpeg doesn't specify the number of frames here */
  /* if (!vids_strh_seen || !vids_strf_seen || AVI->video_frames==0) { */
  if (!vids_strh_seen || !vids_strf_seen) 
    ERR_EXIT(AVI_ERR_NO_VIDS); 

  
  AVI->video_tag[0] = AVI->video_strn/10 + '0';
  AVI->video_tag[1] = 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] = AVI->audio_strn/10 + '0';
  AVI->audio_tag[1] = AVI->audio_strn%10 + '0';
  AVI->audio_tag[2] = 'w';
  AVI->audio_tag[3] = 'b';

  this->input->seek(this->input, AVI->movi_start, SEEK_SET);

  /* 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, 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( strncasecmp(AVI->idx[i],AVI->video_tag,3)==0 ) break;
    if (i>=AVI->n_idx) {
      ERR_EXIT(AVI_ERR_NO_VIDS);
    }
    
    pos = str2ulong(AVI->idx[i]+ 8);
    len = str2ulong(AVI->idx[i]+12);
    
    this->input->seek(this->input, pos, SEEK_SET);
    if(this->input->read(this->input, data, 8)!=8) ERR_EXIT(AVI_ERR_READ) ;
    
    if( strncasecmp(data,AVI->idx[i],4)==0 && str2ulong(data+4)==len ) {
      idx_type = 1; /* Index from start of file */
      
    } else {
      
      this->input->seek(this->input, pos+AVI->movi_start-4, SEEK_SET);
      if(this->input->read(this->input, data, 8)!=8) 
	ERR_EXIT(AVI_ERR_READ) ;
      if( strncasecmp(data,AVI->idx[i],4)==0 && 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 */
    
    this->input->seek(this->input, AVI->movi_start, SEEK_SET);
    
    AVI->n_idx = 0;
    i=0;
    
    printf ("demux_avi: reconstructing index");
    
    while(1) {
      if( this->input->read(this->input, data,8) != 8 ) 
	break;
      n = str2ulong(data+4);
      
      i++;
      if (i>1000) {
	printf (".");
	i = 0; fflush (stdout);
      }
      
      /* The movi list may contain sub-lists, ignore them */
      
      if(strncasecmp(data,"LIST",4)==0) {
	this->input->seek(this->input, 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(this, AVI, data, AVIIF_KEYFRAME, this->input->seek(this->input, 0, SEEK_CUR)-8, n);
      }
      
      this->input->seek(this->input, PAD_EVEN(n), SEEK_CUR);
    }
    printf ("done\n");
    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(strncasecmp(AVI->idx[i],AVI->video_tag,3) == 0) nvi++;
    if(strncasecmp(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_t *) xine_xmalloc(nvi*sizeof(video_index_entry_t));
  if(AVI->video_index==0) ERR_EXIT(AVI_ERR_NO_MEM) ;

  if(AVI->audio_chunks) {
    AVI->audio_index = (audio_index_entry_t *) xine_xmalloc(nai*sizeof(audio_index_entry_t));
    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(strncasecmp(AVI->idx[i],AVI->video_tag,3) == 0)	{
      AVI->video_index[nvi].pos   = str2ulong(AVI->idx[i]+ 8)+ioff;
      AVI->video_index[nvi].len   = str2ulong(AVI->idx[i]+12);
      AVI->video_index[nvi].flags = str2ulong(AVI->idx[i]+ 4);
      nvi++;
    }
    if(strncasecmp(AVI->idx[i],AVI->audio_tag,4) == 0) {
      AVI->audio_index[nai].pos = str2ulong(AVI->idx[i]+ 8)+ioff;
      AVI->audio_index[nai].len = 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 */

  this->input->seek(this->input, AVI->movi_start, SEEK_SET);
  AVI->video_posf = 0;
  AVI->video_posb = 0;

  return AVI;
}

static void AVI_seek_start(avi_t *AVI)
{
  AVI->video_posf = 0;
  AVI->video_posb = 0;
  AVI->audio_posc = 0;
  AVI->audio_posb = 0;
}

static long AVI_read_audio(demux_avi_t *this, avi_t *AVI, char *audbuf, 
			   long bytes, int *bFrameDone)
{
  long nr, pos, left, todo;

  if(!AVI->audio_index)         { this->AVI_errno = AVI_ERR_NO_IDX;   return -1; }

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

  /* printf ("avi audio package len: %d\n", AVI->audio_index[AVI->audio_posc].len); */


  while(bytes>0)
    {
      left = AVI->audio_index[AVI->audio_posc].len - AVI->audio_posb;
      if(left==0)
	{
	  AVI->audio_posc++;
	  AVI->audio_posb = 0;
	  if (nr>0) {
	    *bFrameDone = 2;
	    return nr;
	  }
	  left = AVI->audio_index[AVI->audio_posc].len - AVI->audio_posb;
	}
      if(bytes<left)
	todo = bytes;
      else
	todo = left;
      pos = AVI->audio_index[AVI->audio_posc].pos + AVI->audio_posb;
      /* printf ("demux_avi: read audio from %d\n", pos); */
      if (this->input->seek (this->input, pos, SEEK_SET)<0)
	return -1;
      if (this->input->read(this->input, audbuf+nr,todo) != todo)
	{
	  this->AVI_errno = AVI_ERR_READ;
	  *bFrameDone = 1;
	  return -1;
	}
      bytes -= todo;
      nr    += todo;
      AVI->audio_posb += todo;
    }

  left = AVI->audio_index[AVI->audio_posc].len - AVI->audio_posb;
  if (left==0)
    *bFrameDone = 2;
  else
    *bFrameDone = 1;

  return nr;
}

static long AVI_read_video(demux_avi_t *this, avi_t *AVI, char *vidbuf, 
			   long bytes, int *bFrameDone)
{
  long nr, pos, left, todo;

  if(!AVI->video_index)         { this->AVI_errno = AVI_ERR_NO_IDX;   return -1; }

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

  while(bytes>0)
    {
      left = AVI->video_index[AVI->video_posf].len - AVI->video_posb;
      if(left==0)
	{
	  AVI->video_posf++;
	  AVI->video_posb = 0;
	  if (nr>0) {
	    *bFrameDone = 2;
	    return nr;
	  }
	  left = AVI->video_index[AVI->video_posf].len - AVI->video_posb;
	}
      if(bytes<left)
	todo = bytes;
      else
	todo = left;
      pos = AVI->video_index[AVI->video_posf].pos + AVI->video_posb;
      /* printf ("demux_avi: read video from %d\n", pos); */
      if (this->input->seek (this->input, pos, SEEK_SET)<0) 
	return -1;
      if (this->input->read(this->input, vidbuf+nr,todo) != todo)
	{
	  this->AVI_errno = AVI_ERR_READ;
	  *bFrameDone = 1;
	  return -1;
	}
      bytes -= todo;
      nr    += todo;
      AVI->video_posb += todo;
    }

  left = AVI->video_index[AVI->video_posf].len - AVI->video_posb;
  if (left==0)
    *bFrameDone = 2;
  else
    *bFrameDone = 1;
	 
  return nr;
}

static uint32_t get_audio_pts (demux_avi_t *this, long posc, long posb) {

  if (this->avi->dwSampleSize==0)
    return posc * (double) this->avi->dwScale_audio / this->avi->dwRate_audio * 90000.0;
  else 
    return (this->avi->audio_index[posc].tot+posb)/this->avi->dwSampleSize * (double) this->avi->dwScale_audio / this->avi->dwRate_audio * 90000.0;
}

static uint32_t get_video_pts (demux_avi_t *this, long pos) {
  return pos * (double) this->avi->dwScale / this->avi->dwRate * 90000.0;
}


static int demux_avi_next (demux_avi_t *this) {

  buf_element_t *buf = NULL;
  uint32_t       audio_pts, video_pts;


  if (this->avi->video_frames <= this->avi->video_posf)
    return 0;

  if (!this->no_audio && (this->avi->audio_chunks <= this->avi->audio_posc))
    return 0;

  buf = this->video_fifo->buffer_pool_alloc (this->video_fifo);

  buf->content = buf->mem;

  audio_pts = get_audio_pts (this, this->avi->audio_posc, this->avi->audio_posb);
  video_pts = get_video_pts (this, this->avi->video_posf);

  if (!this->no_audio && (audio_pts < video_pts)) {

    /* read audio */

    buf->PTS    = audio_pts;
    buf->SCR    = audio_pts;
    buf->size   = AVI_read_audio (this, this->avi, buf->mem, 2048, &buf->decoder_info[0]);

    if (buf->size<0) {
      buf->free_buffer (buf);
      return 0;
    }

    buf->input_pos  = 0;
    buf->input_time = 0;

    buf->type = this->avi->audio_type;
    buf->decoder_info[1] = this->avi->a_rate; /* Audio Rate */
    buf->decoder_info[2] = this->avi->a_bits; /* Audio bits */
    buf->decoder_info[3] = this->avi->a_chans; /* Audio channels */

    if(this->audio_fifo) {
      this->audio_fifo->put (this->audio_fifo, buf);
    } else {
      buf->free_buffer (buf);
    }

  } else {
    /* read video */

    buf->PTS        = video_pts;
    buf->SCR        = video_pts;
    buf->size       = AVI_read_video (this, this->avi, buf->mem, 2048, &buf->decoder_info[0]);
    buf->type       = this->avi->video_type;
    
    buf->input_time = video_pts / 90000;
    buf->input_pos  = this->input->get_current_pos(this->input);

    if (buf->size<0) {
      buf->free_buffer (buf);
      return 0;
    }

    /*
    printf ("demux_avi: adding buf %d to video fifo, decoder_info[0]: %d\n", 
	    buf, buf->decoder_info[0]);
	    */

    
    this->video_fifo->put (this->video_fifo, buf);
  }


  return (buf->size>0);
}

static void *demux_avi_loop (void *this_gen) {

  buf_element_t *buf = NULL;
  demux_avi_t *this = (demux_avi_t *) this_gen;

  this->send_end_buffers = 1;

  do {

    /* printf ("avi loop (status %d)\n", this->status);  */

    if (!demux_avi_next(this))
      this->status = DEMUX_FINISHED;

  } while (this->status == DEMUX_OK) ;

  if (this->send_end_buffers) {
    buf = this->video_fifo->buffer_pool_alloc (this->video_fifo);
    buf->type            = BUF_CONTROL_END;
    buf->decoder_info[0] = 0; /* stream finished */
    this->video_fifo->put (this->video_fifo, buf);
    
    if(this->audio_fifo) {
      buf = this->audio_fifo->buffer_pool_alloc (this->audio_fifo);
      buf->type            = BUF_CONTROL_END;
      buf->decoder_info[0] = 0; /* stream finished */
      this->audio_fifo->put (this->audio_fifo, buf);
    }
  }

  printf ("demux_avi: demux loop finished.\n");

  pthread_exit(NULL);

  return NULL;
}

static void demux_avi_stop (demux_plugin_t *this_gen) {
  
  demux_avi_t   *this = (demux_avi_t *) this_gen;
  buf_element_t *buf;
  void *p;

  if (this->status != DEMUX_OK) {
    printf ("demux_avi: stop...ignored\n");
    return;
  }

  this->send_end_buffers = 0;
  this->status = DEMUX_FINISHED;
  
  pthread_cancel (this->thread);
  pthread_join (this->thread, &p);

  /*
  AVI_close (this->avi);
  this->avi = NULL;
  */

  this->video_fifo->clear(this->video_fifo);
  if (this->audio_fifo)
    this->audio_fifo->clear(this->audio_fifo);

  buf = this->video_fifo->buffer_pool_alloc (this->video_fifo);
  buf->type            = BUF_CONTROL_END;
  buf->decoder_info[0] = 1; /* forced */
  this->video_fifo->put (this->video_fifo, buf);

  if(this->audio_fifo) {
    buf = this->audio_fifo->buffer_pool_alloc (this->audio_fifo);
    buf->type            = BUF_CONTROL_END;
    buf->decoder_info[0] = 1; /* forced */
    this->audio_fifo->put (this->audio_fifo, buf);
  }
  
}

static void demux_avi_close (demux_plugin_t *this_gen) {
  demux_avi_t *this = (demux_avi_t *) this_gen;
  free(this);
}

static int demux_avi_get_status (demux_plugin_t *this_gen) {
  demux_avi_t *this = (demux_avi_t *) this_gen;
  return this->status;
}

static void demux_avi_start (demux_plugin_t *this_gen,
			     fifo_buffer_t *video_fifo, 
			     fifo_buffer_t *audio_fifo,
			     off_t start_pos, int start_time) {
  buf_element_t *buf;
  demux_avi_t *this = (demux_avi_t *) this_gen;
  uint32_t video_pts = 0;
  int err;

  this->audio_fifo   = audio_fifo;
  this->video_fifo   = video_fifo;

  this->status       = DEMUX_OK;

  printf ("demux_avi: video format = %s, audio format = 0x%lx\n",
	  this->avi->compressor, this->avi->a_fmt);
  this->no_audio = 0;
  
  this->avi->audio_type = formattag_to_buf_audio (this->avi->a_fmt);
   
  if( !this->avi->audio_type ) {
    printf ("demux_avi: unknown audio type 0x%lx\n", this->avi->a_fmt);
    this->no_audio  = 1;
    this->avi->audio_type     = BUF_CONTROL_NOP;
  }
  else
    printf ("demux_avi: audio type %s (wFormatTag 0x%x)\n",
            buf_audio_name(this->avi->audio_type),
            (int)this->avi->a_fmt);

  AVI_seek_start (this->avi);

  /*
   * seek to start pos / time
   */

  /* seek video */
  if (start_pos) {
    while ( (this->avi->video_index[this->avi->video_posf].pos < start_pos)
	    || !(this->avi->video_index[this->avi->video_posf].flags & AVIIF_KEYFRAME) ) {
      this->avi->video_posf++;
      if (this->avi->video_posf>this->avi->video_frames) {
	this->status = DEMUX_FINISHED;

	printf ("demux_avi: video seek to start failed\n");
	return;
      }
    }
    
    video_pts = get_video_pts (this, this->avi->video_posf); 

  } else if (start_time) {

    video_pts = start_time * 90000;

    while ( (get_video_pts (this, this->avi->video_posf) < video_pts)
	    || !(this->avi->video_index[this->avi->video_posf].flags & AVIIF_KEYFRAME) ) {
      this->avi->video_posf++;
      if (this->avi->video_posf>this->avi->video_frames) {
	this->status = DEMUX_FINISHED;

	printf ("demux_avi: video seek to start failed\n");
	return;
      }
    }
  }

  /* seek audio */
  if (!this->no_audio) {
    
    while (get_audio_pts (this, this->avi->audio_posc, 0) < video_pts) {
      this->avi->audio_posc++;
      if (this->avi->audio_posc>this->avi->audio_chunks) {
	this->status = DEMUX_FINISHED;

	printf ("demux_avi: audio seek to start failed\n");
	return;
      }
    }
  }


  /* 
   * send start buffers
   */

  buf = this->video_fifo->buffer_pool_alloc (this->video_fifo);
  buf->type    = BUF_CONTROL_START;
  this->video_fifo->put (this->video_fifo, buf);

  if(this->audio_fifo) {
    buf = this->audio_fifo->buffer_pool_alloc (this->audio_fifo);
    buf->type    = BUF_CONTROL_START;
    this->audio_fifo->put (this->audio_fifo, buf);
  }

  buf = this->video_fifo->buffer_pool_alloc (this->video_fifo);
  buf->content = buf->mem;
  buf->decoder_info[0] = 0; /* first package, containing bih */
  buf->decoder_info[1] = this->video_step;
  memcpy (buf->content, &this->avi->bih, sizeof (this->avi->bih));
  buf->size = sizeof (this->avi->bih);

  this->avi->video_type = fourcc_to_buf_video((void*)&this->avi->bih.biCompression);
  
  if ( !this->avi->video_type ) {
      printf ("demux_avi: unknown avi format %.4s\n",
	      (char*)&this->avi->bih.biCompression);

      this->status = DEMUX_FINISHED;
      return;
  }
  buf->type = this->avi->video_type;
  printf ("demux_avi: video codec >%s<\n",buf_video_name(buf->type));

  this->video_fifo->put (this->video_fifo, buf);

  if(this->audio_fifo) {
    buf = this->audio_fifo->buffer_pool_alloc (this->audio_fifo);
    buf->content = buf->mem;
    memcpy (buf->content, &this->avi->wavex, 
	    sizeof (this->avi->wavex));
    buf->size = sizeof (this->avi->wavex);
    buf->type = this->avi->audio_type;
    buf->decoder_info[0] = 0; /* first package, containing wavex */
    buf->decoder_info[1] = this->avi->a_rate; /* Audio Rate */
    buf->decoder_info[2] = this->avi->a_bits; /* Audio bits */
    buf->decoder_info[3] = this->avi->a_chans; /* Audio bits */
    this->audio_fifo->put (this->audio_fifo, buf);
  }

  if ((err = pthread_create (&this->thread, NULL, demux_avi_loop, this)) != 0) {
    fprintf (stderr, "demux_avi: can't create new thread (%s)\n",
	     strerror(err));
    exit (1);
  }
}

static int demux_avi_open(demux_plugin_t *this_gen, 
			  input_plugin_t *input, int stage) {

  demux_avi_t *this = (demux_avi_t *) this_gen;

  switch(stage) {

  case STAGE_BY_CONTENT: {
    if (input->get_blocksize(input))
      return DEMUX_CANNOT_HANDLE;

    if (!(input->get_capabilities(input) & INPUT_CAP_SEEKABLE))
      return DEMUX_CANNOT_HANDLE;

    input->seek(input, 0, SEEK_SET);
    
    this->input = input;

    if (strncmp(this->last_mrl, input->get_mrl (input), 1024)) {
      if (this->avi)
	AVI_close (this->avi);
      this->avi = AVI_init (this);
    }

    if (this->avi) {

      printf ("demux_avi: %ld frames\n", this->avi->video_frames);

      strncpy(this->last_mrl, input->get_mrl (input), 1024);

      return DEMUX_CAN_HANDLE;
    } else 
      printf ("demux_avi: AVI_init failed (AVI_errno: %d)\n",this->AVI_errno);

    return DEMUX_CANNOT_HANDLE;
  }
  break;
  
  case STAGE_BY_EXTENSION: {
    char *ending, *mrl;

    mrl = input->get_mrl (input);
    
    ending = strrchr(mrl, '.');
    
    if(ending) {
      if(!strcasecmp(ending, ".avi")) {
	this->input = input;

	if (strncmp(this->last_mrl, input->get_mrl (input), 1024)) {
	  if (this->avi)
	    AVI_close (this->avi);
	  this->avi = AVI_init (this);
	}

	if (this->avi) {
	  strncpy(this->last_mrl, input->get_mrl (input), 1024);
	  return DEMUX_CAN_HANDLE;
	} else {
	  printf ("demux_avi: AVI_init failed (AVI_errno: %d)\n",this->AVI_errno);
	  return DEMUX_CANNOT_HANDLE;
	}
      }
    }
    
    return DEMUX_CANNOT_HANDLE;
  }
  break;
  
  default:
    return DEMUX_CANNOT_HANDLE;
    break;
  }
  
  return DEMUX_CANNOT_HANDLE;
}

static char *demux_avi_get_id(void) {
  return "AVI";
}

static char *demux_avi_get_mimetypes(void) {
  return "video/msvideo: avi: AVI animation;"
         "video/x-msvideo: avi: AVI animation;";
}

static int demux_avi_get_stream_length (demux_plugin_t *this_gen) {

  demux_avi_t *this = (demux_avi_t *) this_gen;

  if (this->avi) {
    return get_video_pts(this, this->avi->video_frames) / 90000 ;
  } 

  return 0;
}

demux_plugin_t *init_demuxer_plugin(int iface, xine_t *xine) {

  demux_avi_t     *this;
  config_values_t *config;

  if (iface != 6) {
    printf( "demux_avi: this plugin doesn't support plugin API version %d.\n"
	    "demux_avi: this means there's a version mismatch between xine and this "
	    "demux_avi: demuxer plugin.\nInstalling current demuxer plugins should help.\n",
	    iface);
    return NULL;
  }

  this        = xine_xmalloc (sizeof (demux_avi_t));
  config      = xine->config;

  this->demux_plugin.interface_version = DEMUXER_PLUGIN_IFACE_VERSION;
  this->demux_plugin.open              = demux_avi_open;
  this->demux_plugin.start             = demux_avi_start;
  this->demux_plugin.stop              = demux_avi_stop;
  this->demux_plugin.close             = demux_avi_close;
  this->demux_plugin.get_status        = demux_avi_get_status;
  this->demux_plugin.get_identifier    = demux_avi_get_id;
  this->demux_plugin.get_stream_length = demux_avi_get_stream_length;
  this->demux_plugin.get_mimetypes     = demux_avi_get_mimetypes;
  
  return (demux_plugin_t *) this;
}