* modules/*: sanitization of the modules description strings.
[vlc.git] / modules / demux / avi / avi.c
1 /*****************************************************************************
2  * avi.c : AVI file Stream input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001 VideoLAN
5  * $Id: avi.c,v 1.42 2003/03/30 18:14:37 gbazin Exp $
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #include <stdlib.h>                                      /* malloc(), free() */
27 #include <string.h>                                              /* strdup() */
28 #include <errno.h>
29 #include <sys/types.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/input.h>
33
34 #include "video.h"
35
36 #include "libavi.h"
37
38 #define __AVI_SUBTITLE__ 1
39
40 #ifdef __AVI_SUBTITLE__
41 #   include "../util/sub.h"
42 #endif
43 #include "avi.h"
44
45 /*****************************************************************************
46  * Local prototypes
47  *****************************************************************************/
48 static int    AVIInit   ( vlc_object_t * );
49 static void __AVIEnd    ( vlc_object_t * );
50 static int    AVISeek   ( input_thread_t *, mtime_t, int );
51 static int    AVIDemux_Seekable  ( input_thread_t * );
52 static int    AVIDemux_UnSeekable( input_thread_t *p_input );
53
54 #define AVIEnd(a) __AVIEnd(VLC_OBJECT(a))
55 #define FREE( p ) if( p ) { free( p ); (p) = NULL; }
56 /*****************************************************************************
57  * Module descriptor
58  *****************************************************************************/
59 vlc_module_begin();
60     add_category_hint( N_("avi-demuxer"), NULL, VLC_TRUE );
61         add_bool( "avi-interleaved", 0, NULL,
62                   N_("force interleaved method"),
63                   N_("force interleaved method"), VLC_TRUE );
64         add_bool( "avi-index", 0, NULL,
65                   N_("force index creation"),
66                   N_("force index creation"), VLC_TRUE );
67
68     set_description( N_("AVI demuxer") );
69     set_capability( "demux", 212 );
70     set_callbacks( AVIInit, __AVIEnd );
71 vlc_module_end();
72
73 /*****************************************************************************
74  * Some useful functions to manipulate memory
75  *****************************************************************************/
76
77 static uint16_t GetWLE( uint8_t *p_buff )
78 {
79     return (uint16_t)p_buff[0] | ( ((uint16_t)p_buff[1]) << 8 );
80 }
81
82 static uint32_t GetDWLE( uint8_t *p_buff )
83 {
84     return (uint32_t)p_buff[0] | ( ((uint32_t)p_buff[1]) << 8 ) |
85             ( ((uint32_t)p_buff[2]) << 16 ) | ( ((uint32_t)p_buff[3]) << 24 );
86 }
87
88 static uint32_t GetDWBE( uint8_t *p_buff )
89 {
90     return (uint32_t)p_buff[3] | ( ((uint32_t)p_buff[2]) << 8 ) |
91             ( ((uint32_t)p_buff[1]) << 16 ) | ( ((uint32_t)p_buff[0]) << 24 );
92 }
93 static vlc_fourcc_t GetFOURCC( byte_t *p_buff )
94 {
95     return VLC_FOURCC( p_buff[0], p_buff[1], p_buff[2], p_buff[3] );
96 }
97
98 static inline off_t __EVEN( off_t i )
99 {
100     return (i & 1) ? i + 1 : i;
101 }
102
103 #define __ABS( x ) ( (x) < 0 ? (-(x)) : (x) )
104
105 /* read data in a pes */
106 static int input_ReadInPES( input_thread_t *p_input,
107                             pes_packet_t **pp_pes,
108                             size_t i_size )
109 {
110     pes_packet_t *p_pes;
111     data_packet_t *p_data;
112
113
114     if( !(p_pes = input_NewPES( p_input->p_method_data ) ) )
115     {
116         pp_pes = NULL;
117         return -1;
118     }
119
120     *pp_pes = p_pes;
121
122     if( !i_size )
123     {
124         p_pes->p_first =
125             p_pes->p_last  =
126                 input_NewPacket( p_input->p_method_data, 0 );
127         p_pes->i_nb_data = 1;
128         p_pes->i_pes_size = 0;
129         return 0;
130     }
131
132     p_pes->i_nb_data = 0;
133     p_pes->i_pes_size = 0;
134
135     while( p_pes->i_pes_size < i_size )
136     {
137         int i_read;
138
139         i_read = input_SplitBuffer(p_input,
140                                    &p_data,
141                                    __MIN( i_size -
142                                           p_pes->i_pes_size, 2048 ) );
143         if( i_read <= 0 )
144         {
145             /* should occur only with EOF and max allocation reached 
146              * it safer to  return an error */
147             /* free pes */
148             input_DeletePES( p_input->p_method_data, p_pes );
149             return -1;
150         }
151
152         if( !p_pes->p_first )
153         {
154             p_pes->p_first = p_data;
155         }
156         else
157         {
158             p_pes->p_last->p_next = p_data;
159         }
160         p_pes->p_last = p_data;
161         p_pes->i_nb_data++;
162         p_pes->i_pes_size += i_read;
163     }
164
165
166     return p_pes->i_pes_size;
167 }
168
169 /* Test if it seems that it's a key frame */
170 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
171 {
172     switch( i_fourcc )
173     {
174         case FOURCC_DIV1:
175             /* we have:
176              *  startcode:      0x00000100   32bits
177              *  framenumber     ?             5bits
178              *  piture type     0(I),1(P)     2bits
179              */
180             if( GetDWBE( p_byte ) != 0x00000100 )
181             {
182                 /* it's not an msmpegv1 stream, strange...*/
183                 return AVIIF_KEYFRAME;
184             }
185             else
186             {
187                 return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
188             }
189         case FOURCC_DIV2:
190         case FOURCC_DIV3:   // wmv1 also
191             /* we have
192              *  picture type    0(I),1(P)     2bits
193              */
194             return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
195         case FOURCC_mp4v:
196             /* we should find first occurence of 0x000001b6 (32bits)
197              *  startcode:      0x000001b6   32bits
198              *  piture type     0(I),1(P)     2bits
199              */
200             if( GetDWBE( p_byte ) != 0x000001b6 )
201             {
202                 /* not true , need to find the first VOP header */
203                 return AVIIF_KEYFRAME;
204             }
205             else
206             {
207                 return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
208             }
209         default:
210             /* I can't do it, so say yes */
211             return AVIIF_KEYFRAME;
212     }
213 }
214
215 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
216 {
217     switch( i_cat )
218     {
219         case AUDIO_ES:
220             switch( i_codec )
221             {
222                 case WAVE_FORMAT_PCM:
223                     return VLC_FOURCC( 'a', 'r', 'a', 'w' );
224                 case WAVE_FORMAT_MPEG:
225                 case WAVE_FORMAT_MPEGLAYER3:
226                     return VLC_FOURCC( 'm', 'p', 'g', 'a' );
227                 case WAVE_FORMAT_A52:
228                     return VLC_FOURCC( 'a', '5', '2', ' ' );
229                 case WAVE_FORMAT_WMA1:
230                     return VLC_FOURCC( 'w', 'm', 'a', '1' );
231                 case WAVE_FORMAT_WMA2:
232                     return VLC_FOURCC( 'w', 'm', 'a', '2' );
233                 default:
234                     return VLC_FOURCC( 'm', 's',
235                                        ( i_codec >> 8 )&0xff, i_codec&0xff );
236             }
237         case VIDEO_ES:
238             // XXX DIV1 <- msmpeg4v1, DIV2 <- msmpeg4v2, DIV3 <- msmpeg4v3, mp4v for mpeg4
239             switch( i_codec )
240             {
241                 case FOURCC_DIV1:
242                 case FOURCC_div1:
243                 case FOURCC_MPG4:
244                 case FOURCC_mpg4:
245                     return FOURCC_DIV1;
246                 case FOURCC_DIV2:
247                 case FOURCC_div2:
248                 case FOURCC_MP42:
249                 case FOURCC_mp42:
250                 case FOURCC_MPG3:
251                 case FOURCC_mpg3:
252                     return FOURCC_DIV2;
253                 case FOURCC_div3:
254                 case FOURCC_MP43:
255                 case FOURCC_mp43:
256                 case FOURCC_DIV3:
257                 case FOURCC_DIV4:
258                 case FOURCC_div4:
259                 case FOURCC_DIV5:
260                 case FOURCC_div5:
261                 case FOURCC_DIV6:
262                 case FOURCC_div6:
263                 case FOURCC_AP41:
264                 case FOURCC_3IV1:
265                 case FOURCC_3iv1:
266                 case FOURCC_3IVD:
267                 case FOURCC_3ivd:
268                 case FOURCC_3VID:
269                 case FOURCC_3vid:
270                     return FOURCC_DIV3;
271                 case FOURCC_DIVX:
272                 case FOURCC_divx:
273                 case FOURCC_MP4S:
274                 case FOURCC_mp4s:
275                 case FOURCC_M4S2:
276                 case FOURCC_m4s2:
277                 case FOURCC_xvid:
278                 case FOURCC_XVID:
279                 case FOURCC_XviD:
280                 case FOURCC_DX50:
281                 case FOURCC_mp4v:
282                 case FOURCC_4:
283                 case FOURCC_3IV2:
284                 case FOURCC_3iv2:
285                     return FOURCC_mp4v;
286             }
287         default:
288             return VLC_FOURCC( 'u', 'n', 'd', 'f' );
289     }
290 }
291
292 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
293                                    int *pi_number, int *pi_type )
294 {
295 #define SET_PTR( p, v ) if( p ) *(p) = (v);
296     int c1, c2;
297
298     c1 = ((uint8_t *)&i_id)[0];
299     c2 = ((uint8_t *)&i_id)[1];
300
301     if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
302     {
303         SET_PTR( pi_number, 100 ); /* > max stream number */
304         SET_PTR( pi_type, UNKNOWN_ES );
305     }
306     else
307     {
308         SET_PTR( pi_number, (c1 - '0') * 10 + (c2 - '0' ) );
309         switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
310         {
311             case AVITWOCC_wb:
312                 SET_PTR( pi_type, AUDIO_ES );
313                 break;
314             case AVITWOCC_dc:
315             case AVITWOCC_db:
316                 SET_PTR( pi_type, VIDEO_ES );
317                 break;
318             default:
319                 SET_PTR( pi_type, UNKNOWN_ES );
320                 break;
321         }
322     }
323 #undef SET_PTR
324 }
325
326 static int AVI_PacketGetHeader( input_thread_t *p_input, avi_packet_t *p_pk )
327 {
328     uint8_t  *p_peek;
329
330     if( input_Peek( p_input, &p_peek, 16 ) < 16 )
331     {
332         return VLC_EGENERIC;
333     }
334     p_pk->i_fourcc  = GetFOURCC( p_peek );
335     p_pk->i_size    = GetDWLE( p_peek + 4 );
336     p_pk->i_pos     = AVI_TellAbsolute( p_input );
337     if( p_pk->i_fourcc == AVIFOURCC_LIST )
338     {
339         p_pk->i_type = GetFOURCC( p_peek + 8 );
340     }
341     else
342     {
343         p_pk->i_type = 0;
344     }
345
346     memcpy( p_pk->i_peek, p_peek + 8, 8 );
347
348     AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
349     return VLC_SUCCESS;
350 }
351
352 static int AVI_PacketNext( input_thread_t *p_input )
353 {
354     avi_packet_t    avi_ck;
355
356     if( AVI_PacketGetHeader( p_input, &avi_ck ) )
357     {
358         return VLC_EGENERIC;
359     }
360     if( avi_ck.i_fourcc == AVIFOURCC_LIST && avi_ck.i_type == AVIFOURCC_rec )
361     {
362         return AVI_SkipBytes( p_input, 12 );
363     }
364     else
365     {
366         return AVI_SkipBytes( p_input, __EVEN( avi_ck.i_size ) + 8 );
367     }
368 }
369 static int AVI_PacketRead( input_thread_t   *p_input,
370                            avi_packet_t     *p_pk,
371                            pes_packet_t     **pp_pes )
372 {
373     size_t i_size;
374     vlc_bool_t b_pad;
375
376     i_size = __EVEN( p_pk->i_size + 8 );
377     b_pad  = ( i_size != p_pk->i_size + 8 );
378
379     if( input_ReadInPES( p_input, pp_pes, i_size ) != (ssize_t)i_size )
380     {
381         return VLC_EGENERIC;
382     }
383     (*pp_pes)->p_first->p_payload_start += 8;
384     (*pp_pes)->i_pes_size -= 8;
385
386     if( b_pad )
387     {
388         (*pp_pes)->p_last->p_payload_end--;
389         (*pp_pes)->i_pes_size--;
390     }
391
392     return VLC_SUCCESS;
393 }
394
395 static int AVI_PacketSearch( input_thread_t *p_input )
396 {
397     demux_sys_t     *p_avi = p_input->p_demux_data;
398
399     avi_packet_t    avi_pk;
400     for( ;; )
401     {
402         if( AVI_SkipBytes( p_input, 1 ) )
403         {
404             return VLC_EGENERIC;
405         }
406         AVI_PacketGetHeader( p_input, &avi_pk );
407         if( avi_pk.i_stream < p_avi->i_streams &&
408             ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
409         {
410             return VLC_SUCCESS;
411         }
412         switch( avi_pk.i_fourcc )
413         {
414             case AVIFOURCC_JUNK:
415             case AVIFOURCC_LIST:
416             case AVIFOURCC_idx1:
417                 return VLC_SUCCESS;
418         }
419     }
420 }
421
422
423 static void __AVI_AddEntryIndex( avi_stream_t *p_info,
424                                  AVIIndexEntry_t *p_index)
425 {
426     if( p_info->p_index == NULL )
427     {
428         p_info->i_idxmax = 16384;
429         p_info->i_idxnb = 0;
430         if( !( p_info->p_index = calloc( p_info->i_idxmax,
431                                   sizeof( AVIIndexEntry_t ) ) ) )
432         {
433             return;
434         }
435     }
436     if( p_info->i_idxnb >= p_info->i_idxmax )
437     {
438         p_info->i_idxmax += 16384;
439         if( !( p_info->p_index = realloc( (void*)p_info->p_index,
440                            p_info->i_idxmax *
441                            sizeof( AVIIndexEntry_t ) ) ) )
442         {
443             return;
444         }
445     }
446     /* calculate cumulate length */
447     if( p_info->i_idxnb > 0 )
448     {
449         p_index->i_lengthtotal =
450             p_info->p_index[p_info->i_idxnb - 1].i_length +
451                 p_info->p_index[p_info->i_idxnb - 1].i_lengthtotal;
452     }
453     else
454     {
455         p_index->i_lengthtotal = 0;
456     }
457
458     p_info->p_index[p_info->i_idxnb] = *p_index;
459     p_info->i_idxnb++;
460
461 }
462
463 static void AVI_IndexAddEntry( demux_sys_t *p_avi,
464                                int i_stream,
465                                AVIIndexEntry_t *p_index)
466 {
467     __AVI_AddEntryIndex( p_avi->pp_info[i_stream],
468                          p_index );
469     if( p_avi->i_movi_lastchunk_pos < p_index->i_pos )
470     {
471         p_avi->i_movi_lastchunk_pos = p_index->i_pos;
472     }
473 }
474
475 static void AVI_IndexLoad( input_thread_t *p_input )
476 {
477     demux_sys_t *p_avi = p_input->p_demux_data;
478
479     avi_chunk_list_t    *p_riff;
480     avi_chunk_list_t    *p_movi;
481     avi_chunk_idx1_t    *p_idx1;
482
483     unsigned int i_stream;
484     unsigned int i_index;
485     off_t   i_offset;
486
487     p_riff = (avi_chunk_list_t*)AVI_ChunkFind( &p_avi->ck_root,
488                                                AVIFOURCC_RIFF, 0);
489
490     p_idx1 = (avi_chunk_idx1_t*)AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
491     p_movi = (avi_chunk_list_t*)AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
492
493     if( !p_idx1 )
494     {
495         msg_Warn( p_input, "cannot find idx1 chunk, no index defined" );
496         return;
497     }
498     for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
499     {
500         p_avi->pp_info[i_stream]->i_idxnb  = 0;
501         p_avi->pp_info[i_stream]->i_idxmax = 0;
502         p_avi->pp_info[i_stream]->p_index  = NULL;
503     }
504     /* *** calculate offset *** */
505     if( p_idx1->i_entry_count > 0 &&
506         p_idx1->entry[0].i_pos < p_movi->i_chunk_pos )
507     {
508         i_offset = p_movi->i_chunk_pos + 8;
509     }
510     else
511     {
512         i_offset = 0;
513     }
514
515     for( i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
516     {
517         unsigned int i_cat;
518
519         AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
520                                &i_stream,
521                                &i_cat );
522         if( i_stream < p_avi->i_streams &&
523             i_cat == p_avi->pp_info[i_stream]->i_cat )
524         {
525             AVIIndexEntry_t index;
526             index.i_id      = p_idx1->entry[i_index].i_fourcc;
527             index.i_flags   =
528                 p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
529             index.i_pos     = p_idx1->entry[i_index].i_pos + i_offset;
530             index.i_length  = p_idx1->entry[i_index].i_length;
531             AVI_IndexAddEntry( p_avi, i_stream, &index );
532         }
533     }
534     for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
535     {
536         msg_Dbg( p_input,
537                 "stream[%d] creating %d index entries",
538                 i_stream,
539                 p_avi->pp_info[i_stream]->i_idxnb );
540     }
541
542 }
543
544 static void AVI_IndexCreate( input_thread_t *p_input )
545 {
546     demux_sys_t *p_avi = p_input->p_demux_data;
547
548     avi_chunk_list_t    *p_riff;
549     avi_chunk_list_t    *p_movi;
550
551     unsigned int i_stream;
552     off_t i_movi_end;
553
554     p_riff = (avi_chunk_list_t*)AVI_ChunkFind( &p_avi->ck_root,
555                                                AVIFOURCC_RIFF, 0);
556     p_movi = (avi_chunk_list_t*)AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
557
558     if( !p_movi )
559     {
560         msg_Err( p_input, "cannot find p_movi" );
561         return;
562     }
563
564     for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
565     {
566         p_avi->pp_info[i_stream]->i_idxnb  = 0;
567         p_avi->pp_info[i_stream]->i_idxmax = 0;
568         p_avi->pp_info[i_stream]->p_index  = NULL;
569     }
570     i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
571                         p_input->stream.p_selected_area->i_size );
572
573     AVI_SeekAbsolute( p_input, p_movi->i_chunk_pos + 12);
574     msg_Warn( p_input, "creating index from LIST-movi, will take time !" );
575     for( ;; )
576     {
577         avi_packet_t pk;
578
579         if( AVI_PacketGetHeader( p_input, &pk ) )
580         {
581             break;
582         }
583         if( pk.i_stream < p_avi->i_streams &&
584             pk.i_cat == p_avi->pp_info[pk.i_stream]->i_cat )
585         {
586             AVIIndexEntry_t index;
587             index.i_id      = pk.i_fourcc;
588             index.i_flags   =
589                AVI_GetKeyFlag(p_avi->pp_info[pk.i_stream]->i_codec, pk.i_peek);
590             index.i_pos     = pk.i_pos;
591             index.i_length  = pk.i_size;
592             AVI_IndexAddEntry( p_avi, pk.i_stream, &index );
593         }
594         else
595         {
596             switch( pk.i_fourcc )
597             {
598                 case AVIFOURCC_idx1:
599                     goto print_stat;
600                 case AVIFOURCC_rec:
601                 case AVIFOURCC_JUNK:
602                     break;
603                 default:
604                     msg_Warn( p_input, "need resync, probably broken avi" );
605                     if( AVI_PacketSearch( p_input ) )
606                     {
607                         msg_Warn( p_input, "lost sync, abord index creation" );
608                         goto print_stat;
609                     }
610             }
611         }
612         if( pk.i_pos + pk.i_size >= i_movi_end ||
613             AVI_PacketNext( p_input ) )
614         {
615             break;
616         }
617     }
618
619 print_stat:
620     for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
621     {
622         msg_Dbg( p_input,
623                 "stream[%d] creating %d index entries",
624                 i_stream,
625                 p_avi->pp_info[i_stream]->i_idxnb );
626     }
627 }
628
629
630 /*****************************************************************************
631  * Stream management
632  *****************************************************************************/
633 static vlc_bool_t AVI_StreamStart ( input_thread_t *, demux_sys_t *, int );
634 static int  AVI_StreamSeek   ( input_thread_t *, demux_sys_t *, int, mtime_t );
635 static void AVI_StreamStop   ( input_thread_t *, demux_sys_t *, int );
636 static int  AVI_StreamStopFinishedStreams( input_thread_t *, demux_sys_t * );
637
638 static vlc_bool_t AVI_StreamStart( input_thread_t *p_input,
639                                    demux_sys_t *p_avi, int i_stream )
640 {
641 #define p_stream    p_avi->pp_info[i_stream]
642     if( !p_stream->p_es )
643     {
644         msg_Warn( p_input, "stream[%d] unselectable", i_stream );
645         return VLC_FALSE;
646     }
647     if( p_stream->b_activated )
648     {
649         msg_Warn( p_input, "stream[%d] already selected", i_stream );
650         return VLC_TRUE;
651     }
652
653     if( !p_stream->p_es->p_decoder_fifo )
654     {
655         vlc_mutex_lock( &p_input->stream.stream_lock );
656         input_SelectES( p_input, p_stream->p_es );
657         vlc_mutex_unlock( &p_input->stream.stream_lock );
658     }
659     p_stream->b_activated = p_stream->p_es->p_decoder_fifo ? VLC_TRUE
660                                                            : VLC_FALSE;
661     if( p_stream->b_activated && p_avi->b_seekable)
662     {
663         AVI_StreamSeek( p_input, p_avi, i_stream, p_avi->i_time );
664     }
665
666     return p_stream->b_activated;
667 #undef  p_stream
668 }
669
670 static void    AVI_StreamStop( input_thread_t *p_input,
671                                demux_sys_t *p_avi, int i_stream )
672 {
673 #define p_stream    p_avi->pp_info[i_stream]
674
675     if( !p_stream->b_activated )
676     {
677         msg_Warn( p_input, "stream[%d] already unselected", i_stream );
678         return;
679     }
680
681     if( p_stream->p_es->p_decoder_fifo )
682     {
683         vlc_mutex_lock( &p_input->stream.stream_lock );
684         input_UnselectES( p_input, p_stream->p_es );
685         vlc_mutex_unlock( &p_input->stream.stream_lock );
686     }
687
688
689     p_stream->b_activated = VLC_FALSE;
690
691 #undef  p_stream
692 }
693
694 static int AVI_StreamStopFinishedStreams( input_thread_t *p_input,
695                                            demux_sys_t *p_avi )
696 {
697     unsigned int i_stream;
698     int b_end;
699
700     for( i_stream = 0,b_end = VLC_TRUE;
701             i_stream < p_avi->i_streams; i_stream++ )
702     {
703 #define p_stream    p_avi->pp_info[i_stream]
704         if( p_stream->i_idxposc >= p_stream->i_idxnb )
705         {
706             AVI_StreamStop( p_input, p_avi, i_stream );
707         }
708         else
709         {
710             b_end = VLC_FALSE;
711         }
712 #undef  p_stream
713     }
714     return( b_end );
715 }
716 /****************************************************************************
717  * AVI_MovieGetLength give max streams length in second
718  ****************************************************************************/
719 static mtime_t  AVI_MovieGetLength( input_thread_t *p_input, demux_sys_t *p_avi )
720 {
721     unsigned int i_stream;
722     mtime_t i_maxlength;
723
724     i_maxlength = 0;
725     for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
726     {
727 #define p_stream  p_avi->pp_info[i_stream]
728         mtime_t i_length;
729         /* fix length for each stream */
730         if( p_stream->i_idxnb < 1 || !p_stream->p_index )
731         {
732             continue;
733         }
734
735         if( p_stream->i_samplesize )
736         {
737             i_length =
738                 (mtime_t)( p_stream->p_index[p_stream->i_idxnb-1].i_lengthtotal +
739                            p_stream->p_index[p_stream->i_idxnb-1].i_length ) *
740                 (mtime_t)p_stream->i_scale /
741                 (mtime_t)p_stream->i_rate /
742                 (mtime_t)p_stream->i_samplesize;
743         }
744         else
745         {
746             i_length = (mtime_t)p_stream->i_idxnb *
747                        (mtime_t)p_stream->i_scale /
748                        (mtime_t)p_stream->i_rate;
749         }
750
751         msg_Dbg( p_input,
752                  "stream[%d] length:"I64Fd" (based on index)",
753                  i_stream,
754                  i_length );
755         i_maxlength = __MAX( i_maxlength, i_length );
756 #undef p_stream
757     }
758
759     return i_maxlength;
760 }
761
762 /*****************************************************************************
763  * AVIEnd: frees unused data
764  *****************************************************************************/
765 static void __AVIEnd ( vlc_object_t * p_this )
766 {
767     input_thread_t *    p_input = (input_thread_t *)p_this;
768     unsigned int i;
769     demux_sys_t *p_avi = p_input->p_demux_data  ;
770
771     if( p_avi->pp_info )
772     {
773         for( i = 0; i < p_avi->i_streams; i++ )
774         {
775             if( p_avi->pp_info[i] )
776             {
777                 if( p_avi->pp_info[i]->p_index )
778                 {
779                       free( p_avi->pp_info[i]->p_index );
780                 }
781                 free( p_avi->pp_info[i] );
782             }
783         }
784          free( p_avi->pp_info );
785     }
786 #ifdef __AVI_SUBTITLE__
787     if( p_avi->p_sub )
788     {
789         subtitle_Close( p_avi->p_sub );
790         p_avi->p_sub = NULL;
791     }
792 #endif
793     AVI_ChunkFreeRoot( p_input, &p_avi->ck_root );
794
795     FREE( p_input->p_demux_data );
796 }
797
798 /*****************************************************************************
799  * AVIInit: check file and initializes AVI structures
800  *****************************************************************************/
801 static int AVIInit( vlc_object_t * p_this )
802 {
803     input_thread_t *    p_input = (input_thread_t *)p_this;
804     avi_chunk_t         ck_riff;
805     avi_chunk_list_t    *p_riff = (avi_chunk_list_t*)&ck_riff;
806     avi_chunk_list_t    *p_hdrl, *p_movi;
807 #if 0
808     avi_chunk_list_t    *p_INFO;
809     avi_chunk_strz_t    *p_name;
810 #endif
811     avi_chunk_avih_t    *p_avih;
812     demux_sys_t *p_avi;
813     es_descriptor_t *p_es = NULL; /* avoid warning */
814     unsigned int i;
815 #ifdef __AVI_SUBTITLE__
816     mtime_t i_microsecperframe = 0; // for some subtitle format
817 #endif
818
819     vlc_bool_t b_stream_audio, b_stream_video;
820
821     p_input->pf_demux = AVIDemux_Seekable;
822     if( AVI_TestFile( p_input ) )
823     {
824         msg_Warn( p_input, "avi module discarded (invalid headr)" );
825         return VLC_EGENERIC;
826     }
827
828     /* Initialize access plug-in structures. */
829     if( p_input->i_mtu == 0 )
830     {
831         /* Improve speed. */
832         p_input->i_bufsize = INPUT_DEFAULT_BUFSIZE;
833     }
834
835     if( !( p_input->p_demux_data =
836                     p_avi = malloc( sizeof(demux_sys_t) ) ) )
837     {
838         msg_Err( p_input, "out of memory" );
839         return VLC_ENOMEM;
840     }
841     memset( p_avi, 0, sizeof( demux_sys_t ) );
842     p_avi->i_time = 0;
843     p_avi->i_pcr  = 0;
844     p_avi->b_seekable = ( ( p_input->stream.b_seekable )
845                         &&( p_input->stream.i_method == INPUT_METHOD_FILE ) );
846     p_avi->i_movi_lastchunk_pos = 0;
847
848     /* *** for unseekable stream, automaticaly use AVIDemux_interleaved *** */
849     if( !p_avi->b_seekable || config_GetInt( p_input, "avi-interleaved" ) )
850     {
851         p_input->pf_demux = AVIDemux_UnSeekable;
852     }
853
854     if( AVI_ChunkReadRoot( p_input, &p_avi->ck_root, p_avi->b_seekable ) )
855     {
856         msg_Err( p_input, "avi module discarded (invalid file)" );
857         return VLC_EGENERIC;
858     }
859     AVI_ChunkDumpDebug( p_input, &p_avi->ck_root );
860
861
862     p_riff  = (avi_chunk_list_t*)AVI_ChunkFind( &p_avi->ck_root,
863                                                 AVIFOURCC_RIFF, 0 );
864     p_hdrl  = (avi_chunk_list_t*)AVI_ChunkFind( p_riff,
865                                                 AVIFOURCC_hdrl, 0 );
866     p_movi  = (avi_chunk_list_t*)AVI_ChunkFind( p_riff,
867                                                 AVIFOURCC_movi, 0 );
868 #if 0
869     p_INFO  = (avi_chunk_list_t*)AVI_ChunkFind( p_riff,
870                                                 AVIFOURCC_INFO, 0 );
871     p_name  = (avi_chunk_strz_t*)AVI_ChunkFind( p_INFO,
872                                                 AVIFOURCC_INAM, 0 );
873     if( p_name )
874     {
875
876     }
877 #endif
878
879     if( !p_hdrl || !p_movi )
880     {
881         msg_Err( p_input, "avi module discarded (invalid file)" );
882         return VLC_EGENERIC;
883     }
884
885     if( !( p_avih = (avi_chunk_avih_t*)AVI_ChunkFind( p_hdrl,
886                                                       AVIFOURCC_avih, 0 ) ) )
887     {
888         msg_Err( p_input, "cannot find avih chunk" );
889         return VLC_EGENERIC;
890     }
891     p_avi->i_streams = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
892     if( p_avih->i_streams != p_avi->i_streams )
893     {
894         msg_Warn( p_input,
895                   "found %d stream but %d are declared",
896                   p_avi->i_streams,
897                   p_avih->i_streams );
898     }
899     if( p_avi->i_streams == 0 )
900     {
901         AVIEnd( p_input );
902         msg_Err( p_input, "no stream defined!" );
903         return VLC_EGENERIC;
904     }
905
906     /*  create one program */
907     vlc_mutex_lock( &p_input->stream.stream_lock );
908     if( input_InitStream( p_input, 0 ) == -1)
909     {
910         vlc_mutex_unlock( &p_input->stream.stream_lock );
911         AVIEnd( p_input );
912         msg_Err( p_input, "cannot init stream" );
913         return VLC_EGENERIC;
914     }
915     if( input_AddProgram( p_input, 0, 0) == NULL )
916     {
917         vlc_mutex_unlock( &p_input->stream.stream_lock );
918         AVIEnd( p_input );
919         msg_Err( p_input, "cannot add program" );
920         return VLC_EGENERIC;
921     }
922     p_input->stream.p_selected_program = p_input->stream.pp_programs[0];
923     vlc_mutex_unlock( &p_input->stream.stream_lock );
924
925     /* print informations on streams */
926     msg_Dbg( p_input, "AVIH: %d stream, flags %s%s%s%s ",
927              p_avi->i_streams,
928              p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
929              p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
930              p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
931              p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
932     {
933         input_info_category_t *p_cat = input_InfoCategory( p_input, _("Avi") );
934         input_AddInfo( p_cat, _("Number of Streams"), "%d", p_avi->i_streams );
935         input_AddInfo( p_cat, _("Flags"), "%s%s%s%s",
936                        p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
937                        p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
938                        p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
939                        p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
940     }
941
942     /* now read info on each stream and create ES */
943     p_avi->pp_info = calloc( p_avi->i_streams,
944                             sizeof( avi_stream_t* ) );
945     memset( p_avi->pp_info,
946             0,
947             sizeof( avi_stream_t* ) * p_avi->i_streams );
948
949     for( i = 0 ; i < p_avi->i_streams; i++ )
950     {
951         avi_chunk_list_t    *p_avi_strl;
952         avi_chunk_strh_t    *p_avi_strh;
953         avi_chunk_strf_auds_t    *p_avi_strf_auds;
954         avi_chunk_strf_vids_t    *p_avi_strf_vids;
955         int     i_init_size;
956         void    *p_init_data;
957 #define p_info  p_avi->pp_info[i]
958         p_info = malloc( sizeof(avi_stream_t ) );
959         memset( p_info, 0, sizeof( avi_stream_t ) );
960
961         p_avi_strl = (avi_chunk_list_t*)AVI_ChunkFind( p_hdrl,
962                                                        AVIFOURCC_strl, i );
963         p_avi_strh = (avi_chunk_strh_t*)AVI_ChunkFind( p_avi_strl,
964                                                        AVIFOURCC_strh, 0 );
965         p_avi_strf_auds = (avi_chunk_strf_auds_t*)
966             p_avi_strf_vids = (avi_chunk_strf_vids_t*)
967                 AVI_ChunkFind( p_avi_strl, AVIFOURCC_strf, 0 );
968
969         if( !p_avi_strl || !p_avi_strh ||
970                 ( !p_avi_strf_auds && !p_avi_strf_vids ) )
971         {
972             msg_Warn( p_input, "stream[%d] incomlete", i );
973             continue;
974         }
975
976         /* *** Init p_info *** */
977         p_info->i_rate  = p_avi_strh->i_rate;
978         p_info->i_scale = p_avi_strh->i_scale;
979         p_info->i_samplesize = p_avi_strh->i_samplesize;
980         msg_Dbg( p_input, "stream[%d] rate:%d scale:%d samplesize:%d",
981                  i,
982                  p_info->i_rate, p_info->i_scale, p_info->i_samplesize );
983         switch( p_avi_strh->i_type )
984         {
985             case( AVIFOURCC_auds ):
986                 p_info->i_cat = AUDIO_ES;
987                 p_info->i_fourcc =
988                     AVI_FourccGetCodec( AUDIO_ES,
989                                         p_avi_strf_auds->p_wf->wFormatTag );
990                 p_info->i_codec  = p_info->i_fourcc;
991                 i_init_size = p_avi_strf_auds->i_chunk_size;
992                 p_init_data = p_avi_strf_auds->p_wf;
993                 msg_Dbg( p_input, "stream[%d] audio(0x%x) %d channels %dHz %dbits",
994                         i,
995                         p_avi_strf_auds->p_wf->wFormatTag,
996                         p_avi_strf_auds->p_wf->nChannels,
997                         p_avi_strf_auds->p_wf->nSamplesPerSec,
998                         p_avi_strf_auds->p_wf->wBitsPerSample );
999                 {
1000                     char hepp[sizeof("Stream") + 10];
1001                     input_info_category_t *p_cat;
1002                     sprintf(hepp, "Stream %d", i);
1003                     p_cat = input_InfoCategory( p_input, hepp);
1004                     input_AddInfo( p_cat, _("Type"), "Audio(0x%x)",
1005                                    p_avi_strf_auds->p_wf->wFormatTag );
1006                     input_AddInfo( p_cat, _("Codec"), "%4.4s",
1007                                    (const char*)&(p_info->i_codec) );
1008                     input_AddInfo( p_cat, _("Channels"), "%d",
1009                                    p_avi_strf_auds->p_wf->nChannels );
1010                     input_AddInfo( p_cat, _("Sample Rate"), "%d",
1011                                    p_avi_strf_auds->p_wf->nSamplesPerSec );
1012                     input_AddInfo( p_cat, _("Bits Per Sample"), "%d",
1013                                    p_avi_strf_auds->p_wf->wBitsPerSample );
1014                 }
1015                 break;
1016
1017             case( AVIFOURCC_vids ):
1018                 p_info->i_cat = VIDEO_ES;
1019                 /* XXX quick hack for playing ffmpeg video, I don't know
1020                     who is doing something wrong */
1021                 p_info->i_samplesize = 0;
1022                 p_info->i_fourcc = p_avi_strf_vids->p_bih->biCompression;
1023                 p_info->i_codec =
1024                     AVI_FourccGetCodec( VIDEO_ES, p_info->i_fourcc );
1025                 i_init_size = p_avi_strf_vids->i_chunk_size;
1026                 p_init_data = p_avi_strf_vids->p_bih;
1027                 msg_Dbg( p_input, "stream[%d] video(%4.4s) %dx%d %dbpp %ffps",
1028                         i,
1029                          (char*)&p_avi_strf_vids->p_bih->biCompression,
1030                          p_avi_strf_vids->p_bih->biWidth,
1031                          p_avi_strf_vids->p_bih->biHeight,
1032                          p_avi_strf_vids->p_bih->biBitCount,
1033                          (float)p_info->i_rate /
1034                              (float)p_info->i_scale );
1035                 {
1036                     char hepp[sizeof("Stream") + 10];
1037                     input_info_category_t *p_cat;
1038                     sprintf(hepp, "Stream %d", i);
1039                     p_cat = input_InfoCategory( p_input, hepp);
1040                     input_AddInfo( p_cat, _("Type"), _("Video") );
1041                     input_AddInfo( p_cat, _("Codec"), "%4.4s",
1042                                    (const char*)&(p_info->i_codec) );
1043                     input_AddInfo( p_cat, _("Resolution"), "%dx%d",
1044                                    p_avi_strf_vids->p_bih->biWidth,
1045                                    p_avi_strf_vids->p_bih->biHeight );
1046                     input_AddInfo( p_cat, _("Frame Rate"), "%f",
1047                                    (float)p_info->i_rate /
1048                                        (float)p_info->i_scale );
1049                     input_AddInfo( p_cat, _("Bits Per Pixel"), "%d",
1050                                    p_avi_strf_vids->p_bih->biBitCount );
1051                 }
1052 #ifdef __AVI_SUBTITLE__
1053                 if( i_microsecperframe == 0 )
1054                 {
1055                     i_microsecperframe = (mtime_t)1000000 *
1056                                          (mtime_t)p_info->i_scale /
1057                                          (mtime_t)p_info->i_rate;
1058                 }
1059 #endif
1060                 break;
1061             default:
1062                 msg_Warn( p_input, "stream[%d] unknown type", i );
1063                 p_info->i_cat = UNKNOWN_ES;
1064                 i_init_size = 0;
1065                 p_init_data = NULL;
1066                 {
1067                     char psz_cat[32]; /* We'll clip i just in case */
1068                     input_info_category_t *p_cat;
1069                     sprintf( psz_cat, "Stream %d", __MIN( i, 100000 ) );
1070                     p_cat = input_InfoCategory( p_input, psz_cat );
1071                     input_AddInfo( p_cat, _("Type"), _("Unknown") );
1072                 }
1073                 break;
1074         }
1075         p_info->b_activated = VLC_FALSE;
1076         /* add one ES */
1077         vlc_mutex_lock( &p_input->stream.stream_lock );
1078         p_info->p_es =
1079             p_es = input_AddES( p_input,
1080                                 p_input->stream.p_selected_program, 1+i,
1081                                 0 );
1082         vlc_mutex_unlock( &p_input->stream.stream_lock );
1083         p_es->i_stream_id =i; /* XXX: i don't use it */
1084         p_es->i_fourcc = p_info->i_fourcc;
1085         p_es->i_cat = p_info->i_cat;
1086         if( p_es->i_cat == AUDIO_ES )
1087         {
1088             p_es->p_waveformatex = malloc( i_init_size );
1089             memcpy( p_es->p_waveformatex, p_init_data, i_init_size );
1090         }
1091         else if( p_es->i_cat == VIDEO_ES )
1092         {
1093             p_es->p_bitmapinfoheader = malloc( i_init_size );
1094             memcpy( p_es->p_bitmapinfoheader, p_init_data, i_init_size );
1095         }
1096 #undef p_info
1097     }
1098
1099 #ifdef __AVI_SUBTITLE__
1100     if( ( p_avi->p_sub = subtitle_New( p_input, NULL, i_microsecperframe ) ) )
1101     {
1102         subtitle_Select( p_avi->p_sub );
1103     }
1104 #endif
1105
1106     if( config_GetInt( p_input, "avi-index" ) )
1107     {
1108         if( p_avi->b_seekable )
1109         {
1110             AVI_IndexCreate( p_input );
1111         }
1112         else
1113         {
1114             msg_Warn( p_input, "cannot create index (unseekable stream)" );
1115             AVI_IndexLoad( p_input );
1116         }
1117     }
1118     else
1119     {
1120         AVI_IndexLoad( p_input );
1121     }
1122
1123     /* *** movie length in sec *** */
1124     p_avi->i_length = AVI_MovieGetLength( p_input, p_avi );
1125     if( p_avi->i_length < (mtime_t)p_avih->i_totalframes *
1126                           (mtime_t)p_avih->i_microsecperframe /
1127                           (mtime_t)1000000 )
1128     {
1129         msg_Warn( p_input, "broken or missing index, 'seek' will be axproximative or will have strange behavour" );
1130     }
1131
1132     /* fix some BeOS MediaKit generated file */
1133     for( i = 0 ; i < p_avi->i_streams; i++ )
1134     {
1135         avi_chunk_list_t    *p_avi_strl;
1136         avi_chunk_strh_t    *p_avi_strh;
1137         avi_chunk_strf_auds_t    *p_avi_strf_auds;
1138 #define p_stream  p_avi->pp_info[i]
1139
1140         if( p_stream->i_cat != AUDIO_ES )
1141         {
1142             continue;
1143         }
1144         if( p_stream->i_idxnb < 1 ||
1145             p_stream->i_scale != 1 ||
1146             p_stream->i_samplesize != 0 )
1147         {
1148             continue;
1149         }
1150         p_avi_strl = (avi_chunk_list_t*)AVI_ChunkFind( p_hdrl,
1151                                                        AVIFOURCC_strl, i );
1152         p_avi_strh = (avi_chunk_strh_t*)AVI_ChunkFind( p_avi_strl,
1153                                                        AVIFOURCC_strh, 0 );
1154         p_avi_strf_auds =
1155             (avi_chunk_strf_auds_t*)AVI_ChunkFind( p_avi_strl,
1156                                                    AVIFOURCC_strf, 0 );
1157
1158         if( p_avi_strf_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
1159             (unsigned int)p_stream->i_rate == p_avi_strf_auds->p_wf->nSamplesPerSec )
1160         {
1161             int64_t i_track_length =
1162                 p_stream->p_index[p_stream->i_idxnb-1].i_length +
1163                 p_stream->p_index[p_stream->i_idxnb-1].i_lengthtotal;
1164             mtime_t i_length = (mtime_t)p_avih->i_totalframes *
1165                                (mtime_t)p_avih->i_microsecperframe;
1166
1167             if( i_length == 0 )
1168             {
1169                 msg_Warn( p_input, "track[%d] cannot be fixed (BeOS MediaKit generated)", i );
1170                 continue;
1171             }
1172             p_stream->i_samplesize = 1;
1173             p_stream->i_rate       = i_track_length  * (int64_t)1000000/ i_length;
1174             msg_Warn( p_input, "track[%d] fixed with rate=%d scale=%d (BeOS MediaKit generated)", i, p_stream->i_rate, p_stream->i_scale );
1175         }
1176 #undef p_stream
1177     }
1178
1179     vlc_mutex_lock( &p_input->stream.stream_lock );
1180     if( p_avi->i_length )
1181     {
1182         p_input->stream.i_mux_rate =
1183             p_input->stream.p_selected_area->i_size / 50 / p_avi->i_length;
1184     }
1185     else
1186     {
1187         p_input->stream.i_mux_rate = 0;
1188     }
1189     vlc_mutex_unlock( &p_input->stream.stream_lock );
1190
1191     b_stream_audio = VLC_FALSE;
1192     b_stream_video = VLC_FALSE;
1193
1194     for( i = 0; i < p_avi->i_streams; i++ )
1195     {
1196 #define p_info  p_avi->pp_info[i]
1197         switch( p_info->p_es->i_cat )
1198         {
1199             case( VIDEO_ES ):
1200
1201                 if( !b_stream_video )
1202                 {
1203                     b_stream_video = AVI_StreamStart( p_input, p_avi, i );
1204                 }
1205                 break;
1206
1207             case( AUDIO_ES ):
1208                 if( !b_stream_audio )
1209                 {
1210                     b_stream_audio = AVI_StreamStart( p_input, p_avi, i );
1211                 }
1212                 break;
1213             default:
1214                 break;
1215         }
1216 #undef p_info
1217     }
1218
1219     if( !b_stream_video )
1220     {
1221         msg_Warn( p_input, "no video stream found" );
1222     }
1223     if( !b_stream_audio )
1224     {
1225         msg_Warn( p_input, "no audio stream found!" );
1226     }
1227
1228     vlc_mutex_lock( &p_input->stream.stream_lock );
1229     p_input->stream.p_selected_program->b_is_ok = 1;
1230     vlc_mutex_unlock( &p_input->stream.stream_lock );
1231
1232     if( p_avi->b_seekable )
1233     {
1234         AVI_ChunkGoto( p_input, p_movi );
1235     }
1236     else
1237     {
1238         // already at begining of p_movi
1239     }
1240     AVI_SkipBytes( p_input, 12 ); // enter in p_movi
1241
1242     p_avi->i_movi_begin = p_movi->i_chunk_pos;
1243     return VLC_SUCCESS;
1244 }
1245
1246
1247
1248
1249 /*****************************************************************************
1250  * Function to convert pts to chunk or byte
1251  *****************************************************************************/
1252
1253 static inline mtime_t AVI_PTSToChunk( avi_stream_t *p_info,
1254                                         mtime_t i_pts )
1255 {
1256     return (mtime_t)((int64_t)i_pts *
1257                      (int64_t)p_info->i_rate /
1258                      (int64_t)p_info->i_scale /
1259                      (int64_t)1000000 );
1260 }
1261 static inline mtime_t AVI_PTSToByte( avi_stream_t *p_info,
1262                                        mtime_t i_pts )
1263 {
1264     return (mtime_t)((int64_t)i_pts *
1265                      (int64_t)p_info->i_rate /
1266                      (int64_t)p_info->i_scale /
1267                      (int64_t)1000000 *
1268                      (int64_t)p_info->i_samplesize );
1269 }
1270
1271 static mtime_t AVI_GetDPTS( avi_stream_t *p_stream, int i_count )
1272 {
1273     if( p_stream->i_samplesize )
1274     {
1275         return (mtime_t)( (int64_t)1000000 *
1276                    (int64_t)i_count *
1277                    (int64_t)p_stream->i_scale /
1278                    (int64_t)p_stream->i_rate /
1279                    (int64_t)p_stream->i_samplesize );
1280     }
1281     else
1282     {
1283         return (mtime_t)( (int64_t)1000000 *
1284                    (int64_t)i_count *
1285                    (int64_t)p_stream->i_scale /
1286                    (int64_t)p_stream->i_rate);
1287     }
1288
1289 }
1290
1291 static mtime_t AVI_GetPTS( avi_stream_t *p_info )
1292 {
1293
1294     if( p_info->i_samplesize )
1295     {
1296         /* we need a valid entry we will emulate one */
1297         int64_t i_len;
1298         if( p_info->i_idxposc == p_info->i_idxnb )
1299         {
1300             if( p_info->i_idxposc )
1301             {
1302                 /* use the last entry */
1303                 i_len = p_info->p_index[p_info->i_idxnb - 1].i_lengthtotal
1304                             + p_info->p_index[p_info->i_idxnb - 1].i_length
1305                             + p_info->i_idxposb; /* should be 0 */
1306             }
1307             else
1308             {
1309                 i_len = p_info->i_idxposb;
1310                 /* no valid entry use only offset*/
1311             }
1312         }
1313         else
1314         {
1315             i_len = p_info->p_index[p_info->i_idxposc].i_lengthtotal
1316                                 + p_info->i_idxposb;
1317         }
1318         return (mtime_t)( (int64_t)1000000 *
1319                   (int64_t)i_len *
1320                    (int64_t)p_info->i_scale /
1321                    (int64_t)p_info->i_rate /
1322                    (int64_t)p_info->i_samplesize );
1323     }
1324     else
1325     {
1326         /* even if p_info->i_idxposc isn't valid, there isn't any problem */
1327         return (mtime_t)( (int64_t)1000000 *
1328                    (int64_t)(p_info->i_idxposc ) *
1329                    (int64_t)p_info->i_scale /
1330                    (int64_t)p_info->i_rate);
1331     }
1332 }
1333
1334 static int AVI_StreamChunkFind( input_thread_t *p_input,
1335                                 unsigned int i_stream )
1336 {
1337     demux_sys_t *p_avi = p_input->p_demux_data;
1338     avi_packet_t avi_pk;
1339
1340     /* find first chunk of i_stream that isn't in index */
1341
1342     if( p_avi->i_movi_lastchunk_pos >= p_avi->i_movi_begin )
1343     {
1344         AVI_SeekAbsolute( p_input, p_avi->i_movi_lastchunk_pos );
1345         if( AVI_PacketNext( p_input ) )
1346         {
1347             return VLC_EGENERIC;
1348         }
1349     }
1350     else
1351     {
1352         AVI_SeekAbsolute( p_input, p_avi->i_movi_begin );
1353     }
1354
1355     for( ;; )
1356     {
1357
1358         if( AVI_PacketGetHeader( p_input, &avi_pk ) )
1359         {
1360             msg_Warn( p_input, "cannot get packet header" );
1361             return VLC_EGENERIC;
1362         }
1363         if( avi_pk.i_stream >= p_avi->i_streams ||
1364             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1365         {
1366             switch( avi_pk.i_fourcc )
1367             {
1368                 case AVIFOURCC_LIST:
1369                     AVI_SkipBytes( p_input, 12 );
1370                     break;
1371                 default:
1372                     if( AVI_PacketNext( p_input ) )
1373                     {
1374                         return VLC_EGENERIC;
1375                     }
1376                     break;
1377             }
1378         }
1379         else
1380         {
1381             /* add this chunk to the index */
1382             AVIIndexEntry_t index;
1383
1384             index.i_id = avi_pk.i_fourcc;
1385             index.i_flags =
1386                AVI_GetKeyFlag(p_avi->pp_info[avi_pk.i_stream]->i_codec,
1387                               avi_pk.i_peek);
1388             index.i_pos = avi_pk.i_pos;
1389             index.i_length = avi_pk.i_size;
1390             AVI_IndexAddEntry( p_avi, avi_pk.i_stream, &index );
1391
1392             if( avi_pk.i_stream == i_stream  )
1393             {
1394                 return VLC_SUCCESS;
1395             }
1396
1397             if( AVI_PacketNext( p_input ) )
1398             {
1399                 return VLC_EGENERIC;
1400             }
1401         }
1402     }
1403 }
1404
1405
1406 /* be sure that i_ck will be a valid index entry */
1407 static int AVI_SetStreamChunk( input_thread_t    *p_input,
1408                                unsigned int i_stream,
1409                                unsigned int i_ck )
1410 {
1411     demux_sys_t *p_avi = p_input->p_demux_data;
1412     avi_stream_t *p_stream = p_avi->pp_info[i_stream];
1413
1414     p_stream->i_idxposc = i_ck;
1415     p_stream->i_idxposb = 0;
1416
1417     if(  i_ck >= p_stream->i_idxnb )
1418     {
1419         p_stream->i_idxposc = p_stream->i_idxnb - 1;
1420         do
1421         {
1422             p_stream->i_idxposc++;
1423             if( AVI_StreamChunkFind( p_input, i_stream ) )
1424             {
1425                 return VLC_EGENERIC;
1426             }
1427
1428         } while( p_stream->i_idxposc < i_ck );
1429     }
1430
1431     return VLC_SUCCESS;
1432 }
1433
1434
1435 /* XXX FIXME up to now, we assume that all chunk are one after one */
1436 static int AVI_SetStreamBytes( input_thread_t    *p_input,
1437                                unsigned int i_stream,
1438                                off_t   i_byte )
1439 {
1440     demux_sys_t *p_avi = p_input->p_demux_data;
1441     avi_stream_t *p_stream = p_avi->pp_info[i_stream];
1442
1443     if( ( p_stream->i_idxnb > 0 )
1444         &&( i_byte < p_stream->p_index[p_stream->i_idxnb - 1].i_lengthtotal +
1445                 p_stream->p_index[p_stream->i_idxnb - 1].i_length ) )
1446     {
1447         /* index is valid to find the ck */
1448         /* uses dichototmie to be fast enougth */
1449         int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->i_idxnb - 1 );
1450         int i_idxmax  = p_stream->i_idxnb;
1451         int i_idxmin  = 0;
1452         for( ;; )
1453         {
1454             if( p_stream->p_index[i_idxposc].i_lengthtotal > i_byte )
1455             {
1456                 i_idxmax  = i_idxposc ;
1457                 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1458             }
1459             else
1460             {
1461                 if( p_stream->p_index[i_idxposc].i_lengthtotal +
1462                         p_stream->p_index[i_idxposc].i_length <= i_byte)
1463                 {
1464                     i_idxmin  = i_idxposc ;
1465                     i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1466                 }
1467                 else
1468                 {
1469                     p_stream->i_idxposc = i_idxposc;
1470                     p_stream->i_idxposb = i_byte -
1471                             p_stream->p_index[i_idxposc].i_lengthtotal;
1472                     return VLC_SUCCESS;
1473                 }
1474             }
1475         }
1476
1477     }
1478     else
1479     {
1480         p_stream->i_idxposc = p_stream->i_idxnb - 1;
1481         p_stream->i_idxposb = 0;
1482         do
1483         {
1484             p_stream->i_idxposc++;
1485             if( AVI_StreamChunkFind( p_input, i_stream ) )
1486             {
1487                 return VLC_EGENERIC;
1488             }
1489
1490         } while( p_stream->p_index[p_stream->i_idxposc].i_lengthtotal +
1491                     p_stream->p_index[p_stream->i_idxposc].i_length <= i_byte );
1492
1493         p_stream->i_idxposb = i_byte -
1494                        p_stream->p_index[p_stream->i_idxposc].i_lengthtotal;
1495         return VLC_SUCCESS;
1496     }
1497 }
1498
1499 static int AVI_StreamSeek( input_thread_t *p_input,
1500                            demux_sys_t  *p_avi,
1501                            int i_stream,
1502                            mtime_t i_date )
1503 {
1504 #define p_stream    p_avi->pp_info[i_stream]
1505     mtime_t i_oldpts;
1506
1507     i_oldpts = AVI_GetPTS( p_stream );
1508
1509     if( !p_stream->i_samplesize )
1510     {
1511         if( AVI_SetStreamChunk( p_input,
1512                                 i_stream,
1513                                 AVI_PTSToChunk( p_stream, i_date ) ) )
1514         {
1515             return VLC_EGENERIC;
1516         }
1517
1518         /* search key frame */
1519         msg_Dbg( p_input,
1520                  "old:"I64Fd" %s new "I64Fd,
1521                  i_oldpts,
1522                  i_oldpts > i_date ? ">" : "<",
1523                  i_date );
1524
1525         if( i_date < i_oldpts )
1526         {
1527             while( p_stream->i_idxposc > 0 &&
1528                !( p_stream->p_index[p_stream->i_idxposc].i_flags &
1529                                                             AVIIF_KEYFRAME ) )
1530             {
1531                 if( AVI_SetStreamChunk( p_input,
1532                                         i_stream,
1533                                         p_stream->i_idxposc - 1 ) )
1534                 {
1535                     return VLC_EGENERIC;
1536                 }
1537             }
1538         }
1539         else
1540         {
1541             while( p_stream->i_idxposc < p_stream->i_idxnb &&
1542                     !( p_stream->p_index[p_stream->i_idxposc].i_flags &
1543                                                             AVIIF_KEYFRAME ) )
1544             {
1545                 if( AVI_SetStreamChunk( p_input,
1546                                         i_stream,
1547                                         p_stream->i_idxposc + 1 ) )
1548                 {
1549                     return VLC_EGENERIC;
1550                 }
1551             }
1552         }
1553     }
1554     else
1555     {
1556         if( AVI_SetStreamBytes( p_input,
1557                                 i_stream,
1558                                 AVI_PTSToByte( p_stream, i_date ) ) )
1559         {
1560             return VLC_EGENERIC;
1561         }
1562     }
1563     return VLC_SUCCESS;
1564 #undef p_stream
1565 }
1566
1567 /*****************************************************************************
1568  * AVISeek: goto to i_date or i_percent
1569  *****************************************************************************
1570  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1571  *****************************************************************************/
1572 static int    AVISeek   ( input_thread_t *p_input,
1573                           mtime_t i_date, int i_percent )
1574 {
1575
1576     demux_sys_t *p_avi = p_input->p_demux_data;
1577     unsigned int i_stream;
1578     msg_Dbg( p_input,
1579              "seek requested: "I64Fd" secondes %d%%",
1580              i_date / 1000000,
1581              i_percent );
1582
1583     if( p_avi->b_seekable )
1584     {
1585         if( !p_avi->i_length )
1586         {
1587             avi_stream_t *p_stream;
1588             uint64_t i_pos;
1589
1590             /* use i_percent to create a true i_date */
1591             msg_Warn( p_input,
1592                       "mmh, seeking without index at %d%%"
1593                       " work only for interleaved file", i_percent );
1594
1595             if( i_percent >= 100 )
1596             {
1597                 msg_Warn( p_input, "cannot seek so far !" );
1598                 return( -1 );
1599             }
1600             i_percent = __MAX( i_percent, 0 );
1601
1602             /* try to find chunk that is at i_percent or the file */
1603             i_pos = __MAX( i_percent *
1604                            p_input->stream.p_selected_area->i_size / 100,
1605                            p_avi->i_movi_begin );
1606             /* search first selected stream */
1607             for( i_stream = 0, p_stream = NULL;
1608                         i_stream < p_avi->i_streams; i_stream++ )
1609             {
1610                 p_stream = p_avi->pp_info[i_stream];
1611                 if( p_stream->b_activated )
1612                 {
1613                     break;
1614                 }
1615             }
1616             if( !p_stream || !p_stream->b_activated )
1617             {
1618                 msg_Warn( p_input, "cannot find any selected stream" );
1619                 return( -1 );
1620             }
1621
1622             /* be sure that the index exit */
1623             if( AVI_SetStreamChunk( p_input,
1624                                     i_stream,
1625                                     0 ) )
1626             {
1627                 msg_Warn( p_input, "cannot seek" );
1628                 return( -1 );
1629             }
1630
1631             while( i_pos >= p_stream->p_index[p_stream->i_idxposc].i_pos +
1632                p_stream->p_index[p_stream->i_idxposc].i_length + 8 )
1633             {
1634                 /* search after i_idxposc */
1635                 if( AVI_SetStreamChunk( p_input,
1636                                         i_stream, p_stream->i_idxposc + 1 ) )
1637                 {
1638                     msg_Warn( p_input, "cannot seek" );
1639                     return( -1 );
1640                 }
1641             }
1642             i_date = AVI_GetPTS( p_stream );
1643             /* TODO better support for i_samplesize != 0 */
1644             msg_Dbg( p_input, "estimate date "I64Fd, i_date );
1645         }
1646
1647 #define p_stream    p_avi->pp_info[i_stream]
1648         p_avi->i_time = 0;
1649         /* seek for chunk based streams */
1650         for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
1651         {
1652             if( p_stream->b_activated && !p_stream->i_samplesize )
1653 //            if( p_stream->b_activated )
1654             {
1655                 AVI_StreamSeek( p_input, p_avi, i_stream, i_date );
1656                 p_avi->i_time = __MAX( AVI_GetPTS( p_stream ),
1657                                         p_avi->i_time );
1658             }
1659         }
1660 #if 1
1661         if( p_avi->i_time )
1662         {
1663             i_date = p_avi->i_time;
1664         }
1665         /* seek for bytes based streams */
1666         for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
1667         {
1668             if( p_stream->b_activated && p_stream->i_samplesize )
1669             {
1670                 AVI_StreamSeek( p_input, p_avi, i_stream, i_date );
1671 //                p_avi->i_time = __MAX( AVI_GetPTS( p_stream ), p_avi->i_time );
1672             }
1673         }
1674         msg_Dbg( p_input, "seek: "I64Fd" secondes", p_avi->i_time /1000000 );
1675         /* set true movie time */
1676 #endif
1677         if( !p_avi->i_time )
1678         {
1679             p_avi->i_time = i_date;
1680         }
1681 #undef p_stream
1682         return( 1 );
1683     }
1684     else
1685     {
1686         msg_Err( p_input, "shouldn't yet be executed" );
1687         return( -1 );
1688     }
1689 }
1690
1691 #if 0
1692 static pes_packet_t *PES_split( input_thread_t *p_input, avi_stream_t *p_stream, pes_packet_t *p_pes )
1693 {
1694     pes_packet_t  *p_pes2;
1695     data_packet_t *p_data;
1696     int           i_nb_data;
1697
1698     if( p_pes->i_nb_data < 2 )
1699     {
1700         return( NULL );
1701     }
1702     p_pes2 = input_NewPES( p_input->p_method_data );
1703     p_pes2->i_pts = p_pes->i_pts;
1704     p_pes2->i_dts = p_pes->i_dts;
1705     p_pes2->i_nb_data = p_pes->i_nb_data/2;
1706     p_pes2->i_pes_size = 0;
1707     for( i_nb_data = 0, p_data = p_pes->p_first;
1708          i_nb_data < p_pes2->i_nb_data;
1709          i_nb_data++, p_data = p_data->p_next )
1710     {
1711         p_pes2->i_pes_size +=
1712             p_data->p_payload_end - p_data->p_payload_start;
1713         p_pes2->p_last = p_data;
1714     }
1715     p_pes2->p_first = p_pes->p_first;
1716     p_pes2->p_last->p_next = NULL;
1717
1718     p_pes->p_first = p_data;
1719     p_pes->i_pes_size -= p_pes2->i_pes_size;
1720     p_pes->i_nb_data -= p_pes2->i_nb_data;
1721 //    p_pes->i_pts += AVI_GetDPTS( p_stream, p_pes2->i_pes_size );
1722 //    p_pes->i_dts += AVI_GetDPTS( p_stream, p_pes2->i_pes_size );
1723     p_pes->i_pts = 0;
1724     p_pes->i_dts = 0;
1725     return( p_pes2 );
1726 }
1727 #endif
1728
1729 /*****************************************************************************
1730  * AVIDemux_Seekable: reads and demuxes data packets for stream seekable
1731  *****************************************************************************
1732  * AVIDemux: reads and demuxes data packets
1733  *****************************************************************************
1734  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1735  *****************************************************************************/
1736 typedef struct avi_stream_toread_s
1737 {
1738     vlc_bool_t b_ok;
1739
1740     int i_toread;
1741
1742     off_t i_posf; // where we will read :
1743                   // if i_idxposb == 0 : begining of chunk (+8 to acces data)
1744                   // else : point on data directly
1745 } avi_stream_toread_t;
1746
1747 static int AVIDemux_Seekable( input_thread_t *p_input )
1748 {
1749     unsigned int i_stream_count;
1750     unsigned int i_stream;
1751     vlc_bool_t b_stream;
1752     vlc_bool_t b_play_audio;
1753     vlc_bool_t b_video; /* is there some video track selected */
1754     // cannot be more than 100 stream (dcXX or wbXX)
1755     avi_stream_toread_t toread[100];
1756
1757     demux_sys_t *p_avi = p_input->p_demux_data;
1758
1759
1760     /* detect new selected/unselected streams */
1761     for( i_stream = 0,i_stream_count= 0, b_video = VLC_FALSE;
1762             i_stream < p_avi->i_streams; i_stream++ )
1763     {
1764 #define p_stream    p_avi->pp_info[i_stream]
1765         if( p_stream->p_es )
1766         {
1767             if( p_stream->p_es->p_decoder_fifo &&
1768                 !p_stream->b_activated )
1769             {
1770                 AVI_StreamStart( p_input, p_avi, i_stream );
1771             }
1772             else
1773             if( !p_stream->p_es->p_decoder_fifo &&
1774                 p_stream->b_activated )
1775             {
1776                 AVI_StreamStop( p_input, p_avi, i_stream );
1777             }
1778         }
1779         if( p_stream->b_activated )
1780         {
1781             i_stream_count++;
1782             if( p_stream->i_cat == VIDEO_ES )
1783             {
1784                 b_video = VLC_TRUE;
1785             }
1786         }
1787 #undef  p_stream
1788     }
1789
1790     if( i_stream_count <= 0 )
1791     {
1792         msg_Warn( p_input, "no track selected, exiting..." );
1793         return( 0 );
1794     }
1795
1796     if( p_input->stream.p_selected_program->i_synchro_state == SYNCHRO_REINIT )
1797     {
1798         mtime_t i_date;
1799         int i_percent;
1800         /* first wait for empty buffer, arbitrary time FIXME */
1801         //msleep( DEFAULT_PTS_DELAY );
1802
1803         i_date = (mtime_t)1000000 *
1804                  (mtime_t)p_avi->i_length *
1805                  (mtime_t)AVI_TellAbsolute( p_input ) /
1806                  (mtime_t)p_input->stream.p_selected_area->i_size;
1807         i_percent = 100 * AVI_TellAbsolute( p_input ) /
1808                         p_input->stream.p_selected_area->i_size;
1809
1810 //        input_ClockInit( p_input->stream.p_selected_program );
1811         AVISeek( p_input, i_date, i_percent);
1812
1813 #ifdef __AVI_SUBTITLE__
1814         if( p_avi->p_sub )
1815         {
1816             subtitle_Seek( p_avi->p_sub, p_avi->i_time );
1817         }
1818 #endif
1819     }
1820
1821
1822     /* wait for the good time */
1823
1824     p_avi->i_pcr = p_avi->i_time * 9 / 100;
1825
1826     input_ClockManageRef( p_input,
1827                           p_input->stream.p_selected_program,
1828                           p_avi->i_pcr );
1829
1830
1831     p_avi->i_time += 25*1000;  /* read 25ms */
1832
1833 #ifdef __AVI_SUBTITLE__
1834     if( p_avi->p_sub )
1835     {
1836         subtitle_Demux( p_avi->p_sub, p_avi->i_time );
1837     }
1838 #endif
1839
1840     /* *** send audio data to decoder if rate == DEFAULT_RATE or no video *** */
1841     vlc_mutex_lock( &p_input->stream.stream_lock );
1842     if( p_input->stream.control.i_rate == DEFAULT_RATE || !b_video )
1843     {
1844         b_play_audio = VLC_TRUE;
1845     }
1846     else
1847     {
1848         b_play_audio = VLC_FALSE;
1849     }
1850     vlc_mutex_unlock( &p_input->stream.stream_lock );
1851
1852     /* init toread */
1853     for( i_stream = 0; i_stream < p_avi->i_streams; i_stream++ )
1854     {
1855 #define p_stream    p_avi->pp_info[i_stream]
1856         mtime_t i_dpts;
1857
1858         toread[i_stream].b_ok = p_stream->b_activated;
1859         if( p_stream->i_idxposc < p_stream->i_idxnb )
1860         {
1861             toread[i_stream].i_posf =
1862                 p_stream->p_index[p_stream->i_idxposc].i_pos;
1863            if( p_stream->i_idxposb > 0 )
1864            {
1865                 toread[i_stream].i_posf += 8 + p_stream->i_idxposb;
1866            }
1867         }
1868         else
1869         {
1870             toread[i_stream].i_posf = -1;
1871         }
1872
1873         i_dpts = p_avi->i_time - AVI_GetPTS( p_stream  );
1874
1875         if( p_stream->i_samplesize )
1876         {
1877             toread[i_stream].i_toread = AVI_PTSToByte( p_stream,
1878                                                        __ABS( i_dpts ) );
1879         }
1880         else
1881         {
1882             toread[i_stream].i_toread = AVI_PTSToChunk( p_stream,
1883                                                         __ABS( i_dpts ) );
1884         }
1885
1886         if( i_dpts < 0 )
1887         {
1888             toread[i_stream].i_toread *= -1;
1889         }
1890 #undef  p_stream
1891     }
1892
1893     b_stream = VLC_FALSE;
1894
1895     for( ;; )
1896     {
1897 #define p_stream    p_avi->pp_info[i_stream]
1898         vlc_bool_t       b_done;
1899         pes_packet_t    *p_pes;
1900         off_t i_pos;
1901         unsigned int i;
1902         size_t i_size;
1903
1904         /* search for first chunk to be read */
1905         for( i = 0, b_done = VLC_TRUE, i_pos = -1; i < p_avi->i_streams; i++ )
1906         {
1907             if( !toread[i].b_ok ||
1908                 AVI_GetDPTS( p_avi->pp_info[i],
1909                              toread[i].i_toread ) <= -25 * 1000 )
1910             {
1911                 continue;
1912             }
1913
1914             if( toread[i].i_toread > 0 )
1915             {
1916                 b_done = VLC_FALSE; // not yet finished
1917             }
1918
1919             if( toread[i].i_posf > 0 )
1920             {
1921                 if( i_pos == -1 || i_pos > toread[i_stream].i_posf )
1922                 {
1923                     i_stream = i;
1924                     i_pos = toread[i].i_posf;
1925                 }
1926             }
1927         }
1928
1929         if( b_done )
1930         {
1931 //            return( b_stream ? 1 : 0 );
1932             return( 1 );
1933         }
1934
1935         if( i_pos == -1 )
1936         {
1937             /* no valid index, we will parse directly the stream
1938              * in case we fail we will disable all finished stream */
1939             if( p_avi->i_movi_lastchunk_pos >= p_avi->i_movi_begin )
1940             {
1941                 AVI_SeekAbsolute( p_input, p_avi->i_movi_lastchunk_pos );
1942                 if( AVI_PacketNext( p_input ) )
1943                 {
1944                     return( AVI_StreamStopFinishedStreams( p_input, p_avi ) ? 0 : 1 );
1945                 }
1946             }
1947             else
1948             {
1949                 AVI_SeekAbsolute( p_input, p_avi->i_movi_begin );
1950             }
1951
1952             for( ;; )
1953             {
1954                 avi_packet_t avi_pk;
1955
1956                 if( AVI_PacketGetHeader( p_input, &avi_pk ) )
1957                 {
1958                     msg_Warn( p_input,
1959                              "cannot get packet header, track disabled" );
1960                     return( AVI_StreamStopFinishedStreams( p_input, p_avi ) ? 0 : 1 );
1961                 }
1962                 if( avi_pk.i_stream >= p_avi->i_streams ||
1963                     ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1964                 {
1965                     switch( avi_pk.i_fourcc )
1966                     {
1967                         case AVIFOURCC_LIST:
1968                             AVI_SkipBytes( p_input, 12 );
1969                             break;
1970                         default:
1971                             if( AVI_PacketNext( p_input ) )
1972                             {
1973                                 msg_Warn( p_input,
1974                                           "cannot skip packet, track disabled" );
1975                                 return( AVI_StreamStopFinishedStreams( p_input, p_avi ) ? 0 : 1 );
1976                             }
1977                             break;
1978                     }
1979                     continue;
1980                 }
1981                 else
1982                 {
1983                     /* add this chunk to the index */
1984                     AVIIndexEntry_t index;
1985
1986                     index.i_id = avi_pk.i_fourcc;
1987                     index.i_flags =
1988                        AVI_GetKeyFlag(p_avi->pp_info[avi_pk.i_stream]->i_codec,
1989                                       avi_pk.i_peek);
1990                     index.i_pos = avi_pk.i_pos;
1991                     index.i_length = avi_pk.i_size;
1992                     AVI_IndexAddEntry( p_avi, avi_pk.i_stream, &index );
1993
1994                     i_stream = avi_pk.i_stream;
1995                     /* do we will read this data ? */
1996                     if( AVI_GetDPTS( p_stream,
1997                              toread[i_stream].i_toread ) > -25 * 1000 )
1998                     {
1999                         break;
2000                     }
2001                     else
2002                     {
2003                         if( AVI_PacketNext( p_input ) )
2004                         {
2005                             msg_Warn( p_input,
2006                                       "cannot skip packet, track disabled" );
2007                             return( AVI_StreamStopFinishedStreams( p_input, p_avi ) ? 0 : 1 );
2008                         }
2009                     }
2010                 }
2011             }
2012
2013         }
2014         else
2015         {
2016             AVI_SeekAbsolute( p_input, i_pos );
2017         }
2018
2019         /* read thoses data */
2020         if( p_stream->i_samplesize )
2021         {
2022             unsigned int i_toread;
2023
2024             if( ( i_toread = toread[i_stream].i_toread ) <= 0 )
2025             {
2026                 if( p_stream->i_samplesize > 1 )
2027                 {
2028                     i_toread = p_stream->i_samplesize;
2029                 }
2030                 else
2031                 {
2032                     i_toread = __MAX( AVI_PTSToByte( p_stream, 20 * 1000 ), 100 );
2033                 }
2034             }
2035             i_size = __MIN( p_stream->p_index[p_stream->i_idxposc].i_length -
2036                                 p_stream->i_idxposb,
2037                             i_toread );
2038         }
2039         else
2040         {
2041             i_size = p_stream->p_index[p_stream->i_idxposc].i_length;
2042         }
2043
2044         if( p_stream->i_idxposb == 0 )
2045         {
2046             i_size += 8; // need to read and skip header
2047         }
2048
2049         if( input_ReadInPES( p_input, &p_pes, __EVEN( i_size ) ) < 0 )
2050         {
2051             msg_Warn( p_input, "failled reading data" );
2052             AVI_StreamStop( p_input, p_avi, i_stream );
2053             toread[i_stream].b_ok = VLC_FALSE;
2054             continue;
2055         }
2056
2057         if( i_size % 2 )    // read was padded on word boundary
2058         {
2059             p_pes->p_last->p_payload_end--;
2060             p_pes->i_pes_size--;
2061         }
2062         // skip header
2063         if( p_stream->i_idxposb == 0 )
2064         {
2065             p_pes->p_first->p_payload_start += 8;
2066             p_pes->i_pes_size -= 8;
2067         }
2068
2069         p_pes->i_pts = AVI_GetPTS( p_stream );
2070
2071         /* read data */
2072         if( p_stream->i_samplesize )
2073         {
2074             if( p_stream->i_idxposb == 0 )
2075             {
2076                 i_size -= 8;
2077             }
2078             toread[i_stream].i_toread -= i_size;
2079             p_stream->i_idxposb += i_size;
2080             if( p_stream->i_idxposb >=
2081                     p_stream->p_index[p_stream->i_idxposc].i_length )
2082             {
2083                 p_stream->i_idxposb = 0;
2084                 p_stream->i_idxposc++;
2085             }
2086         }
2087         else
2088         {
2089             toread[i_stream].i_toread--;
2090             p_stream->i_idxposc++;
2091         }
2092
2093         if( p_stream->i_idxposc < p_stream->i_idxnb)
2094         {
2095             toread[i_stream].i_posf =
2096                 p_stream->p_index[p_stream->i_idxposc].i_pos;
2097             if( p_stream->i_idxposb > 0 )
2098             {
2099                 toread[i_stream].i_posf += 8 + p_stream->i_idxposb;
2100             }
2101
2102         }
2103         else
2104         {
2105             toread[i_stream].i_posf = -1;
2106         }
2107
2108         b_stream = VLC_TRUE; // at least one read succeed
2109
2110         if( p_stream->p_es && p_stream->p_es->p_decoder_fifo &&
2111             ( b_play_audio || p_stream->i_cat != AUDIO_ES ) )
2112         {
2113             p_pes->i_dts =
2114                 p_pes->i_pts =
2115                     input_ClockGetTS( p_input,
2116                                       p_input->stream.p_selected_program,
2117                                       p_pes->i_pts * 9/100);
2118
2119             input_DecodePES( p_stream->p_es->p_decoder_fifo, p_pes );
2120         }
2121         else
2122         {
2123             input_DeletePES( p_input->p_method_data, p_pes );
2124         }
2125     }
2126 }
2127
2128
2129 /*****************************************************************************
2130  * AVIDemux_UnSeekable: reads and demuxes data packets for unseekable file
2131  *****************************************************************************
2132  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2133  *****************************************************************************/
2134 static int AVIDemux_UnSeekable( input_thread_t *p_input )
2135 {
2136     demux_sys_t     *p_avi = p_input->p_demux_data;
2137     avi_stream_t *p_stream_master;
2138     vlc_bool_t b_audio;
2139     unsigned int i_stream;
2140     unsigned int i_packet;
2141
2142     /* *** send audio data to decoder only if rate == DEFAULT_RATE *** */
2143     vlc_mutex_lock( &p_input->stream.stream_lock );
2144     b_audio = p_input->stream.control.i_rate == DEFAULT_RATE;
2145     vlc_mutex_unlock( &p_input->stream.stream_lock );
2146
2147     input_ClockManageRef( p_input,
2148                           p_input->stream.p_selected_program,
2149                           p_avi->i_pcr );
2150     /* *** find master stream for data packet skipping algo *** */
2151     /* *** -> first video, if any, or first audio ES *** */
2152     for( i_stream = 0, p_stream_master = NULL;
2153             i_stream < p_avi->i_streams; i_stream++ )
2154     {
2155 #define p_stream    p_avi->pp_info[i_stream]
2156         if( p_stream->p_es &&
2157             p_stream->p_es->p_decoder_fifo )
2158         {
2159             if( p_stream->i_cat == VIDEO_ES )
2160             {
2161                 p_stream_master = p_stream;
2162                 break;
2163             }
2164             if( p_stream->i_cat == AUDIO_ES && !p_stream_master )
2165             {
2166                 p_stream_master = p_stream;
2167             }
2168         }
2169 #undef p_stream
2170     }
2171     if( !p_stream_master )
2172     {
2173         msg_Warn( p_input, "no more stream selected" );
2174         return( 0 );
2175     }
2176
2177     p_avi->i_pcr = AVI_GetPTS( p_stream_master ) * 9 / 100;
2178
2179     for( i_packet = 0; i_packet < 10; i_packet++)
2180     {
2181 #define p_stream    p_avi->pp_info[avi_pk.i_stream]
2182
2183         avi_packet_t    avi_pk;
2184
2185         if( AVI_PacketGetHeader( p_input, &avi_pk ) )
2186         {
2187             return( 0 );
2188         }
2189 //        AVI_ParseStreamHeader( avi_pk.i_fourcc, &i_stream, &i_cat );
2190
2191         if( avi_pk.i_stream >= p_avi->i_streams ||
2192             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
2193         {
2194             /* we haven't found an audio or video packet:
2195              *  - we have seek, found first next packet
2196              *  - others packets could be found, skip them
2197              */
2198             switch( avi_pk.i_fourcc )
2199             {
2200                 case AVIFOURCC_JUNK:
2201                 case AVIFOURCC_LIST:
2202                     return( !AVI_PacketNext( p_input ) ? 1 : 0 );
2203                 case AVIFOURCC_idx1:
2204                     return( 0 );    // eof
2205                 default:
2206                     msg_Warn( p_input,
2207                               "seems to have lost position, resync" );
2208                     if( AVI_PacketSearch( p_input ) )
2209                     {
2210                         msg_Err( p_input, "resync failed" );
2211                         return( -1 );
2212                     }
2213             }
2214         }
2215         else
2216         {
2217             /* do will send this packet to decoder ? */
2218             if( ( !b_audio && avi_pk.i_cat == AUDIO_ES )||
2219                 !p_stream->p_es ||
2220                 !p_stream->p_es->p_decoder_fifo )
2221             {
2222                 if( AVI_PacketNext( p_input ) )
2223                 {
2224                     return( 0 );
2225                 }
2226             }
2227             else
2228             {
2229                 /* it's a selected stream, check for time */
2230                 if( __ABS( AVI_GetPTS( p_stream ) -
2231                             AVI_GetPTS( p_stream_master ) )< 600*1000 )
2232                 {
2233                     /* load it and send to decoder */
2234                     pes_packet_t    *p_pes;
2235                     if( AVI_PacketRead( p_input, &avi_pk, &p_pes ) || !p_pes)
2236                     {
2237                         return( -1 );
2238                     }
2239                     p_pes->i_dts =
2240                         p_pes->i_pts =
2241                             input_ClockGetTS( p_input,
2242                                           p_input->stream.p_selected_program,
2243                                           AVI_GetPTS( p_stream ) * 9/100);
2244                     input_DecodePES( p_stream->p_es->p_decoder_fifo, p_pes );
2245                 }
2246                 else
2247                 {
2248                     if( AVI_PacketNext( p_input ) )
2249                     {
2250                         return( 0 );
2251                     }
2252                 }
2253             }
2254
2255             /* *** update stream time position *** */
2256             if( p_stream->i_samplesize )
2257             {
2258                 p_stream->i_idxposb += avi_pk.i_size;
2259             }
2260             else
2261             {
2262                 p_stream->i_idxposc++;
2263             }
2264
2265         }
2266
2267 #undef p_stream
2268     }
2269
2270     return( 1 );
2271 }
2272