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