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 /* fraction handling */
57 * f = val + (num / den) + 0.5.
59 * 'num' is normalized so that it is such as 0 <= num < den.
61 * @param f fractional number
62 * @param val integer value
63 * @param num must be >= 0
64 * @param den must be >= 1
66 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
79 * Fractional addition to f: f = f + (incr / f->den).
81 * @param f fractional number
82 * @param incr increment, can be positive or negative
84 static void frac_add(AVFrac *f, int64_t incr)
97 } else if (num >= den) {
104 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
106 const AVCodecTag *avctag;
108 enum AVCodecID id = AV_CODEC_ID_NONE;
109 unsigned int tag = 0;
112 * Check that tag + id is in the table
113 * If neither is in the table -> OK
114 * If tag is in the table with another id -> FAIL
115 * If id is in the table with another tag -> FAIL unless strict < normal
117 for (n = 0; s->oformat->codec_tag[n]; n++) {
118 avctag = s->oformat->codec_tag[n];
119 while (avctag->id != AV_CODEC_ID_NONE) {
120 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
122 if (id == st->codec->codec_id)
125 if (avctag->id == st->codec->codec_id)
130 if (id != AV_CODEC_ID_NONE)
132 if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
138 static int init_muxer(AVFormatContext *s, AVDictionary **options)
142 AVDictionary *tmp = NULL;
143 AVCodecContext *codec = NULL;
144 AVOutputFormat *of = s->oformat;
147 av_dict_copy(&tmp, *options, 0);
149 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
152 #if FF_API_LAVF_BITEXACT
153 if (s->nb_streams && s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)
154 s->flags |= AVFMT_FLAG_BITEXACT;
157 // some sanity checks
158 if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
159 av_log(s, AV_LOG_ERROR, "no streams\n");
160 ret = AVERROR(EINVAL);
164 for (i = 0; i < s->nb_streams; i++) {
168 switch (codec->codec_type) {
169 case AVMEDIA_TYPE_AUDIO:
170 if (codec->sample_rate <= 0) {
171 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
172 ret = AVERROR(EINVAL);
175 if (!codec->block_align)
176 codec->block_align = codec->channels *
177 av_get_bits_per_sample(codec->codec_id) >> 3;
179 case AVMEDIA_TYPE_VIDEO:
180 if (codec->time_base.num <= 0 ||
181 codec->time_base.den <= 0) { //FIXME audio too?
182 av_log(s, AV_LOG_ERROR, "time base not set\n");
183 ret = AVERROR(EINVAL);
187 if ((codec->width <= 0 || codec->height <= 0) &&
188 !(of->flags & AVFMT_NODIMENSIONS)) {
189 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
190 ret = AVERROR(EINVAL);
194 if (av_cmp_q(st->sample_aspect_ratio,
195 codec->sample_aspect_ratio)) {
196 if (st->sample_aspect_ratio.num != 0 &&
197 st->sample_aspect_ratio.den != 0 &&
198 codec->sample_aspect_ratio.den != 0 &&
199 codec->sample_aspect_ratio.den != 0) {
200 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
201 "(%d/%d) and encoder layer (%d/%d)\n",
202 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
203 codec->sample_aspect_ratio.num,
204 codec->sample_aspect_ratio.den);
205 ret = AVERROR(EINVAL);
213 if (codec->codec_tag &&
214 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
215 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
216 !validate_codec_tag(s, st)) {
217 // the current rawvideo encoding system ends up setting
218 // the wrong codec_tag for avi, we override it here
219 codec->codec_tag = 0;
221 if (codec->codec_tag) {
222 if (!validate_codec_tag(s, st)) {
224 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
225 av_log(s, AV_LOG_ERROR,
226 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
227 tagbuf, codec->codec_tag, codec->codec_id);
228 ret = AVERROR_INVALIDDATA;
232 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
235 if (of->flags & AVFMT_GLOBALHEADER &&
236 !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
237 av_log(s, AV_LOG_WARNING,
238 "Codec for stream %d does not use global headers "
239 "but container format requires global headers\n", i);
241 if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
242 s->internal->nb_interleaved_streams++;
245 if (!s->priv_data && of->priv_data_size > 0) {
246 s->priv_data = av_mallocz(of->priv_data_size);
248 ret = AVERROR(ENOMEM);
251 if (of->priv_class) {
252 *(const AVClass **)s->priv_data = of->priv_class;
253 av_opt_set_defaults(s->priv_data);
254 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
259 /* set muxer identification string */
260 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
261 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
265 av_dict_free(options);
276 static int init_pts(AVFormatContext *s)
281 /* init PTS generation */
282 for (i = 0; i < s->nb_streams; i++) {
283 int64_t den = AV_NOPTS_VALUE;
286 switch (st->codec->codec_type) {
287 case AVMEDIA_TYPE_AUDIO:
288 den = (int64_t)st->time_base.num * st->codec->sample_rate;
290 case AVMEDIA_TYPE_VIDEO:
291 den = (int64_t)st->time_base.num * st->codec->time_base.den;
296 if (den != AV_NOPTS_VALUE) {
298 return AVERROR_INVALIDDATA;
300 frac_init(&st->pts, 0, 0, den);
307 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
311 if (ret = init_muxer(s, options))
314 if (s->oformat->write_header) {
315 ret = s->oformat->write_header(s);
320 if ((ret = init_pts(s)) < 0)
326 //FIXME merge with compute_pkt_fields
327 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
329 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
330 int num, den, frame_size, i;
332 av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
333 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
335 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
336 * return AVERROR(EINVAL);*/
339 if (pkt->duration == 0) {
340 ff_compute_frame_duration(&num, &den, st, NULL, pkt);
342 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
346 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
349 //calculate dts from pts
350 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
351 st->pts_buffer[0] = pkt->pts;
352 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
353 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
354 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
355 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
357 pkt->dts = st->pts_buffer[0];
360 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
361 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
362 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
363 av_log(s, AV_LOG_ERROR,
364 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
365 st->index, st->cur_dts, pkt->dts);
366 return AVERROR(EINVAL);
368 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
369 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
370 return AVERROR(EINVAL);
373 av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
375 st->cur_dts = pkt->dts;
376 st->pts.val = pkt->dts;
379 switch (st->codec->codec_type) {
380 case AVMEDIA_TYPE_AUDIO:
381 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
383 /* HACK/FIXME, we skip the initial 0 size packets as they are most
384 * likely equal to the encoder delay, but it would be better if we
385 * had the real timestamps from the encoder */
386 if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
387 frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
390 case AVMEDIA_TYPE_VIDEO:
391 frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
400 * FIXME: this function should NEVER get undefined pts/dts beside when the
401 * AVFMT_NOTIMESTAMPS is set.
402 * Those additional safety checks should be dropped once the correct checks
403 * are set in the callers.
406 static int write_packet(AVFormatContext *s, AVPacket *pkt)
409 if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
410 AVRational time_base = s->streams[pkt->stream_index]->time_base;
413 if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
414 s->offset = -pkt->dts;
415 s->offset_timebase = time_base;
418 offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
420 if (pkt->dts != AV_NOPTS_VALUE)
422 if (pkt->pts != AV_NOPTS_VALUE)
425 ret = s->oformat->write_packet(s, pkt);
427 if (s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
433 static int check_packet(AVFormatContext *s, AVPacket *pkt)
438 if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
439 av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
441 return AVERROR(EINVAL);
444 if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
445 av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
446 return AVERROR(EINVAL);
452 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
456 ret = check_packet(s, pkt);
461 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
462 return s->oformat->write_packet(s, pkt);
466 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
468 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
471 ret = write_packet(s, pkt);
474 s->streams[pkt->stream_index]->nb_frames++;
478 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
479 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
481 AVPacketList **next_point, *this_pktl;
483 this_pktl = av_mallocz(sizeof(AVPacketList));
484 this_pktl->pkt = *pkt;
485 #if FF_API_DESTRUCT_PACKET
486 FF_DISABLE_DEPRECATION_WARNINGS
487 pkt->destruct = NULL; // do not free original but only the copy
488 FF_ENABLE_DEPRECATION_WARNINGS
491 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
493 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
494 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
496 next_point = &s->packet_buffer;
499 if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
500 while (!compare(s, &(*next_point)->pkt, pkt))
501 next_point = &(*next_point)->next;
504 next_point = &(s->packet_buffer_end->next);
507 assert(!*next_point);
509 s->packet_buffer_end = this_pktl;
512 this_pktl->next = *next_point;
514 s->streams[pkt->stream_index]->last_in_packet_buffer =
515 *next_point = this_pktl;
518 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
521 AVStream *st = s->streams[pkt->stream_index];
522 AVStream *st2 = s->streams[next->stream_index];
523 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
527 return pkt->stream_index < next->stream_index;
531 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
532 AVPacket *pkt, int flush)
535 int stream_count = 0;
539 ff_interleave_add_packet(s, pkt, interleave_compare_dts);
542 if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
543 AVPacket *top_pkt = &s->packet_buffer->pkt;
544 int64_t delta_dts = INT64_MIN;
545 int64_t top_dts = av_rescale_q(top_pkt->dts,
546 s->streams[top_pkt->stream_index]->time_base,
549 for (i = 0; i < s->nb_streams; i++) {
551 const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
556 last_dts = av_rescale_q(last->pkt.dts,
557 s->streams[i]->time_base,
559 delta_dts = FFMAX(delta_dts, last_dts - top_dts);
563 if (delta_dts > s->max_interleave_delta) {
564 av_log(s, AV_LOG_DEBUG,
565 "Delay between the first packet and last packet in the "
566 "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
567 delta_dts, s->max_interleave_delta);
571 for (i = 0; i < s->nb_streams; i++)
572 stream_count += !!s->streams[i]->last_in_packet_buffer;
576 if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
577 pktl = s->packet_buffer;
580 s->packet_buffer = pktl->next;
581 if (!s->packet_buffer)
582 s->packet_buffer_end = NULL;
584 if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
585 s->streams[out->stream_index]->last_in_packet_buffer = NULL;
595 * Interleave an AVPacket correctly so it can be muxed.
596 * @param out the interleaved packet will be output here
597 * @param in the input packet
598 * @param flush 1 if no further packets are available as input and all
599 * remaining packets should be output
600 * @return 1 if a packet was output, 0 if no packet could be output,
601 * < 0 if an error occurred
603 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
605 if (s->oformat->interleave_packet) {
606 int ret = s->oformat->interleave_packet(s, out, in, flush);
611 return ff_interleave_packet_per_dts(s, out, in, flush);
614 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
618 ret = check_packet(s, pkt);
623 AVStream *st = s->streams[pkt->stream_index];
625 av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
626 pkt->size, pkt->dts, pkt->pts);
627 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
630 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
631 ret = AVERROR(EINVAL);
635 av_dlog(s, "av_interleaved_write_frame FLUSH\n");
641 int ret = interleave_packet(s, &opkt, pkt, flush);
643 memset(pkt, 0, sizeof(*pkt));
647 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
650 ret = write_packet(s, &opkt);
652 s->streams[opkt.stream_index]->nb_frames++;
654 av_free_packet(&opkt);
660 av_packet_unref(pkt);
664 int av_write_trailer(AVFormatContext *s)
670 ret = interleave_packet(s, &pkt, NULL, 1);
671 if (ret < 0) //FIXME cleanup needed for ret<0 ?
676 ret = write_packet(s, &pkt);
678 s->streams[pkt.stream_index]->nb_frames++;
680 av_free_packet(&pkt);
686 if (s->oformat->write_trailer)
687 ret = s->oformat->write_trailer(s);
689 if (!(s->oformat->flags & AVFMT_NOFILE))
693 for (i = 0; i < s->nb_streams; i++) {
694 av_freep(&s->streams[i]->priv_data);
695 av_freep(&s->streams[i]->index_entries);
697 if (s->oformat->priv_class)
698 av_opt_free(s->priv_data);
699 av_freep(&s->priv_data);
703 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
704 AVFormatContext *src)
709 local_pkt.stream_index = dst_stream;
710 if (pkt->pts != AV_NOPTS_VALUE)
711 local_pkt.pts = av_rescale_q(pkt->pts,
712 src->streams[pkt->stream_index]->time_base,
713 dst->streams[dst_stream]->time_base);
714 if (pkt->dts != AV_NOPTS_VALUE)
715 local_pkt.dts = av_rescale_q(pkt->dts,
716 src->streams[pkt->stream_index]->time_base,
717 dst->streams[dst_stream]->time_base);
718 return av_write_frame(dst, &local_pkt);