]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
Merge rtp_internal.h in rtp.h, and remove rtp_internal.h
[ffmpeg] / libavformat / avidec.c
1 /*
2  * AVI demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/intreadwrite.h"
23 #include "libavutil/bswap.h"
24 #include "avformat.h"
25 #include "avi.h"
26 #include "dv.h"
27 #include "riff.h"
28
29 #undef NDEBUG
30 #include <assert.h>
31
32 //#define DEBUG
33 //#define DEBUG_SEEK
34
35 typedef struct AVIStream {
36     int64_t frame_offset; /* current frame (video) or byte (audio) counter
37                          (used to compute the pts) */
38     int remaining;
39     int packet_size;
40
41     int scale;
42     int rate;
43     int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
44
45     int64_t cum_len; /* temporary storage (used during seek) */
46
47     int prefix;                       ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
48     int prefix_count;
49     uint32_t pal[256];
50     int has_pal;
51 } AVIStream;
52
53 typedef struct {
54     int64_t  riff_end;
55     int64_t  movi_end;
56     int64_t  fsize;
57     int64_t movi_list;
58     int64_t last_pkt_pos;
59     int index_loaded;
60     int is_odml;
61     int non_interleaved;
62     int stream_index;
63     DVDemuxContext* dv_demux;
64 } AVIContext;
65
66 static const char avi_headers[][8] = {
67     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', ' ' },
68     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 'X' },
69     { 'R', 'I', 'F', 'F',    'A', 'V', 'I', 0x19},
70     { 'O', 'N', '2', ' ',    'O', 'N', '2', 'f' },
71     { 'R', 'I', 'F', 'F',    'A', 'M', 'V', ' ' },
72     { 0 }
73 };
74
75 static int avi_load_index(AVFormatContext *s);
76 static int guess_ni_flag(AVFormatContext *s);
77
78 #ifdef DEBUG
79 static void print_tag(const char *str, unsigned int tag, int size)
80 {
81     printf("%s: tag=%c%c%c%c size=0x%x\n",
82            str, tag & 0xff,
83            (tag >> 8) & 0xff,
84            (tag >> 16) & 0xff,
85            (tag >> 24) & 0xff,
86            size);
87 }
88 #endif
89
90 static int get_riff(AVIContext *avi, ByteIOContext *pb)
91 {
92     char header[8];
93     int i;
94
95     /* check RIFF header */
96     get_buffer(pb, header, 4);
97     avi->riff_end = get_le32(pb);   /* RIFF chunk size */
98     avi->riff_end += url_ftell(pb); /* RIFF chunk end */
99     get_buffer(pb, header+4, 4);
100
101     for(i=0; avi_headers[i][0]; i++)
102         if(!memcmp(header, avi_headers[i], 8))
103             break;
104     if(!avi_headers[i][0])
105         return -1;
106
107     if(header[7] == 0x19)
108         av_log(NULL, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
109
110     return 0;
111 }
112
113 static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
114     AVIContext *avi = s->priv_data;
115     ByteIOContext *pb = s->pb;
116     int longs_pre_entry= get_le16(pb);
117     int index_sub_type = get_byte(pb);
118     int index_type     = get_byte(pb);
119     int entries_in_use = get_le32(pb);
120     int chunk_id       = get_le32(pb);
121     int64_t base       = get_le64(pb);
122     int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
123     AVStream *st;
124     AVIStream *ast;
125     int i;
126     int64_t last_pos= -1;
127     int64_t filesize= url_fsize(s->pb);
128
129 #ifdef DEBUG_SEEK
130     av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
131         longs_pre_entry,index_type, entries_in_use, chunk_id, base);
132 #endif
133
134     if(stream_id > s->nb_streams || stream_id < 0)
135         return -1;
136     st= s->streams[stream_id];
137     ast = st->priv_data;
138
139     if(index_sub_type)
140         return -1;
141
142     get_le32(pb);
143
144     if(index_type && longs_pre_entry != 2)
145         return -1;
146     if(index_type>1)
147         return -1;
148
149     if(filesize > 0 && base >= filesize){
150         av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
151         if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
152             base &= 0xFFFFFFFF;
153         else
154             return -1;
155     }
156
157     for(i=0; i<entries_in_use; i++){
158         if(index_type){
159             int64_t pos= get_le32(pb) + base - 8;
160             int len    = get_le32(pb);
161             int key= len >= 0;
162             len &= 0x7FFFFFFF;
163
164 #ifdef DEBUG_SEEK
165             av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
166 #endif
167             if(last_pos == pos || pos == base - 8)
168                 avi->non_interleaved= 1;
169             if(last_pos != pos)
170                 av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
171
172             if(ast->sample_size)
173                 ast->cum_len += len;
174             else
175                 ast->cum_len ++;
176             last_pos= pos;
177         }else{
178             int64_t offset, pos;
179             int duration;
180             offset = get_le64(pb);
181             get_le32(pb);       /* size */
182             duration = get_le32(pb);
183             pos = url_ftell(pb);
184
185             url_fseek(pb, offset+8, SEEK_SET);
186             read_braindead_odml_indx(s, frame_num);
187             frame_num += duration;
188
189             url_fseek(pb, pos, SEEK_SET);
190         }
191     }
192     avi->index_loaded=1;
193     return 0;
194 }
195
196 static void clean_index(AVFormatContext *s){
197     int i;
198     int64_t j;
199
200     for(i=0; i<s->nb_streams; i++){
201         AVStream *st = s->streams[i];
202         AVIStream *ast = st->priv_data;
203         int n= st->nb_index_entries;
204         int max= ast->sample_size;
205         int64_t pos, size, ts;
206
207         if(n != 1 || ast->sample_size==0)
208             continue;
209
210         while(max < 1024) max+=max;
211
212         pos= st->index_entries[0].pos;
213         size= st->index_entries[0].size;
214         ts= st->index_entries[0].timestamp;
215
216         for(j=0; j<size; j+=max){
217             av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
218         }
219     }
220 }
221
222 static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
223 {
224     ByteIOContext *pb = s->pb;
225     uint8_t value[1024];
226
227     int64_t i = url_ftell(pb);
228     size += (size & 1);
229     get_strz(pb, value, sizeof(value));
230     url_fseek(pb, i+size, SEEK_SET);
231
232     return av_metadata_set(&s->metadata, (const AVMetadataTag){key, value});
233 }
234
235 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
236 {
237     AVIContext *avi = s->priv_data;
238     ByteIOContext *pb = s->pb;
239     unsigned int tag, tag1, handler;
240     int codec_type, stream_index, frame_period, bit_rate;
241     unsigned int size, nb_frames;
242     int i;
243     AVStream *st;
244     AVIStream *ast = NULL;
245     int avih_width=0, avih_height=0;
246     int amv_file_format=0;
247
248     avi->stream_index= -1;
249
250     if (get_riff(avi, pb) < 0)
251         return -1;
252
253     avi->fsize = url_fsize(pb);
254     if(avi->fsize<=0)
255         avi->fsize= avi->riff_end;
256
257     /* first list tag */
258     stream_index = -1;
259     codec_type = -1;
260     frame_period = 0;
261     for(;;) {
262         if (url_feof(pb))
263             goto fail;
264         tag = get_le32(pb);
265         size = get_le32(pb);
266 #ifdef DEBUG
267         print_tag("tag", tag, size);
268 #endif
269
270         switch(tag) {
271         case MKTAG('L', 'I', 'S', 'T'):
272             /* Ignored, except at start of video packets. */
273             tag1 = get_le32(pb);
274 #ifdef DEBUG
275             print_tag("list", tag1, 0);
276 #endif
277             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
278                 avi->movi_list = url_ftell(pb) - 4;
279                 if(size) avi->movi_end = avi->movi_list + size + (size & 1);
280                 else     avi->movi_end = url_fsize(pb);
281 #ifdef DEBUG
282                 printf("movi end=%"PRIx64"\n", avi->movi_end);
283 #endif
284                 goto end_of_header;
285             }
286             break;
287         case MKTAG('d', 'm', 'l', 'h'):
288             avi->is_odml = 1;
289             url_fskip(pb, size + (size & 1));
290             break;
291         case MKTAG('a', 'm', 'v', 'h'):
292             amv_file_format=1;
293         case MKTAG('a', 'v', 'i', 'h'):
294             /* AVI header */
295             /* using frame_period is bad idea */
296             frame_period = get_le32(pb);
297             bit_rate = get_le32(pb) * 8;
298             get_le32(pb);
299             avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
300
301             url_fskip(pb, 2 * 4);
302             get_le32(pb);
303             get_le32(pb);
304             avih_width=get_le32(pb);
305             avih_height=get_le32(pb);
306
307             url_fskip(pb, size - 10 * 4);
308             break;
309         case MKTAG('s', 't', 'r', 'h'):
310             /* stream header */
311
312             tag1 = get_le32(pb);
313             handler = get_le32(pb); /* codec tag */
314
315             if(tag1 == MKTAG('p', 'a', 'd', 's')){
316                 url_fskip(pb, size - 8);
317                 break;
318             }else{
319                 stream_index++;
320                 st = av_new_stream(s, stream_index);
321                 if (!st)
322                     goto fail;
323
324                 ast = av_mallocz(sizeof(AVIStream));
325                 if (!ast)
326                     goto fail;
327                 st->priv_data = ast;
328             }
329             if(amv_file_format)
330                 tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
331
332 #ifdef DEBUG
333             print_tag("strh", tag1, -1);
334 #endif
335             if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
336                 int64_t dv_dur;
337
338                 /*
339                  * After some consideration -- I don't think we
340                  * have to support anything but DV in type1 AVIs.
341                  */
342                 if (s->nb_streams != 1)
343                     goto fail;
344
345                 if (handler != MKTAG('d', 'v', 's', 'd') &&
346                     handler != MKTAG('d', 'v', 'h', 'd') &&
347                     handler != MKTAG('d', 'v', 's', 'l'))
348                    goto fail;
349
350                 ast = s->streams[0]->priv_data;
351                 av_freep(&s->streams[0]->codec->extradata);
352                 av_freep(&s->streams[0]);
353                 s->nb_streams = 0;
354                 if (CONFIG_DV_DEMUXER) {
355                     avi->dv_demux = dv_init_demux(s);
356                     if (!avi->dv_demux)
357                         goto fail;
358                 }
359                 s->streams[0]->priv_data = ast;
360                 url_fskip(pb, 3 * 4);
361                 ast->scale = get_le32(pb);
362                 ast->rate = get_le32(pb);
363                 url_fskip(pb, 4);  /* start time */
364
365                 dv_dur = get_le32(pb);
366                 if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
367                     dv_dur *= AV_TIME_BASE;
368                     s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
369                 }
370                 /*
371                  * else, leave duration alone; timing estimation in utils.c
372                  *      will make a guess based on bitrate.
373                  */
374
375                 stream_index = s->nb_streams - 1;
376                 url_fskip(pb, size - 9*4);
377                 break;
378             }
379
380             assert(stream_index < s->nb_streams);
381             st->codec->stream_codec_tag= handler;
382
383             get_le32(pb); /* flags */
384             get_le16(pb); /* priority */
385             get_le16(pb); /* language */
386             get_le32(pb); /* initial frame */
387             ast->scale = get_le32(pb);
388             ast->rate = get_le32(pb);
389             if(!(ast->scale && ast->rate)){
390                 av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
391                 if(frame_period){
392                     ast->rate = 1000000;
393                     ast->scale = frame_period;
394                 }else{
395                     ast->rate = 25;
396                     ast->scale = 1;
397                 }
398             }
399             av_set_pts_info(st, 64, ast->scale, ast->rate);
400
401             ast->cum_len=get_le32(pb); /* start */
402             nb_frames = get_le32(pb);
403
404             st->start_time = 0;
405             st->duration = nb_frames;
406             get_le32(pb); /* buffer size */
407             get_le32(pb); /* quality */
408             ast->sample_size = get_le32(pb); /* sample ssize */
409             ast->cum_len *= FFMAX(1, ast->sample_size);
410 //            av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
411
412             switch(tag1) {
413             case MKTAG('v', 'i', 'd', 's'):
414                 codec_type = CODEC_TYPE_VIDEO;
415
416                 ast->sample_size = 0;
417                 break;
418             case MKTAG('a', 'u', 'd', 's'):
419                 codec_type = CODEC_TYPE_AUDIO;
420                 break;
421             case MKTAG('t', 'x', 't', 's'):
422                 //FIXME
423                 codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ?  FIXME
424                 break;
425             case MKTAG('d', 'a', 't', 's'):
426                 codec_type = CODEC_TYPE_DATA;
427                 break;
428             default:
429                 av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
430                 goto fail;
431             }
432             ast->frame_offset= ast->cum_len;
433             url_fskip(pb, size - 12 * 4);
434             break;
435         case MKTAG('s', 't', 'r', 'f'):
436             /* stream header */
437             if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
438                 url_fskip(pb, size);
439             } else {
440                 st = s->streams[stream_index];
441                 switch(codec_type) {
442                 case CODEC_TYPE_VIDEO:
443                     if(amv_file_format){
444                         st->codec->width=avih_width;
445                         st->codec->height=avih_height;
446                         st->codec->codec_type = CODEC_TYPE_VIDEO;
447                         st->codec->codec_id = CODEC_ID_AMV;
448                         url_fskip(pb, size);
449                         break;
450                     }
451                     get_le32(pb); /* size */
452                     st->codec->width = get_le32(pb);
453                     st->codec->height = get_le32(pb);
454                     get_le16(pb); /* panes */
455                     st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
456                     tag1 = get_le32(pb);
457                     get_le32(pb); /* ImageSize */
458                     get_le32(pb); /* XPelsPerMeter */
459                     get_le32(pb); /* YPelsPerMeter */
460                     get_le32(pb); /* ClrUsed */
461                     get_le32(pb); /* ClrImportant */
462
463                     if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
464                         st->codec->codec_type = CODEC_TYPE_SUBTITLE;
465                         st->codec->codec_tag = tag1;
466                         st->codec->codec_id = CODEC_ID_XSUB;
467                         break;
468                     }
469
470                     if(size > 10*4 && size<(1<<30)){
471                         st->codec->extradata_size= size - 10*4;
472                         st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
473                         get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
474                     }
475
476                     if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
477                         get_byte(pb);
478
479                     /* Extract palette from extradata if bpp <= 8. */
480                     /* This code assumes that extradata contains only palette. */
481                     /* This is true for all paletted codecs implemented in FFmpeg. */
482                     if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
483                         st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
484 #ifdef WORDS_BIGENDIAN
485                         for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
486                             st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
487 #else
488                         memcpy(st->codec->palctrl->palette, st->codec->extradata,
489                                FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
490 #endif
491                         st->codec->palctrl->palette_changed = 1;
492                     }
493
494 #ifdef DEBUG
495                     print_tag("video", tag1, 0);
496 #endif
497                     st->codec->codec_type = CODEC_TYPE_VIDEO;
498                     st->codec->codec_tag = tag1;
499                     st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
500                     st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
501 //                    url_fskip(pb, size - 5 * 4);
502                     break;
503                 case CODEC_TYPE_AUDIO:
504                     get_wav_header(pb, st->codec, size);
505                     if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
506                         av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
507                         ast->sample_size= st->codec->block_align;
508                     }
509                     if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
510                         url_fskip(pb, 1);
511                     /* Force parsing as several audio frames can be in
512                      * one packet and timestamps refer to packet start. */
513                     st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
514                     /* ADTS header is in extradata, AAC without header must be
515                      * stored as exact frames. Parser not needed and it will
516                      * fail. */
517                     if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
518                         st->need_parsing = AVSTREAM_PARSE_NONE;
519                     /* AVI files with Xan DPCM audio (wrongly) declare PCM
520                      * audio in the header but have Axan as stream_code_tag. */
521                     if (st->codec->stream_codec_tag == AV_RL32("Axan")){
522                         st->codec->codec_id  = CODEC_ID_XAN_DPCM;
523                         st->codec->codec_tag = 0;
524                     }
525                     if (amv_file_format)
526                         st->codec->codec_id  = CODEC_ID_ADPCM_IMA_AMV;
527                     break;
528                 default:
529                     st->codec->codec_type = CODEC_TYPE_DATA;
530                     st->codec->codec_id= CODEC_ID_NONE;
531                     st->codec->codec_tag= 0;
532                     url_fskip(pb, size);
533                     break;
534                 }
535             }
536             break;
537         case MKTAG('i', 'n', 'd', 'x'):
538             i= url_ftell(pb);
539             if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
540                 read_braindead_odml_indx(s, 0);
541             }
542             url_fseek(pb, i+size, SEEK_SET);
543             break;
544         case MKTAG('v', 'p', 'r', 'p'):
545             if(stream_index < (unsigned)s->nb_streams && size > 9*4){
546                 AVRational active, active_aspect;
547
548                 st = s->streams[stream_index];
549                 get_le32(pb);
550                 get_le32(pb);
551                 get_le32(pb);
552                 get_le32(pb);
553                 get_le32(pb);
554
555                 active_aspect.den= get_le16(pb);
556                 active_aspect.num= get_le16(pb);
557                 active.num       = get_le32(pb);
558                 active.den       = get_le32(pb);
559                 get_le32(pb); //nbFieldsPerFrame
560
561                 if(active_aspect.num && active_aspect.den && active.num && active.den){
562                     st->sample_aspect_ratio= av_div_q(active_aspect, active);
563 //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
564                 }
565                 size -= 9*4;
566             }
567             url_fseek(pb, size, SEEK_CUR);
568             break;
569         case MKTAG('I', 'N', 'A', 'M'):
570             avi_read_tag(s, "Title", size);
571             break;
572         case MKTAG('I', 'A', 'R', 'T'):
573             avi_read_tag(s, "Artist", size);
574             break;
575         case MKTAG('I', 'C', 'O', 'P'):
576             avi_read_tag(s, "Copyright", size);
577             break;
578         case MKTAG('I', 'C', 'M', 'T'):
579             avi_read_tag(s, "Comment", size);
580             break;
581         case MKTAG('I', 'G', 'N', 'R'):
582             avi_read_tag(s, "Genre", size);
583             break;
584         case MKTAG('I', 'P', 'R', 'D'):
585             avi_read_tag(s, "Album", size);
586             break;
587         case MKTAG('I', 'P', 'R', 'T'):
588             avi_read_tag(s, "Track", size);
589             break;
590         default:
591             if(size > 1000000){
592                 av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
593                                         "I will ignore it and try to continue anyway.\n");
594                 avi->movi_list = url_ftell(pb) - 4;
595                 avi->movi_end  = url_fsize(pb);
596                 goto end_of_header;
597             }
598             /* skip tag */
599             size += (size & 1);
600             url_fskip(pb, size);
601             break;
602         }
603     }
604  end_of_header:
605     /* check stream number */
606     if (stream_index != s->nb_streams - 1) {
607     fail:
608         return -1;
609     }
610
611     if(!avi->index_loaded && !url_is_streamed(pb))
612         avi_load_index(s);
613     avi->index_loaded = 1;
614     avi->non_interleaved |= guess_ni_flag(s);
615     if(avi->non_interleaved) {
616         av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
617         clean_index(s);
618     }
619
620     return 0;
621 }
622
623 static int get_stream_idx(int *d){
624     if(    d[0] >= '0' && d[0] <= '9'
625         && d[1] >= '0' && d[1] <= '9'){
626         return (d[0] - '0') * 10 + (d[1] - '0');
627     }else{
628         return 100; //invalid stream ID
629     }
630 }
631
632 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
633 {
634     AVIContext *avi = s->priv_data;
635     ByteIOContext *pb = s->pb;
636     int n, d[8], size;
637     int64_t i, sync;
638     void* dstr;
639
640     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
641         size = dv_get_packet(avi->dv_demux, pkt);
642         if (size >= 0)
643             return size;
644     }
645
646     if(avi->non_interleaved){
647         int best_stream_index = 0;
648         AVStream *best_st= NULL;
649         AVIStream *best_ast;
650         int64_t best_ts= INT64_MAX;
651         int i;
652
653         for(i=0; i<s->nb_streams; i++){
654             AVStream *st = s->streams[i];
655             AVIStream *ast = st->priv_data;
656             int64_t ts= ast->frame_offset;
657
658             if(ast->sample_size)
659                 ts /= ast->sample_size;
660             ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
661
662 //            av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
663             if(ts < best_ts && st->nb_index_entries){
664                 best_ts= ts;
665                 best_st= st;
666                 best_stream_index= i;
667             }
668         }
669         if(!best_st)
670             return -1;
671
672         best_ast = best_st->priv_data;
673         best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
674         if(best_ast->remaining)
675             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
676         else{
677             i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
678             if(i>=0)
679                 best_ast->frame_offset= best_st->index_entries[i].timestamp
680                                       * FFMAX(1, best_ast->sample_size);
681         }
682
683 //        av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
684         if(i>=0){
685             int64_t pos= best_st->index_entries[i].pos;
686             pos += best_ast->packet_size - best_ast->remaining;
687             url_fseek(s->pb, pos + 8, SEEK_SET);
688 //        av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
689
690             assert(best_ast->remaining <= best_ast->packet_size);
691
692             avi->stream_index= best_stream_index;
693             if(!best_ast->remaining)
694                 best_ast->packet_size=
695                 best_ast->remaining= best_st->index_entries[i].size;
696         }
697     }
698
699 resync:
700     if(avi->stream_index >= 0){
701         AVStream *st= s->streams[ avi->stream_index ];
702         AVIStream *ast= st->priv_data;
703         int size;
704
705         if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
706             size= INT_MAX;
707         else if(ast->sample_size < 32)
708             size= 64*ast->sample_size;
709         else
710             size= ast->sample_size;
711
712         if(size > ast->remaining)
713             size= ast->remaining;
714         avi->last_pkt_pos= url_ftell(pb);
715         av_get_packet(pb, pkt, size);
716
717         if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
718             ast->has_pal=0;
719             pkt->size += 4*256;
720             pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
721             if(pkt->data)
722                 memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
723         }
724
725         if (CONFIG_DV_DEMUXER && avi->dv_demux) {
726             dstr = pkt->destruct;
727             size = dv_produce_packet(avi->dv_demux, pkt,
728                                     pkt->data, pkt->size);
729             pkt->destruct = dstr;
730             pkt->flags |= PKT_FLAG_KEY;
731         } else {
732             /* XXX: How to handle B-frames in AVI? */
733             pkt->dts = ast->frame_offset;
734 //                pkt->dts += ast->start;
735             if(ast->sample_size)
736                 pkt->dts /= ast->sample_size;
737 //av_log(NULL, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
738             pkt->stream_index = avi->stream_index;
739
740             if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
741                 AVIndexEntry *e;
742                 int index;
743                 assert(st->index_entries);
744
745                 index= av_index_search_timestamp(st, pkt->dts, 0);
746                 e= &st->index_entries[index];
747
748                 if(index >= 0 && e->timestamp == ast->frame_offset){
749                     if (e->flags & AVINDEX_KEYFRAME)
750                         pkt->flags |= PKT_FLAG_KEY;
751                 }
752             } else {
753                 pkt->flags |= PKT_FLAG_KEY;
754             }
755             if(ast->sample_size)
756                 ast->frame_offset += pkt->size;
757             else
758                 ast->frame_offset++;
759         }
760         ast->remaining -= size;
761         if(!ast->remaining){
762             avi->stream_index= -1;
763             ast->packet_size= 0;
764         }
765
766         return size;
767     }
768
769     memset(d, -1, sizeof(int)*8);
770     for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
771         int j;
772
773         for(j=0; j<7; j++)
774             d[j]= d[j+1];
775         d[7]= get_byte(pb);
776
777         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
778
779         n= get_stream_idx(d+2);
780 //av_log(NULL, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
781         if(i + size > avi->fsize || d[0]<0)
782             continue;
783
784         //parse ix##
785         if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
786         //parse JUNK
787            ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
788            ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
789             url_fskip(pb, size);
790 //av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
791             goto resync;
792         }
793
794         n= get_stream_idx(d);
795
796         if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
797             continue;
798
799         //parse ##dc/##wb
800         if(n < s->nb_streams){
801             AVStream *st;
802             AVIStream *ast;
803             st = s->streams[n];
804             ast = st->priv_data;
805
806             if(s->nb_streams>=2){
807                 AVStream *st1  = s->streams[1];
808                 AVIStream *ast1= st1->priv_data;
809                 //workaround for broken small-file-bug402.avi
810                 if(   d[2] == 'w' && d[3] == 'b'
811                    && n==0
812                    && st ->codec->codec_type == CODEC_TYPE_VIDEO
813                    && st1->codec->codec_type == CODEC_TYPE_AUDIO
814                    && ast->prefix == 'd'*256+'c'
815                    && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
816                   ){
817                     n=1;
818                     st = st1;
819                     ast = ast1;
820                     av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
821                 }
822             }
823
824
825             if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
826                /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
827                || st->discard >= AVDISCARD_ALL){
828                 if(ast->sample_size) ast->frame_offset += pkt->size;
829                 else                 ast->frame_offset++;
830                 url_fskip(pb, size);
831                 goto resync;
832             }
833
834             if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
835                 int k = get_byte(pb);
836                 int last = (k + get_byte(pb) - 1) & 0xFF;
837
838                 get_le16(pb); //flags
839
840                 for (; k <= last; k++)
841                     ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
842                 ast->has_pal= 1;
843                 goto resync;
844             } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
845                          d[2]*256+d[3] == ast->prefix /*||
846                          (d[2] == 'd' && d[3] == 'c') ||
847                          (d[2] == 'w' && d[3] == 'b')*/) {
848
849 //av_log(NULL, AV_LOG_DEBUG, "OK\n");
850                 if(d[2]*256+d[3] == ast->prefix)
851                     ast->prefix_count++;
852                 else{
853                     ast->prefix= d[2]*256+d[3];
854                     ast->prefix_count= 0;
855                 }
856
857                 avi->stream_index= n;
858                 ast->packet_size= size + 8;
859                 ast->remaining= size;
860
861                 {
862                     uint64_t pos= url_ftell(pb) - 8;
863                     if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
864                         av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
865                     }
866                 }
867                 goto resync;
868             }
869         }
870     }
871
872     return -1;
873 }
874
875 /* XXX: We make the implicit supposition that the positions are sorted
876    for each stream. */
877 static int avi_read_idx1(AVFormatContext *s, int size)
878 {
879     AVIContext *avi = s->priv_data;
880     ByteIOContext *pb = s->pb;
881     int nb_index_entries, i;
882     AVStream *st;
883     AVIStream *ast;
884     unsigned int index, tag, flags, pos, len;
885     unsigned last_pos= -1;
886
887     nb_index_entries = size / 16;
888     if (nb_index_entries <= 0)
889         return -1;
890
891     /* Read the entries and sort them in each stream component. */
892     for(i = 0; i < nb_index_entries; i++) {
893         tag = get_le32(pb);
894         flags = get_le32(pb);
895         pos = get_le32(pb);
896         len = get_le32(pb);
897 #if defined(DEBUG_SEEK)
898         av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
899                i, tag, flags, pos, len);
900 #endif
901         if(i==0 && pos > avi->movi_list)
902             avi->movi_list= 0; //FIXME better check
903         pos += avi->movi_list;
904
905         index = ((tag & 0xff) - '0') * 10;
906         index += ((tag >> 8) & 0xff) - '0';
907         if (index >= s->nb_streams)
908             continue;
909         st = s->streams[index];
910         ast = st->priv_data;
911
912 #if defined(DEBUG_SEEK)
913         av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
914 #endif
915         if(last_pos == pos)
916             avi->non_interleaved= 1;
917         else
918             av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
919         if(ast->sample_size)
920             ast->cum_len += len;
921         else
922             ast->cum_len ++;
923         last_pos= pos;
924     }
925     return 0;
926 }
927
928 static int guess_ni_flag(AVFormatContext *s){
929     int i;
930     int64_t last_start=0;
931     int64_t first_end= INT64_MAX;
932
933     for(i=0; i<s->nb_streams; i++){
934         AVStream *st = s->streams[i];
935         int n= st->nb_index_entries;
936
937         if(n <= 0)
938             continue;
939
940         if(st->index_entries[0].pos > last_start)
941             last_start= st->index_entries[0].pos;
942         if(st->index_entries[n-1].pos < first_end)
943             first_end= st->index_entries[n-1].pos;
944     }
945     return last_start > first_end;
946 }
947
948 static int avi_load_index(AVFormatContext *s)
949 {
950     AVIContext *avi = s->priv_data;
951     ByteIOContext *pb = s->pb;
952     uint32_t tag, size;
953     int64_t pos= url_ftell(pb);
954
955     url_fseek(pb, avi->movi_end, SEEK_SET);
956 #ifdef DEBUG_SEEK
957     printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
958 #endif
959     for(;;) {
960         if (url_feof(pb))
961             break;
962         tag = get_le32(pb);
963         size = get_le32(pb);
964 #ifdef DEBUG_SEEK
965         printf("tag=%c%c%c%c size=0x%x\n",
966                tag & 0xff,
967                (tag >> 8) & 0xff,
968                (tag >> 16) & 0xff,
969                (tag >> 24) & 0xff,
970                size);
971 #endif
972         switch(tag) {
973         case MKTAG('i', 'd', 'x', '1'):
974             if (avi_read_idx1(s, size) < 0)
975                 goto skip;
976             else
977                 goto the_end;
978             break;
979         default:
980         skip:
981             size += (size & 1);
982             url_fskip(pb, size);
983             break;
984         }
985     }
986  the_end:
987     url_fseek(pb, pos, SEEK_SET);
988     return 0;
989 }
990
991 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
992 {
993     AVIContext *avi = s->priv_data;
994     AVStream *st;
995     int i, index;
996     int64_t pos;
997
998     if (!avi->index_loaded) {
999         /* we only load the index on demand */
1000         avi_load_index(s);
1001         avi->index_loaded = 1;
1002     }
1003     assert(stream_index>= 0);
1004
1005     st = s->streams[stream_index];
1006     index= av_index_search_timestamp(st, timestamp, flags);
1007     if(index<0)
1008         return -1;
1009
1010     /* find the position */
1011     pos = st->index_entries[index].pos;
1012     timestamp = st->index_entries[index].timestamp;
1013
1014 //    av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
1015
1016     if (CONFIG_DV_DEMUXER && avi->dv_demux) {
1017         /* One and only one real stream for DV in AVI, and it has video  */
1018         /* offsets. Calling with other stream indexes should have failed */
1019         /* the av_index_search_timestamp call above.                     */
1020         assert(stream_index == 0);
1021
1022         /* Feed the DV video stream version of the timestamp to the */
1023         /* DV demux so it can synthesize correct timestamps.        */
1024         dv_offset_reset(avi->dv_demux, timestamp);
1025
1026         url_fseek(s->pb, pos, SEEK_SET);
1027         avi->stream_index= -1;
1028         return 0;
1029     }
1030
1031     for(i = 0; i < s->nb_streams; i++) {
1032         AVStream *st2 = s->streams[i];
1033         AVIStream *ast2 = st2->priv_data;
1034
1035         ast2->packet_size=
1036         ast2->remaining= 0;
1037
1038         if (st2->nb_index_entries <= 0)
1039             continue;
1040
1041 //        assert(st2->codec->block_align);
1042         assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
1043         index = av_index_search_timestamp(
1044                 st2,
1045                 av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
1046                 flags | AVSEEK_FLAG_BACKWARD);
1047         if(index<0)
1048             index=0;
1049
1050         if(!avi->non_interleaved){
1051             while(index>0 && st2->index_entries[index].pos > pos)
1052                 index--;
1053             while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
1054                 index++;
1055         }
1056
1057 //        av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
1058         /* extract the current frame number */
1059         ast2->frame_offset = st2->index_entries[index].timestamp;
1060         if(ast2->sample_size)
1061             ast2->frame_offset *=ast2->sample_size;
1062     }
1063
1064     /* do the seek */
1065     url_fseek(s->pb, pos, SEEK_SET);
1066     avi->stream_index= -1;
1067     return 0;
1068 }
1069
1070 static int avi_read_close(AVFormatContext *s)
1071 {
1072     int i;
1073     AVIContext *avi = s->priv_data;
1074
1075     for(i=0;i<s->nb_streams;i++) {
1076         AVStream *st = s->streams[i];
1077         av_free(st->codec->palctrl);
1078     }
1079
1080     if (avi->dv_demux)
1081         av_free(avi->dv_demux);
1082
1083     return 0;
1084 }
1085
1086 static int avi_probe(AVProbeData *p)
1087 {
1088     int i;
1089
1090     /* check file header */
1091     for(i=0; avi_headers[i][0]; i++)
1092         if(!memcmp(p->buf  , avi_headers[i]  , 4) &&
1093            !memcmp(p->buf+8, avi_headers[i]+4, 4))
1094             return AVPROBE_SCORE_MAX;
1095
1096     return 0;
1097 }
1098
1099 AVInputFormat avi_demuxer = {
1100     "avi",
1101     NULL_IF_CONFIG_SMALL("AVI format"),
1102     sizeof(AVIContext),
1103     avi_probe,
1104     avi_read_header,
1105     avi_read_packet,
1106     avi_read_close,
1107     avi_read_seek,
1108 };