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 #ifdef OHOS_TIMED_META_TRACK
379         case AVMEDIA_TYPE_TIMEDMETA:
380             den = (int64_t)st->time_base.num * st->time_base.den;
381             break;
382 #endif
383         default:
384             break;
385         }
386 
387         if (!sti->priv_pts)
388             sti->priv_pts = av_mallocz(sizeof(*sti->priv_pts));
389         if (!sti->priv_pts)
390             return AVERROR(ENOMEM);
391 
392         if (den != AV_NOPTS_VALUE) {
393             if (den <= 0)
394                 return AVERROR_INVALIDDATA;
395 
396             frac_init(sti->priv_pts, 0, 0, den);
397         }
398     }
399 
400     si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_UNKNOWN;
401     if (s->avoid_negative_ts < 0) {
402         av_assert2(s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO);
403         if (s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS)) {
404             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_DISABLED;
405             si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_DISABLED;
406         } else
407             s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE;
408     } else if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_DISABLED)
409         si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_DISABLED;
410 
411     return 0;
412 }
413 
flush_if_needed(AVFormatContext *s)414 static void flush_if_needed(AVFormatContext *s)
415 {
416     if (s->pb && s->pb->error >= 0) {
417         if (s->flush_packets == 1 || s->flags & AVFMT_FLAG_FLUSH_PACKETS)
418             avio_flush(s->pb);
419         else if (s->flush_packets && !(s->oformat->flags & AVFMT_NOFILE))
420             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_FLUSH_POINT);
421     }
422 }
423 
deinit_muxer(AVFormatContext *s)424 static void deinit_muxer(AVFormatContext *s)
425 {
426     FFFormatContext *const si = ffformatcontext(s);
427     if (s->oformat && s->oformat->deinit && si->initialized)
428         s->oformat->deinit(s);
429     si->initialized =
430     si->streams_initialized = 0;
431 }
432 
avformat_init_output(AVFormatContext *s, AVDictionary **options)433 int avformat_init_output(AVFormatContext *s, AVDictionary **options)
434 {
435     FFFormatContext *const si = ffformatcontext(s);
436     int ret = 0;
437 
438     if ((ret = init_muxer(s, options)) < 0)
439         return ret;
440 
441     si->initialized = 1;
442     si->streams_initialized = ret;
443 
444     if (s->oformat->init && ret) {
445         if ((ret = init_pts(s)) < 0)
446             return ret;
447 
448         return AVSTREAM_INIT_IN_INIT_OUTPUT;
449     }
450 
451     return AVSTREAM_INIT_IN_WRITE_HEADER;
452 }
453 
avformat_write_header(AVFormatContext *s, AVDictionary **options)454 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
455 {
456     FFFormatContext *const si = ffformatcontext(s);
457     int already_initialized = si->initialized;
458     int streams_already_initialized = si->streams_initialized;
459     int ret = 0;
460 
461     if (!already_initialized)
462         if ((ret = avformat_init_output(s, options)) < 0)
463             return ret;
464 
465     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
466         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
467     if (s->oformat->write_header) {
468         ret = s->oformat->write_header(s);
469         if (ret >= 0 && s->pb && s->pb->error < 0)
470             ret = s->pb->error;
471         if (ret < 0)
472             goto fail;
473         flush_if_needed(s);
474     }
475     if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
476         avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_UNKNOWN);
477 
478     if (!si->streams_initialized) {
479         if ((ret = init_pts(s)) < 0)
480             goto fail;
481     }
482 
483     return streams_already_initialized;
484 
485 fail:
486     deinit_muxer(s);
487     return ret;
488 }
489 
490 #define AV_PKT_FLAG_UNCODED_FRAME 0x2000
491 
492 
493 #if FF_API_COMPUTE_PKT_FIELDS2
494 FF_DISABLE_DEPRECATION_WARNINGS
495 //FIXME merge with compute_pkt_fields
compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)496 static int compute_muxer_pkt_fields(AVFormatContext *s, AVStream *st, AVPacket *pkt)
497 {
498     FFFormatContext *const si = ffformatcontext(s);
499     FFStream *const sti = ffstream(st);
500     int delay = st->codecpar->video_delay;
501     int frame_size;
502 
503     if (!si->missing_ts_warning &&
504         !(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
505         (!(st->disposition & AV_DISPOSITION_ATTACHED_PIC) || (st->disposition & AV_DISPOSITION_TIMED_THUMBNAILS)) &&
506         (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE)) {
507         av_log(s, AV_LOG_WARNING,
508                "Timestamps are unset in a packet for stream %d. "
509                "This is deprecated and will stop working in the future. "
510                "Fix your code to set the timestamps properly\n", st->index);
511         si->missing_ts_warning = 1;
512     }
513 
514     if (s->debug & FF_FDEBUG_TS)
515         av_log(s, AV_LOG_DEBUG, "compute_muxer_pkt_fields: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
516             av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(sti->cur_dts), delay, pkt->size, pkt->stream_index);
517 
518     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
519         pkt->pts = pkt->dts;
520 
521     //XXX/FIXME this is a temporary hack until all encoders output pts
522     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
523         static int warned;
524         if (!warned) {
525             av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
526             warned = 1;
527         }
528         pkt->dts =
529 //        pkt->pts= st->cur_dts;
530             pkt->pts = sti->priv_pts->val;
531     }
532 
533     //calculate dts from pts
534     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
535         sti->pts_buffer[0] = pkt->pts;
536         for (int i = 1; i < delay + 1 && sti->pts_buffer[i] == AV_NOPTS_VALUE; i++)
537             sti->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
538         for (int i = 0; i<delay && sti->pts_buffer[i] > sti->pts_buffer[i + 1]; i++)
539             FFSWAP(int64_t, sti->pts_buffer[i], sti->pts_buffer[i + 1]);
540 
541         pkt->dts = sti->pts_buffer[0];
542     }
543 
544     if (sti->cur_dts && sti->cur_dts != AV_NOPTS_VALUE &&
545         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
546           st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE &&
547           st->codecpar->codec_type != AVMEDIA_TYPE_DATA &&
548           sti->cur_dts >= pkt->dts) || sti->cur_dts > pkt->dts)) {
549         av_log(s, AV_LOG_ERROR,
550                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
551                st->index, av_ts2str(sti->cur_dts), av_ts2str(pkt->dts));
552         return AVERROR(EINVAL);
553     }
554     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
555         av_log(s, AV_LOG_ERROR,
556                "pts (%s) < dts (%s) in stream %d\n",
557                av_ts2str(pkt->pts), av_ts2str(pkt->dts),
558                st->index);
559         return AVERROR(EINVAL);
560     }
561 
562     if (s->debug & FF_FDEBUG_TS)
563         av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%s dts2:%s\n",
564             av_ts2str(pkt->pts), av_ts2str(pkt->dts));
565 
566     sti->cur_dts      = pkt->dts;
567     sti->priv_pts->val = pkt->dts;
568 
569     /* update pts */
570     switch (st->codecpar->codec_type) {
571     case AVMEDIA_TYPE_AUDIO:
572         frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
573                      (*(AVFrame **)pkt->data)->nb_samples :
574                      av_get_audio_frame_duration2(st->codecpar, pkt->size);
575 
576         /* HACK/FIXME, we skip the initial 0 size packets as they are most
577          * likely equal to the encoder delay, but it would be better if we
578          * had the real timestamps from the encoder */
579         if (frame_size >= 0 && (pkt->size || sti->priv_pts->num != sti->priv_pts->den >> 1 || sti->priv_pts->val)) {
580             frac_add(sti->priv_pts, (int64_t)st->time_base.den * frame_size);
581         }
582         break;
583     case AVMEDIA_TYPE_VIDEO:
584         frac_add(sti->priv_pts, (int64_t)st->time_base.den * st->time_base.num);
585         break;
586     }
587     return 0;
588 }
589 FF_ENABLE_DEPRECATION_WARNINGS
590 #endif
591 
guess_pkt_duration(AVFormatContext *s, AVStream *st, AVPacket *pkt)592 static void guess_pkt_duration(AVFormatContext *s, AVStream *st, AVPacket *pkt)
593 {
594     if (pkt->duration < 0 && st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE) {
595         av_log(s, AV_LOG_WARNING, "Packet with invalid duration %"PRId64" in stream %d\n",
596                pkt->duration, pkt->stream_index);
597         pkt->duration = 0;
598     }
599 
600     if (pkt->duration)
601         return;
602 
603     switch (st->codecpar->codec_type) {
604     case AVMEDIA_TYPE_VIDEO:
605         if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0) {
606             pkt->duration = av_rescale_q(1, av_inv_q(st->avg_frame_rate),
607                                          st->time_base);
608         } else if (st->time_base.num * 1000LL > st->time_base.den)
609             pkt->duration = 1;
610         break;
611     case AVMEDIA_TYPE_AUDIO: {
612         int frame_size = av_get_audio_frame_duration2(st->codecpar, pkt->size);
613         if (frame_size && st->codecpar->sample_rate) {
614             pkt->duration = av_rescale_q(frame_size,
615                                          (AVRational){1, st->codecpar->sample_rate},
616                                          st->time_base);
617         }
618         break;
619         }
620     }
621 }
622 
handle_avoid_negative_ts(FFFormatContext *si, FFStream *sti, AVPacket *pkt)623 static void handle_avoid_negative_ts(FFFormatContext *si, FFStream *sti,
624                                      AVPacket *pkt)
625 {
626     AVFormatContext *const s = &si->pub;
627     int64_t offset;
628 
629     if (!AVOID_NEGATIVE_TS_ENABLED(si->avoid_negative_ts_status))
630         return;
631 
632     if (si->avoid_negative_ts_status == AVOID_NEGATIVE_TS_UNKNOWN) {
633         int use_pts = si->avoid_negative_ts_use_pts;
634         int64_t ts = use_pts ? pkt->pts : pkt->dts;
635         AVRational tb = sti->pub.time_base;
636 
637         if (ts == AV_NOPTS_VALUE)
638             return;
639 
640         /* Peek into the muxing queue to improve our estimate
641          * of the lowest timestamp if av_interleaved_write_frame() is used. */
642         for (const PacketListEntry *pktl = si->packet_buffer.head;
643              pktl; pktl = pktl->next) {
644             AVRational cmp_tb = s->streams[pktl->pkt.stream_index]->time_base;
645             int64_t cmp_ts = use_pts ? pktl->pkt.pts : pktl->pkt.dts;
646             if (cmp_ts == AV_NOPTS_VALUE)
647                 continue;
648             if (s->output_ts_offset)
649                 cmp_ts += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, cmp_tb);
650             if (av_compare_ts(cmp_ts, cmp_tb, ts, tb) < 0) {
651                 ts = cmp_ts;
652                 tb = cmp_tb;
653             }
654         }
655 
656         if (ts < 0 ||
657             ts > 0 && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
658             for (unsigned i = 0; i < s->nb_streams; i++) {
659                 AVStream *const st2  = s->streams[i];
660                 FFStream *const sti2 = ffstream(st2);
661                 sti2->mux_ts_offset = av_rescale_q_rnd(-ts, tb,
662                                                        st2->time_base,
663                                                        AV_ROUND_UP);
664             }
665         }
666         si->avoid_negative_ts_status = AVOID_NEGATIVE_TS_KNOWN;
667     }
668 
669     offset = sti->mux_ts_offset;
670 
671     if (pkt->dts != AV_NOPTS_VALUE)
672         pkt->dts += offset;
673     if (pkt->pts != AV_NOPTS_VALUE)
674         pkt->pts += offset;
675 
676     if (si->avoid_negative_ts_use_pts) {
677         if (pkt->pts != AV_NOPTS_VALUE && pkt->pts < 0) {
678             av_log(s, AV_LOG_WARNING, "failed to avoid negative "
679                    "pts %s in stream %d.\n"
680                    "Try -avoid_negative_ts 1 as a possible workaround.\n",
681                    av_ts2str(pkt->pts),
682                    pkt->stream_index
683             );
684         }
685     } else {
686         if (pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
687             av_log(s, AV_LOG_WARNING,
688                    "Packets poorly interleaved, failed to avoid negative "
689                    "timestamp %s in stream %d.\n"
690                    "Try -max_interleave_delta 0 as a possible workaround.\n",
691                    av_ts2str(pkt->dts),
692                    pkt->stream_index
693             );
694         }
695     }
696 }
697 
698 /**
699  * Shift timestamps and call muxer; the original pts/dts are not kept.
700  *
701  * FIXME: this function should NEVER get undefined pts/dts beside when the
702  * AVFMT_NOTIMESTAMPS is set.
703  * Those additional safety checks should be dropped once the correct checks
704  * are set in the callers.
705  */
write_packet(AVFormatContext *s, AVPacket *pkt)706 static int write_packet(AVFormatContext *s, AVPacket *pkt)
707 {
708     FFFormatContext *const si = ffformatcontext(s);
709     AVStream *const st = s->streams[pkt->stream_index];
710     FFStream *const sti = ffstream(st);
711     int ret;
712 
713     // If the timestamp offsetting below is adjusted, adjust
714     // ff_interleaved_peek similarly.
715     if (s->output_ts_offset) {
716         int64_t offset = av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
717 
718         if (pkt->dts != AV_NOPTS_VALUE)
719             pkt->dts += offset;
720         if (pkt->pts != AV_NOPTS_VALUE)
721             pkt->pts += offset;
722     }
723     handle_avoid_negative_ts(si, sti, pkt);
724 
725     if ((pkt->flags & AV_PKT_FLAG_UNCODED_FRAME)) {
726         AVFrame **frame = (AVFrame **)pkt->data;
727         av_assert0(pkt->size == sizeof(*frame));
728         ret = s->oformat->write_uncoded_frame(s, pkt->stream_index, frame, 0);
729     } else {
730         ret = s->oformat->write_packet(s, pkt);
731     }
732 
733     if (s->pb && ret >= 0) {
734         flush_if_needed(s);
735         if (s->pb->error < 0)
736             ret = s->pb->error;
737     }
738 
739     if (ret >= 0)
740         st->nb_frames++;
741 
742     return ret;
743 }
744 
check_packet(AVFormatContext *s, AVPacket *pkt)745 static int check_packet(AVFormatContext *s, AVPacket *pkt)
746 {
747     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
748         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
749                pkt->stream_index);
750         return AVERROR(EINVAL);
751     }
752 
753     if (s->streams[pkt->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
754         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
755         return AVERROR(EINVAL);
756     }
757 
758     return 0;
759 }
760 
prepare_input_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)761 static int prepare_input_packet(AVFormatContext *s, AVStream *st, AVPacket *pkt)
762 {
763     FFStream *const sti = ffstream(st);
764 #if !FF_API_COMPUTE_PKT_FIELDS2
765     /* sanitize the timestamps */
766     if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
767 
768         /* when there is no reordering (so dts is equal to pts), but
769          * only one of them is set, set the other as well */
770         if (!sti->reorder) {
771             if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE)
772                 pkt->pts = pkt->dts;
773             if (pkt->dts == AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE)
774                 pkt->dts = pkt->pts;
775         }
776 
777         /* check that the timestamps are set */
778         if (pkt->pts == AV_NOPTS_VALUE || pkt->dts == AV_NOPTS_VALUE) {
779             av_log(s, AV_LOG_ERROR,
780                    "Timestamps are unset in a packet for stream %d\n", st->index);
781             return AVERROR(EINVAL);
782         }
783 
784         /* check that the dts are increasing (or at least non-decreasing,
785          * if the format allows it */
786         if (sti->cur_dts != AV_NOPTS_VALUE &&
787             ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && sti->cur_dts >= pkt->dts) ||
788              sti->cur_dts > pkt->dts)) {
789             av_log(s, AV_LOG_ERROR,
790                    "Application provided invalid, non monotonically increasing "
791                    "dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
792                    st->index, sti->cur_dts, pkt->dts);
793             return AVERROR(EINVAL);
794         }
795 
796         if (pkt->pts < pkt->dts) {
797             av_log(s, AV_LOG_ERROR, "pts %" PRId64 " < dts %" PRId64 " in stream %d\n",
798                    pkt->pts, pkt->dts, st->index);
799             return AVERROR(EINVAL);
800         }
801     }
802 #endif
803     /* update flags */
804     if (sti->is_intra_only)
805         pkt->flags |= AV_PKT_FLAG_KEY;
806 
807     if (!pkt->data && !pkt->side_data_elems) {
808         /* Such empty packets signal EOS for the BSF API; so sanitize
809          * the packet by allocating data of size 0 (+ padding). */
810         av_buffer_unref(&pkt->buf);
811         return av_packet_make_refcounted(pkt);
812     }
813 
814     return 0;
815 }
816 
817 #define CHUNK_START 0x1000
818 
ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt, int (*compare)(AVFormatContext *, const AVPacket *, const AVPacket *))819 int ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
820                              int (*compare)(AVFormatContext *, const AVPacket *, const AVPacket *))
821 {
822     int ret;
823     FFFormatContext *const si = ffformatcontext(s);
824     PacketListEntry **next_point, *this_pktl;
825     AVStream *st = s->streams[pkt->stream_index];
826     FFStream *const sti = ffstream(st);
827     int chunked  = s->max_chunk_size || s->max_chunk_duration;
828 
829     this_pktl    = av_malloc(sizeof(*this_pktl));
830     if (!this_pktl) {
831         av_packet_unref(pkt);
832         return AVERROR(ENOMEM);
833     }
834     if ((ret = av_packet_make_refcounted(pkt)) < 0) {
835         av_free(this_pktl);
836         av_packet_unref(pkt);
837         return ret;
838     }
839 
840     av_packet_move_ref(&this_pktl->pkt, pkt);
841     pkt = &this_pktl->pkt;
842 
843     if (sti->last_in_packet_buffer) {
844         next_point = &(sti->last_in_packet_buffer->next);
845     } else {
846         next_point = &si->packet_buffer.head;
847     }
848 
849     if (chunked) {
850         uint64_t max= av_rescale_q_rnd(s->max_chunk_duration, AV_TIME_BASE_Q, st->time_base, AV_ROUND_UP);
851         sti->interleaver_chunk_size     += pkt->size;
852         sti->interleaver_chunk_duration += pkt->duration;
853         if (   (s->max_chunk_size && sti->interleaver_chunk_size > s->max_chunk_size)
854             || (max && sti->interleaver_chunk_duration           > max)) {
855             sti->interleaver_chunk_size = 0;
856             pkt->flags |= CHUNK_START;
857             if (max && sti->interleaver_chunk_duration > max) {
858                 int64_t syncoffset = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)*max/2;
859                 int64_t syncto = av_rescale(pkt->dts + syncoffset, 1, max)*max - syncoffset;
860 
861                 sti->interleaver_chunk_duration += (pkt->dts - syncto)/8 - max;
862             } else
863                 sti->interleaver_chunk_duration  = 0;
864         }
865     }
866     if (*next_point) {
867         if (chunked && !(pkt->flags & CHUNK_START))
868             goto next_non_null;
869 
870         if (compare(s, &si->packet_buffer.tail->pkt, pkt)) {
871             while (   *next_point
872                    && ((chunked && !((*next_point)->pkt.flags&CHUNK_START))
873                        || !compare(s, &(*next_point)->pkt, pkt)))
874                 next_point = &(*next_point)->next;
875             if (*next_point)
876                 goto next_non_null;
877         } else {
878             next_point = &(si->packet_buffer.tail->next);
879         }
880     }
881     av_assert1(!*next_point);
882 
883     si->packet_buffer.tail = this_pktl;
884 next_non_null:
885 
886     this_pktl->next = *next_point;
887 
888     sti->last_in_packet_buffer = *next_point = this_pktl;
889 
890     return 0;
891 }
892 
interleave_compare_dts(AVFormatContext *s, const AVPacket *next, const AVPacket *pkt)893 static int interleave_compare_dts(AVFormatContext *s, const AVPacket *next,
894                                                       const AVPacket *pkt)
895 {
896     AVStream *st  = s->streams[pkt->stream_index];
897     AVStream *st2 = s->streams[next->stream_index];
898     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
899                                   st->time_base);
900     if (s->audio_preload) {
901         int preload  = st ->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
902         int preload2 = st2->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
903         if (preload != preload2) {
904             int64_t ts, ts2;
905             preload  *= s->audio_preload;
906             preload2 *= s->audio_preload;
907             ts = av_rescale_q(pkt ->dts, st ->time_base, AV_TIME_BASE_Q) - preload;
908             ts2= av_rescale_q(next->dts, st2->time_base, AV_TIME_BASE_Q) - preload2;
909             if (ts == ts2) {
910                 ts  = ((uint64_t)pkt ->dts*st ->time_base.num*AV_TIME_BASE - (uint64_t)preload *st ->time_base.den)*st2->time_base.den
911                     - ((uint64_t)next->dts*st2->time_base.num*AV_TIME_BASE - (uint64_t)preload2*st2->time_base.den)*st ->time_base.den;
912                 ts2 = 0;
913             }
914             comp = (ts2 > ts) - (ts2 < ts);
915         }
916     }
917 
918     if (comp == 0)
919         return pkt->stream_index < next->stream_index;
920     return comp > 0;
921 }
922 
ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *pkt, int flush, int has_packet)923 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *pkt,
924                                  int flush, int has_packet)
925 {
926     FFFormatContext *const si = ffformatcontext(s);
927     int stream_count = 0;
928     int noninterleaved_count = 0;
929     int ret;
930     int eof = flush;
931 
932     if (has_packet) {
933         if ((ret = ff_interleave_add_packet(s, pkt, interleave_compare_dts)) < 0)
934             return ret;
935     }
936 
937     for (unsigned i = 0; i < s->nb_streams; i++) {
938         const AVStream *const st  = s->streams[i];
939         const FFStream *const sti = cffstream(st);
940         const AVCodecParameters *const par = st->codecpar;
941         if (sti->last_in_packet_buffer) {
942             ++stream_count;
943         } else if (par->codec_type != AVMEDIA_TYPE_ATTACHMENT &&
944                    par->codec_id != AV_CODEC_ID_VP8 &&
945                    par->codec_id != AV_CODEC_ID_VP9) {
946             ++noninterleaved_count;
947         }
948     }
949 
950     if (si->nb_interleaved_streams == stream_count)
951         flush = 1;
952 
953     if (s->max_interleave_delta > 0 &&
954         si->packet_buffer.head &&
955         !flush &&
956         si->nb_interleaved_streams == stream_count+noninterleaved_count
957     ) {
958         AVPacket *const top_pkt = &si->packet_buffer.head->pkt;
959         int64_t delta_dts = INT64_MIN;
960         int64_t top_dts = av_rescale_q(top_pkt->dts,
961                                        s->streams[top_pkt->stream_index]->time_base,
962                                        AV_TIME_BASE_Q);
963 
964         for (unsigned i = 0; i < s->nb_streams; i++) {
965             const AVStream *const st  = s->streams[i];
966             const FFStream *const sti = cffstream(st);
967             const PacketListEntry *const last = sti->last_in_packet_buffer;
968             int64_t last_dts;
969 
970             if (!last)
971                 continue;
972 
973             last_dts = av_rescale_q(last->pkt.dts,
974                                     st->time_base,
975                                     AV_TIME_BASE_Q);
976             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
977         }
978 
979         if (delta_dts > s->max_interleave_delta) {
980             av_log(s, AV_LOG_DEBUG,
981                    "Delay between the first packet and last packet in the "
982                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
983                    delta_dts, s->max_interleave_delta);
984             flush = 1;
985         }
986     }
987 
988     if (si->packet_buffer.head &&
989         eof &&
990         (s->flags & AVFMT_FLAG_SHORTEST) &&
991         si->shortest_end == AV_NOPTS_VALUE) {
992         AVPacket *const top_pkt = &si->packet_buffer.head->pkt;
993 
994         si->shortest_end = av_rescale_q(top_pkt->dts,
995                                        s->streams[top_pkt->stream_index]->time_base,
996                                        AV_TIME_BASE_Q);
997     }
998 
999     if (si->shortest_end != AV_NOPTS_VALUE) {
1000         while (si->packet_buffer.head) {
1001             PacketListEntry *pktl = si->packet_buffer.head;
1002             AVPacket *const top_pkt = &pktl->pkt;
1003             AVStream *const st = s->streams[top_pkt->stream_index];
1004             FFStream *const sti = ffstream(st);
1005             int64_t top_dts = av_rescale_q(top_pkt->dts, st->time_base,
1006                                         AV_TIME_BASE_Q);
1007 
1008             if (si->shortest_end + 1 >= top_dts)
1009                 break;
1010 
1011             si->packet_buffer.head = pktl->next;
1012             if (!si->packet_buffer.head)
1013                 si->packet_buffer.tail = NULL;
1014 
1015             if (sti->last_in_packet_buffer == pktl)
1016                 sti->last_in_packet_buffer = NULL;
1017 
1018             av_packet_unref(&pktl->pkt);
1019             av_freep(&pktl);
1020             flush = 0;
1021         }
1022     }
1023 
1024     if (stream_count && flush) {
1025         PacketListEntry *pktl = si->packet_buffer.head;
1026         AVStream *const st = s->streams[pktl->pkt.stream_index];
1027         FFStream *const sti = ffstream(st);
1028 
1029         if (sti->last_in_packet_buffer == pktl)
1030             sti->last_in_packet_buffer = NULL;
1031         avpriv_packet_list_get(&si->packet_buffer, pkt);
1032 
1033         return 1;
1034     } else {
1035         return 0;
1036     }
1037 }
1038 
ff_interleave_packet_passthrough(AVFormatContext *s, AVPacket *pkt, int flush, int has_packet)1039 int ff_interleave_packet_passthrough(AVFormatContext *s, AVPacket *pkt,
1040                                      int flush, int has_packet)
1041 {
1042     return has_packet;
1043 }
1044 
ff_get_muxer_ts_offset(AVFormatContext *s, int stream_index, int64_t *offset)1045 int ff_get_muxer_ts_offset(AVFormatContext *s, int stream_index, int64_t *offset)
1046 {
1047     AVStream *st;
1048 
1049     if (stream_index < 0 || stream_index >= s->nb_streams)
1050         return AVERROR(EINVAL);
1051 
1052     st = s->streams[stream_index];
1053     *offset = ffstream(st)->mux_ts_offset;
1054 
1055     if (s->output_ts_offset)
1056         *offset += av_rescale_q(s->output_ts_offset, AV_TIME_BASE_Q, st->time_base);
1057 
1058     return 0;
1059 }
1060 
ff_interleaved_peek(AVFormatContext *s, int stream)1061 const AVPacket *ff_interleaved_peek(AVFormatContext *s, int stream)
1062 {
1063     FFFormatContext *const si = ffformatcontext(s);
1064     PacketListEntry *pktl = si->packet_buffer.head;
1065     while (pktl) {
1066         if (pktl->pkt.stream_index == stream) {
1067             return &pktl->pkt;
1068         }
1069         pktl = pktl->next;
1070     }
1071     return NULL;
1072 }
1073 
check_bitstream(AVFormatContext *s, FFStream *sti, AVPacket *pkt)1074 static int check_bitstream(AVFormatContext *s, FFStream *sti, AVPacket *pkt)
1075 {
1076     int ret;
1077 
1078     if (!(s->flags & AVFMT_FLAG_AUTO_BSF))
1079         return 1;
1080 
1081     if (s->oformat->check_bitstream) {
1082         if (!sti->bitstream_checked) {
1083             if ((ret = s->oformat->check_bitstream(s, &sti->pub, pkt)) < 0)
1084                 return ret;
1085             else if (ret == 1)
1086                 sti->bitstream_checked = 1;
1087         }
1088     }
1089 
1090     return 1;
1091 }
1092 
interleaved_write_packet(AVFormatContext *s, AVPacket *pkt, int flush, int has_packet)1093 static int interleaved_write_packet(AVFormatContext *s, AVPacket *pkt,
1094                                     int flush, int has_packet)
1095 {
1096     FFFormatContext *const si = ffformatcontext(s);
1097     for (;; ) {
1098         int ret = si->interleave_packet(s, pkt, flush, has_packet);
1099         if (ret <= 0)
1100             return ret;
1101 
1102         has_packet = 0;
1103 
1104         ret = write_packet(s, pkt);
1105         av_packet_unref(pkt);
1106         if (ret < 0)
1107             return ret;
1108     }
1109 }
1110 
write_packet_common(AVFormatContext *s, AVStream *st, AVPacket *pkt, int interleaved)1111 static int write_packet_common(AVFormatContext *s, AVStream *st, AVPacket *pkt, int interleaved)
1112 {
1113     int ret;
1114 
1115     if (s->debug & FF_FDEBUG_TS)
1116         av_log(s, AV_LOG_DEBUG, "%s size:%d dts:%s pts:%s\n", __FUNCTION__,
1117                pkt->size, av_ts2str(pkt->dts), av_ts2str(pkt->pts));
1118 
1119     guess_pkt_duration(s, st, pkt);
1120 
1121 #if FF_API_COMPUTE_PKT_FIELDS2
1122     if ((ret = compute_muxer_pkt_fields(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
1123         return ret;
1124 #endif
1125 
1126     if (interleaved) {
1127         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
1128             return AVERROR(EINVAL);
1129         return interleaved_write_packet(s, pkt, 0, 1);
1130     } else {
1131         return write_packet(s, pkt);
1132     }
1133 }
1134 
write_packets_from_bsfs(AVFormatContext *s, AVStream *st, AVPacket *pkt, int interleaved)1135 static int write_packets_from_bsfs(AVFormatContext *s, AVStream *st, AVPacket *pkt, int interleaved)
1136 {
1137     FFStream *const sti = ffstream(st);
1138     AVBSFContext *const bsfc = sti->bsfc;
1139     int ret;
1140 
1141     if ((ret = av_bsf_send_packet(bsfc, pkt)) < 0) {
1142         av_log(s, AV_LOG_ERROR,
1143                 "Failed to send packet to filter %s for stream %d\n",
1144                 bsfc->filter->name, st->index);
1145         return ret;
1146     }
1147 
1148     do {
1149         ret = av_bsf_receive_packet(bsfc, pkt);
1150         if (ret < 0) {
1151             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
1152                 return 0;
1153             av_log(s, AV_LOG_ERROR, "Error applying bitstream filters to an output "
1154                    "packet for stream #%d: %s\n", st->index, av_err2str(ret));
1155             if (!(s->error_recognition & AV_EF_EXPLODE) && ret != AVERROR(ENOMEM))
1156                 continue;
1157             return ret;
1158         }
1159         av_packet_rescale_ts(pkt, bsfc->time_base_out, st->time_base);
1160         ret = write_packet_common(s, st, pkt, interleaved);
1161         if (ret >= 0 && !interleaved) // a successful write_packet_common already unrefed pkt for interleaved
1162             av_packet_unref(pkt);
1163     } while (ret >= 0);
1164 
1165     return ret;
1166 }
1167 
write_packets_common(AVFormatContext *s, AVPacket *pkt, int interleaved)1168 static int write_packets_common(AVFormatContext *s, AVPacket *pkt, int interleaved)
1169 {
1170     AVStream *st;
1171     FFStream *sti;
1172     int ret = check_packet(s, pkt);
1173     if (ret < 0)
1174         return ret;
1175     st = s->streams[pkt->stream_index];
1176     sti = ffstream(st);
1177 
1178     ret = prepare_input_packet(s, st, pkt);
1179     if (ret < 0)
1180         return ret;
1181 
1182     ret = check_bitstream(s, sti, pkt);
1183     if (ret < 0)
1184         return ret;
1185 
1186     if (sti->bsfc) {
1187         return write_packets_from_bsfs(s, st, pkt, interleaved);
1188     } else {
1189         return write_packet_common(s, st, pkt, interleaved);
1190     }
1191 }
1192 
av_write_frame(AVFormatContext *s, AVPacket *in)1193 int av_write_frame(AVFormatContext *s, AVPacket *in)
1194 {
1195     FFFormatContext *const si = ffformatcontext(s);
1196     AVPacket *pkt = si->parse_pkt;
1197     int ret;
1198 
1199     if (!in) {
1200         if (s->oformat->flags & AVFMT_ALLOW_FLUSH) {
1201             ret = s->oformat->write_packet(s, NULL);
1202             flush_if_needed(s);
1203             if (ret >= 0 && s->pb && s->pb->error < 0)
1204                 ret = s->pb->error;
1205             return ret;
1206         }
1207         return 1;
1208     }
1209 
1210     if (in->flags & AV_PKT_FLAG_UNCODED_FRAME) {
1211         pkt = in;
1212     } else {
1213         /* We don't own in, so we have to make sure not to modify it.
1214          * (ff_write_chained() relies on this fact.)
1215          * The following avoids copying in's data unnecessarily.
1216          * Copying side data is unavoidable as a bitstream filter
1217          * may change it, e.g. free it on errors. */
1218         pkt->data = in->data;
1219         pkt->size = in->size;
1220         ret = av_packet_copy_props(pkt, in);
1221         if (ret < 0)
1222             return ret;
1223         if (in->buf) {
1224             pkt->buf = av_buffer_ref(in->buf);
1225             if (!pkt->buf) {
1226                 ret = AVERROR(ENOMEM);
1227                 goto fail;
1228             }
1229         }
1230     }
1231 
1232     ret = write_packets_common(s, pkt, 0/*non-interleaved*/);
1233 
1234 fail:
1235     // Uncoded frames using the noninterleaved codepath are also freed here
1236     av_packet_unref(pkt);
1237     return ret;
1238 }
1239 
av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)1240 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
1241 {
1242     int ret;
1243 
1244     if (pkt) {
1245         ret = write_packets_common(s, pkt, 1/*interleaved*/);
1246         if (ret < 0)
1247             av_packet_unref(pkt);
1248         return ret;
1249     } else {
1250         av_log(s, AV_LOG_TRACE, "av_interleaved_write_frame FLUSH\n");
1251         return interleaved_write_packet(s, ffformatcontext(s)->parse_pkt, 1/*flush*/, 0);
1252     }
1253 }
1254 
av_write_trailer(AVFormatContext *s)1255 int av_write_trailer(AVFormatContext *s)
1256 {
1257     FFFormatContext *const si = ffformatcontext(s);
1258     AVPacket *const pkt = si->parse_pkt;
1259     int ret1, ret = 0;
1260 
1261     for (unsigned i = 0; i < s->nb_streams; i++) {
1262         AVStream *const st  = s->streams[i];
1263         FFStream *const sti = ffstream(st);
1264         if (sti->bsfc) {
1265             ret1 = write_packets_from_bsfs(s, st, pkt, 1/*interleaved*/);
1266             if (ret1 < 0)
1267                 av_packet_unref(pkt);
1268             if (ret >= 0)
1269                 ret = ret1;
1270         }
1271     }
1272     ret1 = interleaved_write_packet(s, pkt, 1, 0);
1273     if (ret >= 0)
1274         ret = ret1;
1275 
1276     if (s->oformat->write_trailer) {
1277         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1278             avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
1279         if (ret >= 0) {
1280         ret = s->oformat->write_trailer(s);
1281         } else {
1282             s->oformat->write_trailer(s);
1283         }
1284     }
1285 
1286     deinit_muxer(s);
1287 
1288     if (s->pb)
1289        avio_flush(s->pb);
1290     if (ret == 0)
1291        ret = s->pb ? s->pb->error : 0;
1292     for (unsigned i = 0; i < s->nb_streams; i++) {
1293         av_freep(&s->streams[i]->priv_data);
1294         av_freep(&ffstream(s->streams[i])->index_entries);
1295     }
1296     if (s->oformat->priv_class)
1297         av_opt_free(s->priv_data);
1298     av_freep(&s->priv_data);
1299     av_packet_unref(si->pkt);
1300     return ret;
1301 }
1302 
av_get_output_timestamp(struct AVFormatContext *s, int stream, int64_t *dts, int64_t *wall)1303 int av_get_output_timestamp(struct AVFormatContext *s, int stream,
1304                             int64_t *dts, int64_t *wall)
1305 {
1306     if (!s->oformat || !s->oformat->get_output_timestamp)
1307         return AVERROR(ENOSYS);
1308     s->oformat->get_output_timestamp(s, stream, dts, wall);
1309     return 0;
1310 }
1311 
ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)1312 int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
1313 {
1314     int ret;
1315     const AVBitStreamFilter *bsf;
1316     FFStream *const sti = ffstream(st);
1317     AVBSFContext *bsfc;
1318 
1319     av_assert0(!sti->bsfc);
1320 
1321     if (!(bsf = av_bsf_get_by_name(name))) {
1322         av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter '%s'\n", name);
1323         return AVERROR_BSF_NOT_FOUND;
1324     }
1325 
1326     if ((ret = av_bsf_alloc(bsf, &bsfc)) < 0)
1327         return ret;
1328 
1329     bsfc->time_base_in = st->time_base;
1330     if ((ret = avcodec_parameters_copy(bsfc->par_in, st->codecpar)) < 0) {
1331         av_bsf_free(&bsfc);
1332         return ret;
1333     }
1334 
1335     if (args && bsfc->filter->priv_class) {
1336         if ((ret = av_set_options_string(bsfc->priv_data, args, "=", ":")) < 0) {
1337             av_bsf_free(&bsfc);
1338             return ret;
1339         }
1340     }
1341 
1342     if ((ret = av_bsf_init(bsfc)) < 0) {
1343         av_bsf_free(&bsfc);
1344         return ret;
1345     }
1346 
1347     sti->bsfc = bsfc;
1348 
1349     av_log(NULL, AV_LOG_VERBOSE,
1350            "Automatically inserted bitstream filter '%s'; args='%s'\n",
1351            name, args ? args : "");
1352     return 1;
1353 }
1354 
ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src, int interleave)1355 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
1356                      AVFormatContext *src, int interleave)
1357 {
1358     int64_t pts = pkt->pts, dts = pkt->dts, duration = pkt->duration;
1359     int stream_index = pkt->stream_index;
1360     AVRational time_base = pkt->time_base;
1361     int ret;
1362 
1363     pkt->stream_index = dst_stream;
1364 
1365     av_packet_rescale_ts(pkt,
1366                          src->streams[stream_index]->time_base,
1367                          dst->streams[dst_stream]->time_base);
1368 
1369     if (!interleave) {
1370         ret = av_write_frame(dst, pkt);
1371         /* We only have to backup and restore the fields that
1372          * we changed ourselves, because av_write_frame() does not
1373          * modify the packet given to it. */
1374         pkt->pts          = pts;
1375         pkt->dts          = dts;
1376         pkt->duration     = duration;
1377         pkt->stream_index = stream_index;
1378         pkt->time_base    = time_base;
1379     } else
1380         ret = av_interleaved_write_frame(dst, pkt);
1381 
1382     return ret;
1383 }
1384 
uncoded_frame_free(void *unused, uint8_t *data)1385 static void uncoded_frame_free(void *unused, uint8_t *data)
1386 {
1387     av_frame_free((AVFrame **)data);
1388     av_free(data);
1389 }
1390 
write_uncoded_frame_internal(AVFormatContext *s, int stream_index, AVFrame *frame, int interleaved)1391 static int write_uncoded_frame_internal(AVFormatContext *s, int stream_index,
1392                                         AVFrame *frame, int interleaved)
1393 {
1394     FFFormatContext *const si = ffformatcontext(s);
1395     AVPacket *pkt = si->parse_pkt;
1396 
1397     av_assert0(s->oformat);
1398     if (!s->oformat->write_uncoded_frame) {
1399         av_frame_free(&frame);
1400         return AVERROR(ENOSYS);
1401     }
1402 
1403     if (!frame) {
1404         pkt = NULL;
1405     } else {
1406         size_t   bufsize = sizeof(frame) + AV_INPUT_BUFFER_PADDING_SIZE;
1407         AVFrame **framep = av_mallocz(bufsize);
1408 
1409         if (!framep)
1410             goto fail;
1411         pkt->buf = av_buffer_create((void *)framep, bufsize,
1412                                    uncoded_frame_free, NULL, 0);
1413         if (!pkt->buf) {
1414             av_free(framep);
1415     fail:
1416             av_frame_free(&frame);
1417             return AVERROR(ENOMEM);
1418         }
1419         *framep = frame;
1420 
1421         pkt->data         = (void *)framep;
1422         pkt->size         = sizeof(frame);
1423         pkt->pts          =
1424         pkt->dts          = frame->pts;
1425         pkt->duration     = frame->pkt_duration;
1426         pkt->stream_index = stream_index;
1427         pkt->flags |= AV_PKT_FLAG_UNCODED_FRAME;
1428     }
1429 
1430     return interleaved ? av_interleaved_write_frame(s, pkt) :
1431                          av_write_frame(s, pkt);
1432 }
1433 
av_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame)1434 int av_write_uncoded_frame(AVFormatContext *s, int stream_index,
1435                            AVFrame *frame)
1436 {
1437     return write_uncoded_frame_internal(s, stream_index, frame, 0);
1438 }
1439 
av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame)1440 int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index,
1441                                        AVFrame *frame)
1442 {
1443     return write_uncoded_frame_internal(s, stream_index, frame, 1);
1444 }
1445 
av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)1446 int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index)
1447 {
1448     av_assert0(s->oformat);
1449     if (!s->oformat->write_uncoded_frame)
1450         return AVERROR(ENOSYS);
1451     return s->oformat->write_uncoded_frame(s, stream_index, NULL,
1452                                            AV_WRITE_UNCODED_FRAME_QUERY);
1453 }
1454