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