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