]> git.sesse.net Git - ffmpeg/blob - libavformat/avienc.c
Merge commit 'ae116cd3ed908d28b69d5198712217ec743d74f6'
[ffmpeg] / libavformat / avienc.c
1 /*
2  * AVI muxer
3  * Copyright (c) 2000 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 //#define DEBUG
23
24 #include "avformat.h"
25 #include "internal.h"
26 #include "avi.h"
27 #include "avio_internal.h"
28 #include "riff.h"
29 #include "libavformat/avlanguage.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/dict.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/timestamp.h"
35
36 /*
37  * TODO:
38  *  - fill all fields if non streamed (nb_frames for example)
39  */
40
41 typedef struct AVIIentry {
42     unsigned int flags, pos, len;
43 } AVIIentry;
44
45 #define AVI_INDEX_CLUSTER_SIZE 16384
46
47 typedef struct AVIIndex {
48     int64_t     indx_start;
49     int         entry;
50     int         ents_allocated;
51     AVIIentry** cluster;
52 } AVIIndex;
53
54 typedef struct {
55     int64_t riff_start, movi_list, odml_list;
56     int64_t frames_hdr_all;
57     int riff_id;
58 } AVIContext;
59
60 typedef struct  {
61     int64_t frames_hdr_strm;
62     int64_t audio_strm_length;
63     int packet_count;
64     int entry;
65
66     AVIIndex indexes;
67 } AVIStream;
68
69 static inline AVIIentry *avi_get_ientry(AVIIndex *idx, int ent_id)
70 {
71     int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
72     int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
73     return &idx->cluster[cl][id];
74 }
75
76 static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
77                                   const char *riff_tag, const char *list_tag)
78 {
79     AVIContext *avi = s->priv_data;
80     int64_t loff;
81     int i;
82
83     avi->riff_id++;
84     for (i = 0; i < s->nb_streams; i++) {
85         AVIStream *avist = s->streams[i]->priv_data;
86         avist->indexes.entry = 0;
87     }
88
89     avi->riff_start = ff_start_tag(pb, "RIFF");
90     ffio_wfourcc(pb, riff_tag);
91     loff = ff_start_tag(pb, "LIST");
92     ffio_wfourcc(pb, list_tag);
93     return loff;
94 }
95
96 static char *avi_stream2fourcc(char *tag, int index, enum AVMediaType type)
97 {
98     tag[0] = '0' + index / 10;
99     tag[1] = '0' + index % 10;
100     if (type == AVMEDIA_TYPE_VIDEO) {
101         tag[2] = 'd';
102         tag[3] = 'c';
103     } else if (type == AVMEDIA_TYPE_SUBTITLE) {
104         // note: this is not an official code
105         tag[2] = 's';
106         tag[3] = 'b';
107     } else {
108         tag[2] = 'w';
109         tag[3] = 'b';
110     }
111     tag[4] = '\0';
112     return tag;
113 }
114
115 static int avi_write_counters(AVFormatContext *s, int riff_id)
116 {
117     AVIOContext *pb = s->pb;
118     AVIContext *avi = s->priv_data;
119     int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
120     int64_t file_size;
121     AVCodecContext *stream;
122
123     file_size = avio_tell(pb);
124     for (n = 0; n < s->nb_streams; n++) {
125         AVIStream *avist = s->streams[n]->priv_data;
126
127         av_assert0(avist->frames_hdr_strm);
128         stream = s->streams[n]->codec;
129         avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
130         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
131         if (au_ssize == 0)
132             avio_wl32(pb, avist->packet_count);
133         else
134             avio_wl32(pb, avist->audio_strm_length / au_ssize);
135         if (stream->codec_type == AVMEDIA_TYPE_VIDEO)
136             nb_frames = FFMAX(nb_frames, avist->packet_count);
137     }
138     if (riff_id == 1) {
139         av_assert0(avi->frames_hdr_all);
140         avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
141         avio_wl32(pb, nb_frames);
142     }
143     avio_seek(pb, file_size, SEEK_SET);
144
145     return 0;
146 }
147
148 static int avi_write_header(AVFormatContext *s)
149 {
150     AVIContext *avi = s->priv_data;
151     AVIOContext *pb = s->pb;
152     int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
153     AVCodecContext *stream, *video_enc;
154     int64_t list1, list2, strh, strf;
155     AVDictionaryEntry *t = NULL;
156     int padding;
157
158     if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
159         av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
160                AVI_MAX_STREAM_COUNT);
161         return AVERROR(EINVAL);
162     }
163
164     for (n = 0; n < s->nb_streams; n++) {
165         s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));
166         if (!s->streams[n]->priv_data)
167             return AVERROR(ENOMEM);
168     }
169
170     /* header list */
171     avi->riff_id = 0;
172     list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
173
174     /* avi header */
175     ffio_wfourcc(pb, "avih");
176     avio_wl32(pb, 14 * 4);
177     bitrate = 0;
178
179     video_enc = NULL;
180     for (n = 0; n < s->nb_streams; n++) {
181         stream   = s->streams[n]->codec;
182         bitrate += stream->bit_rate;
183         if (stream->codec_type == AVMEDIA_TYPE_VIDEO)
184             video_enc = stream;
185     }
186
187     nb_frames = 0;
188
189     if (video_enc)
190         avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_enc->time_base.num /
191                                   video_enc->time_base.den));
192     else
193         avio_wl32(pb, 0);
194     avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
195     avio_wl32(pb, 0); /* padding */
196     if (!pb->seekable)
197         avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED);  /* flags */
198     else
199         avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED);  /* flags */
200     avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
201     avio_wl32(pb, nb_frames); /* nb frames, filled later */
202     avio_wl32(pb, 0); /* initial frame */
203     avio_wl32(pb, s->nb_streams); /* nb streams */
204     avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
205     if (video_enc) {
206         avio_wl32(pb, video_enc->width);
207         avio_wl32(pb, video_enc->height);
208     } else {
209         avio_wl32(pb, 0);
210         avio_wl32(pb, 0);
211     }
212     avio_wl32(pb, 0); /* reserved */
213     avio_wl32(pb, 0); /* reserved */
214     avio_wl32(pb, 0); /* reserved */
215     avio_wl32(pb, 0); /* reserved */
216
217     /* stream list */
218     for (i = 0; i < n; i++) {
219         AVIStream *avist = s->streams[i]->priv_data;
220         list2 = ff_start_tag(pb, "LIST");
221         ffio_wfourcc(pb, "strl");
222
223         stream = s->streams[i]->codec;
224
225         /* stream generic header */
226         strh = ff_start_tag(pb, "strh");
227         switch (stream->codec_type) {
228         case AVMEDIA_TYPE_SUBTITLE:
229             // XSUB subtitles behave like video tracks, other subtitles
230             // are not (yet) supported.
231             if (stream->codec_id != AV_CODEC_ID_XSUB) {
232                 av_log(s, AV_LOG_ERROR,
233                        "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");
234                 return AVERROR_PATCHWELCOME;
235             }
236         case AVMEDIA_TYPE_VIDEO:
237             ffio_wfourcc(pb, "vids");
238             break;
239         case AVMEDIA_TYPE_AUDIO:
240             ffio_wfourcc(pb, "auds");
241             break;
242 //      case AVMEDIA_TYPE_TEXT:
243 //          ffio_wfourcc(pb, "txts");
244 //          break;
245         case AVMEDIA_TYPE_DATA:
246             ffio_wfourcc(pb, "dats");
247             break;
248         }
249         if (stream->codec_type == AVMEDIA_TYPE_VIDEO ||
250             stream->codec_id == AV_CODEC_ID_XSUB)
251             avio_wl32(pb, stream->codec_tag);
252         else
253             avio_wl32(pb, 1);
254         avio_wl32(pb, 0); /* flags */
255         avio_wl16(pb, 0); /* priority */
256         avio_wl16(pb, 0); /* language */
257         avio_wl32(pb, 0); /* initial frame */
258
259         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
260
261         if (   stream->codec_type == AVMEDIA_TYPE_VIDEO
262             && stream->codec_id != AV_CODEC_ID_XSUB
263             && au_byterate > 1000LL*au_scale) {
264             au_byterate = 600;
265             au_scale    = 1;
266         }
267         avpriv_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
268         if (stream->codec_id == AV_CODEC_ID_XSUB)
269             au_scale = au_byterate = 0;
270
271         avio_wl32(pb, au_scale); /* scale */
272         avio_wl32(pb, au_byterate); /* rate */
273
274         avio_wl32(pb, 0); /* start */
275         /* remember this offset to fill later */
276         avist->frames_hdr_strm = avio_tell(pb);
277         if (!pb->seekable)
278             /* FIXME: this may be broken, but who cares */
279             avio_wl32(pb, AVI_MAX_RIFF_SIZE);
280         else
281             avio_wl32(pb, 0);  /* length, XXX: filled later */
282
283         /* suggested buffer size */ //FIXME set at the end to largest chunk
284         if (stream->codec_type == AVMEDIA_TYPE_VIDEO)
285             avio_wl32(pb, 1024 * 1024);
286         else if (stream->codec_type == AVMEDIA_TYPE_AUDIO)
287             avio_wl32(pb, 12 * 1024);
288         else
289             avio_wl32(pb, 0);
290         avio_wl32(pb, -1); /* quality */
291         avio_wl32(pb, au_ssize); /* sample size */
292         avio_wl32(pb, 0);
293         avio_wl16(pb, stream->width);
294         avio_wl16(pb, stream->height);
295         ff_end_tag(pb, strh);
296
297         if (stream->codec_type != AVMEDIA_TYPE_DATA) {
298             int ret;
299
300             strf = ff_start_tag(pb, "strf");
301             switch (stream->codec_type) {
302             case AVMEDIA_TYPE_SUBTITLE:
303                 /* XSUB subtitles behave like video tracks, other subtitles
304                  * are not (yet) supported. */
305                 if (stream->codec_id != AV_CODEC_ID_XSUB)
306                     break;
307             case AVMEDIA_TYPE_VIDEO:
308                 ff_put_bmp_header(pb, stream, ff_codec_bmp_tags, 0, 0);
309                 break;
310             case AVMEDIA_TYPE_AUDIO:
311                 if ((ret = ff_put_wav_header(pb, stream)) < 0)
312                     return ret;
313                 break;
314             default:
315                 av_log(s, AV_LOG_ERROR,
316                     "Invalid or not supported codec type '%s' found in the input\n",
317                     (char *)av_x_if_null(av_get_media_type_string(stream->codec_type), "?"));
318                 return AVERROR(EINVAL);
319             }
320             ff_end_tag(pb, strf);
321             if ((t = av_dict_get(s->streams[i]->metadata, "title", NULL, 0))) {
322                 ff_riff_write_info_tag(s->pb, "strn", t->value);
323                 t = NULL;
324             }
325             if (stream->codec_id == AV_CODEC_ID_XSUB
326             && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
327                 const char* langstr = av_convert_lang_to(t->value, AV_LANG_ISO639_1);
328                 t = NULL;
329                 if (langstr) {
330                     char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
331                     ff_riff_write_info_tag(s->pb, "strn", str);
332                     av_free(str);
333                 }
334             }
335         }
336
337         if (pb->seekable) {
338             unsigned char tag[5];
339             int j;
340
341             /* Starting to lay out AVI OpenDML master index.
342              * We want to make it JUNK entry for now, since we'd
343              * like to get away without making AVI an OpenDML one
344              * for compatibility reasons. */
345             avist->indexes.entry      = avist->indexes.ents_allocated = 0;
346             avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
347             avio_wl16(pb, 4);   /* wLongsPerEntry */
348             avio_w8(pb, 0);     /* bIndexSubType (0 == frame index) */
349             avio_w8(pb, 0);     /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
350             avio_wl32(pb, 0);   /* nEntriesInUse (will fill out later on) */
351             ffio_wfourcc(pb, avi_stream2fourcc(tag, i, stream->codec_type));
352                                 /* dwChunkId */
353             avio_wl64(pb, 0);   /* dwReserved[3] */
354             // avio_wl32(pb, 0);   /* Must be 0.    */
355             for (j = 0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
356                 avio_wl64(pb, 0);
357             ff_end_tag(pb, avist->indexes.indx_start);
358         }
359
360         if (stream->codec_type == AVMEDIA_TYPE_VIDEO   &&
361             s->streams[i]->sample_aspect_ratio.num > 0 &&
362             s->streams[i]->sample_aspect_ratio.den > 0) {
363             int vprp       = ff_start_tag(pb, "vprp");
364             AVRational dar = av_mul_q(s->streams[i]->sample_aspect_ratio,
365                                       (AVRational) { stream->width,
366                                                      stream->height });
367             int num, den;
368             av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
369
370             avio_wl32(pb, 0); // video format   = unknown
371             avio_wl32(pb, 0); // video standard = unknown
372             avio_wl32(pb, lrintf(1.0 / av_q2d(stream->time_base)));
373             avio_wl32(pb, stream->width);
374             avio_wl32(pb, stream->height);
375             avio_wl16(pb, den);
376             avio_wl16(pb, num);
377             avio_wl32(pb, stream->width);
378             avio_wl32(pb, stream->height);
379             avio_wl32(pb, 1); // progressive FIXME
380
381             avio_wl32(pb, stream->height);
382             avio_wl32(pb, stream->width);
383             avio_wl32(pb, stream->height);
384             avio_wl32(pb, stream->width);
385             avio_wl32(pb, 0);
386             avio_wl32(pb, 0);
387
388             avio_wl32(pb, 0);
389             avio_wl32(pb, 0);
390             ff_end_tag(pb, vprp);
391         }
392
393         ff_end_tag(pb, list2);
394     }
395
396     if (pb->seekable) {
397         /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
398         avi->odml_list = ff_start_tag(pb, "JUNK");
399         ffio_wfourcc(pb, "odml");
400         ffio_wfourcc(pb, "dmlh");
401         avio_wl32(pb, 248);
402         for (i = 0; i < 248; i += 4)
403             avio_wl32(pb, 0);
404         ff_end_tag(pb, avi->odml_list);
405     }
406
407     ff_end_tag(pb, list1);
408
409     ff_riff_write_info(s);
410
411
412     padding = s->metadata_header_padding;
413     if (padding < 0)
414         padding = 1016;
415
416     /* some padding for easier tag editing */
417     if (padding) {
418         list2 = ff_start_tag(pb, "JUNK");
419         for (i = padding; i > 0; i -= 4)
420             avio_wl32(pb, 0);
421         ff_end_tag(pb, list2);
422     }
423
424     avi->movi_list = ff_start_tag(pb, "LIST");
425     ffio_wfourcc(pb, "movi");
426
427     avio_flush(pb);
428
429     return 0;
430 }
431
432 static int avi_write_ix(AVFormatContext *s)
433 {
434     AVIOContext *pb = s->pb;
435     AVIContext *avi = s->priv_data;
436     char tag[5];
437     char ix_tag[] = "ix00";
438     int i, j;
439
440     av_assert0(pb->seekable);
441
442     if (avi->riff_id > AVI_MASTER_INDEX_SIZE) {
443         av_log(s, AV_LOG_ERROR, "Invalid riff index %d > %d\n",
444                avi->riff_id, AVI_MASTER_INDEX_SIZE);
445         return AVERROR(EINVAL);
446     }
447
448     for (i = 0; i < s->nb_streams; i++) {
449         AVIStream *avist = s->streams[i]->priv_data;
450         int64_t ix, pos;
451
452         avi_stream2fourcc(tag, i, s->streams[i]->codec->codec_type);
453         ix_tag[3] = '0' + i;
454
455         /* Writing AVI OpenDML leaf index chunk */
456         ix = avio_tell(pb);
457         ffio_wfourcc(pb, ix_tag);      /* ix?? */
458         avio_wl32(pb, avist->indexes.entry * 8 + 24);
459         /* chunk size */
460         avio_wl16(pb, 2);           /* wLongsPerEntry */
461         avio_w8(pb, 0);             /* bIndexSubType (0 == frame index) */
462         avio_w8(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
463         avio_wl32(pb, avist->indexes.entry);
464         /* nEntriesInUse */
465         ffio_wfourcc(pb, tag);         /* dwChunkId */
466         avio_wl64(pb, avi->movi_list); /* qwBaseOffset */
467         avio_wl32(pb, 0);              /* dwReserved_3 (must be 0) */
468
469         for (j = 0; j < avist->indexes.entry; j++) {
470             AVIIentry *ie = avi_get_ientry(&avist->indexes, j);
471             avio_wl32(pb, ie->pos + 8);
472             avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
473                           (ie->flags & 0x10 ? 0 : 0x80000000));
474         }
475         avio_flush(pb);
476         pos = avio_tell(pb);
477
478         /* Updating one entry in the AVI OpenDML master index */
479         avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
480         ffio_wfourcc(pb, "indx");             /* enabling this entry */
481         avio_skip(pb, 8);
482         avio_wl32(pb, avi->riff_id);          /* nEntriesInUse */
483         avio_skip(pb, 16 * avi->riff_id);
484         avio_wl64(pb, ix);                    /* qwOffset */
485         avio_wl32(pb, pos - ix);              /* dwSize */
486         avio_wl32(pb, avist->indexes.entry);  /* dwDuration */
487
488         avio_seek(pb, pos, SEEK_SET);
489     }
490     return 0;
491 }
492
493 static int avi_write_idx1(AVFormatContext *s)
494 {
495     AVIOContext *pb = s->pb;
496     AVIContext *avi = s->priv_data;
497     int64_t idx_chunk;
498     int i;
499     char tag[5];
500
501     if (pb->seekable) {
502         AVIStream *avist;
503         AVIIentry *ie = 0, *tie;
504         int empty, stream_id = -1;
505
506         idx_chunk = ff_start_tag(pb, "idx1");
507         for (i = 0; i < s->nb_streams; i++) {
508             avist        = s->streams[i]->priv_data;
509             avist->entry = 0;
510         }
511
512         do {
513             empty = 1;
514             for (i = 0; i < s->nb_streams; i++) {
515                 avist = s->streams[i]->priv_data;
516                 if (avist->indexes.entry <= avist->entry)
517                     continue;
518
519                 tie = avi_get_ientry(&avist->indexes, avist->entry);
520                 if (empty || tie->pos < ie->pos) {
521                     ie        = tie;
522                     stream_id = i;
523                 }
524                 empty = 0;
525             }
526             if (!empty) {
527                 avist = s->streams[stream_id]->priv_data;
528                 avi_stream2fourcc(tag, stream_id,
529                                   s->streams[stream_id]->codec->codec_type);
530                 ffio_wfourcc(pb, tag);
531                 avio_wl32(pb, ie->flags);
532                 avio_wl32(pb, ie->pos);
533                 avio_wl32(pb, ie->len);
534                 avist->entry++;
535             }
536         } while (!empty);
537         ff_end_tag(pb, idx_chunk);
538
539         avi_write_counters(s, avi->riff_id);
540     }
541     return 0;
542 }
543
544 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
545 {
546     unsigned char tag[5];
547     unsigned int flags = 0;
548     const int stream_index = pkt->stream_index;
549     int size               = pkt->size;
550     AVIContext *avi     = s->priv_data;
551     AVIOContext *pb     = s->pb;
552     AVIStream *avist    = s->streams[stream_index]->priv_data;
553     AVCodecContext *enc = s->streams[stream_index]->codec;
554
555     av_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(pkt->dts), avist->packet_count, stream_index);
556     while (enc->block_align == 0 && pkt->dts != AV_NOPTS_VALUE &&
557            pkt->dts > avist->packet_count && enc->codec_id != AV_CODEC_ID_XSUB && avist->packet_count) {
558         AVPacket empty_packet;
559
560         if (pkt->dts - avist->packet_count > 60000) {
561             av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", pkt->dts - avist->packet_count);
562             return AVERROR(EINVAL);
563         }
564
565         av_init_packet(&empty_packet);
566         empty_packet.size         = 0;
567         empty_packet.data         = NULL;
568         empty_packet.stream_index = stream_index;
569         avi_write_packet(s, &empty_packet);
570         av_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(pkt->dts), avist->packet_count);
571     }
572     avist->packet_count++;
573
574     // Make sure to put an OpenDML chunk when the file size exceeds the limits
575     if (pb->seekable &&
576         (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
577         avi_write_ix(s);
578         ff_end_tag(pb, avi->movi_list);
579
580         if (avi->riff_id == 1)
581             avi_write_idx1(s);
582
583         ff_end_tag(pb, avi->riff_start);
584         avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
585     }
586
587     avi_stream2fourcc(tag, stream_index, enc->codec_type);
588     if (pkt->flags & AV_PKT_FLAG_KEY)
589         flags = 0x10;
590     if (enc->codec_type == AVMEDIA_TYPE_AUDIO)
591         avist->audio_strm_length += size;
592
593     if (s->pb->seekable) {
594         AVIIndex *idx = &avist->indexes;
595         int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
596         int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
597         if (idx->ents_allocated <= idx->entry) {
598             idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
599             if (!idx->cluster) {
600                 idx->ents_allocated = 0;
601                 idx->entry          = 0;
602                 return AVERROR(ENOMEM);
603             }
604             idx->cluster[cl] =
605                 av_malloc(AVI_INDEX_CLUSTER_SIZE * sizeof(AVIIentry));
606             if (!idx->cluster[cl])
607                 return AVERROR(ENOMEM);
608             idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
609         }
610
611         idx->cluster[cl][id].flags = flags;
612         idx->cluster[cl][id].pos   = avio_tell(pb) - avi->movi_list;
613         idx->cluster[cl][id].len   = size;
614         idx->entry++;
615     }
616
617     avio_write(pb, tag, 4);
618     avio_wl32(pb, size);
619     avio_write(pb, pkt->data, size);
620     if (size & 1)
621         avio_w8(pb, 0);
622
623     return 0;
624 }
625
626 static int avi_write_trailer(AVFormatContext *s)
627 {
628     AVIContext *avi = s->priv_data;
629     AVIOContext *pb = s->pb;
630     int res = 0;
631     int i, j, n, nb_frames;
632     int64_t file_size;
633
634     if (pb->seekable) {
635         if (avi->riff_id == 1) {
636             ff_end_tag(pb, avi->movi_list);
637             res = avi_write_idx1(s);
638             ff_end_tag(pb, avi->riff_start);
639         } else {
640             avi_write_ix(s);
641             ff_end_tag(pb, avi->movi_list);
642             ff_end_tag(pb, avi->riff_start);
643
644             file_size = avio_tell(pb);
645             avio_seek(pb, avi->odml_list - 8, SEEK_SET);
646             ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
647             avio_skip(pb, 16);
648
649             for (n = nb_frames = 0; n < s->nb_streams; n++) {
650                 AVCodecContext *stream = s->streams[n]->codec;
651                 AVIStream *avist       = s->streams[n]->priv_data;
652
653                 if (stream->codec_type == AVMEDIA_TYPE_VIDEO) {
654                     if (nb_frames < avist->packet_count)
655                         nb_frames = avist->packet_count;
656                 } else {
657                     if (stream->codec_id == AV_CODEC_ID_MP2 ||
658                         stream->codec_id == AV_CODEC_ID_MP3)
659                         nb_frames += avist->packet_count;
660                 }
661             }
662             avio_wl32(pb, nb_frames);
663             avio_seek(pb, file_size, SEEK_SET);
664
665             avi_write_counters(s, avi->riff_id);
666         }
667     }
668
669     for (i = 0; i < s->nb_streams; i++) {
670         AVIStream *avist = s->streams[i]->priv_data;
671         for (j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)
672             av_freep(&avist->indexes.cluster[j]);
673         av_freep(&avist->indexes.cluster);
674         avist->indexes.ents_allocated = avist->indexes.entry = 0;
675     }
676
677     return res;
678 }
679
680 AVOutputFormat ff_avi_muxer = {
681     .name           = "avi",
682     .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
683     .mime_type      = "video/x-msvideo",
684     .extensions     = "avi",
685     .priv_data_size = sizeof(AVIContext),
686     .audio_codec    = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
687     .video_codec    = AV_CODEC_ID_MPEG4,
688     .write_header   = avi_write_header,
689     .write_packet   = avi_write_packet,
690     .write_trailer  = avi_write_trailer,
691     .codec_tag      = (const AVCodecTag * const []) {
692         ff_codec_bmp_tags, ff_codec_wav_tags, 0
693     },
694 };