FFmpeg
ffmpeg_mux_init.c
Go to the documentation of this file.
1 /*
2  * Muxer/output file setup.
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <string.h>
22 
23 #include "cmdutils.h"
24 #include "ffmpeg.h"
25 #include "ffmpeg_mux.h"
26 #include "ffmpeg_sched.h"
27 #include "fopen_utf8.h"
28 
29 #include "libavformat/avformat.h"
30 #include "libavformat/avio.h"
31 
32 #include "libavcodec/avcodec.h"
33 
34 #include "libavfilter/avfilter.h"
35 
36 #include "libavutil/avassert.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/avutil.h"
39 #include "libavutil/bprint.h"
40 #include "libavutil/dict.h"
41 #include "libavutil/display.h"
42 #include "libavutil/getenv_utf8.h"
43 #include "libavutil/iamf.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/log.h"
46 #include "libavutil/mem.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/pixdesc.h"
50 
51 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
52 
53 static int check_opt_bitexact(void *ctx, const AVDictionary *opts,
54  const char *opt_name, int flag)
55 {
56  const AVDictionaryEntry *e = av_dict_get(opts, opt_name, NULL, 0);
57 
58  if (e) {
59  const AVOption *o = av_opt_find(ctx, opt_name, NULL, 0, 0);
60  int val = 0;
61  if (!o)
62  return 0;
63  av_opt_eval_flags(ctx, o, e->value, &val);
64  return !!(val & flag);
65  }
66  return 0;
67 }
68 
70  MuxStream *ms, const AVCodec **enc)
71 {
72  OutputStream *ost = &ms->ost;
73  enum AVMediaType type = ost->type;
74  const char *codec_name = NULL;
75 
76  *enc = NULL;
77 
78  opt_match_per_stream_str(ost, &o->codec_names, s, ost->st, &codec_name);
79 
80  if (type != AVMEDIA_TYPE_VIDEO &&
83  if (codec_name && strcmp(codec_name, "copy")) {
84  const char *type_str = av_get_media_type_string(type);
86  "Encoder '%s' specified, but only '-codec copy' supported "
87  "for %s streams\n", codec_name, type_str);
88  return AVERROR(ENOSYS);
89  }
90  return 0;
91  }
92 
93  if (!codec_name) {
94  ms->par_in->codec_id = av_guess_codec(s->oformat, NULL, s->url, NULL, ost->type);
96  if (!*enc) {
97  av_log(ost, AV_LOG_FATAL, "Automatic encoder selection failed "
98  "Default encoder for format %s (codec %s) is "
99  "probably disabled. Please choose an encoder manually.\n",
100  s->oformat->name, avcodec_get_name(ms->par_in->codec_id));
102  }
103  } else if (strcmp(codec_name, "copy")) {
104  int ret = find_codec(ost, codec_name, ost->type, 1, enc);
105  if (ret < 0)
106  return ret;
107  ms->par_in->codec_id = (*enc)->id;
108  }
109 
110  return 0;
111 }
112 
113 static char *get_line(AVIOContext *s, AVBPrint *bprint)
114 {
115  char c;
116 
117  while ((c = avio_r8(s)) && c != '\n')
118  av_bprint_chars(bprint, c, 1);
119 
120  if (!av_bprint_is_complete(bprint))
121  return NULL;
122 
123  return bprint->str;
124 }
125 
126 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
127 {
128  int i, ret = -1;
129  char filename[1000];
130  char *env_avconv_datadir = getenv_utf8("AVCONV_DATADIR");
131  char *env_home = getenv_utf8("HOME");
132  const char *base[3] = { env_avconv_datadir,
133  env_home,
134  AVCONV_DATADIR,
135  };
136 
137  for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
138  if (!base[i])
139  continue;
140  if (codec_name) {
141  snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
142  i != 1 ? "" : "/.avconv", codec_name, preset_name);
143  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
144  }
145  if (ret < 0) {
146  snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
147  i != 1 ? "" : "/.avconv", preset_name);
148  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
149  }
150  }
151  freeenv_utf8(env_home);
152  freeenv_utf8(env_avconv_datadir);
153  return ret;
154 }
155 
156 typedef struct EncStatsFile {
157  char *path;
159 } EncStatsFile;
160 
163 
164 static int enc_stats_get_file(AVIOContext **io, const char *path)
165 {
166  EncStatsFile *esf;
167  int ret;
168 
169  for (int i = 0; i < nb_enc_stats_files; i++)
170  if (!strcmp(path, enc_stats_files[i].path)) {
171  *io = enc_stats_files[i].io;
172  return 0;
173  }
174 
176  if (ret < 0)
177  return ret;
178 
180 
181  ret = avio_open2(&esf->io, path, AVIO_FLAG_WRITE, &int_cb, NULL);
182  if (ret < 0) {
183  av_log(NULL, AV_LOG_ERROR, "Error opening stats file '%s': %s\n",
184  path, av_err2str(ret));
185  return ret;
186  }
187 
188  esf->path = av_strdup(path);
189  if (!esf->path)
190  return AVERROR(ENOMEM);
191 
192  *io = esf->io;
193 
194  return 0;
195 }
196 
198 {
199  for (int i = 0; i < nb_enc_stats_files; i++) {
200  av_freep(&enc_stats_files[i].path);
202  }
204  nb_enc_stats_files = 0;
205 }
206 
207 static int unescape(char **pdst, size_t *dst_len,
208  const char **pstr, char delim)
209 {
210  const char *str = *pstr;
211  char *dst;
212  size_t len, idx;
213 
214  *pdst = NULL;
215 
216  len = strlen(str);
217  if (!len)
218  return 0;
219 
220  dst = av_malloc(len + 1);
221  if (!dst)
222  return AVERROR(ENOMEM);
223 
224  for (idx = 0; *str; idx++, str++) {
225  if (str[0] == '\\' && str[1])
226  str++;
227  else if (*str == delim)
228  break;
229 
230  dst[idx] = *str;
231  }
232  if (!idx) {
233  av_freep(&dst);
234  return 0;
235  }
236 
237  dst[idx] = 0;
238 
239  *pdst = dst;
240  *dst_len = idx;
241  *pstr = str;
242 
243  return 0;
244 }
245 
246 static int enc_stats_init(OutputStream *ost, EncStats *es, int pre,
247  const char *path, const char *fmt_spec)
248 {
249  static const struct {
250  enum EncStatsType type;
251  const char *str;
252  unsigned pre_only:1;
253  unsigned post_only:1;
254  unsigned need_input_data:1;
255  } fmt_specs[] = {
256  { ENC_STATS_FILE_IDX, "fidx" },
257  { ENC_STATS_STREAM_IDX, "sidx" },
258  { ENC_STATS_FRAME_NUM, "n" },
259  { ENC_STATS_FRAME_NUM_IN, "ni", 0, 0, 1 },
260  { ENC_STATS_TIMEBASE, "tb" },
261  { ENC_STATS_TIMEBASE_IN, "tbi", 0, 0, 1 },
262  { ENC_STATS_PTS, "pts" },
263  { ENC_STATS_PTS_TIME, "t" },
264  { ENC_STATS_PTS_IN, "ptsi", 0, 0, 1 },
265  { ENC_STATS_PTS_TIME_IN, "ti", 0, 0, 1 },
266  { ENC_STATS_DTS, "dts", 0, 1 },
267  { ENC_STATS_DTS_TIME, "dt", 0, 1 },
268  { ENC_STATS_SAMPLE_NUM, "sn", 1 },
269  { ENC_STATS_NB_SAMPLES, "samp", 1 },
270  { ENC_STATS_PKT_SIZE, "size", 0, 1 },
271  { ENC_STATS_BITRATE, "br", 0, 1 },
272  { ENC_STATS_AVG_BITRATE, "abr", 0, 1 },
273  { ENC_STATS_KEYFRAME, "key", 0, 1 },
274  };
275  const char *next = fmt_spec;
276 
277  int ret;
278 
279  while (*next) {
281  char *val;
282  size_t val_len;
283 
284  // get the sequence up until next opening brace
285  ret = unescape(&val, &val_len, &next, '{');
286  if (ret < 0)
287  return ret;
288 
289  if (val) {
291  if (ret < 0) {
292  av_freep(&val);
293  return ret;
294  }
295 
296  c = &es->components[es->nb_components - 1];
297  c->type = ENC_STATS_LITERAL;
298  c->str = val;
299  c->str_len = val_len;
300  }
301 
302  if (!*next)
303  break;
304  next++;
305 
306  // get the part inside braces
307  ret = unescape(&val, &val_len, &next, '}');
308  if (ret < 0)
309  return ret;
310 
311  if (!val) {
313  "Empty formatting directive in: %s\n", fmt_spec);
314  return AVERROR(EINVAL);
315  }
316 
317  if (!*next) {
319  "Missing closing brace in: %s\n", fmt_spec);
320  ret = AVERROR(EINVAL);
321  goto fail;
322  }
323  next++;
324 
326  if (ret < 0)
327  goto fail;
328 
329  c = &es->components[es->nb_components - 1];
330 
331  for (size_t i = 0; i < FF_ARRAY_ELEMS(fmt_specs); i++) {
332  if (!strcmp(val, fmt_specs[i].str)) {
333  if ((pre && fmt_specs[i].post_only) || (!pre && fmt_specs[i].pre_only)) {
335  "Format directive '%s' may only be used %s-encoding\n",
336  val, pre ? "post" : "pre");
337  ret = AVERROR(EINVAL);
338  goto fail;
339  }
340 
341  c->type = fmt_specs[i].type;
342 
343  if (fmt_specs[i].need_input_data && !ost->ist) {
345  "Format directive '%s' is unavailable, because "
346  "this output stream has no associated input stream\n",
347  val);
348  }
349 
350  break;
351  }
352  }
353 
354  if (!c->type) {
355  av_log(NULL, AV_LOG_ERROR, "Invalid format directive: %s\n", val);
356  ret = AVERROR(EINVAL);
357  goto fail;
358  }
359 
360 fail:
361  av_freep(&val);
362  if (ret < 0)
363  return ret;
364  }
365 
366  ret = pthread_mutex_init(&es->lock, NULL);
367  if (ret)
368  return AVERROR(ret);
369  es->lock_initialized = 1;
370 
371  ret = enc_stats_get_file(&es->io, path);
372  if (ret < 0)
373  return ret;
374 
375  return 0;
376 }
377 
378 static const char *output_stream_item_name(void *obj)
379 {
380  const MuxStream *ms = obj;
381 
382  return ms->log_name;
383 }
384 
385 static const AVClass output_stream_class = {
386  .class_name = "OutputStream",
387  .version = LIBAVUTIL_VERSION_INT,
388  .item_name = output_stream_item_name,
389  .category = AV_CLASS_CATEGORY_MUXER,
390 };
391 
393 {
394  const char *type_str = av_get_media_type_string(type);
395  MuxStream *ms;
396 
397  ms = allocate_array_elem(&mux->of.streams, sizeof(*ms), &mux->of.nb_streams);
398  if (!ms)
399  return NULL;
400 
401  ms->ost.file = &mux->of;
402  ms->ost.index = mux->of.nb_streams - 1;
403  ms->ost.type = type;
404 
406 
407  ms->sch_idx = -1;
408  ms->sch_idx_enc = -1;
409 
410  snprintf(ms->log_name, sizeof(ms->log_name), "%cost#%d:%d",
411  type_str ? *type_str : '?', mux->of.index, ms->ost.index);
412 
413  return ms;
414 }
415 
417  OutputStream *ost, char **dst)
418 {
419  const char *filters = NULL;
421 
422  if (!ost->ist) {
423  if (filters) {
425  "Filtergraph '%s' was specified for a stream fed from a complex "
426  "filtergraph. Simple and complex filtering cannot be used "
427  "together for the same stream.\n", filters);
428  return AVERROR(EINVAL);
429  }
430  return 0;
431  }
432 
433  if (filters)
434  *dst = av_strdup(filters);
435  else
436  *dst = av_strdup(ost->type == AVMEDIA_TYPE_VIDEO ? "null" : "anull");
437  return *dst ? 0 : AVERROR(ENOMEM);
438 }
439 
440 static int parse_matrix_coeffs(void *logctx, uint16_t *dest, const char *str)
441 {
442  const char *p = str;
443  for (int i = 0;; i++) {
444  dest[i] = atoi(p);
445  if (i == 63)
446  break;
447  p = strchr(p, ',');
448  if (!p) {
449  av_log(logctx, AV_LOG_FATAL,
450  "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
451  return AVERROR(EINVAL);
452  }
453  p++;
454  }
455 
456  return 0;
457 }
458 
460 {
461  for (; *formats != AV_PIX_FMT_NONE; formats++)
462  if (*formats == format)
463  return 1;
464  return 0;
465 }
466 
467 static enum AVPixelFormat
469 {
470  const enum AVPixelFormat *p;
472  //FIXME: This should check for AV_PIX_FMT_FLAG_ALPHA after PAL8 pixel format without alpha is implemented
473  int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
474  enum AVPixelFormat best= AV_PIX_FMT_NONE;
475  int ret;
476 
478  0, (const void **) &p, NULL);
479  if (ret < 0)
480  return AV_PIX_FMT_NONE;
481 
482  for (; *p != AV_PIX_FMT_NONE; p++) {
483  best = av_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
484  if (*p == target)
485  break;
486  }
487  if (*p == AV_PIX_FMT_NONE) {
488  if (target != AV_PIX_FMT_NONE)
490  "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
491  av_get_pix_fmt_name(target),
492  avctx->codec->name,
493  av_get_pix_fmt_name(best));
494  return best;
495  }
496  return target;
497 }
498 
499 static enum AVPixelFormat pix_fmt_parse(OutputStream *ost, const char *name)
500 {
501  const enum AVPixelFormat *fmts;
502  enum AVPixelFormat fmt;
503  int ret;
504 
505  fmt = av_get_pix_fmt(name);
506  if (fmt == AV_PIX_FMT_NONE) {
507  av_log(ost, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", name);
508  return AV_PIX_FMT_NONE;
509  }
510 
512  0, (const void **) &fmts, NULL);
513  if (ret < 0)
514  return AV_PIX_FMT_NONE;
515 
516  /* when the user specified-format is an alias for an endianness-specific
517  * one (e.g. rgb48 -> rgb48be/le), it gets translated into the native
518  * endianness by av_get_pix_fmt();
519  * the following code handles the case when the native endianness is not
520  * supported by the encoder, but the other one is */
521  if (fmts && !pixfmt_in_list(fmts, fmt)) {
522  const char *name_canonical = av_get_pix_fmt_name(fmt);
523  int len = strlen(name_canonical);
524 
525  if (strcmp(name, name_canonical) &&
526  (!strcmp(name_canonical + len - 2, "le") ||
527  !strcmp(name_canonical + len - 2, "be"))) {
528  char name_other[64];
529  enum AVPixelFormat fmt_other;
530 
531  snprintf(name_other, sizeof(name_other), "%s%ce",
532  name, name_canonical[len - 2] == 'l' ? 'b' : 'l');
533  fmt_other = av_get_pix_fmt(name_other);
534  if (fmt_other != AV_PIX_FMT_NONE && pixfmt_in_list(fmts, fmt_other)) {
535  av_log(ost, AV_LOG_VERBOSE, "Mapping pixel format %s->%s\n",
536  name, name_other);
537  fmt = fmt_other;
538  }
539  }
540  }
541 
542  if (fmts && !pixfmt_in_list(fmts, fmt))
543  fmt = choose_pixel_fmt(ost->enc->enc_ctx, fmt);
544 
545  return fmt;
546 }
547 
548 static int new_stream_video(Muxer *mux, const OptionsContext *o,
549  OutputStream *ost, int *keep_pix_fmt,
550  enum VideoSyncMethod *vsync_method)
551 {
552  MuxStream *ms = ms_from_ost(ost);
553  AVFormatContext *oc = mux->fc;
554  AVStream *st;
555  const char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
556  int ret = 0;
557 
558  st = ost->st;
559 
560  opt_match_per_stream_str(ost, &o->frame_rates, oc, st, &frame_rate);
561  if (frame_rate && av_parse_video_rate(&ms->frame_rate, frame_rate) < 0) {
562  av_log(ost, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
563  return AVERROR(EINVAL);
564  }
565 
566  opt_match_per_stream_str(ost, &o->max_frame_rates, oc, st, &max_frame_rate);
567  if (max_frame_rate && av_parse_video_rate(&ms->max_frame_rate, max_frame_rate) < 0) {
568  av_log(ost, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
569  return AVERROR(EINVAL);
570  }
571 
572  if (frame_rate && max_frame_rate) {
573  av_log(ost, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
574  return AVERROR(EINVAL);
575  }
576 
577  opt_match_per_stream_str(ost, &o->frame_aspect_ratios, oc, st, &frame_aspect_ratio);
578  if (frame_aspect_ratio) {
579  AVRational q;
580  if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
581  q.num <= 0 || q.den <= 0) {
582  av_log(ost, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
583  return AVERROR(EINVAL);
584  }
585  ost->frame_aspect_ratio = q;
586  }
587 
588  if (ost->enc) {
589  AVCodecContext *video_enc = ost->enc->enc_ctx;
590  const char *p = NULL, *fps_mode = NULL;
591  const char *frame_size = NULL;
592  const char *frame_pix_fmt = NULL;
593  const char *intra_matrix = NULL, *inter_matrix = NULL;
594  const char *chroma_intra_matrix = NULL;
595  int do_pass = 0;
596  int i;
597 
599  if (frame_size) {
600  ret = av_parse_video_size(&video_enc->width, &video_enc->height, frame_size);
601  if (ret < 0) {
602  av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
603  return AVERROR(EINVAL);
604  }
605  }
606 
607  opt_match_per_stream_str(ost, &o->frame_pix_fmts, oc, st, &frame_pix_fmt);
608  if (frame_pix_fmt && *frame_pix_fmt == '+') {
609  *keep_pix_fmt = 1;
610  if (!*++frame_pix_fmt)
611  frame_pix_fmt = NULL;
612  }
613  if (frame_pix_fmt) {
614  video_enc->pix_fmt = pix_fmt_parse(ost, frame_pix_fmt);
615  if (video_enc->pix_fmt == AV_PIX_FMT_NONE)
616  return AVERROR(EINVAL);
617  }
618 
619  opt_match_per_stream_str(ost, &o->intra_matrices, oc, st, &intra_matrix);
620  if (intra_matrix) {
621  if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64)))
622  return AVERROR(ENOMEM);
623 
624  ret = parse_matrix_coeffs(ost, video_enc->intra_matrix, intra_matrix);
625  if (ret < 0)
626  return ret;
627  }
628  opt_match_per_stream_str(ost, &o->chroma_intra_matrices, oc, st, &chroma_intra_matrix);
629  if (chroma_intra_matrix) {
630  if (!(video_enc->chroma_intra_matrix = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64)))
631  return AVERROR(ENOMEM);
632  ret = parse_matrix_coeffs(ost, video_enc->chroma_intra_matrix, chroma_intra_matrix);
633  if (ret < 0)
634  return ret;
635  }
636  opt_match_per_stream_str(ost, &o->inter_matrices, oc, st, &inter_matrix);
637  if (inter_matrix) {
638  if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64)))
639  return AVERROR(ENOMEM);
640  ret = parse_matrix_coeffs(ost, video_enc->inter_matrix, inter_matrix);
641  if (ret < 0)
642  return ret;
643  }
644 
645  opt_match_per_stream_str(ost, &o->rc_overrides, oc, st, &p);
646  for (i = 0; p; i++) {
647  int start, end, q;
648  int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
649  if (e != 3) {
650  av_log(ost, AV_LOG_FATAL, "error parsing rc_override\n");
651  return AVERROR(EINVAL);
652  }
653  video_enc->rc_override =
654  av_realloc_array(video_enc->rc_override,
655  i + 1, sizeof(RcOverride));
656  if (!video_enc->rc_override) {
657  av_log(ost, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
658  return AVERROR(ENOMEM);
659  }
660  video_enc->rc_override[i].start_frame = start;
661  video_enc->rc_override[i].end_frame = end;
662  if (q > 0) {
663  video_enc->rc_override[i].qscale = q;
664  video_enc->rc_override[i].quality_factor = 1.0;
665  }
666  else {
667  video_enc->rc_override[i].qscale = 0;
668  video_enc->rc_override[i].quality_factor = -q/100.0;
669  }
670  p = strchr(p, '/');
671  if (p) p++;
672  }
673  video_enc->rc_override_count = i;
674 
675  /* two pass mode */
676  opt_match_per_stream_int(ost, &o->pass, oc, st, &do_pass);
677  if (do_pass) {
678  if (do_pass & 1)
679  video_enc->flags |= AV_CODEC_FLAG_PASS1;
680  if (do_pass & 2)
681  video_enc->flags |= AV_CODEC_FLAG_PASS2;
682  }
683 
684  opt_match_per_stream_str(ost, &o->passlogfiles, oc, st, &ost->logfile_prefix);
685  if (ost->logfile_prefix &&
686  !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
687  return AVERROR(ENOMEM);
688 
689  if (do_pass) {
690  int ost_idx = -1;
691  char logfilename[1024];
692  FILE *f;
693 
694  /* compute this stream's global index */
695  for (int idx = 0; idx <= ost->file->index; idx++)
696  ost_idx += output_files[idx]->nb_streams;
697 
698  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
699  ost->logfile_prefix ? ost->logfile_prefix :
700  DEFAULT_PASS_LOGFILENAME_PREFIX,
701  ost_idx);
702  if (!strcmp(video_enc->codec->name, "libx264") || !strcmp(video_enc->codec->name, "libvvenc")) {
703  if (av_opt_is_set_to_default_by_name(video_enc, "stats",
705  av_opt_set(video_enc, "stats", logfilename,
707  } else if (!strcmp(video_enc->codec->name, "libx265")) {
708  if (av_opt_is_set_to_default_by_name(video_enc, "x265-stats",
710  av_opt_set(video_enc, "x265-stats", logfilename,
712  } else {
713  if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
714  char *logbuffer = read_file_to_string(logfilename);
715 
716  if (!logbuffer) {
717  av_log(ost, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
718  logfilename);
719  return AVERROR(EIO);
720  }
721  video_enc->stats_in = logbuffer;
722  }
723  if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
724  f = fopen_utf8(logfilename, "wb");
725  if (!f) {
727  "Cannot write log file '%s' for pass-1 encoding: %s\n",
728  logfilename, strerror(errno));
729  return AVERROR(errno);
730  }
731  ost->logfile = f;
732  }
733  }
734  }
735 
736  opt_match_per_stream_int(ost, &o->force_fps, oc, st, &ms->force_fps);
737 
738  *vsync_method = VSYNC_AUTO;
739  opt_match_per_stream_str(ost, &o->fps_mode, oc, st, &fps_mode);
740  if (fps_mode) {
741  ret = parse_and_set_vsync(fps_mode, vsync_method, ost->file->index, ost->index);
742  if (ret < 0)
743  return ret;
744  }
745 
746  if ((ms->frame_rate.num || ms->max_frame_rate.num) &&
747  !(*vsync_method == VSYNC_AUTO ||
748  *vsync_method == VSYNC_CFR || *vsync_method == VSYNC_VSCFR)) {
749  av_log(ost, AV_LOG_FATAL, "One of -r/-fpsmax was specified "
750  "together a non-CFR -vsync/-fps_mode. This is contradictory.\n");
751  return AVERROR(EINVAL);
752  }
753 
754  if (*vsync_method == VSYNC_AUTO) {
755  if (ms->frame_rate.num || ms->max_frame_rate.num) {
756  *vsync_method = VSYNC_CFR;
757  } else if (!strcmp(oc->oformat->name, "avi")) {
758  *vsync_method = VSYNC_VFR;
759  } else {
760  *vsync_method = (oc->oformat->flags & AVFMT_VARIABLE_FPS) ?
761  ((oc->oformat->flags & AVFMT_NOTIMESTAMPS) ?
763  }
764 
765  if (ost->ist && *vsync_method == VSYNC_CFR) {
766  const InputFile *ifile = ost->ist->file;
767 
768  if (ifile->nb_streams == 1 && ifile->input_ts_offset == 0)
769  *vsync_method = VSYNC_VSCFR;
770  }
771 
772  if (*vsync_method == VSYNC_CFR && copy_ts) {
773  *vsync_method = VSYNC_VSCFR;
774  }
775  }
776  }
777 
778  return 0;
779 }
780 
781 static int new_stream_audio(Muxer *mux, const OptionsContext *o,
782  OutputStream *ost)
783 {
784  MuxStream *ms = ms_from_ost(ost);
785  AVFormatContext *oc = mux->fc;
786  AVStream *st = ost->st;
787 
788  if (ost->enc) {
789  AVCodecContext *audio_enc = ost->enc->enc_ctx;
790  int channels = 0;
791  const char *layout = NULL;
792  const char *sample_fmt = NULL;
793 
795  if (channels) {
797  audio_enc->ch_layout.nb_channels = channels;
798  }
799 
801  if (layout && av_channel_layout_from_string(&audio_enc->ch_layout, layout) < 0) {
802  av_log(ost, AV_LOG_FATAL, "Unknown channel layout: %s\n", layout);
803  return AVERROR(EINVAL);
804  }
805 
806  opt_match_per_stream_str(ost, &o->sample_fmts, oc, st, &sample_fmt);
807  if (sample_fmt &&
808  (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
809  av_log(ost, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
810  return AVERROR(EINVAL);
811  }
812 
813  opt_match_per_stream_int(ost, &o->audio_sample_rate, oc, st, &audio_enc->sample_rate);
814  opt_match_per_stream_str(ost, &o->apad, oc, st, &ms->apad);
815  }
816 
817  return 0;
818 }
819 
820 static int new_stream_subtitle(Muxer *mux, const OptionsContext *o,
821  OutputStream *ost)
822 {
823  AVStream *st;
824 
825  st = ost->st;
826 
827  if (ost->enc) {
828  AVCodecContext *subtitle_enc = ost->enc->enc_ctx;
829 
830  AVCodecDescriptor const *input_descriptor =
831  avcodec_descriptor_get(ost->ist->par->codec_id);
832  AVCodecDescriptor const *output_descriptor =
833  avcodec_descriptor_get(subtitle_enc->codec_id);
834  int input_props = 0, output_props = 0;
835 
836  const char *frame_size = NULL;
837 
839  if (frame_size) {
840  int ret = av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size);
841  if (ret < 0) {
842  av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
843  return ret;
844  }
845  }
846  if (input_descriptor)
847  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
848  if (output_descriptor)
849  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
850  if (input_props && output_props && input_props != output_props) {
852  "Subtitle encoding currently only possible from text to text "
853  "or bitmap to bitmap\n");
854  return AVERROR(EINVAL);
855  }
856  }
857 
858  return 0;
859 }
860 
861 static int
862 ost_bind_filter(const Muxer *mux, MuxStream *ms, OutputFilter *ofilter,
863  const OptionsContext *o,
864  AVRational enc_tb, enum VideoSyncMethod vsync_method,
865  int keep_pix_fmt, int autoscale, int threads_manual,
866  const ViewSpecifier *vs,
868 {
869  OutputStream *ost = &ms->ost;
870  AVCodecContext *enc_ctx = ost->enc->enc_ctx;
871  char name[16];
872  char *filters = NULL;
873  int ret;
874 
876  .enc = enc_ctx->codec,
877  .name = name,
878  .format = (ost->type == AVMEDIA_TYPE_VIDEO) ?
879  enc_ctx->pix_fmt : enc_ctx->sample_fmt,
880  .width = enc_ctx->width,
881  .height = enc_ctx->height,
882  .color_space = enc_ctx->colorspace,
883  .color_range = enc_ctx->color_range,
884  .alpha_mode = enc_ctx->alpha_mode,
885  .vsync_method = vsync_method,
886  .frame_rate = ms->frame_rate,
887  .max_frame_rate = ms->max_frame_rate,
888  .sample_rate = enc_ctx->sample_rate,
889  .ch_layout = enc_ctx->ch_layout,
890  .sws_opts = o->g->sws_dict,
891  .swr_opts = o->g->swr_opts,
892  .output_tb = enc_tb,
893  .trim_start_us = mux->of.start_time,
894  .trim_duration_us = mux->of.recording_time,
895  .ts_offset = mux->of.start_time == AV_NOPTS_VALUE ?
896  0 : mux->of.start_time,
897  .vs = vs,
898  .nb_threads = -1,
899 
900  .flags = OFILTER_FLAG_DISABLE_CONVERT * !!keep_pix_fmt |
901  OFILTER_FLAG_AUTOSCALE * !!autoscale |
903  };
904 
905  snprintf(name, sizeof(name), "#%d:%d", mux->of.index, ost->index);
906 
907  if (ost->type == AVMEDIA_TYPE_VIDEO) {
908  if (!keep_pix_fmt) {
911  (const void **) &opts.pix_fmts, NULL);
912  if (ret < 0)
913  return ret;
914  }
915  if (!ms->force_fps) {
918  (const void **) &opts.frame_rates, NULL);
919  if (ret < 0)
920  return ret;
921  }
924  (const void **) &opts.color_spaces, NULL);
925  if (ret < 0)
926  return ret;
929  (const void **) &opts.color_ranges, NULL);
930  if (ret < 0)
931  return ret;
934  (const void **) &opts.alpha_modes, NULL);
935  if (ret < 0)
936  return ret;
937  } else {
940  (const void **) &opts.sample_fmts, NULL);
941  if (ret < 0)
942  return ret;
945  (const void **) &opts.sample_rates, NULL);
946  if (ret < 0)
947  return ret;
950  (const void **) &opts.ch_layouts, NULL);
951  if (ret < 0)
952  return ret;
953  }
954 
955  if (threads_manual) {
956  ret = av_opt_get_int(enc_ctx, "threads", 0, &opts.nb_threads);
957  if (ret < 0)
958  return ret;
959  }
960 
961  ret = ost_get_filters(o, mux->fc, ost, &filters);
962  if (ret < 0)
963  return ret;
964 
965  if (ofilter) {
967  ost->filter = ofilter;
968  ret = ofilter_bind_enc(ofilter, ms->sch_idx_enc, &opts);
969  } else {
970  ret = fg_create_simple(&ost->fg_simple, ost->ist, &filters,
971  mux->sch, ms->sch_idx_enc, &opts);
972  if (ret >= 0)
973  ost->filter = ost->fg_simple->outputs[0];
974 
975  }
976  if (ret < 0)
977  return ret;
978 
979  *src = SCH_ENC(ms->sch_idx_enc);
980 
981  return 0;
982 }
983 
984 static int streamcopy_init(const OptionsContext *o, const Muxer *mux,
985  OutputStream *ost, AVDictionary **encoder_opts)
986 {
987  MuxStream *ms = ms_from_ost(ost);
988 
989  const InputStream *ist = ost->ist;
990  const InputFile *ifile = ist->file;
991 
992  AVCodecParameters *par = ms->par_in;
993  uint32_t codec_tag = par->codec_tag;
994 
995  AVCodecContext *codec_ctx = NULL;
996 
997  AVRational fr = ms->frame_rate;
998 
999  int ret = 0;
1000 
1001  const char *filters = NULL;
1002  opt_match_per_stream_str(ost, &o->filters, mux->fc, ost->st, &filters);
1003 
1004  if (filters) {
1006  "Filtergraph '%s' was specified, but codec copy was selected. "
1007  "Filtering and streamcopy cannot be used together.\n", filters);
1008  return AVERROR(EINVAL);
1009  }
1010 
1011  codec_ctx = avcodec_alloc_context3(NULL);
1012  if (!codec_ctx)
1013  return AVERROR(ENOMEM);
1014 
1015  ret = avcodec_parameters_to_context(codec_ctx, ist->par);
1016  if (ret >= 0)
1017  ret = av_opt_set_dict(codec_ctx, encoder_opts);
1018  if (ret < 0) {
1020  "Error setting up codec context options.\n");
1021  goto fail;
1022  }
1023 
1024  ret = avcodec_parameters_from_context(par, codec_ctx);
1025  if (ret < 0) {
1027  "Error getting reference codec parameters.\n");
1028  goto fail;
1029  }
1030 
1031  if (!codec_tag) {
1032  const struct AVCodecTag * const *ct = mux->fc->oformat->codec_tag;
1033  unsigned int codec_tag_tmp;
1034  if (!ct || av_codec_get_id (ct, par->codec_tag) == par->codec_id ||
1035  !av_codec_get_tag2(ct, par->codec_id, &codec_tag_tmp))
1036  codec_tag = par->codec_tag;
1037  }
1038 
1039  par->codec_tag = codec_tag;
1040 
1041  if (!fr.num)
1042  fr = ist->framerate;
1043 
1044  if (fr.num)
1045  ost->st->avg_frame_rate = fr;
1046  else
1047  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
1048 
1049  // copy timebase while removing common factors
1050  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0) {
1051  if (fr.num)
1052  ost->st->time_base = av_inv_q(fr);
1053  else
1054  ost->st->time_base = av_add_q(ist->st->time_base, (AVRational){0, 1});
1055  }
1056 
1057  if (!ms->copy_prior_start) {
1058  ms->ts_copy_start = (mux->of.start_time == AV_NOPTS_VALUE) ?
1059  0 : mux->of.start_time;
1060  if (copy_ts && ifile->start_time != AV_NOPTS_VALUE) {
1061  ms->ts_copy_start = FFMAX(ms->ts_copy_start,
1062  ifile->start_time + ifile->ts_offset);
1063  }
1064  }
1065 
1066  for (int i = 0; i < ist->st->codecpar->nb_coded_side_data; i++) {
1067  const AVPacketSideData *sd_src = &ist->st->codecpar->coded_side_data[i];
1068  AVPacketSideData *sd_dst;
1069 
1072  sd_src->type, sd_src->size, 0);
1073  if (!sd_dst) {
1074  ret = AVERROR(ENOMEM);
1075  goto fail;
1076  }
1077  memcpy(sd_dst->data, sd_src->data, sd_src->size);
1078  }
1079 
1080  switch (par->codec_type) {
1081  case AVMEDIA_TYPE_AUDIO:
1082  if ((par->block_align == 1 || par->block_align == 1152 || par->block_align == 576) &&
1083  par->codec_id == AV_CODEC_ID_MP3)
1084  par->block_align = 0;
1085  if (par->codec_id == AV_CODEC_ID_AC3)
1086  par->block_align = 0;
1087  break;
1088  case AVMEDIA_TYPE_VIDEO: {
1089  AVRational sar;
1090  if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
1091  sar =
1092  av_mul_q(ost->frame_aspect_ratio,
1093  (AVRational){ par->height, par->width });
1094  av_log(ost, AV_LOG_WARNING, "Overriding aspect ratio "
1095  "with stream copy may produce invalid files\n");
1096  }
1097  else if (ist->st->sample_aspect_ratio.num)
1098  sar = ist->st->sample_aspect_ratio;
1099  else
1100  sar = par->sample_aspect_ratio;
1101  ost->st->sample_aspect_ratio = par->sample_aspect_ratio = sar;
1102  ost->st->r_frame_rate = ist->st->r_frame_rate;
1103  break;
1104  }
1105  }
1106 
1107 fail:
1108  avcodec_free_context(&codec_ctx);
1109  return ret;
1110 }
1111 
1112 static int set_encoder_id(OutputStream *ost, const AVCodec *codec)
1113 {
1114  const char *cname = codec->name;
1115  uint8_t *encoder_string;
1116  int encoder_string_len;
1117 
1118  encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(cname) + 2;
1119  encoder_string = av_mallocz(encoder_string_len);
1120  if (!encoder_string)
1121  return AVERROR(ENOMEM);
1122 
1123  if (!ost->file->bitexact && !ost->bitexact)
1124  av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
1125  else
1126  av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
1127  av_strlcat(encoder_string, cname, encoder_string_len);
1128  av_dict_set(&ost->st->metadata, "encoder", encoder_string,
1130 
1131  return 0;
1132 }
1133 
1134 static int ost_add(Muxer *mux, const OptionsContext *o, enum AVMediaType type,
1135  InputStream *ist, OutputFilter *ofilter, const ViewSpecifier *vs,
1136  OutputStream **post)
1137 {
1138  AVFormatContext *oc = mux->fc;
1139  MuxStream *ms;
1140  OutputStream *ost;
1141  const AVCodec *enc;
1142  AVStream *st;
1143  SchedulerNode src = { .type = SCH_NODE_TYPE_NONE };
1144  AVDictionary *encoder_opts = NULL;
1145  int ret = 0, keep_pix_fmt = 0, autoscale = 1;
1146  int threads_manual = 0;
1147  AVRational enc_tb = { 0, 0 };
1148  enum VideoSyncMethod vsync_method = VSYNC_AUTO;
1149  const char *bsfs = NULL, *time_base = NULL, *codec_tag = NULL;
1150  char *next;
1151  double qscale = -1;
1152 
1153  st = avformat_new_stream(oc, NULL);
1154  if (!st)
1155  return AVERROR(ENOMEM);
1156 
1157  ms = mux_stream_alloc(mux, type);
1158  if (!ms)
1159  return AVERROR(ENOMEM);
1160 
1161  // only streams with sources (i.e. not attachments)
1162  // are handled by the scheduler
1163  if (ist || ofilter) {
1165  if (ret < 0)
1166  return ret;
1167 
1168  ret = sch_add_mux_stream(mux->sch, mux->sch_idx);
1169  if (ret < 0)
1170  return ret;
1171 
1172  av_assert0(ret == mux->nb_sch_stream_idx - 1);
1173  mux->sch_stream_idx[ret] = ms->ost.index;
1174  ms->sch_idx = ret;
1175  }
1176 
1177  ost = &ms->ost;
1178 
1179  if (o->streamid) {
1180  AVDictionaryEntry *e;
1181  char idx[16], *p;
1182  snprintf(idx, sizeof(idx), "%d", ost->index);
1183 
1184  e = av_dict_get(o->streamid, idx, NULL, 0);
1185  if (e) {
1186  st->id = strtol(e->value, &p, 0);
1187  if (!e->value[0] || *p) {
1188  av_log(ost, AV_LOG_FATAL, "Invalid stream id: %s\n", e->value);
1189  return AVERROR(EINVAL);
1190  }
1191  }
1192  }
1193 
1195  if (!ms->par_in)
1196  return AVERROR(ENOMEM);
1197 
1199 
1200  ost->st = st;
1201  ost->ist = ist;
1202  ost->kf.ref_pts = AV_NOPTS_VALUE;
1203  ms->par_in->codec_type = type;
1204  st->codecpar->codec_type = type;
1205 
1206  ret = choose_encoder(o, oc, ms, &enc);
1207  if (ret < 0) {
1208  av_log(ost, AV_LOG_FATAL, "Error selecting an encoder\n");
1209  return ret;
1210  }
1211 
1212  if (enc) {
1214  ost->type == AVMEDIA_TYPE_SUBTITLE ? NULL : enc_open);
1215  if (ret < 0)
1216  return ret;
1217  ms->sch_idx_enc = ret;
1218 
1219  ret = enc_alloc(&ost->enc, enc, mux->sch, ms->sch_idx_enc, ost);
1220  if (ret < 0)
1221  return ret;
1222 
1223  av_strlcat(ms->log_name, "/", sizeof(ms->log_name));
1224  av_strlcat(ms->log_name, enc->name, sizeof(ms->log_name));
1225  } else {
1226  if (ofilter) {
1228  "Streamcopy requested for output stream fed "
1229  "from a complex filtergraph. Filtering and streamcopy "
1230  "cannot be used together.\n");
1231  return AVERROR(EINVAL);
1232  }
1233 
1234  av_strlcat(ms->log_name, "/copy", sizeof(ms->log_name));
1235  }
1236 
1237  av_log(ost, AV_LOG_VERBOSE, "Created %s stream from ",
1239  if (ist)
1240  av_log(ost, AV_LOG_VERBOSE, "input stream %d:%d",
1241  ist->file->index, ist->index);
1242  else if (ofilter)
1243  av_log(ost, AV_LOG_VERBOSE, "complex filtergraph %d:[%s]\n",
1244  ofilter->graph->index, ofilter->name);
1245  else if (type == AVMEDIA_TYPE_ATTACHMENT)
1246  av_log(ost, AV_LOG_VERBOSE, "attached file");
1247  else av_assert0(0);
1248  av_log(ost, AV_LOG_VERBOSE, "\n");
1249 
1250  ms->pkt = av_packet_alloc();
1251  if (!ms->pkt)
1252  return AVERROR(ENOMEM);
1253 
1254  if (ost->enc) {
1255  AVIOContext *s = NULL;
1256  char *buf = NULL, *arg = NULL;
1257  const char *enc_stats_pre = NULL, *enc_stats_post = NULL, *mux_stats = NULL;
1258  const char *enc_time_base = NULL, *preset = NULL;
1259 
1260  ret = filter_codec_opts(o->g->codec_opts, enc->id,
1261  oc, st, enc, &encoder_opts,
1262  &mux->enc_opts_used);
1263  if (ret < 0)
1264  goto fail;
1265 
1266  opt_match_per_stream_str(ost, &o->presets, oc, st, &preset);
1267  opt_match_per_stream_int(ost, &o->autoscale, oc, st, &autoscale);
1268  if (preset && (!(ret = get_preset_file_2(preset, enc->name, &s)))) {
1269  AVBPrint bprint;
1271  do {
1272  av_bprint_clear(&bprint);
1273  buf = get_line(s, &bprint);
1274  if (!buf) {
1275  ret = AVERROR(ENOMEM);
1276  break;
1277  }
1278 
1279  if (!buf[0] || buf[0] == '#')
1280  continue;
1281  if (!(arg = strchr(buf, '='))) {
1282  av_log(ost, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1283  ret = AVERROR(EINVAL);
1284  break;
1285  }
1286  *arg++ = 0;
1287  av_dict_set(&encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1288  } while (!s->eof_reached);
1289  av_bprint_finalize(&bprint, NULL);
1290  avio_closep(&s);
1291  }
1292  if (ret) {
1294  "Preset %s specified, but could not be opened.\n", preset);
1295  goto fail;
1296  }
1297 
1298  opt_match_per_stream_str(ost, &o->enc_stats_pre, oc, st, &enc_stats_pre);
1299  if (enc_stats_pre &&
1301  const char *format = "{fidx} {sidx} {n} {t}";
1302 
1304 
1305  ret = enc_stats_init(ost, &ost->enc_stats_pre, 1, enc_stats_pre, format);
1306  if (ret < 0)
1307  goto fail;
1308  }
1309 
1310  opt_match_per_stream_str(ost, &o->enc_stats_post, oc, st, &enc_stats_post);
1311  if (enc_stats_post &&
1313  const char *format = "{fidx} {sidx} {n} {t}";
1314 
1316 
1317  ret = enc_stats_init(ost, &ost->enc_stats_post, 0, enc_stats_post, format);
1318  if (ret < 0)
1319  goto fail;
1320  }
1321 
1322  opt_match_per_stream_str(ost, &o->mux_stats, oc, st, &mux_stats);
1323  if (mux_stats &&
1325  const char *format = "{fidx} {sidx} {n} {t}";
1326 
1328 
1329  ret = enc_stats_init(ost, &ms->stats, 0, mux_stats, format);
1330  if (ret < 0)
1331  goto fail;
1332  }
1333 
1334  opt_match_per_stream_str(ost, &o->enc_time_bases, oc, st, &enc_time_base);
1335  if (enc_time_base && type == AVMEDIA_TYPE_SUBTITLE)
1337  "-enc_time_base not supported for subtitles, ignoring\n");
1338  else if (enc_time_base) {
1339  AVRational q;
1340 
1341  if (!strcmp(enc_time_base, "demux")) {
1342  q = (AVRational){ ENC_TIME_BASE_DEMUX, 0 };
1343  } else if (!strcmp(enc_time_base, "filter")) {
1344  q = (AVRational){ ENC_TIME_BASE_FILTER, 0 };
1345  } else {
1346  ret = av_parse_ratio(&q, enc_time_base, INT_MAX, 0, NULL);
1347  if (ret < 0 || q.den <= 0 || q.num < 0) {
1348  av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", enc_time_base);
1349  ret = ret < 0 ? ret : AVERROR(EINVAL);
1350  goto fail;
1351  }
1352  }
1353 
1354  enc_tb = q;
1355  }
1356 
1357  threads_manual = !!av_dict_get(encoder_opts, "threads", NULL, 0);
1358 
1359  ret = av_opt_set_dict2(ost->enc->enc_ctx, &encoder_opts, AV_OPT_SEARCH_CHILDREN);
1360  if (ret < 0) {
1361  av_log(ost, AV_LOG_ERROR, "Error applying encoder options: %s\n",
1362  av_err2str(ret));
1363  goto fail;
1364  }
1365 
1366  ret = check_avoptions(encoder_opts);
1367  if (ret < 0)
1368  goto fail;
1369 
1370  // default to automatic thread count
1371  if (!threads_manual)
1372  ost->enc->enc_ctx->thread_count = 0;
1373  } else {
1375  NULL, &encoder_opts,
1376  &mux->enc_opts_used);
1377  if (ret < 0)
1378  goto fail;
1379  }
1380 
1381 
1382  if (o->bitexact) {
1383  ost->bitexact = 1;
1384  } else if (ost->enc) {
1385  ost->bitexact = !!(ost->enc->enc_ctx->flags & AV_CODEC_FLAG_BITEXACT);
1386  }
1387 
1388  if (enc) {
1389  ret = set_encoder_id(ost, enc);
1390  if (ret < 0)
1391  return ret;
1392  }
1393 
1394  opt_match_per_stream_str(ost, &o->time_bases, oc, st, &time_base);
1395  if (time_base) {
1396  AVRational q;
1397  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1398  q.num <= 0 || q.den <= 0) {
1399  av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1400  ret = AVERROR(EINVAL);
1401  goto fail;
1402  }
1403  st->time_base = q;
1404  }
1405 
1406  ms->max_frames = INT64_MAX;
1408  for (int i = 0; i < o->max_frames.nb_opt; i++) {
1409  char *p = o->max_frames.opt[i].specifier;
1410  if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1411  av_log(ost, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1412  break;
1413  }
1414  }
1415 
1416  ms->copy_prior_start = -1;
1418  opt_match_per_stream_str(ost, &o->bitstream_filters, oc, st, &bsfs);
1419  if (bsfs && *bsfs) {
1420  ret = av_bsf_list_parse_str(bsfs, &ms->bsf_ctx);
1421  if (ret < 0) {
1422  av_log(ost, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1423  goto fail;
1424  }
1425  }
1426 
1427  opt_match_per_stream_str(ost, &o->codec_tags, oc, st, &codec_tag);
1428  if (codec_tag) {
1429  uint32_t tag = strtol(codec_tag, &next, 0);
1430  if (*next) {
1431  uint8_t buf[4] = { 0 };
1432  memcpy(buf, codec_tag, FFMIN(sizeof(buf), strlen(codec_tag)));
1433  tag = AV_RL32(buf);
1434  }
1435  ost->st->codecpar->codec_tag = tag;
1436  ms->par_in->codec_tag = tag;
1437  if (ost->enc)
1438  ost->enc->enc_ctx->codec_tag = tag;
1439  }
1440 
1441  opt_match_per_stream_dbl(ost, &o->qscale, oc, st, &qscale);
1442  if (ost->enc && qscale >= 0) {
1443  ost->enc->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
1444  ost->enc->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1445  }
1446 
1447  if (ms->sch_idx >= 0) {
1448  int max_muxing_queue_size = 128;
1449  int muxing_queue_data_threshold = 50 * 1024 * 1024;
1450 
1452  &max_muxing_queue_size);
1454  oc, st, &muxing_queue_data_threshold);
1455 
1456  sch_mux_stream_buffering(mux->sch, mux->sch_idx, ms->sch_idx,
1457  max_muxing_queue_size, muxing_queue_data_threshold);
1458  }
1459 
1461  &ost->bits_per_raw_sample);
1462 
1464  oc, st, &ost->fix_sub_duration_heartbeat);
1465 
1466  if (oc->oformat->flags & AVFMT_GLOBALHEADER && ost->enc)
1467  ost->enc->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1468  if (oc->oformat->flags & AVFMT_FIXED_FRAMESIZE && ost->enc)
1469  ost->enc->enc_ctx->flags2 |= AV_CODEC_FLAG2_FIXED_FRAME_SIZE;
1470 
1472  oc, st, &ms->copy_initial_nonkeyframes);
1473  switch (type) {
1474  case AVMEDIA_TYPE_VIDEO: ret = new_stream_video (mux, o, ost, &keep_pix_fmt, &vsync_method); break;
1475  case AVMEDIA_TYPE_AUDIO: ret = new_stream_audio (mux, o, ost); break;
1476  case AVMEDIA_TYPE_SUBTITLE: ret = new_stream_subtitle (mux, o, ost); break;
1477  }
1478  if (ret < 0)
1479  goto fail;
1480 
1481  if (ost->enc &&
1483  ret = ost_bind_filter(mux, ms, ofilter, o, enc_tb, vsync_method,
1484  keep_pix_fmt, autoscale, threads_manual, vs, &src);
1485  if (ret < 0)
1486  goto fail;
1487  } else if (ost->ist) {
1488  ret = ist_use(ost->ist, !!ost->enc, NULL, &src);
1489  if (ret < 0) {
1491  "Error binding an input stream\n");
1492  goto fail;
1493  }
1494  ms->sch_idx_src = src.idx;
1495 
1496  // src refers to a decoder for transcoding, demux stream otherwise
1497  if (ost->enc) {
1498  ret = sch_connect(mux->sch,
1499  src, SCH_ENC(ms->sch_idx_enc));
1500  if (ret < 0)
1501  goto fail;
1502  src = SCH_ENC(ms->sch_idx_enc);
1503  }
1504  }
1505 
1506  if (src.type != SCH_NODE_TYPE_NONE) {
1507  ret = sch_connect(mux->sch,
1508  src, SCH_MSTREAM(mux->sch_idx, ms->sch_idx));
1509  if (ret < 0)
1510  goto fail;
1511  } else {
1512  // only attachment streams don't have a source
1514  }
1515 
1516  if (ost->ist && !ost->enc) {
1517  ret = streamcopy_init(o, mux, ost, &encoder_opts);
1518  if (ret < 0)
1519  goto fail;
1520  }
1521 
1522  // copy estimated duration as a hint to the muxer
1523  if (ost->ist && ost->ist->st->duration > 0) {
1524  ms->stream_duration = ist->st->duration;
1525  ms->stream_duration_tb = ist->st->time_base;
1526  }
1527 
1528  if (post)
1529  *post = ost;
1530 
1531  ret = 0;
1532 
1533 fail:
1534  av_dict_free(&encoder_opts);
1535 
1536  return ret;
1537 }
1538 
1539 static int map_auto_video(Muxer *mux, const OptionsContext *o)
1540 {
1541  AVFormatContext *oc = mux->fc;
1542  InputStreamGroup *best_istg = NULL;
1543  InputStream *best_ist = NULL;
1544  int64_t best_score = 0;
1545  int qcr;
1546 
1547  /* video: highest resolution */
1549  return 0;
1550 
1551  qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
1552  for (int j = 0; j < nb_input_files; j++) {
1553  InputFile *ifile = input_files[j];
1554  InputStreamGroup *file_best_istg = NULL;
1555  InputStream *file_best_ist = NULL;
1556  int64_t file_best_score = 0;
1557  for (int i = 0; i < ifile->nb_stream_groups; i++) {
1558  InputStreamGroup *istg = ifile->stream_groups[i];
1559  int64_t score = 0;
1560 
1561  if (!istg->fg)
1562  continue;
1563 
1564  for (int j = 0; j < istg->stg->nb_streams; j++) {
1565  AVStream *st = istg->stg->streams[j];
1566 
1568  score = 100000000;
1569  break;
1570  }
1571  }
1572 
1573  switch (istg->stg->type) {
1575  const AVStreamGroupTileGrid *tg = istg->stg->params.tile_grid;
1576  score += tg->width * (int64_t)tg->height
1577  + 5000000*!!(istg->stg->disposition & AV_DISPOSITION_DEFAULT);
1578  break;
1579  }
1580  default:
1581  continue;
1582  }
1583 
1584  if (score > file_best_score) {
1585  file_best_score = score;
1586  file_best_istg = istg;
1587  }
1588  }
1589  for (int i = 0; i < ifile->nb_streams; i++) {
1590  InputStream *ist = ifile->streams[i];
1592  int64_t score;
1593 
1594  if (ist->user_set_discard == AVDISCARD_ALL ||
1596  (desc && (desc->props & AV_CODEC_PROP_ENHANCEMENT)))
1597  continue;
1598 
1599  score = ist->st->codecpar->width * (int64_t)ist->st->codecpar->height
1600  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
1601  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
1602  if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1603  score = 1;
1604 
1605  if (score > file_best_score) {
1606  if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1607  continue;
1608  file_best_score = score;
1609  file_best_ist = ist;
1610  file_best_istg = NULL;
1611  }
1612  }
1613  if (file_best_istg) {
1614  file_best_score -= 5000000*!!(file_best_istg->stg->disposition & AV_DISPOSITION_DEFAULT);
1615  if (file_best_score > best_score) {
1616  best_score = file_best_score;
1617  best_istg = file_best_istg;
1618  best_ist = NULL;
1619  }
1620  }
1621  if (file_best_ist) {
1622  if((qcr == MKTAG('A', 'P', 'I', 'C')) ||
1623  !(file_best_ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1624  file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
1625  if (file_best_score > best_score) {
1626  best_score = file_best_score;
1627  best_ist = file_best_ist;
1628  best_istg = NULL;
1629  }
1630  }
1631  }
1632  if (best_istg) {
1633  FilterGraph *fg = best_istg->fg;
1634  OutputFilter *ofilter = fg->outputs[0];
1635 
1636  av_assert0(fg->nb_outputs == 1);
1637  av_log(mux, AV_LOG_VERBOSE, "Creating output stream from stream group derived complex filtergraph %d.\n", fg->index);
1638 
1639  return ost_add(mux, o, AVMEDIA_TYPE_VIDEO, NULL, ofilter, NULL, NULL);
1640  }
1641  if (best_ist)
1642  return ost_add(mux, o, AVMEDIA_TYPE_VIDEO, best_ist, NULL, NULL, NULL);
1643 
1644  return 0;
1645 }
1646 
1647 static int map_auto_audio(Muxer *mux, const OptionsContext *o)
1648 {
1649  AVFormatContext *oc = mux->fc;
1650  InputStream *best_ist = NULL;
1651  int best_score = 0;
1652 
1653  /* audio: most channels */
1655  return 0;
1656 
1657  for (int j = 0; j < nb_input_files; j++) {
1658  InputFile *ifile = input_files[j];
1659  InputStream *file_best_ist = NULL;
1660  int file_best_score = 0;
1661  for (int i = 0; i < ifile->nb_streams; i++) {
1662  InputStream *ist = ifile->streams[i];
1663  int score;
1664 
1665  if (ist->user_set_discard == AVDISCARD_ALL ||
1667  continue;
1668 
1669  score = ist->st->codecpar->ch_layout.nb_channels
1670  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
1671  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
1672  if (score > file_best_score) {
1673  file_best_score = score;
1674  file_best_ist = ist;
1675  }
1676  }
1677  if (file_best_ist) {
1678  file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
1679  if (file_best_score > best_score) {
1680  best_score = file_best_score;
1681  best_ist = file_best_ist;
1682  }
1683  }
1684  }
1685  if (best_ist)
1686  return ost_add(mux, o, AVMEDIA_TYPE_AUDIO, best_ist, NULL, NULL, NULL);
1687 
1688  return 0;
1689 }
1690 
1691 static int map_auto_subtitle(Muxer *mux, const OptionsContext *o)
1692 {
1693  AVFormatContext *oc = mux->fc;
1694  const char *subtitle_codec_name = NULL;
1695 
1696  /* subtitles: pick first */
1699  return 0;
1700 
1701  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist))
1702  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1703  AVCodecDescriptor const *input_descriptor =
1704  avcodec_descriptor_get(ist->st->codecpar->codec_id);
1705  AVCodecDescriptor const *output_descriptor = NULL;
1706  AVCodec const *output_codec =
1708  int input_props = 0, output_props = 0;
1709  if (ist->user_set_discard == AVDISCARD_ALL)
1710  continue;
1711  if (output_codec)
1712  output_descriptor = avcodec_descriptor_get(output_codec->id);
1713  if (input_descriptor)
1714  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1715  if (output_descriptor)
1716  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1717  if (subtitle_codec_name ||
1718  input_props & output_props ||
1719  // Map dvb teletext which has neither property to any output subtitle encoder
1720  input_descriptor && output_descriptor &&
1721  (!input_descriptor->props ||
1722  !output_descriptor->props)) {
1723  return ost_add(mux, o, AVMEDIA_TYPE_SUBTITLE, ist, NULL, NULL, NULL);
1724  }
1725  }
1726 
1727  return 0;
1728 }
1729 
1730 static int map_auto_data(Muxer *mux, const OptionsContext *o)
1731 {
1732  AVFormatContext *oc = mux->fc;
1733  /* Data only if codec id match */
1735 
1736  if (codec_id == AV_CODEC_ID_NONE)
1737  return 0;
1738 
1739  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
1740  if (ist->user_set_discard == AVDISCARD_ALL)
1741  continue;
1742  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
1743  ist->st->codecpar->codec_id == codec_id) {
1744  int ret = ost_add(mux, o, AVMEDIA_TYPE_DATA, ist, NULL, NULL, NULL);
1745  if (ret < 0)
1746  return ret;
1747  }
1748  }
1749 
1750  return 0;
1751 }
1752 
1753 static int map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
1754 {
1755  InputStream *ist;
1756  int ret;
1757 
1758  if (map->disabled)
1759  return 0;
1760 
1761  if (map->linklabel) {
1762  FilterGraph *fg;
1763  OutputFilter *ofilter = NULL;
1764  int j, k;
1765 
1766  for (j = 0; j < nb_filtergraphs; j++) {
1767  fg = filtergraphs[j];
1768  for (k = 0; k < fg->nb_outputs; k++) {
1769  const char *linklabel = fg->outputs[k]->linklabel;
1770  if (linklabel && !strcmp(linklabel, map->linklabel)) {
1771  ofilter = fg->outputs[k];
1772  goto loop_end;
1773  }
1774  }
1775  }
1776 loop_end:
1777  if (!ofilter) {
1778  av_log(mux, AV_LOG_FATAL, "Output with label '%s' does not exist "
1779  "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
1780  return AVERROR(EINVAL);
1781  }
1782 
1783  av_log(mux, AV_LOG_VERBOSE, "Creating output stream from an explicitly "
1784  "mapped complex filtergraph %d, output [%s]\n", fg->index, map->linklabel);
1785 
1786  ret = ost_add(mux, o, ofilter->type, NULL, ofilter, NULL, NULL);
1787  if (ret < 0)
1788  return ret;
1789  } else {
1790  const ViewSpecifier *vs = map->vs.type == VIEW_SPECIFIER_TYPE_NONE ?
1791  NULL : &map->vs;
1792 
1793  ist = input_files[map->file_index]->streams[map->stream_index];
1794  if (ist->user_set_discard == AVDISCARD_ALL) {
1795  av_log(mux, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
1796  map->file_index, map->stream_index);
1797  return AVERROR(EINVAL);
1798  }
1800  return 0;
1802  return 0;
1804  return 0;
1805  if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1806  return 0;
1807 
1808  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
1811  "Cannot map stream #%d:%d - unsupported type.\n",
1812  map->file_index, map->stream_index);
1813  if (!ignore_unknown_streams) {
1814  av_log(mux, AV_LOG_FATAL,
1815  "If you want unsupported types ignored instead "
1816  "of failing, please use the -ignore_unknown option\n"
1817  "If you want them copied, please use -copy_unknown\n");
1818  return AVERROR(EINVAL);
1819  }
1820  return 0;
1821  }
1822 
1823  if (vs && ist->st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
1824  av_log(mux, AV_LOG_ERROR,
1825  "View specifier given for mapping a %s input stream\n",
1827  return AVERROR(EINVAL);
1828  }
1829 
1830  ret = ost_add(mux, o, ist->st->codecpar->codec_type, ist, NULL, vs, NULL);
1831  if (ret < 0)
1832  return ret;
1833  }
1834 
1835  return 0;
1836 }
1837 
1838 static int of_add_attachments(Muxer *mux, const OptionsContext *o)
1839 {
1840  MuxStream *ms;
1841  OutputStream *ost;
1842  int err;
1843 
1844  for (int i = 0; i < o->nb_attachments; i++) {
1845  AVIOContext *pb;
1846  uint8_t *attachment;
1847  char *attachment_filename;
1848  const char *p;
1849  int64_t len;
1850 
1851  if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
1852  av_log(mux, AV_LOG_FATAL, "Could not open attachment file %s.\n",
1853  o->attachments[i]);
1854  return err;
1855  }
1856  if ((len = avio_size(pb)) <= 0) {
1857  av_log(mux, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
1858  o->attachments[i]);
1859  err = len ? len : AVERROR_INVALIDDATA;
1860  goto read_fail;
1861  }
1862  if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
1863  av_log(mux, AV_LOG_FATAL, "Attachment %s too large.\n",
1864  o->attachments[i]);
1865  err = AVERROR(ERANGE);
1866  goto read_fail;
1867  }
1868 
1869  attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE);
1870  if (!attachment) {
1871  err = AVERROR(ENOMEM);
1872  goto read_fail;
1873  }
1874 
1875  err = avio_read(pb, attachment, len);
1876  if (err < 0)
1877  av_log(mux, AV_LOG_FATAL, "Error reading attachment file %s: %s\n",
1878  o->attachments[i], av_err2str(err));
1879  else if (err != len) {
1880  av_log(mux, AV_LOG_FATAL, "Could not read all %"PRId64" bytes for "
1881  "attachment file %s\n", len, o->attachments[i]);
1882  err = AVERROR(EIO);
1883  }
1884 
1885 read_fail:
1886  avio_closep(&pb);
1887  if (err < 0)
1888  return err;
1889 
1890  memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1891 
1892  av_log(mux, AV_LOG_VERBOSE, "Creating attachment stream from file %s\n",
1893  o->attachments[i]);
1894 
1895  attachment_filename = av_strdup(o->attachments[i]);
1896  if (!attachment_filename) {
1897  av_free(attachment);
1898  return AVERROR(ENOMEM);
1899  }
1900 
1901  err = ost_add(mux, o, AVMEDIA_TYPE_ATTACHMENT, NULL, NULL, NULL, &ost);
1902  if (err < 0) {
1903  av_free(attachment_filename);
1904  av_freep(&attachment);
1905  return err;
1906  }
1907 
1908  ms = ms_from_ost(ost);
1909 
1910  ost->attachment_filename = attachment_filename;
1911  ms->par_in->extradata = attachment;
1912  ms->par_in->extradata_size = len;
1913 
1914  p = strrchr(o->attachments[i], '/');
1915  av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
1916  }
1917 
1918  return 0;
1919 }
1920 
1921 static int create_streams(Muxer *mux, const OptionsContext *o)
1922 {
1923  static int (* const map_func[])(Muxer *mux, const OptionsContext *o) = {
1928  };
1929 
1930  AVFormatContext *oc = mux->fc;
1931 
1932  int auto_disable =
1933  o->video_disable * (1 << AVMEDIA_TYPE_VIDEO) |
1934  o->audio_disable * (1 << AVMEDIA_TYPE_AUDIO) |
1936  o->data_disable * (1 << AVMEDIA_TYPE_DATA);
1937 
1938  int ret;
1939 
1940  /* create streams for all unlabeled output pads */
1941  for (int i = 0; i < nb_filtergraphs; i++) {
1942  FilterGraph *fg = filtergraphs[i];
1943  for (int j = 0; j < fg->nb_outputs; j++) {
1944  OutputFilter *ofilter = fg->outputs[j];
1945 
1946  if (ofilter->linklabel || ofilter->bound)
1947  continue;
1948 
1949  auto_disable |= 1 << ofilter->type;
1950 
1951  av_log(mux, AV_LOG_VERBOSE, "Creating output stream from unlabeled "
1952  "output of complex filtergraph %d.", fg->index);
1953  if (!o->nb_stream_maps)
1954  av_log(mux, AV_LOG_VERBOSE, " This overrides automatic %s mapping.",
1955  av_get_media_type_string(ofilter->type));
1956  av_log(mux, AV_LOG_VERBOSE, "\n");
1957 
1958  ret = ost_add(mux, o, ofilter->type, NULL, ofilter, NULL, NULL);
1959  if (ret < 0)
1960  return ret;
1961  }
1962  }
1963 
1964  if (!o->nb_stream_maps) {
1965  av_log(mux, AV_LOG_VERBOSE, "No explicit maps, mapping streams automatically...\n");
1966 
1967  /* pick the "best" stream of each type */
1968  for (int i = 0; i < FF_ARRAY_ELEMS(map_func); i++) {
1969  if (!map_func[i] || auto_disable & (1 << i))
1970  continue;
1971  ret = map_func[i](mux, o);
1972  if (ret < 0)
1973  return ret;
1974  }
1975  } else {
1976  av_log(mux, AV_LOG_VERBOSE, "Adding streams from explicit maps...\n");
1977 
1978  for (int i = 0; i < o->nb_stream_maps; i++) {
1979  ret = map_manual(mux, o, &o->stream_maps[i]);
1980  if (ret < 0)
1981  return ret;
1982  }
1983  }
1984 
1985  ret = of_add_attachments(mux, o);
1986  if (ret < 0)
1987  return ret;
1988 
1989  // setup fix_sub_duration_heartbeat mappings
1990  for (unsigned i = 0; i < oc->nb_streams; i++) {
1991  MuxStream *src = ms_from_ost(mux->of.streams[i]);
1992 
1993  if (!src->ost.fix_sub_duration_heartbeat)
1994  continue;
1995 
1996  for (unsigned j = 0; j < oc->nb_streams; j++) {
1997  MuxStream *dst = ms_from_ost(mux->of.streams[j]);
1998 
1999  if (src == dst || dst->ost.type != AVMEDIA_TYPE_SUBTITLE ||
2000  !dst->ost.enc || !dst->ost.ist || !dst->ost.ist->fix_sub_duration)
2001  continue;
2002 
2003  ret = sch_mux_sub_heartbeat_add(mux->sch, mux->sch_idx, src->sch_idx,
2004  dst->sch_idx_src);
2005 
2006  }
2007  }
2008 
2009  // handle -apad
2010  if (o->shortest) {
2011  int have_video = 0;
2012 
2013  for (unsigned i = 0; i < mux->of.nb_streams; i++)
2014  if (mux->of.streams[i]->type == AVMEDIA_TYPE_VIDEO) {
2015  have_video = 1;
2016  break;
2017  }
2018 
2019  for (unsigned i = 0; have_video && i < mux->of.nb_streams; i++) {
2020  MuxStream *ms = ms_from_ost(mux->of.streams[i]);
2021  OutputFilter *ofilter = ms->ost.filter;
2022 
2023  if (ms->ost.type != AVMEDIA_TYPE_AUDIO || !ms->apad || !ofilter)
2024  continue;
2025 
2026  ofilter->apad = av_strdup(ms->apad);
2027  if (!ofilter->apad)
2028  return AVERROR(ENOMEM);
2029  }
2030  }
2031  for (unsigned i = 0; i < mux->of.nb_streams; i++) {
2032  MuxStream *ms = ms_from_ost(mux->of.streams[i]);
2033  ms->apad = NULL;
2034  }
2035 
2036  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2037  av_dump_format(oc, nb_output_files - 1, oc->url, 1);
2038  av_log(mux, AV_LOG_ERROR, "Output file does not contain any stream\n");
2039  return AVERROR(EINVAL);
2040  }
2041 
2042  return 0;
2043 }
2044 
2046  int64_t buf_size_us, int shortest)
2047 {
2048  OutputFile *of = &mux->of;
2049  int nb_av_enc = 0, nb_audio_fs = 0, nb_interleaved = 0;
2050  int limit_frames = 0, limit_frames_av_enc = 0;
2051 
2052 #define IS_AV_ENC(ost, type) \
2053  (ost->enc && (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO))
2054 #define IS_INTERLEAVED(type) (type != AVMEDIA_TYPE_ATTACHMENT)
2055 
2056  for (int i = 0; i < oc->nb_streams; i++) {
2057  OutputStream *ost = of->streams[i];
2058  MuxStream *ms = ms_from_ost(ost);
2059  enum AVMediaType type = ost->type;
2060 
2061  ms->sq_idx_mux = -1;
2062 
2063  nb_interleaved += IS_INTERLEAVED(type);
2064  nb_av_enc += IS_AV_ENC(ost, type);
2065  nb_audio_fs += (ost->enc && type == AVMEDIA_TYPE_AUDIO &&
2066  (!(ost->enc->enc_ctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE) ||
2067  (ost->enc->enc_ctx->flags2 & AV_CODEC_FLAG2_FIXED_FRAME_SIZE)));
2068 
2069  limit_frames |= ms->max_frames < INT64_MAX;
2070  limit_frames_av_enc |= (ms->max_frames < INT64_MAX) && IS_AV_ENC(ost, type);
2071  }
2072 
2073  if (!((nb_interleaved > 1 && shortest) ||
2074  (nb_interleaved > 0 && limit_frames) ||
2075  nb_audio_fs))
2076  return 0;
2077 
2078  /* we use a sync queue before encoding when:
2079  * - 'shortest' is in effect and we have two or more encoded audio/video
2080  * streams
2081  * - at least one encoded audio/video stream is frame-limited, since
2082  * that has similar semantics to 'shortest'
2083  * - at least one audio encoder requires constant frame sizes
2084  *
2085  * Note that encoding sync queues are handled in the scheduler, because
2086  * different encoders run in different threads and need external
2087  * synchronization, while muxer sync queues can be handled inside the muxer
2088  */
2089  if ((shortest && nb_av_enc > 1) || limit_frames_av_enc || nb_audio_fs) {
2090  int sq_idx, ret;
2091 
2092  sq_idx = sch_add_sq_enc(mux->sch, buf_size_us, mux);
2093  if (sq_idx < 0)
2094  return sq_idx;
2095 
2096  for (int i = 0; i < oc->nb_streams; i++) {
2097  OutputStream *ost = of->streams[i];
2098  MuxStream *ms = ms_from_ost(ost);
2099  enum AVMediaType type = ost->type;
2100 
2101  if (!IS_AV_ENC(ost, type))
2102  continue;
2103 
2104  ret = sch_sq_add_enc(mux->sch, sq_idx, ms->sch_idx_enc,
2105  shortest || ms->max_frames < INT64_MAX,
2106  ms->max_frames);
2107  if (ret < 0)
2108  return ret;
2109  }
2110  }
2111 
2112  /* if there are any additional interleaved streams, then ALL the streams
2113  * are also synchronized before sending them to the muxer */
2114  if (nb_interleaved > nb_av_enc) {
2115  mux->sq_mux = sq_alloc(SYNC_QUEUE_PACKETS, buf_size_us, mux);
2116  if (!mux->sq_mux)
2117  return AVERROR(ENOMEM);
2118 
2119  mux->sq_pkt = av_packet_alloc();
2120  if (!mux->sq_pkt)
2121  return AVERROR(ENOMEM);
2122 
2123  for (int i = 0; i < oc->nb_streams; i++) {
2124  OutputStream *ost = of->streams[i];
2125  MuxStream *ms = ms_from_ost(ost);
2126  enum AVMediaType type = ost->type;
2127 
2128  if (!IS_INTERLEAVED(type))
2129  continue;
2130 
2131  ms->sq_idx_mux = sq_add_stream(mux->sq_mux,
2132  shortest || ms->max_frames < INT64_MAX);
2133  if (ms->sq_idx_mux < 0)
2134  return ms->sq_idx_mux;
2135 
2136  if (ms->max_frames != INT64_MAX)
2137  sq_limit_frames(mux->sq_mux, ms->sq_idx_mux, ms->max_frames);
2138  }
2139  }
2140 
2141 #undef IS_AV_ENC
2142 #undef IS_INTERLEAVED
2143 
2144  return 0;
2145 }
2146 
2147 static int of_parse_iamf_audio_element_layers(Muxer *mux, AVStreamGroup *stg, char *ptr)
2148 {
2149  AVIAMFAudioElement *audio_element = stg->params.iamf_audio_element;
2150  AVDictionary *dict = NULL;
2151  const char *token;
2152  int ret = 0;
2153 
2154  audio_element->demixing_info =
2156  audio_element->recon_gain_info =
2158 
2159  if (!audio_element->demixing_info ||
2160  !audio_element->recon_gain_info)
2161  return AVERROR(ENOMEM);
2162 
2163  /* process manually set layers and parameters */
2164  token = av_strtok(NULL, ",", &ptr);
2165  while (token) {
2166  const AVDictionaryEntry *e;
2167  int demixing = 0, recon_gain = 0;
2168  int layer = 0;
2169 
2170  if (ptr)
2171  ptr += strspn(ptr, " \n\t\r");
2172  if (av_strstart(token, "layer=", &token))
2173  layer = 1;
2174  else if (av_strstart(token, "demixing=", &token))
2175  demixing = 1;
2176  else if (av_strstart(token, "recon_gain=", &token))
2177  recon_gain = 1;
2178 
2179  av_dict_free(&dict);
2180  ret = av_dict_parse_string(&dict, token, "=", ":", 0);
2181  if (ret < 0) {
2182  av_log(mux, AV_LOG_ERROR, "Error parsing audio element specification %s\n", token);
2183  goto fail;
2184  }
2185 
2186  if (layer) {
2187  AVIAMFLayer *audio_layer = av_iamf_audio_element_add_layer(audio_element);
2188  if (!audio_layer) {
2189  av_log(mux, AV_LOG_ERROR, "Error adding layer to stream group %d\n", stg->index);
2190  ret = AVERROR(ENOMEM);
2191  goto fail;
2192  }
2193  av_opt_set_dict(audio_layer, &dict);
2194  } else if (demixing || recon_gain) {
2195  AVIAMFParamDefinition *param = demixing ? audio_element->demixing_info
2196  : audio_element->recon_gain_info;
2197  void *subblock = av_iamf_param_definition_get_subblock(param, 0);
2198 
2199  av_opt_set_dict(param, &dict);
2200  av_opt_set_dict(subblock, &dict);
2201  }
2202 
2203  // make sure that no entries are left in the dict
2204  e = NULL;
2205  if (e = av_dict_iterate(dict, e)) {
2206  av_log(mux, AV_LOG_FATAL, "Unknown layer key %s.\n", e->key);
2207  ret = AVERROR(EINVAL);
2208  goto fail;
2209  }
2210  token = av_strtok(NULL, ",", &ptr);
2211  }
2212 
2213 fail:
2214  av_dict_free(&dict);
2215  if (!ret && !audio_element->nb_layers) {
2216  av_log(mux, AV_LOG_ERROR, "No layer in audio element specification\n");
2217  ret = AVERROR(EINVAL);
2218  }
2219 
2220  return ret;
2221 }
2222 
2223 static int of_parse_iamf_submixes(Muxer *mux, AVStreamGroup *stg, char *ptr)
2224 {
2225  AVFormatContext *oc = mux->fc;
2227  AVDictionary *dict = NULL;
2228  const char *token;
2229  char *submix_str = NULL;
2230  int ret = 0;
2231 
2232  /* process manually set submixes */
2233  token = av_strtok(NULL, ",", &ptr);
2234  while (token) {
2235  AVIAMFSubmix *submix = NULL;
2236  const char *subtoken;
2237  char *subptr = NULL;
2238 
2239  if (ptr)
2240  ptr += strspn(ptr, " \n\t\r");
2241  if (!av_strstart(token, "submix=", &token)) {
2242  av_log(mux, AV_LOG_ERROR, "No submix in mix presentation specification \"%s\"\n", token);
2243  goto fail;
2244  }
2245 
2246  submix_str = av_strdup(token);
2247  if (!submix_str)
2248  goto fail;
2249 
2251  if (!submix) {
2252  av_log(mux, AV_LOG_ERROR, "Error adding submix to stream group %d\n", stg->index);
2253  ret = AVERROR(ENOMEM);
2254  goto fail;
2255  }
2256  submix->output_mix_config =
2258  if (!submix->output_mix_config) {
2259  ret = AVERROR(ENOMEM);
2260  goto fail;
2261  }
2262 
2263  subptr = NULL;
2264  subtoken = av_strtok(submix_str, "|", &subptr);
2265  while (subtoken) {
2266  const AVDictionaryEntry *e;
2267  int element = 0, layout = 0;
2268 
2269  if (subptr)
2270  subptr += strspn(subptr, " \n\t\r");
2271  if (av_strstart(subtoken, "element=", &subtoken))
2272  element = 1;
2273  else if (av_strstart(subtoken, "layout=", &subtoken))
2274  layout = 1;
2275 
2276  av_dict_free(&dict);
2277  ret = av_dict_parse_string(&dict, subtoken, "=", ":", 0);
2278  if (ret < 0) {
2279  av_log(mux, AV_LOG_ERROR, "Error parsing submix specification \"%s\"\n", subtoken);
2280  goto fail;
2281  }
2282 
2283  if (element) {
2284  AVIAMFSubmixElement *submix_element;
2285  char *endptr = NULL;
2286  int64_t idx = -1;
2287 
2288  if (e = av_dict_get(dict, "stg", NULL, 0))
2289  idx = strtoll(e->value, &endptr, 0);
2290  if (!endptr || *endptr || idx < 0 || idx >= oc->nb_stream_groups - 1 ||
2292  av_log(mux, AV_LOG_ERROR, "Invalid or missing stream group index in "
2293  "submix element specification \"%s\"\n", subtoken);
2294  ret = AVERROR(EINVAL);
2295  goto fail;
2296  }
2297  submix_element = av_iamf_submix_add_element(submix);
2298  if (!submix_element) {
2299  av_log(mux, AV_LOG_ERROR, "Error adding element to submix\n");
2300  ret = AVERROR(ENOMEM);
2301  goto fail;
2302  }
2303 
2304  submix_element->audio_element_id = oc->stream_groups[idx]->id;
2305 
2306  submix_element->element_mix_config =
2308  if (!submix_element->element_mix_config)
2309  ret = AVERROR(ENOMEM);
2310  av_dict_set(&dict, "stg", NULL, 0);
2311  av_opt_set_dict2(submix_element, &dict, AV_OPT_SEARCH_CHILDREN);
2312  } else if (layout) {
2313  AVIAMFSubmixLayout *submix_layout = av_iamf_submix_add_layout(submix);
2314  if (!submix_layout) {
2315  av_log(mux, AV_LOG_ERROR, "Error adding layout to submix\n");
2316  ret = AVERROR(ENOMEM);
2317  goto fail;
2318  }
2319  av_opt_set_dict(submix_layout, &dict);
2320  } else
2321  av_opt_set_dict2(submix, &dict, AV_OPT_SEARCH_CHILDREN);
2322 
2323  if (ret < 0) {
2324  goto fail;
2325  }
2326 
2327  // make sure that no entries are left in the dict
2328  e = NULL;
2329  while (e = av_dict_iterate(dict, e)) {
2330  av_log(mux, AV_LOG_FATAL, "Unknown submix key %s.\n", e->key);
2331  ret = AVERROR(EINVAL);
2332  goto fail;
2333  }
2334  subtoken = av_strtok(NULL, "|", &subptr);
2335  }
2336  av_freep(&submix_str);
2337 
2338  if (!submix->nb_elements) {
2339  av_log(mux, AV_LOG_ERROR, "No audio elements in submix specification \"%s\"\n", token);
2340  ret = AVERROR(EINVAL);
2341  }
2342  token = av_strtok(NULL, ",", &ptr);
2343  }
2344 
2345 fail:
2346  av_dict_free(&dict);
2347  av_free(submix_str);
2348 
2349  return ret;
2350 }
2351 
2352 static int of_serialize_options(Muxer *mux, void *obj, AVBPrint *bp)
2353 {
2354  char *ptr;
2355  int ret;
2356 
2358  &ptr, '=', ':');
2359  if (ret < 0) {
2360  av_log(mux, AV_LOG_ERROR, "Failed to serialize group\n");
2361  return ret;
2362  }
2363 
2364  av_bprintf(bp, "%s", ptr);
2365  ret = strlen(ptr);
2366  av_free(ptr);
2367 
2368  return ret;
2369 }
2370 
2371 #define SERIALIZE(parent, child) do { \
2372  ret = of_serialize_options(mux, parent->child, bp); \
2373  if (ret < 0) \
2374  return ret; \
2375 } while (0)
2376 
2377 #define SERIALIZE_LOOP_SUBBLOCK(obj) do { \
2378  for (int k = 0; k < obj->nb_subblocks; k++) { \
2379  ret = of_serialize_options(mux, \
2380  av_iamf_param_definition_get_subblock(obj, k), bp); \
2381  if (ret < 0) \
2382  return ret; \
2383  } \
2384 } while (0)
2385 
2386 #define SERIALIZE_LOOP(parent, child, suffix, separator) do { \
2387  for (int j = 0; j < parent->nb_## child ## suffix; j++) { \
2388  av_bprintf(bp, separator#child "="); \
2389  SERIALIZE(parent, child ## suffix[j]); \
2390  } \
2391 } while (0)
2392 
2394 {
2395  AVFormatContext *oc = mux->fc;
2396 
2397  for (unsigned i = 0; i < oc->nb_stream_groups; i++)
2398  if (oc->stream_groups[i]->id == id)
2399  return oc->stream_groups[i]->index;
2400 
2401  return AVERROR(EINVAL);
2402 }
2403 
2404 static int of_map_group(Muxer *mux, AVDictionary **dict, AVBPrint *bp, const char *map)
2405 {
2406  AVStreamGroup *stg;
2407  int ret, file_idx, stream_idx;
2408  char *ptr;
2409 
2410  file_idx = strtol(map, &ptr, 0);
2411  if (file_idx >= nb_input_files || file_idx < 0 || map == ptr) {
2412  av_log(mux, AV_LOG_ERROR, "Invalid input file index: %d.\n", file_idx);
2413  return AVERROR(EINVAL);
2414  }
2415 
2416  stream_idx = strtol(*ptr == '=' ? ptr + 1 : ptr, &ptr, 0);
2417  if (*ptr || stream_idx >= input_files[file_idx]->ctx->nb_stream_groups || stream_idx < 0) {
2418  av_log(mux, AV_LOG_ERROR, "Invalid input stream group index: %d.\n", stream_idx);
2419  return AVERROR(EINVAL);
2420  }
2421 
2422  stg = input_files[file_idx]->ctx->stream_groups[stream_idx];
2423  ret = of_serialize_options(mux, stg, bp);
2424  if (ret < 0)
2425  return ret;
2426 
2427  ret = av_dict_parse_string(dict, bp->str, "=", ":", 0);
2428  if (ret < 0)
2429  av_log(mux, AV_LOG_ERROR, "Error parsing mapped group specification %s\n", ptr);
2430  av_dict_set_int(dict, "type", stg->type, 0);
2431 
2432  av_bprint_clear(bp);
2433  switch(stg->type) {
2435  AVIAMFAudioElement *audio_element = stg->params.iamf_audio_element;
2436 
2437  if (audio_element->demixing_info) {
2438  AVIAMFParamDefinition *demixing_info = audio_element->demixing_info;
2439  av_bprintf(bp, ",demixing=");
2440  SERIALIZE(audio_element, demixing_info);
2441  if (ret && demixing_info->nb_subblocks)
2442  av_bprintf(bp, ":");
2443  SERIALIZE_LOOP_SUBBLOCK(demixing_info);
2444  }
2445  if (audio_element->recon_gain_info) {
2446  AVIAMFParamDefinition *recon_gain_info = audio_element->recon_gain_info;
2447  av_bprintf(bp, ",recon_gain=");
2448  SERIALIZE(audio_element, recon_gain_info);
2449  if (ret && recon_gain_info->nb_subblocks)
2450  av_bprintf(bp, ":");
2451  SERIALIZE_LOOP_SUBBLOCK(recon_gain_info);
2452  }
2453  SERIALIZE_LOOP(audio_element, layer, s, ",");
2454  break;
2455  }
2458 
2459  for (int i = 0; i < mix->nb_submixes; i++) {
2460  AVIAMFSubmix *submix = mix->submixes[i];
2461  AVIAMFParamDefinition *output_mix_config = submix->output_mix_config;
2462 
2463  av_bprintf(bp, ",submix=");
2464  SERIALIZE(mix, submixes[i]);
2465  if (ret && output_mix_config->nb_subblocks)
2466  av_bprintf(bp, ":");
2467  SERIALIZE_LOOP_SUBBLOCK(output_mix_config);
2468  for (int j = 0; j < submix->nb_elements; j++) {
2469  AVIAMFSubmixElement *element = submix->elements[j];
2470  AVIAMFParamDefinition *element_mix_config = element->element_mix_config;
2472 
2473  if (id < 0) {
2474  av_log(mux, AV_LOG_ERROR, "Invalid or missing stream group index in"
2475  "submix element");
2476  return id;
2477  }
2478 
2479  av_bprintf(bp, "|element=");
2480  SERIALIZE(submix, elements[j]);
2481  if (ret && element_mix_config->nb_subblocks)
2482  av_bprintf(bp, ":");
2483  SERIALIZE_LOOP_SUBBLOCK(element_mix_config);
2484  if (ret)
2485  av_bprintf(bp, ":");
2486  av_bprintf(bp, "stg=%"PRId64, id);
2487  }
2488  SERIALIZE_LOOP(submix, layout, s, "|");
2489  }
2490  break;
2491  }
2495  break;
2496  default:
2497  av_log(mux, AV_LOG_ERROR, "Unsupported mapped group type %d.\n", stg->type);
2498  ret = AVERROR(EINVAL);
2499  break;
2500  }
2501  return 0;
2502 }
2503 
2504 static int of_parse_group_token(Muxer *mux, const char *token, char *ptr)
2505 {
2506  AVFormatContext *oc = mux->fc;
2507  AVStreamGroup *stg;
2508  AVDictionary *dict = NULL, *tmp = NULL;
2509  char *mapped_string = NULL;
2510  const AVDictionaryEntry *e;
2511  const AVOption opts[] = {
2512  { "type", "Set group type", offsetof(AVStreamGroup, type), AV_OPT_TYPE_INT,
2513  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, .unit = "type" },
2514  { "iamf_audio_element", NULL, 0, AV_OPT_TYPE_CONST,
2515  { .i64 = AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT }, .unit = "type" },
2516  { "iamf_mix_presentation", NULL, 0, AV_OPT_TYPE_CONST,
2517  { .i64 = AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION }, .unit = "type" },
2518  { "lcevc", NULL, 0, AV_OPT_TYPE_CONST,
2519  { .i64 = AV_STREAM_GROUP_PARAMS_LCEVC }, .unit = "type" },
2520  { "tref", NULL, 0, AV_OPT_TYPE_CONST,
2521  { .i64 = AV_STREAM_GROUP_PARAMS_TREF }, .unit = "type" },
2522  { NULL },
2523  };
2524  const AVClass class = {
2525  .class_name = "StreamGroupType",
2526  .item_name = av_default_item_name,
2527  .option = opts,
2528  .version = LIBAVUTIL_VERSION_INT,
2529  };
2530  const AVClass *pclass = &class;
2531  int type, ret;
2532 
2533  ret = av_dict_parse_string(&dict, token, "=", ":", AV_DICT_MULTIKEY);
2534  if (ret < 0) {
2535  av_log(mux, AV_LOG_ERROR, "Error parsing group specification %s\n", token);
2536  return ret;
2537  }
2538 
2539  av_dict_copy(&tmp, dict, 0);
2540  e = av_dict_get(dict, "map", NULL, 0);
2541  if (e) {
2542  AVBPrint bp;
2543 
2544  if (ptr) {
2545  av_log(mux, AV_LOG_ERROR, "Unexpected extra parameters when mapping a"
2546  " stream group\n");
2547  ret = AVERROR(EINVAL);
2548  goto end;
2549  }
2550 
2552  ret = of_map_group(mux, &tmp, &bp, e->value);
2553  if (ret < 0) {
2554  av_bprint_finalize(&bp, NULL);
2555  goto end;
2556  }
2557 
2558  av_bprint_finalize(&bp, &mapped_string);
2559  ptr = mapped_string;
2560  }
2561 
2562  // "type" is not a user settable AVOption in AVStreamGroup, so handle it here
2563  e = av_dict_get(tmp, "type", NULL, 0);
2564  if (!e) {
2565  av_log(mux, AV_LOG_ERROR, "No type specified for Stream Group in \"%s\"\n", token);
2566  ret = AVERROR(EINVAL);
2567  goto end;
2568  }
2569 
2570  ret = av_opt_eval_int(&pclass, opts, e->value, &type);
2572  ret = AVERROR(EINVAL);
2573  if (ret < 0) {
2574  av_log(mux, AV_LOG_ERROR, "Invalid group type \"%s\"\n", e->value);
2575  goto end;
2576  }
2577 
2578  stg = avformat_stream_group_create(oc, type, &tmp);
2579  if (!stg) {
2580  ret = AVERROR(ENOMEM);
2581  goto end;
2582  }
2583 
2584  e = NULL;
2585  while (e = av_dict_get(dict, "st", e, 0)) {
2586  char *endptr;
2587  int64_t idx = strtoll(e->value, &endptr, 0);
2588  if (*endptr || idx < 0 || idx >= oc->nb_streams) {
2589  av_log(mux, AV_LOG_ERROR, "Invalid stream index %"PRId64"\n", idx);
2590  ret = AVERROR(EINVAL);
2591  goto end;
2592  }
2593  ret = avformat_stream_group_add_stream(stg, oc->streams[idx]);
2594  if (ret < 0)
2595  goto end;
2596  OutputStream *ost = mux->of.streams[idx];
2599  ost->enc->enc_ctx->flags2 |= AV_CODEC_FLAG2_FIXED_FRAME_SIZE;
2600  }
2601  while (e = av_dict_get(dict, "stg", e, 0)) {
2602  char *endptr;
2603  int64_t idx = strtoll(e->value, &endptr, 0);
2604  if (*endptr || idx < 0 || idx >= oc->nb_stream_groups - 1) {
2605  av_log(mux, AV_LOG_ERROR, "Invalid stream group index %"PRId64"\n", idx);
2606  ret = AVERROR(EINVAL);
2607  goto end;
2608  }
2609  for (unsigned i = 0; i < oc->stream_groups[idx]->nb_streams; i++) {
2611  if (ret < 0)
2612  goto end;
2613  }
2614  }
2615 
2616  switch(type) {
2618  ret = of_parse_iamf_audio_element_layers(mux, stg, ptr);
2619  break;
2621  ret = of_parse_iamf_submixes(mux, stg, ptr);
2622  break;
2623  default:
2624  break;
2625  }
2626 
2627  if (ret < 0)
2628  goto end;
2629 
2630  // make sure that nothing but "st" and "stg" entries are left in the dict
2631  e = NULL;
2632  av_dict_set(&tmp, "map", NULL, 0);
2633  av_dict_set(&tmp, "type", NULL, 0);
2634  while (e = av_dict_iterate(tmp, e)) {
2635  if (!strcmp(e->key, "st") || !strcmp(e->key, "stg"))
2636  continue;
2637 
2638  av_log(mux, AV_LOG_FATAL, "Unknown group key %s.\n", e->key);
2639  ret = AVERROR(EINVAL);
2640  goto end;
2641  }
2642 
2643  ret = 0;
2644 end:
2645  av_free(mapped_string);
2646  av_dict_free(&dict);
2647  av_dict_free(&tmp);
2648 
2649  return ret;
2650 }
2651 
2652 static int of_add_groups(Muxer *mux, const OptionsContext *o)
2653 {
2654  /* process manually set groups */
2655  for (int i = 0; i < o->stream_groups.nb_opt; i++) {
2656  const char *token;
2657  char *str, *ptr = NULL;
2658  int ret = 0;
2659 
2660  str = av_strdup(o->stream_groups.opt[i].u.str);
2661  if (!str)
2662  return ret;
2663 
2664  token = av_strtok(str, ",", &ptr);
2665  if (token) {
2666  if (ptr)
2667  ptr += strspn(ptr, " \n\t\r");
2668  ret = of_parse_group_token(mux, token, ptr);
2669  }
2670 
2671  av_free(str);
2672  if (ret < 0)
2673  return ret;
2674  }
2675 
2676  return 0;
2677 }
2678 
2679 static int of_add_programs(Muxer *mux, const OptionsContext *o)
2680 {
2681  AVFormatContext *oc = mux->fc;
2682  /* process manually set programs */
2683  for (int i = 0; i < o->program.nb_opt; i++) {
2684  AVDictionary *dict = NULL;
2685  const AVDictionaryEntry *e;
2686  AVProgram *program;
2687  int ret, progid = i + 1;
2688 
2689  ret = av_dict_parse_string(&dict, o->program.opt[i].u.str, "=", ":",
2691  if (ret < 0) {
2692  av_log(mux, AV_LOG_ERROR, "Error parsing program specification %s\n",
2693  o->program.opt[i].u.str);
2694  return ret;
2695  }
2696 
2697  e = av_dict_get(dict, "program_num", NULL, 0);
2698  if (e) {
2699  progid = strtol(e->value, NULL, 0);
2700  av_dict_set(&dict, e->key, NULL, 0);
2701  }
2702 
2703  program = av_new_program(oc, progid);
2704  if (!program) {
2705  ret = AVERROR(ENOMEM);
2706  goto fail;
2707  }
2708 
2709  e = av_dict_get(dict, "title", NULL, 0);
2710  if (e) {
2711  av_dict_set(&program->metadata, e->key, e->value, 0);
2712  av_dict_set(&dict, e->key, NULL, 0);
2713  }
2714 
2715  e = NULL;
2716  while (e = av_dict_get(dict, "st", e, 0)) {
2717  int st_num = strtol(e->value, NULL, 0);
2718  av_program_add_stream_index(oc, progid, st_num);
2719  }
2720 
2721  // make sure that nothing but "st" entries are left in the dict
2722  e = NULL;
2723  while (e = av_dict_iterate(dict, e)) {
2724  if (!strcmp(e->key, "st"))
2725  continue;
2726 
2727  av_log(mux, AV_LOG_FATAL, "Unknown program key %s.\n", e->key);
2728  ret = AVERROR(EINVAL);
2729  goto fail;
2730  }
2731 
2732 fail:
2733  av_dict_free(&dict);
2734  if (ret < 0)
2735  return ret;
2736  }
2737 
2738  return 0;
2739 }
2740 
2741 /**
2742  * Parse a metadata specifier passed as 'arg' parameter.
2743  * @param arg metadata string to parse
2744  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
2745  * @param index for type c/p, chapter/program index is written here
2746  * @param stream_spec for type s, the stream specifier is written here
2747  */
2748 static int parse_meta_type(void *logctx, const char *arg,
2749  char *type, int *index, const char **stream_spec)
2750 {
2751  if (*arg) {
2752  *type = *arg;
2753  switch (*arg) {
2754  case 'g':
2755  break;
2756  case 's':
2757  if (*(++arg) && *arg != ':') {
2758  av_log(logctx, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
2759  return AVERROR(EINVAL);
2760  }
2761  *stream_spec = *arg == ':' ? arg + 1 : "";
2762  break;
2763  case 'c':
2764  case 'p':
2765  if (*(++arg) == ':')
2766  *index = strtol(++arg, NULL, 0);
2767  break;
2768  default:
2769  av_log(logctx, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
2770  return AVERROR(EINVAL);
2771  }
2772  } else
2773  *type = 'g';
2774 
2775  return 0;
2776 }
2777 
2779  const OptionsContext *o)
2780 {
2781  for (int i = 0; i < o->metadata.nb_opt; i++) {
2782  AVDictionary **m;
2783  char type, *val;
2784  const char *stream_spec;
2785  int index = 0, ret = 0;
2786 
2787  val = strchr(o->metadata.opt[i].u.str, '=');
2788  if (!val) {
2789  av_log(of, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
2790  o->metadata.opt[i].u.str);
2791  return AVERROR(EINVAL);
2792  }
2793  *val++ = 0;
2794 
2795  ret = parse_meta_type(of, o->metadata.opt[i].specifier, &type, &index, &stream_spec);
2796  if (ret < 0)
2797  return ret;
2798 
2799  if (type == 's') {
2800  for (int j = 0; j < oc->nb_streams; j++) {
2801  if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
2802  av_dict_set(&oc->streams[j]->metadata, o->metadata.opt[i].u.str, *val ? val : NULL, 0);
2803  } else if (ret < 0)
2804  return ret;
2805  }
2806  } else {
2807  switch (type) {
2808  case 'g':
2809  m = &oc->metadata;
2810  break;
2811  case 'c':
2812  if (index < 0 || index >= oc->nb_chapters) {
2813  av_log(of, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
2814  return AVERROR(EINVAL);
2815  }
2816  m = &oc->chapters[index]->metadata;
2817  break;
2818  case 'p':
2819  if (index < 0 || index >= oc->nb_programs) {
2820  av_log(of, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
2821  return AVERROR(EINVAL);
2822  }
2823  m = &oc->programs[index]->metadata;
2824  break;
2825  default:
2826  av_log(of, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata.opt[i].specifier);
2827  return AVERROR(EINVAL);
2828  }
2829  av_dict_set(m, o->metadata.opt[i].u.str, *val ? val : NULL, 0);
2830  }
2831  }
2832 
2833  return 0;
2834 }
2835 
2836 static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os,
2837  int copy_metadata)
2838 {
2839  AVFormatContext *is = ifile->ctx;
2840  AVChapter **tmp;
2841 
2842  tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
2843  if (!tmp)
2844  return AVERROR(ENOMEM);
2845  os->chapters = tmp;
2846 
2847  for (int i = 0; i < is->nb_chapters; i++) {
2848  AVChapter *in_ch = is->chapters[i], *out_ch;
2849  int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
2850  int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
2851  AV_TIME_BASE_Q, in_ch->time_base);
2852  int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
2854 
2855 
2856  if (in_ch->end < ts_off)
2857  continue;
2858  if (rt != INT64_MAX && in_ch->start > rt + ts_off)
2859  break;
2860 
2861  out_ch = av_mallocz(sizeof(AVChapter));
2862  if (!out_ch)
2863  return AVERROR(ENOMEM);
2864 
2865  out_ch->id = in_ch->id;
2866  out_ch->time_base = in_ch->time_base;
2867  out_ch->start = FFMAX(0, in_ch->start - ts_off);
2868  out_ch->end = FFMIN(rt, in_ch->end - ts_off);
2869 
2870  if (copy_metadata)
2871  av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
2872 
2873  os->chapters[os->nb_chapters++] = out_ch;
2874  }
2875  return 0;
2876 }
2877 
2878 static int copy_metadata(Muxer *mux, AVFormatContext *ic,
2879  const char *outspec, const char *inspec,
2880  int *metadata_global_manual, int *metadata_streams_manual,
2881  int *metadata_chapters_manual)
2882 {
2883  AVFormatContext *oc = mux->fc;
2884  AVDictionary **meta_in = NULL;
2885  AVDictionary **meta_out = NULL;
2886  int i, ret = 0;
2887  char type_in, type_out;
2888  const char *istream_spec = NULL, *ostream_spec = NULL;
2889  int idx_in = 0, idx_out = 0;
2890 
2891  ret = parse_meta_type(mux, inspec, &type_in, &idx_in, &istream_spec);
2892  if (ret >= 0)
2893  ret = parse_meta_type(mux, outspec, &type_out, &idx_out, &ostream_spec);
2894  if (ret < 0)
2895  return ret;
2896 
2897  if (type_in == 'g' || type_out == 'g' || (!*outspec && !ic))
2898  *metadata_global_manual = 1;
2899  if (type_in == 's' || type_out == 's' || (!*outspec && !ic))
2900  *metadata_streams_manual = 1;
2901  if (type_in == 'c' || type_out == 'c' || (!*outspec && !ic))
2902  *metadata_chapters_manual = 1;
2903 
2904  /* ic is NULL when just disabling automatic mappings */
2905  if (!ic)
2906  return 0;
2907 
2908 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
2909  if ((index) < 0 || (index) >= (nb_elems)) {\
2910  av_log(mux, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
2911  (desc), (index));\
2912  return AVERROR(EINVAL);\
2913  }
2914 
2915 #define SET_DICT(type, meta, context, index)\
2916  switch (type) {\
2917  case 'g':\
2918  meta = &context->metadata;\
2919  break;\
2920  case 'c':\
2921  METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
2922  meta = &context->chapters[index]->metadata;\
2923  break;\
2924  case 'p':\
2925  METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
2926  meta = &context->programs[index]->metadata;\
2927  break;\
2928  case 's':\
2929  break; /* handled separately below */ \
2930  default: av_assert0(0);\
2931  }\
2932 
2933  SET_DICT(type_in, meta_in, ic, idx_in);
2934  SET_DICT(type_out, meta_out, oc, idx_out);
2935 
2936  /* for input streams choose first matching stream */
2937  if (type_in == 's') {
2938  for (i = 0; i < ic->nb_streams; i++) {
2939  if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
2940  meta_in = &ic->streams[i]->metadata;
2941  break;
2942  } else if (ret < 0)
2943  return ret;
2944  }
2945  if (!meta_in) {
2946  av_log(mux, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
2947  return AVERROR(EINVAL);
2948  }
2949  }
2950 
2951  if (type_out == 's') {
2952  for (i = 0; i < oc->nb_streams; i++) {
2953  if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
2954  meta_out = &oc->streams[i]->metadata;
2955  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
2956  } else if (ret < 0)
2957  return ret;
2958  }
2959  } else
2960  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
2961 
2962  return 0;
2963 }
2964 
2965 static int copy_meta(Muxer *mux, const OptionsContext *o)
2966 {
2967  OutputFile *of = &mux->of;
2968  AVFormatContext *oc = mux->fc;
2969  int chapters_input_file = o->chapters_input_file;
2970  int metadata_global_manual = 0;
2971  int metadata_streams_manual = 0;
2972  int metadata_chapters_manual = 0;
2973  int ret;
2974 
2975  /* copy metadata */
2976  for (int i = 0; i < o->metadata_map.nb_opt; i++) {
2977  char *p;
2978  int in_file_index = strtol(o->metadata_map.opt[i].u.str, &p, 0);
2979 
2980  if (in_file_index >= nb_input_files) {
2981  av_log(mux, AV_LOG_FATAL, "Invalid input file index %d while "
2982  "processing metadata maps\n", in_file_index);
2983  return AVERROR(EINVAL);
2984  }
2985  ret = copy_metadata(mux,
2986  in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL,
2987  o->metadata_map.opt[i].specifier, *p ? p + 1 : p,
2988  &metadata_global_manual, &metadata_streams_manual,
2989  &metadata_chapters_manual);
2990  if (ret < 0)
2991  return ret;
2992  }
2993 
2994  /* copy chapters */
2995  if (chapters_input_file >= nb_input_files) {
2996  if (chapters_input_file == INT_MAX) {
2997  /* copy chapters from the first input file that has them*/
2998  chapters_input_file = -1;
2999  for (int i = 0; i < nb_input_files; i++)
3000  if (input_files[i]->ctx->nb_chapters) {
3001  chapters_input_file = i;
3002  break;
3003  }
3004  } else {
3005  av_log(mux, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
3006  chapters_input_file);
3007  return AVERROR(EINVAL);
3008  }
3009  }
3010  if (chapters_input_file >= 0)
3011  copy_chapters(input_files[chapters_input_file], of, oc,
3012  !metadata_chapters_manual);
3013 
3014  /* copy global metadata by default */
3015  if (!metadata_global_manual && nb_input_files){
3018  if (of->recording_time != INT64_MAX)
3019  av_dict_set(&oc->metadata, "duration", NULL, 0);
3020  av_dict_set(&oc->metadata, "creation_time", NULL, 0);
3021  av_dict_set(&oc->metadata, "company_name", NULL, 0);
3022  av_dict_set(&oc->metadata, "product_name", NULL, 0);
3023  av_dict_set(&oc->metadata, "product_version", NULL, 0);
3024  }
3025  if (!metadata_streams_manual)
3026  for (int i = 0; i < of->nb_streams; i++) {
3027  OutputStream *ost = of->streams[i];
3028 
3029  if (!ost->ist) /* this is true e.g. for attached files */
3030  continue;
3032  }
3033 
3034  return 0;
3035 }
3036 
3037 static int set_dispositions(Muxer *mux, const OptionsContext *o)
3038 {
3039  OutputFile *of = &mux->of;
3040  AVFormatContext *ctx = mux->fc;
3041 
3042  // indexed by type+1, because AVMEDIA_TYPE_UNKNOWN=-1
3043  int nb_streams[AVMEDIA_TYPE_NB + 1] = { 0 };
3044  int have_default[AVMEDIA_TYPE_NB + 1] = { 0 };
3045  int have_manual = 0;
3046  int ret = 0;
3047 
3048  const char **dispositions;
3049 
3050  dispositions = av_calloc(ctx->nb_streams, sizeof(*dispositions));
3051  if (!dispositions)
3052  return AVERROR(ENOMEM);
3053 
3054  // first, copy the input dispositions
3055  for (int i = 0; i < ctx->nb_streams; i++) {
3056  OutputStream *ost = of->streams[i];
3057 
3058  nb_streams[ost->type + 1]++;
3059 
3060  opt_match_per_stream_str(ost, &o->disposition, ctx, ost->st, &dispositions[i]);
3061 
3062  have_manual |= !!dispositions[i];
3063 
3064  if (ost->ist) {
3065  ost->st->disposition = ost->ist->st->disposition;
3066 
3068  have_default[ost->type + 1] = 1;
3069  }
3070  }
3071 
3072  if (have_manual) {
3073  // process manually set dispositions - they override the above copy
3074  for (int i = 0; i < ctx->nb_streams; i++) {
3075  OutputStream *ost = of->streams[i];
3076  const char *disp = dispositions[i];
3077 
3078  if (!disp)
3079  continue;
3080 
3081  ret = av_opt_set(ost->st, "disposition", disp, 0);
3082  if (ret < 0)
3083  goto finish;
3084  }
3085  } else {
3086  // For each media type with more than one stream, find a suitable stream to
3087  // mark as default, unless one is already marked default.
3088  // "Suitable" means the first of that type, skipping attached pictures.
3089  for (int i = 0; i < ctx->nb_streams; i++) {
3090  OutputStream *ost = of->streams[i];
3091  enum AVMediaType type = ost->type;
3092 
3093  if (nb_streams[type + 1] < 2 || have_default[type + 1] ||
3095  continue;
3096 
3098  have_default[type + 1] = 1;
3099  }
3100  }
3101 
3102 finish:
3103  av_freep(&dispositions);
3104 
3105  return ret;
3106 }
3107 
3108 static const char *const forced_keyframes_const_names[] = {
3109  "n",
3110  "n_forced",
3111  "prev_forced_n",
3112  "prev_forced_t",
3113  "t",
3114  NULL
3115 };
3116 
3117 static int compare_int64(const void *a, const void *b)
3118 {
3119  return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
3120 }
3121 
3123  const Muxer *mux, const char *spec)
3124 {
3125  const char *p;
3126  int n = 1, i, ret, size, index = 0;
3127  int64_t t, *pts;
3128 
3129  for (p = spec; *p; p++)
3130  if (*p == ',')
3131  n++;
3132  size = n;
3133  pts = av_malloc_array(size, sizeof(*pts));
3134  if (!pts)
3135  return AVERROR(ENOMEM);
3136 
3137  p = spec;
3138  for (i = 0; i < n; i++) {
3139  char *next = strchr(p, ',');
3140 
3141  if (next)
3142  *next++ = 0;
3143 
3144  if (strstr(p, "chapters") == p) {
3145  AVChapter * const *ch = mux->fc->chapters;
3146  unsigned int nb_ch = mux->fc->nb_chapters;
3147  int j;
3148 
3149  if (nb_ch > INT_MAX - size) {
3150  ret = AVERROR(ERANGE);
3151  goto fail;
3152  }
3153  size += nb_ch - 1;
3154  pts = av_realloc_f(pts, size, sizeof(*pts));
3155  if (!pts)
3156  return AVERROR(ENOMEM);
3157 
3158  if (p[8]) {
3159  ret = av_parse_time(&t, p + 8, 1);
3160  if (ret < 0) {
3162  "Invalid chapter time offset: %s\n", p + 8);
3163  goto fail;
3164  }
3165  } else
3166  t = 0;
3167 
3168  for (j = 0; j < nb_ch; j++) {
3169  const AVChapter *c = ch[j];
3170  av_assert1(index < size);
3171  pts[index++] = av_rescale_q(c->start, c->time_base,
3172  AV_TIME_BASE_Q) + t;
3173  }
3174 
3175  } else {
3176  av_assert1(index < size);
3177  ret = av_parse_time(&t, p, 1);
3178  if (ret < 0) {
3179  av_log(log, AV_LOG_ERROR, "Invalid keyframe time: %s\n", p);
3180  goto fail;
3181  }
3182 
3183  pts[index++] = t;
3184  }
3185 
3186  p = next;
3187  }
3188 
3189  av_assert0(index == size);
3190  qsort(pts, size, sizeof(*pts), compare_int64);
3191  kf->nb_pts = size;
3192  kf->pts = pts;
3193 
3194  return 0;
3195 fail:
3196  av_freep(&pts);
3197  return ret;
3198 }
3199 
3201 {
3202  for (int i = 0; i < mux->of.nb_streams; i++) {
3203  OutputStream *ost = mux->of.streams[i];
3204  const char *forced_keyframes = NULL;
3205 
3207  mux->fc, ost->st, &forced_keyframes);
3208 
3209  if (!(ost->type == AVMEDIA_TYPE_VIDEO &&
3210  ost->enc && forced_keyframes))
3211  continue;
3212 
3213  if (!strncmp(forced_keyframes, "expr:", 5)) {
3214  int ret = av_expr_parse(&ost->kf.pexpr, forced_keyframes + 5,
3216  if (ret < 0) {
3218  "Invalid force_key_frames expression '%s'\n", forced_keyframes + 5);
3219  return ret;
3220  }
3221  ost->kf.expr_const_values[FKF_N] = 0;
3222  ost->kf.expr_const_values[FKF_N_FORCED] = 0;
3223  ost->kf.expr_const_values[FKF_PREV_FORCED_N] = NAN;
3224  ost->kf.expr_const_values[FKF_PREV_FORCED_T] = NAN;
3225 
3226  // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
3227  // parse it only for static kf timings
3228  } else if (!strcmp(forced_keyframes, "source")) {
3229  ost->kf.type = KF_FORCE_SOURCE;
3230  } else if (!strcmp(forced_keyframes, "scd_metadata")) {
3231  ost->kf.type = KF_FORCE_SCD_METADATA;
3232  } else {
3233  int ret = parse_forced_key_frames(ost, &ost->kf, mux, forced_keyframes);
3234  if (ret < 0)
3235  return ret;
3236  }
3237  }
3238 
3239  return 0;
3240 }
3241 
3242 static const char *output_file_item_name(void *obj)
3243 {
3244  const Muxer *mux = obj;
3245 
3246  return mux->log_name;
3247 }
3248 
3249 static const AVClass output_file_class = {
3250  .class_name = "OutputFile",
3251  .version = LIBAVUTIL_VERSION_INT,
3252  .item_name = output_file_item_name,
3253  .category = AV_CLASS_CATEGORY_MUXER,
3254 };
3255 
3256 static Muxer *mux_alloc(void)
3257 {
3258  Muxer *mux = allocate_array_elem(&output_files, sizeof(*mux), &nb_output_files);
3259 
3260  if (!mux)
3261  return NULL;
3262 
3263  mux->of.class = &output_file_class;
3264  mux->of.index = nb_output_files - 1;
3265 
3266  snprintf(mux->log_name, sizeof(mux->log_name), "out#%d", mux->of.index);
3267 
3268  return mux;
3269 }
3270 
3271 int of_open(const OptionsContext *o, const char *filename, Scheduler *sch)
3272 {
3273  Muxer *mux;
3274  AVFormatContext *oc;
3275  int err;
3276  OutputFile *of;
3277 
3278  int64_t recording_time = o->recording_time;
3279  int64_t stop_time = o->stop_time;
3280 
3281  mux = mux_alloc();
3282  if (!mux)
3283  return AVERROR(ENOMEM);
3284 
3285  of = &mux->of;
3286 
3287  if (stop_time != INT64_MAX && recording_time != INT64_MAX) {
3288  stop_time = INT64_MAX;
3289  av_log(mux, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
3290  }
3291 
3292  if (stop_time != INT64_MAX && recording_time == INT64_MAX) {
3294  if (stop_time <= start_time) {
3295  av_log(mux, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
3296  return AVERROR(EINVAL);
3297  } else {
3298  recording_time = stop_time - start_time;
3299  }
3300  }
3301 
3302  of->recording_time = recording_time;
3303  of->start_time = o->start_time;
3304 
3305  mux->limit_filesize = o->limit_filesize;
3306  av_dict_copy(&mux->opts, o->g->format_opts, 0);
3307 
3308  if (!strcmp(filename, "-"))
3309  filename = "pipe:";
3310 
3311  err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
3312  if (!oc) {
3313  av_log(mux, AV_LOG_FATAL, "Error initializing the muxer for %s: %s\n",
3314  filename, av_err2str(err));
3315  return err;
3316  }
3317  mux->fc = oc;
3318 
3319  av_strlcat(mux->log_name, "/", sizeof(mux->log_name));
3320  av_strlcat(mux->log_name, oc->oformat->name, sizeof(mux->log_name));
3321 
3322 
3323  if (recording_time != INT64_MAX)
3324  oc->duration = recording_time;
3325 
3326  oc->interrupt_callback = int_cb;
3327 
3328  if (o->bitexact) {
3329  oc->flags |= AVFMT_FLAG_BITEXACT;
3330  of->bitexact = 1;
3331  } else {
3332  of->bitexact = check_opt_bitexact(oc, mux->opts, "fflags",
3334  }
3335 
3336  err = sch_add_mux(sch, muxer_thread, mux_check_init, mux,
3337  !strcmp(oc->oformat->name, "rtp"), o->thread_queue_size);
3338  if (err < 0)
3339  return err;
3340  mux->sch = sch;
3341  mux->sch_idx = err;
3342 
3343  /* create all output streams for this file */
3344  err = create_streams(mux, o);
3345  if (err < 0)
3346  return err;
3347 
3348  /* check if all codec options have been used */
3349  err = check_avoptions_used(o->g->codec_opts, mux->enc_opts_used, mux, 0);
3350  av_dict_free(&mux->enc_opts_used);
3351  if (err < 0)
3352  return err;
3353 
3354  /* check filename in case of an image number is expected */
3356  av_log(mux, AV_LOG_FATAL,
3357  "Output filename '%s' does not contain a numeric pattern like "
3358  "'%%d', which is required by output format '%s'.\n",
3359  oc->url, oc->oformat->name);
3360  return AVERROR(EINVAL);
3361  }
3362 
3363  if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3364  /* test if it already exists to avoid losing precious files */
3365  err = assert_file_overwrite(filename);
3366  if (err < 0)
3367  return err;
3368 
3369  /* open the file */
3370  if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
3371  &oc->interrupt_callback,
3372  &mux->opts)) < 0) {
3373  av_log(mux, AV_LOG_FATAL, "Error opening output %s: %s\n",
3374  filename, av_err2str(err));
3375  return err;
3376  }
3377  } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename)) {
3378  err = assert_file_overwrite(filename);
3379  if (err < 0)
3380  return err;
3381  }
3382 
3383  if (o->mux_preload) {
3384  av_dict_set_int(&mux->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
3385  }
3386  oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
3387 
3388  /* copy metadata and chapters from input files */
3389  err = copy_meta(mux, o);
3390  if (err < 0)
3391  return err;
3392 
3393  err = of_add_groups(mux, o);
3394  if (err < 0)
3395  return err;
3396 
3397  err = of_add_programs(mux, o);
3398  if (err < 0)
3399  return err;
3400 
3401  err = of_add_metadata(of, oc, o);
3402  if (err < 0)
3403  return err;
3404 
3405  err = set_dispositions(mux, o);
3406  if (err < 0) {
3407  av_log(mux, AV_LOG_FATAL, "Error setting output stream dispositions\n");
3408  return err;
3409  }
3410 
3411  // parse forced keyframe specifications;
3412  // must be done after chapters are created
3413  err = process_forced_keyframes(mux, o);
3414  if (err < 0) {
3415  av_log(mux, AV_LOG_FATAL, "Error processing forced keyframes\n");
3416  return err;
3417  }
3418 
3420  o->shortest);
3421  if (err < 0) {
3422  av_log(mux, AV_LOG_FATAL, "Error setting up output sync queues\n");
3423  return err;
3424  }
3425 
3426  of->url = filename;
3427 
3428  /* initialize streamcopy streams. */
3429  for (int i = 0; i < of->nb_streams; i++) {
3430  OutputStream *ost = of->streams[i];
3431 
3432  if (!ost->enc) {
3433  err = of_stream_init(of, ost, NULL);
3434  if (err < 0)
3435  return err;
3436  }
3437  }
3438 
3439  return 0;
3440 }
AV_OPT_SEARCH_CHILDREN
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition: opt.h:604
formats
formats
Definition: signature.h:47
KeyframeForceCtx::pts
int64_t * pts
Definition: ffmpeg.h:594
MuxStream::ost
OutputStream ost
Definition: ffmpeg_mux.h:37
iamf.h
fopen_utf8
static FILE * fopen_utf8(const char *path, const char *mode)
Definition: fopen_utf8.h:66
map_manual
static int map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
Definition: ffmpeg_mux_init.c:1753
SYNC_QUEUE_PACKETS
@ SYNC_QUEUE_PACKETS
Definition: sync_queue.h:29
AVCodec
AVCodec.
Definition: codec.h:169
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:203
AVIAMFSubmix::elements
AVIAMFSubmixElement ** elements
Array of submix elements.
Definition: iamf.h:568
av_codec_get_id
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
MuxStream::copy_initial_nonkeyframes
int copy_initial_nonkeyframes
Definition: ffmpeg_mux.h:81
MuxStream::sch_idx_enc
int sch_idx_enc
Definition: ffmpeg_mux.h:56
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:216
AVIAMFAudioElement::nb_layers
unsigned int nb_layers
Number of layers, or channel groups, in the Audio Element.
Definition: iamf.h:371
AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_UNLIMITED
InputFile::start_time
int64_t start_time
Definition: ffmpeg.h:518
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:71
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:71
Muxer::fc
AVFormatContext * fc
Definition: ffmpeg_mux.h:98
AVFormatContext::stream_groups
AVStreamGroup ** stream_groups
A list of all stream groups in the file.
Definition: avformat.h:1401
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
OptionsContext::stop_time
int64_t stop_time
Definition: ffmpeg.h:179
ost_get_filters
static int ost_get_filters(const OptionsContext *o, AVFormatContext *oc, OutputStream *ost, char **dst)
Definition: ffmpeg_mux_init.c:416
AVStreamGroup::id
int64_t id
Group type-specific group ID.
Definition: avformat.h:1159
AV_CODEC_ID_AC3
@ AV_CODEC_ID_AC3
Definition: codec_id.h:455
program
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C program
Definition: undefined.txt:6
OutputFilter::graph
struct FilterGraph * graph
Definition: ffmpeg.h:374
FKF_PREV_FORCED_T
@ FKF_PREV_FORCED_T
Definition: ffmpeg.h:535
InputFile::nb_stream_groups
int nb_stream_groups
Definition: ffmpeg.h:528
OptionsContext::force_fps
SpecifierOptList force_fps
Definition: ffmpeg.h:203
AVCodecContext::alpha_mode
enum AVAlphaMode alpha_mode
Indicates how the alpha channel of the video is represented.
Definition: avcodec.h:1937
OptionsContext::forced_key_frames
SpecifierOptList forced_key_frames
Definition: ffmpeg.h:201
ist_use
int ist_use(InputStream *ist, int decoding_needed, const ViewSpecifier *vs, SchedulerNode *src)
Definition: ffmpeg_demux.c:938
VSYNC_VFR
@ VSYNC_VFR
Definition: ffmpeg.h:60
mix
static int mix(int c0, int c1)
Definition: 4xm.c:717
ms_from_ost
static MuxStream * ms_from_ost(OutputStream *ost)
Definition: ffmpeg_mux.h:123
AVOutputFormat::name
const char * name
Definition: avformat.h:508
AVChapter::metadata
AVDictionary * metadata
Definition: avformat.h:1277
av_bprint_is_complete
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition: bprint.h:218
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
nb_input_files
int nb_input_files
Definition: ffmpeg.c:109
opt.h
flag
int flag
Definition: cpu.c:40
of_serialize_options
static int of_serialize_options(Muxer *mux, void *obj, AVBPrint *bp)
Definition: ffmpeg_mux_init.c:2352
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:53
AVStreamGroup::tile_grid
struct AVStreamGroupTileGrid * tile_grid
Definition: avformat.h:1175
LIBAVCODEC_IDENT
#define LIBAVCODEC_IDENT
Definition: version.h:43
AV_STREAM_GROUP_PARAMS_LCEVC
@ AV_STREAM_GROUP_PARAMS_LCEVC
Definition: avformat.h:1132
AVCodecContext::colorspace
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:671
MuxStream::sch_idx
int sch_idx
Definition: ffmpeg_mux.h:55
KF_FORCE_SCD_METADATA
@ KF_FORCE_SCD_METADATA
Definition: ffmpeg.h:585
AVSTREAM_EVENT_FLAG_NEW_PACKETS
#define AVSTREAM_EVENT_FLAG_NEW_PACKETS
Definition: avformat.h:871
check_avoptions
int check_avoptions(AVDictionary *m)
Definition: cmdutils.c:1605
ENC_STATS_PTS
@ ENC_STATS_PTS
Definition: ffmpeg.h:551
OutputFilter::apad
char * apad
Definition: ffmpeg.h:387
Muxer::sch_stream_idx
int * sch_stream_idx
Definition: ffmpeg_mux.h:104
ENC_STATS_FRAME_NUM_IN
@ ENC_STATS_FRAME_NUM_IN
Definition: ffmpeg.h:548
elements
static const ElemCat * elements[ELEMENT_COUNT]
Definition: signature.h:565
AVCodecContext::sample_rate
int sample_rate
samples per second
Definition: avcodec.h:1040
FKF_PREV_FORCED_N
@ FKF_PREV_FORCED_N
Definition: ffmpeg.h:534
av_bprint_init
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
is
The official guide to swscale for confused that is
Definition: swscale.txt:28
AVFormatContext::nb_chapters
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1414
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:49
Muxer::nb_sch_stream_idx
int nb_sch_stream_idx
Definition: ffmpeg_mux.h:105
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
enc_open
int enc_open(void *opaque, const AVFrame *frame)
Definition: ffmpeg_enc.c:184
av_pix_fmt_desc_get
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:3456
AVFMT_VARIABLE_FPS
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:482
av_iamf_param_definition_alloc
AVIAMFParamDefinition * av_iamf_param_definition_alloc(enum AVIAMFParamDefinitionType type, unsigned int nb_subblocks, size_t *out_size)
Allocates memory for AVIAMFParamDefinition, plus an array of.
Definition: iamf.c:159
AV_DISPOSITION_ATTACHED_PIC
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:673
ENC_STATS_DTS
@ ENC_STATS_DTS
Definition: ffmpeg.h:555
sq_limit_frames
void sq_limit_frames(SyncQueue *sq, unsigned int stream_idx, uint64_t frames)
Limit the number of output frames for stream with index stream_idx to max_frames.
Definition: sync_queue.c:628
pthread_mutex_init
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:104
AV_CODEC_CONFIG_SAMPLE_RATE
@ AV_CODEC_CONFIG_SAMPLE_RATE
int, terminated by 0
Definition: avcodec.h:2549
of_parse_iamf_audio_element_layers
static int of_parse_iamf_audio_element_layers(Muxer *mux, AVStreamGroup *stg, char *ptr)
Definition: ffmpeg_mux_init.c:2147
KeyframeForceCtx::nb_pts
int nb_pts
Definition: ffmpeg.h:595
AV_CODEC_FLAG_QSCALE
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition: avcodec.h:213
AVFMT_NOTIMESTAMPS
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition: avformat.h:479
AV_TIME_BASE_Q
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:263
int64_t
long long int64_t
Definition: coverity.c:34
InputStream::user_set_discard
int user_set_discard
Definition: ffmpeg.h:470
OptionsContext::bits_per_raw_sample
SpecifierOptList bits_per_raw_sample
Definition: ffmpeg.h:237
parse_and_set_vsync
int parse_and_set_vsync(const char *arg, enum VideoSyncMethod *vsync_var, int file_idx, int st_idx)
Definition: ffmpeg_opt.c:359
ENC_STATS_AVG_BITRATE
@ ENC_STATS_AVG_BITRATE
Definition: ffmpeg.h:561
AVCodecContext::intra_matrix
uint16_t * intra_matrix
custom intra quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition: avcodec.h:960
OptionsContext::audio_ch_layouts
SpecifierOptList audio_ch_layouts
Definition: ffmpeg.h:142
OptionsContext::qscale
SpecifierOptList qscale
Definition: ffmpeg.h:200
AVStreamGroup::disposition
int disposition
Stream group disposition - a combination of AV_DISPOSITION_* flags.
Definition: avformat.h:1225
ist_iter
InputStream * ist_iter(InputStream *prev)
Definition: ffmpeg.c:387
normalize.log
log
Definition: normalize.py:21
AV_DISPOSITION_DEFAULT
#define AV_DISPOSITION_DEFAULT
The stream should be chosen by default among other streams of the same type, unless the user has expl...
Definition: avformat.h:620
OptionsContext::nb_attachments
int nb_attachments
Definition: ffmpeg.h:174
OutputFile::start_time
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:684
avcodec_find_encoder
const AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
Definition: allcodecs.c:983
InputFile::index
int index
Definition: ffmpeg.h:507
OptionsContext::presets
SpecifierOptList presets
Definition: ffmpeg.h:215
pixdesc.h
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1382
OptionsContext::mux_max_delay
float mux_max_delay
Definition: ffmpeg.h:182
AVPacketSideData
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition: packet.h:424
subtitle_codec_name
static const char * subtitle_codec_name
Definition: ffplay.c:342
ENC_STATS_LITERAL
@ ENC_STATS_LITERAL
Definition: ffmpeg.h:544
OptionsContext::subtitle_disable
int subtitle_disable
Definition: ffmpeg.h:189
AV_CODEC_CONFIG_COLOR_RANGE
@ AV_CODEC_CONFIG_COLOR_RANGE
AVColorRange, terminated by AVCOL_RANGE_UNSPECIFIED.
Definition: avcodec.h:2552
OptionsContext::passlogfiles
SpecifierOptList passlogfiles
Definition: ffmpeg.h:225
AVOption
AVOption.
Definition: opt.h:428
OutputStream::index
int index
Definition: ffmpeg.h:629
streamcopy_init
static int streamcopy_init(const OptionsContext *o, const Muxer *mux, OutputStream *ost, AVDictionary **encoder_opts)
Definition: ffmpeg_mux_init.c:984
b
#define b
Definition: input.c:43
ofilter_bind_enc
int ofilter_bind_enc(OutputFilter *ofilter, unsigned sched_idx_enc, const OutputFilterOptions *opts)
Definition: ffmpeg_filter.c:812
FilterGraph::index
int index
Definition: ffmpeg.h:397
choose_pixel_fmt
static enum AVPixelFormat choose_pixel_fmt(const AVCodecContext *avctx, enum AVPixelFormat target)
Definition: ffmpeg_mux_init.c:468
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:836
AVChapter::start
int64_t start
Definition: avformat.h:1276
Muxer::of
OutputFile of
Definition: ffmpeg_mux.h:93
MuxStream::force_fps
int force_fps
Definition: ffmpeg_mux.h:87
RcOverride::qscale
int qscale
Definition: avcodec.h:196
ffmpeg.h
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:226
base
uint8_t base
Definition: vp3data.h:128
freeenv_utf8
static void freeenv_utf8(char *var)
Definition: getenv_utf8.h:72
nb_streams
static unsigned int nb_streams
Definition: ffprobe.c:352
OptionGroup::swr_opts
AVDictionary * swr_opts
Definition: cmdutils.h:350
AVFormatContext::programs
AVProgram ** programs
Definition: avformat.h:1512
AVIAMFParamDefinition
Parameters as defined in section 3.6.1 of IAMF.
Definition: iamf.h:193
OptionsContext::bitexact
int bitexact
Definition: ffmpeg.h:185
ViewSpecifier
Definition: ffmpeg.h:116
get_stream_group_index_from_id
static int64_t get_stream_group_index_from_id(Muxer *mux, int64_t id)
Definition: ffmpeg_mux_init.c:2393
AVCodecParameters::codec_tag
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:61
video_disable
static int video_disable
Definition: ffplay.c:317
AVDictionary
Definition: dict.c:32
AVChannelLayout::order
enum AVChannelOrder order
Channel order used in this layout.
Definition: channel_layout.h:324
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
AV_CODEC_CONFIG_PIX_FORMAT
@ AV_CODEC_CONFIG_PIX_FORMAT
AVPixelFormat, terminated by AV_PIX_FMT_NONE.
Definition: avcodec.h:2547
MuxStream::copy_prior_start
int copy_prior_start
Definition: ffmpeg_mux.h:82
OptionsContext::format
const char * format
Definition: ffmpeg.h:139
parse_forced_key_frames
static int parse_forced_key_frames(void *log, KeyframeForceCtx *kf, const Muxer *mux, const char *spec)
Definition: ffmpeg_mux_init.c:3122
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:329
enc_stats_init
static int enc_stats_init(OutputStream *ost, EncStats *es, int pre, const char *path, const char *fmt_spec)
Definition: ffmpeg_mux_init.c:246
ost_add
static int ost_add(Muxer *mux, const OptionsContext *o, enum AVMediaType type, InputStream *ist, OutputFilter *ofilter, const ViewSpecifier *vs, OutputStream **post)
Definition: ffmpeg_mux_init.c:1134
avio_size
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:326
ost
static AVStream * ost
Definition: vaapi_transcode.c:42
parse_matrix_coeffs
static int parse_matrix_coeffs(void *logctx, uint16_t *dest, const char *str)
Definition: ffmpeg_mux_init.c:440
OptionsContext::frame_pix_fmts
SpecifierOptList frame_pix_fmts
Definition: ffmpeg.h:148
set_dispositions
static int set_dispositions(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:3037
av_opt_serialize
int av_opt_serialize(void *obj, int opt_flags, int flags, char **buffer, const char key_val_sep, const char pairs_sep)
Serialize object's options.
Definition: opt.c:2753
MuxStream::ts_copy_start
int64_t ts_copy_start
Definition: ffmpeg_mux.h:66
OutputStream::file
struct OutputFile * file
Definition: ffmpeg.h:627
AVOutputFormat::subtitle_codec
enum AVCodecID subtitle_codec
default subtitle codec
Definition: avformat.h:520
MuxStream::stream_duration_tb
AVRational stream_duration_tb
Definition: ffmpeg_mux.h:73
ENC_STATS_TIMEBASE_IN
@ ENC_STATS_TIMEBASE_IN
Definition: ffmpeg.h:550
AV_CODEC_FLAG_GLOBAL_HEADER
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition: avcodec.h:318
get_preset_file_2
static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
Definition: ffmpeg_mux_init.c:126
OutputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:681
av_filename_number_test
int av_filename_number_test(const char *filename)
Check whether filename actually is a numbered sequence generator.
Definition: utils.c:121
av_expr_parse
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
Definition: eval.c:735
Muxer
Definition: ffmpeg_mux.h:92
InputStream
Definition: ffmpeg.h:461
OptionsContext::chapters_input_file
int chapters_input_file
Definition: ffmpeg.h:176
AVPacketSideData::size
size_t size
Definition: packet.h:426
OutputFilterOptions
Definition: ffmpeg.h:292
EncStatsFile
Definition: ffmpeg_mux_init.c:156
AVFormatContext::interrupt_callback
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1584
map_auto_subtitle
static int map_auto_subtitle(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1691
OptionsContext::max_frame_rates
SpecifierOptList max_frame_rates
Definition: ffmpeg.h:146
AV_OPT_SERIALIZE_SEARCH_CHILDREN
#define AV_OPT_SERIALIZE_SEARCH_CHILDREN
Serialize options in possible children of the given object.
Definition: opt.h:1093
finish
static void finish(void)
Definition: movenc.c:374
fopen_utf8.h
av_iamf_mix_presentation_add_submix
AVIAMFSubmix * av_iamf_mix_presentation_add_submix(AVIAMFMixPresentation *mix_presentation)
Allocate a submix and add it to a given AVIAMFMixPresentation.
AVCodecContext::codec
const struct AVCodec * codec
Definition: avcodec.h:452
of_parse_group_token
static int of_parse_group_token(Muxer *mux, const char *token, char *ptr)
Definition: ffmpeg_mux_init.c:2504
InputStreamGroup
Definition: ffmpeg.h:492
OptionsContext::g
OptionGroup * g
Definition: ffmpeg.h:133
AVCodecContext::ch_layout
AVChannelLayout ch_layout
Audio channel layout.
Definition: avcodec.h:1055
mux_alloc
static Muxer * mux_alloc(void)
Definition: ffmpeg_mux_init.c:3256
opt_match_per_stream_int
void opt_match_per_stream_int(void *logctx, const SpecifierOptList *sol, AVFormatContext *fc, AVStream *st, int *out)
OptionsContext::enc_stats_pre_fmt
SpecifierOptList enc_stats_pre_fmt
Definition: ffmpeg.h:241
AVFMT_FIXED_FRAMESIZE
#define AVFMT_FIXED_FRAMESIZE
Format wants fixed size audio frames..
Definition: avformat.h:499
AVStreamGroupTileGrid
AVStreamGroupTileGrid holds information on how to combine several independent images on a single canv...
Definition: avformat.h:954
OptionsContext::mux_stats_fmt
SpecifierOptList mux_stats_fmt
Definition: ffmpeg.h:243
AVIAMFSubmixLayout
Submix layout as defined in section 3.7.6 of IAMF.
Definition: iamf.h:517
sch_add_mux_stream
int sch_add_mux_stream(Scheduler *sch, unsigned mux_idx)
Add a muxed stream for a previously added muxer.
Definition: ffmpeg_sched.c:694
SCH_NODE_TYPE_NONE
@ SCH_NODE_TYPE_NONE
Definition: ffmpeg_sched.h:94
copy_meta
static int copy_meta(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2965
AV_BPRINT_SIZE_AUTOMATIC
#define AV_BPRINT_SIZE_AUTOMATIC
AVCodecContext::flags
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:500
AVChapter
Definition: avformat.h:1273
val
static double val(void *priv, double ch)
Definition: aeval.c:77
SCH_ENC
#define SCH_ENC(encoder)
Definition: ffmpeg_sched.h:123
type
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf type
Definition: writing_filters.txt:86
pts
static int64_t pts
Definition: transcode_aac.c:649
OptionsContext
Definition: ffmpeg.h:132
av_opt_set
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:824
av_new_program
AVProgram * av_new_program(AVFormatContext *ac, int id)
Definition: avformat.c:277
AV_CODEC_ID_MP3
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: codec_id.h:453
Muxer::sq_pkt
AVPacket * sq_pkt
Definition: ffmpeg_mux.h:118
AVStream::duration
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:806
av_codec_get_tag2
int av_codec_get_tag2(const struct AVCodecTag *const *tags, enum AVCodecID id, unsigned int *tag)
Get the codec tag for the given codec id.
AV_OPT_SERIALIZE_SKIP_DEFAULTS
#define AV_OPT_SERIALIZE_SKIP_DEFAULTS
Serialize options that are not set to default values only.
Definition: opt.h:1091
enc_stats_files
static EncStatsFile * enc_stats_files
Definition: ffmpeg_mux_init.c:161
new_stream_video
static int new_stream_video(Muxer *mux, const OptionsContext *o, OutputStream *ost, int *keep_pix_fmt, enum VideoSyncMethod *vsync_method)
Definition: ffmpeg_mux_init.c:548
AV_STREAM_GROUP_PARAMS_DOLBY_VISION
@ AV_STREAM_GROUP_PARAMS_DOLBY_VISION
Definition: avformat.h:1134
AVRational::num
int num
Numerator.
Definition: rational.h:59
OutputFilter::bound
int bound
Definition: ffmpeg.h:384
InputFile
Definition: ffmpeg.h:504
FFDIFFSIGN
#define FFDIFFSIGN(x, y)
Comparator.
Definition: macros.h:45
AV_DICT_DONT_STRDUP_VAL
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:79
AV_IAMF_PARAMETER_DEFINITION_RECON_GAIN
@ AV_IAMF_PARAMETER_DEFINITION_RECON_GAIN
Subblocks are of struct type AVIAMFReconGain.
Definition: iamf.h:181
OptionsContext::recording_time
int64_t recording_time
Definition: ffmpeg.h:178
OptionsContext::nb_stream_maps
int nb_stream_maps
Definition: ffmpeg.h:172
OptionsContext::audio_disable
int audio_disable
Definition: ffmpeg.h:188
check_stream_specifier
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
Check if the given stream matches a stream specifier.
Definition: cmdutils.c:1338
preset
preset
Definition: vf_curves.c:47
avassert.h
RcOverride::quality_factor
float quality_factor
Definition: avcodec.h:197
MuxStream::log_name
char log_name[32]
Definition: ffmpeg_mux.h:46
opt_match_per_stream_int64
void opt_match_per_stream_int64(void *logctx, const SpecifierOptList *sol, AVFormatContext *fc, AVStream *st, int64_t *out)
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:210
AVFormatContext::metadata
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1546
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
OptionGroup::codec_opts
AVDictionary * codec_opts
Definition: cmdutils.h:347
av_dump_format
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Print detailed information about the input or output format, such as duration, bitrate,...
Definition: dump.c:852
AVCodecTag
Definition: internal.h:42
ENC_STATS_PTS_IN
@ ENC_STATS_PTS_IN
Definition: ffmpeg.h:553
OptionsContext::metadata
SpecifierOptList metadata
Definition: ffmpeg.h:195
SpecifierOptList::nb_opt
int nb_opt
Definition: cmdutils.h:185
OptionsContext::filters
SpecifierOptList filters
Definition: ffmpeg.h:218
choose_encoder
static int choose_encoder(const OptionsContext *o, AVFormatContext *s, MuxStream *ms, const AVCodec **enc)
Definition: ffmpeg_mux_init.c:69
av_dict_get
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:60
avformat_query_codec
int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance)
Test if the given container can store a codec.
Definition: mux_utils.c:32
av_iamf_submix_add_layout
AVIAMFSubmixLayout * av_iamf_submix_add_layout(AVIAMFSubmix *submix)
Allocate a submix layout and add it to a given AVIAMFSubmix.
AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION
@ AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION
Definition: avformat.h:1130
output_stream_class
static const AVClass output_stream_class
Definition: ffmpeg_mux_init.c:385
VSYNC_VSCFR
@ VSYNC_VSCFR
Definition: ffmpeg.h:61
EncStats::components
EncStatsComponent * components
Definition: ffmpeg.h:573
of_parse_iamf_submixes
static int of_parse_iamf_submixes(Muxer *mux, AVStreamGroup *stg, char *ptr)
Definition: ffmpeg_mux_init.c:2223
avcodec_alloc_context3
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:149
assert_file_overwrite
int assert_file_overwrite(const char *filename)
Definition: ffmpeg_opt.c:816
AVChapter::end
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1276
SpecifierOpt::specifier
char * specifier
Definition: cmdutils.h:169
AVCodecDescriptor
This struct describes the properties of a single codec described by an AVCodecID.
Definition: codec_desc.h:38
mux_stream_alloc
static MuxStream * mux_stream_alloc(Muxer *mux, enum AVMediaType type)
Definition: ffmpeg_mux_init.c:392
AV_CODEC_CONFIG_SAMPLE_FORMAT
@ AV_CODEC_CONFIG_SAMPLE_FORMAT
AVSampleFormat, terminated by AV_SAMPLE_FMT_NONE.
Definition: avcodec.h:2550
intreadwrite.h
sch_add_mux
int sch_add_mux(Scheduler *sch, SchThreadFunc func, int(*init)(void *), void *arg, int sdp_auto, unsigned thread_queue_size)
Add a muxer to the scheduler.
Definition: ffmpeg_sched.c:670
OptionsContext::intra_matrices
SpecifierOptList intra_matrices
Definition: ffmpeg.h:211
s
#define s(width, name)
Definition: cbs_vp9.c:198
AVCodecContext::stats_in
char * stats_in
pass2 encoding statistics input buffer Concatenated stuff from stats_out of pass1 should be placed he...
Definition: avcodec.h:1338
MuxStream::pkt
AVPacket * pkt
Definition: ffmpeg_mux.h:51
OptionsContext::stream_groups
SpecifierOptList stream_groups
Definition: ffmpeg.h:233
FilterGraph::outputs
OutputFilter ** outputs
Definition: ffmpeg.h:401
enc_stats_get_file
static int enc_stats_get_file(AVIOContext **io, const char *path)
Definition: ffmpeg_mux_init.c:164
of_add_groups
static int of_add_groups(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2652
InputStream::framerate
AVRational framerate
Definition: ffmpeg.h:482
av_realloc_array
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:217
AVFormatContext::flags
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1465
AVCodecParameters::sample_aspect_ratio
AVRational sample_aspect_ratio
The aspect ratio (width/height) which a single pixel should have when displayed.
Definition: codec_par.h:161
output_file_class
static const AVClass output_file_class
Definition: ffmpeg_mux_init.c:3249
AVFormatContext::nb_programs
unsigned int nb_programs
Definition: avformat.h:1511
RcOverride
Definition: avcodec.h:193
AVFormatContext::chapters
AVChapter ** chapters
Definition: avformat.h:1415
ENC_STATS_FILE_IDX
@ ENC_STATS_FILE_IDX
Definition: ffmpeg.h:545
AVDictionaryEntry::key
char * key
Definition: dict.h:91
frame_size
int frame_size
Definition: mxfenc.c:2489
OptionsContext::limit_filesize
int64_t limit_filesize
Definition: ffmpeg.h:180
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:201
AVCodecParameters::width
int width
The width of the video frame in pixels.
Definition: codec_par.h:143
av_iamf_param_definition_get_subblock
static av_always_inline void * av_iamf_param_definition_get_subblock(const AVIAMFParamDefinition *par, unsigned int idx)
Get the subblock at the specified.
Definition: iamf.h:260
VIEW_SPECIFIER_TYPE_NONE
@ VIEW_SPECIFIER_TYPE_NONE
Definition: ffmpeg.h:105
AV_CHANNEL_ORDER_UNSPEC
@ AV_CHANNEL_ORDER_UNSPEC
Only the channel count is specified, without any further information about the channel order.
Definition: channel_layout.h:119
OptionsContext::autoscale
SpecifierOptList autoscale
Definition: ffmpeg.h:236
OutputFilter::linklabel
uint8_t * linklabel
Definition: ffmpeg.h:385
av_strtok
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok().
Definition: avstring.c:179
get_line
static char * get_line(AVIOContext *s, AVBPrint *bprint)
Definition: ffmpeg_mux_init.c:113
filters
#define filters(fmt, type, inverse, clp, inverset, clip, one, clip_fn, packed)
Definition: af_crystalizer.c:55
ENC_STATS_BITRATE
@ ENC_STATS_BITRATE
Definition: ffmpeg.h:560
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:42
AVMEDIA_TYPE_NB
@ AVMEDIA_TYPE_NB
Definition: avutil.h:205
output_stream_item_name
static const char * output_stream_item_name(void *obj)
Definition: ffmpeg_mux_init.c:378
of_add_metadata
static int of_add_metadata(OutputFile *of, AVFormatContext *oc, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2778
AVIO_FLAG_WRITE
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:618
OptionsContext::sample_fmts
SpecifierOptList sample_fmts
Definition: ffmpeg.h:199
AVStreamGroup::index
unsigned int index
Group index in AVFormatContext.
Definition: avformat.h:1151
AVPacketSideData::data
uint8_t * data
Definition: packet.h:425
ignore_unknown_streams
int ignore_unknown_streams
Definition: ffmpeg_opt.c:86
ctx
static AVFormatContext * ctx
Definition: movenc.c:49
RcOverride::start_frame
int start_frame
Definition: avcodec.h:194
channels
channels
Definition: aptx.h:31
OFILTER_FLAG_AUTOSCALE
@ OFILTER_FLAG_AUTOSCALE
Definition: ffmpeg.h:287
av_rescale_q
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
KF_FORCE_SOURCE
@ KF_FORCE_SOURCE
Definition: ffmpeg.h:583
encoder_thread
int encoder_thread(void *arg)
Definition: ffmpeg_enc.c:847
OptionsContext::shortest
int shortest
Definition: ffmpeg.h:184
AVOutputFormat::codec_tag
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "better choice first".
Definition: avformat.h:533
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:410
AVCodecParameters::nb_coded_side_data
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition: codec_par.h:88
AVMEDIA_TYPE_DATA
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition: avutil.h:202
av_mallocz
#define av_mallocz(s)
Definition: tableprint_vlc.h:31
InputStreamGroup::stg
AVStreamGroup * stg
Definition: ffmpeg.h:501
NAN
#define NAN
Definition: mathematics.h:115
MuxStream::max_frames
int64_t max_frames
Definition: ffmpeg_mux.h:61
tmp
static uint8_t tmp[40]
Definition: aes_ctr.c:52
AVFMT_NEEDNUMBER
#define AVFMT_NEEDNUMBER
Needs 'd' in filename.
Definition: avformat.h:470
AVCodecContext::codec_id
enum AVCodecID codec_id
Definition: avcodec.h:453
Muxer::limit_filesize
int64_t limit_filesize
Definition: ffmpeg_mux.h:113
arg
const char * arg
Definition: jacosubdec.c:65
AVCodecDescriptor::props
int props
Codec properties, a combination of AV_CODEC_PROP_* flags.
Definition: codec_desc.h:54
if
if(ret)
Definition: filter_design.txt:179
pixfmt_in_list
static int pixfmt_in_list(const enum AVPixelFormat *formats, enum AVPixelFormat format)
Definition: ffmpeg_mux_init.c:459
sq_add_stream
int sq_add_stream(SyncQueue *sq, int limiting)
Add a new stream to the sync queue.
Definition: sync_queue.c:598
OptionsContext::start_time
int64_t start_time
Definition: ffmpeg.h:136
AVDISCARD_ALL
@ AVDISCARD_ALL
discard all
Definition: defs.h:232
AVFormatContext
Format I/O context.
Definition: avformat.h:1314
av_realloc_f
#define av_realloc_f(p, o, n)
Definition: tableprint_vlc.h:33
MuxStream::max_frame_rate
AVRational max_frame_rate
Definition: ffmpeg_mux.h:86
fail
#define fail
Definition: test.h:478
ENC_STATS_KEYFRAME
@ ENC_STATS_KEYFRAME
Definition: ffmpeg.h:562
OptionGroup::format_opts
AVDictionary * format_opts
Definition: cmdutils.h:348
opts
static AVDictionary * opts
Definition: movenc.c:51
new_stream_subtitle
static int new_stream_subtitle(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:820
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:770
AVCodecParameters::avcodec_parameters_to_context
int avcodec_parameters_to_context(AVCodecContext *codec, const struct AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:76
OutputFilter::name
uint8_t * name
Definition: ffmpeg.h:375
parse_meta_type
static int parse_meta_type(void *logctx, const char *arg, char *type, int *index, const char **stream_spec)
Parse a metadata specifier passed as 'arg' parameter.
Definition: ffmpeg_mux_init.c:2748
AVStream::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:786
NULL
#define NULL
Definition: coverity.c:32
av_program_add_stream_index
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
Definition: avformat.c:338
MuxStream::frame_rate
AVRational frame_rate
Definition: ffmpeg_mux.h:85
format
New swscale design to change SwsGraph is what coordinates multiple passes These can include cascaded scaling error diffusion and so on Or we could have separate passes for the vertical and horizontal scaling In between each SwsPass lies a fully allocated image buffer Graph passes may have different levels of e g we can have a single threaded error diffusion pass following a multi threaded scaling pass SwsGraph is internally recreated whenever the image format
Definition: swscale-v2.txt:14
AVCodecContext::color_range
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:681
InputStream::st
AVStream * st
Definition: ffmpeg.h:469
AV_DICT_MULTIKEY
#define AV_DICT_MULTIKEY
Allow to store several equal keys in the dictionary.
Definition: dict.h:84
AV_CODEC_CONFIG_FRAME_RATE
@ AV_CODEC_CONFIG_FRAME_RATE
AVRational, terminated by {0, 0}.
Definition: avcodec.h:2548
MuxStream::sch_idx_src
int sch_idx_src
Definition: ffmpeg_mux.h:57
OptionsContext::audio_channels
SpecifierOptList audio_channels
Definition: ffmpeg.h:143
map_auto_video
static int map_auto_video(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1539
nb_enc_stats_files
static int nb_enc_stats_files
Definition: ffmpeg_mux_init.c:162
sch_add_enc
int sch_add_enc(Scheduler *sch, SchThreadFunc func, void *ctx, int(*open_cb)(void *opaque, const AVFrame *frame))
Definition: ffmpeg_sched.c:837
ENC_STATS_PTS_TIME
@ ENC_STATS_PTS_TIME
Definition: ffmpeg.h:552
OptionsContext::fix_sub_duration_heartbeat
SpecifierOptList fix_sub_duration_heartbeat
Definition: ffmpeg.h:222
avcodec_free_context
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition: options.c:164
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
OFILTER_FLAG_AUDIO_24BIT
@ OFILTER_FLAG_AUDIO_24BIT
Definition: ffmpeg.h:286
EncStats::lock
pthread_mutex_t lock
Definition: ffmpeg.h:578
OptionsContext::copy_prior_start
SpecifierOptList copy_prior_start
Definition: ffmpeg.h:217
AVPacketSideData::type
enum AVPacketSideDataType type
Definition: packet.h:427
filter_codec_opts
int filter_codec_opts(const AVDictionary *opts, enum AVCodecID codec_id, AVFormatContext *s, AVStream *st, const AVCodec *codec, AVDictionary **dst, AVDictionary **opts_used)
Filter out options for given codec.
Definition: cmdutils.c:1423
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:242
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1356
AV_CODEC_PROP_BITMAP_SUB
#define AV_CODEC_PROP_BITMAP_SUB
Subtitle codec is bitmap based Decoded AVSubtitle data can be read from the AVSubtitleRect->pict fiel...
Definition: codec_desc.h:111
parseutils.h
AVIAMFLayer
A layer defining a Channel Layout in the Audio Element.
Definition: iamf.h:294
EncStats
Definition: ffmpeg.h:572
OptionsContext::program
SpecifierOptList program
Definition: ffmpeg.h:232
EncStatsFile::io
AVIOContext * io
Definition: ffmpeg_mux_init.c:158
getenv_utf8
static char * getenv_utf8(const char *varname)
Definition: getenv_utf8.h:67
copy_unknown_streams
int copy_unknown_streams
Definition: ffmpeg_opt.c:87
AVStream::metadata
AVDictionary * metadata
Definition: avformat.h:827
OptionsContext::frame_aspect_ratios
SpecifierOptList frame_aspect_ratios
Definition: ffmpeg.h:204
MuxStream::bsf_ctx
AVBSFContext * bsf_ctx
Definition: ffmpeg_mux.h:48
MuxStream::par_in
AVCodecParameters * par_in
Codec parameters for packets submitted to the muxer (i.e.
Definition: ffmpeg_mux.h:43
AV_CODEC_CAP_VARIABLE_FRAME_SIZE
#define AV_CODEC_CAP_VARIABLE_FRAME_SIZE
Audio encoder supports receiving a different number of samples in each call.
Definition: codec.h:110
av_parse_time
int av_parse_time(int64_t *timeval, const char *timestr, int duration)
Parse timestr and return in *time a corresponding number of microseconds.
Definition: parseutils.c:592
of_stream_init
int of_stream_init(OutputFile *of, OutputStream *ost, const AVCodecContext *enc_ctx)
Definition: ffmpeg_mux.c:606
AV_DICT_DONT_OVERWRITE
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition: dict.h:81
av_parse_ratio
int av_parse_ratio(AVRational *q, const char *str, int max, int log_offset, void *log_ctx)
Parse str and store the parsed ratio in q.
Definition: parseutils.c:45
OptionsContext::max_frames
SpecifierOptList max_frames
Definition: ffmpeg.h:196
Muxer::log_name
char log_name[32]
Definition: ffmpeg_mux.h:96
av_opt_get_int
int av_opt_get_int(void *obj, const char *name, int search_flags, int64_t *out_val)
Definition: opt.c:1262
AVCodecParameters::ch_layout
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition: codec_par.h:207
OutputFile::index
int index
Definition: ffmpeg.h:676
OutputFile::class
const AVClass * class
Definition: ffmpeg.h:674
ENC_STATS_PTS_TIME_IN
@ ENC_STATS_PTS_TIME_IN
Definition: ffmpeg.h:554
FilterGraph::nb_outputs
int nb_outputs
Definition: ffmpeg.h:402
copy_metadata
static int copy_metadata(Muxer *mux, AVFormatContext *ic, const char *outspec, const char *inspec, int *metadata_global_manual, int *metadata_streams_manual, int *metadata_chapters_manual)
Definition: ffmpeg_mux_init.c:2878
AV_OPT_FLAG_ENCODING_PARAM
#define AV_OPT_FLAG_ENCODING_PARAM
A generic parameter which can be set by the user for muxing or encoding.
Definition: opt.h:351
index
int index
Definition: gxfenc.c:90
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
find_codec
int find_codec(void *logctx, const char *name, enum AVMediaType type, int encoder, const AVCodec **codec)
Definition: ffmpeg_opt.c:783
InputStream::par
AVCodecParameters * par
Codec parameters - to be used by the decoding/streamcopy code.
Definition: ffmpeg.h:477
input_files
InputFile ** input_files
Definition: ffmpeg.c:108
OutputFile::streams
OutputStream ** streams
Definition: ffmpeg.h:680
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:47
Scheduler
Definition: ffmpeg_sched.c:278
AVIAMFSubmixElement::audio_element_id
unsigned int audio_element_id
The id of the Audio Element this submix element references.
Definition: iamf.h:455
avformat_stream_group_add_stream
int avformat_stream_group_add_stream(AVStreamGroup *stg, AVStream *st)
Add an already allocated stream to a stream group.
Definition: options.c:557
FilterGraph
Definition: ffmpeg.h:395
AVCodecParameters::extradata_size
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:75
AVIAMFSubmix
Submix layout as defined in section 3.7 of IAMF.
Definition: iamf.h:559
AVFormatContext::nb_streams
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1370
ENC_TIME_BASE_DEMUX
@ ENC_TIME_BASE_DEMUX
Definition: ffmpeg.h:65
of_add_programs
static int of_add_programs(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2679
AVOutputFormat::flags
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_EXPERIMENTAL, AVFMT_GLOBALHEADER,...
Definition: avformat.h:527
AV_STREAM_GROUP_PARAMS_TILE_GRID
@ AV_STREAM_GROUP_PARAMS_TILE_GRID
Definition: avformat.h:1131
avcodec_get_supported_config
int avcodec_get_supported_config(const AVCodecContext *avctx, const AVCodec *codec, enum AVCodecConfig config, unsigned flags, const void **out, int *out_num)
Retrieve a list of all supported values for a given configuration type.
Definition: avcodec.c:818
AV_CODEC_CONFIG_CHANNEL_LAYOUT
@ AV_CODEC_CONFIG_CHANNEL_LAYOUT
AVChannelLayout, terminated by {0}.
Definition: avcodec.h:2551
VideoSyncMethod
VideoSyncMethod
Definition: ffmpeg.h:56
av_get_exact_bits_per_sample
int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:446
av_opt_find
const AVOption * av_opt_find(void *obj, const char *name, const char *unit, int opt_flags, int search_flags)
Look for an option in an object.
Definition: opt.c:1984
OptionsContext::apad
SpecifierOptList apad
Definition: ffmpeg.h:229
OptionsContext::enc_stats_post_fmt
SpecifierOptList enc_stats_post_fmt
Definition: ffmpeg.h:242
OutputStream::filter
OutputFilter * filter
Definition: ffmpeg.h:652
f
f
Definition: af_crystalizer.c:122
AVIOContext
Bytestream IO Context.
Definition: avio.h:160
AVCodecContext::rc_override
RcOverride * rc_override
Definition: avcodec.h:1281
OptionsContext::thread_queue_size
int thread_queue_size
Definition: ffmpeg.h:158
AVMediaType
AVMediaType
Definition: avutil.h:198
Muxer::sq_mux
SyncQueue * sq_mux
Definition: ffmpeg_mux.h:117
AV_STREAM_GROUP_PARAMS_TREF
@ AV_STREAM_GROUP_PARAMS_TREF
Definition: avformat.h:1133
InputStreamGroup::fg
FilterGraph * fg
Definition: ffmpeg.h:500
av_bprint_finalize
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:235
MuxStream::apad
const char * apad
Definition: ffmpeg_mux.h:89
OptionsContext::enc_stats_pre
SpecifierOptList enc_stats_pre
Definition: ffmpeg.h:238
dst
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition: dsp.h:87
output_files
OutputFile ** output_files
Definition: ffmpeg.c:111
i
#define i(width, name, range_min, range_max)
Definition: cbs_h264.c:63
av_err2str
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:122
start_time
static int64_t start_time
Definition: ffplay.c:328
AVFormatContext::url
char * url
input or output URL.
Definition: avformat.h:1430
EncStatsType
EncStatsType
Definition: ffmpeg.h:543
Muxer::sch
Scheduler * sch
Definition: ffmpeg_mux.h:100
AVCodecContext::sample_fmt
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1047
AV_SAMPLE_FMT_NONE
@ AV_SAMPLE_FMT_NONE
Definition: samplefmt.h:56
StreamMap
Definition: ffmpeg.h:122
ENC_STATS_NB_SAMPLES
@ ENC_STATS_NB_SAMPLES
Definition: ffmpeg.h:558
size
int size
Definition: twinvq_data.h:10344
copy_ts
int copy_ts
Definition: ffmpeg_opt.c:64
AV_CODEC_CONFIG_ALPHA_MODE
@ AV_CODEC_CONFIG_ALPHA_MODE
AVAlphaMode, terminated by AVALPHA_MODE_UNSPECIFIED.
Definition: avcodec.h:2554
avio.h
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:247
AVStreamGroup::iamf_audio_element
struct AVIAMFAudioElement * iamf_audio_element
Definition: avformat.h:1173
AVStream::event_flags
int event_flags
Flags indicating events happening on the stream, a combination of AVSTREAM_EVENT_FLAG_*.
Definition: avformat.h:858
OptionsContext::streamid
AVDictionary * streamid
Definition: ffmpeg.h:193
enc_alloc
int enc_alloc(Encoder **penc, const AVCodec *codec, Scheduler *sch, unsigned sch_idx, void *log_parent)
Definition: ffmpeg_enc.c:99
OptionsContext::pass
SpecifierOptList pass
Definition: ffmpeg.h:224
OutputStream::type
enum AVMediaType type
Definition: ffmpeg.h:624
OutputFile::url
const char * url
Definition: ffmpeg.h:678
setup_sync_queues
static int setup_sync_queues(Muxer *mux, AVFormatContext *oc, int64_t buf_size_us, int shortest)
Definition: ffmpeg_mux_init.c:2045
AVFMT_NOFILE
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:469
AVCodecContext::chroma_intra_matrix
uint16_t * chroma_intra_matrix
custom intra quantization matrix
Definition: avcodec.h:976
AVMEDIA_TYPE_UNKNOWN
@ AVMEDIA_TYPE_UNKNOWN
Usually treated as AVMEDIA_TYPE_DATA.
Definition: avutil.h:199
Muxer::opts
AVDictionary * opts
Definition: ffmpeg_mux.h:107
AVStream::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:825
OptionsContext::disposition
SpecifierOptList disposition
Definition: ffmpeg.h:231
AVFMT_NOSTREAMS
#define AVFMT_NOSTREAMS
Format does not require any streams.
Definition: avformat.h:484
allocate_array_elem
void * allocate_array_elem(void *ptr, size_t elem_size, int *nb_elems)
Atomically add a new element to an array of pointers, i.e.
Definition: cmdutils.c:1540
of_enc_stats_close
void of_enc_stats_close(void)
Definition: ffmpeg_mux_init.c:197
MuxStream
Definition: ffmpeg_mux.h:36
AV_CODEC_FLAG_PASS2
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition: avcodec.h:294
avio_r8
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:606
getenv_utf8.h
a
The reader does not expect b to be semantically here and if the code is changed by maybe adding a a division or other the signedness will almost certainly be mistaken To avoid this confusion a new type was SUINT is the C unsigned type but it holds a signed int to use the same example SUINT a
Definition: undefined.txt:41
av_iamf_submix_add_element
AVIAMFSubmixElement * av_iamf_submix_add_element(AVIAMFSubmix *submix)
Allocate a submix element and add it to a given AVIAMFSubmix.
AVIAMFAudioElement
Information on how to combine one or more audio streams, as defined in section 3.6 of IAMF.
Definition: iamf.h:359
SpecifierOptList::opt
SpecifierOpt * opt
Definition: cmdutils.h:184
opt_match_per_stream_dbl
void opt_match_per_stream_dbl(void *logctx, const SpecifierOptList *sol, AVFormatContext *fc, AVStream *st, double *out)
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: packet.c:63
av_dict_free
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition: dict.c:233
AVStreamGroup::params
union AVStreamGroup::@454 params
Group type-specific parameters.
av_strstart
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:36
AVCodecParameters::avcodec_parameters_alloc
AVCodecParameters * avcodec_parameters_alloc(void)
Allocate a new AVCodecParameters and set its fields to default values (unknown/invalid/0).
Definition: codec_par.c:57
AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT
@ AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT
Definition: avformat.h:1129
AVStreamGroup::streams
AVStream ** streams
A list of streams in the group.
Definition: avformat.h:1215
av_parse_video_size
int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str)
Parse str and put in width_ptr and height_ptr the detected values.
Definition: parseutils.c:150
Muxer::sch_idx
unsigned sch_idx
Definition: ffmpeg_mux.h:101
ENC_STATS_FRAME_NUM
@ ENC_STATS_FRAME_NUM
Definition: ffmpeg.h:547
KeyframeForceCtx
Definition: ffmpeg.h:588
OutputFilter::type
enum AVMediaType type
Definition: ffmpeg.h:389
AVStreamGroup::iamf_mix_presentation
struct AVIAMFMixPresentation * iamf_mix_presentation
Definition: avformat.h:1174
OptionsContext::chroma_intra_matrices
SpecifierOptList chroma_intra_matrices
Definition: ffmpeg.h:213
fg_create_simple
int fg_create_simple(FilterGraph **pfg, InputStream *ist, char **graph_desc, Scheduler *sch, unsigned sched_idx_enc, const OutputFilterOptions *opts)
Definition: ffmpeg_filter.c:1238
mux_check_init
int mux_check_init(void *arg)
Definition: ffmpeg_mux.c:550
AVCodec::id
enum AVCodecID id
Definition: codec.h:183
layout
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel layout
Definition: filter_design.txt:18
avcodec_get_name
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:406
av_parse_video_rate
int av_parse_video_rate(AVRational *rate, const char *arg)
Parse str and store the detected values in *rate.
Definition: parseutils.c:181
of_open
int of_open(const OptionsContext *o, const char *filename, Scheduler *sch)
Definition: ffmpeg_mux_init.c:3271
av_channel_layout_from_string
int av_channel_layout_from_string(AVChannelLayout *channel_layout, const char *str)
Initialize a channel layout from a given string description.
Definition: channel_layout.c:313
bprint.h
AVStreamGroupTileGrid::width
int width
Width of the final image for presentation.
Definition: avformat.h:1039
map_auto_data
static int map_auto_data(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1730
AV_STREAM_GROUP_PARAMS_NONE
@ AV_STREAM_GROUP_PARAMS_NONE
Definition: avformat.h:1128
log.h
AVFMT_GLOBALHEADER
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:478
av_malloc
#define av_malloc(s)
Definition: ops_asmgen.c:44
AV_CODEC_ID_NONE
@ AV_CODEC_ID_NONE
Definition: codec_id.h:48
RcOverride::end_frame
int end_frame
Definition: avcodec.h:195
OptionsContext::frame_rates
SpecifierOptList frame_rates
Definition: ffmpeg.h:145
AVChapter::id
int64_t id
unique ID to identify the chapter
Definition: avformat.h:1274
OptionsContext::codec_names
SpecifierOptList codec_names
Definition: ffmpeg.h:141
MuxStream::stats
EncStats stats
Definition: ffmpeg_mux.h:53
OptionsContext::stream_maps
StreamMap * stream_maps
Definition: ffmpeg.h:171
av_opt_set_dict2
int av_opt_set_dict2(void *obj, AVDictionary **options, int search_flags)
Set all the options from a given dictionary on an object.
Definition: opt.c:1955
pix_fmt_parse
static enum AVPixelFormat pix_fmt_parse(OutputStream *ost, const char *name)
Definition: ffmpeg_mux_init.c:499
AVCodecParameters::height
int height
The height of the video frame in pixels.
Definition: codec_par.h:150
av_get_sample_fmt
enum AVSampleFormat av_get_sample_fmt(const char *name)
Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE on error.
Definition: samplefmt.c:58
AV_TIME_BASE
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:253
OptionsContext::fps_mode
SpecifierOptList fps_mode
Definition: ffmpeg.h:202
AVCodecParameters::block_align
int block_align
The number of bytes per coded audio frame, required by some formats.
Definition: codec_par.h:221
VSYNC_CFR
@ VSYNC_CFR
Definition: ffmpeg.h:59
OptionsContext::shortest_buf_duration
float shortest_buf_duration
Definition: ffmpeg.h:183
av_malloc_array
#define av_malloc_array(a, b)
Definition: tableprint_vlc.h:32
AVProgram::metadata
AVDictionary * metadata
Definition: avformat.h:1244
OutputFile::bitexact
int bitexact
Definition: ffmpeg.h:686
display.h
AVIAMFMixPresentation
Information on how to render and mix one or more AVIAMFAudioElement to generate the final audio outpu...
Definition: iamf.h:616
OptionsContext::mux_stats
SpecifierOptList mux_stats
Definition: ffmpeg.h:240
av_assert1
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:58
OptionsContext::muxing_queue_data_threshold
SpecifierOptList muxing_queue_data_threshold
Definition: ffmpeg.h:227
AVMEDIA_TYPE_ATTACHMENT
@ AVMEDIA_TYPE_ATTACHMENT
Opaque data information usually sparse.
Definition: avutil.h:204
InputFile::ctx
AVFormatContext * ctx
Definition: ffmpeg.h:509
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AVFormatContext::max_delay
int max_delay
Definition: avformat.h:1459
AVProgram
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1238
OptionsContext::enc_stats_post
SpecifierOptList enc_stats_post
Definition: ffmpeg.h:239
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:176
av_inv_q
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
len
int len
Definition: vorbis_enc_data.h:426
SchedulerNode
Definition: ffmpeg_sched.h:103
ENC_STATS_STREAM_IDX
@ ENC_STATS_STREAM_IDX
Definition: ffmpeg.h:546
filtergraphs
FilterGraph ** filtergraphs
Definition: ffmpeg.c:114
int_cb
const AVIOInterruptCB int_cb
Definition: ffmpeg.c:312
InputFile::stream_groups
InputStreamGroup ** stream_groups
Definition: ffmpeg.h:527
AVCodecContext::height
int height
Definition: avcodec.h:604
AVCodecParameters::coded_side_data
AVPacketSideData * coded_side_data
Additional data associated with the entire stream.
Definition: codec_par.h:83
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:643
ENC_STATS_SAMPLE_NUM
@ ENC_STATS_SAMPLE_NUM
Definition: ffmpeg.h:557
av_calloc
void * av_calloc(size_t nmemb, size_t size)
Definition: mem.c:264
nb_output_files
int nb_output_files
Definition: ffmpeg.c:112
AVIAMFParamDefinition::nb_subblocks
unsigned int nb_subblocks
Number of subblocks in the array.
Definition: iamf.h:208
sch_connect
int sch_connect(Scheduler *sch, SchedulerNode src, SchedulerNode dst)
Definition: ffmpeg_sched.c:973
avcodec.h
OptionGroup::sws_dict
AVDictionary * sws_dict
Definition: cmdutils.h:349
av_opt_eval_flags
int av_opt_eval_flags(void *obj, const AVOption *o, const char *val, int *flags_out)
AVStream::disposition
int disposition
Stream disposition - a combination of AV_DISPOSITION_* flags.
Definition: avformat.h:816
tag
uint32_t tag
Definition: movenc.c:2054
OptionsContext::metadata_map
SpecifierOptList metadata_map
Definition: ffmpeg.h:214
AVStream::id
int id
Format-specific stream ID.
Definition: avformat.h:759
AVFMT_FLAG_BITEXACT
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1482
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:747
AV_LOG_FATAL
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:204
AVClass::class_name
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:81
AVFormatContext::oformat
const struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1333
av_strlcat
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition: avstring.c:95
output_file_item_name
static const char * output_file_item_name(void *obj)
Definition: ffmpeg_mux_init.c:3242
av_opt_eval_int
int av_opt_eval_int(void *obj, const AVOption *o, const char *val, int *int_out)
AV_CODEC_PROP_ENHANCEMENT
#define AV_CODEC_PROP_ENHANCEMENT
Video codec contains enhancement information meant to be applied to other existing frames,...
Definition: codec_desc.h:105
AV_CODEC_PROP_TEXT_SUB
#define AV_CODEC_PROP_TEXT_SUB
Subtitle codec is text based.
Definition: codec_desc.h:116
InputFile::streams
InputStream ** streams
Definition: ffmpeg.h:523
avformat.h
av_bprintf
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:122
ost_bind_filter
static int ost_bind_filter(const Muxer *mux, MuxStream *ms, OutputFilter *ofilter, const OptionsContext *o, AVRational enc_tb, enum VideoSyncMethod vsync_method, int keep_pix_fmt, int autoscale, int threads_manual, const ViewSpecifier *vs, SchedulerNode *src)
Definition: ffmpeg_mux_init.c:862
dict.h
av_packet_side_data_new
AVPacketSideData * av_packet_side_data_new(AVPacketSideData **psd, int *pnb_sd, enum AVPacketSideDataType type, size_t size, int flags)
Allocate a new packet side data.
Definition: packet.c:620
check_avoptions_used
int check_avoptions_used(const AVDictionary *opts, const AVDictionary *opts_used, void *logctx, int decode)
Definition: ffmpeg.c:501
set_encoder_id
static int set_encoder_id(OutputStream *ost, const AVCodec *codec)
Definition: ffmpeg_mux_init.c:1112
AV_INPUT_BUFFER_PADDING_SIZE
#define AV_INPUT_BUFFER_PADDING_SIZE
Definition: defs.h:40
id
enum AVCodecID id
Definition: dts2pts.c:578
av_guess_codec
enum AVCodecID av_guess_codec(const AVOutputFormat *fmt, const char *short_name, const char *filename, const char *mime_type, enum AVMediaType type)
Guess the codec ID based upon muxer and filename.
Definition: format.c:117
SCH_MSTREAM
#define SCH_MSTREAM(file, stream)
Definition: ffmpeg_sched.h:114
AV_RL32
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:92
av_get_pix_fmt
enum AVPixelFormat av_get_pix_fmt(const char *name)
Return the pixel format corresponding to name.
Definition: pixdesc.c:3388
OptionsContext::max_muxing_queue_size
SpecifierOptList max_muxing_queue_size
Definition: ffmpeg.h:226
AVStreamGroup
Definition: avformat.h:1140
of_add_attachments
static int of_add_attachments(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1838
av_get_media_type_string
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:28
AVCodecContext
main external API structure.
Definition: avcodec.h:443
OptionsContext::inter_matrices
SpecifierOptList inter_matrices
Definition: ffmpeg.h:212
AVStream::index
int index
stream index in AVFormatContext
Definition: avformat.h:753
AV_CLASS_CATEGORY_MUXER
@ AV_CLASS_CATEGORY_MUXER
Definition: log.h:32
av_find_best_pix_fmt_of_2
enum AVPixelFormat av_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr)
Compute what kind of losses will occur when converting from one specific pixel format to another.
Definition: pixdesc.c:3735
AVStreamGroup::nb_streams
unsigned int nb_streams
Number of elements in AVStreamGroup.streams.
Definition: avformat.h:1202
OptionsContext::audio_sample_rate
SpecifierOptList audio_sample_rate
Definition: ffmpeg.h:144
OptionsContext::mux_preload
float mux_preload
Definition: ffmpeg.h:181
AVRational::den
int den
Denominator.
Definition: rational.h:60
InputStream::file
struct InputFile * file
Definition: ffmpeg.h:465
SpecifierOpt::str
uint8_t * str
Definition: cmdutils.h:174
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:72
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition: opt.h:258
avfilter.h
av_bprint_clear
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition: bprint.c:227
av_dict_parse_string
int av_dict_parse_string(AVDictionary **pm, const char *str, const char *key_val_sep, const char *pairs_sep, int flags)
Parse the key/value pairs list and add the parsed entries to a dictionary.
Definition: dict.c:210
avio_read
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:615
OptionsContext::frame_sizes
SpecifierOptList frame_sizes
Definition: ffmpeg.h:147
OptionsContext::video_disable
int video_disable
Definition: ffmpeg.h:187
AVOutputFormat::video_codec
enum AVCodecID video_codec
default video codec
Definition: avformat.h:519
AVStream::r_frame_rate
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:881
AV_IAMF_PARAMETER_DEFINITION_MIX_GAIN
@ AV_IAMF_PARAMETER_DEFINITION_MIX_GAIN
Subblocks are of struct type AVIAMFMixGain.
Definition: iamf.h:173
EncStats::lock_initialized
int lock_initialized
Definition: ffmpeg.h:579
Windows::Graphics::DirectX::Direct3D11::p
IDirect3DDxgiInterfaceAccess _COM_Outptr_ void ** p
Definition: vsrc_gfxcapture_winrt.hpp:53
AVFormatContext::duration
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1449
av_mul_q
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
GROW_ARRAY
#define GROW_ARRAY(array, nb_elems)
Definition: cmdutils.h:536
InputFile::ts_offset
int64_t ts_offset
Definition: ffmpeg.h:516
av_iamf_audio_element_add_layer
AVIAMFLayer * av_iamf_audio_element_add_layer(AVIAMFAudioElement *audio_element)
Allocate a layer and add it to a given AVIAMFAudioElement.
VSYNC_AUTO
@ VSYNC_AUTO
Definition: ffmpeg.h:57
OutputFilter
Definition: ffmpeg.h:371
map_auto_audio
static int map_auto_audio(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1647
av_dict_set_int
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition: dict.c:177
OptionsContext::codec_tags
SpecifierOptList codec_tags
Definition: ffmpeg.h:198
AVIAMFSubmix::nb_elements
unsigned int nb_elements
Number of elements in the submix.
Definition: iamf.h:575
AVIO_FLAG_READ
#define AVIO_FLAG_READ
read-only
Definition: avio.h:617
desc
const char * desc
Definition: libsvtav1.c:83
OptionsContext::time_bases
SpecifierOptList time_bases
Definition: ffmpeg.h:234
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:200
AVERROR_ENCODER_NOT_FOUND
#define AVERROR_ENCODER_NOT_FOUND
Encoder not found.
Definition: error.h:56
av_bsf_list_parse_str
int av_bsf_list_parse_str(const char *str, AVBSFContext **bsf_lst)
Parse string describing list of bitstream filters and create single AVBSFContext describing the whole...
Definition: bsf.c:526
unescape
static int unescape(char **pdst, size_t *dst_len, const char **pstr, char delim)
Definition: ffmpeg_mux_init.c:207
avutil.h
AVIAMFAudioElement::demixing_info
AVIAMFParamDefinition * demixing_info
Demixing information used to reconstruct a scalable channel audio representation.
Definition: iamf.h:379
sch_sq_add_enc
int sch_sq_add_enc(Scheduler *sch, unsigned sq_idx, unsigned enc_idx, int limiting, uint64_t max_frames)
Definition: ffmpeg_sched.c:942
mem.h
AVIAMFSubmix::output_mix_config
AVIAMFParamDefinition * output_mix_config
Information required for post-processing the mixed audio signal to generate the audio signal for play...
Definition: iamf.h:598
MuxStream::sq_idx_mux
int sq_idx_mux
Definition: ffmpeg_mux.h:59
AVStreamGroup::type
enum AVStreamGroupParamsType type
Group type.
Definition: avformat.h:1167
SpecifierOpt::u
union SpecifierOpt::@0 u
avio_open2
int avio_open2(AVIOContext **s, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: avio.c:497
av_strdup
#define av_strdup(s)
Definition: ops_asmgen.c:47
AV_CODEC_FLAG_BITEXACT
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition: avcodec.h:322
ffmpeg_mux.h
OptionsContext::rc_overrides
SpecifierOptList rc_overrides
Definition: ffmpeg.h:210
AVCodecParameters::avcodec_parameters_from_context
int avcodec_parameters_from_context(struct AVCodecParameters *par, const AVCodecContext *codec)
Fill the parameters struct based on the values from the supplied codec context.
Definition: codec_par.c:138
new_stream_audio
static int new_stream_audio(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:781
AVPixFmtDescriptor
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:69
sch_mux_sub_heartbeat_add
int sch_mux_sub_heartbeat_add(Scheduler *sch, unsigned mux_idx, unsigned stream_idx, unsigned dec_idx)
Definition: ffmpeg_sched.c:1292
map
const VDPAUPixFmtMap * map
Definition: hwcontext_vdpau.c:71
avformat_stream_group_create
AVStreamGroup * avformat_stream_group_create(AVFormatContext *s, enum AVStreamGroupParamsType type, AVDictionary **options)
Add a new empty stream group to a media file.
Definition: options.c:469
InputStream::index
int index
Definition: ffmpeg.h:467
of_map_group
static int of_map_group(Muxer *mux, AVDictionary **dict, AVBPrint *bp, const char *map)
Definition: ffmpeg_mux_init.c:2404
AVFormatContext::nb_stream_groups
unsigned int nb_stream_groups
Number of elements in AVFormatContext.stream_groups.
Definition: avformat.h:1389
AVStreamGroupTileGrid::height
int height
Height of the final image for presentation.
Definition: avformat.h:1049
ffmpeg_sched.h
EncStatsFile::path
char * path
Definition: ffmpeg_mux_init.c:157
compare_int64
static int compare_int64(const void *a, const void *b)
Definition: ffmpeg_mux_init.c:3117
OptionsContext::copy_initial_nonkeyframes
SpecifierOptList copy_initial_nonkeyframes
Definition: ffmpeg.h:216
av_free
#define av_free(p)
Definition: tableprint_vlc.h:34
FKF_N_FORCED
@ FKF_N_FORCED
Definition: ffmpeg.h:533
AVDictionaryEntry
Definition: dict.h:90
OptionsContext::attachments
const char ** attachments
Definition: ffmpeg.h:173
ENC_TIME_BASE_FILTER
@ ENC_TIME_BASE_FILTER
Definition: ffmpeg.h:66
av_add_q
AVRational av_add_q(AVRational b, AVRational c)
Add two rationals.
Definition: rational.c:93
AVCodecParameters::codec_id
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:57
audio_disable
static int audio_disable
Definition: ffplay.c:316
EncStatsComponent
Definition: ffmpeg.h:565
avio_closep
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: avio.c:655
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
av_dict_set
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:86
OFILTER_FLAG_DISABLE_CONVERT
@ OFILTER_FLAG_DISABLE_CONVERT
Definition: ffmpeg.h:284
av_dict_copy
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:247
AVCodecContext::inter_matrix
uint16_t * inter_matrix
custom inter quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition: avcodec.h:969
cmdutils.h
Muxer::enc_opts_used
AVDictionary * enc_opts_used
Definition: ffmpeg_mux.h:110
AVCodecContext::rc_override_count
int rc_override_count
ratecontrol override, see RcOverride
Definition: avcodec.h:1280
InputFile::input_ts_offset
int64_t input_ts_offset
Definition: ffmpeg.h:510
EncStats::nb_components
int nb_components
Definition: ffmpeg.h:574
OptionsContext::data_disable
int data_disable
Definition: ffmpeg.h:190
nb_filtergraphs
int nb_filtergraphs
Definition: ffmpeg.c:115
AVIAMFSubmixElement::element_mix_config
AVIAMFParamDefinition * element_mix_config
Information required required for applying any processing to the referenced and rendered Audio Elemen...
Definition: iamf.h:464
AVCodecContext::width
int width
picture width / height.
Definition: avcodec.h:604
AV_CODEC_FLAG2_FIXED_FRAME_SIZE
#define AV_CODEC_FLAG2_FIXED_FRAME_SIZE
Force audio encoders to use a fixed frame size.
Definition: avcodec.h:359
muxer_thread
int muxer_thread(void *arg)
Definition: ffmpeg_mux.c:402
AVIAMFSubmixElement
Submix element as defined in section 3.7 of IAMF.
Definition: iamf.h:449
ENC_STATS_PKT_SIZE
@ ENC_STATS_PKT_SIZE
Definition: ffmpeg.h:559
OutputStream
Definition: mux.c:53
check_opt_bitexact
static int check_opt_bitexact(void *ctx, const AVDictionary *opts, const char *opt_name, int flag)
Definition: ffmpeg_mux_init.c:53
av_strlcpy
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:85
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
forced_keyframes_const_names
static const char *const forced_keyframes_const_names[]
Definition: ffmpeg_mux_init.c:3108
read_file_to_string
char * read_file_to_string(const char *filename)
Definition: cmdutils.c:1571
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
MKTAG
#define MKTAG(a, b, c, d)
Definition: macros.h:55
process_forced_keyframes
static int process_forced_keyframes(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:3200
av_bprint_chars
void av_bprint_chars(AVBPrint *buf, char c, unsigned n)
Append char c n times to a print buffer.
Definition: bprint.c:130
avcodec_descriptor_get
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:3878
AVIAMFAudioElement::recon_gain_info
AVIAMFParamDefinition * recon_gain_info
Recon gain information used to reconstruct a scalable channel audio representation.
Definition: iamf.h:386
sq_alloc
SyncQueue * sq_alloc(enum SyncQueueType type, int64_t buf_size_us, void *logctx)
Allocate a sync queue of the given type.
Definition: sync_queue.c:654
av_opt_set_dict
int av_opt_set_dict(void *obj, AVDictionary **options)
Set all the options from a given dictionary on an object.
Definition: opt.c:1979
AVDictionaryEntry::value
char * value
Definition: dict.h:92
avstring.h
FF_QP2LAMBDA
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:226
opt_match_per_type_str
const char * opt_match_per_type_str(const SpecifierOptList *sol, char mediatype)
Definition: ffmpeg_opt.c:165
opt_match_per_stream_str
void opt_match_per_stream_str(void *logctx, const SpecifierOptList *sol, AVFormatContext *fc, AVStream *st, const char **out)
sch_mux_stream_buffering
void sch_mux_stream_buffering(Scheduler *sch, unsigned mux_idx, unsigned stream_idx, size_t data_threshold, int max_packets)
Configure limits on packet buffering performed before the muxer task is started.
Definition: ffmpeg_sched.c:1251
InputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:524
FKF_N
@ FKF_N
Definition: ffmpeg.h:532
avformat_alloc_output_context2
int avformat_alloc_output_context2(AVFormatContext **ctx, const AVOutputFormat *oformat, const char *format_name, const char *filename)
Allocate an AVFormatContext for an output format.
Definition: mux.c:95
ENC_STATS_DTS_TIME
@ ENC_STATS_DTS_TIME
Definition: ffmpeg.h:556
AVChapter::time_base
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1275
OutputFile::recording_time
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:683
VSYNC_PASSTHROUGH
@ VSYNC_PASSTHROUGH
Definition: ffmpeg.h:58
AV_OPT_TYPE_CONST
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition: opt.h:298
snprintf
#define snprintf
Definition: snprintf.h:34
EncStats::io
AVIOContext * io
Definition: ffmpeg.h:576
av_dict_iterate
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition: dict.c:42
OptionsContext::bitstream_filters
SpecifierOptList bitstream_filters
Definition: ffmpeg.h:197
src
#define src
Definition: vp8dsp.c:248
copy_chapters
static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os, int copy_metadata)
Definition: ffmpeg_mux_init.c:2836
MuxStream::last_mux_dts
int64_t last_mux_dts
Definition: ffmpeg_mux.h:70
OptionsContext::enc_time_bases
SpecifierOptList enc_time_bases
Definition: ffmpeg.h:235
av_opt_is_set_to_default_by_name
int av_opt_is_set_to_default_by_name(void *obj, const char *name, int search_flags)
Check if given option is set to its default value.
Definition: opt.c:2698
ENC_STATS_TIMEBASE
@ ENC_STATS_TIMEBASE
Definition: ffmpeg.h:549
create_streams
static int create_streams(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1921
MuxStream::stream_duration
int64_t stream_duration
Definition: ffmpeg_mux.h:72
OutputStream::class
const AVClass * class
Definition: ffmpeg.h:622
av_get_pix_fmt_name
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:3376
AV_IAMF_PARAMETER_DEFINITION_DEMIXING
@ AV_IAMF_PARAMETER_DEFINITION_DEMIXING
Subblocks are of struct type AVIAMFDemixingInfo.
Definition: iamf.h:177
OutputFile
Definition: ffmpeg.h:673
AV_CODEC_FLAG_PASS1
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:290
sch_add_sq_enc
int sch_add_sq_enc(Scheduler *sch, uint64_t buf_size_us, void *logctx)
Add an pre-encoding sync queue to the scheduler.
Definition: ffmpeg_sched.c:917
AV_CODEC_CONFIG_COLOR_SPACE
@ AV_CODEC_CONFIG_COLOR_SPACE
AVColorSpace, terminated by AVCOL_SPC_UNSPECIFIED.
Definition: avcodec.h:2553