2 * muxing functions for use within FFmpeg
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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"
30 #include "libavutil/timestamp.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/time.h"
40 #include "audiointerleave.h"
52 * muxing functions for use within libavformat
55 /* fraction handling */
58 * f = val + (num / den) + 0.5.
60 * 'num' is normalized so that it is such as 0 <= num < den.
62 * @param f fractional number
63 * @param val integer value
64 * @param num must be >= 0
65 * @param den must be >= 1
67 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
80 * Fractional addition to f: f = f + (incr / f->den).
82 * @param f fractional number
83 * @param incr increment, can be positive or negative
85 static void frac_add(AVFrac *f, int64_t incr)
98 } else if (num >= den) {
105 AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precision)
112 for (j=2; j<14; j+= 1+(j>2))
113 while (q.den / q.num < min_precision && q.num % j == 0)
115 while (q.den / q.num < min_precision && q.den < (1<<24))
121 int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
122 const char *format, const char *filename)
124 AVFormatContext *s = avformat_alloc_context();
133 oformat = av_guess_format(format, NULL, NULL);
135 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
136 ret = AVERROR(EINVAL);
140 oformat = av_guess_format(NULL, filename, NULL);
142 ret = AVERROR(EINVAL);
143 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
150 s->oformat = oformat;
151 if (s->oformat->priv_data_size > 0) {
152 s->priv_data = av_mallocz(s->oformat->priv_data_size);
155 if (s->oformat->priv_class) {
156 *(const AVClass**)s->priv_data= s->oformat->priv_class;
157 av_opt_set_defaults(s->priv_data);
163 av_strlcpy(s->filename, filename, sizeof(s->filename));
167 av_log(s, AV_LOG_ERROR, "Out of memory\n");
168 ret = AVERROR(ENOMEM);
170 avformat_free_context(s);
174 #if FF_API_ALLOC_OUTPUT_CONTEXT
175 AVFormatContext *avformat_alloc_output_context(const char *format,
176 AVOutputFormat *oformat, const char *filename)
178 AVFormatContext *avctx;
179 int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
180 return ret < 0 ? NULL : avctx;
184 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
186 const AVCodecTag *avctag;
188 enum AVCodecID id = AV_CODEC_ID_NONE;
192 * Check that tag + id is in the table
193 * If neither is in the table -> OK
194 * If tag is in the table with another id -> FAIL
195 * If id is in the table with another tag -> FAIL unless strict < normal
197 for (n = 0; s->oformat->codec_tag[n]; n++) {
198 avctag = s->oformat->codec_tag[n];
199 while (avctag->id != AV_CODEC_ID_NONE) {
200 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
202 if (id == st->codec->codec_id)
205 if (avctag->id == st->codec->codec_id)
210 if (id != AV_CODEC_ID_NONE)
212 if (tag >= 0 && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
218 static int init_muxer(AVFormatContext *s, AVDictionary **options)
222 AVDictionary *tmp = NULL;
223 AVCodecContext *codec = NULL;
224 AVOutputFormat *of = s->oformat;
225 AVDictionaryEntry *e;
228 av_dict_copy(&tmp, *options, 0);
230 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
232 if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
233 (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
236 #if FF_API_LAVF_BITEXACT
237 if (s->nb_streams && s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)
238 s->flags |= AVFMT_FLAG_BITEXACT;
241 // some sanity checks
242 if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
243 av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
244 ret = AVERROR(EINVAL);
248 for (i = 0; i < s->nb_streams; i++) {
252 #if FF_API_LAVF_CODEC_TB
253 FF_DISABLE_DEPRECATION_WARNINGS
254 if (!st->time_base.num && codec->time_base.num) {
255 av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
256 "timebase hint to the muxer is deprecated. Set "
257 "AVStream.time_base instead.\n");
258 avpriv_set_pts_info(st, 64, codec->time_base.num, codec->time_base.den);
260 FF_ENABLE_DEPRECATION_WARNINGS
263 if (!st->time_base.num) {
264 /* fall back on the default timebase values */
265 if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->sample_rate)
266 avpriv_set_pts_info(st, 64, 1, codec->sample_rate);
268 avpriv_set_pts_info(st, 33, 1, 90000);
271 switch (codec->codec_type) {
272 case AVMEDIA_TYPE_AUDIO:
273 if (codec->sample_rate <= 0) {
274 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
275 ret = AVERROR(EINVAL);
278 if (!codec->block_align)
279 codec->block_align = codec->channels *
280 av_get_bits_per_sample(codec->codec_id) >> 3;
282 case AVMEDIA_TYPE_VIDEO:
283 if ((codec->width <= 0 || codec->height <= 0) &&
284 !(of->flags & AVFMT_NODIMENSIONS)) {
285 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
286 ret = AVERROR(EINVAL);
289 if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
290 && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
292 if (st->sample_aspect_ratio.num != 0 &&
293 st->sample_aspect_ratio.den != 0 &&
294 codec->sample_aspect_ratio.den != 0 &&
295 codec->sample_aspect_ratio.den != 0) {
296 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
297 "(%d/%d) and encoder layer (%d/%d)\n",
298 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
299 codec->sample_aspect_ratio.num,
300 codec->sample_aspect_ratio.den);
301 ret = AVERROR(EINVAL);
309 if ( codec->codec_tag
310 && codec->codec_id == AV_CODEC_ID_RAWVIDEO
311 && ( av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
312 || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
313 && !validate_codec_tag(s, st)) {
314 // the current rawvideo encoding system ends up setting
315 // the wrong codec_tag for avi/mov, we override it here
316 codec->codec_tag = 0;
318 if (codec->codec_tag) {
319 if (!validate_codec_tag(s, st)) {
320 char tagbuf[32], tagbuf2[32];
321 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
322 av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
323 av_log(s, AV_LOG_ERROR,
324 "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
325 tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
326 ret = AVERROR_INVALIDDATA;
330 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
333 if (of->flags & AVFMT_GLOBALHEADER &&
334 !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
335 av_log(s, AV_LOG_WARNING,
336 "Codec for stream %d does not use global headers "
337 "but container format requires global headers\n", i);
339 if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
340 s->internal->nb_interleaved_streams++;
343 if (!s->priv_data && of->priv_data_size > 0) {
344 s->priv_data = av_mallocz(of->priv_data_size);
346 ret = AVERROR(ENOMEM);
349 if (of->priv_class) {
350 *(const AVClass **)s->priv_data = of->priv_class;
351 av_opt_set_defaults(s->priv_data);
352 if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
357 /* set muxer identification string */
358 if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
359 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
361 av_dict_set(&s->metadata, "encoder", NULL, 0);
364 for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
365 av_dict_set(&s->metadata, e->key, NULL, 0);
369 av_dict_free(options);
380 static int init_pts(AVFormatContext *s)
385 /* init PTS generation */
386 for (i = 0; i < s->nb_streams; i++) {
387 int64_t den = AV_NOPTS_VALUE;
390 switch (st->codec->codec_type) {
391 case AVMEDIA_TYPE_AUDIO:
392 den = (int64_t)st->time_base.num * st->codec->sample_rate;
394 case AVMEDIA_TYPE_VIDEO:
395 den = (int64_t)st->time_base.num * st->codec->time_base.den;
400 if (den != AV_NOPTS_VALUE) {
402 return AVERROR_INVALIDDATA;
404 frac_init(&st->pts, 0, 0, den);
411 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
415 if (ret = init_muxer(s, options))
418 if (s->oformat->write_header) {
419 ret = s->oformat->write_header(s);
420 if (ret >= 0 && s->pb && s->pb->error < 0)
426 if ((ret = init_pts(s)) < 0)
429 if (s->avoid_negative_ts < 0) {
430 if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
431 s->avoid_negative_ts = 0;
433 s->avoid_negative_ts = 1;
439 #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
441 /* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
442 it is only being used internally to this file as a consistency check.
443 The value is chosen to be very unlikely to appear on its own and to cause
444 immediate failure if used anywhere as a real size. */
445 #define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))
448 //FIXME merge with compute_pkt_fields
449 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
451 int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
455 av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
456 av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
458 if (pkt->duration < 0 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
459 av_log(s, AV_LOG_WARNING, "Packet with invalid duration %d in stream %d\n",
460 pkt->duration, pkt->stream_index);
465 if (pkt->duration == 0) {
466 ff_compute_frame_duration(&num, &den, st, NULL, pkt);
468 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
472 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
475 //XXX/FIXME this is a temporary hack until all encoders output pts
476 if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
479 av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
483 // pkt->pts= st->cur_dts;
484 pkt->pts = st->pts.val;
487 //calculate dts from pts
488 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
489 st->pts_buffer[0] = pkt->pts;
490 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
491 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
492 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
493 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
495 pkt->dts = st->pts_buffer[0];
498 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
499 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
500 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
501 av_log(s, AV_LOG_ERROR,
502 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
503 st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
504 return AVERROR(EINVAL);
506 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
507 av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
508 av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
509 return AVERROR(EINVAL);
512 av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
513 av_ts2str(pkt->pts), av_ts2str(pkt->dts));
514 st->cur_dts = pkt->dts;
515 st->pts.val = pkt->dts;
518 switch (st->codec->codec_type) {
519 case AVMEDIA_TYPE_AUDIO:
520 frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
521 ((AVFrame *)pkt->data)->nb_samples :
522 ff_get_audio_frame_size(st->codec, pkt->size, 1);
524 /* HACK/FIXME, we skip the initial 0 size packets as they are most
525 * likely equal to the encoder delay, but it would be better if we
526 * had the real timestamps from the encoder */
527 if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
528 frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
531 case AVMEDIA_TYPE_VIDEO:
532 frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
539 * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
542 * FIXME: this function should NEVER get undefined pts/dts beside when the
543 * AVFMT_NOTIMESTAMPS is set.
544 * Those additional safety checks should be dropped once the correct checks
545 * are set in the callers.
547 static int write_packet(AVFormatContext *s, AVPacket *pkt)
551 if (s->output_ts_offset) {
552 AVStream *st = s->streams[pkt->stream_index];
553 int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
555 if (pkt->dts != AV_NOPTS_VALUE)
557 if (pkt->pts != AV_NOPTS_VALUE)
561 if (s->avoid_negative_ts > 0) {
562 AVStream *st = s->streams[pkt->stream_index];
563 int64_t offset = st->mux_ts_offset;
565 if ((pkt->dts < 0 || s->avoid_negative_ts == 2) && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
566 s->offset = -pkt->dts;
567 s->offset_timebase = st->time_base;
570 if (s->offset && !offset) {
571 offset = st->mux_ts_offset =
572 av_rescale_q_rnd(s->offset,
578 if (pkt->dts != AV_NOPTS_VALUE)
580 if (pkt->pts != AV_NOPTS_VALUE)
583 av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
586 did_split = av_packet_split_side_data(pkt);
587 if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
588 AVFrame *frame = (AVFrame *)pkt->data;
589 av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
590 ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
591 av_frame_free(&frame);
593 ret = s->oformat->write_packet(s, pkt);
596 if (s->flush_packets && s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
600 av_packet_merge_side_data(pkt);
605 static int check_packet(AVFormatContext *s, AVPacket *pkt)
610 if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
611 av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
613 return AVERROR(EINVAL);
616 if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
617 av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
618 return AVERROR(EINVAL);
624 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
628 ret = check_packet(s, pkt);
633 if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
634 ret = s->oformat->write_packet(s, NULL);
635 if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
637 if (ret >= 0 && s->pb && s->pb->error < 0)
644 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
646 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
649 ret = write_packet(s, pkt);
650 if (ret >= 0 && s->pb && s->pb->error < 0)
654 s->streams[pkt->stream_index]->nb_frames++;
658 #define CHUNK_START 0x1000
660 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
661 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
663 AVPacketList **next_point, *this_pktl;
664 AVStream *st = s->streams[pkt->stream_index];
665 int chunked = s->max_chunk_size || s->max_chunk_duration;
668 this_pktl = av_mallocz(sizeof(AVPacketList));
670 return AVERROR(ENOMEM);
671 this_pktl->pkt = *pkt;
672 #if FF_API_DESTRUCT_PACKET
673 FF_DISABLE_DEPRECATION_WARNINGS
674 pkt->destruct = NULL; // do not free original but only the copy
675 FF_ENABLE_DEPRECATION_WARNINGS
678 pkt->side_data = NULL;
679 pkt->side_data_elems = 0;
680 if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
681 av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
682 av_assert0(((AVFrame *)pkt->data)->buf);
684 // duplicate the packet if it uses non-allocated memory
685 if ((ret = av_dup_packet(&this_pktl->pkt)) < 0) {
691 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
692 next_point = &(st->last_in_packet_buffer->next);
694 next_point = &s->packet_buffer;
698 uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
699 st->interleaver_chunk_size += pkt->size;
700 st->interleaver_chunk_duration += pkt->duration;
701 if ( (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
702 || (max && st->interleaver_chunk_duration > max)) {
703 st->interleaver_chunk_size = 0;
704 this_pktl->pkt.flags |= CHUNK_START;
705 if (max && st->interleaver_chunk_duration > max) {
706 int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
707 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
709 st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
711 st->interleaver_chunk_duration = 0;
715 if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
718 if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
720 && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
721 || !compare(s, &(*next_point)->pkt, pkt)))
722 next_point = &(*next_point)->next;
726 next_point = &(s->packet_buffer_end->next);
729 av_assert1(!*next_point);
731 s->packet_buffer_end = this_pktl;
734 this_pktl->next = *next_point;
736 s->streams[pkt->stream_index]->last_in_packet_buffer =
737 *next_point = this_pktl;
741 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
744 AVStream *st = s->streams[pkt->stream_index];
745 AVStream *st2 = s->streams[next->stream_index];
746 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
748 if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
749 int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
750 int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
752 ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
753 -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
756 comp= (ts>ts2) - (ts<ts2);
760 return pkt->stream_index < next->stream_index;
764 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
765 AVPacket *pkt, int flush)
768 int stream_count = 0, noninterleaved_count = 0;
772 ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
777 for (i = 0; i < s->nb_streams; i++) {
778 if (s->streams[i]->last_in_packet_buffer) {
780 } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
781 ++noninterleaved_count;
785 if (s->internal->nb_interleaved_streams == stream_count)
788 if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
789 AVPacket *top_pkt = &s->packet_buffer->pkt;
790 int64_t delta_dts = INT64_MIN;
791 int64_t top_dts = av_rescale_q(top_pkt->dts,
792 s->streams[top_pkt->stream_index]->time_base,
795 for (i = 0; i < s->nb_streams; i++) {
797 const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
802 last_dts = av_rescale_q(last->pkt.dts,
803 s->streams[i]->time_base,
805 delta_dts = FFMAX(delta_dts, last_dts - top_dts);
808 if (delta_dts > s->max_interleave_delta) {
809 av_log(s, AV_LOG_DEBUG,
810 "Delay between the first packet and last packet in the "
811 "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
812 delta_dts, s->max_interleave_delta);
817 if (stream_count && flush) {
819 pktl = s->packet_buffer;
821 st = s->streams[out->stream_index];
823 s->packet_buffer = pktl->next;
824 if (!s->packet_buffer)
825 s->packet_buffer_end = NULL;
827 if (st->last_in_packet_buffer == pktl)
828 st->last_in_packet_buffer = NULL;
839 * Interleave an AVPacket correctly so it can be muxed.
840 * @param out the interleaved packet will be output here
841 * @param in the input packet
842 * @param flush 1 if no further packets are available as input and all
843 * remaining packets should be output
844 * @return 1 if a packet was output, 0 if no packet could be output,
845 * < 0 if an error occurred
847 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
849 if (s->oformat->interleave_packet) {
850 int ret = s->oformat->interleave_packet(s, out, in, flush);
855 return ff_interleave_packet_per_dts(s, out, in, flush);
858 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
862 ret = check_packet(s, pkt);
867 AVStream *st = s->streams[pkt->stream_index];
869 av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
870 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
871 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
874 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
875 ret = AVERROR(EINVAL);
879 av_dlog(s, "av_interleaved_write_frame FLUSH\n");
885 int ret = interleave_packet(s, &opkt, pkt, flush);
887 memset(pkt, 0, sizeof(*pkt));
891 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
894 ret = write_packet(s, &opkt);
896 s->streams[opkt.stream_index]->nb_frames++;
898 av_free_packet(&opkt);
902 if(s->pb && s->pb->error)
906 av_packet_unref(pkt);
910 int av_write_trailer(AVFormatContext *s)
916 ret = interleave_packet(s, &pkt, NULL, 1);
917 if (ret < 0) //FIXME cleanup needed for ret<0 ?
922 ret = write_packet(s, &pkt);
924 s->streams[pkt.stream_index]->nb_frames++;
926 av_free_packet(&pkt);
930 if(s->pb && s->pb->error)
934 if (s->oformat->write_trailer)
935 ret = s->oformat->write_trailer(s);
941 ret = s->pb ? s->pb->error : 0;
942 for (i = 0; i < s->nb_streams; i++) {
943 av_freep(&s->streams[i]->priv_data);
944 av_freep(&s->streams[i]->index_entries);
946 if (s->oformat->priv_class)
947 av_opt_free(s->priv_data);
948 av_freep(&s->priv_data);
952 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
953 int64_t *dts, int64_t *wall)
955 if (!s->oformat || !s->oformat->get_output_timestamp)
956 return AVERROR(ENOSYS);
957 s->oformat->get_output_timestamp(s, stream, dts, wall);
961 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
962 AVFormatContext *src)
967 local_pkt.stream_index = dst_stream;
968 if (pkt->pts != AV_NOPTS_VALUE)
969 local_pkt.pts = av_rescale_q(pkt->pts,
970 src->streams[pkt->stream_index]->time_base,
971 dst->streams[dst_stream]->time_base);
972 if (pkt->dts != AV_NOPTS_VALUE)
973 local_pkt.dts = av_rescale_q(pkt->dts,
974 src->streams[pkt->stream_index]->time_base,
975 dst->streams[dst_stream]->time_base);
977 local_pkt.duration = av_rescale_q(pkt->duration,
978 src->streams[pkt->stream_index]->time_base,
979 dst->streams[dst_stream]->time_base);
980 return av_write_frame(dst, &local_pkt);
983 static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
984 AVFrame *frame, int interleaved)
988 av_assert0(s->oformat);
989 if (!s->oformat->write_uncoded_frame)
990 return AVERROR(ENOSYS);
996 av_init_packet(&pkt);
997 pkt.data = (void *)frame;
998 pkt.size = UNCODED_FRAME_PACKET_SIZE;
1000 pkt.dts = frame->pts;
1001 pkt.duration = av_frame_get_pkt_duration(frame);
1002 pkt.stream_index = stream_index;
1003 pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
1006 return interleaved ? av_interleaved_write_frame(s, pktp) :
1007 av_write_frame(s, pktp);
1010 int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
1013 return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
1016 int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
1019 return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
1022 int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
1024 av_assert0(s->oformat);
1025 if (!s->oformat->write_uncoded_frame)
1026 return AVERROR(ENOSYS);
1027 return s->oformat->write_uncoded_frame(s, stream_index, NULL,
1028 AV_WRITE_UNCODED_FRAME_QUERY);