]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
lavf/dnxhd: Autodetect more valid files.
[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     AVDictionaryEntry *e;
243
244     if (options)
245         av_dict_copy(&tmp, *options, 0);
246
247     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
248         goto fail;
249     if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
250         (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
251         goto fail;
252
253 #if FF_API_LAVF_BITEXACT
254     if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT)
255         s->flags |= AVFMT_FLAG_BITEXACT;
256 #endif
257
258     // some sanity checks
259     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
260         av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
261         ret = AVERROR(EINVAL);
262         goto fail;
263     }
264
265     for (i = 0; i < s->nb_streams; i++) {
266         st    = s->streams[i];
267         codec = st->codec;
268
269 #if FF_API_LAVF_CODEC_TB
270 FF_DISABLE_DEPRECATION_WARNINGS
271         if (!st->time_base.num && codec->time_base.num) {
272             av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
273                    "timebase hint to the muxer is deprecated. Set "
274                    "AVStream.time_base instead.\n");
275             avpriv_set_pts_info(st, 64, codec->time_base.num, codec->time_base.den);
276         }
277 FF_ENABLE_DEPRECATION_WARNINGS
278 #endif
279
280         if (!st->time_base.num) {
281             /* fall back on the default timebase values */
282             if (codec->codec_type == AVMEDIA_TYPE_AUDIO && codec->sample_rate)
283                 avpriv_set_pts_info(st, 64, 1, codec->sample_rate);
284             else
285                 avpriv_set_pts_info(st, 33, 1, 90000);
286         }
287
288         switch (codec->codec_type) {
289         case AVMEDIA_TYPE_AUDIO:
290             if (codec->sample_rate <= 0) {
291                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
292                 ret = AVERROR(EINVAL);
293                 goto fail;
294             }
295             if (!codec->block_align)
296                 codec->block_align = codec->channels *
297                                      av_get_bits_per_sample(codec->codec_id) >> 3;
298             break;
299         case AVMEDIA_TYPE_VIDEO:
300             if ((codec->width <= 0 || codec->height <= 0) &&
301                 !(of->flags & AVFMT_NODIMENSIONS)) {
302                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
303                 ret = AVERROR(EINVAL);
304                 goto fail;
305             }
306             if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
307                 && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
308             ) {
309                 if (st->sample_aspect_ratio.num != 0 &&
310                     st->sample_aspect_ratio.den != 0 &&
311                     codec->sample_aspect_ratio.num != 0 &&
312                     codec->sample_aspect_ratio.den != 0) {
313                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
314                            "(%d/%d) and encoder layer (%d/%d)\n",
315                            st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
316                            codec->sample_aspect_ratio.num,
317                            codec->sample_aspect_ratio.den);
318                     ret = AVERROR(EINVAL);
319                     goto fail;
320                 }
321             }
322             break;
323         }
324
325         if (of->codec_tag) {
326             if (   codec->codec_tag
327                 && codec->codec_id == AV_CODEC_ID_RAWVIDEO
328                 && (   av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
329                     || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
330                 && !validate_codec_tag(s, st)) {
331                 // the current rawvideo encoding system ends up setting
332                 // the wrong codec_tag for avi/mov, we override it here
333                 codec->codec_tag = 0;
334             }
335             if (codec->codec_tag) {
336                 if (!validate_codec_tag(s, st)) {
337                     char tagbuf[32], tagbuf2[32];
338                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
339                     av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
340                     av_log(s, AV_LOG_ERROR,
341                            "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
342                            tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
343                     ret = AVERROR_INVALIDDATA;
344                     goto fail;
345                 }
346             } else
347                 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
348         }
349
350         if (of->flags & AVFMT_GLOBALHEADER &&
351             !(codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER))
352             av_log(s, AV_LOG_WARNING,
353                    "Codec for stream %d does not use global headers "
354                    "but container format requires global headers\n", i);
355
356         if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
357             s->internal->nb_interleaved_streams++;
358     }
359
360     if (!s->priv_data && of->priv_data_size > 0) {
361         s->priv_data = av_mallocz(of->priv_data_size);
362         if (!s->priv_data) {
363             ret = AVERROR(ENOMEM);
364             goto fail;
365         }
366         if (of->priv_class) {
367             *(const AVClass **)s->priv_data = of->priv_class;
368             av_opt_set_defaults(s->priv_data);
369             if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
370                 goto fail;
371         }
372     }
373
374     /* set muxer identification string */
375     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
376         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
377     } else {
378         av_dict_set(&s->metadata, "encoder", NULL, 0);
379     }
380
381     for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
382         av_dict_set(&s->metadata, e->key, NULL, 0);
383     }
384
385     if (options) {
386          av_dict_free(options);
387          *options = tmp;
388     }
389
390     return 0;
391
392 fail:
393     av_dict_free(&tmp);
394     return ret;
395 }
396
397 static int init_pts(AVFormatContext *s)
398 {
399     int i;
400     AVStream *st;
401
402     /* init PTS generation */
403     for (i = 0; i < s->nb_streams; i++) {
404         int64_t den = AV_NOPTS_VALUE;
405         st = s->streams[i];
406
407         switch (st->codec->codec_type) {
408         case AVMEDIA_TYPE_AUDIO:
409             den = (int64_t)st->time_base.num * st->codec->sample_rate;
410             break;
411         case AVMEDIA_TYPE_VIDEO:
412             den = (int64_t)st->time_base.num * st->codec->time_base.den;
413             break;
414         default:
415             break;
416         }
417
418         if (!st->priv_pts)
419             st->priv_pts = av_mallocz(sizeof(*st->priv_pts));
420         if (!st->priv_pts)
421             return AVERROR(ENOMEM);
422
423         if (den != AV_NOPTS_VALUE) {
424             if (den <= 0)
425                 return AVERROR_INVALIDDATA;
426
427             frac_init(st->priv_pts, 0, 0, den);
428         }
429     }
430
431     return 0;
432 }
433
434 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
435 {
436     int ret = 0;
437
438     if ((ret = init_muxer(s, options)) < 0)
439         return ret;
440
441     if (s->oformat->write_header) {
442         ret = s->oformat->write_header(s);
443         if (ret >= 0 && s->pb && s->pb->error < 0)
444             ret = s->pb->error;
445         if (ret < 0)
446             return ret;
447         if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
448             avio_flush(s->pb);
449     }
450
451     if ((ret = init_pts(s)) < 0)
452         return ret;
453
454     if (s->avoid_negative_ts < 0) {
455         av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
456         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
457             s->avoid_negative_ts = 0;
458         } else
459             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
460     }
461
462     return 0;
463 }
464
465 #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
466
467 /* Note: using sizeof(AVFrame) from outside lavu is unsafe in general, but
468    it is only being used internally to this file as a consistency check.
469    The value is chosen to be very unlikely to appear on its own and to cause
470    immediate failure if used anywhere as a real size. */
471 #define UNCODED_FRAME_PACKET_SIZE (INT_MIN / 3 * 2 + (int)sizeof(AVFrame))
472
473
474 //FIXME merge with compute_pkt_fields
475 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
476 {
477     int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
478     int num, den, i;
479     int frame_size;
480
481     if (s->debug & FF_FDEBUG_TS)
482         av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
483             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
484
485     if (pkt->duration < 0 && st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) {
486         av_log(s, AV_LOG_WARNING, "Packet with invalid duration %d in stream %d\n",
487                pkt->duration, pkt->stream_index);
488         pkt->duration = 0;
489     }
490
491     /* duration field */
492     if (pkt->duration == 0) {
493         ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
494         if (den && num) {
495             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
496         }
497     }
498
499     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
500         pkt->pts = pkt->dts;
501
502     //XXX/FIXME this is a temporary hack until all encoders output pts
503     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
504         static int warned;
505         if (!warned) {
506             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
507             warned = 1;
508         }
509         pkt->dts =
510 //        pkt->pts= st->cur_dts;
511             pkt->pts = st->priv_pts->val;
512     }
513
514     //calculate dts from pts
515     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
516         st->pts_buffer[0] = pkt->pts;
517         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
518             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
519         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
520             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
521
522         pkt->dts = st->pts_buffer[0];
523     }
524
525     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
526         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
527           st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE &&
528           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
529         av_log(s, AV_LOG_ERROR,
530                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
531                st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
532         return AVERROR(EINVAL);
533     }
534     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
535         av_log(s, AV_LOG_ERROR,
536                "pts (%s) < dts (%s) in stream %d\n",
537                av_ts2str(pkt->pts), av_ts2str(pkt->dts),
538                st->index);
539         return AVERROR(EINVAL);
540     }
541
542     if (s->debug & FF_FDEBUG_TS)
543         av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%s dts2:%s\n",
544             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
545
546     st->cur_dts = pkt->dts;
547     st->priv_pts->val = pkt->dts;
548
549     /* update pts */
550     switch (st->codec->codec_type) {
551     case AVMEDIA_TYPE_AUDIO:
552         frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
553                      ((AVFrame *)pkt->data)->nb_samples :
554                      av_get_audio_frame_duration(st->codec, pkt->size);
555
556         /* HACK/FIXME, we skip the initial 0 size packets as they are most
557          * likely equal to the encoder delay, but it would be better if we
558          * had the real timestamps from the encoder */
559         if (frame_size >= 0 && (pkt->size || st->priv_pts->num != st->priv_pts->den >> 1 || st->priv_pts->val)) {
560             frac_add(st->priv_pts, (int64_t)st->time_base.den * frame_size);
561         }
562         break;
563     case AVMEDIA_TYPE_VIDEO:
564         frac_add(st->priv_pts, (int64_t)st->time_base.den * st->codec->time_base.num);
565         break;
566     }
567     return 0;
568 }
569
570 /**
571  * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
572  * sidedata.
573  *
574  * FIXME: this function should NEVER get undefined pts/dts beside when the
575  * AVFMT_NOTIMESTAMPS is set.
576  * Those additional safety checks should be dropped once the correct checks
577  * are set in the callers.
578  */
579 static int write_packet(AVFormatContext *s, AVPacket *pkt)
580 {
581     int ret, did_split;
582
583     if (s->output_ts_offset) {
584         AVStream *st = s->streams[pkt->stream_index];
585         int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
586
587         if (pkt->dts != AV_NOPTS_VALUE)
588             pkt->dts += offset;
589         if (pkt->pts != AV_NOPTS_VALUE)
590             pkt->pts += offset;
591     }
592
593     if (s->avoid_negative_ts > 0) {
594         AVStream *st = s->streams[pkt->stream_index];
595         int64_t offset = st->mux_ts_offset;
596         int64_t ts = s->internal->avoid_negative_ts_use_pts ? pkt->pts : pkt->dts;
597
598         if (s->internal->offset == AV_NOPTS_VALUE && ts != AV_NOPTS_VALUE &&
599             (ts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
600             s->internal->offset = -ts;
601             s->internal->offset_timebase = st->time_base;
602         }
603
604         if (s->internal->offset != AV_NOPTS_VALUE && !offset) {
605             offset = st->mux_ts_offset =
606                 av_rescale_q_rnd(s->internal->offset,
607                                  s->internal->offset_timebase,
608                                  st->time_base,
609                                  AV_ROUND_UP);
610         }
611
612         if (pkt->dts != AV_NOPTS_VALUE)
613             pkt->dts += offset;
614         if (pkt->pts != AV_NOPTS_VALUE)
615             pkt->pts += offset;
616
617         if (s->internal->avoid_negative_ts_use_pts) {
618             if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
619                 av_log(s, AV_LOG_WARNING, "failed to avoid negative "
620                     "pts %s in stream %d.\n"
621                     "Try -avoid_negative_ts 1 as a possible workaround.\n",
622                     av_ts2str(pkt->dts),
623                     pkt->stream_index
624                 );
625             }
626         } else {
627             av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0 || s->max_interleave_delta > 0);
628             if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
629                 av_log(s, AV_LOG_WARNING,
630                     "Packets poorly interleaved, failed to avoid negative "
631                     "timestamp %s in stream %d.\n"
632                     "Try -max_interleave_delta 0 as a possible workaround.\n",
633                     av_ts2str(pkt->dts),
634                     pkt->stream_index
635                 );
636             }
637         }
638     }
639
640     did_split = av_packet_split_side_data(pkt);
641     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
642         AVFrame *frame = (AVFrame *)pkt->data;
643         av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
644         ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, &frame, 0);
645         av_frame_free(&frame);
646     } else {
647         ret = s->oformat->write_packet(s, pkt);
648     }
649
650     if (s->flush_packets && s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
651         avio_flush(s->pb);
652
653     if (did_split)
654         av_packet_merge_side_data(pkt);
655
656     return ret;
657 }
658
659 static int check_packet(AVFormatContext *s, AVPacket *pkt)
660 {
661     if (!pkt)
662         return 0;
663
664     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
665         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
666                pkt->stream_index);
667         return AVERROR(EINVAL);
668     }
669
670     if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
671         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
672         return AVERROR(EINVAL);
673     }
674
675     return 0;
676 }
677
678 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
679 {
680     int ret;
681
682     ret = check_packet(s, pkt);
683     if (ret < 0)
684         return ret;
685
686     if (!pkt) {
687         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
688             ret = s->oformat->write_packet(s, NULL);
689             if (s->flush_packets && s->pb && s->pb->error >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
690                 avio_flush(s->pb);
691             if (ret >= 0 && s->pb && s->pb->error < 0)
692                 ret = s->pb->error;
693             return ret;
694         }
695         return 1;
696     }
697
698     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
699
700     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
701         return ret;
702
703     ret = write_packet(s, pkt);
704     if (ret >= 0 && s->pb && s->pb->error < 0)
705         ret = s->pb->error;
706
707     if (ret >= 0)
708         s->streams[pkt->stream_index]->nb_frames++;
709     return ret;
710 }
711
712 #define CHUNK_START 0x1000
713
714 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
715                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
716 {
717     int ret;
718     AVPacketList **next_point, *this_pktl;
719     AVStream *st   = s->streams[pkt->stream_index];
720     int chunked    = s->max_chunk_size || s->max_chunk_duration;
721
722     this_pktl      = av_mallocz(sizeof(AVPacketList));
723     if (!this_pktl)
724         return AVERROR(ENOMEM);
725     this_pktl->pkt = *pkt;
726 #if FF_API_DESTRUCT_PACKET
727 FF_DISABLE_DEPRECATION_WARNINGS
728     pkt->destruct  = NULL;           // do not free original but only the copy
729 FF_ENABLE_DEPRECATION_WARNINGS
730 #endif
731     pkt->buf       = NULL;
732     pkt->side_data = NULL;
733     pkt->side_data_elems = 0;
734     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
735         av_assert0(pkt->size == UNCODED_FRAME_PACKET_SIZE);
736         av_assert0(((AVFrame *)pkt->data)->buf);
737     } else {
738         // Duplicate the packet if it uses non-allocated memory
739         if ((ret = av_dup_packet(&this_pktl->pkt)) < 0) {
740             av_free(this_pktl);
741             return ret;
742         }
743     }
744
745     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
746         next_point = &(st->last_in_packet_buffer->next);
747     } else {
748         next_point = &s->internal->packet_buffer;
749     }
750
751     if (chunked) {
752         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
753         st->interleaver_chunk_size     += pkt->size;
754         st->interleaver_chunk_duration += pkt->duration;
755         if (   (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
756             || (max && st->interleaver_chunk_duration           > max)) {
757             st->interleaver_chunk_size      = 0;
758             this_pktl->pkt.flags |= CHUNK_START;
759             if (max && st->interleaver_chunk_duration > max) {
760                 int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
761                 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
762
763                 st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
764             } else
765                 st->interleaver_chunk_duration = 0;
766         }
767     }
768     if (*next_point) {
769         if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
770             goto next_non_null;
771
772         if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
773             while (   *next_point
774                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
775                        || !compare(s, &(*next_point)->pkt, pkt)))
776                 next_point = &(*next_point)->next;
777             if (*next_point)
778                 goto next_non_null;
779         } else {
780             next_point = &(s->internal->packet_buffer_end->next);
781         }
782     }
783     av_assert1(!*next_point);
784
785     s->internal->packet_buffer_end = this_pktl;
786 next_non_null:
787
788     this_pktl->next = *next_point;
789
790     s->streams[pkt->stream_index]->last_in_packet_buffer =
791         *next_point                                      = this_pktl;
792
793     return 0;
794 }
795
796 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
797                                   AVPacket *pkt)
798 {
799     AVStream *st  = s->streams[pkt->stream_index];
800     AVStream *st2 = s->streams[next->stream_index];
801     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
802                                   st->time_base);
803     if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
804         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);
805         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);
806         if (ts == ts2) {
807             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
808                -( 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;
809             ts2=0;
810         }
811         comp= (ts>ts2) - (ts<ts2);
812     }
813
814     if (comp == 0)
815         return pkt->stream_index < next->stream_index;
816     return comp > 0;
817 }
818
819 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
820                                  AVPacket *pkt, int flush)
821 {
822     AVPacketList *pktl;
823     int stream_count = 0;
824     int noninterleaved_count = 0;
825     int i, ret;
826
827     if (pkt) {
828         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
829             return ret;
830     }
831
832     for (i = 0; i < s->nb_streams; i++) {
833         if (s->streams[i]->last_in_packet_buffer) {
834             ++stream_count;
835         } else if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
836                    s->streams[i]->codec->codec_id != AV_CODEC_ID_VP8 &&
837                    s->streams[i]->codec->codec_id != AV_CODEC_ID_VP9) {
838             ++noninterleaved_count;
839         }
840     }
841
842     if (s->internal->nb_interleaved_streams == stream_count)
843         flush = 1;
844
845     if (s->max_interleave_delta > 0 &&
846         s->internal->packet_buffer &&
847         !flush &&
848         s->internal->nb_interleaved_streams == stream_count+noninterleaved_count
849     ) {
850         AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
851         int64_t delta_dts = INT64_MIN;
852         int64_t top_dts = av_rescale_q(top_pkt->dts,
853                                        s->streams[top_pkt->stream_index]->time_base,
854                                        AV_TIME_BASE_Q);
855
856         for (i = 0; i < s->nb_streams; i++) {
857             int64_t last_dts;
858             const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
859
860             if (!last)
861                 continue;
862
863             last_dts = av_rescale_q(last->pkt.dts,
864                                     s->streams[i]->time_base,
865                                     AV_TIME_BASE_Q);
866             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
867         }
868
869         if (delta_dts > s->max_interleave_delta) {
870             av_log(s, AV_LOG_DEBUG,
871                    "Delay between the first packet and last packet in the "
872                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
873                    delta_dts, s->max_interleave_delta);
874             flush = 1;
875         }
876     }
877
878     if (stream_count && flush) {
879         AVStream *st;
880         pktl = s->internal->packet_buffer;
881         *out = pktl->pkt;
882         st   = s->streams[out->stream_index];
883
884         s->internal->packet_buffer = pktl->next;
885         if (!s->internal->packet_buffer)
886             s->internal->packet_buffer_end = NULL;
887
888         if (st->last_in_packet_buffer == pktl)
889             st->last_in_packet_buffer = NULL;
890         av_freep(&pktl);
891
892         return 1;
893     } else {
894         av_init_packet(out);
895         return 0;
896     }
897 }
898
899 /**
900  * Interleave an AVPacket correctly so it can be muxed.
901  * @param out the interleaved packet will be output here
902  * @param in the input packet
903  * @param flush 1 if no further packets are available as input and all
904  *              remaining packets should be output
905  * @return 1 if a packet was output, 0 if no packet could be output,
906  *         < 0 if an error occurred
907  */
908 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
909 {
910     if (s->oformat->interleave_packet) {
911         int ret = s->oformat->interleave_packet(s, out, in, flush);
912         if (in)
913             av_free_packet(in);
914         return ret;
915     } else
916         return ff_interleave_packet_per_dts(s, out, in, flush);
917 }
918
919 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
920 {
921     int ret, flush = 0;
922
923     ret = check_packet(s, pkt);
924     if (ret < 0)
925         goto fail;
926
927     if (pkt) {
928         AVStream *st = s->streams[pkt->stream_index];
929
930         if (s->debug & FF_FDEBUG_TS)
931             av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
932                 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
933
934         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
935             goto fail;
936
937         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
938             ret = AVERROR(EINVAL);
939             goto fail;
940         }
941     } else {
942         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
943         flush = 1;
944     }
945
946     for (;; ) {
947         AVPacket opkt;
948         int ret = interleave_packet(s, &opkt, pkt, flush);
949         if (pkt) {
950             memset(pkt, 0, sizeof(*pkt));
951             av_init_packet(pkt);
952             pkt = NULL;
953         }
954         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
955             return ret;
956
957         ret = write_packet(s, &opkt);
958         if (ret >= 0)
959             s->streams[opkt.stream_index]->nb_frames++;
960
961         av_free_packet(&opkt);
962
963         if (ret < 0)
964             return ret;
965         if(s->pb && s->pb->error)
966             return s->pb->error;
967     }
968 fail:
969     av_packet_unref(pkt);
970     return ret;
971 }
972
973 int av_write_trailer(AVFormatContext *s)
974 {
975     int ret, i;
976
977     for (;; ) {
978         AVPacket pkt;
979         ret = interleave_packet(s, &pkt, NULL, 1);
980         if (ret < 0)
981             goto fail;
982         if (!ret)
983             break;
984
985         ret = write_packet(s, &pkt);
986         if (ret >= 0)
987             s->streams[pkt.stream_index]->nb_frames++;
988
989         av_free_packet(&pkt);
990
991         if (ret < 0)
992             goto fail;
993         if(s->pb && s->pb->error)
994             goto fail;
995     }
996
997 fail:
998     if (s->oformat->write_trailer)
999         if (ret >= 0) {
1000         ret = s->oformat->write_trailer(s);
1001         } else {
1002             s->oformat->write_trailer(s);
1003         }
1004
1005     if (s->pb)
1006        avio_flush(s->pb);
1007     if (ret == 0)
1008        ret = s->pb ? s->pb->error : 0;
1009     for (i = 0; i < s->nb_streams; i++) {
1010         av_freep(&s->streams[i]->priv_data);
1011         av_freep(&s->streams[i]->index_entries);
1012     }
1013     if (s->oformat->priv_class)
1014         av_opt_free(s->priv_data);
1015     av_freep(&s->priv_data);
1016     return ret;
1017 }
1018
1019 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
1020                             int64_t *dts, int64_t *wall)
1021 {
1022     if (!s->oformat || !s->oformat->get_output_timestamp)
1023         return AVERROR(ENOSYS);
1024     s->oformat->get_output_timestamp(s, stream, dts, wall);
1025     return 0;
1026 }
1027
1028 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
1029                      AVFormatContext *src, int interleave)
1030 {
1031     AVPacket local_pkt;
1032     int ret;
1033
1034     local_pkt = *pkt;
1035     local_pkt.stream_index = dst_stream;
1036     if (pkt->pts != AV_NOPTS_VALUE)
1037         local_pkt.pts = av_rescale_q(pkt->pts,
1038                                      src->streams[pkt->stream_index]->time_base,
1039                                      dst->streams[dst_stream]->time_base);
1040     if (pkt->dts != AV_NOPTS_VALUE)
1041         local_pkt.dts = av_rescale_q(pkt->dts,
1042                                      src->streams[pkt->stream_index]->time_base,
1043                                      dst->streams[dst_stream]->time_base);
1044     if (pkt->duration)
1045         local_pkt.duration = av_rescale_q(pkt->duration,
1046                                           src->streams[pkt->stream_index]->time_base,
1047                                           dst->streams[dst_stream]->time_base);
1048
1049     if (interleave) ret = av_interleaved_write_frame(dst, &local_pkt);
1050     else            ret = av_write_frame(dst, &local_pkt);
1051     pkt->buf = local_pkt.buf;
1052     pkt->side_data       = local_pkt.side_data;
1053     pkt->side_data_elems = local_pkt.side_data_elems;
1054 #if FF_API_DESTRUCT_PACKET
1055 FF_DISABLE_DEPRECATION_WARNINGS
1056     pkt->destruct = local_pkt.destruct;
1057 FF_ENABLE_DEPRECATION_WARNINGS
1058 #endif
1059     return ret;
1060 }
1061
1062 static int av_write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
1063                                            AVFrame *frame, int interleaved)
1064 {
1065     AVPacket pkt, *pktp;
1066
1067     av_assert0(s->oformat);
1068     if (!s->oformat->write_uncoded_frame)
1069         return AVERROR(ENOSYS);
1070
1071     if (!frame) {
1072         pktp = NULL;
1073     } else {
1074         pktp = &pkt;
1075         av_init_packet(&pkt);
1076         pkt.data = (void *)frame;
1077         pkt.size         = UNCODED_FRAME_PACKET_SIZE;
1078         pkt.pts          =
1079         pkt.dts          = frame->pts;
1080         pkt.duration     = av_frame_get_pkt_duration(frame);
1081         pkt.stream_index = stream_index;
1082         pkt.flags |= AV_PKT_FLAG_UNCODED_FRAME;
1083     }
1084
1085     return interleaved ? av_interleaved_write_frame(s, pktp) :
1086                          av_write_frame(s, pktp);
1087 }
1088
1089 int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
1090                            AVFrame *frame)
1091 {
1092     return av_write_uncoded_frame_internal(s, stream_index, frame, 0);
1093 }
1094
1095 int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
1096                                        AVFrame *frame)
1097 {
1098     return av_write_uncoded_frame_internal(s, stream_index, frame, 1);
1099 }
1100
1101 int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
1102 {
1103     av_assert0(s->oformat);
1104     if (!s->oformat->write_uncoded_frame)
1105         return AVERROR(ENOSYS);
1106     return s->oformat->write_uncoded_frame(s, stream_index, NULL,
1107                                            AV_WRITE_UNCODED_FRAME_QUERY);
1108 }