libavformat/mux.c
55f9037f
 /*
513042c9
  * muxing functions for use within FFmpeg
55f9037f
  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  *
513042c9
  * This file is part of FFmpeg.
55f9037f
  *
513042c9
  * FFmpeg is free software; you can redistribute it and/or
55f9037f
  * 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.
  *
513042c9
  * FFmpeg is distributed in the hope that it will be useful,
55f9037f
  * 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
513042c9
  * License along with FFmpeg; if not, write to the Free Software
55f9037f
  * 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"
513042c9
 #include "libavutil/timestamp.h"
55f9037f
 #include "metadata.h"
 #include "id3v2.h"
 #include "libavutil/avassert.h"
 #include "libavutil/avstring.h"
7950e519
 #include "libavutil/internal.h"
55f9037f
 #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
513042c9
  * muxing functions for use within libavformat
55f9037f
  */
 
 /* 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
  */
b4d68e7c
 static void frac_init(FFFrac *f, int64_t val, int64_t num, int64_t den)
55f9037f
 {
     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
  */
b4d68e7c
 static void frac_add(FFFrac *f, int64_t incr)
55f9037f
 {
     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;
 }
 
8cbf0827
 AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precision)
de707bc8
 {
     AVRational q;
     int j;
 
1d54f510
     q = st->time_base;
 
5e6439a1
     for (j=2; j<14; j+= 1+(j>2))
8cbf0827
         while (q.den / q.num < min_precision && q.num % j == 0)
de707bc8
             q.num /= j;
8cbf0827
     while (q.den / q.num < min_precision && q.den < (1<<24))
de707bc8
         q.den <<= 1;
 
     return q;
 }
 
a45cf639
 enum AVChromaLocation ff_choose_chroma_location(AVFormatContext *s, AVStream *st)
 {
6f69f7a8
     AVCodecParameters *par = st->codecpar;
     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(par->format);
a45cf639
 
6f69f7a8
     if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED)
         return par->chroma_location;
a45cf639
 
     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) {
6f69f7a8
             if (par->field_order == AV_FIELD_UNKNOWN || par->field_order == AV_FIELD_PROGRESSIVE) {
                 switch (par->codec_id) {
a45cf639
                 case AV_CODEC_ID_MJPEG:
                 case AV_CODEC_ID_MPEG1VIDEO: return AVCHROMA_LOC_CENTER;
                 }
             }
6f69f7a8
             if (par->field_order == AV_FIELD_UNKNOWN || par->field_order != AV_FIELD_PROGRESSIVE) {
                 switch (par->codec_id) {
a45cf639
                 case AV_CODEC_ID_MPEG2VIDEO: return AVCHROMA_LOC_LEFT;
                 }
             }
         }
     }
 
     return AVCHROMA_LOC_UNSPECIFIED;
 
 }
 
513042c9
 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;
 }
 
55f9037f
 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
 {
     const AVCodecTag *avctag;
     int n;
     enum AVCodecID id = AV_CODEC_ID_NONE;
e9a26dc5
     int64_t tag  = -1;
55f9037f
 
     /**
      * 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) {
9200514a
             if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codecpar->codec_tag)) {
55f9037f
                 id = avctag->id;
9200514a
                 if (id == st->codecpar->codec_id)
55f9037f
                     return 1;
             }
9200514a
             if (avctag->id == st->codecpar->codec_id)
55f9037f
                 tag = avctag->tag;
             avctag++;
         }
     }
     if (id != AV_CODEC_ID_NONE)
         return 0;
042eba52
     if (tag >= 0 && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
55f9037f
         return 0;
     return 1;
 }
 
1e46c63e
 
 static int init_muxer(AVFormatContext *s, AVDictionary **options)
55f9037f
 {
     int ret = 0, i;
     AVStream *st;
     AVDictionary *tmp = NULL;
9200514a
     AVCodecParameters *par = NULL;
86bbdf86
     AVOutputFormat *of = s->oformat;
8de1ee9f
     const AVCodecDescriptor *desc;
9893e883
     AVDictionaryEntry *e;
55f9037f
 
     if (options)
         av_dict_copy(&tmp, *options, 0);
86bbdf86
 
55f9037f
     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
         goto fail;
513042c9
     if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
c9a12fdd
         (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
513042c9
         goto fail;
55f9037f
 
6f69f7a8
 #if FF_API_LAVF_AVCTX
9200514a
 FF_DISABLE_DEPRECATION_WARNINGS
c34363ac
     if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT) {
         if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
             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");
         }
     }
9200514a
 FF_ENABLE_DEPRECATION_WARNINGS
0c1959b0
 #endif
 
55f9037f
     // some sanity checks
86bbdf86
     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
d37d4b6e
         av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
55f9037f
         ret = AVERROR(EINVAL);
         goto fail;
     }
 
     for (i = 0; i < s->nb_streams; i++) {
9200514a
         st  = s->streams[i];
         par = st->codecpar;
55f9037f
 
9200514a
 #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;
194be1f4
         }
 FF_ENABLE_DEPRECATION_WARNINGS
 #endif
 
         if (!st->time_base.num) {
             /* fall back on the default timebase values */
9200514a
             if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
                 avpriv_set_pts_info(st, 64, 1, par->sample_rate);
194be1f4
             else
                 avpriv_set_pts_info(st, 33, 1, 90000);
         }
 
9200514a
         switch (par->codec_type) {
55f9037f
         case AVMEDIA_TYPE_AUDIO:
9200514a
             if (par->sample_rate <= 0) {
55f9037f
                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
                 ret = AVERROR(EINVAL);
                 goto fail;
             }
9200514a
             if (!par->block_align)
                 par->block_align = par->channels *
                                    av_get_bits_per_sample(par->codec_id) >> 3;
55f9037f
             break;
         case AVMEDIA_TYPE_VIDEO:
9200514a
             if ((par->width <= 0 || par->height <= 0) &&
86bbdf86
                 !(of->flags & AVFMT_NODIMENSIONS)) {
55f9037f
                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
                 ret = AVERROR(EINVAL);
                 goto fail;
             }
6f69f7a8
             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)
513042c9
             ) {
e21307a2
                 if (st->sample_aspect_ratio.num != 0 &&
                     st->sample_aspect_ratio.den != 0 &&
6f69f7a8
                     par->sample_aspect_ratio.num != 0 &&
9200514a
                     par->sample_aspect_ratio.den != 0) {
e21307a2
                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
f48366c7
                            "(%d/%d) and encoder layer (%d/%d)\n",
                            st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
6f69f7a8
                            par->sample_aspect_ratio.num,
                            par->sample_aspect_ratio.den);
e21307a2
                     ret = AVERROR(EINVAL);
                     goto fail;
                 }
55f9037f
             }
             break;
         }
 
9200514a
         desc = avcodec_descriptor_get(par->codec_id);
8de1ee9f
         if (desc && desc->props & AV_CODEC_PROP_REORDER)
             st->internal->reorder = 1;
 
86bbdf86
         if (of->codec_tag) {
6f69f7a8
             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', ' '))
6cbbf4a2
                 && !validate_codec_tag(s, st)) {
86bbdf86
                 // the current rawvideo encoding system ends up setting
6cbbf4a2
                 // the wrong codec_tag for avi/mov, we override it here
9200514a
                 par->codec_tag = 0;
55f9037f
             }
9200514a
             if (par->codec_tag) {
55f9037f
                 if (!validate_codec_tag(s, st)) {
cd4d6cba
                     const uint32_t otag = av_codec_get_tag(s->oformat->codec_tag, par->codec_id);
55f9037f
                     av_log(s, AV_LOG_ERROR,
54904525
                            "Tag %s incompatible with output codec id '%d' (%s)\n",
                            av_fourcc2str(par->codec_tag), par->codec_id, av_fourcc2str(otag));
55f9037f
                     ret = AVERROR_INVALIDDATA;
                     goto fail;
                 }
             } else
9200514a
                 par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
55f9037f
         }
 
9200514a
         if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
33c859c1
             s->internal->nb_interleaved_streams++;
55f9037f
     }
 
86bbdf86
     if (!s->priv_data && of->priv_data_size > 0) {
         s->priv_data = av_mallocz(of->priv_data_size);
55f9037f
         if (!s->priv_data) {
             ret = AVERROR(ENOMEM);
             goto fail;
         }
86bbdf86
         if (of->priv_class) {
             *(const AVClass **)s->priv_data = of->priv_class;
55f9037f
             av_opt_set_defaults(s->priv_data);
330d547e
             if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
55f9037f
                 goto fail;
         }
     }
 
     /* set muxer identification string */
0c1959b0
     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
55f9037f
         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
618bdb7f
     } else {
         av_dict_set(&s->metadata, "encoder", NULL, 0);
55f9037f
     }
 
9893e883
     for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
         av_dict_set(&s->metadata, e->key, NULL, 0);
     }
 
1e46c63e
     if (options) {
          av_dict_free(options);
          *options = tmp;
55f9037f
     }
 
a246fef1
     if (s->oformat->init) {
         if ((ret = s->oformat->init(s)) < 0) {
             if (s->oformat->deinit)
                 s->oformat->deinit(s);
             return ret;
         }
         return ret == 0;
1f9139b0
     }
 
1e46c63e
     return 0;
 
 fail:
     av_dict_free(&tmp);
     return ret;
 }
 
 static int init_pts(AVFormatContext *s)
 {
     int i;
     AVStream *st;
 
55f9037f
     /* init PTS generation */
     for (i = 0; i < s->nb_streams; i++) {
         int64_t den = AV_NOPTS_VALUE;
         st = s->streams[i];
 
6f69f7a8
         switch (st->codecpar->codec_type) {
55f9037f
         case AVMEDIA_TYPE_AUDIO:
6f69f7a8
             den = (int64_t)st->time_base.num * st->codecpar->sample_rate;
55f9037f
             break;
         case AVMEDIA_TYPE_VIDEO:
6f69f7a8
             den = (int64_t)st->time_base.num * st->time_base.den;
55f9037f
             break;
         default:
             break;
         }
b4d68e7c
 
cd1ff3e4
         if (!st->internal->priv_pts)
             st->internal->priv_pts = av_mallocz(sizeof(*st->internal->priv_pts));
         if (!st->internal->priv_pts)
b4d68e7c
             return AVERROR(ENOMEM);
 
55f9037f
         if (den != AV_NOPTS_VALUE) {
1e46c63e
             if (den <= 0)
                 return AVERROR_INVALIDDATA;
 
cd1ff3e4
             frac_init(st->internal->priv_pts, 0, 0, den);
55f9037f
         }
     }
 
1e46c63e
     return 0;
 }
 
eeeb595c
 static void flush_if_needed(AVFormatContext *s)
 {
     if (s->pb && s->pb->error >= 0) {
         if (s->flush_packets == 1 || s->flags & AVFMT_FLAG_FLUSH_PACKETS)
             avio_flush(s->pb);
         else if (s->flush_packets && !(s->oformat->flags & AVFMT_NOFILE))
             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
     }
 }
 
9da27fb5
 static int write_header_internal(AVFormatContext *s)
 {
db7968bf
     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
9da27fb5
     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;
517fe644
         s->internal->write_header_ret = ret;
9da27fb5
         if (ret < 0)
             return ret;
eeeb595c
         flush_if_needed(s);
9da27fb5
     }
     s->internal->header_written = 1;
db7968bf
     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
9da27fb5
     return 0;
 }
 
a246fef1
 int avformat_init_output(AVFormatContext *s, AVDictionary **options)
1e46c63e
 {
     int ret = 0;
 
da4ef13c
     if ((ret = init_muxer(s, options)) < 0)
1e46c63e
         return ret;
 
a246fef1
     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;
 
1f6d7eb4
     if (!(s->oformat->check_bitstream && s->flags & AVFMT_FLAG_AUTO_BSF)) {
9da27fb5
         ret = write_header_internal(s);
1e46c63e
         if (ret < 0)
301ead13
             goto fail;
55f9037f
     }
1e46c63e
 
a246fef1
     if (!s->internal->streams_initialized) {
         if ((ret = init_pts(s)) < 0)
             goto fail;
1e46c63e
 
a246fef1
         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;
         }
eba33396
     }
 
a246fef1
     return streams_already_initialized;
301ead13
 
 fail:
     if (s->oformat->deinit)
         s->oformat->deinit(s);
     return ret;
55f9037f
 }
 
1b05ac22
 #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))
 
 
11de006b
 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
9200514a
 FF_DISABLE_DEPRECATION_WARNINGS
55f9037f
 //FIXME merge with compute_pkt_fields
0106a20a
 static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
55f9037f
 {
6f69f7a8
     int delay = FFMAX(st->codecpar->video_delay, st->internal->avctx->max_b_frames > 0);
a312f710
     int num, den, i;
999a99c8
     int frame_size;
55f9037f
 
8de1ee9f
     if (!s->internal->missing_ts_warning &&
         !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
f8e3ebde
         (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) || (st->disposition & AV_DISPOSITION_TIMED_THUMBNAILS)) &&
8de1ee9f
         (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;
     }
 
d4cf3779
     if (s->debug & FF_FDEBUG_TS)
0106a20a
         av_log(s, AV_LOG_TRACE, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
513042c9
             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
55f9037f
 
3af1aba2
     if (pkt->duration < 0 && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
b01891a9
         av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
dc6a17cf
                pkt->duration, pkt->stream_index);
         pkt->duration = 0;
     }
 
55f9037f
     /* duration field */
     if (pkt->duration == 0) {
2d6e5849
         ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
55f9037f
         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) {
513042c9
         static int warned;
         if (!warned) {
             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
             warned = 1;
         }
55f9037f
         pkt->dts =
 //        pkt->pts= st->cur_dts;
cd1ff3e4
             pkt->pts = st->internal->priv_pts->val;
55f9037f
     }
 
     //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) &&
6f69f7a8
           st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE &&
           st->codecpar->codec_type != AVMEDIA_TYPE_DATA &&
55f9037f
           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
         av_log(s, AV_LOG_ERROR,
513042c9
                "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));
55f9037f
         return AVERROR(EINVAL);
     }
     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
eb4f9069
         av_log(s, AV_LOG_ERROR,
fc6aa304
                "pts (%s) < dts (%s) in stream %d\n",
                av_ts2str(pkt->pts), av_ts2str(pkt->dts),
eb4f9069
                st->index);
55f9037f
         return AVERROR(EINVAL);
     }
 
d4cf3779
     if (s->debug & FF_FDEBUG_TS)
         av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%s dts2:%s\n",
513042c9
             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
d4cf3779
 
55f9037f
     st->cur_dts = pkt->dts;
cd1ff3e4
     st->internal->priv_pts->val = pkt->dts;
55f9037f
 
     /* update pts */
3af1aba2
     switch (st->codecpar->codec_type) {
55f9037f
     case AVMEDIA_TYPE_AUDIO:
1b05ac22
         frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
                      ((AVFrame *)pkt->data)->nb_samples :
d92550d1
                      av_get_audio_frame_duration(st->codec, pkt->size);
55f9037f
 
         /* 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 */
cd1ff3e4
         if (frame_size >= 0 && (pkt->size || st->internal->priv_pts->num != st->internal->priv_pts->den >> 1 || st->internal->priv_pts->val)) {
             frac_add(st->internal->priv_pts, (int64_t)st->time_base.den * frame_size);
55f9037f
         }
         break;
     case AVMEDIA_TYPE_VIDEO:
cd1ff3e4
         frac_add(st->internal->priv_pts, (int64_t)st->time_base.den * st->time_base.num);
55f9037f
         break;
     }
     return 0;
 }
9200514a
 FF_ENABLE_DEPRECATION_WARNINGS
8de1ee9f
 #endif
55f9037f
 
0072116c
 /**
c4bf7402
  * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
  * sidedata.
  *
c2cb01d4
  * 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.
0072116c
  */
c2cb01d4
 static int write_packet(AVFormatContext *s, AVPacket *pkt)
0072116c
 {
ca4df37f
     int ret;
2fc9a3eb
     int64_t pts_backup, dts_backup;
 
     pts_backup = pkt->pts;
     dts_backup = pkt->dts;
c4bf7402
 
785c2544
     // If the timestamp offsetting below is adjusted, adjust
     // ff_interleaved_peek similarly.
5871ee50
     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;
     }
 
c4bf7402
     if (s->avoid_negative_ts > 0) {
         AVStream *st = s->streams[pkt->stream_index];
c329195a
         int64_t offset = st->mux_ts_offset;
7ac5c38e
         int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
060f14f4
 
7ac5c38e
         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;
29245147
             s->internal->offset_timebase = st->time_base;
c4bf7402
         }
060f14f4
 
29245147
         if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
c329195a
             offset = st->mux_ts_offset =
29245147
                 av_rescale_q_rnd(s->internal->offset,
                                  s->internal->offset_timebase,
060f14f4
                                  st->time_base,
                                  AV_ROUND_UP);
         }
 
         if (pkt->dts != AV_NOPTS_VALUE)
c329195a
             pkt->dts += offset;
c4bf7402
         if (pkt->pts != AV_NOPTS_VALUE)
c329195a
             pkt->pts += offset;
647f306b
 
7ac5c38e
         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",
1a363546
                     av_ts2str(pkt->pts),
7ac5c38e
                     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
                 );
             }
ec6a5fc6
         }
c4bf7402
     }
 
9da27fb5
     if (!s->internal->header_written) {
517fe644
         ret = s->internal->write_header_ret ? s->internal->write_header_ret : write_header_internal(s);
1f9139b0
         if (ret < 0)
             goto fail;
     }
 
1b05ac22
     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);
     }
596e5d47
 
9ad1e0c1
     if (s->pb && ret >= 0) {
eeeb595c
         flush_if_needed(s);
9ad1e0c1
         if (s->pb->error < 0)
             ret = s->pb->error;
     }
596e5d47
 
1f9139b0
 fail:
6005c7e6
 
2fc9a3eb
     if (ret < 0) {
         pkt->pts = pts_backup;
         pkt->dts = dts_backup;
     }
 
0072116c
     return ret;
 }
 
7b03b65b
 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);
     }
 
9200514a
     if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
7b03b65b
         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
         return AVERROR(EINVAL);
     }
 
     return 0;
 }
 
8de1ee9f
 static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
55f9037f
 {
     int ret;
 
7b03b65b
     ret = check_packet(s, pkt);
     if (ret < 0)
         return ret;
 
cdcfa97d
 #if !FF_API_COMPUTE_PKT_FIELDS2 || !FF_API_LAVF_AVCTX
8de1ee9f
     /* 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;
 }
 
de9674c5
 static int do_packet_auto_bsf(AVFormatContext *s, AVPacket *pkt) {
     AVStream *st = s->streams[pkt->stream_index];
     int i, ret;
 
1f6d7eb4
     if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
         return 1;
 
de9674c5
     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;
         }
     }
 
     for (i = 0; i < st->internal->nb_bsfcs; i++) {
         AVBSFContext *ctx = st->internal->bsfcs[i];
         // 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,
db23fde7
                     "Failed to send packet to filter %s for stream %d\n",
de9674c5
                     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,
db23fde7
                     "Failed to send packet to filter %s for stream %d\n",
de9674c5
                     ctx->filter->name, pkt->stream_index);
e70cdf91
             if (s->error_recognition & AV_EF_EXPLODE)
                 return ret;
             return 0;
de9674c5
         }
     }
     return 1;
 }
 
8de1ee9f
 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
 {
6005c7e6
     int ret;
8de1ee9f
 
     ret = prepare_input_packet(s, pkt);
     if (ret < 0)
         return ret;
 
55f9037f
     if (!pkt) {
513042c9
         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
e07b8d68
             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;
             }
0072116c
             ret = s->oformat->write_packet(s, NULL);
eeeb595c
             flush_if_needed(s);
513042c9
             if (ret >= 0 && s->pb && s->pb->error < 0)
                 ret = s->pb->error;
             return ret;
         }
55f9037f
         return 1;
6005c7e6
     }
55f9037f
 
a2c90d5f
     ret = do_packet_auto_bsf(s, pkt);
     if (ret <= 0)
         return ret;
 
11de006b
 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
0106a20a
     ret = compute_muxer_pkt_fields(s, s->streams[pkt->stream_index], pkt);
55f9037f
 
     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
         return ret;
8de1ee9f
 #endif
55f9037f
 
c2cb01d4
     ret = write_packet(s, pkt);
513042c9
     if (ret >= 0 && s->pb && s->pb->error < 0)
         ret = s->pb->error;
55f9037f
 
     if (ret >= 0)
         s->streams[pkt->stream_index]->nb_frames++;
     return ret;
 }
 
513042c9
 #define CHUNK_START 0x1000
 
 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
324ff594
                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
55f9037f
 {
324ff594
     int ret;
55f9037f
     AVPacketList **next_point, *this_pktl;
513042c9
     AVStream *st   = s->streams[pkt->stream_index];
     int chunked    = s->max_chunk_size || s->max_chunk_duration;
55f9037f
 
     this_pktl      = av_mallocz(sizeof(AVPacketList));
513042c9
     if (!this_pktl)
         return AVERROR(ENOMEM);
1b05ac22
     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
         av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
         av_assert0(((AVFrame *)pkt->data)->buf);
b66ac803
         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;
         }
1b05ac22
     }
55f9037f
 
     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
513042c9
         next_point = &(st->last_in_packet_buffer->next);
     } else {
9deaec78
         next_point = &s->internal->packet_buffer;
513042c9
     }
55f9037f
 
1191db31
     if (chunked) {
         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
c57c1329
         st->interleaver_chunk_size     += pkt->size;
         st->interleaver_chunk_duration += pkt->duration;
69a96f9d
         if (   (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
             || (max && st->interleaver_chunk_duration           > max)) {
46730e7a
             st->interleaver_chunk_size      = 0;
1191db31
             this_pktl->pkt.flags |= CHUNK_START;
46730e7a
             if (max && st->interleaver_chunk_duration > max) {
6f69f7a8
                 int64_t syncoffset = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
46730e7a
                 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;
513042c9
         }
1191db31
     }
     if (*next_point) {
         if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
             goto next_non_null;
513042c9
 
9deaec78
         if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
513042c9
             while (   *next_point
                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
                        || !compare(s, &(*next_point)->pkt, pkt)))
55f9037f
                 next_point = &(*next_point)->next;
513042c9
             if (*next_point)
                 goto next_non_null;
55f9037f
         } else {
9deaec78
             next_point = &(s->internal->packet_buffer_end->next);
55f9037f
         }
     }
f2a7e1a6
     av_assert1(!*next_point);
55f9037f
 
9deaec78
     s->internal->packet_buffer_end = this_pktl;
55f9037f
 next_non_null:
 
     this_pktl->next = *next_point;
 
     s->streams[pkt->stream_index]->last_in_packet_buffer =
         *next_point                                      = this_pktl;
324ff594
 
9b56d5c1
     av_packet_unref(pkt);
 
513042c9
     return 0;
55f9037f
 }
 
e926b5ce
 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
                                   AVPacket *pkt)
55f9037f
 {
     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);
6f69f7a8
     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);
513042c9
         if (ts == ts2) {
6f69f7a8
             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;
513042c9
             ts2=0;
         }
         comp= (ts>ts2) - (ts<ts2);
     }
55f9037f
 
     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;
e5cb7795
     int noninterleaved_count = 0;
513042c9
     int i, ret;
cb114ed4
     int eof = flush;
55f9037f
 
     if (pkt) {
324ff594
         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
513042c9
             return ret;
55f9037f
     }
 
513042c9
     for (i = 0; i < s->nb_streams; i++) {
         if (s->streams[i]->last_in_packet_buffer) {
             ++stream_count;
6f69f7a8
         } 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) {
513042c9
             ++noninterleaved_count;
         }
     }
55f9037f
 
3adb5f8d
     if (s->internal->nb_interleaved_streams == stream_count)
513042c9
         flush = 1;
3adb5f8d
 
a06fac35
     if (s->max_interleave_delta > 0 &&
29245147
         s->internal->packet_buffer &&
a06fac35
         !flush &&
         s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
     ) {
9deaec78
         AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
d9ae1031
         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);
513042c9
         }
d9ae1031
 
         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);
513042c9
             flush = 1;
         }
     }
d9ae1031
 
cb114ed4
     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;
         }
     }
 
513042c9
     if (stream_count && flush) {
         AVStream *st;
9deaec78
         pktl = s->internal->packet_buffer;
55f9037f
         *out = pktl->pkt;
513042c9
         st   = s->streams[out->stream_index];
55f9037f
 
9deaec78
         s->internal->packet_buffer = pktl->next;
         if (!s->internal->packet_buffer)
             s->internal->packet_buffer_end = NULL;
55f9037f
 
513042c9
         if (st->last_in_packet_buffer == pktl)
             st->last_in_packet_buffer = NULL;
55f9037f
         av_freep(&pktl);
513042c9
 
55f9037f
         return 1;
     } else {
         av_init_packet(out);
         return 0;
     }
 }
 
785c2544
 int ff_interleaved_peek(AVFormatContext *s, int stream,
                         AVPacket *pkt, int add_offset)
e1eb0fc9
 {
     AVPacketList *pktl = s->internal->packet_buffer;
     while (pktl) {
46a60fe1
         if (pktl->pkt.stream_index == stream) {
785c2544
             *pkt = pktl->pkt;
8fad4b4e
             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);
 
785c2544
                 if (pkt->dts != AV_NOPTS_VALUE)
                     pkt->dts += offset;
                 if (pkt->pts != AV_NOPTS_VALUE)
                     pkt->pts += offset;
             }
             return 0;
46a60fe1
         }
e1eb0fc9
         pktl = pktl->next;
     }
785c2544
     return AVERROR(ENOENT);
e1eb0fc9
 }
 
55f9037f
 /**
  * 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)
ce70f28a
             av_packet_unref(in);
55f9037f
         return ret;
     } else
         return ff_interleave_packet_per_dts(s, out, in, flush);
 }
 
 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
 {
6005c7e6
     int ret, flush = 0;
55f9037f
 
8de1ee9f
     ret = prepare_input_packet(s, pkt);
7b03b65b
     if (ret < 0)
394fb56c
         goto fail;
7b03b65b
 
55f9037f
     if (pkt) {
         AVStream *st = s->streams[pkt->stream_index];
 
de9674c5
         ret = do_packet_auto_bsf(s, pkt);
         if (ret == 0)
             return 0;
         else if (ret < 0)
             goto fail;
6d8ab358
 
d4cf3779
         if (s->debug & FF_FDEBUG_TS)
             av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
513042c9
                 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
d4cf3779
 
a444a505
 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
0106a20a
         if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
394fb56c
             goto fail;
8de1ee9f
 #endif
55f9037f
 
394fb56c
         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
             ret = AVERROR(EINVAL);
             goto fail;
         }
55f9037f
     } else {
1a3eb042
         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
55f9037f
         flush = 1;
     }
 
     for (;; ) {
         AVPacket opkt;
         int ret = interleave_packet(s, &opkt, pkt, flush);
394fb56c
         if (pkt) {
             memset(pkt, 0, sizeof(*pkt));
             av_init_packet(pkt);
             pkt = NULL;
         }
55f9037f
         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
             return ret;
 
c2cb01d4
         ret = write_packet(s, &opkt);
55f9037f
         if (ret >= 0)
             s->streams[opkt.stream_index]->nb_frames++;
 
ce70f28a
         av_packet_unref(&opkt);
55f9037f
 
         if (ret < 0)
             return ret;
513042c9
         if(s->pb && s->pb->error)
             return s->pb->error;
55f9037f
     }
394fb56c
 fail:
     av_packet_unref(pkt);
     return ret;
55f9037f
 }
 
 int av_write_trailer(AVFormatContext *s)
 {
     int ret, i;
 
     for (;; ) {
         AVPacket pkt;
         ret = interleave_packet(s, &pkt, NULL, 1);
25ccf5df
         if (ret < 0)
55f9037f
             goto fail;
         if (!ret)
             break;
 
c2cb01d4
         ret = write_packet(s, &pkt);
55f9037f
         if (ret >= 0)
             s->streams[pkt.stream_index]->nb_frames++;
 
ce70f28a
         av_packet_unref(&pkt);
55f9037f
 
         if (ret < 0)
             goto fail;
513042c9
         if(s->pb && s->pb->error)
             goto fail;
55f9037f
     }
 
9da27fb5
     if (!s->internal->header_written) {
517fe644
         ret = s->internal->write_header_ret ? s->internal->write_header_ret : write_header_internal(s);
1f9139b0
         if (ret < 0)
             goto fail;
     }
 
25ccf5df
 fail:
5d75e466
     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);
25ccf5df
         if (ret >= 0) {
55f9037f
         ret = s->oformat->write_trailer(s);
25ccf5df
         } else {
             s->oformat->write_trailer(s);
         }
5d75e466
     }
55f9037f
 
1f9139b0
     if (s->oformat->deinit)
         s->oformat->deinit(s);
 
a246fef1
     s->internal->header_written =
     s->internal->initialized =
     s->internal->streams_initialized = 0;
 
513042c9
     if (s->pb)
        avio_flush(s->pb);
     if (ret == 0)
        ret = s->pb ? s->pb->error : 0;
55f9037f
     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;
 }
513042c9
 
 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;
6cbbf4a2
 }
8097307b
 
12db891d
 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
351b22ca
                      AVFormatContext *src, int interleave)
12db891d
 {
     AVPacket local_pkt;
383a04a1
     int ret;
12db891d
 
     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);
8097307b
     if (pkt->duration)
         local_pkt.duration = av_rescale_q(pkt->duration,
                                           src->streams[pkt->stream_index]->time_base,
                                           dst->streams[dst_stream]->time_base);
383a04a1
 
351b22ca
     if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
     else            ret = av_write_frame(dst, &local_pkt);
383a04a1
     pkt->buf = local_pkt.buf;
db91e0ed
     pkt->side_data       = local_pkt.side_data;
     pkt->side_data_elems = local_pkt.side_data_elems;
383a04a1
     return ret;
12db891d
 }
1b05ac22
 
 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;
9f030ee0
         pkt.duration     = frame->pkt_duration;
1b05ac22
         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);
 }