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