3 * Copyright (c) 2000 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
27 #include "avio_internal.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"
43 * - fill all fields if non streamed (nb_frames for example)
46 typedef struct AVIIentry {
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 */
58 typedef struct AVIIndex {
60 int64_t audio_strm_offset;
63 int master_odml_riff_id_base;
67 typedef struct AVIContext {
69 AVPacket *empty_packet;
70 int64_t riff_start, movi_list, odml_list;
71 int64_t frames_hdr_all;
73 int reserve_index_space;
74 int master_index_max_size;
75 int write_channel_mask;
79 typedef struct AVIStream {
80 int64_t frames_hdr_strm;
81 int64_t audio_strm_length;
91 int64_t strh_flags_offset;
93 uint32_t palette[AVPALETTE_COUNT];
94 uint32_t old_palette[AVPALETTE_COUNT];
98 static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt);
100 static inline AVIIentry *avi_get_ientry(const AVIIndex *idx, int ent_id)
102 int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
103 int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
104 return &idx->cluster[cl][id];
107 static int avi_add_ientry(AVFormatContext *s, int stream_index, char *tag,
108 unsigned int flags, unsigned int size)
110 AVIContext *avi = s->priv_data;
111 AVIOContext *pb = s->pb;
112 AVIStream *avist = s->streams[stream_index]->priv_data;
113 AVIIndex *idx = &avist->indexes;
114 int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
115 int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
117 if (idx->ents_allocated <= idx->entry) {
118 idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
120 idx->ents_allocated = 0;
122 return AVERROR(ENOMEM);
125 av_malloc(AVI_INDEX_CLUSTER_SIZE * sizeof(AVIIentry));
126 if (!idx->cluster[cl])
127 return AVERROR(ENOMEM);
128 idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
132 memcpy(idx->cluster[cl][id].tag, tag, 4);
134 memset(idx->cluster[cl][id].tag, 0, 4);
135 idx->cluster[cl][id].flags = flags;
136 idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
137 idx->cluster[cl][id].len = size;
138 avist->max_size = FFMAX(avist->max_size, size);
144 static av_cold int avi_init(struct AVFormatContext *s)
146 AVIContext *avi = s->priv_data;
148 if (avi->reserve_index_space > 0) {
149 avi->master_index_max_size = (avi->reserve_index_space - AVI_MASTER_INDEX_PREFIX_SIZE) / AVI_MASTER_INDEX_ENTRY_SIZE;
150 avi->master_index_max_size = FFMAX(avi->master_index_max_size, 16);
152 avi->master_index_max_size = AVI_MASTER_INDEX_SIZE_DEFAULT;
153 av_log(s, AV_LOG_DEBUG, "reserve_index_space:%d master_index_max_size:%d\n",
154 avi->reserve_index_space, avi->master_index_max_size);
156 return 1; /* stream initialization continues in avi_write_header */
159 static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
160 const char *riff_tag, const char *list_tag)
162 AVIContext *avi = s->priv_data;
167 for (i = 0; i < s->nb_streams; i++) {
168 AVIStream *avist = s->streams[i]->priv_data;
169 avist->indexes.audio_strm_offset = avist->audio_strm_length;
170 avist->indexes.entry = 0;
173 avi->riff_start = ff_start_tag(pb, "RIFF");
174 ffio_wfourcc(pb, riff_tag);
175 loff = ff_start_tag(pb, "LIST");
176 ffio_wfourcc(pb, list_tag);
180 static char *avi_stream2fourcc(char *tag, int index, enum AVMediaType type)
182 tag[0] = '0' + index / 10;
183 tag[1] = '0' + index % 10;
184 if (type == AVMEDIA_TYPE_VIDEO) {
187 } else if (type == AVMEDIA_TYPE_SUBTITLE) {
188 // note: this is not an official code
199 static int avi_write_counters(AVFormatContext *s, int riff_id)
201 AVIOContext *pb = s->pb;
202 AVIContext *avi = s->priv_data;
203 int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
205 AVCodecParameters *par;
207 file_size = avio_tell(pb);
208 for (n = 0; n < s->nb_streams; n++) {
209 AVIStream *avist = s->streams[n]->priv_data;
211 av_assert0(avist->frames_hdr_strm);
212 par = s->streams[n]->codecpar;
213 avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
214 ff_parse_specific_params(s->streams[n], &au_byterate, &au_ssize, &au_scale);
216 avio_wl32(pb, avist->packet_count);
218 avio_wl32(pb, avist->audio_strm_length / au_ssize);
219 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
220 nb_frames = FFMAX(nb_frames, avist->packet_count);
223 av_assert0(avi->frames_hdr_all);
224 avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
225 avio_wl32(pb, nb_frames);
227 avio_seek(pb, file_size, SEEK_SET);
232 static void write_odml_master(AVFormatContext *s, int stream_index)
234 AVIOContext *pb = s->pb;
235 AVIContext *avi = s->priv_data;
236 AVStream *st = s->streams[stream_index];
237 AVCodecParameters *par = st->codecpar;
238 AVIStream *avist = st->priv_data;
239 unsigned char tag[5];
242 /* Starting to lay out AVI OpenDML master index.
243 * We want to make it JUNK entry for now, since we'd
244 * like to get away without making AVI an OpenDML one
245 * for compatibility reasons. */
246 avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
247 avio_wl16(pb, 4); /* wLongsPerEntry */
248 avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
249 avio_w8(pb, 0); /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
250 avio_wl32(pb, 0); /* nEntriesInUse (will fill out later on) */
251 ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, par->codec_type));
253 avio_wl64(pb, 0); /* dwReserved[3] */
254 avio_wl32(pb, 0); /* Must be 0. */
255 for (j = 0; j < avi->master_index_max_size * 2; j++)
257 ff_end_tag(pb, avist->indexes.indx_start);
260 static int avi_write_header(AVFormatContext *s)
262 AVIContext *avi = s->priv_data;
263 AVIOContext *pb = s->pb;
264 int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
265 int64_t max_stream_duration = 0;
266 AVCodecParameters *video_par;
267 AVStream *video_st = NULL;
268 int64_t list1, list2, strh, strf;
269 AVDictionaryEntry *t = NULL;
272 if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
273 av_log(s, AV_LOG_ERROR, "AVI does not support "
274 ">"AV_STRINGIFY(AVI_MAX_STREAM_COUNT)" streams\n");
275 return AVERROR(EINVAL);
278 avi->empty_packet = av_packet_alloc();
279 if (!avi->empty_packet)
280 return AVERROR(ENOMEM);
282 for (n = 0; n < s->nb_streams; n++) {
283 s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));
284 if (!s->streams[n]->priv_data)
285 return AVERROR(ENOMEM);
290 list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
293 ffio_wfourcc(pb, "avih");
294 avio_wl32(pb, 14 * 4);
298 for (n = 0; n < s->nb_streams; n++) {
299 AVCodecParameters *par = s->streams[n]->codecpar;
300 AVStream *st = s->streams[n];
301 bitrate = FFMIN(bitrate + par->bit_rate, INT32_MAX);
302 if (st->duration > 0) {
303 int64_t stream_duration = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
304 max_stream_duration = FFMAX(stream_duration, max_stream_duration);
306 if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
312 /* guess master index size based on bitrate and duration */
313 if (!avi->reserve_index_space) {
314 double duration_est, filesize_est;
316 duration_est = (double)s->duration / AV_TIME_BASE;
317 else if (max_stream_duration > 0)
318 duration_est = (double)max_stream_duration / AV_TIME_BASE;
320 duration_est = 10 * 60 * 60; /* default to 10 hours */
321 filesize_est = duration_est * (bitrate / 8) * 1.10; /* add 10% safety margin for muxer+bitrate */
322 avi->master_index_max_size = FFMAX((int)ceil(filesize_est / AVI_MAX_RIFF_SIZE) + 1,
323 avi->master_index_max_size);
324 av_log(s, AV_LOG_DEBUG, "duration_est:%0.3f, filesize_est:%0.1fGiB, master_index_max_size:%d\n",
325 duration_est, filesize_est / (1024*1024*1024), avi->master_index_max_size);
330 // TODO: should be avg_frame_rate
332 avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_st->time_base.num /
333 video_st->time_base.den));
336 avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
337 avio_wl32(pb, 0); /* padding */
338 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
339 avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
341 avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
342 avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
343 avio_wl32(pb, nb_frames); /* nb frames, filled later */
344 avio_wl32(pb, 0); /* initial frame */
345 avio_wl32(pb, s->nb_streams); /* nb streams */
346 avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
348 avio_wl32(pb, video_par->width);
349 avio_wl32(pb, video_par->height);
354 avio_wl32(pb, 0); /* reserved */
355 avio_wl32(pb, 0); /* reserved */
356 avio_wl32(pb, 0); /* reserved */
357 avio_wl32(pb, 0); /* reserved */
360 for (i = 0; i < n; i++) {
361 AVStream *st = s->streams[i];
362 AVCodecParameters *par = st->codecpar;
363 AVIStream *avist = st->priv_data;
364 list2 = ff_start_tag(pb, "LIST");
365 ffio_wfourcc(pb, "strl");
367 /* stream generic header */
368 strh = ff_start_tag(pb, "strh");
369 switch (par->codec_type) {
370 case AVMEDIA_TYPE_SUBTITLE:
371 // XSUB subtitles behave like video tracks, other subtitles
372 // are not (yet) supported.
373 if (par->codec_id != AV_CODEC_ID_XSUB) {
374 avpriv_report_missing_feature(s, "Subtitle streams other than DivX XSUB");
375 return AVERROR_PATCHWELCOME;
377 case AVMEDIA_TYPE_VIDEO:
378 ffio_wfourcc(pb, "vids");
380 case AVMEDIA_TYPE_AUDIO:
381 ffio_wfourcc(pb, "auds");
383 // case AVMEDIA_TYPE_TEXT:
384 // ffio_wfourcc(pb, "txts");
386 case AVMEDIA_TYPE_DATA:
387 ffio_wfourcc(pb, "dats");
390 if (par->codec_type == AVMEDIA_TYPE_VIDEO ||
391 par->codec_id == AV_CODEC_ID_XSUB)
392 avio_wl32(pb, par->codec_tag);
395 avist->strh_flags_offset = avio_tell(pb);
396 avio_wl32(pb, 0); /* flags */
397 avio_wl16(pb, 0); /* priority */
398 avio_wl16(pb, 0); /* language */
399 avio_wl32(pb, 0); /* initial frame */
401 ff_parse_specific_params(st, &au_byterate, &au_ssize, &au_scale);
403 if ( par->codec_type == AVMEDIA_TYPE_VIDEO
404 && par->codec_id != AV_CODEC_ID_XSUB
405 && au_byterate > 1000LL*au_scale) {
409 avpriv_set_pts_info(st, 64, au_scale, au_byterate);
410 if (par->codec_id == AV_CODEC_ID_XSUB)
411 au_scale = au_byterate = 0;
413 avio_wl32(pb, au_scale); /* scale */
414 avio_wl32(pb, au_byterate); /* rate */
416 avio_wl32(pb, 0); /* start */
417 /* remember this offset to fill later */
418 avist->frames_hdr_strm = avio_tell(pb);
419 if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
420 /* FIXME: this may be broken, but who cares */
421 avio_wl32(pb, AVI_MAX_RIFF_SIZE);
423 avio_wl32(pb, 0); /* length, XXX: filled later */
425 /* suggested buffer size, is set to largest chunk size in avi_write_trailer */
426 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
427 avio_wl32(pb, 1024 * 1024);
428 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
429 avio_wl32(pb, 12 * 1024);
432 avio_wl32(pb, -1); /* quality */
433 avio_wl32(pb, au_ssize); /* sample size */
435 avio_wl16(pb, par->width);
436 avio_wl16(pb, par->height);
437 ff_end_tag(pb, strh);
439 if (par->codec_type != AVMEDIA_TYPE_DATA) {
441 enum AVPixelFormat pix_fmt;
443 strf = ff_start_tag(pb, "strf");
444 switch (par->codec_type) {
445 case AVMEDIA_TYPE_SUBTITLE:
446 /* XSUB subtitles behave like video tracks, other subtitles
447 * are not (yet) supported. */
448 if (par->codec_id != AV_CODEC_ID_XSUB)
450 case AVMEDIA_TYPE_VIDEO:
451 /* WMP expects RGB 5:5:5 rawvideo in avi to have bpp set to 16. */
453 && par->codec_id == AV_CODEC_ID_RAWVIDEO
454 && par->format == AV_PIX_FMT_RGB555LE
455 && par->bits_per_coded_sample == 15)
456 par->bits_per_coded_sample = 16;
457 avist->pal_offset = avio_tell(pb) + 40;
458 ff_put_bmp_header(pb, par, 0, 0, avi->flipped_raw_rgb);
459 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
460 par->bits_per_coded_sample);
462 && par->codec_id == AV_CODEC_ID_RAWVIDEO
463 && par->format != pix_fmt
464 && par->format != AV_PIX_FMT_NONE)
465 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to avi, output file will be unreadable\n",
466 av_get_pix_fmt_name(par->format));
468 if (par->format == AV_PIX_FMT_PAL8) {
469 if (par->bits_per_coded_sample < 0 || par->bits_per_coded_sample > 8) {
470 av_log(s, AV_LOG_ERROR, "PAL8 with %d bps is not allowed\n", par->bits_per_coded_sample);
471 return AVERROR(EINVAL);
476 case AVMEDIA_TYPE_AUDIO:
477 flags = (avi->write_channel_mask == 0) ? FF_PUT_WAV_HEADER_SKIP_CHANNELMASK : 0;
478 if ((ret = ff_put_wav_header(s, pb, par, flags)) < 0)
482 av_log(s, AV_LOG_ERROR,
483 "Invalid or not supported codec type '%s' found in the input\n",
484 (char *)av_x_if_null(av_get_media_type_string(par->codec_type), "?"));
485 return AVERROR(EINVAL);
487 ff_end_tag(pb, strf);
488 if ((t = av_dict_get(st->metadata, "title", NULL, 0))) {
489 ff_riff_write_info_tag(s->pb, "strn", t->value);
492 if (par->codec_id == AV_CODEC_ID_XSUB
493 && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
494 const char* langstr = ff_convert_lang_to(t->value, AV_LANG_ISO639_1);
497 char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
499 return AVERROR(ENOMEM);
500 ff_riff_write_info_tag(s->pb, "strn", str);
506 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
507 write_odml_master(s, i);
510 if (par->codec_type == AVMEDIA_TYPE_VIDEO &&
511 st->sample_aspect_ratio.num > 0 &&
512 st->sample_aspect_ratio.den > 0) {
513 int vprp = ff_start_tag(pb, "vprp");
514 AVRational dar = av_mul_q(st->sample_aspect_ratio,
515 (AVRational) { par->width,
517 int num, den, fields, i;
518 av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
519 if (par->field_order == AV_FIELD_TT || par->field_order == AV_FIELD_BB ||
520 par->field_order == AV_FIELD_TB || par->field_order == AV_FIELD_BT) {
521 fields = 2; // interlaced
523 fields = 1; // progressive
526 avio_wl32(pb, 0); // video format = unknown
527 avio_wl32(pb, 0); // video standard = unknown
528 // TODO: should be avg_frame_rate
529 avio_wl32(pb, (2LL*st->time_base.den + st->time_base.num - 1) / (2LL * st->time_base.num));
530 avio_wl32(pb, par->width);
531 avio_wl32(pb, par->height);
534 avio_wl32(pb, par->width);
535 avio_wl32(pb, par->height);
536 avio_wl32(pb, fields); // fields per frame
538 for (i = 0; i < fields; i++) {
540 // OpenDML v1.02 is not very specific on what value to use for
541 // start_line when frame data is not coming from a capturing device,
542 // so just use 0/1 depending on the field order for interlaced frames
543 if (par->field_order == AV_FIELD_TT || par->field_order == AV_FIELD_TB) {
544 start_line = (i == 0) ? 0 : 1;
545 } else if (par->field_order == AV_FIELD_BB || par->field_order == AV_FIELD_BT) {
546 start_line = (i == 0) ? 1 : 0;
551 avio_wl32(pb, par->height / fields); // compressed bitmap height
552 avio_wl32(pb, par->width); // compressed bitmap width
553 avio_wl32(pb, par->height / fields); // valid bitmap height
554 avio_wl32(pb, par->width); // valid bitmap width
555 avio_wl32(pb, 0); // valid bitmap X offset
556 avio_wl32(pb, 0); // valid bitmap Y offset
557 avio_wl32(pb, 0); // valid X offset in T
558 avio_wl32(pb, start_line); // valid Y start line
560 ff_end_tag(pb, vprp);
563 ff_end_tag(pb, list2);
566 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
567 /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
568 avi->odml_list = ff_start_tag(pb, "JUNK");
569 ffio_wfourcc(pb, "odml");
570 ffio_wfourcc(pb, "dmlh");
572 for (i = 0; i < 248; i += 4)
574 ff_end_tag(pb, avi->odml_list);
577 ff_end_tag(pb, list1);
579 ff_riff_write_info(s);
582 padding = s->metadata_header_padding;
586 /* some padding for easier tag editing */
588 list2 = ff_start_tag(pb, "JUNK");
589 for (i = padding; i > 0; i -= 4)
591 ff_end_tag(pb, list2);
594 avi->movi_list = ff_start_tag(pb, "LIST");
595 ffio_wfourcc(pb, "movi");
600 static void update_odml_entry(AVFormatContext *s, int stream_index, int64_t ix, int size)
602 AVIOContext *pb = s->pb;
603 AVIContext *avi = s->priv_data;
604 AVIStream *avist = s->streams[stream_index]->priv_data;
606 int au_byterate, au_ssize, au_scale;
610 /* Updating one entry in the AVI OpenDML master index */
611 avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
612 ffio_wfourcc(pb, "indx"); /* enabling this entry */
614 avio_wl32(pb, avi->riff_id - avist->indexes.master_odml_riff_id_base); /* nEntriesInUse */
615 avio_skip(pb, 16 * (avi->riff_id - avist->indexes.master_odml_riff_id_base));
616 avio_wl64(pb, ix); /* qwOffset */
617 avio_wl32(pb, size); /* dwSize */
618 ff_parse_specific_params(s->streams[stream_index], &au_byterate, &au_ssize, &au_scale);
619 if (s->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {
620 uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);
621 if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {
622 avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");
623 avist->sample_requested = 1;
625 avio_wl32(pb, audio_segm_size / au_ssize); /* dwDuration (sample count) */
627 avio_wl32(pb, avist->indexes.entry); /* dwDuration (packet count) */
629 avio_seek(pb, pos, SEEK_SET);
632 static int avi_write_ix(AVFormatContext *s)
634 AVIOContext *pb = s->pb;
635 AVIContext *avi = s->priv_data;
637 char ix_tag[] = "ix00";
640 av_assert0(pb->seekable & AVIO_SEEKABLE_NORMAL);
642 for (i = 0; i < s->nb_streams; i++) {
643 AVIStream *avist = s->streams[i]->priv_data;
644 if (avi->riff_id - avist->indexes.master_odml_riff_id_base == avi->master_index_max_size) {
646 int size = AVI_MASTER_INDEX_PREFIX_SIZE + AVI_MASTER_INDEX_ENTRY_SIZE * avi->master_index_max_size;
649 update_odml_entry(s, i, pos, size);
650 write_odml_master(s, i);
651 av_assert1(avio_tell(pb) - pos == size);
652 avist->indexes.master_odml_riff_id_base = avi->riff_id - 1;
654 av_assert0(avi->riff_id - avist->indexes.master_odml_riff_id_base < avi->master_index_max_size);
657 for (i = 0; i < s->nb_streams; i++) {
658 AVIStream *avist = s->streams[i]->priv_data;
661 avi_stream2fourcc(tag, i, s->streams[i]->codecpar->codec_type);
664 /* Writing AVI OpenDML leaf index chunk */
666 ffio_wfourcc(pb, ix_tag); /* ix?? */
667 avio_wl32(pb, avist->indexes.entry * 8 + 24);
669 avio_wl16(pb, 2); /* wLongsPerEntry */
670 avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
671 avio_w8(pb, 1); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
672 avio_wl32(pb, avist->indexes.entry);
674 ffio_wfourcc(pb, tag); /* dwChunkId */
675 avio_wl64(pb, avi->movi_list); /* qwBaseOffset */
676 avio_wl32(pb, 0); /* dwReserved_3 (must be 0) */
678 for (j = 0; j < avist->indexes.entry; j++) {
679 AVIIentry *ie = avi_get_ientry(&avist->indexes, j);
680 avio_wl32(pb, ie->pos + 8);
681 avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
682 (ie->flags & 0x10 ? 0 : 0x80000000));
685 update_odml_entry(s, i, ix, avio_tell(pb) - ix);
690 static int avi_write_idx1(AVFormatContext *s)
692 AVIOContext *pb = s->pb;
693 AVIContext *avi = s->priv_data;
698 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
700 AVIIentry *ie = 0, *tie;
701 int empty, stream_id = -1;
703 idx_chunk = ff_start_tag(pb, "idx1");
704 for (i = 0; i < s->nb_streams; i++) {
705 avist = s->streams[i]->priv_data;
711 for (i = 0; i < s->nb_streams; i++) {
712 avist = s->streams[i]->priv_data;
713 if (avist->indexes.entry <= avist->entry)
716 tie = avi_get_ientry(&avist->indexes, avist->entry);
717 if (empty || tie->pos < ie->pos) {
724 avist = s->streams[stream_id]->priv_data;
726 ffio_wfourcc(pb, ie->tag);
728 avi_stream2fourcc(tag, stream_id,
729 s->streams[stream_id]->codecpar->codec_type);
730 ffio_wfourcc(pb, tag);
732 avio_wl32(pb, ie->flags);
733 avio_wl32(pb, ie->pos);
734 avio_wl32(pb, ie->len);
738 ff_end_tag(pb, idx_chunk);
740 avi_write_counters(s, avi->riff_id);
745 static int write_skip_frames(AVFormatContext *s, int stream_index, int64_t dts)
747 AVIContext *avi = s->priv_data;
748 AVIStream *avist = s->streams[stream_index]->priv_data;
749 AVCodecParameters *par = s->streams[stream_index]->codecpar;
751 ff_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(dts), avist->packet_count, stream_index);
752 while (par->block_align == 0 && dts != AV_NOPTS_VALUE &&
753 dts > avist->packet_count && par->codec_id != AV_CODEC_ID_XSUB && avist->packet_count) {
755 if (dts - avist->packet_count > 60000) {
756 av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", dts - avist->packet_count);
757 return AVERROR(EINVAL);
760 avi->empty_packet->stream_index = stream_index;
761 avi_write_packet_internal(s, avi->empty_packet);
762 ff_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(dts), avist->packet_count);
768 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
770 const int stream_index = pkt->stream_index;
771 AVCodecParameters *par = s->streams[stream_index]->codecpar;
774 if (par->codec_id == AV_CODEC_ID_H264 && par->codec_tag == MKTAG('H','2','6','4') && pkt->size) {
775 ret = ff_check_h264_startcode(s, s->streams[stream_index], pkt);
780 if ((ret = write_skip_frames(s, stream_index, pkt->dts)) < 0)
784 return avi_write_packet_internal(s, pkt); /* Passthrough */
786 if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
787 AVIStream *avist = s->streams[stream_index]->priv_data;
788 AVIOContext *pb = s->pb;
789 AVPacket *opkt = pkt;
791 if (par->codec_id == AV_CODEC_ID_RAWVIDEO && par->codec_tag == 0) {
792 int64_t bpc = par->bits_per_coded_sample != 15 ? par->bits_per_coded_sample : 16;
793 int expected_stride = ((par->width * bpc + 31) >> 5)*4;
794 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, par, expected_stride);
795 if (reshuffle_ret < 0)
796 return reshuffle_ret;
799 if (par->format == AV_PIX_FMT_PAL8) {
800 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, avist->palette);
804 int pal_size = 1 << par->bits_per_coded_sample;
807 av_assert0(par->bits_per_coded_sample >= 0 && par->bits_per_coded_sample <= 8);
809 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) && avist->pal_offset) {
810 int64_t cur_offset = avio_tell(pb);
811 avio_seek(pb, avist->pal_offset, SEEK_SET);
812 for (i = 0; i < pal_size; i++) {
813 uint32_t v = avist->palette[i];
814 avio_wl32(pb, v & 0xffffff);
816 avio_seek(pb, cur_offset, SEEK_SET);
817 memcpy(avist->old_palette, avist->palette, pal_size * 4);
818 avist->pal_offset = 0;
820 if (memcmp(avist->palette, avist->old_palette, pal_size * 4)) {
821 unsigned char tag[5];
822 avi_stream2fourcc(tag, stream_index, par->codec_type);
823 tag[2] = 'p'; tag[3] = 'c';
824 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
825 if (avist->strh_flags_offset) {
826 int64_t cur_offset = avio_tell(pb);
827 avio_seek(pb, avist->strh_flags_offset, SEEK_SET);
828 avio_wl32(pb, AVISF_VIDEO_PALCHANGES);
829 avio_seek(pb, cur_offset, SEEK_SET);
830 avist->strh_flags_offset = 0;
832 ret = avi_add_ientry(s, stream_index, tag, AVIIF_NO_TIME,
837 pc_tag = ff_start_tag(pb, tag);
839 avio_w8(pb, pal_size & 0xFF);
840 avio_wl16(pb, 0); // reserved
841 for (i = 0; i < pal_size; i++) {
842 uint32_t v = avist->palette[i];
845 ff_end_tag(pb, pc_tag);
846 memcpy(avist->old_palette, avist->palette, pal_size * 4);
851 ret = avi_write_packet_internal(s, pkt);
855 av_packet_free(&pkt);
860 return avi_write_packet_internal(s, pkt);
863 static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
865 unsigned char tag[5];
866 unsigned int flags = 0;
867 const int stream_index = pkt->stream_index;
868 int size = pkt->size;
869 AVIContext *avi = s->priv_data;
870 AVIOContext *pb = s->pb;
871 AVIStream *avist = s->streams[stream_index]->priv_data;
872 AVCodecParameters *par = s->streams[stream_index]->codecpar;
874 if (pkt->dts != AV_NOPTS_VALUE)
875 avist->last_dts = pkt->dts + pkt->duration;
877 avist->packet_count++;
879 // Make sure to put an OpenDML chunk when the file size exceeds the limits
880 if ((pb->seekable & AVIO_SEEKABLE_NORMAL) &&
881 (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
883 ff_end_tag(pb, avi->movi_list);
885 if (avi->riff_id == 1)
888 ff_end_tag(pb, avi->riff_start);
889 avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
892 avi_stream2fourcc(tag, stream_index, par->codec_type);
893 if (pkt->flags & AV_PKT_FLAG_KEY)
895 if (par->codec_type == AVMEDIA_TYPE_AUDIO)
896 avist->audio_strm_length += size;
898 if (s->pb->seekable & AVIO_SEEKABLE_NORMAL) {
900 ret = avi_add_ientry(s, stream_index, NULL, flags, size);
905 avio_write(pb, tag, 4);
907 avio_write(pb, pkt->data, size);
914 static int avi_write_trailer(AVFormatContext *s)
916 AVIContext *avi = s->priv_data;
917 AVIOContext *pb = s->pb;
922 for (i = 0; i < s->nb_streams; i++) {
923 AVIStream *avist = s->streams[i]->priv_data;
924 write_skip_frames(s, i, avist->last_dts);
927 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
928 if (avi->riff_id == 1) {
929 ff_end_tag(pb, avi->movi_list);
930 res = avi_write_idx1(s);
931 ff_end_tag(pb, avi->riff_start);
934 ff_end_tag(pb, avi->movi_list);
935 ff_end_tag(pb, avi->riff_start);
937 file_size = avio_tell(pb);
938 avio_seek(pb, avi->odml_list - 8, SEEK_SET);
939 ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
942 for (n = nb_frames = 0; n < s->nb_streams; n++) {
943 AVCodecParameters *par = s->streams[n]->codecpar;
944 AVIStream *avist = s->streams[n]->priv_data;
946 if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
947 if (nb_frames < avist->packet_count)
948 nb_frames = avist->packet_count;
950 if (par->codec_id == AV_CODEC_ID_MP2 ||
951 par->codec_id == AV_CODEC_ID_MP3)
952 nb_frames += avist->packet_count;
955 avio_wl32(pb, nb_frames);
956 avio_seek(pb, file_size, SEEK_SET);
958 avi_write_counters(s, avi->riff_id);
962 if (avi->riff_id >= avi->master_index_max_size) {
963 int index_space = AVI_MASTER_INDEX_PREFIX_SIZE +
964 AVI_MASTER_INDEX_ENTRY_SIZE * avi->riff_id;
965 av_log(s, AV_LOG_WARNING, "Output file not strictly OpenDML compliant, "
966 "consider re-muxing with 'reserve_index_space' option value >= %d\n",
970 for (i = 0; i < s->nb_streams; i++) {
971 AVIStream *avist = s->streams[i]->priv_data;
972 if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
973 avio_seek(pb, avist->frames_hdr_strm + 4, SEEK_SET);
974 avio_wl32(pb, avist->max_size);
981 static void avi_deinit(AVFormatContext *s)
983 AVIContext *avi = s->priv_data;
985 av_packet_free(&avi->empty_packet);
987 for (int i = 0; i < s->nb_streams; i++) {
988 AVIStream *avist = s->streams[i]->priv_data;
991 for (int j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)
992 av_freep(&avist->indexes.cluster[j]);
993 av_freep(&avist->indexes.cluster);
994 avist->indexes.ents_allocated = avist->indexes.entry = 0;
998 #define OFFSET(x) offsetof(AVIContext, x)
999 #define ENC AV_OPT_FLAG_ENCODING_PARAM
1000 static const AVOption options[] = {
1001 { "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 },
1002 { "write_channel_mask", "write channel mask into wave format header", OFFSET(write_channel_mask), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, ENC },
1003 { "flipped_raw_rgb", "Raw RGB bitmaps are stored bottom-up", OFFSET(flipped_raw_rgb), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, ENC },
1007 static const AVClass avi_muxer_class = {
1008 .class_name = "AVI muxer",
1009 .item_name = av_default_item_name,
1011 .version = LIBAVUTIL_VERSION_INT,
1014 AVOutputFormat ff_avi_muxer = {
1016 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
1017 .mime_type = "video/x-msvideo",
1018 .extensions = "avi",
1019 .priv_data_size = sizeof(AVIContext),
1020 .audio_codec = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
1021 .video_codec = AV_CODEC_ID_MPEG4,
1023 .deinit = avi_deinit,
1024 .write_header = avi_write_header,
1025 .write_packet = avi_write_packet,
1026 .write_trailer = avi_write_trailer,
1027 .codec_tag = ff_riff_codec_tags_list,
1028 .priv_class = &avi_muxer_class,