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