]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
Merge commit '12db891dcd57b305d6e3c1e22ea8204dc26edda1'
[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/mathematics.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/time.h"
38 #include "riff.h"
39 #include "audiointerleave.h"
40 #include "url.h"
41 #include <stdarg.h>
42 #if CONFIG_NETWORK
43 #include "network.h"
44 #endif
45
46 #undef NDEBUG
47 #include <assert.h>
48
49 /**
50  * @file
51  * muxing functions for use within libavformat
52  */
53
54 /* fraction handling */
55
56 /**
57  * f = val + (num / den) + 0.5.
58  *
59  * 'num' is normalized so that it is such as 0 <= num < den.
60  *
61  * @param f fractional number
62  * @param val integer value
63  * @param num must be >= 0
64  * @param den must be >= 1
65  */
66 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
67 {
68     num += (den >> 1);
69     if (num >= den) {
70         val += num / den;
71         num  = num % den;
72     }
73     f->val = val;
74     f->num = num;
75     f->den = den;
76 }
77
78 /**
79  * Fractional addition to f: f = f + (incr / f->den).
80  *
81  * @param f fractional number
82  * @param incr increment, can be positive or negative
83  */
84 static void frac_add(AVFrac *f, int64_t incr)
85 {
86     int64_t num, den;
87
88     num = f->num + incr;
89     den = f->den;
90     if (num < 0) {
91         f->val += num / den;
92         num     = num % den;
93         if (num < 0) {
94             num += den;
95             f->val--;
96         }
97     } else if (num >= den) {
98         f->val += num / den;
99         num     = num % den;
100     }
101     f->num = num;
102 }
103
104 AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precission)
105 {
106     AVRational q;
107     int j;
108
109     if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
110         q = (AVRational){1, st->codec->sample_rate};
111     } else {
112         q = st->codec->time_base;
113     }
114     for (j=2; j<14; j+= 1+(j>2))
115         while (q.den / q.num < min_precission && q.num % j == 0)
116             q.num /= j;
117     while (q.den / q.num < min_precission && q.den < (1<<24))
118         q.den <<= 1;
119
120     return q;
121 }
122
123 int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,
124                                    const char *format, const char *filename)
125 {
126     AVFormatContext *s = avformat_alloc_context();
127     int ret = 0;
128
129     *avctx = NULL;
130     if (!s)
131         goto nomem;
132
133     if (!oformat) {
134         if (format) {
135             oformat = av_guess_format(format, NULL, NULL);
136             if (!oformat) {
137                 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
138                 ret = AVERROR(EINVAL);
139                 goto error;
140             }
141         } else {
142             oformat = av_guess_format(NULL, filename, NULL);
143             if (!oformat) {
144                 ret = AVERROR(EINVAL);
145                 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
146                        filename);
147                 goto error;
148             }
149         }
150     }
151
152     s->oformat = oformat;
153     if (s->oformat->priv_data_size > 0) {
154         s->priv_data = av_mallocz(s->oformat->priv_data_size);
155         if (!s->priv_data)
156             goto nomem;
157         if (s->oformat->priv_class) {
158             *(const AVClass**)s->priv_data= s->oformat->priv_class;
159             av_opt_set_defaults(s->priv_data);
160         }
161     } else
162         s->priv_data = NULL;
163
164     if (filename)
165         av_strlcpy(s->filename, filename, sizeof(s->filename));
166     *avctx = s;
167     return 0;
168 nomem:
169     av_log(s, AV_LOG_ERROR, "Out of memory\n");
170     ret = AVERROR(ENOMEM);
171 error:
172     avformat_free_context(s);
173     return ret;
174 }
175
176 #if FF_API_ALLOC_OUTPUT_CONTEXT
177 AVFormatContext *avformat_alloc_output_context(const char *format,
178                                                AVOutputFormat *oformat, const char *filename)
179 {
180     AVFormatContext *avctx;
181     int ret = avformat_alloc_output_context2(&avctx, oformat, format, filename);
182     return ret < 0 ? NULL : avctx;
183 }
184 #endif
185
186 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
187 {
188     const AVCodecTag *avctag;
189     int n;
190     enum AVCodecID id = AV_CODEC_ID_NONE;
191     unsigned int tag  = 0;
192
193     /**
194      * Check that tag + id is in the table
195      * If neither is in the table -> OK
196      * If tag is in the table with another id -> FAIL
197      * If id is in the table with another tag -> FAIL unless strict < normal
198      */
199     for (n = 0; s->oformat->codec_tag[n]; n++) {
200         avctag = s->oformat->codec_tag[n];
201         while (avctag->id != AV_CODEC_ID_NONE) {
202             if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
203                 id = avctag->id;
204                 if (id == st->codec->codec_id)
205                     return 1;
206             }
207             if (avctag->id == st->codec->codec_id)
208                 tag = avctag->tag;
209             avctag++;
210         }
211     }
212     if (id != AV_CODEC_ID_NONE)
213         return 0;
214     if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
215         return 0;
216     return 1;
217 }
218
219
220 static int init_muxer(AVFormatContext *s, AVDictionary **options)
221 {
222     int ret = 0, i;
223     AVStream *st;
224     AVDictionary *tmp = NULL;
225     AVCodecContext *codec = NULL;
226     AVOutputFormat *of = s->oformat;
227
228     if (options)
229         av_dict_copy(&tmp, *options, 0);
230
231     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
232         goto fail;
233     if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
234         (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
235         goto fail;
236
237     // some sanity checks
238     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
239         av_log(s, AV_LOG_ERROR, "no streams\n");
240         ret = AVERROR(EINVAL);
241         goto fail;
242     }
243
244     for (i = 0; i < s->nb_streams; i++) {
245         st    = s->streams[i];
246         codec = st->codec;
247
248         switch (codec->codec_type) {
249         case AVMEDIA_TYPE_AUDIO:
250             if (codec->sample_rate <= 0) {
251                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
252                 ret = AVERROR(EINVAL);
253                 goto fail;
254             }
255             if (!codec->block_align)
256                 codec->block_align = codec->channels *
257                                      av_get_bits_per_sample(codec->codec_id) >> 3;
258             break;
259         case AVMEDIA_TYPE_VIDEO:
260             if (codec->time_base.num <= 0 ||
261                 codec->time_base.den <= 0) { //FIXME audio too?
262                 av_log(s, AV_LOG_ERROR, "time base not set\n");
263                 ret = AVERROR(EINVAL);
264                 goto fail;
265             }
266
267             if ((codec->width <= 0 || codec->height <= 0) &&
268                 !(of->flags & AVFMT_NODIMENSIONS)) {
269                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
270                 ret = AVERROR(EINVAL);
271                 goto fail;
272             }
273             if (av_cmp_q(st->sample_aspect_ratio, codec->sample_aspect_ratio)
274                 && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
275             ) {
276                 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
277                                         "(%d/%d) and encoder layer (%d/%d)\n",
278                        st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
279                        codec->sample_aspect_ratio.num,
280                        codec->sample_aspect_ratio.den);
281                 ret = AVERROR(EINVAL);
282                 goto fail;
283             }
284             break;
285         }
286
287         if (of->codec_tag) {
288             if (   codec->codec_tag
289                 && codec->codec_id == AV_CODEC_ID_RAWVIDEO
290                 && (   av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
291                     || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
292                 && !validate_codec_tag(s, st)) {
293                 // the current rawvideo encoding system ends up setting
294                 // the wrong codec_tag for avi/mov, we override it here
295                 codec->codec_tag = 0;
296             }
297             if (codec->codec_tag) {
298                 if (!validate_codec_tag(s, st)) {
299                     char tagbuf[32], cortag[32];
300                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
301                     av_get_codec_tag_string(cortag, sizeof(cortag), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
302                     av_log(s, AV_LOG_ERROR,
303                            "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
304                            tagbuf, codec->codec_tag, codec->codec_id, cortag);
305                     ret = AVERROR_INVALIDDATA;
306                     goto fail;
307                 }
308             } else
309                 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
310         }
311
312         if (of->flags & AVFMT_GLOBALHEADER &&
313             !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
314             av_log(s, AV_LOG_WARNING,
315                    "Codec for stream %d does not use global headers "
316                    "but container format requires global headers\n", i);
317     }
318
319     if (!s->priv_data && of->priv_data_size > 0) {
320         s->priv_data = av_mallocz(of->priv_data_size);
321         if (!s->priv_data) {
322             ret = AVERROR(ENOMEM);
323             goto fail;
324         }
325         if (of->priv_class) {
326             *(const AVClass **)s->priv_data = of->priv_class;
327             av_opt_set_defaults(s->priv_data);
328             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
329                 goto fail;
330         }
331     }
332
333     /* set muxer identification string */
334     if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
335         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
336     }
337
338     if (options) {
339          av_dict_free(options);
340          *options = tmp;
341     }
342
343     return 0;
344
345 fail:
346     av_dict_free(&tmp);
347     return ret;
348 }
349
350 static int init_pts(AVFormatContext *s)
351 {
352     int i;
353     AVStream *st;
354
355     /* init PTS generation */
356     for (i = 0; i < s->nb_streams; i++) {
357         int64_t den = AV_NOPTS_VALUE;
358         st = s->streams[i];
359
360         switch (st->codec->codec_type) {
361         case AVMEDIA_TYPE_AUDIO:
362             den = (int64_t)st->time_base.num * st->codec->sample_rate;
363             break;
364         case AVMEDIA_TYPE_VIDEO:
365             den = (int64_t)st->time_base.num * st->codec->time_base.den;
366             break;
367         default:
368             break;
369         }
370         if (den != AV_NOPTS_VALUE) {
371             if (den <= 0)
372                 return AVERROR_INVALIDDATA;
373
374             frac_init(&st->pts, 0, 0, den);
375         }
376     }
377
378     return 0;
379 }
380
381 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
382 {
383     int ret = 0;
384
385     if (ret = init_muxer(s, options))
386         return ret;
387
388     if (s->oformat->write_header) {
389         ret = s->oformat->write_header(s);
390         if (ret >= 0 && s->pb && s->pb->error < 0)
391             ret = s->pb->error;
392         if (ret < 0)
393             return ret;
394     }
395
396     if ((ret = init_pts(s)) < 0)
397         return ret;
398
399     if (s->avoid_negative_ts < 0) {
400         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
401             s->avoid_negative_ts = 0;
402         } else
403             s->avoid_negative_ts = 1;
404     }
405
406     return 0;
407 }
408
409 //FIXME merge with compute_pkt_fields
410 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
411 {
412     int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
413     int num, den, frame_size, i;
414
415     av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
416             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
417
418     /* duration field */
419     if (pkt->duration == 0) {
420         ff_compute_frame_duration(&num, &den, st, NULL, pkt);
421         if (den && num) {
422             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
423         }
424     }
425
426     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
427         pkt->pts = pkt->dts;
428
429     //XXX/FIXME this is a temporary hack until all encoders output pts
430     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
431         static int warned;
432         if (!warned) {
433             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
434             warned = 1;
435         }
436         pkt->dts =
437 //        pkt->pts= st->cur_dts;
438             pkt->pts = st->pts.val;
439     }
440
441     //calculate dts from pts
442     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
443         st->pts_buffer[0] = pkt->pts;
444         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
445             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
446         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
447             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
448
449         pkt->dts = st->pts_buffer[0];
450     }
451
452     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
453         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
454           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
455         av_log(s, AV_LOG_ERROR,
456                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
457                st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
458         return AVERROR(EINVAL);
459     }
460     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
461         av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
462                av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
463         return AVERROR(EINVAL);
464     }
465
466     av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
467             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
468     st->cur_dts = pkt->dts;
469     st->pts.val = pkt->dts;
470
471     /* update pts */
472     switch (st->codec->codec_type) {
473     case AVMEDIA_TYPE_AUDIO:
474         frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
475
476         /* HACK/FIXME, we skip the initial 0 size packets as they are most
477          * likely equal to the encoder delay, but it would be better if we
478          * had the real timestamps from the encoder */
479         if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
480             frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
481         }
482         break;
483     case AVMEDIA_TYPE_VIDEO:
484         frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
485         break;
486     default:
487         break;
488     }
489     return 0;
490 }
491
492 /**
493  * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
494  * sidedata.
495  *
496  * FIXME: this function should NEVER get undefined pts/dts beside when the
497  * AVFMT_NOTIMESTAMPS is set.
498  * Those additional safety checks should be dropped once the correct checks
499  * are set in the callers.
500  */
501 static int write_packet(AVFormatContext *s, AVPacket *pkt)
502 {
503     int ret, did_split;
504
505     if (s->avoid_negative_ts > 0) {
506         AVStream *st = s->streams[pkt->stream_index];
507         int64_t offset = st->mux_ts_offset;
508
509         if (pkt->dts < 0 && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
510             s->offset = -pkt->dts;
511             s->offset_timebase = st->time_base;
512         }
513
514         if (s->offset && !offset) {
515             offset = st->mux_ts_offset =
516                 av_rescale_q_rnd(s->offset,
517                                  s->offset_timebase,
518                                  st->time_base,
519                                  AV_ROUND_UP);
520         }
521
522         if (pkt->dts != AV_NOPTS_VALUE)
523             pkt->dts += offset;
524         if (pkt->pts != AV_NOPTS_VALUE)
525             pkt->pts += offset;
526
527         av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
528     }
529
530     did_split = av_packet_split_side_data(pkt);
531     ret = s->oformat->write_packet(s, pkt);
532     if (s->flush_packets && s->pb && s->pb->error >= 0)
533         avio_flush(s->pb);
534     if (did_split)
535         av_packet_merge_side_data(pkt);
536     return ret;
537 }
538
539 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
540 {
541     int ret;
542
543     if (!pkt) {
544         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
545             ret = s->oformat->write_packet(s, NULL);
546             if (s->flush_packets && s->pb && s->pb->error >= 0)
547                 avio_flush(s->pb);
548             if (ret >= 0 && s->pb && s->pb->error < 0)
549                 ret = s->pb->error;
550             return ret;
551         }
552         return 1;
553     }
554
555     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
556
557     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
558         return ret;
559
560     ret = write_packet(s, pkt);
561     if (ret >= 0 && s->pb && s->pb->error < 0)
562         ret = s->pb->error;
563
564     if (ret >= 0)
565         s->streams[pkt->stream_index]->nb_frames++;
566     return ret;
567 }
568
569 #define CHUNK_START 0x1000
570
571 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
572                               int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
573 {
574     AVPacketList **next_point, *this_pktl;
575     AVStream *st   = s->streams[pkt->stream_index];
576     int chunked    = s->max_chunk_size || s->max_chunk_duration;
577
578     this_pktl      = av_mallocz(sizeof(AVPacketList));
579     if (!this_pktl)
580         return AVERROR(ENOMEM);
581     this_pktl->pkt = *pkt;
582 #if FF_API_DESTRUCT_PACKET
583     pkt->destruct  = NULL;           // do not free original but only the copy
584 #endif
585     pkt->buf       = NULL;
586     av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-allocated memory
587     av_copy_packet_side_data(&this_pktl->pkt, &this_pktl->pkt); // copy side data
588
589     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
590         next_point = &(st->last_in_packet_buffer->next);
591     } else {
592         next_point = &s->packet_buffer;
593     }
594
595     if (chunked) {
596         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
597         st->interleaver_chunk_size     += pkt->size;
598         st->interleaver_chunk_duration += pkt->duration;
599         if (   (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
600             || (max && st->interleaver_chunk_duration           > max)) {
601             st->interleaver_chunk_size      = 0;
602             this_pktl->pkt.flags |= CHUNK_START;
603             if (max && st->interleaver_chunk_duration > max) {
604                 int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
605                 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
606
607                 st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
608             } else
609                 st->interleaver_chunk_duration = 0;
610         }
611     }
612     if (*next_point) {
613         if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
614             goto next_non_null;
615
616         if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
617             while (   *next_point
618                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
619                        || !compare(s, &(*next_point)->pkt, pkt)))
620                 next_point = &(*next_point)->next;
621             if (*next_point)
622                 goto next_non_null;
623         } else {
624             next_point = &(s->packet_buffer_end->next);
625         }
626     }
627     av_assert1(!*next_point);
628
629     s->packet_buffer_end = this_pktl;
630 next_non_null:
631
632     this_pktl->next = *next_point;
633
634     s->streams[pkt->stream_index]->last_in_packet_buffer =
635         *next_point                                      = this_pktl;
636     return 0;
637 }
638
639 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
640                                   AVPacket *pkt)
641 {
642     AVStream *st  = s->streams[pkt->stream_index];
643     AVStream *st2 = s->streams[next->stream_index];
644     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
645                                   st->time_base);
646     if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
647         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);
648         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);
649         if (ts == ts2) {
650             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
651                -( 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;
652             ts2=0;
653         }
654         comp= (ts>ts2) - (ts<ts2);
655     }
656
657     if (comp == 0)
658         return pkt->stream_index < next->stream_index;
659     return comp > 0;
660 }
661
662 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
663                                  AVPacket *pkt, int flush)
664 {
665     AVPacketList *pktl;
666     int stream_count = 0, noninterleaved_count = 0;
667     int64_t delta_dts_max = 0;
668     int i, ret;
669
670     if (pkt) {
671         ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
672         if (ret < 0)
673             return ret;
674     }
675
676     for (i = 0; i < s->nb_streams; i++) {
677         if (s->streams[i]->last_in_packet_buffer) {
678             ++stream_count;
679         } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
680             ++noninterleaved_count;
681         }
682     }
683
684     if (s->nb_streams == stream_count) {
685         flush = 1;
686     } else if (!flush) {
687         for (i=0; i < s->nb_streams; i++) {
688             if (s->streams[i]->last_in_packet_buffer) {
689                 int64_t delta_dts =
690                     av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
691                                 s->streams[i]->time_base,
692                                 AV_TIME_BASE_Q) -
693                     av_rescale_q(s->packet_buffer->pkt.dts,
694                                 s->streams[s->packet_buffer->pkt.stream_index]->time_base,
695                                 AV_TIME_BASE_Q);
696                 delta_dts_max= FFMAX(delta_dts_max, delta_dts);
697             }
698         }
699         if (s->nb_streams == stream_count+noninterleaved_count &&
700            delta_dts_max > 20*AV_TIME_BASE) {
701             av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
702             flush = 1;
703         }
704     }
705     if (stream_count && flush) {
706         AVStream *st;
707         pktl = s->packet_buffer;
708         *out = pktl->pkt;
709         st   = s->streams[out->stream_index];
710
711         s->packet_buffer = pktl->next;
712         if (!s->packet_buffer)
713             s->packet_buffer_end = NULL;
714
715         if (st->last_in_packet_buffer == pktl)
716             st->last_in_packet_buffer = NULL;
717         av_freep(&pktl);
718
719         return 1;
720     } else {
721         av_init_packet(out);
722         return 0;
723     }
724 }
725
726 /**
727  * Interleave an AVPacket correctly so it can be muxed.
728  * @param out the interleaved packet will be output here
729  * @param in the input packet
730  * @param flush 1 if no further packets are available as input and all
731  *              remaining packets should be output
732  * @return 1 if a packet was output, 0 if no packet could be output,
733  *         < 0 if an error occurred
734  */
735 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
736 {
737     if (s->oformat->interleave_packet) {
738         int ret = s->oformat->interleave_packet(s, out, in, flush);
739         if (in)
740             av_free_packet(in);
741         return ret;
742     } else
743         return ff_interleave_packet_per_dts(s, out, in, flush);
744 }
745
746 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
747 {
748     int ret, flush = 0;
749
750     if (pkt) {
751         AVStream *st = s->streams[pkt->stream_index];
752
753         //FIXME/XXX/HACK drop zero sized packets
754         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
755             return 0;
756
757         av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
758                 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
759         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
760             return ret;
761
762         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
763             return AVERROR(EINVAL);
764     } else {
765         av_dlog(s, "av_interleaved_write_frame FLUSH\n");
766         flush = 1;
767     }
768
769     for (;; ) {
770         AVPacket opkt;
771         int ret = interleave_packet(s, &opkt, pkt, flush);
772         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
773             return ret;
774
775         ret = write_packet(s, &opkt);
776         if (ret >= 0)
777             s->streams[opkt.stream_index]->nb_frames++;
778
779         av_free_packet(&opkt);
780         pkt = NULL;
781
782         if (ret < 0)
783             return ret;
784         if(s->pb && s->pb->error)
785             return s->pb->error;
786     }
787 }
788
789 int av_write_trailer(AVFormatContext *s)
790 {
791     int ret, i;
792
793     for (;; ) {
794         AVPacket pkt;
795         ret = interleave_packet(s, &pkt, NULL, 1);
796         if (ret < 0) //FIXME cleanup needed for ret<0 ?
797             goto fail;
798         if (!ret)
799             break;
800
801         ret = write_packet(s, &pkt);
802         if (ret >= 0)
803             s->streams[pkt.stream_index]->nb_frames++;
804
805         av_free_packet(&pkt);
806
807         if (ret < 0)
808             goto fail;
809         if(s->pb && s->pb->error)
810             goto fail;
811     }
812
813     if (s->oformat->write_trailer)
814         ret = s->oformat->write_trailer(s);
815
816 fail:
817     if (s->pb)
818        avio_flush(s->pb);
819     if (ret == 0)
820        ret = s->pb ? s->pb->error : 0;
821     for (i = 0; i < s->nb_streams; i++) {
822         av_freep(&s->streams[i]->priv_data);
823         av_freep(&s->streams[i]->index_entries);
824     }
825     if (s->oformat->priv_class)
826         av_opt_free(s->priv_data);
827     av_freep(&s->priv_data);
828     return ret;
829 }
830
831 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
832                             int64_t *dts, int64_t *wall)
833 {
834     if (!s->oformat || !s->oformat->get_output_timestamp)
835         return AVERROR(ENOSYS);
836     s->oformat->get_output_timestamp(s, stream, dts, wall);
837     return 0;
838 }
839
840 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
841                      AVFormatContext *src)
842 {
843     AVPacket local_pkt;
844
845     local_pkt = *pkt;
846     local_pkt.stream_index = dst_stream;
847     if (pkt->pts != AV_NOPTS_VALUE)
848         local_pkt.pts = av_rescale_q(pkt->pts,
849                                      src->streams[pkt->stream_index]->time_base,
850                                      dst->streams[dst_stream]->time_base);
851     if (pkt->dts != AV_NOPTS_VALUE)
852         local_pkt.dts = av_rescale_q(pkt->dts,
853                                      src->streams[pkt->stream_index]->time_base,
854                                      dst->streams[dst_stream]->time_base);
855     if (pkt->duration)
856         local_pkt.duration = av_rescale_q(pkt->duration,
857                                           src->streams[pkt->stream_index]->time_base,
858                                           dst->streams[dst_stream]->time_base);
859     return av_write_frame(dst, &local_pkt);
860 }