]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
avio: Allow custom IO users to get labels for the output bytestream
[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 (s->avoid_negative_ts > 0) {
361         AVRational time_base = s->streams[pkt->stream_index]->time_base;
362         int64_t offset = 0;
363
364         if (s->internal->offset == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE &&
365             (pkt->dts < 0 || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)) {
366             s->internal->offset = -pkt->dts;
367             s->internal->offset_timebase = time_base;
368         }
369         if (s->internal->offset != AV_NOPTS_VALUE)
370             offset = av_rescale_q(s->internal->offset, s->internal->offset_timebase, time_base);
371
372         if (pkt->dts != AV_NOPTS_VALUE)
373             pkt->dts += offset;
374         if (pkt->pts != AV_NOPTS_VALUE)
375             pkt->pts += offset;
376
377         if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
378             av_log(s, AV_LOG_WARNING,
379                    "Packets poorly interleaved, failed to avoid negative "
380                    "timestamp %"PRId64" in stream %d.\n"
381                    "Try -max_interleave_delta 0 as a possible workaround.\n",
382                    pkt->dts, pkt->stream_index);
383         }
384     }
385     ret = s->oformat->write_packet(s, pkt);
386
387     if (s->pb && ret >= 0) {
388         if (s->flags & AVFMT_FLAG_FLUSH_PACKETS)
389             avio_flush(s->pb);
390         if (s->pb->error < 0)
391             ret = s->pb->error;
392     }
393
394     return ret;
395 }
396
397 static int check_packet(AVFormatContext *s, AVPacket *pkt)
398 {
399     if (!pkt)
400         return 0;
401
402     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
403         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
404                pkt->stream_index);
405         return AVERROR(EINVAL);
406     }
407
408     if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
409         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
410         return AVERROR(EINVAL);
411     }
412
413     return 0;
414 }
415
416 static int prepare_input_packet(AVFormatContext *s, AVPacket *pkt)
417 {
418     int ret;
419
420     ret = check_packet(s, pkt);
421     if (ret < 0)
422         return ret;
423
424 #if !FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
425     /* sanitize the timestamps */
426     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
427         AVStream *st = s->streams[pkt->stream_index];
428
429         /* when there is no reordering (so dts is equal to pts), but
430          * only one of them is set, set the other as well */
431         if (!st->internal->reorder) {
432             if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
433                 pkt->pts = pkt->dts;
434             if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
435                 pkt->dts = pkt->pts;
436         }
437
438         /* check that the timestamps are set */
439         if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
440             av_log(s, AV_LOG_ERROR,
441                    "Timestamps are unset in a packet for stream %d\n", st->index);
442             return AVERROR(EINVAL);
443         }
444
445         /* check that the dts are increasing (or at least non-decreasing,
446          * if the format allows it */
447         if (st->cur_dts != AV_NOPTS_VALUE &&
448             ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) ||
449              st->cur_dts > pkt->dts)) {
450             av_log(s, AV_LOG_ERROR,
451                    "Application provided invalid, non monotonically increasing "
452                    "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
453                    st->index, st->cur_dts, pkt->dts);
454             return AVERROR(EINVAL);
455         }
456
457         if (pkt->pts < pkt->dts) {
458             av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
459                    pkt->pts, pkt->dts, st->index);
460             return AVERROR(EINVAL);
461         }
462     }
463 #endif
464
465     return 0;
466 }
467
468 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
469 {
470     int ret;
471
472     ret = prepare_input_packet(s, pkt);
473     if (ret < 0)
474         return ret;
475
476     if (!pkt) {
477         if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
478             return s->oformat->write_packet(s, pkt);
479         return 1;
480     }
481
482 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
483     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
484
485     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
486         return ret;
487 #endif
488
489     ret = write_packet(s, pkt);
490
491     if (ret >= 0)
492         s->streams[pkt->stream_index]->nb_frames++;
493     return ret;
494 }
495
496 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
497                              int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
498 {
499     int ret;
500     AVPacketList **next_point, *this_pktl;
501
502     this_pktl      = av_mallocz(sizeof(AVPacketList));
503     if (!this_pktl)
504         return AVERROR(ENOMEM);
505
506     if ((ret = av_packet_ref(&this_pktl->pkt, pkt)) < 0) {
507         av_free(this_pktl);
508         return ret;
509     }
510
511     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
512         next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
513     } else
514         next_point = &s->internal->packet_buffer;
515
516     if (*next_point) {
517         if (compare(s, &s->internal->packet_buffer_end->pkt, pkt)) {
518             while (!compare(s, &(*next_point)->pkt, pkt))
519                 next_point = &(*next_point)->next;
520             goto next_non_null;
521         } else {
522             next_point = &(s->internal->packet_buffer_end->next);
523         }
524     }
525     assert(!*next_point);
526
527     s->internal->packet_buffer_end = this_pktl;
528 next_non_null:
529
530     this_pktl->next = *next_point;
531
532     s->streams[pkt->stream_index]->last_in_packet_buffer =
533         *next_point                                      = this_pktl;
534
535     av_packet_unref(pkt);
536
537     return 0;
538 }
539
540 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
541                                   AVPacket *pkt)
542 {
543     AVStream *st  = s->streams[pkt->stream_index];
544     AVStream *st2 = s->streams[next->stream_index];
545     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
546                                   st->time_base);
547
548     if (comp == 0)
549         return pkt->stream_index < next->stream_index;
550     return comp > 0;
551 }
552
553 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
554                                  AVPacket *pkt, int flush)
555 {
556     AVPacketList *pktl;
557     int stream_count = 0;
558     int i, ret;
559
560     if (pkt) {
561         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
562             return ret;
563     }
564
565     if (s->max_interleave_delta > 0 && s->internal->packet_buffer && !flush) {
566         AVPacket *top_pkt = &s->internal->packet_buffer->pkt;
567         int64_t delta_dts = INT64_MIN;
568         int64_t top_dts = av_rescale_q(top_pkt->dts,
569                                        s->streams[top_pkt->stream_index]->time_base,
570                                        AV_TIME_BASE_Q);
571
572         for (i = 0; i < s->nb_streams; i++) {
573             int64_t last_dts;
574             const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
575
576             if (!last)
577                 continue;
578
579             last_dts = av_rescale_q(last->pkt.dts,
580                                     s->streams[i]->time_base,
581                                     AV_TIME_BASE_Q);
582             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
583             stream_count++;
584         }
585
586         if (delta_dts > s->max_interleave_delta) {
587             av_log(s, AV_LOG_DEBUG,
588                    "Delay between the first packet and last packet in the "
589                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
590                    delta_dts, s->max_interleave_delta);
591             flush = 1;
592         }
593     } else {
594         for (i = 0; i < s->nb_streams; i++)
595             stream_count += !!s->streams[i]->last_in_packet_buffer;
596     }
597
598
599     if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
600         pktl = s->internal->packet_buffer;
601         *out = pktl->pkt;
602
603         s->internal->packet_buffer = pktl->next;
604         if (!s->internal->packet_buffer)
605             s->internal->packet_buffer_end = NULL;
606
607         if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
608             s->streams[out->stream_index]->last_in_packet_buffer = NULL;
609         av_freep(&pktl);
610         return 1;
611     } else {
612         av_init_packet(out);
613         return 0;
614     }
615 }
616
617 /**
618  * Interleave an AVPacket correctly so it can be muxed.
619  * @param out the interleaved packet will be output here
620  * @param in the input packet
621  * @param flush 1 if no further packets are available as input and all
622  *              remaining packets should be output
623  * @return 1 if a packet was output, 0 if no packet could be output,
624  *         < 0 if an error occurred
625  */
626 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
627 {
628     if (s->oformat->interleave_packet) {
629         int ret = s->oformat->interleave_packet(s, out, in, flush);
630         if (in)
631             av_packet_unref(in);
632         return ret;
633     } else
634         return ff_interleave_packet_per_dts(s, out, in, flush);
635 }
636
637 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
638 {
639     int ret, flush = 0;
640
641     ret = prepare_input_packet(s, pkt);
642     if (ret < 0)
643         goto fail;
644
645     if (pkt) {
646 #if FF_API_COMPUTE_PKT_FIELDS2 && FF_API_LAVF_AVCTX
647         AVStream *st = s->streams[pkt->stream_index];
648
649         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
650                 pkt->size, pkt->dts, pkt->pts);
651         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
652             goto fail;
653 #endif
654
655         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
656             ret = AVERROR(EINVAL);
657             goto fail;
658         }
659     } else {
660         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
661         flush = 1;
662     }
663
664     for (;; ) {
665         AVPacket opkt;
666         int ret = interleave_packet(s, &opkt, pkt, flush);
667         if (pkt) {
668             memset(pkt, 0, sizeof(*pkt));
669             av_init_packet(pkt);
670             pkt = NULL;
671         }
672         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
673             return ret;
674
675         ret = write_packet(s, &opkt);
676         if (ret >= 0)
677             s->streams[opkt.stream_index]->nb_frames++;
678
679         av_packet_unref(&opkt);
680
681         if (ret < 0)
682             return ret;
683     }
684 fail:
685     av_packet_unref(pkt);
686     return ret;
687 }
688
689 int av_write_trailer(AVFormatContext *s)
690 {
691     int ret, i;
692
693     for (;; ) {
694         AVPacket pkt;
695         ret = interleave_packet(s, &pkt, NULL, 1);
696         if (ret < 0) //FIXME cleanup needed for ret<0 ?
697             goto fail;
698         if (!ret)
699             break;
700
701         ret = write_packet(s, &pkt);
702         if (ret >= 0)
703             s->streams[pkt.stream_index]->nb_frames++;
704
705         av_packet_unref(&pkt);
706
707         if (ret < 0)
708             goto fail;
709     }
710
711     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
712         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
713     if (s->oformat->write_trailer)
714         ret = s->oformat->write_trailer(s);
715
716     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
717         avio_flush(s->pb);
718
719 fail:
720     for (i = 0; i < s->nb_streams; i++) {
721         av_freep(&s->streams[i]->priv_data);
722         av_freep(&s->streams[i]->index_entries);
723     }
724     if (s->oformat->priv_class)
725         av_opt_free(s->priv_data);
726     av_freep(&s->priv_data);
727     return ret;
728 }
729
730 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
731                      AVFormatContext *src)
732 {
733     AVPacket local_pkt;
734
735     local_pkt = *pkt;
736     local_pkt.stream_index = dst_stream;
737     if (pkt->pts != AV_NOPTS_VALUE)
738         local_pkt.pts = av_rescale_q(pkt->pts,
739                                      src->streams[pkt->stream_index]->time_base,
740                                      dst->streams[dst_stream]->time_base);
741     if (pkt->dts != AV_NOPTS_VALUE)
742         local_pkt.dts = av_rescale_q(pkt->dts,
743                                      src->streams[pkt->stream_index]->time_base,
744                                      dst->streams[dst_stream]->time_base);
745     return av_write_frame(dst, &local_pkt);
746 }