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