]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
Ignore all generated example binaries
[ffmpeg] / libavformat / mux.c
1 /*
2  * muxing functions for use within Libav
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 "metadata.h"
31 #include "id3v2.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/time.h"
37 #include "riff.h"
38 #include "audiointerleave.h"
39 #include "url.h"
40 #include <stdarg.h>
41 #if CONFIG_NETWORK
42 #include "network.h"
43 #endif
44
45 #undef NDEBUG
46 #include <assert.h>
47
48 /**
49  * @file
50  * muxing functions for use within Libav
51  */
52
53 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
54 {
55     const AVCodecTag *avctag;
56     int n;
57     enum AVCodecID id = AV_CODEC_ID_NONE;
58     unsigned int tag  = 0;
59
60     /**
61      * Check that tag + id is in the table
62      * If neither is in the table -> OK
63      * If tag is in the table with another id -> FAIL
64      * If id is in the table with another tag -> FAIL unless strict < normal
65      */
66     for (n = 0; s->oformat->codec_tag[n]; n++) {
67         avctag = s->oformat->codec_tag[n];
68         while (avctag->id != AV_CODEC_ID_NONE) {
69             if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codecpar->codec_tag)) {
70                 id = avctag->id;
71                 if (id == st->codecpar->codec_id)
72                     return 1;
73             }
74             if (avctag->id == st->codecpar->codec_id)
75                 tag = avctag->tag;
76             avctag++;
77         }
78     }
79     if (id != AV_CODEC_ID_NONE)
80         return 0;
81     if (tag && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
82         return 0;
83     return 1;
84 }
85
86
87 static int init_muxer(AVFormatContext *s, AVDictionary **options)
88 {
89     int ret = 0, i;
90     AVStream *st;
91     AVDictionary *tmp = NULL;
92     AVCodecParameters *par = NULL;
93     AVOutputFormat *of = s->oformat;
94     const AVCodecDescriptor *desc;
95
96     if (options)
97         av_dict_copy(&tmp, *options, 0);
98
99     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
100         goto fail;
101
102 #if FF_API_LAVF_BITEXACT && FF_API_LAVF_AVCTX
103 FF_DISABLE_DEPRECATION_WARNINGS
104     if (s->nb_streams && s->streams[0]->codec->flags & AV_CODEC_FLAG_BITEXACT)
105         s->flags |= AVFMT_FLAG_BITEXACT;
106 FF_ENABLE_DEPRECATION_WARNINGS
107 #endif
108
109     // some sanity checks
110     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
111         av_log(s, AV_LOG_ERROR, "no streams\n");
112         ret = AVERROR(EINVAL);
113         goto fail;
114     }
115
116     for (i = 0; i < s->nb_streams; i++) {
117         st  = s->streams[i];
118         par = st->codecpar;
119
120 #if FF_API_LAVF_CODEC_TB && FF_API_LAVF_AVCTX
121 FF_DISABLE_DEPRECATION_WARNINGS
122         if (!st->time_base.num && st->codec->time_base.num) {
123             av_log(s, AV_LOG_WARNING, "Using AVStream.codec.time_base as a "
124                    "timebase hint to the muxer is deprecated. Set "
125                    "AVStream.time_base instead.\n");
126             avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
127         }
128 FF_ENABLE_DEPRECATION_WARNINGS
129 #endif
130
131 #if FF_API_LAVF_AVCTX
132 FF_DISABLE_DEPRECATION_WARNINGS
133         if (st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
134             st->codec->codec_type    != AVMEDIA_TYPE_UNKNOWN) {
135             av_log(s, AV_LOG_WARNING, "Using AVStream.codec to pass codec "
136                    "parameters to muxers is deprecated, use AVStream.codecpar "
137                    "instead.\n");
138             ret = avcodec_parameters_from_context(st->codecpar, st->codec);
139             if (ret < 0)
140                 goto fail;
141         }
142 FF_ENABLE_DEPRECATION_WARNINGS
143 #endif
144
145         if (!st->time_base.num) {
146             /* fall back on the default timebase values */
147             if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
148                 avpriv_set_pts_info(st, 64, 1, par->sample_rate);
149             else
150                 avpriv_set_pts_info(st, 33, 1, 90000);
151         }
152
153         switch (par->codec_type) {
154         case AVMEDIA_TYPE_AUDIO:
155             if (par->sample_rate <= 0) {
156                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
157                 ret = AVERROR(EINVAL);
158                 goto fail;
159             }
160             if (!par->block_align)
161                 par->block_align = par->channels *
162                                    av_get_bits_per_sample(par->codec_id) >> 3;
163             break;
164         case AVMEDIA_TYPE_VIDEO:
165             if ((par->width <= 0 || par->height <= 0) &&
166                 !(of->flags & AVFMT_NODIMENSIONS)) {
167                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
168                 ret = AVERROR(EINVAL);
169                 goto fail;
170             }
171
172             if (av_cmp_q(st->sample_aspect_ratio,
173                          par->sample_aspect_ratio)) {
174                 if (st->sample_aspect_ratio.num != 0 &&
175                     st->sample_aspect_ratio.den != 0 &&
176                     par->sample_aspect_ratio.den != 0 &&
177                     par->sample_aspect_ratio.den != 0) {
178                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
179                             "(%d/%d) and encoder layer (%d/%d)\n",
180                             st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
181                             par->sample_aspect_ratio.num,
182                             par->sample_aspect_ratio.den);
183                     ret = AVERROR(EINVAL);
184                     goto fail;
185                 }
186             }
187             break;
188         }
189
190         desc = avcodec_descriptor_get(par->codec_id);
191         if (desc && desc->props & AV_CODEC_PROP_REORDER)
192             st->internal->reorder = 1;
193
194         if (of->codec_tag) {
195             if (par->codec_tag &&
196                 par->codec_id == AV_CODEC_ID_RAWVIDEO &&
197                 !av_codec_get_tag(of->codec_tag, par->codec_id) &&
198                 !validate_codec_tag(s, st)) {
199                 // the current rawvideo encoding system ends up setting
200                 // the wrong codec_tag for avi, we override it here
201                 par->codec_tag = 0;
202             }
203             if (par->codec_tag) {
204                 if (!validate_codec_tag(s, st)) {
205                     char tagbuf[32];
206                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), par->codec_tag);
207                     av_log(s, AV_LOG_ERROR,
208                            "Tag %s/0x%08x incompatible with output codec id '%d'\n",
209                            tagbuf, par->codec_tag, par->codec_id);
210                     ret = AVERROR_INVALIDDATA;
211                     goto fail;
212                 }
213             } else
214                 par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
215         }
216
217         if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
218             s->internal->nb_interleaved_streams++;
219     }
220
221     if (!s->priv_data && of->priv_data_size > 0) {
222         s->priv_data = av_mallocz(of->priv_data_size);
223         if (!s->priv_data) {
224             ret = AVERROR(ENOMEM);
225             goto fail;
226         }
227         if (of->priv_class) {
228             *(const AVClass **)s->priv_data = of->priv_class;
229             av_opt_set_defaults(s->priv_data);
230             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
231                 goto fail;
232         }
233     }
234
235     /* set muxer identification string */
236     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
237         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
238     }
239
240     if (options) {
241          av_dict_free(options);
242          *options = tmp;
243     }
244
245     return 0;
246
247 fail:
248     av_dict_free(&tmp);
249     return ret;
250 }
251
252 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
253 {
254     int ret = 0;
255
256     if (ret = init_muxer(s, options))
257         return ret;
258
259     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
260         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
261     if (s->oformat->write_header) {
262         ret = s->oformat->write_header(s);
263         if (ret < 0)
264             return ret;
265     }
266     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
267         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
268
269     if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) {
270         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
271             s->avoid_negative_ts = 0;
272         } else
273             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
274     }
275
276     return 0;
277 }
278
279 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
280 FF_DISABLE_DEPRECATION_WARNINGS
281 //FIXME merge with compute_pkt_fields
282 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
283 {
284     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
285     int num, den, i;
286
287     if (!s->internal->missing_ts_warning &&
288         !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
289         (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
290         av_log(s, AV_LOG_WARNING,
291                "Timestamps are unset in a packet for stream %d. "
292                "This is deprecated and will stop working in the future. "
293                "Fix your code to set the timestamps properly\n", st->index);
294         s->internal->missing_ts_warning = 1;
295     }
296
297     av_log(s, AV_LOG_TRACE, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
298             pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
299
300 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
301  *      return AVERROR(EINVAL);*/
302
303     /* duration field */
304     if (pkt->duration == 0) {
305         ff_compute_frame_duration(s, &num, &den, st, NULL, pkt);
306         if (den && num) {
307             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
308         }
309     }
310
311     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
312         pkt->pts = pkt->dts;
313
314     //calculate dts from pts
315     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
316         st->pts_buffer[0] = pkt->pts;
317         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
318             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
319         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
320             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
321
322         pkt->dts = st->pts_buffer[0];
323     }
324
325     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
326         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
327           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
328         av_log(s, AV_LOG_ERROR,
329                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
330                st->index, st->cur_dts, pkt->dts);
331         return AVERROR(EINVAL);
332     }
333     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
334         av_log(s, AV_LOG_ERROR,
335                "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
336                pkt->pts, pkt->dts,
337                st->index);
338         return AVERROR(EINVAL);
339     }
340
341     av_log(s, AV_LOG_TRACE, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
342             pkt->pts, pkt->dts);
343     st->cur_dts = pkt->dts;
344
345     return 0;
346 }
347 FF_ENABLE_DEPRECATION_WARNINGS
348 #endif
349
350 /*
351  * FIXME: this function should NEVER get undefined pts/dts beside when the
352  * AVFMT_NOTIMESTAMPS is set.
353  * Those additional safety checks should be dropped once the correct checks
354  * are set in the callers.
355  */
356
357 static int write_packet(AVFormatContext *s, AVPacket *pkt)
358 {
359     int ret;
360     // If the timestamp offsetting below is adjusted, adjust
361     // ff_interleaved_peek similarly.
362     if (s->avoid_negative_ts > 0) {
363         AVRational time_base = s->streams[pkt->stream_index]->time_base;
364         int64_t offset = 0;
365
366         if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
367             (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
368             s->internal->offset = -pkt->dts;
369             s->internal->offset_timebase = time_base;
370         }
371         if (s->internal->offset != AV_NOPTS_VALUE)
372             offset = av_rescale_q(s->internal->offset, s->internal->offset_timebase, time_base);
373
374         if (pkt->dts != AV_NOPTS_VALUE)
375             pkt->dts += offset;
376         if (pkt->pts != AV_NOPTS_VALUE)
377             pkt->pts += offset;
378
379         if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
380             av_log(s, AV_LOG_WARNING,
381                    "Packets poorly interleaved, failed to avoid negative "
382                    "timestamp %"PRId64" in stream %d.\n"
383                    "Try -max_interleave_delta 0 as a possible workaround.\n",
384                    pkt->dts, pkt->stream_index);
385         }
386     }
387     ret = s->oformat->write_packet(s, pkt);
388
389     if (s->pb && ret >= 0) {
390         if (s->flags & AVFMT_FLAG_FLUSH_PACKETS)
391             avio_flush(s->pb);
392         if (s->pb->error < 0)
393             ret = s->pb->error;
394     }
395
396     return ret;
397 }
398
399 static int check_packet(AVFormatContext *s, AVPacket *pkt)
400 {
401     if (!pkt)
402         return 0;
403
404     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
405         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
406                pkt->stream_index);
407         return AVERROR(EINVAL);
408     }
409
410     if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
411         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
412         return AVERROR(EINVAL);
413     }
414
415     return 0;
416 }
417
418 static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
419 {
420     int ret;
421
422     ret = check_packet(s, pkt);
423     if (ret < 0)
424         return ret;
425
426 #if !FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
427     /* sanitize the timestamps */
428     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
429         AVStream *st = s->streams[pkt->stream_index];
430
431         /* when there is no reordering (so dts is equal to pts), but
432          * only one of them is set, set the other as well */
433         if (!st->internal->reorder) {
434             if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
435                 pkt->pts = pkt->dts;
436             if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
437                 pkt->dts = pkt->pts;
438         }
439
440         /* check that the timestamps are set */
441         if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
442             av_log(s, AV_LOG_ERROR,
443                    "Timestamps are unset in a packet for stream %d\n", st->index);
444             return AVERROR(EINVAL);
445         }
446
447         /* check that the dts are increasing (or at least non-decreasing,
448          * if the format allows it */
449         if (st->cur_dts != AV_NOPTS_VALUE &&
450             ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
451              st->cur_dts > pkt->dts)) {
452             av_log(s, AV_LOG_ERROR,
453                    "Application provided invalid, non monotonically increasing "
454                    "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
455                    st->index, st->cur_dts, pkt->dts);
456             return AVERROR(EINVAL);
457         }
458
459         if (pkt->pts < pkt->dts) {
460             av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
461                    pkt->pts, pkt->dts, st->index);
462             return AVERROR(EINVAL);
463         }
464     }
465 #endif
466
467     return 0;
468 }
469
470 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
471 {
472     int ret;
473
474     ret = prepare_input_packet(s, pkt);
475     if (ret < 0)
476         return ret;
477
478     if (!pkt) {
479         if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
480             return s->oformat->write_packet(s, pkt);
481         return 1;
482     }
483
484 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
485     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
486
487     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
488         return ret;
489 #endif
490
491     ret = write_packet(s, pkt);
492
493     if (ret >= 0)
494         s->streams[pkt->stream_index]->nb_frames++;
495     return ret;
496 }
497
498 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
499                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
500 {
501     int ret;
502     AVPacketList **next_point, *this_pktl;
503
504     this_pktl      = av_mallocz(sizeof(AVPacketList));
505     if (!this_pktl)
506         return AVERROR(ENOMEM);
507
508     if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
509         av_free(this_pktl);
510         return ret;
511     }
512
513     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
514         next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
515     } else
516         next_point = &s->internal->packet_buffer;
517
518     if (*next_point) {
519         if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
520             while (!compare(s, &(*next_point)->pkt, pkt))
521                 next_point = &(*next_point)->next;
522             goto next_non_null;
523         } else {
524             next_point = &(s->internal->packet_buffer_end->next);
525         }
526     }
527     assert(!*next_point);
528
529     s->internal->packet_buffer_end = this_pktl;
530 next_non_null:
531
532     this_pktl->next = *next_point;
533
534     s->streams[pkt->stream_index]->last_in_packet_buffer =
535         *next_point                                      = this_pktl;
536
537     av_packet_unref(pkt);
538
539     return 0;
540 }
541
542 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
543                                   AVPacket *pkt)
544 {
545     AVStream *st  = s->streams[pkt->stream_index];
546     AVStream *st2 = s->streams[next->stream_index];
547     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
548                                   st->time_base);
549
550     if (comp == 0)
551         return pkt->stream_index < next->stream_index;
552     return comp > 0;
553 }
554
555 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
556                                  AVPacket *pkt, int flush)
557 {
558     AVPacketList *pktl;
559     int stream_count = 0;
560     int i, ret;
561
562     if (pkt) {
563         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
564             return ret;
565     }
566
567     if (s->max_interleave_delta > 0 && s->internal->packet_buffer && !flush) {
568         AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
569         int64_t delta_dts = INT64_MIN;
570         int64_t top_dts = av_rescale_q(top_pkt->dts,
571                                        s->streams[top_pkt->stream_index]->time_base,
572                                        AV_TIME_BASE_Q);
573
574         for (i = 0; i < s->nb_streams; i++) {
575             int64_t last_dts;
576             const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
577
578             if (!last)
579                 continue;
580
581             last_dts = av_rescale_q(last->pkt.dts,
582                                     s->streams[i]->time_base,
583                                     AV_TIME_BASE_Q);
584             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
585             stream_count++;
586         }
587
588         if (delta_dts > s->max_interleave_delta) {
589             av_log(s, AV_LOG_DEBUG,
590                    "Delay between the first packet and last packet in the "
591                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
592                    delta_dts, s->max_interleave_delta);
593             flush = 1;
594         }
595     } else {
596         for (i = 0; i < s->nb_streams; i++)
597             stream_count += !!s->streams[i]->last_in_packet_buffer;
598     }
599
600
601     if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
602         pktl = s->internal->packet_buffer;
603         *out = pktl->pkt;
604
605         s->internal->packet_buffer = pktl->next;
606         if (!s->internal->packet_buffer)
607             s->internal->packet_buffer_end = NULL;
608
609         if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
610             s->streams[out->stream_index]->last_in_packet_buffer = NULL;
611         av_freep(&pktl);
612         return 1;
613     } else {
614         av_init_packet(out);
615         return 0;
616     }
617 }
618
619 int ff_interleaved_peek(AVFormatContext *s, int stream,
620                         AVPacket *pkt, int add_offset)
621 {
622     AVPacketList *pktl = s->internal->packet_buffer;
623     while (pktl) {
624         if (pktl->pkt.stream_index == stream) {
625             *pkt = pktl->pkt;
626             if (add_offset && s->internal->offset != AV_NOPTS_VALUE) {
627                 int64_t offset = av_rescale_q(s->internal->offset,
628                                               s->internal->offset_timebase,
629                                               s->streams[stream]->time_base);
630                 if (pkt->dts != AV_NOPTS_VALUE)
631                     pkt->dts += offset;
632                 if (pkt->pts != AV_NOPTS_VALUE)
633                     pkt->pts += offset;
634             }
635             return 0;
636         }
637         pktl = pktl->next;
638     }
639     return AVERROR(ENOENT);
640 }
641
642 /**
643  * Interleave an AVPacket correctly so it can be muxed.
644  * @param out the interleaved packet will be output here
645  * @param in the input packet
646  * @param flush 1 if no further packets are available as input and all
647  *              remaining packets should be output
648  * @return 1 if a packet was output, 0 if no packet could be output,
649  *         < 0 if an error occurred
650  */
651 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
652 {
653     if (s->oformat->interleave_packet) {
654         int ret = s->oformat->interleave_packet(s, out, in, flush);
655         if (in)
656             av_packet_unref(in);
657         return ret;
658     } else
659         return ff_interleave_packet_per_dts(s, out, in, flush);
660 }
661
662 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
663 {
664     int ret, flush = 0;
665
666     ret = prepare_input_packet(s, pkt);
667     if (ret < 0)
668         goto fail;
669
670     if (pkt) {
671 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
672         AVStream *st = s->streams[pkt->stream_index];
673
674         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
675                 pkt->size, pkt->dts, pkt->pts);
676         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
677             goto fail;
678 #endif
679
680         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
681             ret = AVERROR(EINVAL);
682             goto fail;
683         }
684     } else {
685         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
686         flush = 1;
687     }
688
689     for (;; ) {
690         AVPacket opkt;
691         int ret = interleave_packet(s, &opkt, pkt, flush);
692         if (pkt) {
693             memset(pkt, 0, sizeof(*pkt));
694             av_init_packet(pkt);
695             pkt = NULL;
696         }
697         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
698             return ret;
699
700         ret = write_packet(s, &opkt);
701         if (ret >= 0)
702             s->streams[opkt.stream_index]->nb_frames++;
703
704         av_packet_unref(&opkt);
705
706         if (ret < 0)
707             return ret;
708     }
709 fail:
710     av_packet_unref(pkt);
711     return ret;
712 }
713
714 int av_write_trailer(AVFormatContext *s)
715 {
716     int ret, i;
717
718     for (;; ) {
719         AVPacket pkt;
720         ret = interleave_packet(s, &pkt, NULL, 1);
721         if (ret < 0) //FIXME cleanup needed for ret<0 ?
722             goto fail;
723         if (!ret)
724             break;
725
726         ret = write_packet(s, &pkt);
727         if (ret >= 0)
728             s->streams[pkt.stream_index]->nb_frames++;
729
730         av_packet_unref(&pkt);
731
732         if (ret < 0)
733             goto fail;
734     }
735
736     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
737         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
738     if (s->oformat->write_trailer)
739         ret = s->oformat->write_trailer(s);
740
741     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
742         avio_flush(s->pb);
743
744 fail:
745     for (i = 0; i < s->nb_streams; i++) {
746         av_freep(&s->streams[i]->priv_data);
747         av_freep(&s->streams[i]->index_entries);
748     }
749     if (s->oformat->priv_class)
750         av_opt_free(s->priv_data);
751     av_freep(&s->priv_data);
752     return ret;
753 }
754
755 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
756                      AVFormatContext *src)
757 {
758     AVPacket local_pkt;
759
760     local_pkt = *pkt;
761     local_pkt.stream_index = dst_stream;
762     if (pkt->pts != AV_NOPTS_VALUE)
763         local_pkt.pts = av_rescale_q(pkt->pts,
764                                      src->streams[pkt->stream_index]->time_base,
765                                      dst->streams[dst_stream]->time_base);
766     if (pkt->dts != AV_NOPTS_VALUE)
767         local_pkt.dts = av_rescale_q(pkt->dts,
768                                      src->streams[pkt->stream_index]->time_base,
769                                      dst->streams[dst_stream]->time_base);
770     return av_write_frame(dst, &local_pkt);
771 }