]> git.sesse.net Git - ffmpeg/blob - libavformat/avienc.c
New demuxers: Sega FILM/CPK, Westwood VQA & AUD; new decoders: MS RLE &
[ffmpeg] / libavformat / avienc.c
1 /*
2  * AVI encoder.
3  * Copyright (c) 2000 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
22 /*
23  * TODO: 
24  *  - fill all fields if non streamed (nb_frames for example)
25  */
26
27 typedef struct AVIIentry {
28     unsigned int flags, pos, len;
29 } AVIIentry;
30
31 #define AVI_INDEX_CLUSTER_SIZE 16384
32
33 typedef struct AVIIndex {
34     offset_t    indx_start;
35     int         entry;
36     int         ents_allocated;
37     AVIIentry** cluster;
38 } AVIIndex;
39
40 typedef struct {
41     offset_t riff_start, movi_list, odml_list;
42     offset_t frames_hdr_all, frames_hdr_strm[MAX_STREAMS];
43     int audio_strm_length[MAX_STREAMS];
44     int riff_id;
45
46     AVIIndex indexes[MAX_STREAMS];
47 } AVIContext;
48
49 static inline AVIIentry* avi_get_ientry(AVIIndex* idx, int ent_id) 
50 {
51     int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
52     int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
53     return &idx->cluster[cl][id];
54 }
55
56 offset_t start_tag(ByteIOContext *pb, const char *tag)
57 {
58     put_tag(pb, tag);
59     put_le32(pb, 0);
60     return url_ftell(pb);
61 }
62
63 void end_tag(ByteIOContext *pb, offset_t start)
64 {
65     offset_t pos;
66
67     pos = url_ftell(pb);
68     url_fseek(pb, start - 4, SEEK_SET);
69     put_le32(pb, (uint32_t)(pos - start));
70     url_fseek(pb, pos, SEEK_SET);
71 }
72
73 /* Note: when encoding, the first matching tag is used, so order is
74    important if multiple tags possible for a given codec. */
75 const CodecTag codec_bmp_tags[] = {
76     { CODEC_ID_H263, MKTAG('H', '2', '6', '3') },
77     { CODEC_ID_H263P, MKTAG('H', '2', '6', '3') },
78     { CODEC_ID_H263I, MKTAG('I', '2', '6', '3') }, /* intel h263 */
79
80     /* added based on MPlayer */
81     { CODEC_ID_H263P, MKTAG('U', '2', '6', '3') },
82     { CODEC_ID_H263P, MKTAG('v', 'i', 'v', '1') },
83
84     { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X'), .invalid_asf = 1 },
85     { CODEC_ID_MPEG4, MKTAG('D', 'X', '5', '0'), .invalid_asf = 1 },
86     { CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D'), .invalid_asf = 1 },
87     { CODEC_ID_MPEG4, MKTAG('M', 'P', '4', 'S') },
88     { CODEC_ID_MPEG4, MKTAG('M', '4', 'S', '2') },
89     { CODEC_ID_MPEG4, MKTAG(0x04, 0, 0, 0) }, /* some broken avi use this */
90
91     /* added based on MPlayer */
92     { CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', '1') },
93     { CODEC_ID_MPEG4, MKTAG('B', 'L', 'Z', '0') },
94     { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
95     { CODEC_ID_MPEG4, MKTAG('U', 'M', 'P', '4') },
96
97     { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '3'), .invalid_asf = 1 }, /* default signature when using MSMPEG4 */
98     { CODEC_ID_MSMPEG4V3, MKTAG('M', 'P', '4', '3') }, 
99
100     /* added based on MPlayer */
101     { CODEC_ID_MSMPEG4V3, MKTAG('M', 'P', 'G', '3') }, 
102     { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '5') }, 
103     { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '6') }, 
104     { CODEC_ID_MSMPEG4V3, MKTAG('D', 'I', 'V', '4') }, 
105     { CODEC_ID_MSMPEG4V3, MKTAG('A', 'P', '4', '1') }, 
106     { CODEC_ID_MSMPEG4V3, MKTAG('C', 'O', 'L', '1') }, 
107     { CODEC_ID_MSMPEG4V3, MKTAG('C', 'O', 'L', '0') }, 
108
109     { CODEC_ID_MSMPEG4V2, MKTAG('M', 'P', '4', '2') }, 
110
111     /* added based on MPlayer */
112     { CODEC_ID_MSMPEG4V2, MKTAG('D', 'I', 'V', '2') },
113  
114     { CODEC_ID_MSMPEG4V1, MKTAG('M', 'P', 'G', '4') }, 
115
116     { CODEC_ID_WMV1, MKTAG('W', 'M', 'V', '1') }, 
117
118     /* added based on MPlayer */
119     { CODEC_ID_WMV2, MKTAG('W', 'M', 'V', '2') }, 
120     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 's', 'd') }, 
121     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', 'd') }, 
122     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 's', 'l') }, 
123     { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '2', '5') },
124     { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'g', '1') }, 
125     { CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'g', '2') }, 
126     { CODEC_ID_MPEG1VIDEO, MKTAG('P', 'I', 'M', '1') }, 
127     { CODEC_ID_MPEG1VIDEO, MKTAG('V', 'C', 'R', '2') }, 
128     { CODEC_ID_MJPEG, MKTAG('M', 'J', 'P', 'G') },
129     { CODEC_ID_MJPEG, MKTAG('L', 'J', 'P', 'G') },
130     { CODEC_ID_LJPEG, MKTAG('L', 'J', 'P', 'G') },
131     { CODEC_ID_MJPEG, MKTAG('J', 'P', 'G', 'L') }, /* Pegasus lossless JPEG */
132     { CODEC_ID_HUFFYUV, MKTAG('H', 'F', 'Y', 'U') },
133     { CODEC_ID_CYUV, MKTAG('C', 'Y', 'U', 'V') },
134     { CODEC_ID_RAWVIDEO, MKTAG('Y', '4', '2', '2') },
135     { CODEC_ID_RAWVIDEO, MKTAG('I', '4', '2', '0') },
136     { CODEC_ID_INDEO3, MKTAG('I', 'V', '3', '1') },
137     { CODEC_ID_INDEO3, MKTAG('I', 'V', '3', '2') },
138     { CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') },
139     { CODEC_ID_ASV1, MKTAG('A', 'S', 'V', '1') },
140     { CODEC_ID_ASV2, MKTAG('A', 'S', 'V', '2') },
141     { CODEC_ID_VCR1, MKTAG('V', 'C', 'R', '1') },
142     { CODEC_ID_FFV1, MKTAG('F', 'F', 'V', '1') },
143     { CODEC_ID_XAN_WC4, MKTAG('X', 'x', 'a', 'n') },
144     { CODEC_ID_MSRLE, MKTAG('m', 'r', 'l', 'e') },
145     { CODEC_ID_MSRLE, MKTAG(0x1, 0x0, 0x0, 0x0) },
146     { CODEC_ID_MSVIDEO1, MKTAG('M', 'S', 'V', 'C') },
147     { CODEC_ID_MSVIDEO1, MKTAG('m', 's', 'v', 'c') },
148     { CODEC_ID_MSVIDEO1, MKTAG('C', 'R', 'A', 'M') },
149     { CODEC_ID_MSVIDEO1, MKTAG('c', 'r', 'a', 'm') },
150     { CODEC_ID_MSVIDEO1, MKTAG('W', 'H', 'A', 'M') },
151     { CODEC_ID_MSVIDEO1, MKTAG('w', 'h', 'a', 'm') },
152     { CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') },
153     { 0, 0 },
154 };
155
156 unsigned int codec_get_tag(const CodecTag *tags, int id)
157 {
158     while (tags->id != 0) {
159         if (tags->id == id)
160             return tags->tag;
161         tags++;
162     }
163     return 0;
164 }
165
166 static unsigned int codec_get_asf_tag(const CodecTag *tags, int id)
167 {
168     while (tags->id != 0) {
169         if (!tags->invalid_asf && tags->id == id)
170             return tags->tag;
171         tags++;
172     }
173     return 0;
174 }
175
176 enum CodecID codec_get_id(const CodecTag *tags, unsigned int tag)
177 {
178     while (tags->id != 0) {
179         if(   toupper((tag >> 0)&0xFF) == toupper((tags->tag >> 0)&0xFF)
180            && toupper((tag >> 8)&0xFF) == toupper((tags->tag >> 8)&0xFF)
181            && toupper((tag >>16)&0xFF) == toupper((tags->tag >>16)&0xFF)
182            && toupper((tag >>24)&0xFF) == toupper((tags->tag >>24)&0xFF))
183             return tags->id;
184         tags++;
185     }
186     return CODEC_ID_NONE;
187 }
188
189 unsigned int codec_get_bmp_tag(int id)
190 {
191     return codec_get_tag(codec_bmp_tags, id);
192 }
193
194 unsigned int codec_get_wav_tag(int id)
195 {
196     return codec_get_tag(codec_wav_tags, id);
197 }
198
199 enum CodecID codec_get_bmp_id(unsigned int tag)
200 {
201     return codec_get_id(codec_bmp_tags, tag);
202 }
203
204 enum CodecID codec_get_wav_id(unsigned int tag)
205 {
206     return codec_get_id(codec_wav_tags, tag);
207 }
208
209 /* BITMAPINFOHEADER header */
210 void put_bmp_header(ByteIOContext *pb, AVCodecContext *enc, const CodecTag *tags, int for_asf)
211 {
212     put_le32(pb, 40 + enc->extradata_size); /* size */
213     put_le32(pb, enc->width);
214     put_le32(pb, enc->height);
215     put_le16(pb, 1); /* planes */
216     
217     put_le16(pb, enc->bits_per_sample ? enc->bits_per_sample : 24); /* depth */
218     /* compression type */
219     put_le32(pb, for_asf ? codec_get_asf_tag(tags, enc->codec_id) : enc->codec_tag);
220     put_le32(pb, enc->width * enc->height * 3);
221     put_le32(pb, 0);
222     put_le32(pb, 0);
223     put_le32(pb, 0);
224     put_le32(pb, 0);
225     
226     put_buffer(pb, enc->extradata, enc->extradata_size);
227
228     if (enc->extradata_size & 1)
229         put_byte(pb, 0);
230 }
231
232 static void parse_specific_params(AVCodecContext *stream, int *au_byterate, int *au_ssize, int *au_scale)
233 {
234     switch(stream->codec_id) {
235     case CODEC_ID_PCM_S16LE:
236        *au_scale = *au_ssize = 2*stream->channels;
237        *au_byterate = *au_ssize * stream->sample_rate;
238         break;
239     case CODEC_ID_PCM_U8:
240     case CODEC_ID_PCM_ALAW:
241     case CODEC_ID_PCM_MULAW:
242         *au_scale = *au_ssize = stream->channels;
243         *au_byterate = *au_ssize * stream->sample_rate;
244         break;
245     case CODEC_ID_MP2:
246         *au_ssize = 1;
247         *au_scale = 1;
248         *au_byterate = stream->bit_rate / 8;
249     case CODEC_ID_MP3:
250         *au_ssize = 1;
251         *au_scale = 1;
252         *au_byterate = stream->bit_rate / 8;    
253     default:
254         *au_ssize = 1;
255         *au_scale = 1; 
256         *au_byterate = stream->bit_rate / 8;
257         break;
258     }
259 }
260
261 static offset_t avi_start_new_riff(AVIContext *avi, ByteIOContext *pb, 
262                                    const char* riff_tag, const char* list_tag)
263 {
264     offset_t loff;
265     int i;
266     
267     avi->riff_id++;
268     for (i=0; i<MAX_STREAMS; i++)
269          avi->indexes[i].entry = 0;
270     
271     avi->riff_start = start_tag(pb, "RIFF");
272     put_tag(pb, riff_tag);
273     loff = start_tag(pb, "LIST");
274     put_tag(pb, list_tag);
275     return loff;
276 }
277
278 static unsigned char* avi_stream2fourcc(unsigned char* tag, int index, 
279                                         enum CodecType type)
280 {
281     tag[0] = '0';
282     tag[1] = '0' + index;
283     if (type == CODEC_TYPE_VIDEO) {
284         tag[2] = 'd';
285         tag[3] = 'c';
286     } else {
287         tag[2] = 'w';
288         tag[3] = 'b';
289     }
290     tag[4] = '\0';
291     return tag;
292 }
293
294 static int avi_write_header(AVFormatContext *s)
295 {
296     AVIContext *avi = s->priv_data;
297     ByteIOContext *pb = &s->pb;
298     int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
299     AVCodecContext *stream, *video_enc;
300     offset_t list1, list2, strh, strf;
301
302     /* header list */
303     avi->riff_id = 0;
304     list1 = avi_start_new_riff(avi, pb, "AVI ", "hdrl");
305
306     /* avi header */
307     put_tag(pb, "avih");
308     put_le32(pb, 14 * 4);
309     bitrate = 0;
310
311     video_enc = NULL;
312     for(n=0;n<s->nb_streams;n++) {
313         stream = &s->streams[n]->codec;
314         bitrate += stream->bit_rate;
315         if (stream->codec_type == CODEC_TYPE_VIDEO)
316             video_enc = stream;
317     }
318     
319     nb_frames = 0;
320
321     if(video_enc){
322         put_le32(pb, (uint32_t)(int64_t_C(1000000) * video_enc->frame_rate_base / video_enc->frame_rate));
323     } else {
324         put_le32(pb, 0);
325     }
326     put_le32(pb, bitrate / 8); /* XXX: not quite exact */
327     put_le32(pb, 0); /* padding */
328     put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
329     avi->frames_hdr_all = url_ftell(pb); /* remember this offset to fill later */
330     put_le32(pb, nb_frames); /* nb frames, filled later */
331     put_le32(pb, 0); /* initial frame */
332     put_le32(pb, s->nb_streams); /* nb streams */
333     put_le32(pb, 1024 * 1024); /* suggested buffer size */
334     if(video_enc){    
335     put_le32(pb, video_enc->width);
336     put_le32(pb, video_enc->height);
337     } else {
338         put_le32(pb, 0);
339         put_le32(pb, 0);
340     }   
341     put_le32(pb, 0); /* reserved */
342     put_le32(pb, 0); /* reserved */
343     put_le32(pb, 0); /* reserved */
344     put_le32(pb, 0); /* reserved */
345     
346     /* stream list */
347     for(i=0;i<n;i++) {
348         list2 = start_tag(pb, "LIST");
349         put_tag(pb, "strl");
350     
351         stream = &s->streams[i]->codec;
352
353         /* FourCC should really be set by the codec itself */
354         if (! stream->codec_tag) {
355             stream->codec_tag = codec_get_bmp_tag(stream->codec_id);
356         }
357
358         /* stream generic header */
359         strh = start_tag(pb, "strh");
360         switch(stream->codec_type) {
361         case CODEC_TYPE_VIDEO:
362             put_tag(pb, "vids");
363             put_le32(pb, stream->codec_tag);
364             put_le32(pb, 0); /* flags */
365             put_le16(pb, 0); /* priority */
366             put_le16(pb, 0); /* language */
367             put_le32(pb, 0); /* initial frame */
368             
369             put_le32(pb, stream->frame_rate_base); /* scale */
370             put_le32(pb, stream->frame_rate); /* rate */
371
372             put_le32(pb, 0); /* start */
373             avi->frames_hdr_strm[i] = url_ftell(pb); /* remember this offset to fill later */
374             put_le32(pb, nb_frames); /* length, XXX: fill later */
375             put_le32(pb, 1024 * 1024); /* suggested buffer size */
376             put_le32(pb, -1); /* quality */
377             put_le32(pb, stream->width * stream->height * 3); /* sample size */
378             put_le16(pb, 0);
379             put_le16(pb, 0);
380             put_le16(pb, stream->width);
381             put_le16(pb, stream->height);
382             break;
383         case CODEC_TYPE_AUDIO:
384             put_tag(pb, "auds");
385             put_le32(pb, 1); /* tag */
386             put_le32(pb, 0); /* flags */
387             put_le16(pb, 0); /* priority */
388             put_le16(pb, 0); /* language */
389             put_le32(pb, 0); /* initial frame */
390             parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
391             put_le32(pb, au_scale); /* scale */
392             put_le32(pb, au_byterate); /* rate */
393             put_le32(pb, 0); /* start */
394             avi->frames_hdr_strm[i] = url_ftell(pb); /* remember this offset to fill later */
395             put_le32(pb, 0); /* length, XXX: filled later */
396             put_le32(pb, 12 * 1024); /* suggested buffer size */
397             put_le32(pb, -1); /* quality */
398             put_le32(pb, au_ssize); /* sample size */
399             put_le32(pb, 0);
400             put_le32(pb, 0);
401             break;
402         default:
403             av_abort();
404         }
405         end_tag(pb, strh);
406
407         strf = start_tag(pb, "strf");
408         switch(stream->codec_type) {
409         case CODEC_TYPE_VIDEO:
410             put_bmp_header(pb, stream, codec_bmp_tags, 0);
411             break;
412         case CODEC_TYPE_AUDIO:
413             if (put_wav_header(pb, stream) < 0) {
414                 av_free(avi);
415                 return -1;
416             }
417             break;
418         default:
419             av_abort();
420         }
421         end_tag(pb, strf);
422         
423         if (!url_is_streamed(pb)) {
424             unsigned char tag[5];
425             int j;
426     
427             /* Starting to lay out AVI OpenDML master index. 
428              * We want to make it JUNK entry for now, since we'd
429              * like to get away without making AVI an OpenDML one 
430              * for compatibility reasons.
431              */
432             avi->indexes[i].entry = avi->indexes[i].ents_allocated = 0;
433             avi->indexes[i].indx_start = start_tag(pb, "JUNK"); 
434             put_le16(pb, 4);        /* wLongsPerEntry */
435             put_byte(pb, 0);        /* bIndexSubType (0 == frame index) */
436             put_byte(pb, 0);        /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
437             put_le32(pb, 0);        /* nEntriesInUse (will fill out later on) */
438             put_tag(pb, avi_stream2fourcc(&tag[0], i, stream->codec_type));
439                                     /* dwChunkId */
440             put_le64(pb, 0);        /* dwReserved[3]
441             put_le32(pb, 0);           Must be 0.    */
442             for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
443                  put_le64(pb, 0);
444             end_tag(pb, avi->indexes[i].indx_start);
445         }
446         
447         end_tag(pb, list2);
448     }
449     
450     if (!url_is_streamed(pb)) {
451         /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
452         avi->odml_list = start_tag(pb, "JUNK");
453         put_tag(pb, "odml");
454         put_tag(pb, "dmlh");
455         put_le32(pb, 248);
456         for (i = 0; i < 248; i+= 4)
457              put_le32(pb, 0);
458         end_tag(pb, avi->odml_list);
459     }
460
461     end_tag(pb, list1);
462     
463     avi->movi_list = start_tag(pb, "LIST");
464     put_tag(pb, "movi");
465
466     put_flush_packet(pb);
467
468     return 0;
469 }
470
471 static int avi_write_ix(AVFormatContext *s)
472 {
473     ByteIOContext *pb = &s->pb;
474     AVIContext *avi = s->priv_data;
475     unsigned char tag[5];
476     unsigned char ix_tag[] = "ix00";
477     int i, j;
478     
479     if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
480         return -1;
481     
482     for (i=0;i<s->nb_streams;i++) {
483          offset_t ix, pos;
484          
485          avi_stream2fourcc(&tag[0], i, s->streams[i]->codec.codec_type);
486          ix_tag[3] = '0' + i;
487          
488          /* Writing AVI OpenDML leaf index chunk */
489          ix = url_ftell(pb); 
490          put_tag(pb, &ix_tag[0]);     /* ix?? */
491          put_le32(pb, avi->indexes[i].entry * 8 + 24); 
492                                       /* chunk size */
493          put_le16(pb, 2);             /* wLongsPerEntry */
494          put_byte(pb, 0);             /* bIndexSubType (0 == frame index) */ 
495          put_byte(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
496          put_le32(pb, avi->indexes[i].entry);          
497                                       /* nEntriesInUse */
498          put_tag(pb, &tag[0]);        /* dwChunkId */
499          put_le64(pb, avi->movi_list);/* qwBaseOffset */
500          put_le32(pb, 0);             /* dwReserved_3 (must be 0) */
501
502          for (j=0; j<avi->indexes[i].entry; j++) {
503              AVIIentry* ie = avi_get_ientry(&avi->indexes[i], j);
504              put_le32(pb, ie->pos + 8);
505              put_le32(pb, ((uint32_t)ie->len & ~0x80000000) |
506                           (ie->flags & 0x10 ? 0 : 0x80000000));
507          }
508          put_flush_packet(pb);
509          pos = url_ftell(pb);
510         
511          /* Updating one entry in the AVI OpenDML master index */
512          url_fseek(pb, avi->indexes[i].indx_start - 8, SEEK_SET);
513          put_tag(pb, "indx");                 /* enabling this entry */
514          url_fskip(pb, 8);
515          put_le32(pb, avi->riff_id);          /* nEntriesInUse */
516          url_fskip(pb, 16*avi->riff_id);
517          put_le64(pb, ix);                    /* qwOffset */
518          put_le32(pb, pos - ix);              /* dwSize */
519          put_le32(pb, avi->indexes[i].entry); /* dwDuration */
520
521          url_fseek(pb, pos, SEEK_SET);
522     }
523     return 0;
524 }
525
526 static int avi_write_idx1(AVFormatContext *s)
527 {
528     ByteIOContext *pb = &s->pb;
529     AVIContext *avi = s->priv_data;
530     offset_t file_size, idx_chunk;
531     int i, n, nb_frames, au_byterate, au_ssize, au_scale;
532     AVCodecContext *stream;
533     unsigned char tag[5];
534
535     if (!url_is_streamed(pb)) {
536         AVIIentry* ie = 0, *tie;
537         int entry[MAX_STREAMS];
538         int empty, stream_id = -1;
539
540         idx_chunk = start_tag(pb, "idx1");
541         memset(&entry[0], 0, sizeof(entry));
542         do {
543             empty = 1;
544             for (i=0; i<s->nb_streams; i++) {
545                  if (avi->indexes[i].entry <= entry[i])
546                      continue;
547                  
548                  tie = avi_get_ientry(&avi->indexes[i], entry[i]);
549                  if (empty || tie->pos < ie->pos) {
550                      ie = tie; 
551                      stream_id = i;
552                  }
553                  empty = 0;
554             }
555             if (!empty) {
556                 avi_stream2fourcc(&tag[0], stream_id, 
557                                   s->streams[stream_id]->codec.codec_type); 
558                 put_tag(pb, &tag[0]);
559                 put_le32(pb, ie->flags);
560                 put_le32(pb, ie->pos);
561                 put_le32(pb, ie->len);
562                 entry[stream_id]++;
563             }
564         } while (!empty);
565         end_tag(pb, idx_chunk);
566
567         /* Fill in frame/sample counters */
568         file_size = url_ftell(pb);
569         nb_frames = 0;
570         for(n=0;n<s->nb_streams;n++) {
571             if (avi->frames_hdr_strm[n] != 0) {
572                 stream = &s->streams[n]->codec;
573                 url_fseek(pb, avi->frames_hdr_strm[n], SEEK_SET);
574                 if (stream->codec_type == CODEC_TYPE_VIDEO) {
575                     put_le32(pb, stream->frame_number); 
576                     if (nb_frames < stream->frame_number)
577                         nb_frames = stream->frame_number;
578                 } else {
579                     if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3) {
580                         put_le32(pb, stream->frame_number);
581                         nb_frames += stream->frame_number;
582                     } else {
583                         parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
584                         put_le32(pb, avi->audio_strm_length[n] / au_ssize);
585                     }
586                 }
587             }
588        }
589        if (avi->frames_hdr_all != 0) {
590            url_fseek(pb, avi->frames_hdr_all, SEEK_SET);
591            put_le32(pb, nb_frames); 
592        }
593        url_fseek(pb, file_size, SEEK_SET);
594     }
595     return 0;
596 }
597
598 static int avi_write_packet(AVFormatContext *s, int stream_index,
599                             const uint8_t *buf, int size, int64_t pts)
600 {
601     AVIContext *avi = s->priv_data;
602     ByteIOContext *pb = &s->pb;
603     unsigned char tag[5];
604     unsigned int flags;
605     AVCodecContext *enc;
606
607     if (url_ftell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE) { 
608         avi_write_ix(s);
609         end_tag(pb, avi->movi_list);
610         
611         if (avi->riff_id == 1)
612             avi_write_idx1(s);
613
614         end_tag(pb, avi->riff_start);
615         avi->movi_list = avi_start_new_riff(avi, pb, "AVIX", "movi");
616     }
617     
618     enc = &s->streams[stream_index]->codec;
619     avi_stream2fourcc(&tag[0], stream_index, enc->codec_type);
620     if (enc->codec_type == CODEC_TYPE_AUDIO) {
621        avi->audio_strm_length[stream_index] += size;
622        flags = 0x10;
623     } else
624        flags = enc->coded_frame->key_frame ? 0x10 : 0x00;
625
626     if (!url_is_streamed(&s->pb)) {
627         AVIIndex* idx = &avi->indexes[stream_index];
628         int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
629         int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
630         if (idx->ents_allocated <= idx->entry) {
631             idx->cluster = av_realloc(idx->cluster, (cl+1)*sizeof(void*)); 
632             if (!idx->cluster)
633                 return -1;
634             idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
635             if (!idx->cluster[cl])
636                 return -1;
637             idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
638         }
639         
640         idx->cluster[cl][id].flags = flags; 
641         idx->cluster[cl][id].pos = url_ftell(pb) - avi->movi_list;
642         idx->cluster[cl][id].len = size;
643         idx->entry++;
644     }
645     
646     put_buffer(pb, tag, 4);
647     put_le32(pb, size);
648     put_buffer(pb, buf, size);
649     if (size & 1)
650         put_byte(pb, 0);
651
652     put_flush_packet(pb);
653     return 0;
654 }
655
656 static int avi_write_trailer(AVFormatContext *s)
657 {
658     AVIContext *avi = s->priv_data;
659     ByteIOContext *pb = &s->pb;
660     int res = 0;
661     int i, j, n, nb_frames;
662     offset_t file_size;
663
664     if (avi->riff_id == 1) {
665         end_tag(pb, avi->movi_list);
666         res = avi_write_idx1(s);
667         end_tag(pb, avi->riff_start);
668     } else {
669         avi_write_ix(s);
670         end_tag(pb, avi->movi_list);
671         end_tag(pb, avi->riff_start);
672
673         file_size = url_ftell(pb);
674         url_fseek(pb, avi->odml_list - 8, SEEK_SET);
675         put_tag(pb, "LIST"); /* Making this AVI OpenDML one */
676         url_fskip(pb, 16);
677
678         for (n=nb_frames=0;n<s->nb_streams;n++) {
679              AVCodecContext *stream = &s->streams[n]->codec;
680              if (stream->codec_type == CODEC_TYPE_VIDEO) {
681                  if (nb_frames < stream->frame_number)
682                      nb_frames = stream->frame_number;
683              } else {
684                  if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3) {
685                      nb_frames += stream->frame_number;
686                 }
687             }
688         }
689         put_le32(pb, nb_frames);
690         url_fseek(pb, file_size, SEEK_SET);
691     }
692     put_flush_packet(pb);
693
694     for (i=0; i<MAX_STREAMS; i++) {
695          for (j=0; j<avi->indexes[i].ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++)
696               av_free(avi->indexes[i].cluster[j]);
697          av_free(avi->indexes[i].cluster);
698          avi->indexes[i].cluster = NULL;
699          avi->indexes[i].ents_allocated = avi->indexes[i].entry = 0;
700     }
701     
702     return res;
703 }
704
705 static AVOutputFormat avi_oformat = {
706     "avi",
707     "avi format",
708     "video/x-msvideo",
709     "avi",
710     sizeof(AVIContext),
711     CODEC_ID_MP2,
712     CODEC_ID_MPEG4,
713     avi_write_header,
714     avi_write_packet,
715     avi_write_trailer,
716 };
717
718 int avienc_init(void)
719 {
720     av_register_output_format(&avi_oformat);
721     return 0;
722 }