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