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"
29 #include "libavformat/avlanguage.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/dict.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/timestamp.h"
38 * - fill all fields if non streamed (nb_frames for example)
41 typedef struct AVIIentry {
42 unsigned int flags, pos, len;
45 #define AVI_INDEX_CLUSTER_SIZE 16384
47 typedef struct AVIIndex {
55 int64_t riff_start, movi_list, odml_list;
56 int64_t frames_hdr_all;
61 int64_t frames_hdr_strm;
62 int64_t audio_strm_length;
69 static inline AVIIentry* avi_get_ientry(AVIIndex* idx, int ent_id)
71 int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
72 int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
73 return &idx->cluster[cl][id];
76 static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
77 const char* riff_tag, const char* list_tag)
79 AVIContext *avi= s->priv_data;
84 for (i=0; i<s->nb_streams; i++){
85 AVIStream *avist= s->streams[i]->priv_data;
86 avist->indexes.entry = 0;
89 avi->riff_start = ff_start_tag(pb, "RIFF");
90 ffio_wfourcc(pb, riff_tag);
91 loff = ff_start_tag(pb, "LIST");
92 ffio_wfourcc(pb, list_tag);
96 static char* avi_stream2fourcc(char* tag, int index, enum AVMediaType type)
98 tag[0] = '0' + index/10;
99 tag[1] = '0' + index%10;
100 if (type == AVMEDIA_TYPE_VIDEO) {
103 } else if (type == AVMEDIA_TYPE_SUBTITLE) {
104 // note: this is not an official code
115 static int avi_write_counters(AVFormatContext* s, int riff_id)
117 AVIOContext *pb = s->pb;
118 AVIContext *avi = s->priv_data;
119 int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
121 AVCodecContext* stream;
123 file_size = avio_tell(pb);
124 for(n = 0; n < s->nb_streams; n++) {
125 AVIStream *avist= s->streams[n]->priv_data;
127 av_assert0(avist->frames_hdr_strm);
128 stream = s->streams[n]->codec;
129 avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
130 ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
132 avio_wl32(pb, avist->packet_count);
134 avio_wl32(pb, avist->audio_strm_length / au_ssize);
136 if(stream->codec_type == AVMEDIA_TYPE_VIDEO)
137 nb_frames = FFMAX(nb_frames, avist->packet_count);
140 av_assert0(avi->frames_hdr_all);
141 avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
142 avio_wl32(pb, nb_frames);
144 avio_seek(pb, file_size, SEEK_SET);
149 static int avi_write_header(AVFormatContext *s)
151 AVIContext *avi = s->priv_data;
152 AVIOContext *pb = s->pb;
153 int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
154 AVCodecContext *stream, *video_enc;
155 int64_t list1, list2, strh, strf;
156 AVDictionaryEntry *t = NULL;
158 if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
159 av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
160 AVI_MAX_STREAM_COUNT);
161 return AVERROR(EINVAL);
164 for(n=0;n<s->nb_streams;n++) {
165 s->streams[n]->priv_data= av_mallocz(sizeof(AVIStream));
166 if(!s->streams[n]->priv_data)
167 return AVERROR(ENOMEM);
172 list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
175 ffio_wfourcc(pb, "avih");
176 avio_wl32(pb, 14 * 4);
180 for(n=0;n<s->nb_streams;n++) {
181 stream = s->streams[n]->codec;
182 bitrate += stream->bit_rate;
183 if (stream->codec_type == AVMEDIA_TYPE_VIDEO)
190 avio_wl32(pb, (uint32_t)(INT64_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
194 avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
195 avio_wl32(pb, 0); /* padding */
197 avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
199 avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
200 avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
201 avio_wl32(pb, nb_frames); /* nb frames, filled later */
202 avio_wl32(pb, 0); /* initial frame */
203 avio_wl32(pb, s->nb_streams); /* nb streams */
204 avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
206 avio_wl32(pb, video_enc->width);
207 avio_wl32(pb, video_enc->height);
212 avio_wl32(pb, 0); /* reserved */
213 avio_wl32(pb, 0); /* reserved */
214 avio_wl32(pb, 0); /* reserved */
215 avio_wl32(pb, 0); /* reserved */
219 AVIStream *avist= s->streams[i]->priv_data;
220 list2 = ff_start_tag(pb, "LIST");
221 ffio_wfourcc(pb, "strl");
223 stream = s->streams[i]->codec;
225 /* stream generic header */
226 strh = ff_start_tag(pb, "strh");
227 switch(stream->codec_type) {
228 case AVMEDIA_TYPE_SUBTITLE:
229 // XSUB subtitles behave like video tracks, other subtitles
230 // are not (yet) supported.
231 if (stream->codec_id != AV_CODEC_ID_XSUB) {
232 av_log(s, AV_LOG_ERROR, "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");
233 return AVERROR_PATCHWELCOME;
235 case AVMEDIA_TYPE_VIDEO: ffio_wfourcc(pb, "vids"); break;
236 case AVMEDIA_TYPE_AUDIO: ffio_wfourcc(pb, "auds"); break;
237 // case AVMEDIA_TYPE_TEXT : ffio_wfourcc(pb, "txts"); break;
238 case AVMEDIA_TYPE_DATA : ffio_wfourcc(pb, "dats"); break;
240 if(stream->codec_type == AVMEDIA_TYPE_VIDEO ||
241 stream->codec_id == AV_CODEC_ID_XSUB)
242 avio_wl32(pb, stream->codec_tag);
245 avio_wl32(pb, 0); /* flags */
246 avio_wl16(pb, 0); /* priority */
247 avio_wl16(pb, 0); /* language */
248 avio_wl32(pb, 0); /* initial frame */
250 ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
252 if ( stream->codec_type == AVMEDIA_TYPE_VIDEO
253 && stream->codec_id != AV_CODEC_ID_XSUB
254 && au_byterate > 1000LL*au_scale) {
258 avpriv_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
259 if(stream->codec_id == AV_CODEC_ID_XSUB)
260 au_scale = au_byterate = 0;
262 avio_wl32(pb, au_scale); /* scale */
263 avio_wl32(pb, au_byterate); /* rate */
265 avio_wl32(pb, 0); /* start */
266 avist->frames_hdr_strm = avio_tell(pb); /* remember this offset to fill later */
268 avio_wl32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
270 avio_wl32(pb, 0); /* length, XXX: filled later */
272 /* suggested buffer size */ //FIXME set at the end to largest chunk
273 if(stream->codec_type == AVMEDIA_TYPE_VIDEO)
274 avio_wl32(pb, 1024 * 1024);
275 else if(stream->codec_type == AVMEDIA_TYPE_AUDIO)
276 avio_wl32(pb, 12 * 1024);
279 avio_wl32(pb, -1); /* quality */
280 avio_wl32(pb, au_ssize); /* sample size */
282 avio_wl16(pb, stream->width);
283 avio_wl16(pb, stream->height);
284 ff_end_tag(pb, strh);
286 if(stream->codec_type != AVMEDIA_TYPE_DATA){
289 strf = ff_start_tag(pb, "strf");
290 switch(stream->codec_type) {
291 case AVMEDIA_TYPE_SUBTITLE:
292 // XSUB subtitles behave like video tracks, other subtitles
293 // are not (yet) supported.
294 if (stream->codec_id != AV_CODEC_ID_XSUB) break;
295 case AVMEDIA_TYPE_VIDEO:
296 ff_put_bmp_header(pb, stream, ff_codec_bmp_tags, 0);
298 case AVMEDIA_TYPE_AUDIO:
299 if ((ret = ff_put_wav_header(pb, stream)) < 0) {
304 av_log(s, AV_LOG_ERROR,
305 "Invalid or not supported codec type '%s' found in the input\n",
306 (char *)av_x_if_null(av_get_media_type_string(stream->codec_type), "?"));
307 return AVERROR(EINVAL);
309 ff_end_tag(pb, strf);
310 if ((t = av_dict_get(s->streams[i]->metadata, "title", NULL, 0))) {
311 ff_riff_write_info_tag(s->pb, "strn", t->value);
314 if(stream->codec_id == AV_CODEC_ID_XSUB
315 && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
316 const char* langstr = av_convert_lang_to(t->value, AV_LANG_ISO639_1);
319 char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
320 ff_riff_write_info_tag(s->pb, "strn", str);
327 unsigned char tag[5];
330 /* Starting to lay out AVI OpenDML master index.
331 * We want to make it JUNK entry for now, since we'd
332 * like to get away without making AVI an OpenDML one
333 * for compatibility reasons.
335 avist->indexes.entry = avist->indexes.ents_allocated = 0;
336 avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
337 avio_wl16(pb, 4); /* wLongsPerEntry */
338 avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
339 avio_w8(pb, 0); /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
340 avio_wl32(pb, 0); /* nEntriesInUse (will fill out later on) */
341 ffio_wfourcc(pb, avi_stream2fourcc(tag, i, stream->codec_type));
343 avio_wl64(pb, 0); /* dwReserved[3]
344 avio_wl32(pb, 0); Must be 0. */
345 for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
347 ff_end_tag(pb, avist->indexes.indx_start);
350 if( stream->codec_type == AVMEDIA_TYPE_VIDEO
351 && s->streams[i]->sample_aspect_ratio.num>0
352 && s->streams[i]->sample_aspect_ratio.den>0){
353 int vprp= ff_start_tag(pb, "vprp");
354 AVRational dar = av_mul_q(s->streams[i]->sample_aspect_ratio,
355 (AVRational){stream->width, stream->height});
357 av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
359 avio_wl32(pb, 0); //video format = unknown
360 avio_wl32(pb, 0); //video standard= unknown
361 avio_wl32(pb, lrintf(1.0/av_q2d(stream->time_base)));
362 avio_wl32(pb, stream->width );
363 avio_wl32(pb, stream->height);
366 avio_wl32(pb, stream->width );
367 avio_wl32(pb, stream->height);
368 avio_wl32(pb, 1); //progressive FIXME
370 avio_wl32(pb, stream->height);
371 avio_wl32(pb, stream->width );
372 avio_wl32(pb, stream->height);
373 avio_wl32(pb, stream->width );
379 ff_end_tag(pb, vprp);
382 ff_end_tag(pb, list2);
386 /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
387 avi->odml_list = ff_start_tag(pb, "JUNK");
388 ffio_wfourcc(pb, "odml");
389 ffio_wfourcc(pb, "dmlh");
391 for (i = 0; i < 248; i+= 4)
393 ff_end_tag(pb, avi->odml_list);
396 ff_end_tag(pb, list1);
398 ff_riff_write_info(s);
400 /* some padding for easier tag editing */
401 list2 = ff_start_tag(pb, "JUNK");
402 for (i = 0; i < 1016; i += 4)
404 ff_end_tag(pb, list2);
406 avi->movi_list = ff_start_tag(pb, "LIST");
407 ffio_wfourcc(pb, "movi");
414 static int avi_write_ix(AVFormatContext *s)
416 AVIOContext *pb = s->pb;
417 AVIContext *avi = s->priv_data;
419 char ix_tag[] = "ix00";
422 av_assert0(pb->seekable);
424 if (avi->riff_id > AVI_MASTER_INDEX_SIZE) {
425 av_log(s, AV_LOG_ERROR, "Invalid riff index %d > %d\n",
426 avi->riff_id, AVI_MASTER_INDEX_SIZE);
427 return AVERROR(EINVAL);
430 for (i=0;i<s->nb_streams;i++) {
431 AVIStream *avist= s->streams[i]->priv_data;
434 avi_stream2fourcc(tag, i, s->streams[i]->codec->codec_type);
437 /* Writing AVI OpenDML leaf index chunk */
439 ffio_wfourcc(pb, ix_tag); /* ix?? */
440 avio_wl32(pb, avist->indexes.entry * 8 + 24);
442 avio_wl16(pb, 2); /* wLongsPerEntry */
443 avio_w8(pb, 0); /* bIndexSubType (0 == frame index) */
444 avio_w8(pb, 1); /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
445 avio_wl32(pb, avist->indexes.entry);
447 ffio_wfourcc(pb, tag); /* dwChunkId */
448 avio_wl64(pb, avi->movi_list);/* qwBaseOffset */
449 avio_wl32(pb, 0); /* dwReserved_3 (must be 0) */
451 for (j=0; j<avist->indexes.entry; j++) {
452 AVIIentry* ie = avi_get_ientry(&avist->indexes, j);
453 avio_wl32(pb, ie->pos + 8);
454 avio_wl32(pb, ((uint32_t)ie->len & ~0x80000000) |
455 (ie->flags & 0x10 ? 0 : 0x80000000));
460 /* Updating one entry in the AVI OpenDML master index */
461 avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
462 ffio_wfourcc(pb, "indx"); /* enabling this entry */
464 avio_wl32(pb, avi->riff_id); /* nEntriesInUse */
465 avio_skip(pb, 16*avi->riff_id);
466 avio_wl64(pb, ix); /* qwOffset */
467 avio_wl32(pb, pos - ix); /* dwSize */
468 avio_wl32(pb, avist->indexes.entry); /* dwDuration */
470 avio_seek(pb, pos, SEEK_SET);
475 static int avi_write_idx1(AVFormatContext *s)
477 AVIOContext *pb = s->pb;
478 AVIContext *avi = s->priv_data;
485 AVIIentry* ie = 0, *tie;
486 int empty, stream_id = -1;
488 idx_chunk = ff_start_tag(pb, "idx1");
489 for(i=0; i<s->nb_streams; i++){
490 avist= s->streams[i]->priv_data;
496 for (i=0; i<s->nb_streams; i++) {
497 avist= s->streams[i]->priv_data;
498 if (avist->indexes.entry <= avist->entry)
501 tie = avi_get_ientry(&avist->indexes, avist->entry);
502 if (empty || tie->pos < ie->pos) {
509 avist= s->streams[stream_id]->priv_data;
510 avi_stream2fourcc(tag, stream_id,
511 s->streams[stream_id]->codec->codec_type);
512 ffio_wfourcc(pb, tag);
513 avio_wl32(pb, ie->flags);
514 avio_wl32(pb, ie->pos);
515 avio_wl32(pb, ie->len);
519 ff_end_tag(pb, idx_chunk);
521 avi_write_counters(s, avi->riff_id);
526 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
528 AVIContext *avi = s->priv_data;
529 AVIOContext *pb = s->pb;
530 unsigned char tag[5];
531 unsigned int flags=0;
532 const int stream_index= pkt->stream_index;
533 AVIStream *avist= s->streams[stream_index]->priv_data;
534 AVCodecContext *enc= s->streams[stream_index]->codec;
537 av_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(pkt->dts), avist->packet_count, stream_index);
538 while(enc->block_align==0 && pkt->dts != AV_NOPTS_VALUE && pkt->dts > avist->packet_count && enc->codec_id != AV_CODEC_ID_XSUB && avist->packet_count){
539 AVPacket empty_packet;
541 if(pkt->dts - avist->packet_count > 60000){
542 av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", pkt->dts - avist->packet_count);
543 return AVERROR(EINVAL);
546 av_init_packet(&empty_packet);
547 empty_packet.size= 0;
548 empty_packet.data= NULL;
549 empty_packet.stream_index= stream_index;
550 avi_write_packet(s, &empty_packet);
551 av_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(pkt->dts), avist->packet_count);
553 avist->packet_count++;
555 // Make sure to put an OpenDML chunk when the file size exceeds the limits
557 (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
560 ff_end_tag(pb, avi->movi_list);
562 if (avi->riff_id == 1)
565 ff_end_tag(pb, avi->riff_start);
566 avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
569 avi_stream2fourcc(tag, stream_index, enc->codec_type);
570 if(pkt->flags&AV_PKT_FLAG_KEY)
572 if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
573 avist->audio_strm_length += size;
576 if (s->pb->seekable) {
577 AVIIndex* idx = &avist->indexes;
578 int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
579 int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
580 if (idx->ents_allocated <= idx->entry) {
581 idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
583 idx->ents_allocated = 0;
585 return AVERROR(ENOMEM);
587 idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
588 if (!idx->cluster[cl])
589 return AVERROR(ENOMEM);
590 idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
593 idx->cluster[cl][id].flags = flags;
594 idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
595 idx->cluster[cl][id].len = size;
599 avio_write(pb, tag, 4);
601 avio_write(pb, pkt->data, size);
608 static int avi_write_trailer(AVFormatContext *s)
610 AVIContext *avi = s->priv_data;
611 AVIOContext *pb = s->pb;
613 int i, j, n, nb_frames;
617 if (avi->riff_id == 1) {
618 ff_end_tag(pb, avi->movi_list);
619 res = avi_write_idx1(s);
620 ff_end_tag(pb, avi->riff_start);
623 ff_end_tag(pb, avi->movi_list);
624 ff_end_tag(pb, avi->riff_start);
626 file_size = avio_tell(pb);
627 avio_seek(pb, avi->odml_list - 8, SEEK_SET);
628 ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
631 for (n=nb_frames=0;n<s->nb_streams;n++) {
632 AVCodecContext *stream = s->streams[n]->codec;
633 AVIStream *avist= s->streams[n]->priv_data;
635 if (stream->codec_type == AVMEDIA_TYPE_VIDEO) {
636 if (nb_frames < avist->packet_count)
637 nb_frames = avist->packet_count;
639 if (stream->codec_id == AV_CODEC_ID_MP2 || stream->codec_id == AV_CODEC_ID_MP3) {
640 nb_frames += avist->packet_count;
644 avio_wl32(pb, nb_frames);
645 avio_seek(pb, file_size, SEEK_SET);
647 avi_write_counters(s, avi->riff_id);
651 for (i=0; i<s->nb_streams; i++) {
652 AVIStream *avist= s->streams[i]->priv_data;
653 for (j=0; j<avist->indexes.ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++)
654 av_freep(&avist->indexes.cluster[j]);
655 av_freep(&avist->indexes.cluster);
656 avist->indexes.ents_allocated = avist->indexes.entry = 0;
662 AVOutputFormat ff_avi_muxer = {
664 .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
665 .mime_type = "video/x-msvideo",
667 .priv_data_size = sizeof(AVIContext),
668 .audio_codec = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
669 .video_codec = AV_CODEC_ID_MPEG4,
670 .write_header = avi_write_header,
671 .write_packet = avi_write_packet,
672 .write_trailer = avi_write_trailer,
673 .codec_tag = (const AVCodecTag* const []){
674 ff_codec_bmp_tags, ff_codec_wav_tags, 0