]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
libxvid: add working lumimasking and variance AQ
[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                 if (st->sample_aspect_ratio.num != 0 &&
277                     st->sample_aspect_ratio.den != 0 &&
278                     codec->sample_aspect_ratio.den != 0 &&
279                     codec->sample_aspect_ratio.den != 0) {
280                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
281                            "(%d/%d) and encoder layer (%d/%d)\n",
282                            st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
283                            codec->sample_aspect_ratio.num,
284                            codec->sample_aspect_ratio.den);
285                     ret = AVERROR(EINVAL);
286                     goto fail;
287                 }
288             }
289             break;
290         }
291
292         if (of->codec_tag) {
293             if (   codec->codec_tag
294                 && codec->codec_id == AV_CODEC_ID_RAWVIDEO
295                 && (   av_codec_get_tag(of->codec_tag, codec->codec_id) == 0
296                     || av_codec_get_tag(of->codec_tag, codec->codec_id) == MKTAG('r', 'a', 'w', ' '))
297                 && !validate_codec_tag(s, st)) {
298                 // the current rawvideo encoding system ends up setting
299                 // the wrong codec_tag for avi/mov, we override it here
300                 codec->codec_tag = 0;
301             }
302             if (codec->codec_tag) {
303                 if (!validate_codec_tag(s, st)) {
304                     char tagbuf[32], tagbuf2[32];
305                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
306                     av_get_codec_tag_string(tagbuf2, sizeof(tagbuf2), av_codec_get_tag(s->oformat->codec_tag, codec->codec_id));
307                     av_log(s, AV_LOG_ERROR,
308                            "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",
309                            tagbuf, codec->codec_tag, codec->codec_id, tagbuf2);
310                     ret = AVERROR_INVALIDDATA;
311                     goto fail;
312                 }
313             } else
314                 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
315         }
316
317         if (of->flags & AVFMT_GLOBALHEADER &&
318             !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
319             av_log(s, AV_LOG_WARNING,
320                    "Codec for stream %d does not use global headers "
321                    "but container format requires global headers\n", i);
322     }
323
324     if (!s->priv_data && of->priv_data_size > 0) {
325         s->priv_data = av_mallocz(of->priv_data_size);
326         if (!s->priv_data) {
327             ret = AVERROR(ENOMEM);
328             goto fail;
329         }
330         if (of->priv_class) {
331             *(const AVClass **)s->priv_data = of->priv_class;
332             av_opt_set_defaults(s->priv_data);
333             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
334                 goto fail;
335         }
336     }
337
338     /* set muxer identification string */
339     if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
340         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
341     }
342
343     if (options) {
344          av_dict_free(options);
345          *options = tmp;
346     }
347
348     return 0;
349
350 fail:
351     av_dict_free(&tmp);
352     return ret;
353 }
354
355 static int init_pts(AVFormatContext *s)
356 {
357     int i;
358     AVStream *st;
359
360     /* init PTS generation */
361     for (i = 0; i < s->nb_streams; i++) {
362         int64_t den = AV_NOPTS_VALUE;
363         st = s->streams[i];
364
365         switch (st->codec->codec_type) {
366         case AVMEDIA_TYPE_AUDIO:
367             den = (int64_t)st->time_base.num * st->codec->sample_rate;
368             break;
369         case AVMEDIA_TYPE_VIDEO:
370             den = (int64_t)st->time_base.num * st->codec->time_base.den;
371             break;
372         default:
373             break;
374         }
375         if (den != AV_NOPTS_VALUE) {
376             if (den <= 0)
377                 return AVERROR_INVALIDDATA;
378
379             frac_init(&st->pts, 0, 0, den);
380         }
381     }
382
383     return 0;
384 }
385
386 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
387 {
388     int ret = 0;
389
390     if (ret = init_muxer(s, options))
391         return ret;
392
393     if (s->oformat->write_header) {
394         ret = s->oformat->write_header(s);
395         if (ret >= 0 && s->pb && s->pb->error < 0)
396             ret = s->pb->error;
397         if (ret < 0)
398             return ret;
399     }
400
401     if ((ret = init_pts(s)) < 0)
402         return ret;
403
404     if (s->avoid_negative_ts < 0) {
405         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
406             s->avoid_negative_ts = 0;
407         } else
408             s->avoid_negative_ts = 1;
409     }
410
411     return 0;
412 }
413
414 //FIXME merge with compute_pkt_fields
415 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
416 {
417     int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
418     int num, den, frame_size, i;
419
420     av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
421             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
422
423     /* duration field */
424     if (pkt->duration == 0) {
425         ff_compute_frame_duration(&num, &den, st, NULL, pkt);
426         if (den && num) {
427             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
428         }
429     }
430
431     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
432         pkt->pts = pkt->dts;
433
434     //XXX/FIXME this is a temporary hack until all encoders output pts
435     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
436         static int warned;
437         if (!warned) {
438             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
439             warned = 1;
440         }
441         pkt->dts =
442 //        pkt->pts= st->cur_dts;
443             pkt->pts = st->pts.val;
444     }
445
446     //calculate dts from pts
447     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
448         st->pts_buffer[0] = pkt->pts;
449         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
450             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
451         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
452             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
453
454         pkt->dts = st->pts_buffer[0];
455     }
456
457     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
458         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
459           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
460         av_log(s, AV_LOG_ERROR,
461                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
462                st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
463         return AVERROR(EINVAL);
464     }
465     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
466         av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
467                av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
468         return AVERROR(EINVAL);
469     }
470
471     av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
472             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
473     st->cur_dts = pkt->dts;
474     st->pts.val = pkt->dts;
475
476     /* update pts */
477     switch (st->codec->codec_type) {
478     case AVMEDIA_TYPE_AUDIO:
479         frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
480
481         /* HACK/FIXME, we skip the initial 0 size packets as they are most
482          * likely equal to the encoder delay, but it would be better if we
483          * had the real timestamps from the encoder */
484         if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
485             frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
486         }
487         break;
488     case AVMEDIA_TYPE_VIDEO:
489         frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
490         break;
491     default:
492         break;
493     }
494     return 0;
495 }
496
497 /**
498  * Make timestamps non negative, move side data from payload to internal struct, call muxer, and restore
499  * sidedata.
500  *
501  * FIXME: this function should NEVER get undefined pts/dts beside when the
502  * AVFMT_NOTIMESTAMPS is set.
503  * Those additional safety checks should be dropped once the correct checks
504  * are set in the callers.
505  */
506 static int write_packet(AVFormatContext *s, AVPacket *pkt)
507 {
508     int ret, did_split;
509
510     if (s->avoid_negative_ts > 0) {
511         AVStream *st = s->streams[pkt->stream_index];
512         int64_t offset = st->mux_ts_offset;
513
514         if (pkt->dts < 0 && pkt->dts != AV_NOPTS_VALUE && !s->offset) {
515             s->offset = -pkt->dts;
516             s->offset_timebase = st->time_base;
517         }
518
519         if (s->offset && !offset) {
520             offset = st->mux_ts_offset =
521                 av_rescale_q_rnd(s->offset,
522                                  s->offset_timebase,
523                                  st->time_base,
524                                  AV_ROUND_UP);
525         }
526
527         if (pkt->dts != AV_NOPTS_VALUE)
528             pkt->dts += offset;
529         if (pkt->pts != AV_NOPTS_VALUE)
530             pkt->pts += offset;
531
532         av_assert2(pkt->dts == AV_NOPTS_VALUE || pkt->dts >= 0);
533     }
534
535     did_split = av_packet_split_side_data(pkt);
536     ret = s->oformat->write_packet(s, pkt);
537     if (s->flush_packets && s->pb && s->pb->error >= 0)
538         avio_flush(s->pb);
539     if (did_split)
540         av_packet_merge_side_data(pkt);
541     return ret;
542 }
543
544 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
545 {
546     int ret;
547
548     if (!pkt) {
549         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
550             ret = s->oformat->write_packet(s, NULL);
551             if (s->flush_packets && s->pb && s->pb->error >= 0)
552                 avio_flush(s->pb);
553             if (ret >= 0 && s->pb && s->pb->error < 0)
554                 ret = s->pb->error;
555             return ret;
556         }
557         return 1;
558     }
559
560     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
561
562     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
563         return ret;
564
565     ret = write_packet(s, pkt);
566     if (ret >= 0 && s->pb && s->pb->error < 0)
567         ret = s->pb->error;
568
569     if (ret >= 0)
570         s->streams[pkt->stream_index]->nb_frames++;
571     return ret;
572 }
573
574 #define CHUNK_START 0x1000
575
576 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
577                               int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
578 {
579     AVPacketList **next_point, *this_pktl;
580     AVStream *st   = s->streams[pkt->stream_index];
581     int chunked    = s->max_chunk_size || s->max_chunk_duration;
582
583     this_pktl      = av_mallocz(sizeof(AVPacketList));
584     if (!this_pktl)
585         return AVERROR(ENOMEM);
586     this_pktl->pkt = *pkt;
587 #if FF_API_DESTRUCT_PACKET
588     pkt->destruct  = NULL;           // do not free original but only the copy
589 #endif
590     pkt->buf       = NULL;
591     av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-allocated memory
592     av_copy_packet_side_data(&this_pktl->pkt, &this_pktl->pkt); // copy side data
593
594     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
595         next_point = &(st->last_in_packet_buffer->next);
596     } else {
597         next_point = &s->packet_buffer;
598     }
599
600     if (chunked) {
601         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
602         st->interleaver_chunk_size     += pkt->size;
603         st->interleaver_chunk_duration += pkt->duration;
604         if (   (s->max_chunk_size && st->interleaver_chunk_size > s->max_chunk_size)
605             || (max && st->interleaver_chunk_duration           > max)) {
606             st->interleaver_chunk_size      = 0;
607             this_pktl->pkt.flags |= CHUNK_START;
608             if (max && st->interleaver_chunk_duration > max) {
609                 int64_t syncoffset = (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
610                 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
611
612                 st->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
613             } else
614                 st->interleaver_chunk_duration = 0;
615         }
616     }
617     if (*next_point) {
618         if (chunked && !(this_pktl->pkt.flags & CHUNK_START))
619             goto next_non_null;
620
621         if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
622             while (   *next_point
623                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
624                        || !compare(s, &(*next_point)->pkt, pkt)))
625                 next_point = &(*next_point)->next;
626             if (*next_point)
627                 goto next_non_null;
628         } else {
629             next_point = &(s->packet_buffer_end->next);
630         }
631     }
632     av_assert1(!*next_point);
633
634     s->packet_buffer_end = this_pktl;
635 next_non_null:
636
637     this_pktl->next = *next_point;
638
639     s->streams[pkt->stream_index]->last_in_packet_buffer =
640         *next_point                                      = this_pktl;
641     return 0;
642 }
643
644 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
645                                   AVPacket *pkt)
646 {
647     AVStream *st  = s->streams[pkt->stream_index];
648     AVStream *st2 = s->streams[next->stream_index];
649     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
650                                   st->time_base);
651     if (s->audio_preload && ((st->codec->codec_type == AVMEDIA_TYPE_AUDIO) != (st2->codec->codec_type == AVMEDIA_TYPE_AUDIO))) {
652         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);
653         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);
654         if (ts == ts2) {
655             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
656                -( 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;
657             ts2=0;
658         }
659         comp= (ts>ts2) - (ts<ts2);
660     }
661
662     if (comp == 0)
663         return pkt->stream_index < next->stream_index;
664     return comp > 0;
665 }
666
667 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
668                                  AVPacket *pkt, int flush)
669 {
670     AVPacketList *pktl;
671     int stream_count = 0, noninterleaved_count = 0;
672     int64_t delta_dts_max = 0;
673     int i, ret;
674
675     if (pkt) {
676         ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts);
677         if (ret < 0)
678             return ret;
679     }
680
681     for (i = 0; i < s->nb_streams; i++) {
682         if (s->streams[i]->last_in_packet_buffer) {
683             ++stream_count;
684         } else if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
685             ++noninterleaved_count;
686         }
687     }
688
689     if (s->nb_streams == stream_count) {
690         flush = 1;
691     } else if (!flush) {
692         for (i=0; i < s->nb_streams; i++) {
693             if (s->streams[i]->last_in_packet_buffer) {
694                 int64_t delta_dts =
695                     av_rescale_q(s->streams[i]->last_in_packet_buffer->pkt.dts,
696                                 s->streams[i]->time_base,
697                                 AV_TIME_BASE_Q) -
698                     av_rescale_q(s->packet_buffer->pkt.dts,
699                                 s->streams[s->packet_buffer->pkt.stream_index]->time_base,
700                                 AV_TIME_BASE_Q);
701                 delta_dts_max= FFMAX(delta_dts_max, delta_dts);
702             }
703         }
704         if (s->nb_streams == stream_count+noninterleaved_count &&
705            delta_dts_max > 20*AV_TIME_BASE) {
706             av_log(s, AV_LOG_DEBUG, "flushing with %d noninterleaved\n", noninterleaved_count);
707             flush = 1;
708         }
709     }
710     if (stream_count && flush) {
711         AVStream *st;
712         pktl = s->packet_buffer;
713         *out = pktl->pkt;
714         st   = s->streams[out->stream_index];
715
716         s->packet_buffer = pktl->next;
717         if (!s->packet_buffer)
718             s->packet_buffer_end = NULL;
719
720         if (st->last_in_packet_buffer == pktl)
721             st->last_in_packet_buffer = NULL;
722         av_freep(&pktl);
723
724         return 1;
725     } else {
726         av_init_packet(out);
727         return 0;
728     }
729 }
730
731 /**
732  * Interleave an AVPacket correctly so it can be muxed.
733  * @param out the interleaved packet will be output here
734  * @param in the input packet
735  * @param flush 1 if no further packets are available as input and all
736  *              remaining packets should be output
737  * @return 1 if a packet was output, 0 if no packet could be output,
738  *         < 0 if an error occurred
739  */
740 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
741 {
742     if (s->oformat->interleave_packet) {
743         int ret = s->oformat->interleave_packet(s, out, in, flush);
744         if (in)
745             av_free_packet(in);
746         return ret;
747     } else
748         return ff_interleave_packet_per_dts(s, out, in, flush);
749 }
750
751 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
752 {
753     int ret, flush = 0;
754
755     if (pkt) {
756         AVStream *st = s->streams[pkt->stream_index];
757
758         //FIXME/XXX/HACK drop zero sized packets
759         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
760             return 0;
761
762         av_dlog(s, "av_interleaved_write_frame size:%d dts:%s pts:%s\n",
763                 pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
764         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
765             return ret;
766
767         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
768             return AVERROR(EINVAL);
769     } else {
770         av_dlog(s, "av_interleaved_write_frame FLUSH\n");
771         flush = 1;
772     }
773
774     for (;; ) {
775         AVPacket opkt;
776         int ret = interleave_packet(s, &opkt, pkt, flush);
777         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
778             return ret;
779
780         ret = write_packet(s, &opkt);
781         if (ret >= 0)
782             s->streams[opkt.stream_index]->nb_frames++;
783
784         av_free_packet(&opkt);
785         pkt = NULL;
786
787         if (ret < 0)
788             return ret;
789         if(s->pb && s->pb->error)
790             return s->pb->error;
791     }
792 }
793
794 int av_write_trailer(AVFormatContext *s)
795 {
796     int ret, i;
797
798     for (;; ) {
799         AVPacket pkt;
800         ret = interleave_packet(s, &pkt, NULL, 1);
801         if (ret < 0) //FIXME cleanup needed for ret<0 ?
802             goto fail;
803         if (!ret)
804             break;
805
806         ret = write_packet(s, &pkt);
807         if (ret >= 0)
808             s->streams[pkt.stream_index]->nb_frames++;
809
810         av_free_packet(&pkt);
811
812         if (ret < 0)
813             goto fail;
814         if(s->pb && s->pb->error)
815             goto fail;
816     }
817
818     if (s->oformat->write_trailer)
819         ret = s->oformat->write_trailer(s);
820
821 fail:
822     if (s->pb)
823        avio_flush(s->pb);
824     if (ret == 0)
825        ret = s->pb ? s->pb->error : 0;
826     for (i = 0; i < s->nb_streams; i++) {
827         av_freep(&s->streams[i]->priv_data);
828         av_freep(&s->streams[i]->index_entries);
829     }
830     if (s->oformat->priv_class)
831         av_opt_free(s->priv_data);
832     av_freep(&s->priv_data);
833     return ret;
834 }
835
836 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
837                             int64_t *dts, int64_t *wall)
838 {
839     if (!s->oformat || !s->oformat->get_output_timestamp)
840         return AVERROR(ENOSYS);
841     s->oformat->get_output_timestamp(s, stream, dts, wall);
842     return 0;
843 }
844
845 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
846                      AVFormatContext *src)
847 {
848     AVPacket local_pkt;
849
850     local_pkt = *pkt;
851     local_pkt.stream_index = dst_stream;
852     if (pkt->pts != AV_NOPTS_VALUE)
853         local_pkt.pts = av_rescale_q(pkt->pts,
854                                      src->streams[pkt->stream_index]->time_base,
855                                      dst->streams[dst_stream]->time_base);
856     if (pkt->dts != AV_NOPTS_VALUE)
857         local_pkt.dts = av_rescale_q(pkt->dts,
858                                      src->streams[pkt->stream_index]->time_base,
859                                      dst->streams[dst_stream]->time_base);
860     if (pkt->duration)
861         local_pkt.duration = av_rescale_q(pkt->duration,
862                                           src->streams[pkt->stream_index]->time_base,
863                                           dst->streams[dst_stream]->time_base);
864     return av_write_frame(dst, &local_pkt);
865 }