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