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