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