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