]> git.sesse.net Git - ffmpeg/blob - libavformat/avidec.c
yep, FLI support
[ffmpeg] / libavformat / avidec.c
1 /*
2  * AVI decoder.
3  * Copyright (c) 2001 Fabrice Bellard.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19 #include "avformat.h"
20 #include "avi.h"
21 #include "dv.h"
22
23 //#define DEBUG
24 //#define DEBUG_SEEK
25
26 typedef struct AVIIndexEntry {
27     unsigned int flags;
28     unsigned int pos;
29     unsigned int cum_len; /* sum of all lengths before this packet */
30 } AVIIndexEntry;
31
32 typedef struct AVIStream {
33     AVIIndexEntry *index_entries;
34     int nb_index_entries;
35     int index_entries_allocated_size;
36     int frame_offset; /* current frame (video) or byte (audio) counter
37                          (used to compute the pts) */
38     int scale;
39     int rate;    
40     int sample_size; /* audio only data */
41     
42     int new_frame_offset; /* temporary storage (used during seek) */
43     int cum_len; /* temporary storage (used during seek) */
44 } AVIStream;
45
46 typedef struct {
47     int64_t  riff_end;
48     int64_t  movi_end;
49     offset_t movi_list;
50     int index_loaded;
51     DVDemuxContext* dv_demux;
52 } AVIContext;
53
54 #ifdef DEBUG
55 static void print_tag(const char *str, unsigned int tag, int size)
56 {
57     printf("%s: tag=%c%c%c%c size=0x%x\n",
58            str, tag & 0xff,
59            (tag >> 8) & 0xff,
60            (tag >> 16) & 0xff,
61            (tag >> 24) & 0xff,
62            size);
63 }
64 #endif
65
66 static int get_riff(AVIContext *avi, ByteIOContext *pb)
67 {
68     uint32_t tag; 
69     /* check RIFF header */
70     tag = get_le32(pb);
71
72     if (tag != MKTAG('R', 'I', 'F', 'F'))
73         return -1;
74     avi->riff_end = get_le32(pb);   /* RIFF chunk size */
75     avi->riff_end += url_ftell(pb); /* RIFF chunk end */
76     tag = get_le32(pb);
77     if (tag != MKTAG('A', 'V', 'I', ' ') && tag != MKTAG('A', 'V', 'I', 'X'))
78         return -1;
79     
80     return 0;
81 }
82
83 static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
84 {
85     AVIContext *avi = s->priv_data;
86     ByteIOContext *pb = &s->pb;
87     uint32_t tag, tag1, handler;
88     int codec_type, stream_index, frame_period, bit_rate, scale, rate;
89     unsigned int size, nb_frames;
90     int i, n;
91     AVStream *st;
92     AVIStream *ast;
93     int xan_video = 0;  /* hack to support Xan A/V */
94
95     av_set_pts_info(s, 64, 1, AV_TIME_BASE);
96
97     if (get_riff(avi, pb) < 0)
98         return -1;
99
100     /* first list tag */
101     stream_index = -1;
102     codec_type = -1;
103     frame_period = 0;
104     for(;;) {
105         if (url_feof(pb))
106             goto fail;
107         tag = get_le32(pb);
108         size = get_le32(pb);
109 #ifdef DEBUG
110         print_tag("tag", tag, size);
111 #endif
112
113         switch(tag) {
114         case MKTAG('L', 'I', 'S', 'T'):
115             /* ignored, except when start of video packets */
116             tag1 = get_le32(pb);
117 #ifdef DEBUG
118             print_tag("list", tag1, 0);
119 #endif
120             if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
121                 avi->movi_list = url_ftell(pb) - 4;
122                 avi->movi_end = avi->movi_list + size;
123 #ifdef DEBUG
124                 printf("movi end=%Lx\n", avi->movi_end);
125 #endif
126                 goto end_of_header;
127             }
128             break;
129         case MKTAG('a', 'v', 'i', 'h'):
130             /* avi header */
131             /* using frame_period is bad idea */
132             frame_period = get_le32(pb);
133             bit_rate = get_le32(pb) * 8;
134             url_fskip(pb, 4 * 4);
135             n = get_le32(pb);
136             for(i=0;i<n;i++) {
137                 AVIStream *ast;
138                 st = av_new_stream(s, i);
139                 if (!st)
140                     goto fail;
141                 ast = av_mallocz(sizeof(AVIStream));
142                 if (!ast)
143                     goto fail;
144                 st->priv_data = ast;
145             }
146             url_fskip(pb, size - 7 * 4);
147             break;
148         case MKTAG('s', 't', 'r', 'h'):
149             /* stream header */
150             stream_index++;
151             tag1 = get_le32(pb);
152             handler = get_le32(pb); /* codec tag */
153             switch(tag1) {
154             case MKTAG('i', 'a', 'v', 's'):
155             case MKTAG('i', 'v', 'a', 's'):
156                 /* 
157                  * After some consideration -- I don't think we 
158                  * have to support anything but DV in a type1 AVIs.
159                  */
160                 if (s->nb_streams != 1)
161                     goto fail;
162                 
163                 if (handler != MKTAG('d', 'v', 's', 'd') &&
164                     handler != MKTAG('d', 'v', 'h', 'd') &&
165                     handler != MKTAG('d', 'v', 's', 'l'))
166                    goto fail;
167                 
168                 av_freep(&s->streams[0]->codec.extradata);
169                 av_freep(&s->streams[0]);
170                 s->nb_streams = 0;
171                 avi->dv_demux = dv_init_demux(s);
172                 if (!avi->dv_demux)
173                     goto fail;
174                 stream_index = s->nb_streams - 1;
175                 url_fskip(pb, size - 8);
176                 break;
177             case MKTAG('v', 'i', 'd', 's'):
178                 codec_type = CODEC_TYPE_VIDEO;
179
180                 if (stream_index >= s->nb_streams) {
181                     url_fskip(pb, size - 8);
182                     break;
183                 } 
184
185                 st = s->streams[stream_index];
186                 ast = st->priv_data;
187                 
188                 get_le32(pb); /* flags */
189                 get_le16(pb); /* priority */
190                 get_le16(pb); /* language */
191                 get_le32(pb); /* XXX: initial frame ? */
192                 scale = get_le32(pb); /* scale */
193                 rate = get_le32(pb); /* rate */
194
195                 if(scale && rate){
196                 }else if(frame_period){
197                     rate = 1000000;
198                     scale = frame_period;
199                 }else{
200                     rate = 25;
201                     scale = 1;
202                 }
203                 ast->rate = rate;
204                 ast->scale = scale;
205                 st->codec.frame_rate = rate;
206                 st->codec.frame_rate_base = scale;
207                 get_le32(pb); /* start */
208                 nb_frames = get_le32(pb);
209                 st->start_time = 0;
210                 st->duration = (double)nb_frames * 
211                     st->codec.frame_rate_base * AV_TIME_BASE / 
212                     st->codec.frame_rate;
213                 url_fskip(pb, size - 9 * 4);
214                 break;
215             case MKTAG('a', 'u', 'd', 's'):
216                 {
217                     unsigned int length;
218
219                     codec_type = CODEC_TYPE_AUDIO;
220
221                     if (stream_index >= s->nb_streams) {
222                         url_fskip(pb, size - 8);
223                         break;
224                     } 
225                     st = s->streams[stream_index];
226                     ast = st->priv_data;
227                     
228                     get_le32(pb); /* flags */
229                     get_le16(pb); /* priority */
230                     get_le16(pb); /* language */
231                     get_le32(pb); /* initial frame */
232                     ast->scale = get_le32(pb); /* scale */
233                     ast->rate = get_le32(pb);
234                     get_le32(pb); /* start */
235                     length = get_le32(pb); /* length, in samples or bytes */
236                     get_le32(pb); /* buffer size */
237                     get_le32(pb); /* quality */
238                     ast->sample_size = get_le32(pb); /* sample ssize */
239                     st->start_time = 0;
240                     if (ast->rate != 0)
241                         st->duration = (int64_t)length * AV_TIME_BASE / ast->rate;
242                     url_fskip(pb, size - 12 * 4);
243                 }
244                 break;
245             default:
246                 goto fail;
247             }
248             break;
249         case MKTAG('s', 't', 'r', 'f'):
250             /* stream header */
251             if (stream_index >= s->nb_streams || avi->dv_demux) {
252                 url_fskip(pb, size);
253             } else {
254                 st = s->streams[stream_index];
255                 switch(codec_type) {
256                 case CODEC_TYPE_VIDEO:
257                     get_le32(pb); /* size */
258                     st->codec.width = get_le32(pb);
259                     st->codec.height = get_le32(pb);
260                     get_le16(pb); /* panes */
261                     st->codec.bits_per_sample= get_le16(pb); /* depth */
262                     tag1 = get_le32(pb);
263                     get_le32(pb); /* ImageSize */
264                     get_le32(pb); /* XPelsPerMeter */
265                     get_le32(pb); /* YPelsPerMeter */
266                     get_le32(pb); /* ClrUsed */
267                     get_le32(pb); /* ClrImportant */
268
269                     st->codec.extradata_size= size - 10*4;
270                     st->codec.extradata= av_malloc(st->codec.extradata_size);
271                     get_buffer(pb, st->codec.extradata, st->codec.extradata_size);
272                     
273                     if(st->codec.extradata_size & 1) //FIXME check if the encoder really did this correctly
274                         get_byte(pb);
275
276                     /* Extract palette from extradata if bpp <= 8 */
277                     /* This code assumes that extradata contains only palette */
278                     /* This is true for all paletted codecs implemented in ffmpeg */
279                     if (st->codec.extradata_size && (st->codec.bits_per_sample <= 8)) {
280                         st->codec.palctrl = av_mallocz(sizeof(AVPaletteControl));
281 #ifdef WORDS_BIGENDIAN
282                         for (i = 0; i < FFMIN(st->codec.extradata_size, AVPALETTE_SIZE)/4; i++)
283                             st->codec.palctrl->palette[i] = bswap_32(((uint32_t*)st->codec.extradata)[i]);
284 #else
285                         memcpy(st->codec.palctrl->palette, st->codec.extradata,
286                                FFMIN(st->codec.extradata_size, AVPALETTE_SIZE));
287 #endif
288                         st->codec.palctrl->palette_changed = 1;
289                     }
290
291 #ifdef DEBUG
292                     print_tag("video", tag1, 0);
293 #endif
294                     st->codec.codec_type = CODEC_TYPE_VIDEO;
295                     st->codec.codec_tag = tag1;
296                     st->codec.codec_id = codec_get_id(codec_bmp_tags, tag1);
297                     if (st->codec.codec_id == CODEC_ID_XAN_WC4)
298                         xan_video = 1;
299 //                    url_fskip(pb, size - 5 * 4);
300                     break;
301                 case CODEC_TYPE_AUDIO:
302                     get_wav_header(pb, &st->codec, size);
303                     if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
304                         url_fskip(pb, 1);
305                     /* special case time: To support Xan DPCM, hardcode
306                      * the format if Xxan is the video codec */
307                     st->need_parsing = 1;
308                     /* force parsing as several audio frames can be in
309                        one packet */
310                     if (xan_video)
311                         st->codec.codec_id = CODEC_ID_XAN_DPCM;
312                     break;
313                 default:
314                     url_fskip(pb, size);
315                     break;
316                 }
317             }
318             break;
319         default:
320             /* skip tag */
321             size += (size & 1);
322             url_fskip(pb, size);
323             break;
324         }
325     }
326  end_of_header:
327     /* check stream number */
328     if (stream_index != s->nb_streams - 1) {
329     fail:
330         for(i=0;i<s->nb_streams;i++) {
331             av_freep(&s->streams[i]->codec.extradata);
332             av_freep(&s->streams[i]);
333         }
334         return -1;
335     }
336
337     return 0;
338 }
339
340 static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
341 {
342     AVIContext *avi = s->priv_data;
343     ByteIOContext *pb = &s->pb;
344     int n, d[8], size, i;
345     void* dstr;
346
347     memset(d, -1, sizeof(int)*8);
348    
349     if (avi->dv_demux) {
350         size = dv_get_packet(avi->dv_demux, pkt);
351         if (size >= 0)
352             return size;
353     }
354         
355     for(i=url_ftell(pb); !url_feof(pb); i++) {
356         int j;
357
358         if (i >= avi->movi_end) { /* Let's see if it's an OpenDML AVI */
359             uint32_t tag, size, tag2;
360             url_fskip(pb, avi->riff_end - url_ftell(pb));
361             if (get_riff(avi, pb) < 0)
362                 return -1;
363             
364             tag = get_le32(pb);
365             size = get_le32(pb);
366             tag2 = get_le32(pb);
367             if (tag == MKTAG('L','I','S','T') && tag2 == MKTAG('m','o','v','i'))
368                 avi->movi_end = url_ftell(pb) + size - 4; 
369             else
370                 return -1;
371         }
372
373         for(j=0; j<7; j++)
374             d[j]= d[j+1];
375         d[7]= get_byte(pb);
376         
377         size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
378         
379         //parse ix##
380         n= (d[2] - '0') * 10 + (d[3] - '0');
381         if(    d[2] >= '0' && d[2] <= '9'
382             && d[3] >= '0' && d[3] <= '9'
383             && d[0] == 'i' && d[1] == 'x'
384             && n < s->nb_streams
385             && i + size <= avi->movi_end){
386             
387             url_fskip(pb, size);
388         }
389         
390         //parse ##dc/##wb
391         n= (d[0] - '0') * 10 + (d[1] - '0');
392         if(    d[0] >= '0' && d[0] <= '9'
393             && d[1] >= '0' && d[1] <= '9'
394             && ((d[2] == 'd' && d[3] == 'c') || 
395                 (d[2] == 'w' && d[3] == 'b') || 
396                 (d[2] == 'd' && d[3] == 'b') ||
397                 (d[2] == '_' && d[3] == '_'))
398             && n < s->nb_streams
399             && i + size <= avi->movi_end) {
400         
401             av_new_packet(pkt, size);
402             get_buffer(pb, pkt->data, size);
403             if (size & 1) {
404                 get_byte(pb);
405                 size++;
406             }
407         
408             if (avi->dv_demux) {
409                 dstr = pkt->destruct;
410                 size = dv_produce_packet(avi->dv_demux, pkt,
411                                          pkt->data, pkt->size);
412                 pkt->destruct = dstr;
413                 pkt->flags |= PKT_FLAG_KEY;
414             } else {
415                 AVStream *st;
416                 AVIStream *ast;
417                 st = s->streams[n];
418                 ast = st->priv_data;
419
420                 /* XXX: how to handle B frames in avi ? */
421                 pkt->pts = ((int64_t)ast->frame_offset * ast->scale* AV_TIME_BASE) / ast->rate;
422                 pkt->stream_index = n;
423                 /* FIXME: We really should read index for that */
424                 if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
425                     if (ast->frame_offset < ast->nb_index_entries) {
426                         if (ast->index_entries[ast->frame_offset].flags & AVIIF_INDEX)
427                             pkt->flags |= PKT_FLAG_KEY; 
428                     } else {
429                         /* if no index, better to say that all frames
430                            are key frames */
431                         pkt->flags |= PKT_FLAG_KEY;
432                     }
433                     ast->frame_offset++;
434                 } else {
435                     ast->frame_offset += pkt->size;
436                     pkt->flags |= PKT_FLAG_KEY; 
437                 }
438             }
439             return size;
440         }
441     }
442     return -1;
443 }
444
445 /* XXX: we make the implicit supposition that the position are sorted
446    for each stream */
447 static int avi_read_idx1(AVFormatContext *s, int size)
448 {
449     ByteIOContext *pb = &s->pb;
450     int nb_index_entries, i;
451     AVStream *st;
452     AVIStream *ast;
453     AVIIndexEntry *ie, *entries;
454     unsigned int index, tag, flags, pos, len;
455     
456     nb_index_entries = size / 16;
457     if (nb_index_entries <= 0)
458         return -1;
459
460     /* read the entries and sort them in each stream component */
461     for(i = 0; i < nb_index_entries; i++) {
462         tag = get_le32(pb);
463         flags = get_le32(pb);
464         pos = get_le32(pb);
465         len = get_le32(pb);
466 #if defined(DEBUG_SEEK) && 0
467         printf("%d: tag=0x%x flags=0x%x pos=0x%x len=%d\n", 
468                i, tag, flags, pos, len);
469 #endif
470         index = ((tag & 0xff) - '0') * 10;
471         index += ((tag >> 8) & 0xff) - '0';
472         if (index >= s->nb_streams)
473             continue;
474         st = s->streams[index];
475         ast = st->priv_data;
476         
477         entries = av_fast_realloc(ast->index_entries,
478                                   &ast->index_entries_allocated_size,
479                                   (ast->nb_index_entries + 1) * 
480                                   sizeof(AVIIndexEntry));
481         if (entries) {
482             ast->index_entries = entries;
483             ie = &entries[ast->nb_index_entries++];
484             ie->flags = flags;
485             ie->pos = pos;
486             ie->cum_len = ast->cum_len;
487             ast->cum_len += len;
488         }
489     }
490     return 0;
491 }
492
493 static int avi_load_index(AVFormatContext *s)
494 {
495     AVIContext *avi = s->priv_data;
496     ByteIOContext *pb = &s->pb;
497     uint32_t tag, size;
498
499     url_fseek(pb, avi->movi_end, SEEK_SET);
500 #ifdef DEBUG_SEEK
501     printf("movi_end=0x%llx\n", avi->movi_end);
502 #endif
503     for(;;) {
504         if (url_feof(pb))
505             break;
506         tag = get_le32(pb);
507         size = get_le32(pb);
508 #ifdef DEBUG_SEEK
509         printf("tag=%c%c%c%c size=0x%x\n",
510                tag & 0xff,
511                (tag >> 8) & 0xff,
512                (tag >> 16) & 0xff,
513                (tag >> 24) & 0xff,
514                size);
515 #endif
516         switch(tag) {
517         case MKTAG('i', 'd', 'x', '1'):
518             if (avi_read_idx1(s, size) < 0)
519                 goto skip;
520             else
521                 goto the_end;
522             break;
523         default:
524         skip:
525             size += (size & 1);
526             url_fskip(pb, size);
527             break;
528         }
529     }
530  the_end:
531     return 0;
532 }
533
534 /* return the index entry whose position is immediately >= 'wanted_pos' */
535 static int locate_frame_in_index(AVIIndexEntry *entries, 
536                                  int nb_entries, int wanted_pos)
537 {
538     int a, b, m, pos;
539     
540     a = 0;
541     b = nb_entries - 1;
542     while (a <= b) {
543         m = (a + b) >> 1;
544         pos = entries[m].pos;
545         if (pos == wanted_pos)
546             goto found;
547         else if (pos > wanted_pos) {
548             b = m - 1;
549         } else {
550             a = m + 1;
551         }
552     }
553     m = a;
554     if (m > 0)
555         m--;
556  found:
557     return m;
558 }
559
560 static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp)
561 {
562     AVIContext *avi = s->priv_data;
563     AVStream *st;
564     AVIStream *ast;
565     int frame_number, i;
566     int64_t pos;
567
568     if (!avi->index_loaded) {
569         /* we only load the index on demand */
570         avi_load_index(s);
571         avi->index_loaded = 1;
572     }
573     if (stream_index < 0) {
574         for(i = 0; i < s->nb_streams; i++) {
575             st = s->streams[i];
576             if (st->codec.codec_type == CODEC_TYPE_VIDEO)
577                 goto found;
578         }
579         return -1;
580     found:
581         stream_index = i;
582     }
583
584     st = s->streams[stream_index];
585     if (st->codec.codec_type != CODEC_TYPE_VIDEO)
586         return -1;
587     ast = st->priv_data;
588     /* compute the frame number */
589     frame_number = (timestamp * ast->rate) /
590         (ast->scale * (int64_t)AV_TIME_BASE);
591 #ifdef DEBUG_SEEK
592     printf("timestamp=%0.3f nb_indexes=%d frame_number=%d\n", 
593            (double)timestamp / AV_TIME_BASE,
594            ast->nb_index_entries, frame_number);
595 #endif
596     /* find a closest key frame before */
597     if (frame_number >= ast->nb_index_entries)
598         return -1;
599     while (frame_number >= 0 &&
600            !(ast->index_entries[frame_number].flags & AVIIF_INDEX))
601         frame_number--;
602     if (frame_number < 0)
603         return -1;
604     ast->new_frame_offset = frame_number;
605
606     /* find the position */
607     pos = ast->index_entries[frame_number].pos;
608
609 #ifdef DEBUG_SEEK
610     printf("key_frame_number=%d pos=0x%llx\n", 
611            frame_number, pos);
612 #endif
613     
614     /* update the frame counters for all the other stream by looking
615        at the positions just after the one found */
616     for(i = 0; i < s->nb_streams; i++) {
617         int j;
618         if (i != stream_index) {
619             st = s->streams[i];
620             ast = st->priv_data;
621             if (ast->nb_index_entries <= 0)
622                 return -1;
623             j = locate_frame_in_index(ast->index_entries,
624                                       ast->nb_index_entries,
625                                       pos);
626             /* get next frame */
627             if ((j  + 1) < ast->nb_index_entries)
628                 j++;
629             /* extract the current frame number */
630             if (st->codec.codec_type == CODEC_TYPE_VIDEO)           
631                 ast->new_frame_offset = j;
632             else
633                 ast->new_frame_offset = ast->index_entries[j].cum_len;
634         }
635     }
636     
637     /* everything is OK now. We can update the frame offsets */
638     for(i = 0; i < s->nb_streams; i++) {
639         st = s->streams[i];
640         ast = st->priv_data;
641         ast->frame_offset = ast->new_frame_offset;
642 #ifdef DEBUG_SEEK
643         printf("%d: frame_offset=%d\n", i, 
644                ast->frame_offset);
645 #endif
646     }
647     /* do the seek */
648     pos += avi->movi_list;
649     url_fseek(&s->pb, pos, SEEK_SET);
650     return 0;
651 }
652
653 static int avi_read_close(AVFormatContext *s)
654 {
655     int i;
656     AVIContext *avi = s->priv_data;
657
658     for(i=0;i<s->nb_streams;i++) {
659         AVStream *st = s->streams[i];
660         AVIStream *ast = st->priv_data;
661         av_free(ast->index_entries);
662         av_free(ast);
663         av_free(st->codec.extradata);
664         av_free(st->codec.palctrl);
665     }
666
667     if (avi->dv_demux)
668         av_free(avi->dv_demux);
669
670     return 0;
671 }
672
673 static int avi_probe(AVProbeData *p)
674 {
675     /* check file header */
676     if (p->buf_size <= 32)
677         return 0;
678     if (p->buf[0] == 'R' && p->buf[1] == 'I' &&
679         p->buf[2] == 'F' && p->buf[3] == 'F' &&
680         p->buf[8] == 'A' && p->buf[9] == 'V' &&
681         p->buf[10] == 'I' && p->buf[11] == ' ')
682         return AVPROBE_SCORE_MAX;
683     else
684         return 0;
685 }
686
687 static AVInputFormat avi_iformat = {
688     "avi",
689     "avi format",
690     sizeof(AVIContext),
691     avi_probe,
692     avi_read_header,
693     avi_read_packet,
694     avi_read_close,
695     avi_read_seek,
696 };
697
698 int avidec_init(void)
699 {
700     av_register_input_format(&avi_iformat);
701     return 0;
702 }