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
29 #include "avio_internal.h"
32 #include "libavformat/avlanguage.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/avutil.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/intreadwrite.h"
37 #include "libavutil/dict.h"
38 #include "libavutil/avassert.h"
39 #include "libavutil/timestamp.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/pixdesc.h"
42 #include "libavcodec/raw.h"
46 * - fill all fields if non streamed (nb_frames for example)
49 typedef struct AVIIentry {
56 #define AVI_INDEX_CLUSTER_SIZE 16384
57 #define AVI_MASTER_INDEX_PREFIX_SIZE (8+2+1+1+4+8+4+4)
58 #define AVI_MASTER_INDEX_ENTRY_SIZE 16 /* bytes per entry */
59 #define AVI_MASTER_INDEX_SIZE_DEFAULT 256 /* number of entries */
61 typedef struct AVIIndex {
63 int64_t audio_strm_offset;
66 int master_odml_riff_id_base;
70 typedef struct AVIContext {
72 int64_t riff_start, movi_list, odml_list;
73 int64_t frames_hdr_all;
75 int reserve_index_space;
76 int master_index_max_size;
77 int write_channel_mask;
80 typedef struct AVIStream {
81 int64_t frames_hdr_strm;
82 int64_t audio_strm_length;
92 int64_t strh_flags_offset;
94 uint32_t palette[AVPALETTE_COUNT];
95 uint32_t old_palette[AVPALETTE_COUNT];
99 static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt);
101 static inline AVIIentry *avi_get_ientry(const AVIIndex *idx, int ent_id)
103 int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
104 int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
105 return &idx->cluster[cl][id];
108 static int avi_add_ientry(AVFormatContext *s, int stream_index, char *tag,
109 unsigned int flags, unsigned int size)
111 AVIContext *avi = s->priv_data;
112 AVIOContext *pb = s->pb;
113 AVIStream *avist = s->streams[stream_index]->priv_data;
114 AVIIndex *idx = &avist->indexes;
115 int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
116 int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
118 if (idx->ents_allocated <= idx->entry) {
119 idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
121 idx->ents_allocated = 0;
123 return AVERROR(ENOMEM);
126 av_malloc(AVI_INDEX_CLUSTER_SIZE * sizeof(AVIIentry));
127 if (!idx->cluster[cl])
128 return AVERROR(ENOMEM);
129 idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
133 memcpy(idx->cluster[cl][id].tag, tag, 4);
135 memset(idx->cluster[cl][id].tag, 0, 4);
136 idx->cluster[cl][id].flags = flags;
137 idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
138 idx->cluster[cl][id].len = size;
139 avist->max_size = FFMAX(avist->max_size, size);
145 static av_cold int avi_init(struct AVFormatContext *s)
147 AVIContext *avi = s->priv_data;
149 if (avi->reserve_index_space > 0) {
150 avi->master_index_max_size = (avi->reserve_index_space - AVI_MASTER_INDEX_PREFIX_SIZE) / AVI_MASTER_INDEX_ENTRY_SIZE;
151 avi->master_index_max_size = FFMAX(avi->master_index_max_size, 16);
153 avi->master_index_max_size = AVI_MASTER_INDEX_SIZE_DEFAULT;
154 av_log(s, AV_LOG_DEBUG, "reserve_index_space:%d master_index_max_size:%d\n",
155 avi->reserve_index_space, avi->master_index_max_size);
157 return 1; /* stream initialization continues in avi_write_header */
160 static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
161 const char *riff_tag, const char *list_tag)
163 AVIContext *avi = s->priv_data;
168 for (i = 0; i < s->nb_streams; i++) {
169 AVIStream *avist = s->streams[i]->priv_data;
170 avist->indexes.audio_strm_offset = avist->audio_strm_length;
171 avist->indexes.entry = 0;
174 avi->riff_start = ff_start_tag(pb, "RIFF");
175 ffio_wfourcc(pb, riff_tag);
176 loff = ff_start_tag(pb, "LIST");
177 ffio_wfourcc(pb, list_tag);
181 static char *avi_stream2fourcc(char *tag, int index, enum AVMediaType type)
183 tag[0] = '0' + index / 10;
184 tag[1] = '0' + index % 10;
185 if (type == AVMEDIA_TYPE_VIDEO) {
188 } else if (type == AVMEDIA_TYPE_SUBTITLE) {
189 // note: this is not an official code
200 static int avi_write_counters(AVFormatContext *s, int riff_id)
202 AVIOContext *pb = s->pb;
203 AVIContext *avi = s->priv_data;
204 int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
206 AVCodecParameters *par;
208 file_size = avio_tell(pb);
209 for (n = 0; n < s->nb_streams; n++) {
210 AVIStream *avist = s->streams[n]->priv_data;
212 av_assert0(avist->frames_hdr_strm);
213 par = s->streams[n]->codecpar;
214 avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
215 ff_parse_specific_params(s->streams[n], &au_byterate, &au_ssize, &au_scale);
217 avio_wl32(pb, avist->packet_count);
219 avio_wl32(pb, avist->audio_strm_length / au_ssize);
220 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
221 nb_frames = FFMAX(nb_frames, avist->packet_count);
224 av_assert0(avi->frames_hdr_all);
225 avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
226 avio_wl32(pb, nb_frames);
228 avio_seek(pb, file_size, SEEK_SET);
233 static void write_odml_master(AVFormatContext *s, int stream_index)
235 AVIOContext *pb = s->pb;
236 AVIContext *avi = s->priv_data;
237 AVStream *st = s->streams[stream_index];
238 AVCodecParameters *par = st->codecpar;
239 AVIStream *avist = st->priv_data;
240 unsigned char tag[5];
243 /* Starting to lay out AVI OpenDML master index.
244 * We want to make it JUNK entry for now, since we'd
245 * like to get away without making AVI an OpenDML one
246 * for compatibility reasons. */
247 avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
248 avio_wl16(pb, 4); /* wLongsPerEntry */
249 avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
250 avio_w8(pb, 0); /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
251 avio_wl32(pb, 0); /* nEntriesInUse (will fill out later on) */
252 ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, par->codec_type));
254 avio_wl64(pb, 0); /* dwReserved[3] */
255 avio_wl32(pb, 0); /* Must be 0. */
256 for (j = 0; j < avi->master_index_max_size * 2; j++)
258 ff_end_tag(pb, avist->indexes.indx_start);
261 static int avi_write_header(AVFormatContext *s)
263 AVIContext *avi = s->priv_data;
264 AVIOContext *pb = s->pb;
265 int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
266 int64_t max_stream_duration = 0;
267 AVCodecParameters *video_par;
268 AVStream *video_st = NULL;
269 int64_t list1, list2, strh, strf;
270 AVDictionaryEntry *t = NULL;
273 if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
274 av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
275 AVI_MAX_STREAM_COUNT);
276 return AVERROR(EINVAL);
279 for (n = 0; n < s->nb_streams; n++) {
280 s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));
281 if (!s->streams[n]->priv_data)
282 return AVERROR(ENOMEM);
287 list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
290 ffio_wfourcc(pb, "avih");
291 avio_wl32(pb, 14 * 4);
295 for (n = 0; n < s->nb_streams; n++) {
296 AVCodecParameters *par = s->streams[n]->codecpar;
297 AVStream *st = s->streams[n];
298 bitrate = FFMIN(bitrate + par->bit_rate, INT32_MAX);
299 if (st->duration > 0) {
300 int64_t stream_duration = av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
301 max_stream_duration = FFMAX(stream_duration, max_stream_duration);
303 if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
309 /* guess master index size based on bitrate and duration */
310 if (!avi->reserve_index_space) {
311 double duration_est, filesize_est;
313 duration_est = (double)s->duration / AV_TIME_BASE;
314 else if (max_stream_duration > 0)
315 duration_est = (double)max_stream_duration / AV_TIME_BASE;
317 duration_est = 10 * 60 * 60; /* default to 10 hours */
318 filesize_est = duration_est * (bitrate / 8) * 1.10; /* add 10% safety margin for muxer+bitrate */
319 avi->master_index_max_size = FFMAX((int)ceil(filesize_est / AVI_MAX_RIFF_SIZE) + 1,
320 avi->master_index_max_size);
321 av_log(s, AV_LOG_DEBUG, "duration_est:%0.3f, filesize_est:%0.1fGiB, master_index_max_size:%d\n",
322 duration_est, filesize_est / (1024*1024*1024), avi->master_index_max_size);
327 // TODO: should be avg_frame_rate
329 avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_st->time_base.num /
330 video_st->time_base.den));
333 avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
334 avio_wl32(pb, 0); /* padding */
336 avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
338 avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
339 avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
340 avio_wl32(pb, nb_frames); /* nb frames, filled later */
341 avio_wl32(pb, 0); /* initial frame */
342 avio_wl32(pb, s->nb_streams); /* nb streams */
343 avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
345 avio_wl32(pb, video_par->width);
346 avio_wl32(pb, video_par->height);
351 avio_wl32(pb, 0); /* reserved */
352 avio_wl32(pb, 0); /* reserved */
353 avio_wl32(pb, 0); /* reserved */
354 avio_wl32(pb, 0); /* reserved */
357 for (i = 0; i < n; i++) {
358 AVStream *st = s->streams[i];
359 AVCodecParameters *par = st->codecpar;
360 AVIStream *avist = st->priv_data;
361 list2 = ff_start_tag(pb, "LIST");
362 ffio_wfourcc(pb, "strl");
364 /* stream generic header */
365 strh = ff_start_tag(pb, "strh");
366 switch (par->codec_type) {
367 case AVMEDIA_TYPE_SUBTITLE:
368 // XSUB subtitles behave like video tracks, other subtitles
369 // are not (yet) supported.
370 if (par->codec_id != AV_CODEC_ID_XSUB) {
371 av_log(s, AV_LOG_ERROR,
372 "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");
373 return AVERROR_PATCHWELCOME;
375 case AVMEDIA_TYPE_VIDEO:
376 ffio_wfourcc(pb, "vids");
378 case AVMEDIA_TYPE_AUDIO:
379 ffio_wfourcc(pb, "auds");
381 // case AVMEDIA_TYPE_TEXT:
382 // ffio_wfourcc(pb, "txts");
384 case AVMEDIA_TYPE_DATA:
385 ffio_wfourcc(pb, "dats");
388 if (par->codec_type == AVMEDIA_TYPE_VIDEO ||
389 par->codec_id == AV_CODEC_ID_XSUB)
390 avio_wl32(pb, par->codec_tag);
393 avist->strh_flags_offset = avio_tell(pb);
394 avio_wl32(pb, 0); /* flags */
395 avio_wl16(pb, 0); /* priority */
396 avio_wl16(pb, 0); /* language */
397 avio_wl32(pb, 0); /* initial frame */
399 ff_parse_specific_params(st, &au_byterate, &au_ssize, &au_scale);
401 if ( par->codec_type == AVMEDIA_TYPE_VIDEO
402 && par->codec_id != AV_CODEC_ID_XSUB
403 && au_byterate > 1000LL*au_scale) {
407 avpriv_set_pts_info(st, 64, au_scale, au_byterate);
408 if (par->codec_id == AV_CODEC_ID_XSUB)
409 au_scale = au_byterate = 0;
411 avio_wl32(pb, au_scale); /* scale */
412 avio_wl32(pb, au_byterate); /* rate */
414 avio_wl32(pb, 0); /* start */
415 /* remember this offset to fill later */
416 avist->frames_hdr_strm = avio_tell(pb);
418 /* FIXME: this may be broken, but who cares */
419 avio_wl32(pb, AVI_MAX_RIFF_SIZE);
421 avio_wl32(pb, 0); /* length, XXX: filled later */
423 /* suggested buffer size, is set to largest chunk size in avi_write_trailer */
424 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
425 avio_wl32(pb, 1024 * 1024);
426 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
427 avio_wl32(pb, 12 * 1024);
430 avio_wl32(pb, -1); /* quality */
431 avio_wl32(pb, au_ssize); /* sample size */
433 avio_wl16(pb, par->width);
434 avio_wl16(pb, par->height);
435 ff_end_tag(pb, strh);
437 if (par->codec_type != AVMEDIA_TYPE_DATA) {
439 enum AVPixelFormat pix_fmt;
441 strf = ff_start_tag(pb, "strf");
442 switch (par->codec_type) {
443 case AVMEDIA_TYPE_SUBTITLE:
444 /* XSUB subtitles behave like video tracks, other subtitles
445 * are not (yet) supported. */
446 if (par->codec_id != AV_CODEC_ID_XSUB)
448 case AVMEDIA_TYPE_VIDEO:
449 /* WMP expects RGB 5:5:5 rawvideo in avi to have bpp set to 16. */
451 && par->codec_id == AV_CODEC_ID_RAWVIDEO
452 && par->format == AV_PIX_FMT_RGB555LE
453 && par->bits_per_coded_sample == 15)
454 par->bits_per_coded_sample = 16;
455 avist->pal_offset = avio_tell(pb) + 40;
456 ff_put_bmp_header(pb, par, ff_codec_bmp_tags, 0, 0);
457 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
458 par->bits_per_coded_sample);
460 && par->codec_id == AV_CODEC_ID_RAWVIDEO
461 && par->format != pix_fmt
462 && par->format != AV_PIX_FMT_NONE)
463 av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to avi, output file will be unreadable\n",
464 av_get_pix_fmt_name(par->format));
466 case AVMEDIA_TYPE_AUDIO:
467 flags = (avi->write_channel_mask == 0) ? FF_PUT_WAV_HEADER_SKIP_CHANNELMASK : 0;
468 if ((ret = ff_put_wav_header(s, pb, par, flags)) < 0)
472 av_log(s, AV_LOG_ERROR,
473 "Invalid or not supported codec type '%s' found in the input\n",
474 (char *)av_x_if_null(av_get_media_type_string(par->codec_type), "?"));
475 return AVERROR(EINVAL);
477 ff_end_tag(pb, strf);
478 if ((t = av_dict_get(st->metadata, "title", NULL, 0))) {
479 ff_riff_write_info_tag(s->pb, "strn", t->value);
482 if (par->codec_id == AV_CODEC_ID_XSUB
483 && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
484 const char* langstr = ff_convert_lang_to(t->value, AV_LANG_ISO639_1);
487 char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
489 return AVERROR(ENOMEM);
490 ff_riff_write_info_tag(s->pb, "strn", str);
497 write_odml_master(s, i);
500 if (par->codec_type == AVMEDIA_TYPE_VIDEO &&
501 st->sample_aspect_ratio.num > 0 &&
502 st->sample_aspect_ratio.den > 0) {
503 int vprp = ff_start_tag(pb, "vprp");
504 AVRational dar = av_mul_q(st->sample_aspect_ratio,
505 (AVRational) { par->width,
508 av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
510 avio_wl32(pb, 0); // video format = unknown
511 avio_wl32(pb, 0); // video standard = unknown
512 // TODO: should be avg_frame_rate
513 avio_wl32(pb, (2LL*st->time_base.den + st->time_base.num - 1) / (2LL * st->time_base.num));
514 avio_wl32(pb, par->width);
515 avio_wl32(pb, par->height);
518 avio_wl32(pb, par->width);
519 avio_wl32(pb, par->height);
520 avio_wl32(pb, 1); // progressive FIXME
522 avio_wl32(pb, par->height);
523 avio_wl32(pb, par->width);
524 avio_wl32(pb, par->height);
525 avio_wl32(pb, par->width);
531 ff_end_tag(pb, vprp);
534 ff_end_tag(pb, list2);
538 /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
539 avi->odml_list = ff_start_tag(pb, "JUNK");
540 ffio_wfourcc(pb, "odml");
541 ffio_wfourcc(pb, "dmlh");
543 for (i = 0; i < 248; i += 4)
545 ff_end_tag(pb, avi->odml_list);
548 ff_end_tag(pb, list1);
550 ff_riff_write_info(s);
553 padding = s->metadata_header_padding;
557 /* some padding for easier tag editing */
559 list2 = ff_start_tag(pb, "JUNK");
560 for (i = padding; i > 0; i -= 4)
562 ff_end_tag(pb, list2);
565 avi->movi_list = ff_start_tag(pb, "LIST");
566 ffio_wfourcc(pb, "movi");
573 static void update_odml_entry(AVFormatContext *s, int stream_index, int64_t ix, int size)
575 AVIOContext *pb = s->pb;
576 AVIContext *avi = s->priv_data;
577 AVIStream *avist = s->streams[stream_index]->priv_data;
579 int au_byterate, au_ssize, au_scale;
584 /* Updating one entry in the AVI OpenDML master index */
585 avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
586 ffio_wfourcc(pb, "indx"); /* enabling this entry */
588 avio_wl32(pb, avi->riff_id - avist->indexes.master_odml_riff_id_base); /* nEntriesInUse */
589 avio_skip(pb, 16 * (avi->riff_id - avist->indexes.master_odml_riff_id_base));
590 avio_wl64(pb, ix); /* qwOffset */
591 avio_wl32(pb, size); /* dwSize */
592 ff_parse_specific_params(s->streams[stream_index], &au_byterate, &au_ssize, &au_scale);
593 if (s->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {
594 uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);
595 if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {
596 avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");
597 avist->sample_requested = 1;
599 avio_wl32(pb, audio_segm_size / au_ssize); /* dwDuration (sample count) */
601 avio_wl32(pb, avist->indexes.entry); /* dwDuration (packet count) */
603 avio_seek(pb, pos, SEEK_SET);
606 static int avi_write_ix(AVFormatContext *s)
608 AVIOContext *pb = s->pb;
609 AVIContext *avi = s->priv_data;
611 char ix_tag[] = "ix00";
614 av_assert0(pb->seekable);
616 for (i = 0; i < s->nb_streams; i++) {
617 AVIStream *avist = s->streams[i]->priv_data;
618 if (avi->riff_id - avist->indexes.master_odml_riff_id_base == avi->master_index_max_size) {
620 int size = AVI_MASTER_INDEX_PREFIX_SIZE + AVI_MASTER_INDEX_ENTRY_SIZE * avi->master_index_max_size;
623 update_odml_entry(s, i, pos, size);
624 write_odml_master(s, i);
625 av_assert1(avio_tell(pb) - pos == size);
626 avist->indexes.master_odml_riff_id_base = avi->riff_id - 1;
628 av_assert0(avi->riff_id - avist->indexes.master_odml_riff_id_base < avi->master_index_max_size);
631 for (i = 0; i < s->nb_streams; i++) {
632 AVIStream *avist = s->streams[i]->priv_data;
635 avi_stream2fourcc(tag, i, s->streams[i]->codecpar->codec_type);
638 /* Writing AVI OpenDML leaf index chunk */
640 ffio_wfourcc(pb, ix_tag); /* ix?? */
641 avio_wl32(pb, avist->indexes.entry * 8 + 24);
643 avio_wl16(pb, 2); /* wLongsPerEntry */
644 avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
645 avio_w8(pb, 1); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
646 avio_wl32(pb, avist->indexes.entry);
648 ffio_wfourcc(pb, tag); /* dwChunkId */
649 avio_wl64(pb, avi->movi_list); /* qwBaseOffset */
650 avio_wl32(pb, 0); /* dwReserved_3 (must be 0) */
652 for (j = 0; j < avist->indexes.entry; j++) {
653 AVIIentry *ie = avi_get_ientry(&avist->indexes, j);
654 avio_wl32(pb, ie->pos + 8);
655 avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
656 (ie->flags & 0x10 ? 0 : 0x80000000));
659 update_odml_entry(s, i, ix, avio_tell(pb) - ix);
664 static int avi_write_idx1(AVFormatContext *s)
666 AVIOContext *pb = s->pb;
667 AVIContext *avi = s->priv_data;
674 AVIIentry *ie = 0, *tie;
675 int empty, stream_id = -1;
677 idx_chunk = ff_start_tag(pb, "idx1");
678 for (i = 0; i < s->nb_streams; i++) {
679 avist = s->streams[i]->priv_data;
685 for (i = 0; i < s->nb_streams; i++) {
686 avist = s->streams[i]->priv_data;
687 if (avist->indexes.entry <= avist->entry)
690 tie = avi_get_ientry(&avist->indexes, avist->entry);
691 if (empty || tie->pos < ie->pos) {
698 avist = s->streams[stream_id]->priv_data;
700 ffio_wfourcc(pb, ie->tag);
702 avi_stream2fourcc(tag, stream_id,
703 s->streams[stream_id]->codecpar->codec_type);
704 ffio_wfourcc(pb, tag);
706 avio_wl32(pb, ie->flags);
707 avio_wl32(pb, ie->pos);
708 avio_wl32(pb, ie->len);
712 ff_end_tag(pb, idx_chunk);
714 avi_write_counters(s, avi->riff_id);
719 static int write_skip_frames(AVFormatContext *s, int stream_index, int64_t dts)
721 AVIStream *avist = s->streams[stream_index]->priv_data;
722 AVCodecParameters *par = s->streams[stream_index]->codecpar;
724 ff_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(dts), avist->packet_count, stream_index);
725 while (par->block_align == 0 && dts != AV_NOPTS_VALUE &&
726 dts > avist->packet_count && par->codec_id != AV_CODEC_ID_XSUB && avist->packet_count) {
727 AVPacket empty_packet;
729 if (dts - avist->packet_count > 60000) {
730 av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", dts - avist->packet_count);
731 return AVERROR(EINVAL);
734 av_init_packet(&empty_packet);
735 empty_packet.size = 0;
736 empty_packet.data = NULL;
737 empty_packet.stream_index = stream_index;
738 avi_write_packet_internal(s, &empty_packet);
739 ff_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(dts), avist->packet_count);
745 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
747 const int stream_index = pkt->stream_index;
748 AVCodecParameters *par = s->streams[stream_index]->codecpar;
751 if (par->codec_id == AV_CODEC_ID_H264 && par->codec_tag == MKTAG('H','2','6','4') && pkt->size) {
752 ret = ff_check_h264_startcode(s, s->streams[stream_index], pkt);
757 if ((ret = write_skip_frames(s, stream_index, pkt->dts)) < 0)
761 return avi_write_packet_internal(s, pkt); /* Passthrough */
763 if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
764 AVIStream *avist = s->streams[stream_index]->priv_data;
765 AVIOContext *pb = s->pb;
766 AVPacket *opkt = pkt;
768 if (par->codec_id == AV_CODEC_ID_RAWVIDEO && par->codec_tag == 0) {
769 int64_t bpc = par->bits_per_coded_sample != 15 ? par->bits_per_coded_sample : 16;
770 int expected_stride = ((par->width * bpc + 31) >> 5)*4;
771 reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, par, expected_stride);
772 if (reshuffle_ret < 0)
773 return reshuffle_ret;
776 if (par->format == AV_PIX_FMT_PAL8) {
777 ret = ff_get_packet_palette(s, opkt, reshuffle_ret, avist->palette);
781 int pal_size = 1 << par->bits_per_coded_sample;
784 av_assert0(par->bits_per_coded_sample >= 0 && par->bits_per_coded_sample <= 8);
786 if (pb->seekable && avist->pal_offset) {
787 int64_t cur_offset = avio_tell(pb);
788 avio_seek(pb, avist->pal_offset, SEEK_SET);
789 for (i = 0; i < pal_size; i++) {
790 uint32_t v = avist->palette[i];
791 avio_wl32(pb, v & 0xffffff);
793 avio_seek(pb, cur_offset, SEEK_SET);
794 memcpy(avist->old_palette, avist->palette, pal_size * 4);
795 avist->pal_offset = 0;
797 if (memcmp(avist->palette, avist->old_palette, pal_size * 4)) {
798 unsigned char tag[5];
799 avi_stream2fourcc(tag, stream_index, par->codec_type);
800 tag[2] = 'p'; tag[3] = 'c';
801 if (s->pb->seekable) {
802 if (avist->strh_flags_offset) {
803 int64_t cur_offset = avio_tell(pb);
804 avio_seek(pb, avist->strh_flags_offset, SEEK_SET);
805 avio_wl32(pb, AVISF_VIDEO_PALCHANGES);
806 avio_seek(pb, cur_offset, SEEK_SET);
807 avist->strh_flags_offset = 0;
809 ret = avi_add_ientry(s, stream_index, tag, AVIIF_NO_TIME,
814 pc_tag = ff_start_tag(pb, tag);
816 avio_w8(pb, pal_size & 0xFF);
817 avio_wl16(pb, 0); // reserved
818 for (i = 0; i < pal_size; i++) {
819 uint32_t v = avist->palette[i];
822 ff_end_tag(pb, pc_tag);
823 memcpy(avist->old_palette, avist->palette, pal_size * 4);
828 ret = avi_write_packet_internal(s, pkt);
832 av_packet_free(&pkt);
837 return avi_write_packet_internal(s, pkt);
840 static int avi_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
842 unsigned char tag[5];
843 unsigned int flags = 0;
844 const int stream_index = pkt->stream_index;
845 int size = pkt->size;
846 AVIContext *avi = s->priv_data;
847 AVIOContext *pb = s->pb;
848 AVIStream *avist = s->streams[stream_index]->priv_data;
849 AVCodecParameters *par = s->streams[stream_index]->codecpar;
851 if (pkt->dts != AV_NOPTS_VALUE)
852 avist->last_dts = pkt->dts + pkt->duration;
854 avist->packet_count++;
856 // Make sure to put an OpenDML chunk when the file size exceeds the limits
858 (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
860 ff_end_tag(pb, avi->movi_list);
862 if (avi->riff_id == 1)
865 ff_end_tag(pb, avi->riff_start);
866 avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
869 avi_stream2fourcc(tag, stream_index, par->codec_type);
870 if (pkt->flags & AV_PKT_FLAG_KEY)
872 if (par->codec_type == AVMEDIA_TYPE_AUDIO)
873 avist->audio_strm_length += size;
875 if (s->pb->seekable) {
877 ret = avi_add_ientry(s, stream_index, NULL, flags, size);
882 avio_write(pb, tag, 4);
884 avio_write(pb, pkt->data, size);
891 static int avi_write_trailer(AVFormatContext *s)
893 AVIContext *avi = s->priv_data;
894 AVIOContext *pb = s->pb;
896 int i, j, n, nb_frames;
899 for (i = 0; i < s->nb_streams; i++) {
900 AVIStream *avist = s->streams[i]->priv_data;
901 write_skip_frames(s, i, avist->last_dts);
905 if (avi->riff_id == 1) {
906 ff_end_tag(pb, avi->movi_list);
907 res = avi_write_idx1(s);
908 ff_end_tag(pb, avi->riff_start);
911 ff_end_tag(pb, avi->movi_list);
912 ff_end_tag(pb, avi->riff_start);
914 file_size = avio_tell(pb);
915 avio_seek(pb, avi->odml_list - 8, SEEK_SET);
916 ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
919 for (n = nb_frames = 0; n < s->nb_streams; n++) {
920 AVCodecParameters *par = s->streams[n]->codecpar;
921 AVIStream *avist = s->streams[n]->priv_data;
923 if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
924 if (nb_frames < avist->packet_count)
925 nb_frames = avist->packet_count;
927 if (par->codec_id == AV_CODEC_ID_MP2 ||
928 par->codec_id == AV_CODEC_ID_MP3)
929 nb_frames += avist->packet_count;
932 avio_wl32(pb, nb_frames);
933 avio_seek(pb, file_size, SEEK_SET);
935 avi_write_counters(s, avi->riff_id);
939 if (avi->riff_id >= avi->master_index_max_size) {
940 int index_space = AVI_MASTER_INDEX_PREFIX_SIZE +
941 AVI_MASTER_INDEX_ENTRY_SIZE * avi->riff_id;
942 av_log(s, AV_LOG_WARNING, "Output file not strictly OpenDML compliant, "
943 "consider re-muxing with 'reserve_index_space' option value >= %d\n",
947 for (i = 0; i < s->nb_streams; i++) {
948 AVIStream *avist = s->streams[i]->priv_data;
949 for (j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)
950 av_freep(&avist->indexes.cluster[j]);
951 av_freep(&avist->indexes.cluster);
952 avist->indexes.ents_allocated = avist->indexes.entry = 0;
954 avio_seek(pb, avist->frames_hdr_strm + 4, SEEK_SET);
955 avio_wl32(pb, avist->max_size);
962 #define OFFSET(x) offsetof(AVIContext, x)
963 #define ENC AV_OPT_FLAG_ENCODING_PARAM
964 static const AVOption options[] = {
965 { "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 },
966 { "write_channel_mask", "write channel mask into wave format header", OFFSET(write_channel_mask), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, ENC },
970 static const AVClass avi_muxer_class = {
971 .class_name = "AVI muxer",
972 .item_name = av_default_item_name,
974 .version = LIBAVUTIL_VERSION_INT,
977 AVOutputFormat ff_avi_muxer = {
979 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
980 .mime_type = "video/x-msvideo",
982 .priv_data_size = sizeof(AVIContext),
983 .audio_codec = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
984 .video_codec = AV_CODEC_ID_MPEG4,
986 .write_header = avi_write_header,
987 .write_packet = avi_write_packet,
988 .write_trailer = avi_write_trailer,
989 .codec_tag = (const AVCodecTag * const []) {
990 ff_codec_bmp_tags, ff_codec_wav_tags, 0
992 .priv_class = &avi_muxer_class,