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