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 && (st->codec->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;
97 av_dict_copy(&tmp, *options, 0);
99 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
102 #if FF_API_LAVF_BITEXACT
103 if (s->nb_streams && s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)
104 s->flags |= AVFMT_FLAG_BITEXACT;
107 // some sanity checks
108 if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
109 av_log(s, AV_LOG_ERROR, "no streams\n");
110 ret = AVERROR(EINVAL);
114 for (i = 0; i < s->nb_streams; i++) {
118 #if FF_API_LAVF_CODEC_TB
119 FF_DISABLE_DEPRECATION_WARNINGS
120 if (!st->time_base.num && codec->time_base.num) {
121 av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
122 "timebase hint to the muxer is deprecated. Set "
123 "AVStream.time_base instead.\n");
124 avpriv_set_pts_info(st, 64, codec->time_base.num, codec->time_base.den);
126 FF_ENABLE_DEPRECATION_WARNINGS
129 if (!st->time_base.num) {
130 /* fall back on the default timebase values */
131 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->sample_rate)
132 avpriv_set_pts_info(st, 64, 1, codec->sample_rate);
134 avpriv_set_pts_info(st, 33, 1, 90000);
137 switch (codec->codec_type) {
138 case AVMEDIA_TYPE_AUDIO:
139 if (codec->sample_rate <= 0) {
140 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
141 ret = AVERROR(EINVAL);
144 if (!codec->block_align)
145 codec->block_align = codec->channels *
146 av_get_bits_per_sample(codec->codec_id) >> 3;
148 case AVMEDIA_TYPE_VIDEO:
149 if ((codec->width <= 0 || codec->height <= 0) &&
150 !(of->flags & AVFMT_NODIMENSIONS)) {
151 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
152 ret = AVERROR(EINVAL);
156 if (av_cmp_q(st->sample_aspect_ratio,
157 codec->sample_aspect_ratio)) {
158 if (st->sample_aspect_ratio.num != 0 &&
159 st->sample_aspect_ratio.den != 0 &&
160 codec->sample_aspect_ratio.den != 0 &&
161 codec->sample_aspect_ratio.den != 0) {
162 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
163 "(%d/%d) and encoder layer (%d/%d)\n",
164 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
165 codec->sample_aspect_ratio.num,
166 codec->sample_aspect_ratio.den);
167 ret = AVERROR(EINVAL);
175 if (codec->codec_tag &&
176 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
177 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
178 !validate_codec_tag(s, st)) {
179 // the current rawvideo encoding system ends up setting
180 // the wrong codec_tag for avi, we override it here
181 codec->codec_tag = 0;
183 if (codec->codec_tag) {
184 if (!validate_codec_tag(s, st)) {
186 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
187 av_log(s, AV_LOG_ERROR,
188 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
189 tagbuf, codec->codec_tag, codec->codec_id);
190 ret = AVERROR_INVALIDDATA;
194 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
197 if (of->flags & AVFMT_GLOBALHEADER &&
198 !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
199 av_log(s, AV_LOG_WARNING,
200 "Codec for stream %d does not use global headers "
201 "but container format requires global headers\n", i);
203 if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
204 s->internal->nb_interleaved_streams++;
207 if (!s->priv_data && of->priv_data_size > 0) {
208 s->priv_data = av_mallocz(of->priv_data_size);
210 ret = AVERROR(ENOMEM);
213 if (of->priv_class) {
214 *(const AVClass **)s->priv_data = of->priv_class;
215 av_opt_set_defaults(s->priv_data);
216 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
221 /* set muxer identification string */
222 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
223 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
227 av_dict_free(options);
238 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
242 if (ret = init_muxer(s, options))
245 if (s->oformat->write_header) {
246 ret = s->oformat->write_header(s);
254 //FIXME merge with compute_pkt_fields
255 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
257 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
260 av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
261 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
263 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
264 * return AVERROR(EINVAL);*/
267 if (pkt->duration == 0) {
268 ff_compute_frame_duration(&num, &den, st, NULL, pkt);
270 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
274 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
277 //calculate dts from pts
278 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
279 st->pts_buffer[0] = pkt->pts;
280 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
281 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
282 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
283 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
285 pkt->dts = st->pts_buffer[0];
288 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
289 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
290 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
291 av_log(s, AV_LOG_ERROR,
292 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
293 st->index, st->cur_dts, pkt->dts);
294 return AVERROR(EINVAL);
296 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
297 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
298 return AVERROR(EINVAL);
301 av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
303 st->cur_dts = pkt->dts;
309 * FIXME: this function should NEVER get undefined pts/dts beside when the
310 * AVFMT_NOTIMESTAMPS is set.
311 * Those additional safety checks should be dropped once the correct checks
312 * are set in the callers.
315 static int write_packet(AVFormatContext *s, AVPacket *pkt)
318 if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
319 AVRational time_base = s->streams[pkt->stream_index]->time_base;
322 if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
323 s->offset = -pkt->dts;
324 s->offset_timebase = time_base;
327 offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
329 if (pkt->dts != AV_NOPTS_VALUE)
331 if (pkt->pts != AV_NOPTS_VALUE)
334 ret = s->oformat->write_packet(s, pkt);
336 if (s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
342 static int check_packet(AVFormatContext *s, AVPacket *pkt)
347 if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
348 av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
350 return AVERROR(EINVAL);
353 if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
354 av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
355 return AVERROR(EINVAL);
361 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
365 ret = check_packet(s, pkt);
370 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
371 return s->oformat->write_packet(s, pkt);
375 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
377 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
380 ret = write_packet(s, pkt);
383 s->streams[pkt->stream_index]->nb_frames++;
387 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
388 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
391 AVPacketList **next_point, *this_pktl;
393 this_pktl = av_mallocz(sizeof(AVPacketList));
395 return AVERROR(ENOMEM);
396 this_pktl->pkt = *pkt;
397 #if FF_API_DESTRUCT_PACKET
398 FF_DISABLE_DEPRECATION_WARNINGS
399 pkt->destruct = NULL; // do not free original but only the copy
400 FF_ENABLE_DEPRECATION_WARNINGS
403 // Duplicate the packet if it uses non-allocated memory
404 if ((ret = av_dup_packet(&this_pktl->pkt)) < 0) {
409 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
410 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
412 next_point = &s->packet_buffer;
415 if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
416 while (!compare(s, &(*next_point)->pkt, pkt))
417 next_point = &(*next_point)->next;
420 next_point = &(s->packet_buffer_end->next);
423 assert(!*next_point);
425 s->packet_buffer_end = this_pktl;
428 this_pktl->next = *next_point;
430 s->streams[pkt->stream_index]->last_in_packet_buffer =
431 *next_point = this_pktl;
436 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
439 AVStream *st = s->streams[pkt->stream_index];
440 AVStream *st2 = s->streams[next->stream_index];
441 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
445 return pkt->stream_index < next->stream_index;
449 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
450 AVPacket *pkt, int flush)
453 int stream_count = 0;
457 if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
461 if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
462 AVPacket *top_pkt = &s->packet_buffer->pkt;
463 int64_t delta_dts = INT64_MIN;
464 int64_t top_dts = av_rescale_q(top_pkt->dts,
465 s->streams[top_pkt->stream_index]->time_base,
468 for (i = 0; i < s->nb_streams; i++) {
470 const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
475 last_dts = av_rescale_q(last->pkt.dts,
476 s->streams[i]->time_base,
478 delta_dts = FFMAX(delta_dts, last_dts - top_dts);
482 if (delta_dts > s->max_interleave_delta) {
483 av_log(s, AV_LOG_DEBUG,
484 "Delay between the first packet and last packet in the "
485 "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
486 delta_dts, s->max_interleave_delta);
490 for (i = 0; i < s->nb_streams; i++)
491 stream_count += !!s->streams[i]->last_in_packet_buffer;
495 if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
496 pktl = s->packet_buffer;
499 s->packet_buffer = pktl->next;
500 if (!s->packet_buffer)
501 s->packet_buffer_end = NULL;
503 if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
504 s->streams[out->stream_index]->last_in_packet_buffer = NULL;
514 * Interleave an AVPacket correctly so it can be muxed.
515 * @param out the interleaved packet will be output here
516 * @param in the input packet
517 * @param flush 1 if no further packets are available as input and all
518 * remaining packets should be output
519 * @return 1 if a packet was output, 0 if no packet could be output,
520 * < 0 if an error occurred
522 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
524 if (s->oformat->interleave_packet) {
525 int ret = s->oformat->interleave_packet(s, out, in, flush);
530 return ff_interleave_packet_per_dts(s, out, in, flush);
533 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
537 ret = check_packet(s, pkt);
542 AVStream *st = s->streams[pkt->stream_index];
544 av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
545 pkt->size, pkt->dts, pkt->pts);
546 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
549 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
550 ret = AVERROR(EINVAL);
554 av_dlog(s, "av_interleaved_write_frame FLUSH\n");
560 int ret = interleave_packet(s, &opkt, pkt, flush);
562 memset(pkt, 0, sizeof(*pkt));
566 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
569 ret = write_packet(s, &opkt);
571 s->streams[opkt.stream_index]->nb_frames++;
573 av_free_packet(&opkt);
579 av_packet_unref(pkt);
583 int av_write_trailer(AVFormatContext *s)
589 ret = interleave_packet(s, &pkt, NULL, 1);
590 if (ret < 0) //FIXME cleanup needed for ret<0 ?
595 ret = write_packet(s, &pkt);
597 s->streams[pkt.stream_index]->nb_frames++;
599 av_free_packet(&pkt);
605 if (s->oformat->write_trailer)
606 ret = s->oformat->write_trailer(s);
608 if (!(s->oformat->flags & AVFMT_NOFILE))
612 for (i = 0; i < s->nb_streams; i++) {
613 av_freep(&s->streams[i]->priv_data);
614 av_freep(&s->streams[i]->index_entries);
616 if (s->oformat->priv_class)
617 av_opt_free(s->priv_data);
618 av_freep(&s->priv_data);
622 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
623 AVFormatContext *src)
628 local_pkt.stream_index = dst_stream;
629 if (pkt->pts != AV_NOPTS_VALUE)
630 local_pkt.pts = av_rescale_q(pkt->pts,
631 src->streams[pkt->stream_index]->time_base,
632 dst->streams[dst_stream]->time_base);
633 if (pkt->dts != AV_NOPTS_VALUE)
634 local_pkt.dts = av_rescale_q(pkt->dts,
635 src->streams[pkt->stream_index]->time_base,
636 dst->streams[dst_stream]->time_base);
637 return av_write_frame(dst, &local_pkt);