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