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