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