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