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/avassert.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/internal.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/time.h"
39 #include "audiointerleave.h"
51 * muxing functions for use within Libav
54 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
56 const AVCodecTag *avctag;
58 enum AVCodecID id = AV_CODEC_ID_NONE;
62 * Check that tag + id is in the table
63 * If neither is in the table -> OK
64 * If tag is in the table with another id -> FAIL
65 * If id is in the table with another tag -> FAIL unless strict < normal
67 for (n = 0; s->oformat->codec_tag[n]; n++) {
68 avctag = s->oformat->codec_tag[n];
69 while (avctag->id != AV_CODEC_ID_NONE) {
70 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
72 if (id == st->codec->codec_id)
75 if (avctag->id == st->codec->codec_id)
80 if (id != AV_CODEC_ID_NONE)
82 if (tag && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
88 static int init_muxer(AVFormatContext *s, AVDictionary **options)
92 AVDictionary *tmp = NULL;
93 AVCodecContext *codec = NULL;
94 AVOutputFormat *of = s->oformat;
95 const AVCodecDescriptor *desc;
98 av_dict_copy(&tmp, *options, 0);
100 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
103 #if FF_API_LAVF_BITEXACT
104 if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT)
105 s->flags |= AVFMT_FLAG_BITEXACT;
108 // some sanity checks
109 if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
110 av_log(s, AV_LOG_ERROR, "no streams\n");
111 ret = AVERROR(EINVAL);
115 for (i = 0; i < s->nb_streams; i++) {
119 #if FF_API_LAVF_CODEC_TB
120 FF_DISABLE_DEPRECATION_WARNINGS
121 if (!st->time_base.num && codec->time_base.num) {
122 av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
123 "timebase hint to the muxer is deprecated. Set "
124 "AVStream.time_base instead.\n");
125 avpriv_set_pts_info(st, 64, codec->time_base.num, codec->time_base.den);
127 FF_ENABLE_DEPRECATION_WARNINGS
130 if (!st->time_base.num) {
131 /* fall back on the default timebase values */
132 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->sample_rate)
133 avpriv_set_pts_info(st, 64, 1, codec->sample_rate);
135 avpriv_set_pts_info(st, 33, 1, 90000);
138 switch (codec->codec_type) {
139 case AVMEDIA_TYPE_AUDIO:
140 if (codec->sample_rate <= 0) {
141 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
142 ret = AVERROR(EINVAL);
145 if (!codec->block_align)
146 codec->block_align = codec->channels *
147 av_get_bits_per_sample(codec->codec_id) >> 3;
149 case AVMEDIA_TYPE_VIDEO:
150 if ((codec->width <= 0 || codec->height <= 0) &&
151 !(of->flags & AVFMT_NODIMENSIONS)) {
152 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
153 ret = AVERROR(EINVAL);
157 if (av_cmp_q(st->sample_aspect_ratio,
158 codec->sample_aspect_ratio)) {
159 if (st->sample_aspect_ratio.num != 0 &&
160 st->sample_aspect_ratio.den != 0 &&
161 codec->sample_aspect_ratio.den != 0 &&
162 codec->sample_aspect_ratio.den != 0) {
163 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
164 "(%d/%d) and encoder layer (%d/%d)\n",
165 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
166 codec->sample_aspect_ratio.num,
167 codec->sample_aspect_ratio.den);
168 ret = AVERROR(EINVAL);
175 desc = avcodec_descriptor_get(codec->codec_id);
176 if (desc && desc->props & AV_CODEC_PROP_REORDER)
177 st->internal->reorder = 1;
180 if (codec->codec_tag &&
181 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
182 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
183 !validate_codec_tag(s, st)) {
184 // the current rawvideo encoding system ends up setting
185 // the wrong codec_tag for avi, we override it here
186 codec->codec_tag = 0;
188 if (codec->codec_tag) {
189 if (!validate_codec_tag(s, st)) {
191 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
192 av_log(s, AV_LOG_ERROR,
193 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
194 tagbuf, codec->codec_tag, codec->codec_id);
195 ret = AVERROR_INVALIDDATA;
199 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
202 if (of->flags & AVFMT_GLOBALHEADER &&
203 !(codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
204 av_log(s, AV_LOG_WARNING,
205 "Codec for stream %d does not use global headers "
206 "but container format requires global headers\n", i);
208 if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
209 s->internal->nb_interleaved_streams++;
212 if (!s->priv_data && of->priv_data_size > 0) {
213 s->priv_data = av_mallocz(of->priv_data_size);
215 ret = AVERROR(ENOMEM);
218 if (of->priv_class) {
219 *(const AVClass **)s->priv_data = of->priv_class;
220 av_opt_set_defaults(s->priv_data);
221 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
226 /* set muxer identification string */
227 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
228 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
232 av_dict_free(options);
243 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
247 if (ret = init_muxer(s, options))
250 if (s->oformat->write_header) {
251 ret = s->oformat->write_header(s);
256 if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) {
257 if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
258 s->avoid_negative_ts = 0;
260 s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
266 #if FF_API_COMPUTE_PKT_FIELDS2
267 //FIXME merge with compute_pkt_fields
268 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
270 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
273 if (!s->internal->missing_ts_warning &&
274 !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
275 (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
276 av_log(s, AV_LOG_WARNING,
277 "Timestamps are unset in a packet for stream %d. "
278 "This is deprecated and will stop working in the future. "
279 "Fix your code to set the timestamps properly\n", st->index);
280 s->internal->missing_ts_warning = 1;
283 av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
284 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
286 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
287 * return AVERROR(EINVAL);*/
290 if (pkt->duration == 0) {
291 ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
293 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
297 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
300 //calculate dts from pts
301 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
302 st->pts_buffer[0] = pkt->pts;
303 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
304 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
305 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
306 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
308 pkt->dts = st->pts_buffer[0];
311 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
312 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
313 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
314 av_log(s, AV_LOG_ERROR,
315 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
316 st->index, st->cur_dts, pkt->dts);
317 return AVERROR(EINVAL);
319 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
320 av_log(s, AV_LOG_ERROR,
321 "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
324 return AVERROR(EINVAL);
327 av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
329 st->cur_dts = pkt->dts;
336 * FIXME: this function should NEVER get undefined pts/dts beside when the
337 * AVFMT_NOTIMESTAMPS is set.
338 * Those additional safety checks should be dropped once the correct checks
339 * are set in the callers.
342 static int write_packet(AVFormatContext *s, AVPacket *pkt)
345 if (s->avoid_negative_ts > 0) {
346 AVRational time_base = s->streams[pkt->stream_index]->time_base;
349 if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
350 (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
351 s->internal->offset = -pkt->dts;
352 s->internal->offset_timebase = time_base;
354 if (s->internal->offset != AV_NOPTS_VALUE)
355 offset = av_rescale_q(s->internal->offset, s->internal->offset_timebase, time_base);
357 if (pkt->dts != AV_NOPTS_VALUE)
359 if (pkt->pts != AV_NOPTS_VALUE)
362 if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
363 av_log(s, AV_LOG_WARNING,
364 "Packets poorly interleaved, failed to avoid negative "
365 "timestamp %"PRId64" in stream %d.\n"
366 "Try -max_interleave_delta 0 as a possible workaround.\n",
367 pkt->dts, pkt->stream_index);
370 ret = s->oformat->write_packet(s, pkt);
372 if (s->pb && ret >= 0) {
373 if (s->flags & AVFMT_FLAG_FLUSH_PACKETS)
375 if (s->pb->error < 0)
382 static int check_packet(AVFormatContext *s, AVPacket *pkt)
387 if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
388 av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
390 return AVERROR(EINVAL);
393 if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
394 av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
395 return AVERROR(EINVAL);
401 static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
405 ret = check_packet(s, pkt);
409 #if !FF_API_COMPUTE_PKT_FIELDS2
410 /* sanitize the timestamps */
411 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
412 AVStream *st = s->streams[pkt->stream_index];
414 /* when there is no reordering (so dts is equal to pts), but
415 * only one of them is set, set the other as well */
416 if (!st->internal->reorder) {
417 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
419 if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
423 /* check that the timestamps are set */
424 if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
425 av_log(s, AV_LOG_ERROR,
426 "Timestamps are unset in a packet for stream %d\n", st->index);
427 return AVERROR(EINVAL);
430 /* check that the dts are increasing (or at least non-decreasing,
431 * if the format allows it */
432 if (st->cur_dts != AV_NOPTS_VALUE &&
433 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
434 st->cur_dts > pkt->dts)) {
435 av_log(s, AV_LOG_ERROR,
436 "Application provided invalid, non monotonically increasing "
437 "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
438 st->index, st->cur_dts, pkt->dts);
439 return AVERROR(EINVAL);
442 if (pkt->pts < pkt->dts) {
443 av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
444 pkt->pts, pkt->dts, st->index);
445 return AVERROR(EINVAL);
453 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
457 ret = prepare_input_packet(s, pkt);
462 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
463 return s->oformat->write_packet(s, pkt);
467 #if FF_API_COMPUTE_PKT_FIELDS2
468 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
470 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
474 ret = write_packet(s, pkt);
477 s->streams[pkt->stream_index]->nb_frames++;
481 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
482 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
485 AVPacketList **next_point, *this_pktl;
487 this_pktl = av_mallocz(sizeof(AVPacketList));
489 return AVERROR(ENOMEM);
491 if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
496 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
497 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
499 next_point = &s->internal->packet_buffer;
502 if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
503 while (!compare(s, &(*next_point)->pkt, pkt))
504 next_point = &(*next_point)->next;
507 next_point = &(s->internal->packet_buffer_end->next);
510 assert(!*next_point);
512 s->internal->packet_buffer_end = this_pktl;
515 this_pktl->next = *next_point;
517 s->streams[pkt->stream_index]->last_in_packet_buffer =
518 *next_point = this_pktl;
520 av_packet_unref(pkt);
525 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
528 AVStream *st = s->streams[pkt->stream_index];
529 AVStream *st2 = s->streams[next->stream_index];
530 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
534 return pkt->stream_index < next->stream_index;
538 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
539 AVPacket *pkt, int flush)
542 int stream_count = 0;
546 if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
550 if (s->max_interleave_delta > 0 && s->internal->packet_buffer && !flush) {
551 AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
552 int64_t delta_dts = INT64_MIN;
553 int64_t top_dts = av_rescale_q(top_pkt->dts,
554 s->streams[top_pkt->stream_index]->time_base,
557 for (i = 0; i < s->nb_streams; i++) {
559 const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
564 last_dts = av_rescale_q(last->pkt.dts,
565 s->streams[i]->time_base,
567 delta_dts = FFMAX(delta_dts, last_dts - top_dts);
571 if (delta_dts > s->max_interleave_delta) {
572 av_log(s, AV_LOG_DEBUG,
573 "Delay between the first packet and last packet in the "
574 "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
575 delta_dts, s->max_interleave_delta);
579 for (i = 0; i < s->nb_streams; i++)
580 stream_count += !!s->streams[i]->last_in_packet_buffer;
584 if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
585 pktl = s->internal->packet_buffer;
588 s->internal->packet_buffer = pktl->next;
589 if (!s->internal->packet_buffer)
590 s->internal->packet_buffer_end = NULL;
592 if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
593 s->streams[out->stream_index]->last_in_packet_buffer = NULL;
603 * Interleave an AVPacket correctly so it can be muxed.
604 * @param out the interleaved packet will be output here
605 * @param in the input packet
606 * @param flush 1 if no further packets are available as input and all
607 * remaining packets should be output
608 * @return 1 if a packet was output, 0 if no packet could be output,
609 * < 0 if an error occurred
611 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
613 if (s->oformat->interleave_packet) {
614 int ret = s->oformat->interleave_packet(s, out, in, flush);
619 return ff_interleave_packet_per_dts(s, out, in, flush);
622 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
626 ret = prepare_input_packet(s, pkt);
631 AVStream *st = s->streams[pkt->stream_index];
633 av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
634 pkt->size, pkt->dts, pkt->pts);
635 #if FF_API_COMPUTE_PKT_FIELDS2
636 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
640 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
641 ret = AVERROR(EINVAL);
645 av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
651 int ret = interleave_packet(s, &opkt, pkt, flush);
653 memset(pkt, 0, sizeof(*pkt));
657 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
660 ret = write_packet(s, &opkt);
662 s->streams[opkt.stream_index]->nb_frames++;
664 av_packet_unref(&opkt);
670 av_packet_unref(pkt);
674 int av_write_trailer(AVFormatContext *s)
680 ret = interleave_packet(s, &pkt, NULL, 1);
681 if (ret < 0) //FIXME cleanup needed for ret<0 ?
686 ret = write_packet(s, &pkt);
688 s->streams[pkt.stream_index]->nb_frames++;
690 av_packet_unref(&pkt);
696 if (s->oformat->write_trailer)
697 ret = s->oformat->write_trailer(s);
699 if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
703 for (i = 0; i < s->nb_streams; i++) {
704 av_freep(&s->streams[i]->priv_data);
705 av_freep(&s->streams[i]->index_entries);
707 if (s->oformat->priv_class)
708 av_opt_free(s->priv_data);
709 av_freep(&s->priv_data);
713 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
714 AVFormatContext *src)
719 local_pkt.stream_index = dst_stream;
720 if (pkt->pts != AV_NOPTS_VALUE)
721 local_pkt.pts = av_rescale_q(pkt->pts,
722 src->streams[pkt->stream_index]->time_base,
723 dst->streams[dst_stream]->time_base);
724 if (pkt->dts != AV_NOPTS_VALUE)
725 local_pkt.dts = av_rescale_q(pkt->dts,
726 src->streams[pkt->stream_index]->time_base,
727 dst->streams[dst_stream]->time_base);
728 return av_write_frame(dst, &local_pkt);