2 * muxing functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include "avio_internal.h"
25 #include "libavcodec/internal.h"
26 #include "libavcodec/bytestream.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/pixdesc.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/time.h"
38 #include "audiointerleave.h"
50 * muxing functions for use within Libav
53 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
55 const AVCodecTag *avctag;
57 enum AVCodecID id = AV_CODEC_ID_NONE;
61 * Check that tag + id is in the table
62 * If neither is in the table -> OK
63 * If tag is in the table with another id -> FAIL
64 * If id is in the table with another tag -> FAIL unless strict < normal
66 for (n = 0; s->oformat->codec_tag[n]; n++) {
67 avctag = s->oformat->codec_tag[n];
68 while (avctag->id != AV_CODEC_ID_NONE) {
69 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codecpar->codec_tag)) {
71 if (id == st->codecpar->codec_id)
74 if (avctag->id == st->codecpar->codec_id)
79 if (id != AV_CODEC_ID_NONE)
81 if (tag && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
87 static int init_muxer(AVFormatContext *s, AVDictionary **options)
91 AVDictionary *tmp = NULL;
92 AVCodecParameters *par = NULL;
93 AVOutputFormat *of = s->oformat;
94 const AVCodecDescriptor *desc;
97 av_dict_copy(&tmp, *options, 0);
99 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
102 // some sanity checks
103 if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
104 av_log(s, AV_LOG_ERROR, "no streams\n");
105 ret = AVERROR(EINVAL);
109 for (i = 0; i < s->nb_streams; i++) {
113 #if FF_API_LAVF_AVCTX
114 FF_DISABLE_DEPRECATION_WARNINGS
115 if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
116 st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN) {
117 av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "
118 "parameters to muxers is deprecated, use AVStream.codecpar "
120 ret = avcodec_parameters_from_context(st->codecpar, st->codec);
124 FF_ENABLE_DEPRECATION_WARNINGS
127 if (!st->time_base.num) {
128 /* fall back on the default timebase values */
129 if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
130 avpriv_set_pts_info(st, 64, 1, par->sample_rate);
132 avpriv_set_pts_info(st, 33, 1, 90000);
135 switch (par->codec_type) {
136 case AVMEDIA_TYPE_AUDIO:
137 if (par->sample_rate <= 0) {
138 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
139 ret = AVERROR(EINVAL);
142 if (!par->block_align)
143 par->block_align = par->channels *
144 av_get_bits_per_sample(par->codec_id) >> 3;
146 case AVMEDIA_TYPE_VIDEO:
147 if ((par->width <= 0 || par->height <= 0) &&
148 !(of->flags & AVFMT_NODIMENSIONS)) {
149 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
150 ret = AVERROR(EINVAL);
154 if (av_cmp_q(st->sample_aspect_ratio,
155 par->sample_aspect_ratio)) {
156 if (st->sample_aspect_ratio.num != 0 &&
157 st->sample_aspect_ratio.den != 0 &&
158 par->sample_aspect_ratio.den != 0 &&
159 par->sample_aspect_ratio.den != 0) {
160 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
161 "(%d/%d) and encoder layer (%d/%d)\n",
162 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
163 par->sample_aspect_ratio.num,
164 par->sample_aspect_ratio.den);
165 ret = AVERROR(EINVAL);
172 desc = avcodec_descriptor_get(par->codec_id);
173 if (desc && desc->props & AV_CODEC_PROP_REORDER)
174 st->internal->reorder = 1;
177 if (par->codec_tag &&
178 par->codec_id == AV_CODEC_ID_RAWVIDEO &&
179 !av_codec_get_tag(of->codec_tag, par->codec_id) &&
180 !validate_codec_tag(s, st)) {
181 // the current rawvideo encoding system ends up setting
182 // the wrong codec_tag for avi, we override it here
185 if (par->codec_tag) {
186 if (!validate_codec_tag(s, st)) {
188 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), par->codec_tag);
189 av_log(s, AV_LOG_ERROR,
190 "Tag %s/0x%08"PRIx32" incompatible with output codec id '%d'\n",
191 tagbuf, par->codec_tag, par->codec_id);
192 ret = AVERROR_INVALIDDATA;
196 par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
199 if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
200 s->internal->nb_interleaved_streams++;
203 if (!s->priv_data && of->priv_data_size > 0) {
204 s->priv_data = av_mallocz(of->priv_data_size);
206 ret = AVERROR(ENOMEM);
209 if (of->priv_class) {
210 *(const AVClass **)s->priv_data = of->priv_class;
211 av_opt_set_defaults(s->priv_data);
212 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
217 /* set muxer identification string */
218 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
219 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
223 av_dict_free(options);
234 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
238 if (ret = init_muxer(s, options))
241 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
242 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
243 if (s->oformat->write_header) {
244 ret = s->oformat->write_header(s);
248 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
249 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
251 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) {
252 if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
253 s->avoid_negative_ts = 0;
255 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
261 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
262 FF_DISABLE_DEPRECATION_WARNINGS
263 //FIXME merge with compute_pkt_fields
264 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
266 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
269 if (!s->internal->missing_ts_warning &&
270 !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
271 (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
272 av_log(s, AV_LOG_WARNING,
273 "Timestamps are unset in a packet for stream %d. "
274 "This is deprecated and will stop working in the future. "
275 "Fix your code to set the timestamps properly\n", st->index);
276 s->internal->missing_ts_warning = 1;
279 av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
280 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
282 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
283 * return AVERROR(EINVAL);*/
286 if (pkt->duration == 0) {
287 ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
289 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
293 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
296 //calculate dts from pts
297 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
298 st->pts_buffer[0] = pkt->pts;
299 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
300 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
301 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
302 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
304 pkt->dts = st->pts_buffer[0];
307 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
308 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
309 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
310 av_log(s, AV_LOG_ERROR,
311 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
312 st->index, st->cur_dts, pkt->dts);
313 return AVERROR(EINVAL);
315 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
316 av_log(s, AV_LOG_ERROR,
317 "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
320 return AVERROR(EINVAL);
323 av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
325 st->cur_dts = pkt->dts;
329 FF_ENABLE_DEPRECATION_WARNINGS
333 * FIXME: this function should NEVER get undefined pts/dts beside when the
334 * AVFMT_NOTIMESTAMPS is set.
335 * Those additional safety checks should be dropped once the correct checks
336 * are set in the callers.
339 static int write_packet(AVFormatContext *s, AVPacket *pkt)
342 // If the timestamp offsetting below is adjusted, adjust
343 // ff_interleaved_peek similarly.
344 if (s->avoid_negative_ts > 0) {
345 AVRational time_base = s->streams[pkt->stream_index]->time_base;
348 if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
349 (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
350 s->internal->offset = -pkt->dts;
351 s->internal->offset_timebase = time_base;
353 if (s->internal->offset != AV_NOPTS_VALUE)
354 offset = av_rescale_q(s->internal->offset, s->internal->offset_timebase, time_base);
356 if (pkt->dts != AV_NOPTS_VALUE)
358 if (pkt->pts != AV_NOPTS_VALUE)
361 if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
362 av_log(s, AV_LOG_WARNING,
363 "Packets poorly interleaved, failed to avoid negative "
364 "timestamp %"PRId64" in stream %d.\n"
365 "Try -max_interleave_delta 0 as a possible workaround.\n",
366 pkt->dts, pkt->stream_index);
369 ret = s->oformat->write_packet(s, pkt);
371 if (s->pb && ret >= 0) {
372 if (s->flags & AVFMT_FLAG_FLUSH_PACKETS)
374 if (s->pb->error < 0)
381 static int check_packet(AVFormatContext *s, AVPacket *pkt)
386 if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
387 av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
389 return AVERROR(EINVAL);
392 if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
393 av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
394 return AVERROR(EINVAL);
400 static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
404 ret = check_packet(s, pkt);
408 #if !FF_API_COMPUTE_PKT_FIELDS2 || !FF_API_LAVF_AVCTX
409 /* sanitize the timestamps */
410 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
411 AVStream *st = s->streams[pkt->stream_index];
413 /* when there is no reordering (so dts is equal to pts), but
414 * only one of them is set, set the other as well */
415 if (!st->internal->reorder) {
416 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
418 if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
422 /* check that the timestamps are set */
423 if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
424 av_log(s, AV_LOG_ERROR,
425 "Timestamps are unset in a packet for stream %d\n", st->index);
426 return AVERROR(EINVAL);
429 /* check that the dts are increasing (or at least non-decreasing,
430 * if the format allows it */
431 if (st->cur_dts != AV_NOPTS_VALUE &&
432 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
433 st->cur_dts > pkt->dts)) {
434 av_log(s, AV_LOG_ERROR,
435 "Application provided invalid, non monotonically increasing "
436 "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
437 st->index, st->cur_dts, pkt->dts);
438 return AVERROR(EINVAL);
441 if (pkt->pts < pkt->dts) {
442 av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
443 pkt->pts, pkt->dts, st->index);
444 return AVERROR(EINVAL);
452 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
456 ret = prepare_input_packet(s, pkt);
461 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
462 return s->oformat->write_packet(s, pkt);
466 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
467 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
469 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
473 ret = write_packet(s, pkt);
476 s->streams[pkt->stream_index]->nb_frames++;
480 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
481 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
484 AVPacketList **next_point, *this_pktl;
486 this_pktl = av_mallocz(sizeof(AVPacketList));
488 return AVERROR(ENOMEM);
490 if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
495 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
496 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
498 next_point = &s->internal->packet_buffer;
501 if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
502 while (!compare(s, &(*next_point)->pkt, pkt))
503 next_point = &(*next_point)->next;
506 next_point = &(s->internal->packet_buffer_end->next);
509 assert(!*next_point);
511 s->internal->packet_buffer_end = this_pktl;
514 this_pktl->next = *next_point;
516 s->streams[pkt->stream_index]->last_in_packet_buffer =
517 *next_point = this_pktl;
519 av_packet_unref(pkt);
524 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
527 AVStream *st = s->streams[pkt->stream_index];
528 AVStream *st2 = s->streams[next->stream_index];
529 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
533 return pkt->stream_index < next->stream_index;
537 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
538 AVPacket *pkt, int flush)
541 int stream_count = 0;
545 if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
549 if (s->max_interleave_delta > 0 && s->internal->packet_buffer && !flush) {
550 AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
551 int64_t delta_dts = INT64_MIN;
552 int64_t top_dts = av_rescale_q(top_pkt->dts,
553 s->streams[top_pkt->stream_index]->time_base,
556 for (i = 0; i < s->nb_streams; i++) {
558 const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
563 last_dts = av_rescale_q(last->pkt.dts,
564 s->streams[i]->time_base,
566 delta_dts = FFMAX(delta_dts, last_dts - top_dts);
570 if (delta_dts > s->max_interleave_delta) {
571 av_log(s, AV_LOG_DEBUG,
572 "Delay between the first packet and last packet in the "
573 "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
574 delta_dts, s->max_interleave_delta);
578 for (i = 0; i < s->nb_streams; i++)
579 stream_count += !!s->streams[i]->last_in_packet_buffer;
583 if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
584 pktl = s->internal->packet_buffer;
587 s->internal->packet_buffer = pktl->next;
588 if (!s->internal->packet_buffer)
589 s->internal->packet_buffer_end = NULL;
591 if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
592 s->streams[out->stream_index]->last_in_packet_buffer = NULL;
601 int ff_interleaved_peek(AVFormatContext *s, int stream,
602 AVPacket *pkt, int add_offset)
604 AVPacketList *pktl = s->internal->packet_buffer;
606 if (pktl->pkt.stream_index == stream) {
608 if (add_offset && s->internal->offset != AV_NOPTS_VALUE) {
609 int64_t offset = av_rescale_q(s->internal->offset,
610 s->internal->offset_timebase,
611 s->streams[stream]->time_base);
612 if (pkt->dts != AV_NOPTS_VALUE)
614 if (pkt->pts != AV_NOPTS_VALUE)
621 return AVERROR(ENOENT);
625 * Interleave an AVPacket correctly so it can be muxed.
626 * @param out the interleaved packet will be output here
627 * @param in the input packet
628 * @param flush 1 if no further packets are available as input and all
629 * remaining packets should be output
630 * @return 1 if a packet was output, 0 if no packet could be output,
631 * < 0 if an error occurred
633 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
635 if (s->oformat->interleave_packet) {
636 int ret = s->oformat->interleave_packet(s, out, in, flush);
641 return ff_interleave_packet_per_dts(s, out, in, flush);
644 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
648 ret = prepare_input_packet(s, pkt);
653 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
654 AVStream *st = s->streams[pkt->stream_index];
656 av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
657 pkt->size, pkt->dts, pkt->pts);
658 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
662 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
663 ret = AVERROR(EINVAL);
667 av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
673 int ret = interleave_packet(s, &opkt, pkt, flush);
675 memset(pkt, 0, sizeof(*pkt));
679 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
682 ret = write_packet(s, &opkt);
684 s->streams[opkt.stream_index]->nb_frames++;
686 av_packet_unref(&opkt);
692 av_packet_unref(pkt);
696 int av_write_trailer(AVFormatContext *s)
702 ret = interleave_packet(s, &pkt, NULL, 1);
703 if (ret < 0) //FIXME cleanup needed for ret<0 ?
708 ret = write_packet(s, &pkt);
710 s->streams[pkt.stream_index]->nb_frames++;
712 av_packet_unref(&pkt);
718 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
719 avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
720 if (s->oformat->write_trailer)
721 ret = s->oformat->write_trailer(s);
723 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
727 for (i = 0; i < s->nb_streams; i++) {
728 av_freep(&s->streams[i]->priv_data);
729 av_freep(&s->streams[i]->index_entries);
731 if (s->oformat->priv_class)
732 av_opt_free(s->priv_data);
733 av_freep(&s->priv_data);
737 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
738 AVFormatContext *src)
743 local_pkt.stream_index = dst_stream;
744 if (pkt->pts != AV_NOPTS_VALUE)
745 local_pkt.pts = av_rescale_q(pkt->pts,
746 src->streams[pkt->stream_index]->time_base,
747 dst->streams[dst_stream]->time_base);
748 if (pkt->dts != AV_NOPTS_VALUE)
749 local_pkt.dts = av_rescale_q(pkt->dts,
750 src->streams[pkt->stream_index]->time_base,
751 dst->streams[dst_stream]->time_base);
752 return av_write_frame(dst, &local_pkt);