• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * muxing functions for use within FFmpeg
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include "avformat.h"
23 #include "internal.h"
24 #include "mux.h"
25 #include "version.h"
26 #include "libavcodec/bsf.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/packet_internal.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/timestamp.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/mathematics.h"
35 
36 /**
37  * @file
38  * muxing functions for use within libavformat
39  */
40 
41 /* fraction handling */
42 
43 /**
44  * f = val + (num / den) + 0.5.
45  *
46  * 'num' is normalized so that it is such as 0 <= num < den.
47  *
48  * @param f fractional number
49  * @param val integer value
50  * @param num must be >= 0
51  * @param den must be >= 1
52  */
frac_init(FFFrac * f,int64_t val,int64_t num,int64_t den)53 static void frac_init(FFFrac *f, int64_t val, int64_t num, int64_t den)
54 {
55     num += (den >> 1);
56     if (num >= den) {
57         val += num / den;
58         num  = num % den;
59     }
60     f->val = val;
61     f->num = num;
62     f->den = den;
63 }
64 
65 /**
66  * Fractional addition to f: f = f + (incr / f->den).
67  *
68  * @param f fractional number
69  * @param incr increment, can be positive or negative
70  */
frac_add(FFFrac * f,int64_t incr)71 static void frac_add(FFFrac *f, int64_t incr)
72 {
73     int64_t num, den;
74 
75     num = f->num + incr;
76     den = f->den;
77     if (num < 0) {
78         f->val += num / den;
79         num     = num % den;
80         if (num < 0) {
81             num += den;
82             f->val--;
83         }
84     } else if (num >= den) {
85         f->val += num / den;
86         num     = num % den;
87     }
88     f->num = num;
89 }
90 
avformat_alloc_output_context2(AVFormatContext ** avctx,const AVOutputFormat * oformat,const char * format,const char * filename)91 int avformat_alloc_output_context2(AVFormatContext **avctx, const AVOutputFormat *oformat,
92                                    const char *format, const char *filename)
93 {
94     AVFormatContext *s = avformat_alloc_context();
95     int ret = 0;
96 
97     *avctx = NULL;
98     if (!s)
99         goto nomem;
100 
101     if (!oformat) {
102         if (format) {
103             oformat = av_guess_format(format, NULL, NULL);
104             if (!oformat) {
105                 av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);
106                 ret = AVERROR(EINVAL);
107                 goto error;
108             }
109         } else {
110             oformat = av_guess_format(NULL, filename, NULL);
111             if (!oformat) {
112                 ret = AVERROR(EINVAL);
113                 av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",
114                        filename);
115                 goto error;
116             }
117         }
118     }
119 
120     s->oformat = oformat;
121     if (s->oformat->priv_data_size > 0) {
122         s->priv_data = av_mallocz(s->oformat->priv_data_size);
123         if (!s->priv_data)
124             goto nomem;
125         if (s->oformat->priv_class) {
126             *(const AVClass**)s->priv_data= s->oformat->priv_class;
127             av_opt_set_defaults(s->priv_data);
128         }
129     } else
130         s->priv_data = NULL;
131 
132     if (filename) {
133         if (!(s->url = av_strdup(filename)))
134             goto nomem;
135 
136     }
137     *avctx = s;
138     return 0;
139 nomem:
140     av_log(s, AV_LOG_ERROR, "Out of memory\n");
141     ret = AVERROR(ENOMEM);
142 error:
143     avformat_free_context(s);
144     return ret;
145 }
146 
validate_codec_tag(AVFormatContext * s,AVStream * st)147 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
148 {
149     const AVCodecTag *avctag;
150     enum AVCodecID id = AV_CODEC_ID_NONE;
151     int64_t tag  = -1;
152 
153     /**
154      * Check that tag + id is in the table
155      * If neither is in the table -> OK
156      * If tag is in the table with another id -> FAIL
157      * If id is in the table with another tag -> FAIL unless strict < normal
158      */
159     for (int n = 0; s->oformat->codec_tag[n]; n++) {
160         avctag = s->oformat->codec_tag[n];
161         while (avctag->id != AV_CODEC_ID_NONE) {
162             if (ff_toupper4(avctag->tag) == ff_toupper4(st->codecpar->codec_tag)) {
163                 id = avctag->id;
164                 if (id == st->codecpar->codec_id)
165                     return 1;
166             }
167             if (avctag->id == st->codecpar->codec_id)
168                 tag = avctag->tag;
169             avctag++;
170         }
171     }
172     if (id != AV_CODEC_ID_NONE)
173         return 0;
174     if (tag >= 0 && (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
175         return 0;
176     return 1;
177 }
178 
179 
init_muxer(AVFormatContext * s,AVDictionary ** options)180 static int init_muxer(AVFormatContext *s, AVDictionary **options)
181 {
182     FFFormatContext *const si = ffformatcontext(s);
183     AVDictionary *tmp = NULL;
184     const AVOutputFormat *of = s->oformat;
185     AVDictionaryEntry *e;
186     int ret = 0;
187 
188     if (options)
189         av_dict_copy(&tmp, *options, 0);
190 
191     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
192         goto fail;
193     if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&
194         (ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
195         goto fail;
196 
197     if (!s->url && !(s->url = av_strdup(""))) {
198         ret = AVERROR(ENOMEM);
199         goto fail;
200     }
201 
202     // some sanity checks
203     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
204         av_log(s, AV_LOG_ERROR, "No streams to mux were specified\n");
205         ret = AVERROR(EINVAL);
206         goto fail;
207     }
208 
209     for (unsigned i = 0; i < s->nb_streams; i++) {
210         AVStream          *const  st = s->streams[i];
211         FFStream          *const sti = ffstream(st);
212         AVCodecParameters *const par = st->codecpar;
213         const AVCodecDescriptor *desc;
214 
215         if (!st->time_base.num) {
216             /* fall back on the default timebase values */
217             if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate)
218                 avpriv_set_pts_info(st, 64, 1, par->sample_rate);
219             else
220                 avpriv_set_pts_info(st, 33, 1, 90000);
221         }
222 
223         switch (par->codec_type) {
224         case AVMEDIA_TYPE_AUDIO:
225             if (par->sample_rate <= 0) {
226                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
227                 ret = AVERROR(EINVAL);
228                 goto fail;
229             }
230 
231 #if FF_API_OLD_CHANNEL_LAYOUT
232 FF_DISABLE_DEPRECATION_WARNINGS
233             /* if the caller is using the deprecated channel layout API,
234              * convert it to the new style */
235             if (!par->ch_layout.nb_channels &&
236                 par->channels) {
237                 if (par->channel_layout) {
238                     av_channel_layout_from_mask(&par->ch_layout, par->channel_layout);
239                 } else {
240                     par->ch_layout.order       = AV_CHANNEL_ORDER_UNSPEC;
241                     par->ch_layout.nb_channels = par->channels;
242                 }
243             }
244 FF_ENABLE_DEPRECATION_WARNINGS
245 #endif
246 
247             if (!par->block_align)
248                 par->block_align = par->ch_layout.nb_channels *
249                                    av_get_bits_per_sample(par->codec_id) >> 3;
250             break;
251         case AVMEDIA_TYPE_VIDEO:
252             if ((par->width <= 0 || par->height <= 0) &&
253                 !(of->flags & AVFMT_NODIMENSIONS)) {
254                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
255                 ret = AVERROR(EINVAL);
256                 goto fail;
257             }
258             if (av_cmp_q(st->sample_aspect_ratio, par->sample_aspect_ratio)
259                 && fabs(av_q2d(st->sample_aspect_ratio) - av_q2d(par->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)
260             ) {
261                 if (st->sample_aspect_ratio.num != 0 &&
262                     st->sample_aspect_ratio.den != 0 &&
263                     par->sample_aspect_ratio.num != 0 &&
264                     par->sample_aspect_ratio.den != 0) {
265                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
266                            "(%d/%d) and encoder layer (%d/%d)\n",
267                            st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
268                            par->sample_aspect_ratio.num,
269                            par->sample_aspect_ratio.den);
270                     ret = AVERROR(EINVAL);
271                     goto fail;
272                 }
273             }
274             break;
275         }
276 
277         desc = avcodec_descriptor_get(par->codec_id);
278         if (desc && desc->props & AV_CODEC_PROP_REORDER)
279             sti->reorder = 1;
280 
281         sti->is_intra_only = ff_is_intra_only(par->codec_id);
282 
283         if (of->codec_tag) {
284             if (   par->codec_tag
285                 && par->codec_id == AV_CODEC_ID_RAWVIDEO
286                 && (   av_codec_get_tag(of->codec_tag, par->codec_id) == 0
287                     || av_codec_get_tag(of->codec_tag, par->codec_id) == MKTAG('r', 'a', 'w', ' '))
288                 && !validate_codec_tag(s, st)) {
289                 // the current rawvideo encoding system ends up setting
290                 // the wrong codec_tag for avi/mov, we override it here
291                 par->codec_tag = 0;
292             }
293             if (par->codec_tag) {
294                 if (!validate_codec_tag(s, st)) {
295                     const uint32_t otag = av_codec_get_tag(s->oformat->codec_tag, par->codec_id);
296                     av_log(s, AV_LOG_ERROR,
297                            "Tag %s incompatible with output codec id '%d' (%s)\n",
298                            av_fourcc2str(par->codec_tag), par->codec_id, av_fourcc2str(otag));
299                     ret = AVERROR_INVALIDDATA;
300                     goto fail;
301                 }
302             } else
303                 par->codec_tag = av_codec_get_tag(of->codec_tag, par->codec_id);
304         }
305 
306         if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT)
307             si->nb_interleaved_streams++;
308     }
309     si->interleave_packet = of->interleave_packet;
310     if (!si->interleave_packet)
311         si->interleave_packet = si->nb_interleaved_streams > 1 ?
312                                     ff_interleave_packet_per_dts :
313                                     ff_interleave_packet_passthrough;
314 
315     if (!s->priv_data && of->priv_data_size > 0) {
316         s->priv_data = av_mallocz(of->priv_data_size);
317         if (!s->priv_data) {
318             ret = AVERROR(ENOMEM);
319             goto fail;
320         }
321         if (of->priv_class) {
322             *(const AVClass **)s->priv_data = of->priv_class;
323             av_opt_set_defaults(s->priv_data);
324             if ((ret = av_opt_set_dict2(s->priv_data, &tmp, AV_OPT_SEARCH_CHILDREN)) < 0)
325                 goto fail;
326         }
327     }
328 
329     /* set muxer identification string */
330     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
331         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
332     } else {
333         av_dict_set(&s->metadata, "encoder", NULL, 0);
334     }
335 
336     for (e = NULL; e = av_dict_get(s->metadata, "encoder-", e, AV_DICT_IGNORE_SUFFIX); ) {
337         av_dict_set(&s->metadata, e->key, NULL, 0);
338     }
339 
340     if (options) {
341          av_dict_free(options);
342          *options = tmp;
343     }
344 
345     if (s->oformat->init) {
346         if ((ret = s->oformat->init(s)) < 0) {
347             if (s->oformat->deinit)
348                 s->oformat->deinit(s);
349             return ret;
350         }
351         return ret == 0;
352     }
353 
354     return 0;
355 
356 fail:
357     av_dict_free(&tmp);
358     return ret;
359 }
360 
init_pts(AVFormatContext * s)361 static int init_pts(AVFormatContext *s)
362 {
363     FFFormatContext *const si = ffformatcontext(s);
364 
365     /* init PTS generation */
366     for (unsigned i = 0; i < s->nb_streams; i++) {
367         AVStream *const st = s->streams[i];
368         FFStream *const sti = ffstream(st);
369         int64_t den = AV_NOPTS_VALUE;
370 
371         switch (st->codecpar->codec_type) {
372         case AVMEDIA_TYPE_AUDIO:
373             den = (int64_t)st->time_base.num * st->codecpar->sample_rate;
374             break;
375         case AVMEDIA_TYPE_VIDEO:
376             den = (int64_t)st->time_base.num * st->time_base.den;
377             break;
378         default:
379             break;
380         }
381 
382         if (!sti->priv_pts)
383             sti->priv_pts = av_mallocz(sizeof(*sti->priv_pts));
384         if (!sti->priv_pts)
385             return AVERROR(ENOMEM);
386 
387         if (den != AV_NOPTS_VALUE) {
388             if (den <= 0)
389                 return AVERROR_INVALIDDATA;
390 
391             frac_init(sti->priv_pts, 0, 0, den);
392         }
393     }
394 
395     si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_UNKNOWN;
396     if (s->avoid_negative_ts < 0) {
397         av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
398         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
399             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_DISABLED;
400             si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_DISABLED;
401         } else
402             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
403     } else if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_DISABLED)
404         si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_DISABLED;
405 
406     return 0;
407 }
408 
flush_if_needed(AVFormatContext * s)409 static void flush_if_needed(AVFormatContext *s)
410 {
411     if (s->pb && s->pb->error >= 0) {
412         if (s->flush_packets == 1 || s->flags & AVFMT_FLAG_FLUSH_PACKETS)
413             avio_flush(s->pb);
414         else if (s->flush_packets && !(s->oformat->flags & AVFMT_NOFILE))
415             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
416     }
417 }
418 
deinit_muxer(AVFormatContext * s)419 static void deinit_muxer(AVFormatContext *s)
420 {
421     FFFormatContext *const si = ffformatcontext(s);
422     if (s->oformat && s->oformat->deinit && si->initialized)
423         s->oformat->deinit(s);
424     si->initialized =
425     si->streams_initialized = 0;
426 }
427 
avformat_init_output(AVFormatContext * s,AVDictionary ** options)428 int avformat_init_output(AVFormatContext *s, AVDictionary **options)
429 {
430     FFFormatContext *const si = ffformatcontext(s);
431     int ret = 0;
432 
433     if ((ret = init_muxer(s, options)) < 0)
434         return ret;
435 
436     si->initialized = 1;
437     si->streams_initialized = ret;
438 
439     if (s->oformat->init && ret) {
440         if ((ret = init_pts(s)) < 0)
441             return ret;
442 
443         return AVSTREAM_INIT_IN_INIT_OUTPUT;
444     }
445 
446     return AVSTREAM_INIT_IN_WRITE_HEADER;
447 }
448 
avformat_write_header(AVFormatContext * s,AVDictionary ** options)449 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
450 {
451     FFFormatContext *const si = ffformatcontext(s);
452     int already_initialized = si->initialized;
453     int streams_already_initialized = si->streams_initialized;
454     int ret = 0;
455 
456     if (!already_initialized)
457         if ((ret = avformat_init_output(s, options)) < 0)
458             return ret;
459 
460     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
461         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
462     if (s->oformat->write_header) {
463         ret = s->oformat->write_header(s);
464         if (ret >= 0 && s->pb && s->pb->error < 0)
465             ret = s->pb->error;
466         if (ret < 0)
467             goto fail;
468         flush_if_needed(s);
469     }
470     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
471         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
472 
473     if (!si->streams_initialized) {
474         if ((ret = init_pts(s)) < 0)
475             goto fail;
476     }
477 
478     return streams_already_initialized;
479 
480 fail:
481     deinit_muxer(s);
482     return ret;
483 }
484 
485 #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
486 
487 
488 #if FF_API_COMPUTE_PKT_FIELDS2
489 FF_DISABLE_DEPRECATION_WARNINGS
490 //FIXME merge with compute_pkt_fields
compute_muxer_pkt_fields(AVFormatContext * s,AVStream * st,AVPacket * pkt)491 static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
492 {
493     FFFormatContext *const si = ffformatcontext(s);
494     FFStream *const sti = ffstream(st);
495     int delay = st->codecpar->video_delay;
496     int frame_size;
497 
498     if (!si->missing_ts_warning &&
499         !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
500         (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) || (st->disposition & AV_DISPOSITION_TIMED_THUMBNAILS)) &&
501         (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
502         av_log(s, AV_LOG_WARNING,
503                "Timestamps are unset in a packet for stream %d. "
504                "This is deprecated and will stop working in the future. "
505                "Fix your code to set the timestamps properly\n", st->index);
506         si->missing_ts_warning = 1;
507     }
508 
509     if (s->debug & FF_FDEBUG_TS)
510         av_log(s, AV_LOG_DEBUG, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
511             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(sti->cur_dts), delay, pkt->size, pkt->stream_index);
512 
513     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
514         pkt->pts = pkt->dts;
515 
516     //XXX/FIXME this is a temporary hack until all encoders output pts
517     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
518         static int warned;
519         if (!warned) {
520             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
521             warned = 1;
522         }
523         pkt->dts =
524 //        pkt->pts= st->cur_dts;
525             pkt->pts = sti->priv_pts->val;
526     }
527 
528     //calculate dts from pts
529     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
530         sti->pts_buffer[0] = pkt->pts;
531         for (int i = 1; i < delay + 1 && sti->pts_buffer[i] == AV_NOPTS_VALUE; i++)
532             sti->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
533         for (int i = 0; i<delay && sti->pts_buffer[i] > sti->pts_buffer[i + 1]; i++)
534             FFSWAP(int64_t, sti->pts_buffer[i], sti->pts_buffer[i + 1]);
535 
536         pkt->dts = sti->pts_buffer[0];
537     }
538 
539     if (sti->cur_dts && sti->cur_dts != AV_NOPTS_VALUE &&
540         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
541           st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE &&
542           st->codecpar->codec_type != AVMEDIA_TYPE_DATA &&
543           sti->cur_dts >= pkt->dts) || sti->cur_dts > pkt->dts)) {
544         av_log(s, AV_LOG_ERROR,
545                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
546                st->index, av_ts2str(sti->cur_dts), av_ts2str(pkt->dts));
547         return AVERROR(EINVAL);
548     }
549     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
550         av_log(s, AV_LOG_ERROR,
551                "pts (%s) < dts (%s) in stream %d\n",
552                av_ts2str(pkt->pts), av_ts2str(pkt->dts),
553                st->index);
554         return AVERROR(EINVAL);
555     }
556 
557     if (s->debug & FF_FDEBUG_TS)
558         av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%s dts2:%s\n",
559             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
560 
561     sti->cur_dts      = pkt->dts;
562     sti->priv_pts->val = pkt->dts;
563 
564     /* update pts */
565     switch (st->codecpar->codec_type) {
566     case AVMEDIA_TYPE_AUDIO:
567         frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
568                      (*(AVFrame **)pkt->data)->nb_samples :
569                      av_get_audio_frame_duration2(st->codecpar, pkt->size);
570 
571         /* HACK/FIXME, we skip the initial 0 size packets as they are most
572          * likely equal to the encoder delay, but it would be better if we
573          * had the real timestamps from the encoder */
574         if (frame_size >= 0 && (pkt->size || sti->priv_pts->num != sti->priv_pts->den >> 1 || sti->priv_pts->val)) {
575             frac_add(sti->priv_pts, (int64_t)st->time_base.den * frame_size);
576         }
577         break;
578     case AVMEDIA_TYPE_VIDEO:
579         frac_add(sti->priv_pts, (int64_t)st->time_base.den * st->time_base.num);
580         break;
581     }
582     return 0;
583 }
584 FF_ENABLE_DEPRECATION_WARNINGS
585 #endif
586 
guess_pkt_duration(AVFormatContext * s,AVStream * st,AVPacket * pkt)587 static void guess_pkt_duration(AVFormatContext *s, AVStream *st, AVPacket *pkt)
588 {
589     if (pkt->duration < 0 && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
590         av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
591                pkt->duration, pkt->stream_index);
592         pkt->duration = 0;
593     }
594 
595     if (pkt->duration)
596         return;
597 
598     switch (st->codecpar->codec_type) {
599     case AVMEDIA_TYPE_VIDEO:
600         if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0) {
601             pkt->duration = av_rescale_q(1, av_inv_q(st->avg_frame_rate),
602                                          st->time_base);
603         } else if (st->time_base.num * 1000LL > st->time_base.den)
604             pkt->duration = 1;
605         break;
606     case AVMEDIA_TYPE_AUDIO: {
607         int frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
608         if (frame_size && st->codecpar->sample_rate) {
609             pkt->duration = av_rescale_q(frame_size,
610                                          (AVRational){1, st->codecpar->sample_rate},
611                                          st->time_base);
612         }
613         break;
614         }
615     }
616 }
617 
handle_avoid_negative_ts(FFFormatContext * si,FFStream * sti,AVPacket * pkt)618 static void handle_avoid_negative_ts(FFFormatContext *si, FFStream *sti,
619                                      AVPacket *pkt)
620 {
621     AVFormatContext *const s = &si->pub;
622     int64_t offset;
623 
624     if (!AVOID_NEGATIVE_TS_ENABLED(si->avoid_negative_ts_status))
625         return;
626 
627     if (si->avoid_negative_ts_status == AVOID_NEGATIVE_TS_UNKNOWN) {
628         int use_pts = si->avoid_negative_ts_use_pts;
629         int64_t ts = use_pts ? pkt->pts : pkt->dts;
630         AVRational tb = sti->pub.time_base;
631 
632         if (ts == AV_NOPTS_VALUE)
633             return;
634 
635         /* Peek into the muxing queue to improve our estimate
636          * of the lowest timestamp if av_interleaved_write_frame() is used. */
637         for (const PacketListEntry *pktl = si->packet_buffer.head;
638              pktl; pktl = pktl->next) {
639             AVRational cmp_tb = s->streams[pktl->pkt.stream_index]->time_base;
640             int64_t cmp_ts = use_pts ? pktl->pkt.pts : pktl->pkt.dts;
641             if (cmp_ts == AV_NOPTS_VALUE)
642                 continue;
643             if (s->output_ts_offset)
644                 cmp_ts += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, cmp_tb);
645             if (av_compare_ts(cmp_ts, cmp_tb, ts, tb) < 0) {
646                 ts = cmp_ts;
647                 tb = cmp_tb;
648             }
649         }
650 
651         if (ts < 0 ||
652             ts > 0 && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
653             for (unsigned i = 0; i < s->nb_streams; i++) {
654                 AVStream *const st2  = s->streams[i];
655                 FFStream *const sti2 = ffstream(st2);
656                 sti2->mux_ts_offset = av_rescale_q_rnd(-ts, tb,
657                                                        st2->time_base,
658                                                        AV_ROUND_UP);
659             }
660         }
661         si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_KNOWN;
662     }
663 
664     offset = sti->mux_ts_offset;
665 
666     if (pkt->dts != AV_NOPTS_VALUE)
667         pkt->dts += offset;
668     if (pkt->pts != AV_NOPTS_VALUE)
669         pkt->pts += offset;
670 
671     if (si->avoid_negative_ts_use_pts) {
672         if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
673             av_log(s, AV_LOG_WARNING, "failed to avoid negative "
674                    "pts %s in stream %d.\n"
675                    "Try -avoid_negative_ts 1 as a possible workaround.\n",
676                    av_ts2str(pkt->pts),
677                    pkt->stream_index
678             );
679         }
680     } else {
681         if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
682             av_log(s, AV_LOG_WARNING,
683                    "Packets poorly interleaved, failed to avoid negative "
684                    "timestamp %s in stream %d.\n"
685                    "Try -max_interleave_delta 0 as a possible workaround.\n",
686                    av_ts2str(pkt->dts),
687                    pkt->stream_index
688             );
689         }
690     }
691 }
692 
693 /**
694  * Shift timestamps and call muxer; the original pts/dts are not kept.
695  *
696  * FIXME: this function should NEVER get undefined pts/dts beside when the
697  * AVFMT_NOTIMESTAMPS is set.
698  * Those additional safety checks should be dropped once the correct checks
699  * are set in the callers.
700  */
write_packet(AVFormatContext * s,AVPacket * pkt)701 static int write_packet(AVFormatContext *s, AVPacket *pkt)
702 {
703     FFFormatContext *const si = ffformatcontext(s);
704     AVStream *const st = s->streams[pkt->stream_index];
705     FFStream *const sti = ffstream(st);
706     int ret;
707 
708     // If the timestamp offsetting below is adjusted, adjust
709     // ff_interleaved_peek similarly.
710     if (s->output_ts_offset) {
711         int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
712 
713         if (pkt->dts != AV_NOPTS_VALUE)
714             pkt->dts += offset;
715         if (pkt->pts != AV_NOPTS_VALUE)
716             pkt->pts += offset;
717     }
718     handle_avoid_negative_ts(si, sti, pkt);
719 
720     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
721         AVFrame **frame = (AVFrame **)pkt->data;
722         av_assert0(pkt->size == sizeof(*frame));
723         ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, frame, 0);
724     } else {
725         ret = s->oformat->write_packet(s, pkt);
726     }
727 
728     if (s->pb && ret >= 0) {
729         flush_if_needed(s);
730         if (s->pb->error < 0)
731             ret = s->pb->error;
732     }
733 
734     if (ret >= 0)
735         st->nb_frames++;
736 
737     return ret;
738 }
739 
check_packet(AVFormatContext * s,AVPacket * pkt)740 static int check_packet(AVFormatContext *s, AVPacket *pkt)
741 {
742     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
743         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
744                pkt->stream_index);
745         return AVERROR(EINVAL);
746     }
747 
748     if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
749         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
750         return AVERROR(EINVAL);
751     }
752 
753     return 0;
754 }
755 
prepare_input_packet(AVFormatContext * s,AVStream * st,AVPacket * pkt)756 static int prepare_input_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
757 {
758     FFStream *const sti = ffstream(st);
759 #if !FF_API_COMPUTE_PKT_FIELDS2
760     /* sanitize the timestamps */
761     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
762 
763         /* when there is no reordering (so dts is equal to pts), but
764          * only one of them is set, set the other as well */
765         if (!sti->reorder) {
766             if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
767                 pkt->pts = pkt->dts;
768             if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
769                 pkt->dts = pkt->pts;
770         }
771 
772         /* check that the timestamps are set */
773         if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
774             av_log(s, AV_LOG_ERROR,
775                    "Timestamps are unset in a packet for stream %d\n", st->index);
776             return AVERROR(EINVAL);
777         }
778 
779         /* check that the dts are increasing (or at least non-decreasing,
780          * if the format allows it */
781         if (sti->cur_dts != AV_NOPTS_VALUE &&
782             ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && sti->cur_dts >= pkt->dts) ||
783              sti->cur_dts > pkt->dts)) {
784             av_log(s, AV_LOG_ERROR,
785                    "Application provided invalid, non monotonically increasing "
786                    "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
787                    st->index, sti->cur_dts, pkt->dts);
788             return AVERROR(EINVAL);
789         }
790 
791         if (pkt->pts < pkt->dts) {
792             av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
793                    pkt->pts, pkt->dts, st->index);
794             return AVERROR(EINVAL);
795         }
796     }
797 #endif
798     /* update flags */
799     if (sti->is_intra_only)
800         pkt->flags |= AV_PKT_FLAG_KEY;
801 
802     if (!pkt->data && !pkt->side_data_elems) {
803         /* Such empty packets signal EOS for the BSF API; so sanitize
804          * the packet by allocating data of size 0 (+ padding). */
805         av_buffer_unref(&pkt->buf);
806         return av_packet_make_refcounted(pkt);
807     }
808 
809     return 0;
810 }
811 
812 #define CHUNK_START 0x1000
813 
ff_interleave_add_packet(AVFormatContext * s,AVPacket * pkt,int (* compare)(AVFormatContext *,const AVPacket *,const AVPacket *))814 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
815                              int (*compare)(AVFormatContext *, const AVPacket *, const AVPacket *))
816 {
817     int ret;
818     FFFormatContext *const si = ffformatcontext(s);
819     PacketListEntry **next_point, *this_pktl;
820     AVStream *st = s->streams[pkt->stream_index];
821     FFStream *const sti = ffstream(st);
822     int chunked  = s->max_chunk_size || s->max_chunk_duration;
823 
824     this_pktl    = av_malloc(sizeof(*this_pktl));
825     if (!this_pktl) {
826         av_packet_unref(pkt);
827         return AVERROR(ENOMEM);
828     }
829     if ((ret = av_packet_make_refcounted(pkt)) < 0) {
830         av_free(this_pktl);
831         av_packet_unref(pkt);
832         return ret;
833     }
834 
835     av_packet_move_ref(&this_pktl->pkt, pkt);
836     pkt = &this_pktl->pkt;
837 
838     if (sti->last_in_packet_buffer) {
839         next_point = &(sti->last_in_packet_buffer->next);
840     } else {
841         next_point = &si->packet_buffer.head;
842     }
843 
844     if (chunked) {
845         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
846         sti->interleaver_chunk_size     += pkt->size;
847         sti->interleaver_chunk_duration += pkt->duration;
848         if (   (s->max_chunk_size && sti->interleaver_chunk_size > s->max_chunk_size)
849             || (max && sti->interleaver_chunk_duration           > max)) {
850             sti->interleaver_chunk_size = 0;
851             pkt->flags |= CHUNK_START;
852             if (max && sti->interleaver_chunk_duration > max) {
853                 int64_t syncoffset = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
854                 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
855 
856                 sti->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
857             } else
858                 sti->interleaver_chunk_duration  = 0;
859         }
860     }
861     if (*next_point) {
862         if (chunked && !(pkt->flags & CHUNK_START))
863             goto next_non_null;
864 
865         if (compare(s, &si->packet_buffer.tail->pkt, pkt)) {
866             while (   *next_point
867                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
868                        || !compare(s, &(*next_point)->pkt, pkt)))
869                 next_point = &(*next_point)->next;
870             if (*next_point)
871                 goto next_non_null;
872         } else {
873             next_point = &(si->packet_buffer.tail->next);
874         }
875     }
876     av_assert1(!*next_point);
877 
878     si->packet_buffer.tail = this_pktl;
879 next_non_null:
880 
881     this_pktl->next = *next_point;
882 
883     sti->last_in_packet_buffer = *next_point = this_pktl;
884 
885     return 0;
886 }
887 
interleave_compare_dts(AVFormatContext * s,const AVPacket * next,const AVPacket * pkt)888 static int interleave_compare_dts(AVFormatContext *s, const AVPacket *next,
889                                                       const AVPacket *pkt)
890 {
891     AVStream *st  = s->streams[pkt->stream_index];
892     AVStream *st2 = s->streams[next->stream_index];
893     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
894                                   st->time_base);
895     if (s->audio_preload) {
896         int preload  = st ->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
897         int preload2 = st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
898         if (preload != preload2) {
899             int64_t ts, ts2;
900             preload  *= s->audio_preload;
901             preload2 *= s->audio_preload;
902             ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - preload;
903             ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - preload2;
904             if (ts == ts2) {
905                 ts  = ((uint64_t)pkt ->dts*st ->time_base.num*AV_TIME_BASE - (uint64_t)preload *st ->time_base.den)*st2->time_base.den
906                     - ((uint64_t)next->dts*st2->time_base.num*AV_TIME_BASE - (uint64_t)preload2*st2->time_base.den)*st ->time_base.den;
907                 ts2 = 0;
908             }
909             comp = (ts2 > ts) - (ts2 < ts);
910         }
911     }
912 
913     if (comp == 0)
914         return pkt->stream_index < next->stream_index;
915     return comp > 0;
916 }
917 
ff_interleave_packet_per_dts(AVFormatContext * s,AVPacket * pkt,int flush,int has_packet)918 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *pkt,
919                                  int flush, int has_packet)
920 {
921     FFFormatContext *const si = ffformatcontext(s);
922     int stream_count = 0;
923     int noninterleaved_count = 0;
924     int ret;
925     int eof = flush;
926 
927     if (has_packet) {
928         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
929             return ret;
930     }
931 
932     for (unsigned i = 0; i < s->nb_streams; i++) {
933         const AVStream *const st  = s->streams[i];
934         const FFStream *const sti = cffstream(st);
935         const AVCodecParameters *const par = st->codecpar;
936         if (sti->last_in_packet_buffer) {
937             ++stream_count;
938         } else if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
939                    par->codec_id != AV_CODEC_ID_VP8 &&
940                    par->codec_id != AV_CODEC_ID_VP9) {
941             ++noninterleaved_count;
942         }
943     }
944 
945     if (si->nb_interleaved_streams == stream_count)
946         flush = 1;
947 
948     if (s->max_interleave_delta > 0 &&
949         si->packet_buffer.head &&
950         !flush &&
951         si->nb_interleaved_streams == stream_count+noninterleaved_count
952     ) {
953         AVPacket *const top_pkt = &si->packet_buffer.head->pkt;
954         int64_t delta_dts = INT64_MIN;
955         int64_t top_dts = av_rescale_q(top_pkt->dts,
956                                        s->streams[top_pkt->stream_index]->time_base,
957                                        AV_TIME_BASE_Q);
958 
959         for (unsigned i = 0; i < s->nb_streams; i++) {
960             const AVStream *const st  = s->streams[i];
961             const FFStream *const sti = cffstream(st);
962             const PacketListEntry *const last = sti->last_in_packet_buffer;
963             int64_t last_dts;
964 
965             if (!last)
966                 continue;
967 
968             last_dts = av_rescale_q(last->pkt.dts,
969                                     st->time_base,
970                                     AV_TIME_BASE_Q);
971             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
972         }
973 
974         if (delta_dts > s->max_interleave_delta) {
975             av_log(s, AV_LOG_DEBUG,
976                    "Delay between the first packet and last packet in the "
977                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
978                    delta_dts, s->max_interleave_delta);
979             flush = 1;
980         }
981     }
982 
983     if (si->packet_buffer.head &&
984         eof &&
985         (s->flags & AVFMT_FLAG_SHORTEST) &&
986         si->shortest_end == AV_NOPTS_VALUE) {
987         AVPacket *const top_pkt = &si->packet_buffer.head->pkt;
988 
989         si->shortest_end = av_rescale_q(top_pkt->dts,
990                                        s->streams[top_pkt->stream_index]->time_base,
991                                        AV_TIME_BASE_Q);
992     }
993 
994     if (si->shortest_end != AV_NOPTS_VALUE) {
995         while (si->packet_buffer.head) {
996             PacketListEntry *pktl = si->packet_buffer.head;
997             AVPacket *const top_pkt = &pktl->pkt;
998             AVStream *const st = s->streams[top_pkt->stream_index];
999             FFStream *const sti = ffstream(st);
1000             int64_t top_dts = av_rescale_q(top_pkt->dts, st->time_base,
1001                                         AV_TIME_BASE_Q);
1002 
1003             if (si->shortest_end + 1 >= top_dts)
1004                 break;
1005 
1006             si->packet_buffer.head = pktl->next;
1007             if (!si->packet_buffer.head)
1008                 si->packet_buffer.tail = NULL;
1009 
1010             if (sti->last_in_packet_buffer == pktl)
1011                 sti->last_in_packet_buffer = NULL;
1012 
1013             av_packet_unref(&pktl->pkt);
1014             av_freep(&pktl);
1015             flush = 0;
1016         }
1017     }
1018 
1019     if (stream_count && flush) {
1020         PacketListEntry *pktl = si->packet_buffer.head;
1021         AVStream *const st = s->streams[pktl->pkt.stream_index];
1022         FFStream *const sti = ffstream(st);
1023 
1024         if (sti->last_in_packet_buffer == pktl)
1025             sti->last_in_packet_buffer = NULL;
1026         avpriv_packet_list_get(&si->packet_buffer, pkt);
1027 
1028         return 1;
1029     } else {
1030         return 0;
1031     }
1032 }
1033 
ff_interleave_packet_passthrough(AVFormatContext * s,AVPacket * pkt,int flush,int has_packet)1034 int ff_interleave_packet_passthrough(AVFormatContext *s, AVPacket *pkt,
1035                                      int flush, int has_packet)
1036 {
1037     return has_packet;
1038 }
1039 
ff_get_muxer_ts_offset(AVFormatContext * s,int stream_index,int64_t * offset)1040 int ff_get_muxer_ts_offset(AVFormatContext *s, int stream_index, int64_t *offset)
1041 {
1042     AVStream *st;
1043 
1044     if (stream_index < 0 || stream_index >= s->nb_streams)
1045         return AVERROR(EINVAL);
1046 
1047     st = s->streams[stream_index];
1048     *offset = ffstream(st)->mux_ts_offset;
1049 
1050     if (s->output_ts_offset)
1051         *offset += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
1052 
1053     return 0;
1054 }
1055 
ff_interleaved_peek(AVFormatContext * s,int stream)1056 const AVPacket *ff_interleaved_peek(AVFormatContext *s, int stream)
1057 {
1058     FFFormatContext *const si = ffformatcontext(s);
1059     PacketListEntry *pktl = si->packet_buffer.head;
1060     while (pktl) {
1061         if (pktl->pkt.stream_index == stream) {
1062             return &pktl->pkt;
1063         }
1064         pktl = pktl->next;
1065     }
1066     return NULL;
1067 }
1068 
check_bitstream(AVFormatContext * s,FFStream * sti,AVPacket * pkt)1069 static int check_bitstream(AVFormatContext *s, FFStream *sti, AVPacket *pkt)
1070 {
1071     int ret;
1072 
1073     if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
1074         return 1;
1075 
1076     if (s->oformat->check_bitstream) {
1077         if (!sti->bitstream_checked) {
1078             if ((ret = s->oformat->check_bitstream(s, &sti->pub, pkt)) < 0)
1079                 return ret;
1080             else if (ret == 1)
1081                 sti->bitstream_checked = 1;
1082         }
1083     }
1084 
1085     return 1;
1086 }
1087 
interleaved_write_packet(AVFormatContext * s,AVPacket * pkt,int flush,int has_packet)1088 static int interleaved_write_packet(AVFormatContext *s, AVPacket *pkt,
1089                                     int flush, int has_packet)
1090 {
1091     FFFormatContext *const si = ffformatcontext(s);
1092     for (;; ) {
1093         int ret = si->interleave_packet(s, pkt, flush, has_packet);
1094         if (ret <= 0)
1095             return ret;
1096 
1097         has_packet = 0;
1098 
1099         ret = write_packet(s, pkt);
1100         av_packet_unref(pkt);
1101         if (ret < 0)
1102             return ret;
1103     }
1104 }
1105 
write_packet_common(AVFormatContext * s,AVStream * st,AVPacket * pkt,int interleaved)1106 static int write_packet_common(AVFormatContext *s, AVStream *st, AVPacket *pkt, int interleaved)
1107 {
1108     int ret;
1109 
1110     if (s->debug & FF_FDEBUG_TS)
1111         av_log(s, AV_LOG_DEBUG, "%s size:%d dts:%s pts:%s\n", __FUNCTION__,
1112                pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
1113 
1114     guess_pkt_duration(s, st, pkt);
1115 
1116 #if FF_API_COMPUTE_PKT_FIELDS2
1117     if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
1118         return ret;
1119 #endif
1120 
1121     if (interleaved) {
1122         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
1123             return AVERROR(EINVAL);
1124         return interleaved_write_packet(s, pkt, 0, 1);
1125     } else {
1126         return write_packet(s, pkt);
1127     }
1128 }
1129 
write_packets_from_bsfs(AVFormatContext * s,AVStream * st,AVPacket * pkt,int interleaved)1130 static int write_packets_from_bsfs(AVFormatContext *s, AVStream *st, AVPacket *pkt, int interleaved)
1131 {
1132     FFStream *const sti = ffstream(st);
1133     AVBSFContext *const bsfc = sti->bsfc;
1134     int ret;
1135 
1136     if ((ret = av_bsf_send_packet(bsfc, pkt)) < 0) {
1137         av_log(s, AV_LOG_ERROR,
1138                 "Failed to send packet to filter %s for stream %d\n",
1139                 bsfc->filter->name, st->index);
1140         return ret;
1141     }
1142 
1143     do {
1144         ret = av_bsf_receive_packet(bsfc, pkt);
1145         if (ret < 0) {
1146             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1147                 return 0;
1148             av_log(s, AV_LOG_ERROR, "Error applying bitstream filters to an output "
1149                    "packet for stream #%d: %s\n", st->index, av_err2str(ret));
1150             if (!(s->error_recognition & AV_EF_EXPLODE) && ret != AVERROR(ENOMEM))
1151                 continue;
1152             return ret;
1153         }
1154         av_packet_rescale_ts(pkt, bsfc->time_base_out, st->time_base);
1155         ret = write_packet_common(s, st, pkt, interleaved);
1156         if (ret >= 0 && !interleaved) // a successful write_packet_common already unrefed pkt for interleaved
1157             av_packet_unref(pkt);
1158     } while (ret >= 0);
1159 
1160     return ret;
1161 }
1162 
write_packets_common(AVFormatContext * s,AVPacket * pkt,int interleaved)1163 static int write_packets_common(AVFormatContext *s, AVPacket *pkt, int interleaved)
1164 {
1165     AVStream *st;
1166     FFStream *sti;
1167     int ret = check_packet(s, pkt);
1168     if (ret < 0)
1169         return ret;
1170     st = s->streams[pkt->stream_index];
1171     sti = ffstream(st);
1172 
1173     ret = prepare_input_packet(s, st, pkt);
1174     if (ret < 0)
1175         return ret;
1176 
1177     ret = check_bitstream(s, sti, pkt);
1178     if (ret < 0)
1179         return ret;
1180 
1181     if (sti->bsfc) {
1182         return write_packets_from_bsfs(s, st, pkt, interleaved);
1183     } else {
1184         return write_packet_common(s, st, pkt, interleaved);
1185     }
1186 }
1187 
av_write_frame(AVFormatContext * s,AVPacket * in)1188 int av_write_frame(AVFormatContext *s, AVPacket *in)
1189 {
1190     FFFormatContext *const si = ffformatcontext(s);
1191     AVPacket *pkt = si->parse_pkt;
1192     int ret;
1193 
1194     if (!in) {
1195         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
1196             ret = s->oformat->write_packet(s, NULL);
1197             flush_if_needed(s);
1198             if (ret >= 0 && s->pb && s->pb->error < 0)
1199                 ret = s->pb->error;
1200             return ret;
1201         }
1202         return 1;
1203     }
1204 
1205     if (in->flags & AV_PKT_FLAG_UNCODED_FRAME) {
1206         pkt = in;
1207     } else {
1208         /* We don't own in, so we have to make sure not to modify it.
1209          * (ff_write_chained() relies on this fact.)
1210          * The following avoids copying in's data unnecessarily.
1211          * Copying side data is unavoidable as a bitstream filter
1212          * may change it, e.g. free it on errors. */
1213         pkt->data = in->data;
1214         pkt->size = in->size;
1215         ret = av_packet_copy_props(pkt, in);
1216         if (ret < 0)
1217             return ret;
1218         if (in->buf) {
1219             pkt->buf = av_buffer_ref(in->buf);
1220             if (!pkt->buf) {
1221                 ret = AVERROR(ENOMEM);
1222                 goto fail;
1223             }
1224         }
1225     }
1226 
1227     ret = write_packets_common(s, pkt, 0/*non-interleaved*/);
1228 
1229 fail:
1230     // Uncoded frames using the noninterleaved codepath are also freed here
1231     av_packet_unref(pkt);
1232     return ret;
1233 }
1234 
av_interleaved_write_frame(AVFormatContext * s,AVPacket * pkt)1235 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
1236 {
1237     int ret;
1238 
1239     if (pkt) {
1240         ret = write_packets_common(s, pkt, 1/*interleaved*/);
1241         if (ret < 0)
1242             av_packet_unref(pkt);
1243         return ret;
1244     } else {
1245         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
1246         return interleaved_write_packet(s, ffformatcontext(s)->parse_pkt, 1/*flush*/, 0);
1247     }
1248 }
1249 
av_write_trailer(AVFormatContext * s)1250 int av_write_trailer(AVFormatContext *s)
1251 {
1252     FFFormatContext *const si = ffformatcontext(s);
1253     AVPacket *const pkt = si->parse_pkt;
1254     int ret1, ret = 0;
1255 
1256     for (unsigned i = 0; i < s->nb_streams; i++) {
1257         AVStream *const st  = s->streams[i];
1258         FFStream *const sti = ffstream(st);
1259         if (sti->bsfc) {
1260             ret1 = write_packets_from_bsfs(s, st, pkt, 1/*interleaved*/);
1261             if (ret1 < 0)
1262                 av_packet_unref(pkt);
1263             if (ret >= 0)
1264                 ret = ret1;
1265         }
1266     }
1267     ret1 = interleaved_write_packet(s, pkt, 1, 0);
1268     if (ret >= 0)
1269         ret = ret1;
1270 
1271     if (s->oformat->write_trailer) {
1272         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1273             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
1274         if (ret >= 0) {
1275         ret = s->oformat->write_trailer(s);
1276         } else {
1277             s->oformat->write_trailer(s);
1278         }
1279     }
1280 
1281     deinit_muxer(s);
1282 
1283     if (s->pb)
1284        avio_flush(s->pb);
1285     if (ret == 0)
1286        ret = s->pb ? s->pb->error : 0;
1287     for (unsigned i = 0; i < s->nb_streams; i++) {
1288         av_freep(&s->streams[i]->priv_data);
1289         av_freep(&ffstream(s->streams[i])->index_entries);
1290     }
1291     if (s->oformat->priv_class)
1292         av_opt_free(s->priv_data);
1293     av_freep(&s->priv_data);
1294     av_packet_unref(si->pkt);
1295     return ret;
1296 }
1297 
av_get_output_timestamp(struct AVFormatContext * s,int stream,int64_t * dts,int64_t * wall)1298 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
1299                             int64_t *dts, int64_t *wall)
1300 {
1301     if (!s->oformat || !s->oformat->get_output_timestamp)
1302         return AVERROR(ENOSYS);
1303     s->oformat->get_output_timestamp(s, stream, dts, wall);
1304     return 0;
1305 }
1306 
ff_stream_add_bitstream_filter(AVStream * st,const char * name,const char * args)1307 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
1308 {
1309     int ret;
1310     const AVBitStreamFilter *bsf;
1311     FFStream *const sti = ffstream(st);
1312     AVBSFContext *bsfc;
1313 
1314     av_assert0(!sti->bsfc);
1315 
1316     if (!(bsf = av_bsf_get_by_name(name))) {
1317         av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
1318         return AVERROR_BSF_NOT_FOUND;
1319     }
1320 
1321     if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
1322         return ret;
1323 
1324     bsfc->time_base_in = st->time_base;
1325     if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
1326         av_bsf_free(&bsfc);
1327         return ret;
1328     }
1329 
1330     if (args && bsfc->filter->priv_class) {
1331         if ((ret = av_set_options_string(bsfc->priv_data, args, "=", ":")) < 0) {
1332             av_bsf_free(&bsfc);
1333             return ret;
1334         }
1335     }
1336 
1337     if ((ret = av_bsf_init(bsfc)) < 0) {
1338         av_bsf_free(&bsfc);
1339         return ret;
1340     }
1341 
1342     sti->bsfc = bsfc;
1343 
1344     av_log(NULL, AV_LOG_VERBOSE,
1345            "Automatically inserted bitstream filter '%s'; args='%s'\n",
1346            name, args ? args : "");
1347     return 1;
1348 }
1349 
ff_write_chained(AVFormatContext * dst,int dst_stream,AVPacket * pkt,AVFormatContext * src,int interleave)1350 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
1351                      AVFormatContext *src, int interleave)
1352 {
1353     int64_t pts = pkt->pts, dts = pkt->dts, duration = pkt->duration;
1354     int stream_index = pkt->stream_index;
1355     AVRational time_base = pkt->time_base;
1356     int ret;
1357 
1358     pkt->stream_index = dst_stream;
1359 
1360     av_packet_rescale_ts(pkt,
1361                          src->streams[stream_index]->time_base,
1362                          dst->streams[dst_stream]->time_base);
1363 
1364     if (!interleave) {
1365         ret = av_write_frame(dst, pkt);
1366         /* We only have to backup and restore the fields that
1367          * we changed ourselves, because av_write_frame() does not
1368          * modify the packet given to it. */
1369         pkt->pts          = pts;
1370         pkt->dts          = dts;
1371         pkt->duration     = duration;
1372         pkt->stream_index = stream_index;
1373         pkt->time_base    = time_base;
1374     } else
1375         ret = av_interleaved_write_frame(dst, pkt);
1376 
1377     return ret;
1378 }
1379 
uncoded_frame_free(void * unused,uint8_t * data)1380 static void uncoded_frame_free(void *unused, uint8_t *data)
1381 {
1382     av_frame_free((AVFrame **)data);
1383     av_free(data);
1384 }
1385 
write_uncoded_frame_internal(AVFormatContext * s,int stream_index,AVFrame * frame,int interleaved)1386 static int write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
1387                                         AVFrame *frame, int interleaved)
1388 {
1389     FFFormatContext *const si = ffformatcontext(s);
1390     AVPacket *pkt = si->parse_pkt;
1391 
1392     av_assert0(s->oformat);
1393     if (!s->oformat->write_uncoded_frame) {
1394         av_frame_free(&frame);
1395         return AVERROR(ENOSYS);
1396     }
1397 
1398     if (!frame) {
1399         pkt = NULL;
1400     } else {
1401         size_t   bufsize = sizeof(frame) + AV_INPUT_BUFFER_PADDING_SIZE;
1402         AVFrame **framep = av_mallocz(bufsize);
1403 
1404         if (!framep)
1405             goto fail;
1406         pkt->buf = av_buffer_create((void *)framep, bufsize,
1407                                    uncoded_frame_free, NULL, 0);
1408         if (!pkt->buf) {
1409             av_free(framep);
1410     fail:
1411             av_frame_free(&frame);
1412             return AVERROR(ENOMEM);
1413         }
1414         *framep = frame;
1415 
1416         pkt->data         = (void *)framep;
1417         pkt->size         = sizeof(frame);
1418         pkt->pts          =
1419         pkt->dts          = frame->pts;
1420         pkt->duration     = frame->pkt_duration;
1421         pkt->stream_index = stream_index;
1422         pkt->flags |= AV_PKT_FLAG_UNCODED_FRAME;
1423     }
1424 
1425     return interleaved ? av_interleaved_write_frame(s, pkt) :
1426                          av_write_frame(s, pkt);
1427 }
1428 
av_write_uncoded_frame(AVFormatContext * s,int stream_index,AVFrame * frame)1429 int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
1430                            AVFrame *frame)
1431 {
1432     return write_uncoded_frame_internal(s, stream_index, frame, 0);
1433 }
1434 
av_interleaved_write_uncoded_frame(AVFormatContext * s,int stream_index,AVFrame * frame)1435 int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
1436                                        AVFrame *frame)
1437 {
1438     return write_uncoded_frame_internal(s, stream_index, frame, 1);
1439 }
1440 
av_write_uncoded_frame_query(AVFormatContext * s,int stream_index)1441 int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
1442 {
1443     av_assert0(s->oformat);
1444     if (!s->oformat->write_uncoded_frame)
1445         return AVERROR(ENOSYS);
1446     return s->oformat->write_uncoded_frame(s, stream_index, NULL,
1447                                            AV_WRITE_UNCODED_FRAME_QUERY);
1448 }
1449