mux.c 47.6 KB
Newer Older
1
/*
2
 * muxing functions for use within FFmpeg
3 4
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 9 10 11
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * 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 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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 20 21 22 23 24 25 26 27 28 29
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "avformat.h"
#include "avio_internal.h"
#include "internal.h"
#include "libavcodec/internal.h"
#include "libavcodec/bytestream.h"
#include "libavutil/opt.h"
#include "libavutil/dict.h"
#include "libavutil/pixdesc.h"
30
#include "libavutil/timestamp.h"
31 32 33 34
#include "metadata.h"
#include "id3v2.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
35
#include "libavutil/internal.h"
36 37 38 39 40 41 42 43 44 45 46 47 48
#include "libavutil/mathematics.h"
#include "libavutil/parseutils.h"
#include "libavutil/time.h"
#include "riff.h"
#include "audiointerleave.h"
#include "url.h"
#include <stdarg.h>
#if CONFIG_NETWORK
#include "network.h"
#endif

/**
 * @file
49
 * muxing functions for use within libavformat
50 51 52 53 54 55 56 57 58 59 60 61 62 63
 */

/* fraction handling */

/**
 * f = val + (num / den) + 0.5.
 *
 * 'num' is normalized so that it is such as 0 <= num < den.
 *
 * @param f fractional number
 * @param val integer value
 * @param num must be >= 0
 * @param den must be >= 1
 */
64
static void frac_init(FFFrac *f, int64_t val, int64_t num, int64_t den)
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
{
    num += (den >> 1);
    if (num >= den) {
        val += num / den;
        num  = num % den;
    }
    f->val = val;
    f->num = num;
    f->den = den;
}

/**
 * Fractional addition to f: f = f + (incr / f->den).
 *
 * @param f fractional number
 * @param incr increment, can be positive or negative
 */
82
static void frac_add(FFFrac *f, int64_t incr)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
{
    int64_t num, den;

    num = f->num + incr;
    den = f->den;
    if (num < 0) {
        f->val += num / den;
        num     = num % den;
        if (num < 0) {
            num += den;
            f->val--;
        }
    } else if (num >= den) {
        f->val += num / den;
        num     = num % den;
    }
    f->num = num;
}

102
AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precision)
103 104 105 106
{
    AVRational q;
    int j;

107 108
    q = st->time_base;

109
    for (j=2; j<14; j+= 1+(j>2))
110
        while (q.den / q.num < min_precision && q.num % j == 0)
111
            q.num /= j;
112
    while (q.den / q.num < min_precision && q.den < (1<<24))
113 114 115 116 117
        q.den <<= 1;

    return q;
}

118 119
enum AVChromaLocation ff_choose_chroma_location(AVFormatContext *s, AVStream *st)
{
120 121
    AVCodecParameters *par = st->codecpar;
    const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(par->format);
122

123 124
    if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
        return par->chroma_location;
125 126 127 128 129

    if (pix_desc) {
        if (pix_desc->log2_chroma_h == 0) {
            return AVCHROMA_LOC_TOPLEFT;
        } else if (pix_desc->log2_chroma_w == 1 && pix_desc->log2_chroma_h == 1) {
130 131
            if (par->field_order == AV_FIELD_UNKNOWN || par->field_order == AV_FIELD_PROGRESSIVE) {
                switch (par->codec_id) {
132 133 134 135
                case AV_CODEC_ID_MJPEG:
                case AV_CODEC_ID_MPEG1VIDEO: return AVCHROMA_LOC_CENTER;
                }
            }
136 137
            if (par->field_order == AV_FIELD_UNKNOWN || par->field_order != AV_FIELD_PROGRESSIVE) {
                switch (par->codec_id) {
138 139 140 141 142 143 144 145 146 147
                case AV_CODEC_ID_MPEG2VIDEO: return AVCHROMA_LOC_LEFT;
                }
            }
        }
    }

    return AVCHROMA_LOC_UNSPECIFIED;

}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
                                   const char *format, const char *filename)
{
    AVFormatContext *s = avformat_alloc_context();
    int ret = 0;

    *avctx = NULL;
    if (!s)
        goto nomem;

    if (!oformat) {
        if (format) {
            oformat = av_guess_format(format, NULL, NULL);
            if (!oformat) {
                av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
                ret = AVERROR(EINVAL);
                goto error;
            }
        } else {
            oformat = av_guess_format(NULL, filename, NULL);
            if (!oformat) {
                ret = AVERROR(EINVAL);
                av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
                       filename);
                goto error;
            }
        }
    }

    s->oformat = oformat;
    if (s->oformat->priv_data_size > 0) {
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
        if (!s->priv_data)
            goto nomem;
        if (s->oformat->priv_class) {
            *(const AVClass**)s->priv_data= s->oformat->priv_class;
            av_opt_set_defaults(s->priv_data);
        }
    } else
        s->priv_data = NULL;

    if (filename)
        av_strlcpy(s->filename, filename, sizeof(s->filename));
    *avctx = s;
    return 0;
nomem:
    av_log(s, AV_LOG_ERROR, "Out of memory\n");
    ret = AVERROR(ENOMEM);
error:
    avformat_free_context(s);
    return ret;
}

201 202 203 204 205
static int validate_codec_tag(AVFormatContext *s, AVStream *st)
{
    const AVCodecTag *avctag;
    int n;
    enum AVCodecID id = AV_CODEC_ID_NONE;
206
    int64_t tag  = -1;
207 208 209 210 211 212 213 214 215 216

    /**
     * Check that tag + id is in the table
     * If neither is in the table -> OK
     * If tag is in the table with another id -> FAIL
     * If id is in the table with another tag -> FAIL unless strict < normal
     */
    for (n = 0; s->oformat->codec_tag[n]; n++) {
        avctag = s->oformat->codec_tag[n];
        while (avctag->id != AV_CODEC_ID_NONE) {
217
            if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codecpar->codec_tag)) {
218
                id = avctag->id;
219
                if (id == st->codecpar->codec_id)
220 221
                    return 1;
            }
222
            if (avctag->id == st->codecpar->codec_id)
223 224 225 226 227 228
                tag = avctag->tag;
            avctag++;
        }
    }
    if (id != AV_CODEC_ID_NONE)
        return 0;
229
    if (tag >= 0 && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
230 231 232 233
        return 0;
    return 1;
}

234 235

static int init_muxer(AVFormatContext *s, AVDictionary **options)
236 237 238 239
{
    int ret = 0, i;
    AVStream *st;
    AVDictionary *tmp = NULL;
240
    AVCodecParameters *par = NULL;
241
    AVOutputFormat *of = s->oformat;
242
    const AVCodecDescriptor *desc;
243
    AVDictionaryEntry *e;
244 245 246

    if (options)
        av_dict_copy(&tmp, *options, 0);
247

248 249
    if ((ret = av_opt_set_dict(s, &tmp)) < 0)
        goto fail;
250
    if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
251
        (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
252
        goto fail;
253

254
#if FF_API_LAVF_AVCTX
255
FF_DISABLE_DEPRECATION_WARNINGS
256 257
    if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT) {
        if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
258
#if FF_API_LAVF_BITEXACT
259 260 261 262 263 264 265 266 267 268 269
            av_log(s, AV_LOG_WARNING,
                   "Setting the AVFormatContext to bitexact mode, because "
                   "the AVCodecContext is in that mode. This behavior will "
                   "change in the future. To keep the current behavior, set "
                   "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");
            s->flags |= AVFMT_FLAG_BITEXACT;
#else
            av_log(s, AV_LOG_WARNING,
                   "The AVFormatContext is not in set to bitexact mode, only "
                   "the AVCodecContext. If this is not intended, set "
                   "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");
270
#endif
271 272
        }
    }
273
FF_ENABLE_DEPRECATION_WARNINGS
274 275
#endif

276
    // some sanity checks
277
    if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
278
        av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
279 280 281 282 283
        ret = AVERROR(EINVAL);
        goto fail;
    }

    for (i = 0; i < s->nb_streams; i++) {
284 285
        st  = s->streams[i];
        par = st->codecpar;
286

287
#if FF_API_LAVF_CODEC_TB && FF_API_LAVF_AVCTX
288
FF_DISABLE_DEPRECATION_WARNINGS
289
        if (!st->time_base.num && st->codec->time_base.num) {
290 291 292
            av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
                   "timebase hint to the muxer is deprecated. Set "
                   "AVStream.time_base instead.\n");
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
            avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
        }
FF_ENABLE_DEPRECATION_WARNINGS
#endif

#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
        if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
            st->codec->codec_type    != AVMEDIA_TYPE_UNKNOWN) {
            av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "
                   "parameters to muxers is deprecated, use AVStream.codecpar "
                   "instead.\n");
            ret = avcodec_parameters_from_context(st->codecpar, st->codec);
            if (ret < 0)
                goto fail;
308 309 310 311 312 313
        }
FF_ENABLE_DEPRECATION_WARNINGS
#endif

        if (!st->time_base.num) {
            /* fall back on the default timebase values */
314 315
            if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
                avpriv_set_pts_info(st, 64, 1, par->sample_rate);
316 317 318 319
            else
                avpriv_set_pts_info(st, 33, 1, 90000);
        }

320
        switch (par->codec_type) {
321
        case AVMEDIA_TYPE_AUDIO:
322
            if (par->sample_rate <= 0) {
323 324 325 326
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
                ret = AVERROR(EINVAL);
                goto fail;
            }
327 328 329
            if (!par->block_align)
                par->block_align = par->channels *
                                   av_get_bits_per_sample(par->codec_id) >> 3;
330 331
            break;
        case AVMEDIA_TYPE_VIDEO:
332
            if ((par->width <= 0 || par->height <= 0) &&
333
                !(of->flags & AVFMT_NODIMENSIONS)) {
334 335 336 337
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
                ret = AVERROR(EINVAL);
                goto fail;
            }
338 339
            if (av_cmp_q(st->sample_aspect_ratio, par->sample_aspect_ratio)
                && fabs(av_q2d(st->sample_aspect_ratio) - av_q2d(par->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
340
            ) {
341 342
                if (st->sample_aspect_ratio.num != 0 &&
                    st->sample_aspect_ratio.den != 0 &&
343
                    par->sample_aspect_ratio.num != 0 &&
344
                    par->sample_aspect_ratio.den != 0) {
345
                    av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
346 347
                           "(%d/%d) and encoder layer (%d/%d)\n",
                           st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
348 349
                           par->sample_aspect_ratio.num,
                           par->sample_aspect_ratio.den);
350 351 352
                    ret = AVERROR(EINVAL);
                    goto fail;
                }
353 354 355 356
            }
            break;
        }

357
        desc = avcodec_descriptor_get(par->codec_id);
358 359 360
        if (desc && desc->props & AV_CODEC_PROP_REORDER)
            st->internal->reorder = 1;

361
        if (of->codec_tag) {
362 363 364 365
            if (   par->codec_tag
                && par->codec_id == AV_CODEC_ID_RAWVIDEO
                && (   av_codec_get_tag(of->codec_tag, par->codec_id) == 0
                    || av_codec_get_tag(of->codec_tag, par->codec_id) == MKTAG('r', 'a', 'w', ' '))
366
                && !validate_codec_tag(s, st)) {
367
                // the current rawvideo encoding system ends up setting
368
                // the wrong codec_tag for avi/mov, we override it here
369
                par->codec_tag = 0;
370
            }
371
            if (par->codec_tag) {
372
                if (!validate_codec_tag(s, st)) {
373
                    char tagbuf[32], tagbuf2[32];
374
                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), par->codec_tag);
375
                    av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, par->codec_id));
376
                    av_log(s, AV_LOG_ERROR,
377
                           "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
378
                           tagbuf, par->codec_tag, par->codec_id, tagbuf2);
379 380 381 382
                    ret = AVERROR_INVALIDDATA;
                    goto fail;
                }
            } else
383
                par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
384 385
        }

386
        if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
387
            s->internal->nb_interleaved_streams++;
388 389
    }

390 391
    if (!s->priv_data && of->priv_data_size > 0) {
        s->priv_data = av_mallocz(of->priv_data_size);
392 393 394 395
        if (!s->priv_data) {
            ret = AVERROR(ENOMEM);
            goto fail;
        }
396 397
        if (of->priv_class) {
            *(const AVClass **)s->priv_data = of->priv_class;
398
            av_opt_set_defaults(s->priv_data);
399
            if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
400 401 402 403 404
                goto fail;
        }
    }

    /* set muxer identification string */
405
    if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
406
        av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
407 408
    } else {
        av_dict_set(&s->metadata, "encoder", NULL, 0);
409 410
    }

411 412 413 414
    for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
        av_dict_set(&s->metadata, e->key, NULL, 0);
    }

415 416 417
    if (options) {
         av_dict_free(options);
         *options = tmp;
418 419
    }

420 421 422 423 424 425 426
    if (s->oformat->init) {
        if ((ret = s->oformat->init(s)) < 0) {
            if (s->oformat->deinit)
                s->oformat->deinit(s);
            return ret;
        }
        return ret == 0;
427 428
    }

429 430 431 432 433 434 435 436 437 438 439 440
    return 0;

fail:
    av_dict_free(&tmp);
    return ret;
}

static int init_pts(AVFormatContext *s)
{
    int i;
    AVStream *st;

441 442 443 444 445
    /* init PTS generation */
    for (i = 0; i < s->nb_streams; i++) {
        int64_t den = AV_NOPTS_VALUE;
        st = s->streams[i];

446
        switch (st->codecpar->codec_type) {
447
        case AVMEDIA_TYPE_AUDIO:
448
            den = (int64_t)st->time_base.num * st->codecpar->sample_rate;
449 450
            break;
        case AVMEDIA_TYPE_VIDEO:
451
            den = (int64_t)st->time_base.num * st->time_base.den;
452 453 454 455
            break;
        default:
            break;
        }
456 457 458 459 460 461

        if (!st->priv_pts)
            st->priv_pts = av_mallocz(sizeof(*st->priv_pts));
        if (!st->priv_pts)
            return AVERROR(ENOMEM);

462
        if (den != AV_NOPTS_VALUE) {
463 464 465
            if (den <= 0)
                return AVERROR_INVALIDDATA;

466
            frac_init(st->priv_pts, 0, 0, den);
467 468 469
        }
    }

470 471 472
    return 0;
}

473 474
static int write_header_internal(AVFormatContext *s)
{
475 476
    if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
        avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
477 478 479 480
    if (s->oformat->write_header) {
        int ret = s->oformat->write_header(s);
        if (ret >= 0 && s->pb && s->pb->error < 0)
            ret = s->pb->error;
481
        s->internal->write_header_ret = ret;
482 483 484 485 486 487
        if (ret < 0)
            return ret;
        if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
            avio_flush(s->pb);
    }
    s->internal->header_written = 1;
488 489
    if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
        avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
490 491 492
    return 0;
}

493
int avformat_init_output(AVFormatContext *s, AVDictionary **options)
494 495 496
{
    int ret = 0;

497
    if ((ret = init_muxer(s, options)) < 0)
498 499
        return ret;

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
    s->internal->initialized = 1;
    s->internal->streams_initialized = ret;

    if (s->oformat->init && ret) {
        if ((ret = init_pts(s)) < 0)
            return ret;

        if (s->avoid_negative_ts < 0) {
            av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
            if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
                s->avoid_negative_ts = 0;
            } else
                s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
        }

        return AVSTREAM_INIT_IN_INIT_OUTPUT;
    }

    return AVSTREAM_INIT_IN_WRITE_HEADER;
}

int avformat_write_header(AVFormatContext *s, AVDictionary **options)
{
    int ret = 0;
    int already_initialized = s->internal->initialized;
    int streams_already_initialized = s->internal->streams_initialized;

    if (!already_initialized)
        if ((ret = avformat_init_output(s, options)) < 0)
            return ret;

531
    if (!(s->oformat->check_bitstream && s->flags & AVFMT_FLAG_AUTO_BSF)) {
532
        ret = write_header_internal(s);
533
        if (ret < 0)
534
            goto fail;
535
    }
536

537 538 539
    if (!s->internal->streams_initialized) {
        if ((ret = init_pts(s)) < 0)
            goto fail;
540

541 542 543 544 545 546 547
        if (s->avoid_negative_ts < 0) {
            av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
            if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
                s->avoid_negative_ts = 0;
            } else
                s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
        }
548 549
    }

550
    return streams_already_initialized;
551 552 553 554 555

fail:
    if (s->oformat->deinit)
        s->oformat->deinit(s);
    return ret;
556 557
}

558 559 560 561 562 563 564 565 566
#define AV_PKT_FLAG_UNCODED_FRAME 0x2000

/* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
   it is only being used internally to this file as a consistency check.
   The value is chosen to be very unlikely to appear on its own and to cause
   immediate failure if used anywhere as a real size. */
#define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))


567
#if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
568
FF_DISABLE_DEPRECATION_WARNINGS
569
//FIXME merge with compute_pkt_fields
570
static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
571
{
572
    int delay = FFMAX(st->codecpar->video_delay, st->internal->avctx->max_b_frames > 0);
573
    int num, den, i;
574
    int frame_size;
575

576 577
    if (!s->internal->missing_ts_warning &&
        !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
578
        (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) || (st->disposition & AV_DISPOSITION_TIMED_THUMBNAILS)) &&
579 580 581 582 583 584 585 586
        (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
        av_log(s, AV_LOG_WARNING,
               "Timestamps are unset in a packet for stream %d. "
               "This is deprecated and will stop working in the future. "
               "Fix your code to set the timestamps properly\n", st->index);
        s->internal->missing_ts_warning = 1;
    }

587
    if (s->debug & FF_FDEBUG_TS)
588
        av_log(s, AV_LOG_TRACE, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
589
            av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
590

591
    if (pkt->duration < 0 && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
592
        av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
593 594 595 596
               pkt->duration, pkt->stream_index);
        pkt->duration = 0;
    }

597 598
    /* duration field */
    if (pkt->duration == 0) {
599
        ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
600 601 602 603 604 605 606 607 608 609
        if (den && num) {
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
        }
    }

    if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
        pkt->pts = pkt->dts;

    //XXX/FIXME this is a temporary hack until all encoders output pts
    if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
610 611 612 613 614
        static int warned;
        if (!warned) {
            av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
            warned = 1;
        }
615 616
        pkt->dts =
//        pkt->pts= st->cur_dts;
617
            pkt->pts = st->priv_pts->val;
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    }

    //calculate dts from pts
    if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
        st->pts_buffer[0] = pkt->pts;
        for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
            st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
        for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);

        pkt->dts = st->pts_buffer[0];
    }

    if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
        ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
633 634
          st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE &&
          st->codecpar->codec_type != AVMEDIA_TYPE_DATA &&
635 636
          st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
        av_log(s, AV_LOG_ERROR,
637 638
               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
               st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
639 640 641
        return AVERROR(EINVAL);
    }
    if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
642
        av_log(s, AV_LOG_ERROR,
643 644
               "pts (%s) < dts (%s) in stream %d\n",
               av_ts2str(pkt->pts), av_ts2str(pkt->dts),
645
               st->index);
646 647 648
        return AVERROR(EINVAL);
    }

649 650
    if (s->debug & FF_FDEBUG_TS)
        av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%s dts2:%s\n",
651
            av_ts2str(pkt->pts), av_ts2str(pkt->dts));
652

653
    st->cur_dts = pkt->dts;
654
    st->priv_pts->val = pkt->dts;
655 656

    /* update pts */
657
    switch (st->codecpar->codec_type) {
658
    case AVMEDIA_TYPE_AUDIO:
659 660
        frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
                     ((AVFrame *)pkt->data)->nb_samples :
661
                     av_get_audio_frame_duration(st->codec, pkt->size);
662 663 664 665

        /* HACK/FIXME, we skip the initial 0 size packets as they are most
         * likely equal to the encoder delay, but it would be better if we
         * had the real timestamps from the encoder */
666 667
        if (frame_size >= 0 && (pkt->size || st->priv_pts->num != st->priv_pts->den >> 1 || st->priv_pts->val)) {
            frac_add(st->priv_pts, (int64_t)st->time_base.den * frame_size);
668 669 670
        }
        break;
    case AVMEDIA_TYPE_VIDEO:
671
        frac_add(st->priv_pts, (int64_t)st->time_base.den * st->time_base.num);
672 673 674 675
        break;
    }
    return 0;
}
676
FF_ENABLE_DEPRECATION_WARNINGS
677
#endif
678

679
/**
680 681 682
 * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
 * sidedata.
 *
683 684 685 686
 * FIXME: this function should NEVER get undefined pts/dts beside when the
 * AVFMT_NOTIMESTAMPS is set.
 * Those additional safety checks should be dropped once the correct checks
 * are set in the callers.
687
 */
688
static int write_packet(AVFormatContext *s, AVPacket *pkt)
689
{
690
    int ret, did_split;
691 692 693 694
    int64_t pts_backup, dts_backup;

    pts_backup = pkt->pts;
    dts_backup = pkt->dts;
695

696 697
    // If the timestamp offsetting below is adjusted, adjust
    // ff_interleaved_peek similarly.
698 699 700 701 702 703 704 705 706 707
    if (s->output_ts_offset) {
        AVStream *st = s->streams[pkt->stream_index];
        int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);

        if (pkt->dts != AV_NOPTS_VALUE)
            pkt->dts += offset;
        if (pkt->pts != AV_NOPTS_VALUE)
            pkt->pts += offset;
    }

708 709
    if (s->avoid_negative_ts > 0) {
        AVStream *st = s->streams[pkt->stream_index];
710
        int64_t offset = st->mux_ts_offset;
711
        int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
712

713 714 715
        if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
            (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
            s->internal->offset = -ts;
716
            s->internal->offset_timebase = st->time_base;
717
        }
718

719
        if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
720
            offset = st->mux_ts_offset =
721 722
                av_rescale_q_rnd(s->internal->offset,
                                 s->internal->offset_timebase,
723 724 725 726 727
                                 st->time_base,
                                 AV_ROUND_UP);
        }

        if (pkt->dts != AV_NOPTS_VALUE)
728
            pkt->dts += offset;
729
        if (pkt->pts != AV_NOPTS_VALUE)
730
            pkt->pts += offset;
731

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
        if (s->internal->avoid_negative_ts_use_pts) {
            if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
                av_log(s, AV_LOG_WARNING, "failed to avoid negative "
                    "pts %s in stream %d.\n"
                    "Try -avoid_negative_ts 1 as a possible workaround.\n",
                    av_ts2str(pkt->dts),
                    pkt->stream_index
                );
            }
        } else {
            av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
            if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
                av_log(s, AV_LOG_WARNING,
                    "Packets poorly interleaved, failed to avoid negative "
                    "timestamp %s in stream %d.\n"
                    "Try -max_interleave_delta 0 as a possible workaround.\n",
                    av_ts2str(pkt->dts),
                    pkt->stream_index
                );
            }
752
        }
753 754
    }

755 756
    did_split = av_packet_split_side_data(pkt);

757
    if (!s->internal->header_written) {
758
        ret = s->internal->write_header_ret ? s->internal->write_header_ret : write_header_internal(s);
759 760 761 762
        if (ret < 0)
            goto fail;
    }

763 764 765 766 767 768 769 770
    if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
        AVFrame *frame = (AVFrame *)pkt->data;
        av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
        ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
        av_frame_free(&frame);
    } else {
        ret = s->oformat->write_packet(s, pkt);
    }
771

772
    if (s->pb && ret >= 0) {
773
        if (s->flush_packets && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
774 775 776 777
            avio_flush(s->pb);
        if (s->pb->error < 0)
            ret = s->pb->error;
    }
778

779
fail:
780 781 782
    if (did_split)
        av_packet_merge_side_data(pkt);

783 784 785 786 787
    if (ret < 0) {
        pkt->pts = pts_backup;
        pkt->dts = dts_backup;
    }

788 789 790
    return ret;
}

791 792 793 794 795 796 797 798 799 800 801
static int check_packet(AVFormatContext *s, AVPacket *pkt)
{
    if (!pkt)
        return 0;

    if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
        av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
               pkt->stream_index);
        return AVERROR(EINVAL);
    }

802
    if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
803 804 805 806 807 808 809
        av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
        return AVERROR(EINVAL);
    }

    return 0;
}

810
static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
811 812 813
{
    int ret;

814 815 816 817
    ret = check_packet(s, pkt);
    if (ret < 0)
        return ret;

818
#if !FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    /* sanitize the timestamps */
    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
        AVStream *st = s->streams[pkt->stream_index];

        /* when there is no reordering (so dts is equal to pts), but
         * only one of them is set, set the other as well */
        if (!st->internal->reorder) {
            if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
                pkt->pts = pkt->dts;
            if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
                pkt->dts = pkt->pts;
        }

        /* check that the timestamps are set */
        if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
            av_log(s, AV_LOG_ERROR,
                   "Timestamps are unset in a packet for stream %d\n", st->index);
            return AVERROR(EINVAL);
        }

        /* check that the dts are increasing (or at least non-decreasing,
         * if the format allows it */
        if (st->cur_dts != AV_NOPTS_VALUE &&
            ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
             st->cur_dts > pkt->dts)) {
            av_log(s, AV_LOG_ERROR,
                   "Application provided invalid, non monotonically increasing "
                   "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
                   st->index, st->cur_dts, pkt->dts);
            return AVERROR(EINVAL);
        }

        if (pkt->pts < pkt->dts) {
            av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
                   pkt->pts, pkt->dts, st->index);
            return AVERROR(EINVAL);
        }
    }
#endif

    return 0;
}

862 863 864 865
static int do_packet_auto_bsf(AVFormatContext *s, AVPacket *pkt) {
    AVStream *st = s->streams[pkt->stream_index];
    int i, ret;

866 867 868
    if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
        return 1;

869 870 871 872 873 874 875 876 877
    if (s->oformat->check_bitstream) {
        if (!st->internal->bitstream_checked) {
            if ((ret = s->oformat->check_bitstream(s, pkt)) < 0)
                return ret;
            else if (ret == 1)
                st->internal->bitstream_checked = 1;
        }
    }

878 879 880
    if (st->internal->nb_bsfcs)
        av_packet_split_side_data(pkt);

881 882 883 884 885 886 887 888 889 890 891 892 893
    for (i = 0; i < st->internal->nb_bsfcs; i++) {
        AVBSFContext *ctx = st->internal->bsfcs[i];
        if (i > 0) {
            AVBSFContext* prev_ctx = st->internal->bsfcs[i - 1];
            if (prev_ctx->par_out->extradata_size != ctx->par_in->extradata_size) {
                if ((ret = avcodec_parameters_copy(ctx->par_in, prev_ctx->par_out)) < 0)
                    return ret;
            }
        }
        // TODO: when any bitstream filter requires flushing at EOF, we'll need to
        // flush each stream's BSF chain on write_trailer.
        if ((ret = av_bsf_send_packet(ctx, pkt)) < 0) {
            av_log(ctx, AV_LOG_ERROR,
894
                    "Failed to send packet to filter %s for stream %d\n",
895 896 897 898 899 900 901 902 903 904
                    ctx->filter->name, pkt->stream_index);
            return ret;
        }
        // TODO: when any automatically-added bitstream filter is generating multiple
        // output packets for a single input one, we'll need to call this in a loop
        // and write each output packet.
        if ((ret = av_bsf_receive_packet(ctx, pkt)) < 0) {
            if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                return 0;
            av_log(ctx, AV_LOG_ERROR,
905
                    "Failed to send packet to filter %s for stream %d\n",
906 907 908 909 910 911 912 913 914 915 916 917 918
                    ctx->filter->name, pkt->stream_index);
            return ret;
        }
        if (i == st->internal->nb_bsfcs - 1) {
            if (ctx->par_out->extradata_size != st->codecpar->extradata_size) {
                if ((ret = avcodec_parameters_copy(st->codecpar, ctx->par_out)) < 0)
                    return ret;
            }
        }
    }
    return 1;
}

919 920
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
{
921
    int ret;
922 923 924 925 926

    ret = prepare_input_packet(s, pkt);
    if (ret < 0)
        return ret;

927
    if (!pkt) {
928
        if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
929 930 931 932 933
            if (!s->internal->header_written) {
                ret = s->internal->write_header_ret ? s->internal->write_header_ret : write_header_internal(s);
                if (ret < 0)
                    return ret;
            }
934
            ret = s->oformat->write_packet(s, NULL);
935
            if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
936
                avio_flush(s->pb);
937 938 939 940
            if (ret >= 0 && s->pb && s->pb->error < 0)
                ret = s->pb->error;
            return ret;
        }
941
        return 1;
942
    }
943

944 945 946 947
    ret = do_packet_auto_bsf(s, pkt);
    if (ret <= 0)
        return ret;

948
#if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
949
    ret = compute_muxer_pkt_fields(s, s->streams[pkt->stream_index], pkt);
950 951 952

    if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
        return ret;
953
#endif
954

955
    ret = write_packet(s, pkt);
956 957
    if (ret >= 0 && s->pb && s->pb->error < 0)
        ret = s->pb->error;
958 959 960 961 962 963

    if (ret >= 0)
        s->streams[pkt->stream_index]->nb_frames++;
    return ret;
}

964 965 966
#define CHUNK_START 0x1000

int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
967
                             int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
968
{
969
    int ret;
970
    AVPacketList **next_point, *this_pktl;
971 972
    AVStream *st   = s->streams[pkt->stream_index];
    int chunked    = s->max_chunk_size || s->max_chunk_duration;
973 974

    this_pktl      = av_mallocz(sizeof(AVPacketList));
975 976
    if (!this_pktl)
        return AVERROR(ENOMEM);
977 978 979
    if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
        av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
        av_assert0(((AVFrame *)pkt->data)->buf);
980 981 982 983 984 985 986 987 988
        this_pktl->pkt = *pkt;
        pkt->buf = NULL;
        pkt->side_data = NULL;
        pkt->side_data_elems = 0;
    } else {
        if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
            av_free(this_pktl);
            return ret;
        }
989
    }
990 991

    if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
992 993
        next_point = &(st->last_in_packet_buffer->next);
    } else {
994
        next_point = &s->internal->packet_buffer;
995
    }
996

997 998
    if (chunked) {
        uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
999 1000
        st->interleaver_chunk_size     += pkt->size;
        st->interleaver_chunk_duration += pkt->duration;
1001 1002
        if (   (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
            || (max && st->interleaver_chunk_duration           > max)) {
1003
            st->interleaver_chunk_size      = 0;
1004
            this_pktl->pkt.flags |= CHUNK_START;
1005
            if (max && st->interleaver_chunk_duration > max) {
1006
                int64_t syncoffset = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
1007 1008 1009 1010 1011
                int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;

                st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
            } else
                st->interleaver_chunk_duration = 0;
1012
        }
1013 1014 1015 1016
    }
    if (*next_point) {
        if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
            goto next_non_null;
1017

1018
        if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
1019 1020 1021
            while (   *next_point
                   && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
                       || !compare(s, &(*next_point)->pkt, pkt)))
1022
                next_point = &(*next_point)->next;
1023 1024
            if (*next_point)
                goto next_non_null;
1025
        } else {
1026
            next_point = &(s->internal->packet_buffer_end->next);
1027 1028
        }
    }
1029
    av_assert1(!*next_point);
1030

1031
    s->internal->packet_buffer_end = this_pktl;
1032 1033 1034 1035 1036 1037
next_non_null:

    this_pktl->next = *next_point;

    s->streams[pkt->stream_index]->last_in_packet_buffer =
        *next_point                                      = this_pktl;
1038

1039 1040
    av_packet_unref(pkt);

1041
    return 0;
1042 1043
}

1044 1045
static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
                                  AVPacket *pkt)
1046 1047 1048 1049 1050
{
    AVStream *st  = s->streams[pkt->stream_index];
    AVStream *st2 = s->streams[next->stream_index];
    int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
                                  st->time_base);
1051 1052 1053
    if (s->audio_preload && ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))) {
        int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codecpar->codec_type == AVMEDIA_TYPE_AUDIO);
        int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO);
1054
        if (ts == ts2) {
1055 1056
            ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
               -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
1057 1058 1059 1060
            ts2=0;
        }
        comp= (ts>ts2) - (ts<ts2);
    }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

    if (comp == 0)
        return pkt->stream_index < next->stream_index;
    return comp > 0;
}

int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
                                 AVPacket *pkt, int flush)
{
    AVPacketList *pktl;
    int stream_count = 0;
1072
    int noninterleaved_count = 0;
1073
    int i, ret;
1074
    int eof = flush;
1075 1076

    if (pkt) {
1077
        if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
1078
            return ret;
1079 1080
    }

1081 1082 1083
    for (i = 0; i < s->nb_streams; i++) {
        if (s->streams[i]->last_in_packet_buffer) {
            ++stream_count;
1084 1085 1086
        } else if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
                   s->streams[i]->codecpar->codec_id != AV_CODEC_ID_VP8 &&
                   s->streams[i]->codecpar->codec_id != AV_CODEC_ID_VP9) {
1087 1088 1089
            ++noninterleaved_count;
        }
    }
1090

1091
    if (s->internal->nb_interleaved_streams == stream_count)
1092
        flush = 1;
1093

1094
    if (s->max_interleave_delta > 0 &&
1095
        s->internal->packet_buffer &&
1096 1097 1098
        !flush &&
        s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
    ) {
1099
        AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        int64_t delta_dts = INT64_MIN;
        int64_t top_dts = av_rescale_q(top_pkt->dts,
                                       s->streams[top_pkt->stream_index]->time_base,
                                       AV_TIME_BASE_Q);

        for (i = 0; i < s->nb_streams; i++) {
            int64_t last_dts;
            const AVPacketList *last = s->streams[i]->last_in_packet_buffer;

            if (!last)
                continue;

            last_dts = av_rescale_q(last->pkt.dts,
                                    s->streams[i]->time_base,
                                    AV_TIME_BASE_Q);
            delta_dts = FFMAX(delta_dts, last_dts - top_dts);
1116
        }
1117 1118 1119 1120 1121 1122

        if (delta_dts > s->max_interleave_delta) {
            av_log(s, AV_LOG_DEBUG,
                   "Delay between the first packet and last packet in the "
                   "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
                   delta_dts, s->max_interleave_delta);
1123 1124 1125
            flush = 1;
        }
    }
1126

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    if (s->internal->packet_buffer &&
        eof &&
        (s->flags & AVFMT_FLAG_SHORTEST) &&
        s->internal->shortest_end == AV_NOPTS_VALUE) {
        AVPacket *top_pkt = &s->internal->packet_buffer->pkt;

        s->internal->shortest_end = av_rescale_q(top_pkt->dts,
                                       s->streams[top_pkt->stream_index]->time_base,
                                       AV_TIME_BASE_Q);
    }

    if (s->internal->shortest_end != AV_NOPTS_VALUE) {
        while (s->internal->packet_buffer) {
            AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
            AVStream *st;
            int64_t top_dts = av_rescale_q(top_pkt->dts,
                                        s->streams[top_pkt->stream_index]->time_base,
                                        AV_TIME_BASE_Q);

            if (s->internal->shortest_end + 1 >= top_dts)
                break;

            pktl = s->internal->packet_buffer;
            st   = s->streams[pktl->pkt.stream_index];

            s->internal->packet_buffer = pktl->next;
            if (!s->internal->packet_buffer)
                s->internal->packet_buffer_end = NULL;

            if (st->last_in_packet_buffer == pktl)
                st->last_in_packet_buffer = NULL;

            av_packet_unref(&pktl->pkt);
            av_freep(&pktl);
            flush = 0;
        }
    }

1165 1166
    if (stream_count && flush) {
        AVStream *st;
1167
        pktl = s->internal->packet_buffer;
1168
        *out = pktl->pkt;
1169
        st   = s->streams[out->stream_index];
1170

1171 1172 1173
        s->internal->packet_buffer = pktl->next;
        if (!s->internal->packet_buffer)
            s->internal->packet_buffer_end = NULL;
1174

1175 1176
        if (st->last_in_packet_buffer == pktl)
            st->last_in_packet_buffer = NULL;
1177
        av_freep(&pktl);
1178

1179 1180 1181 1182 1183 1184 1185
        return 1;
    } else {
        av_init_packet(out);
        return 0;
    }
}

1186 1187
int ff_interleaved_peek(AVFormatContext *s, int stream,
                        AVPacket *pkt, int add_offset)
1188 1189 1190
{
    AVPacketList *pktl = s->internal->packet_buffer;
    while (pktl) {
1191
        if (pktl->pkt.stream_index == stream) {
1192
            *pkt = pktl->pkt;
1193 1194 1195 1196 1197 1198 1199
            if (add_offset) {
                AVStream *st = s->streams[pkt->stream_index];
                int64_t offset = st->mux_ts_offset;

                if (s->output_ts_offset)
                    offset += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);

1200 1201 1202 1203 1204 1205
                if (pkt->dts != AV_NOPTS_VALUE)
                    pkt->dts += offset;
                if (pkt->pts != AV_NOPTS_VALUE)
                    pkt->pts += offset;
            }
            return 0;
1206
        }
1207 1208
        pktl = pktl->next;
    }
1209
    return AVERROR(ENOENT);
1210 1211
}

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
/**
 * Interleave an AVPacket correctly so it can be muxed.
 * @param out the interleaved packet will be output here
 * @param in the input packet
 * @param flush 1 if no further packets are available as input and all
 *              remaining packets should be output
 * @return 1 if a packet was output, 0 if no packet could be output,
 *         < 0 if an error occurred
 */
static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
{
    if (s->oformat->interleave_packet) {
        int ret = s->oformat->interleave_packet(s, out, in, flush);
        if (in)
1226
            av_packet_unref(in);
1227 1228 1229 1230 1231 1232 1233
        return ret;
    } else
        return ff_interleave_packet_per_dts(s, out, in, flush);
}

int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
{
1234
    int ret, flush = 0;
1235

1236
    ret = prepare_input_packet(s, pkt);
1237
    if (ret < 0)
1238
        goto fail;
1239

1240 1241 1242
    if (pkt) {
        AVStream *st = s->streams[pkt->stream_index];

1243 1244 1245 1246 1247
        ret = do_packet_auto_bsf(s, pkt);
        if (ret == 0)
            return 0;
        else if (ret < 0)
            goto fail;
1248

1249 1250
        if (s->debug & FF_FDEBUG_TS)
            av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
1251
                pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
1252

1253
#if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
1254
        if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
1255
            goto fail;
1256
#endif
1257

1258 1259 1260 1261
        if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
            ret = AVERROR(EINVAL);
            goto fail;
        }
1262
    } else {
1263
        av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
1264 1265 1266 1267 1268 1269
        flush = 1;
    }

    for (;; ) {
        AVPacket opkt;
        int ret = interleave_packet(s, &opkt, pkt, flush);
1270 1271 1272 1273 1274
        if (pkt) {
            memset(pkt, 0, sizeof(*pkt));
            av_init_packet(pkt);
            pkt = NULL;
        }
1275 1276 1277
        if (ret <= 0) //FIXME cleanup needed for ret<0 ?
            return ret;

1278
        ret = write_packet(s, &opkt);
1279 1280 1281
        if (ret >= 0)
            s->streams[opkt.stream_index]->nb_frames++;

1282
        av_packet_unref(&opkt);
1283 1284 1285

        if (ret < 0)
            return ret;
1286 1287
        if(s->pb && s->pb->error)
            return s->pb->error;
1288
    }
1289 1290 1291
fail:
    av_packet_unref(pkt);
    return ret;
1292 1293 1294 1295 1296 1297 1298 1299 1300
}

int av_write_trailer(AVFormatContext *s)
{
    int ret, i;

    for (;; ) {
        AVPacket pkt;
        ret = interleave_packet(s, &pkt, NULL, 1);
1301
        if (ret < 0)
1302 1303 1304 1305
            goto fail;
        if (!ret)
            break;

1306
        ret = write_packet(s, &pkt);
1307 1308 1309
        if (ret >= 0)
            s->streams[pkt.stream_index]->nb_frames++;

1310
        av_packet_unref(&pkt);
1311 1312 1313

        if (ret < 0)
            goto fail;
1314 1315
        if(s->pb && s->pb->error)
            goto fail;
1316 1317
    }

1318
    if (!s->internal->header_written) {
1319
        ret = s->internal->write_header_ret ? s->internal->write_header_ret : write_header_internal(s);
1320 1321 1322 1323
        if (ret < 0)
            goto fail;
    }

1324
fail:
1325 1326 1327
    if (s->internal->header_written && s->oformat->write_trailer) {
        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
            avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
1328
        if (ret >= 0) {
1329
        ret = s->oformat->write_trailer(s);
1330 1331 1332
        } else {
            s->oformat->write_trailer(s);
        }
1333
    }
1334

1335 1336 1337
    if (s->oformat->deinit)
        s->oformat->deinit(s);

1338 1339 1340 1341
    s->internal->header_written =
    s->internal->initialized =
    s->internal->streams_initialized = 0;

1342 1343 1344 1345
    if (s->pb)
       avio_flush(s->pb);
    if (ret == 0)
       ret = s->pb ? s->pb->error : 0;
1346 1347 1348 1349 1350 1351 1352 1353 1354
    for (i = 0; i < s->nb_streams; i++) {
        av_freep(&s->streams[i]->priv_data);
        av_freep(&s->streams[i]->index_entries);
    }
    if (s->oformat->priv_class)
        av_opt_free(s->priv_data);
    av_freep(&s->priv_data);
    return ret;
}
1355 1356 1357 1358 1359 1360 1361 1362

int av_get_output_timestamp(struct AVFormatContext *s, int stream,
                            int64_t *dts, int64_t *wall)
{
    if (!s->oformat || !s->oformat->get_output_timestamp)
        return AVERROR(ENOSYS);
    s->oformat->get_output_timestamp(s, stream, dts, wall);
    return 0;
1363
}
1364

1365
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
1366
                     AVFormatContext *src, int interleave)
1367 1368
{
    AVPacket local_pkt;
1369
    int ret;
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380

    local_pkt = *pkt;
    local_pkt.stream_index = dst_stream;
    if (pkt->pts != AV_NOPTS_VALUE)
        local_pkt.pts = av_rescale_q(pkt->pts,
                                     src->streams[pkt->stream_index]->time_base,
                                     dst->streams[dst_stream]->time_base);
    if (pkt->dts != AV_NOPTS_VALUE)
        local_pkt.dts = av_rescale_q(pkt->dts,
                                     src->streams[pkt->stream_index]->time_base,
                                     dst->streams[dst_stream]->time_base);
1381 1382 1383 1384
    if (pkt->duration)
        local_pkt.duration = av_rescale_q(pkt->duration,
                                          src->streams[pkt->stream_index]->time_base,
                                          dst->streams[dst_stream]->time_base);
1385

1386 1387
    if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
    else            ret = av_write_frame(dst, &local_pkt);
1388
    pkt->buf = local_pkt.buf;
1389 1390
    pkt->side_data       = local_pkt.side_data;
    pkt->side_data_elems = local_pkt.side_data_elems;
1391
    return ret;
1392
}
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440

static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
                                           AVFrame *frame, int interleaved)
{
    AVPacket pkt, *pktp;

    av_assert0(s->oformat);
    if (!s->oformat->write_uncoded_frame)
        return AVERROR(ENOSYS);

    if (!frame) {
        pktp = NULL;
    } else {
        pktp = &pkt;
        av_init_packet(&pkt);
        pkt.data = (void *)frame;
        pkt.size         = UNCODED_FRAME_PACKET_SIZE;
        pkt.pts          =
        pkt.dts          = frame->pts;
        pkt.duration     = av_frame_get_pkt_duration(frame);
        pkt.stream_index = stream_index;
        pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
    }

    return interleaved ? av_interleaved_write_frame(s, pktp) :
                         av_write_frame(s, pktp);
}

int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
                           AVFrame *frame)
{
    return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
}

int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
                                       AVFrame *frame)
{
    return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
}

int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
{
    av_assert0(s->oformat);
    if (!s->oformat->write_uncoded_frame)
        return AVERROR(ENOSYS);
    return s->oformat->write_uncoded_frame(s, stream_index, NULL,
                                           AV_WRITE_UNCODED_FRAME_QUERY);
}