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 switch (codec->codec_type) {
119 case AVMEDIA_TYPE_AUDIO:
120 if (codec->sample_rate <= 0) {
121 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
122 ret = AVERROR(EINVAL);
125 if (!codec->block_align)
126 codec->block_align = codec->channels *
127 av_get_bits_per_sample(codec->codec_id) >> 3;
129 case AVMEDIA_TYPE_VIDEO:
130 if (codec->time_base.num <= 0 ||
131 codec->time_base.den <= 0) { //FIXME audio too?
132 av_log(s, AV_LOG_ERROR, "time base not set\n");
133 ret = AVERROR(EINVAL);
137 if ((codec->width <= 0 || codec->height <= 0) &&
138 !(of->flags & AVFMT_NODIMENSIONS)) {
139 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
140 ret = AVERROR(EINVAL);
144 if (av_cmp_q(st->sample_aspect_ratio,
145 codec->sample_aspect_ratio)) {
146 if (st->sample_aspect_ratio.num != 0 &&
147 st->sample_aspect_ratio.den != 0 &&
148 codec->sample_aspect_ratio.den != 0 &&
149 codec->sample_aspect_ratio.den != 0) {
150 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
151 "(%d/%d) and encoder layer (%d/%d)\n",
152 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
153 codec->sample_aspect_ratio.num,
154 codec->sample_aspect_ratio.den);
155 ret = AVERROR(EINVAL);
163 if (codec->codec_tag &&
164 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
165 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
166 !validate_codec_tag(s, st)) {
167 // the current rawvideo encoding system ends up setting
168 // the wrong codec_tag for avi, we override it here
169 codec->codec_tag = 0;
171 if (codec->codec_tag) {
172 if (!validate_codec_tag(s, st)) {
174 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
175 av_log(s, AV_LOG_ERROR,
176 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
177 tagbuf, codec->codec_tag, codec->codec_id);
178 ret = AVERROR_INVALIDDATA;
182 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
185 if (of->flags & AVFMT_GLOBALHEADER &&
186 !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
187 av_log(s, AV_LOG_WARNING,
188 "Codec for stream %d does not use global headers "
189 "but container format requires global headers\n", i);
191 if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
192 s->internal->nb_interleaved_streams++;
195 if (!s->priv_data && of->priv_data_size > 0) {
196 s->priv_data = av_mallocz(of->priv_data_size);
198 ret = AVERROR(ENOMEM);
201 if (of->priv_class) {
202 *(const AVClass **)s->priv_data = of->priv_class;
203 av_opt_set_defaults(s->priv_data);
204 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
209 /* set muxer identification string */
210 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
211 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
215 av_dict_free(options);
226 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
230 if (ret = init_muxer(s, options))
233 if (s->oformat->write_header) {
234 ret = s->oformat->write_header(s);
242 //FIXME merge with compute_pkt_fields
243 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
245 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
248 av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
249 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
251 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
252 * return AVERROR(EINVAL);*/
255 if (pkt->duration == 0) {
256 ff_compute_frame_duration(&num, &den, st, NULL, pkt);
258 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
262 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
265 //calculate dts from pts
266 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
267 st->pts_buffer[0] = pkt->pts;
268 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
269 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
270 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
271 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
273 pkt->dts = st->pts_buffer[0];
276 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
277 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
278 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
279 av_log(s, AV_LOG_ERROR,
280 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
281 st->index, st->cur_dts, pkt->dts);
282 return AVERROR(EINVAL);
284 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
285 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
286 return AVERROR(EINVAL);
289 av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
291 st->cur_dts = pkt->dts;
297 * FIXME: this function should NEVER get undefined pts/dts beside when the
298 * AVFMT_NOTIMESTAMPS is set.
299 * Those additional safety checks should be dropped once the correct checks
300 * are set in the callers.
303 static int write_packet(AVFormatContext *s, AVPacket *pkt)
306 if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
307 AVRational time_base = s->streams[pkt->stream_index]->time_base;
310 if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
311 s->offset = -pkt->dts;
312 s->offset_timebase = time_base;
315 offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
317 if (pkt->dts != AV_NOPTS_VALUE)
319 if (pkt->pts != AV_NOPTS_VALUE)
322 ret = s->oformat->write_packet(s, pkt);
324 if (s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
330 static int check_packet(AVFormatContext *s, AVPacket *pkt)
335 if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
336 av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
338 return AVERROR(EINVAL);
341 if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
342 av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
343 return AVERROR(EINVAL);
349 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
353 ret = check_packet(s, pkt);
358 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
359 return s->oformat->write_packet(s, pkt);
363 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
365 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
368 ret = write_packet(s, pkt);
371 s->streams[pkt->stream_index]->nb_frames++;
375 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
376 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
378 AVPacketList **next_point, *this_pktl;
380 this_pktl = av_mallocz(sizeof(AVPacketList));
381 this_pktl->pkt = *pkt;
382 #if FF_API_DESTRUCT_PACKET
383 FF_DISABLE_DEPRECATION_WARNINGS
384 pkt->destruct = NULL; // do not free original but only the copy
385 FF_ENABLE_DEPRECATION_WARNINGS
388 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
390 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
391 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
393 next_point = &s->packet_buffer;
396 if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
397 while (!compare(s, &(*next_point)->pkt, pkt))
398 next_point = &(*next_point)->next;
401 next_point = &(s->packet_buffer_end->next);
404 assert(!*next_point);
406 s->packet_buffer_end = this_pktl;
409 this_pktl->next = *next_point;
411 s->streams[pkt->stream_index]->last_in_packet_buffer =
412 *next_point = this_pktl;
415 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
418 AVStream *st = s->streams[pkt->stream_index];
419 AVStream *st2 = s->streams[next->stream_index];
420 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
424 return pkt->stream_index < next->stream_index;
428 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
429 AVPacket *pkt, int flush)
432 int stream_count = 0;
436 ff_interleave_add_packet(s, pkt, interleave_compare_dts);
439 if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
440 AVPacket *top_pkt = &s->packet_buffer->pkt;
441 int64_t delta_dts = INT64_MIN;
442 int64_t top_dts = av_rescale_q(top_pkt->dts,
443 s->streams[top_pkt->stream_index]->time_base,
446 for (i = 0; i < s->nb_streams; i++) {
448 const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
453 last_dts = av_rescale_q(last->pkt.dts,
454 s->streams[i]->time_base,
456 delta_dts = FFMAX(delta_dts, last_dts - top_dts);
460 if (delta_dts > s->max_interleave_delta) {
461 av_log(s, AV_LOG_DEBUG,
462 "Delay between the first packet and last packet in the "
463 "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
464 delta_dts, s->max_interleave_delta);
468 for (i = 0; i < s->nb_streams; i++)
469 stream_count += !!s->streams[i]->last_in_packet_buffer;
473 if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
474 pktl = s->packet_buffer;
477 s->packet_buffer = pktl->next;
478 if (!s->packet_buffer)
479 s->packet_buffer_end = NULL;
481 if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
482 s->streams[out->stream_index]->last_in_packet_buffer = NULL;
492 * Interleave an AVPacket correctly so it can be muxed.
493 * @param out the interleaved packet will be output here
494 * @param in the input packet
495 * @param flush 1 if no further packets are available as input and all
496 * remaining packets should be output
497 * @return 1 if a packet was output, 0 if no packet could be output,
498 * < 0 if an error occurred
500 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
502 if (s->oformat->interleave_packet) {
503 int ret = s->oformat->interleave_packet(s, out, in, flush);
508 return ff_interleave_packet_per_dts(s, out, in, flush);
511 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
515 ret = check_packet(s, pkt);
520 AVStream *st = s->streams[pkt->stream_index];
522 av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
523 pkt->size, pkt->dts, pkt->pts);
524 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
527 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
528 ret = AVERROR(EINVAL);
532 av_dlog(s, "av_interleaved_write_frame FLUSH\n");
538 int ret = interleave_packet(s, &opkt, pkt, flush);
540 memset(pkt, 0, sizeof(*pkt));
544 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
547 ret = write_packet(s, &opkt);
549 s->streams[opkt.stream_index]->nb_frames++;
551 av_free_packet(&opkt);
557 av_packet_unref(pkt);
561 int av_write_trailer(AVFormatContext *s)
567 ret = interleave_packet(s, &pkt, NULL, 1);
568 if (ret < 0) //FIXME cleanup needed for ret<0 ?
573 ret = write_packet(s, &pkt);
575 s->streams[pkt.stream_index]->nb_frames++;
577 av_free_packet(&pkt);
583 if (s->oformat->write_trailer)
584 ret = s->oformat->write_trailer(s);
586 if (!(s->oformat->flags & AVFMT_NOFILE))
590 for (i = 0; i < s->nb_streams; i++) {
591 av_freep(&s->streams[i]->priv_data);
592 av_freep(&s->streams[i]->index_entries);
594 if (s->oformat->priv_class)
595 av_opt_free(s->priv_data);
596 av_freep(&s->priv_data);
600 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
601 AVFormatContext *src)
606 local_pkt.stream_index = dst_stream;
607 if (pkt->pts != AV_NOPTS_VALUE)
608 local_pkt.pts = av_rescale_q(pkt->pts,
609 src->streams[pkt->stream_index]->time_base,
610 dst->streams[dst_stream]->time_base);
611 if (pkt->dts != AV_NOPTS_VALUE)
612 local_pkt.dts = av_rescale_q(pkt->dts,
613 src->streams[pkt->stream_index]->time_base,
614 dst->streams[dst_stream]->time_base);
615 return av_write_frame(dst, &local_pkt);