]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
Merge commit '68e547ae8b455e5e2b60839f35c359d77a6d94bc'
[ffmpeg] / libavformat / mux.c
1 /*
2  * muxing functions for use within FFmpeg
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "avformat.h"
23 #include "avio_internal.h"
24 #include "internal.h"
25 #include "libavcodec/internal.h"
26 #include "libavcodec/bytestream.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/timestamp.h"
31 #include "metadata.h"
32 #include "id3v2.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/time.h"
39 #include "riff.h"
40 #include "audiointerleave.h"
41 #include "url.h"
42 #include <stdarg.h>
43 #if CONFIG_NETWORK
44 #include "network.h"
45 #endif
46
47 /**
48  * @file
49  * muxing functions for use within libavformat
50  */
51
52 /* fraction handling */
53
54 /**
55  * f = val + (num / den) + 0.5.
56  *
57  * 'num' is normalized so that it is such as 0 <= num < den.
58  *
59  * @param f fractional number
60  * @param val integer value
61  * @param num must be >= 0
62  * @param den must be >= 1
63  */
64 static void frac_init(FFFrac *f, int64_t val, int64_t num, int64_t den)
65 {
66     num += (den >> 1);
67     if (num >= den) {
68         val += num / den;
69         num  = num % den;
70     }
71     f->val = val;
72     f->num = num;
73     f->den = den;
74 }
75
76 /**
77  * Fractional addition to f: f = f + (incr / f->den).
78  *
79  * @param f fractional number
80  * @param incr increment, can be positive or negative
81  */
82 static void frac_add(FFFrac *f, int64_t incr)
83 {
84     int64_t num, den;
85
86     num = f->num + incr;
87     den = f->den;
88     if (num < 0) {
89         f->val += num / den;
90         num     = num % den;
91         if (num < 0) {
92             num += den;
93             f->val--;
94         }
95     } else if (num >= den) {
96         f->val += num / den;
97         num     = num % den;
98     }
99     f->num = num;
100 }
101
102 AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precision)
103 {
104     AVRational q;
105     int j;
106
107     q = st->time_base;
108
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         q.den <<= 1;
114
115     return q;
116 }
117
118 enum AVChromaLocation ff_choose_chroma_location(AVFormatContext *s, AVStream *st)
119 {
120     AVCodecContext *avctx = st->codec;
121     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(avctx->pix_fmt);
122
123     if (avctx->chroma_sample_location != AVCHROMA_LOC_UNSPECIFIED)
124         return avctx->chroma_sample_location;
125
126     if (pix_desc) {
127         if (pix_desc->log2_chroma_h == 0) {
128             return AVCHROMA_LOC_TOPLEFT;
129         } else if (pix_desc->log2_chroma_w == 1 && pix_desc->log2_chroma_h == 1) {
130             if (avctx->field_order == AV_FIELD_UNKNOWN || avctx->field_order == AV_FIELD_PROGRESSIVE) {
131                 switch (avctx->codec_id) {
132                 case AV_CODEC_ID_MJPEG:
133                 case AV_CODEC_ID_MPEG1VIDEO: return AVCHROMA_LOC_CENTER;
134                 }
135             }
136             if (avctx->field_order == AV_FIELD_UNKNOWN || avctx->field_order != AV_FIELD_PROGRESSIVE) {
137                 switch (avctx->codec_id) {
138                 case AV_CODEC_ID_MPEG2VIDEO: return AVCHROMA_LOC_LEFT;
139                 }
140             }
141         }
142     }
143
144     return AVCHROMA_LOC_UNSPECIFIED;
145
146 }
147
148 int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
149                                    const char *format, const char *filename)
150 {
151     AVFormatContext *s = avformat_alloc_context();
152     int ret = 0;
153
154     *avctx = NULL;
155     if (!s)
156         goto nomem;
157
158     if (!oformat) {
159         if (format) {
160             oformat = av_guess_format(format, NULL, NULL);
161             if (!oformat) {
162                 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
163                 ret = AVERROR(EINVAL);
164                 goto error;
165             }
166         } else {
167             oformat = av_guess_format(NULL, filename, NULL);
168             if (!oformat) {
169                 ret = AVERROR(EINVAL);
170                 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
171                        filename);
172                 goto error;
173             }
174         }
175     }
176
177     s->oformat = oformat;
178     if (s->oformat->priv_data_size > 0) {
179         s->priv_data = av_mallocz(s->oformat->priv_data_size);
180         if (!s->priv_data)
181             goto nomem;
182         if (s->oformat->priv_class) {
183             *(const AVClass**)s->priv_data= s->oformat->priv_class;
184             av_opt_set_defaults(s->priv_data);
185         }
186     } else
187         s->priv_data = NULL;
188
189     if (filename)
190         av_strlcpy(s->filename, filename, sizeof(s->filename));
191     *avctx = s;
192     return 0;
193 nomem:
194     av_log(s, AV_LOG_ERROR, "Out of memory\n");
195     ret = AVERROR(ENOMEM);
196 error:
197     avformat_free_context(s);
198     return ret;
199 }
200
201 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
202 {
203     const AVCodecTag *avctag;
204     int n;
205     enum AVCodecID id = AV_CODEC_ID_NONE;
206     int64_t tag  = -1;
207
208     /**
209      * Check that tag + id is in the table
210      * If neither is in the table -> OK
211      * If tag is in the table with another id -> FAIL
212      * If id is in the table with another tag -> FAIL unless strict < normal
213      */
214     for (n = 0; s->oformat->codec_tag[n]; n++) {
215         avctag = s->oformat->codec_tag[n];
216         while (avctag->id != AV_CODEC_ID_NONE) {
217             if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
218                 id = avctag->id;
219                 if (id == st->codec->codec_id)
220                     return 1;
221             }
222             if (avctag->id == st->codec->codec_id)
223                 tag = avctag->tag;
224             avctag++;
225         }
226     }
227     if (id != AV_CODEC_ID_NONE)
228         return 0;
229     if (tag >= 0 && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
230         return 0;
231     return 1;
232 }
233
234
235 static int init_muxer(AVFormatContext *s, AVDictionary **options)
236 {
237     int ret = 0, i;
238     AVStream *st;
239     AVDictionary *tmp = NULL;
240     AVCodecContext *codec = NULL;
241     AVOutputFormat *of = s->oformat;
242     const AVCodecDescriptor *desc;
243     AVDictionaryEntry *e;
244
245     if (options)
246         av_dict_copy(&tmp, *options, 0);
247
248     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
249         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 (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT) {
255         if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
256 #if FF_API_LAVF_BITEXACT
257             av_log(s, AV_LOG_WARNING,
258                    "Setting the AVFormatContext to bitexact mode, because "
259                    "the AVCodecContext is in that mode. This behavior will "
260                    "change in the future. To keep the current behavior, set "
261                    "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");
262             s->flags |= AVFMT_FLAG_BITEXACT;
263 #else
264             av_log(s, AV_LOG_WARNING,
265                    "The AVFormatContext is not in set to bitexact mode, only "
266                    "the AVCodecContext. If this is not intended, set "
267                    "AVFormatContext.flags |= AVFMT_FLAG_BITEXACT.\n");
268 #endif
269         }
270     }
271
272     // some sanity checks
273     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
274         av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
275         ret = AVERROR(EINVAL);
276         goto fail;
277     }
278
279     for (i = 0; i < s->nb_streams; i++) {
280         st    = s->streams[i];
281         codec = st->codec;
282
283 #if FF_API_LAVF_CODEC_TB
284 FF_DISABLE_DEPRECATION_WARNINGS
285         if (!st->time_base.num && codec->time_base.num) {
286             av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
287                    "timebase hint to the muxer is deprecated. Set "
288                    "AVStream.time_base instead.\n");
289             avpriv_set_pts_info(st, 64, codec->time_base.num, codec->time_base.den);
290         }
291 FF_ENABLE_DEPRECATION_WARNINGS
292 #endif
293
294         if (!st->time_base.num) {
295             /* fall back on the default timebase values */
296             if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->sample_rate)
297                 avpriv_set_pts_info(st, 64, 1, codec->sample_rate);
298             else
299                 avpriv_set_pts_info(st, 33, 1, 90000);
300         }
301
302         switch (codec->codec_type) {
303         case AVMEDIA_TYPE_AUDIO:
304             if (codec->sample_rate <= 0) {
305                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
306                 ret = AVERROR(EINVAL);
307                 goto fail;
308             }
309             if (!codec->block_align)
310                 codec->block_align = codec->channels *
311                                      av_get_bits_per_sample(codec->codec_id) >> 3;
312             break;
313         case AVMEDIA_TYPE_VIDEO:
314             if ((codec->width <= 0 || codec->height <= 0) &&
315                 !(of->flags & AVFMT_NODIMENSIONS)) {
316                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
317                 ret = AVERROR(EINVAL);
318                 goto fail;
319             }
320             if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
321                 && fabs(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
322             ) {
323                 if (st->sample_aspect_ratio.num != 0 &&
324                     st->sample_aspect_ratio.den != 0 &&
325                     codec->sample_aspect_ratio.num != 0 &&
326                     codec->sample_aspect_ratio.den != 0) {
327                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
328                            "(%d/%d) and encoder layer (%d/%d)\n",
329                            st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
330                            codec->sample_aspect_ratio.num,
331                            codec->sample_aspect_ratio.den);
332                     ret = AVERROR(EINVAL);
333                     goto fail;
334                 }
335             }
336             break;
337         }
338
339         desc = avcodec_descriptor_get(codec->codec_id);
340         if (desc && desc->props & AV_CODEC_PROP_REORDER)
341             st->internal->reorder = 1;
342
343         if (of->codec_tag) {
344             if (   codec->codec_tag
345                 && codec->codec_id == AV_CODEC_ID_RAWVIDEO
346                 && (   av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
347                     || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
348                 && !validate_codec_tag(s, st)) {
349                 // the current rawvideo encoding system ends up setting
350                 // the wrong codec_tag for avi/mov, we override it here
351                 codec->codec_tag = 0;
352             }
353             if (codec->codec_tag) {
354                 if (!validate_codec_tag(s, st)) {
355                     char tagbuf[32], tagbuf2[32];
356                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
357                     av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
358                     av_log(s, AV_LOG_ERROR,
359                            "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
360                            tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
361                     ret = AVERROR_INVALIDDATA;
362                     goto fail;
363                 }
364             } else
365                 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
366         }
367
368         if (of->flags & AVFMT_GLOBALHEADER &&
369             !(codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
370             av_log(s, AV_LOG_WARNING,
371                    "Codec for stream %d does not use global headers "
372                    "but container format requires global headers\n", i);
373
374         if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
375             s->internal->nb_interleaved_streams++;
376     }
377
378     if (!s->priv_data && of->priv_data_size > 0) {
379         s->priv_data = av_mallocz(of->priv_data_size);
380         if (!s->priv_data) {
381             ret = AVERROR(ENOMEM);
382             goto fail;
383         }
384         if (of->priv_class) {
385             *(const AVClass **)s->priv_data = of->priv_class;
386             av_opt_set_defaults(s->priv_data);
387             if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
388                 goto fail;
389         }
390     }
391
392     /* set muxer identification string */
393     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
394         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
395     } else {
396         av_dict_set(&s->metadata, "encoder", NULL, 0);
397     }
398
399     for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
400         av_dict_set(&s->metadata, e->key, NULL, 0);
401     }
402
403     if (options) {
404          av_dict_free(options);
405          *options = tmp;
406     }
407
408     return 0;
409
410 fail:
411     av_dict_free(&tmp);
412     return ret;
413 }
414
415 static int init_pts(AVFormatContext *s)
416 {
417     int i;
418     AVStream *st;
419
420     /* init PTS generation */
421     for (i = 0; i < s->nb_streams; i++) {
422         int64_t den = AV_NOPTS_VALUE;
423         st = s->streams[i];
424
425         switch (st->codec->codec_type) {
426         case AVMEDIA_TYPE_AUDIO:
427             den = (int64_t)st->time_base.num * st->codec->sample_rate;
428             break;
429         case AVMEDIA_TYPE_VIDEO:
430             den = (int64_t)st->time_base.num * st->codec->time_base.den;
431             break;
432         default:
433             break;
434         }
435
436         if (!st->priv_pts)
437             st->priv_pts = av_mallocz(sizeof(*st->priv_pts));
438         if (!st->priv_pts)
439             return AVERROR(ENOMEM);
440
441         if (den != AV_NOPTS_VALUE) {
442             if (den <= 0)
443                 return AVERROR_INVALIDDATA;
444
445             frac_init(st->priv_pts, 0, 0, den);
446         }
447     }
448
449     return 0;
450 }
451
452 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
453 {
454     int ret = 0;
455
456     if ((ret = init_muxer(s, options)) < 0)
457         return ret;
458
459     if (s->oformat->write_header) {
460         ret = s->oformat->write_header(s);
461         if (ret >= 0 && s->pb && s->pb->error < 0)
462             ret = s->pb->error;
463         if (ret < 0)
464             return ret;
465         if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
466             avio_flush(s->pb);
467     }
468
469     if ((ret = init_pts(s)) < 0)
470         return ret;
471
472     if (s->avoid_negative_ts < 0) {
473         av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
474         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
475             s->avoid_negative_ts = 0;
476         } else
477             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
478     }
479
480     return 0;
481 }
482
483 #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
484
485 /* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
486    it is only being used internally to this file as a consistency check.
487    The value is chosen to be very unlikely to appear on its own and to cause
488    immediate failure if used anywhere as a real size. */
489 #define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))
490
491
492 #if FF_API_COMPUTE_PKT_FIELDS2
493 //FIXME merge with compute_pkt_fields
494 static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
495 {
496     int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
497     int num, den, i;
498     int frame_size;
499
500     if (!s->internal->missing_ts_warning &&
501         !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
502         (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
503         av_log(s, AV_LOG_WARNING,
504                "Timestamps are unset in a packet for stream %d. "
505                "This is deprecated and will stop working in the future. "
506                "Fix your code to set the timestamps properly\n", st->index);
507         s->internal->missing_ts_warning = 1;
508     }
509
510     if (s->debug & FF_FDEBUG_TS)
511         av_log(s, AV_LOG_TRACE, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
512             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
513
514     if (pkt->duration < 0 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
515         av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
516                pkt->duration, pkt->stream_index);
517         pkt->duration = 0;
518     }
519
520     /* duration field */
521     if (pkt->duration == 0) {
522         ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
523         if (den && num) {
524             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
525         }
526     }
527
528     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
529         pkt->pts = pkt->dts;
530
531     //XXX/FIXME this is a temporary hack until all encoders output pts
532     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
533         static int warned;
534         if (!warned) {
535             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
536             warned = 1;
537         }
538         pkt->dts =
539 //        pkt->pts= st->cur_dts;
540             pkt->pts = st->priv_pts->val;
541     }
542
543     //calculate dts from pts
544     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
545         st->pts_buffer[0] = pkt->pts;
546         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
547             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
548         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
549             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
550
551         pkt->dts = st->pts_buffer[0];
552     }
553
554     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
555         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
556           st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE &&
557           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
558         av_log(s, AV_LOG_ERROR,
559                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
560                st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
561         return AVERROR(EINVAL);
562     }
563     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
564         av_log(s, AV_LOG_ERROR,
565                "pts (%s) < dts (%s) in stream %d\n",
566                av_ts2str(pkt->pts), av_ts2str(pkt->dts),
567                st->index);
568         return AVERROR(EINVAL);
569     }
570
571     if (s->debug & FF_FDEBUG_TS)
572         av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%s dts2:%s\n",
573             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
574
575     st->cur_dts = pkt->dts;
576     st->priv_pts->val = pkt->dts;
577
578     /* update pts */
579     switch (st->codec->codec_type) {
580     case AVMEDIA_TYPE_AUDIO:
581         frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
582                      ((AVFrame *)pkt->data)->nb_samples :
583                      av_get_audio_frame_duration(st->codec, pkt->size);
584
585         /* HACK/FIXME, we skip the initial 0 size packets as they are most
586          * likely equal to the encoder delay, but it would be better if we
587          * had the real timestamps from the encoder */
588         if (frame_size >= 0 && (pkt->size || st->priv_pts->num != st->priv_pts->den >> 1 || st->priv_pts->val)) {
589             frac_add(st->priv_pts, (int64_t)st->time_base.den * frame_size);
590         }
591         break;
592     case AVMEDIA_TYPE_VIDEO:
593         frac_add(st->priv_pts, (int64_t)st->time_base.den * st->codec->time_base.num);
594         break;
595     }
596     return 0;
597 }
598 #endif
599
600 /**
601  * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
602  * sidedata.
603  *
604  * FIXME: this function should NEVER get undefined pts/dts beside when the
605  * AVFMT_NOTIMESTAMPS is set.
606  * Those additional safety checks should be dropped once the correct checks
607  * are set in the callers.
608  */
609 static int write_packet(AVFormatContext *s, AVPacket *pkt)
610 {
611     int ret, did_split;
612
613     if (s->output_ts_offset) {
614         AVStream *st = s->streams[pkt->stream_index];
615         int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
616
617         if (pkt->dts != AV_NOPTS_VALUE)
618             pkt->dts += offset;
619         if (pkt->pts != AV_NOPTS_VALUE)
620             pkt->pts += offset;
621     }
622
623     if (s->avoid_negative_ts > 0) {
624         AVStream *st = s->streams[pkt->stream_index];
625         int64_t offset = st->mux_ts_offset;
626         int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
627
628         if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
629             (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
630             s->internal->offset = -ts;
631             s->internal->offset_timebase = st->time_base;
632         }
633
634         if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
635             offset = st->mux_ts_offset =
636                 av_rescale_q_rnd(s->internal->offset,
637                                  s->internal->offset_timebase,
638                                  st->time_base,
639                                  AV_ROUND_UP);
640         }
641
642         if (pkt->dts != AV_NOPTS_VALUE)
643             pkt->dts += offset;
644         if (pkt->pts != AV_NOPTS_VALUE)
645             pkt->pts += offset;
646
647         if (s->internal->avoid_negative_ts_use_pts) {
648             if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
649                 av_log(s, AV_LOG_WARNING, "failed to avoid negative "
650                     "pts %s in stream %d.\n"
651                     "Try -avoid_negative_ts 1 as a possible workaround.\n",
652                     av_ts2str(pkt->dts),
653                     pkt->stream_index
654                 );
655             }
656         } else {
657             av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
658             if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
659                 av_log(s, AV_LOG_WARNING,
660                     "Packets poorly interleaved, failed to avoid negative "
661                     "timestamp %s in stream %d.\n"
662                     "Try -max_interleave_delta 0 as a possible workaround.\n",
663                     av_ts2str(pkt->dts),
664                     pkt->stream_index
665                 );
666             }
667         }
668     }
669
670     did_split = av_packet_split_side_data(pkt);
671     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
672         AVFrame *frame = (AVFrame *)pkt->data;
673         av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
674         ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
675         av_frame_free(&frame);
676     } else {
677         ret = s->oformat->write_packet(s, pkt);
678     }
679
680     if (s->pb && ret >= 0) {
681         if (s->flush_packets && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
682             avio_flush(s->pb);
683         if (s->pb->error < 0)
684             ret = s->pb->error;
685     }
686
687
688     if (did_split)
689         av_packet_merge_side_data(pkt);
690
691     return ret;
692 }
693
694 static int check_packet(AVFormatContext *s, AVPacket *pkt)
695 {
696     if (!pkt)
697         return 0;
698
699     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
700         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
701                pkt->stream_index);
702         return AVERROR(EINVAL);
703     }
704
705     if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
706         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
707         return AVERROR(EINVAL);
708     }
709
710     return 0;
711 }
712
713 static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
714 {
715     int ret;
716
717     ret = check_packet(s, pkt);
718     if (ret < 0)
719         return ret;
720
721 #if !FF_API_COMPUTE_PKT_FIELDS2
722     /* sanitize the timestamps */
723     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
724         AVStream *st = s->streams[pkt->stream_index];
725
726         /* when there is no reordering (so dts is equal to pts), but
727          * only one of them is set, set the other as well */
728         if (!st->internal->reorder) {
729             if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
730                 pkt->pts = pkt->dts;
731             if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
732                 pkt->dts = pkt->pts;
733         }
734
735         /* check that the timestamps are set */
736         if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
737             av_log(s, AV_LOG_ERROR,
738                    "Timestamps are unset in a packet for stream %d\n", st->index);
739             return AVERROR(EINVAL);
740         }
741
742         /* check that the dts are increasing (or at least non-decreasing,
743          * if the format allows it */
744         if (st->cur_dts != AV_NOPTS_VALUE &&
745             ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
746              st->cur_dts > pkt->dts)) {
747             av_log(s, AV_LOG_ERROR,
748                    "Application provided invalid, non monotonically increasing "
749                    "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
750                    st->index, st->cur_dts, pkt->dts);
751             return AVERROR(EINVAL);
752         }
753
754         if (pkt->pts < pkt->dts) {
755             av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
756                    pkt->pts, pkt->dts, st->index);
757             return AVERROR(EINVAL);
758         }
759     }
760 #endif
761
762     return 0;
763 }
764
765 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
766 {
767     int ret;
768
769     ret = prepare_input_packet(s, pkt);
770     if (ret < 0)
771         return ret;
772
773     if (!pkt) {
774         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
775             ret = s->oformat->write_packet(s, NULL);
776             if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
777                 avio_flush(s->pb);
778             if (ret >= 0 && s->pb && s->pb->error < 0)
779                 ret = s->pb->error;
780             return ret;
781         }
782         return 1;
783     }
784
785 #if FF_API_COMPUTE_PKT_FIELDS2
786     ret = compute_muxer_pkt_fields(s, s->streams[pkt->stream_index], pkt);
787
788     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
789         return ret;
790 #endif
791
792     ret = write_packet(s, pkt);
793     if (ret >= 0 && s->pb && s->pb->error < 0)
794         ret = s->pb->error;
795
796     if (ret >= 0)
797         s->streams[pkt->stream_index]->nb_frames++;
798     return ret;
799 }
800
801 #define CHUNK_START 0x1000
802
803 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
804                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
805 {
806     int ret;
807     AVPacketList **next_point, *this_pktl;
808     AVStream *st   = s->streams[pkt->stream_index];
809     int chunked    = s->max_chunk_size || s->max_chunk_duration;
810
811     this_pktl      = av_mallocz(sizeof(AVPacketList));
812     if (!this_pktl)
813         return AVERROR(ENOMEM);
814     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
815         av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
816         av_assert0(((AVFrame *)pkt->data)->buf);
817     }
818
819     if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
820         av_free(this_pktl);
821         return ret;
822     }
823
824     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
825         next_point = &(st->last_in_packet_buffer->next);
826     } else {
827         next_point = &s->internal->packet_buffer;
828     }
829
830     if (chunked) {
831         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
832         st->interleaver_chunk_size     += pkt->size;
833         st->interleaver_chunk_duration += pkt->duration;
834         if (   (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
835             || (max && st->interleaver_chunk_duration           > max)) {
836             st->interleaver_chunk_size      = 0;
837             this_pktl->pkt.flags |= CHUNK_START;
838             if (max && st->interleaver_chunk_duration > max) {
839                 int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
840                 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
841
842                 st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
843             } else
844                 st->interleaver_chunk_duration = 0;
845         }
846     }
847     if (*next_point) {
848         if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
849             goto next_non_null;
850
851         if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
852             while (   *next_point
853                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
854                        || !compare(s, &(*next_point)->pkt, pkt)))
855                 next_point = &(*next_point)->next;
856             if (*next_point)
857                 goto next_non_null;
858         } else {
859             next_point = &(s->internal->packet_buffer_end->next);
860         }
861     }
862     av_assert1(!*next_point);
863
864     s->internal->packet_buffer_end = this_pktl;
865 next_non_null:
866
867     this_pktl->next = *next_point;
868
869     s->streams[pkt->stream_index]->last_in_packet_buffer =
870         *next_point                                      = this_pktl;
871
872     av_packet_unref(pkt);
873
874     return 0;
875 }
876
877 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
878                                   AVPacket *pkt)
879 {
880     AVStream *st  = s->streams[pkt->stream_index];
881     AVStream *st2 = s->streams[next->stream_index];
882     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
883                                   st->time_base);
884     if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
885         int64_t ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO);
886         int64_t ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - s->audio_preload*(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO);
887         if (ts == ts2) {
888             ts= ( pkt ->dts* st->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st ->codec->codec_type == AVMEDIA_TYPE_AUDIO)* st->time_base.den)*st2->time_base.den
889                -( next->dts*st2->time_base.num*AV_TIME_BASE - s->audio_preload*(int64_t)(st2->codec->codec_type == AVMEDIA_TYPE_AUDIO)*st2->time_base.den)* st->time_base.den;
890             ts2=0;
891         }
892         comp= (ts>ts2) - (ts<ts2);
893     }
894
895     if (comp == 0)
896         return pkt->stream_index < next->stream_index;
897     return comp > 0;
898 }
899
900 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
901                                  AVPacket *pkt, int flush)
902 {
903     AVPacketList *pktl;
904     int stream_count = 0;
905     int noninterleaved_count = 0;
906     int i, ret;
907
908     if (pkt) {
909         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
910             return ret;
911     }
912
913     for (i = 0; i < s->nb_streams; i++) {
914         if (s->streams[i]->last_in_packet_buffer) {
915             ++stream_count;
916         } else if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
917                    s->streams[i]->codec->codec_id != AV_CODEC_ID_VP8 &&
918                    s->streams[i]->codec->codec_id != AV_CODEC_ID_VP9) {
919             ++noninterleaved_count;
920         }
921     }
922
923     if (s->internal->nb_interleaved_streams == stream_count)
924         flush = 1;
925
926     if (s->max_interleave_delta > 0 &&
927         s->internal->packet_buffer &&
928         !flush &&
929         s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
930     ) {
931         AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
932         int64_t delta_dts = INT64_MIN;
933         int64_t top_dts = av_rescale_q(top_pkt->dts,
934                                        s->streams[top_pkt->stream_index]->time_base,
935                                        AV_TIME_BASE_Q);
936
937         for (i = 0; i < s->nb_streams; i++) {
938             int64_t last_dts;
939             const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
940
941             if (!last)
942                 continue;
943
944             last_dts = av_rescale_q(last->pkt.dts,
945                                     s->streams[i]->time_base,
946                                     AV_TIME_BASE_Q);
947             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
948         }
949
950         if (delta_dts > s->max_interleave_delta) {
951             av_log(s, AV_LOG_DEBUG,
952                    "Delay between the first packet and last packet in the "
953                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
954                    delta_dts, s->max_interleave_delta);
955             flush = 1;
956         }
957     }
958
959     if (stream_count && flush) {
960         AVStream *st;
961         pktl = s->internal->packet_buffer;
962         *out = pktl->pkt;
963         st   = s->streams[out->stream_index];
964
965         s->internal->packet_buffer = pktl->next;
966         if (!s->internal->packet_buffer)
967             s->internal->packet_buffer_end = NULL;
968
969         if (st->last_in_packet_buffer == pktl)
970             st->last_in_packet_buffer = NULL;
971         av_freep(&pktl);
972
973         return 1;
974     } else {
975         av_init_packet(out);
976         return 0;
977     }
978 }
979
980 /**
981  * Interleave an AVPacket correctly so it can be muxed.
982  * @param out the interleaved packet will be output here
983  * @param in the input packet
984  * @param flush 1 if no further packets are available as input and all
985  *              remaining packets should be output
986  * @return 1 if a packet was output, 0 if no packet could be output,
987  *         < 0 if an error occurred
988  */
989 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
990 {
991     if (s->oformat->interleave_packet) {
992         int ret = s->oformat->interleave_packet(s, out, in, flush);
993         if (in)
994             av_packet_unref(in);
995         return ret;
996     } else
997         return ff_interleave_packet_per_dts(s, out, in, flush);
998 }
999
1000 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
1001 {
1002     int ret, flush = 0;
1003
1004     ret = prepare_input_packet(s, pkt);
1005     if (ret < 0)
1006         goto fail;
1007
1008     if (pkt) {
1009         AVStream *st = s->streams[pkt->stream_index];
1010
1011         if (s->debug & FF_FDEBUG_TS)
1012             av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
1013                 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
1014
1015 #if FF_API_COMPUTE_PKT_FIELDS2
1016         if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
1017             goto fail;
1018 #endif
1019
1020         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
1021             ret = AVERROR(EINVAL);
1022             goto fail;
1023         }
1024     } else {
1025         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
1026         flush = 1;
1027     }
1028
1029     for (;; ) {
1030         AVPacket opkt;
1031         int ret = interleave_packet(s, &opkt, pkt, flush);
1032         if (pkt) {
1033             memset(pkt, 0, sizeof(*pkt));
1034             av_init_packet(pkt);
1035             pkt = NULL;
1036         }
1037         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
1038             return ret;
1039
1040         ret = write_packet(s, &opkt);
1041         if (ret >= 0)
1042             s->streams[opkt.stream_index]->nb_frames++;
1043
1044         av_packet_unref(&opkt);
1045
1046         if (ret < 0)
1047             return ret;
1048         if(s->pb && s->pb->error)
1049             return s->pb->error;
1050     }
1051 fail:
1052     av_packet_unref(pkt);
1053     return ret;
1054 }
1055
1056 int av_write_trailer(AVFormatContext *s)
1057 {
1058     int ret, i;
1059
1060     for (;; ) {
1061         AVPacket pkt;
1062         ret = interleave_packet(s, &pkt, NULL, 1);
1063         if (ret < 0)
1064             goto fail;
1065         if (!ret)
1066             break;
1067
1068         ret = write_packet(s, &pkt);
1069         if (ret >= 0)
1070             s->streams[pkt.stream_index]->nb_frames++;
1071
1072         av_packet_unref(&pkt);
1073
1074         if (ret < 0)
1075             goto fail;
1076         if(s->pb && s->pb->error)
1077             goto fail;
1078     }
1079
1080 fail:
1081     if (s->oformat->write_trailer)
1082         if (ret >= 0) {
1083         ret = s->oformat->write_trailer(s);
1084         } else {
1085             s->oformat->write_trailer(s);
1086         }
1087
1088     if (s->pb)
1089        avio_flush(s->pb);
1090     if (ret == 0)
1091        ret = s->pb ? s->pb->error : 0;
1092     for (i = 0; i < s->nb_streams; i++) {
1093         av_freep(&s->streams[i]->priv_data);
1094         av_freep(&s->streams[i]->index_entries);
1095     }
1096     if (s->oformat->priv_class)
1097         av_opt_free(s->priv_data);
1098     av_freep(&s->priv_data);
1099     return ret;
1100 }
1101
1102 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
1103                             int64_t *dts, int64_t *wall)
1104 {
1105     if (!s->oformat || !s->oformat->get_output_timestamp)
1106         return AVERROR(ENOSYS);
1107     s->oformat->get_output_timestamp(s, stream, dts, wall);
1108     return 0;
1109 }
1110
1111 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
1112                      AVFormatContext *src, int interleave)
1113 {
1114     AVPacket local_pkt;
1115     int ret;
1116
1117     local_pkt = *pkt;
1118     local_pkt.stream_index = dst_stream;
1119     if (pkt->pts != AV_NOPTS_VALUE)
1120         local_pkt.pts = av_rescale_q(pkt->pts,
1121                                      src->streams[pkt->stream_index]->time_base,
1122                                      dst->streams[dst_stream]->time_base);
1123     if (pkt->dts != AV_NOPTS_VALUE)
1124         local_pkt.dts = av_rescale_q(pkt->dts,
1125                                      src->streams[pkt->stream_index]->time_base,
1126                                      dst->streams[dst_stream]->time_base);
1127     if (pkt->duration)
1128         local_pkt.duration = av_rescale_q(pkt->duration,
1129                                           src->streams[pkt->stream_index]->time_base,
1130                                           dst->streams[dst_stream]->time_base);
1131
1132     if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
1133     else            ret = av_write_frame(dst, &local_pkt);
1134     pkt->buf = local_pkt.buf;
1135     pkt->side_data       = local_pkt.side_data;
1136     pkt->side_data_elems = local_pkt.side_data_elems;
1137     return ret;
1138 }
1139
1140 static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
1141                                            AVFrame *frame, int interleaved)
1142 {
1143     AVPacket pkt, *pktp;
1144
1145     av_assert0(s->oformat);
1146     if (!s->oformat->write_uncoded_frame)
1147         return AVERROR(ENOSYS);
1148
1149     if (!frame) {
1150         pktp = NULL;
1151     } else {
1152         pktp = &pkt;
1153         av_init_packet(&pkt);
1154         pkt.data = (void *)frame;
1155         pkt.size         = UNCODED_FRAME_PACKET_SIZE;
1156         pkt.pts          =
1157         pkt.dts          = frame->pts;
1158         pkt.duration     = av_frame_get_pkt_duration(frame);
1159         pkt.stream_index = stream_index;
1160         pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
1161     }
1162
1163     return interleaved ? av_interleaved_write_frame(s, pktp) :
1164                          av_write_frame(s, pktp);
1165 }
1166
1167 int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
1168                            AVFrame *frame)
1169 {
1170     return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
1171 }
1172
1173 int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
1174                                        AVFrame *frame)
1175 {
1176     return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
1177 }
1178
1179 int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
1180 {
1181     av_assert0(s->oformat);
1182     if (!s->oformat->write_uncoded_frame)
1183         return AVERROR(ENOSYS);
1184     return s->oformat->write_uncoded_frame(s, stream_index, NULL,
1185                                            AV_WRITE_UNCODED_FRAME_QUERY);
1186 }