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  OutputStream *ost, const AVCodec **enc)
71 {
72  enum AVMediaType type = ost->type;
73  char *codec_name = NULL;
74 
75  *enc = NULL;
76 
77  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
78 
79  if (type != AVMEDIA_TYPE_VIDEO &&
82  if (codec_name && strcmp(codec_name, "copy")) {
83  const char *type_str = av_get_media_type_string(type);
85  "Encoder '%s' specified, but only '-codec copy' supported "
86  "for %s streams\n", codec_name, type_str);
87  return AVERROR(ENOSYS);
88  }
89  return 0;
90  }
91 
92  if (!codec_name) {
93  ost->par_in->codec_id = av_guess_codec(s->oformat, NULL, s->url, NULL, ost->type);
94  *enc = avcodec_find_encoder(ost->par_in->codec_id);
95  if (!*enc) {
96  av_log(ost, AV_LOG_FATAL, "Automatic encoder selection failed "
97  "Default encoder for format %s (codec %s) is "
98  "probably disabled. Please choose an encoder manually.\n",
99  s->oformat->name, avcodec_get_name(ost->par_in->codec_id));
101  }
102  } else if (strcmp(codec_name, "copy")) {
103  int ret = find_codec(ost, codec_name, ost->type, 1, enc);
104  if (ret < 0)
105  return ret;
106  ost->par_in->codec_id = (*enc)->id;
107  }
108 
109  return 0;
110 }
111 
112 static char *get_line(AVIOContext *s, AVBPrint *bprint)
113 {
114  char c;
115 
116  while ((c = avio_r8(s)) && c != '\n')
117  av_bprint_chars(bprint, c, 1);
118 
119  if (!av_bprint_is_complete(bprint))
120  return NULL;
121 
122  return bprint->str;
123 }
124 
125 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
126 {
127  int i, ret = -1;
128  char filename[1000];
129  char *env_avconv_datadir = getenv_utf8("AVCONV_DATADIR");
130  char *env_home = getenv_utf8("HOME");
131  const char *base[3] = { env_avconv_datadir,
132  env_home,
133  AVCONV_DATADIR,
134  };
135 
136  for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
137  if (!base[i])
138  continue;
139  if (codec_name) {
140  snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
141  i != 1 ? "" : "/.avconv", codec_name, preset_name);
142  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
143  }
144  if (ret < 0) {
145  snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
146  i != 1 ? "" : "/.avconv", preset_name);
147  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
148  }
149  }
150  freeenv_utf8(env_home);
151  freeenv_utf8(env_avconv_datadir);
152  return ret;
153 }
154 
155 typedef struct EncStatsFile {
156  char *path;
158 } EncStatsFile;
159 
162 
163 static int enc_stats_get_file(AVIOContext **io, const char *path)
164 {
165  EncStatsFile *esf;
166  int ret;
167 
168  for (int i = 0; i < nb_enc_stats_files; i++)
169  if (!strcmp(path, enc_stats_files[i].path)) {
170  *io = enc_stats_files[i].io;
171  return 0;
172  }
173 
175  if (ret < 0)
176  return ret;
177 
179 
180  ret = avio_open2(&esf->io, path, AVIO_FLAG_WRITE, &int_cb, NULL);
181  if (ret < 0) {
182  av_log(NULL, AV_LOG_ERROR, "Error opening stats file '%s': %s\n",
183  path, av_err2str(ret));
184  return ret;
185  }
186 
187  esf->path = av_strdup(path);
188  if (!esf->path)
189  return AVERROR(ENOMEM);
190 
191  *io = esf->io;
192 
193  return 0;
194 }
195 
197 {
198  for (int i = 0; i < nb_enc_stats_files; i++) {
199  av_freep(&enc_stats_files[i].path);
201  }
203  nb_enc_stats_files = 0;
204 }
205 
206 static int unescape(char **pdst, size_t *dst_len,
207  const char **pstr, char delim)
208 {
209  const char *str = *pstr;
210  char *dst;
211  size_t len, idx;
212 
213  *pdst = NULL;
214 
215  len = strlen(str);
216  if (!len)
217  return 0;
218 
219  dst = av_malloc(len + 1);
220  if (!dst)
221  return AVERROR(ENOMEM);
222 
223  for (idx = 0; *str; idx++, str++) {
224  if (str[0] == '\\' && str[1])
225  str++;
226  else if (*str == delim)
227  break;
228 
229  dst[idx] = *str;
230  }
231  if (!idx) {
232  av_freep(&dst);
233  return 0;
234  }
235 
236  dst[idx] = 0;
237 
238  *pdst = dst;
239  *dst_len = idx;
240  *pstr = str;
241 
242  return 0;
243 }
244 
245 static int enc_stats_init(OutputStream *ost, EncStats *es, int pre,
246  const char *path, const char *fmt_spec)
247 {
248  static const struct {
249  enum EncStatsType type;
250  const char *str;
251  unsigned pre_only:1;
252  unsigned post_only:1;
253  unsigned need_input_data:1;
254  } fmt_specs[] = {
255  { ENC_STATS_FILE_IDX, "fidx" },
256  { ENC_STATS_STREAM_IDX, "sidx" },
257  { ENC_STATS_FRAME_NUM, "n" },
258  { ENC_STATS_FRAME_NUM_IN, "ni", 0, 0, 1 },
259  { ENC_STATS_TIMEBASE, "tb" },
260  { ENC_STATS_TIMEBASE_IN, "tbi", 0, 0, 1 },
261  { ENC_STATS_PTS, "pts" },
262  { ENC_STATS_PTS_TIME, "t" },
263  { ENC_STATS_PTS_IN, "ptsi", 0, 0, 1 },
264  { ENC_STATS_PTS_TIME_IN, "ti", 0, 0, 1 },
265  { ENC_STATS_DTS, "dts", 0, 1 },
266  { ENC_STATS_DTS_TIME, "dt", 0, 1 },
267  { ENC_STATS_SAMPLE_NUM, "sn", 1 },
268  { ENC_STATS_NB_SAMPLES, "samp", 1 },
269  { ENC_STATS_PKT_SIZE, "size", 0, 1 },
270  { ENC_STATS_BITRATE, "br", 0, 1 },
271  { ENC_STATS_AVG_BITRATE, "abr", 0, 1 },
272  { ENC_STATS_KEYFRAME, "key", 0, 1 },
273  };
274  const char *next = fmt_spec;
275 
276  int ret;
277 
278  while (*next) {
280  char *val;
281  size_t val_len;
282 
283  // get the sequence up until next opening brace
284  ret = unescape(&val, &val_len, &next, '{');
285  if (ret < 0)
286  return ret;
287 
288  if (val) {
290  if (ret < 0) {
291  av_freep(&val);
292  return ret;
293  }
294 
295  c = &es->components[es->nb_components - 1];
296  c->type = ENC_STATS_LITERAL;
297  c->str = val;
298  c->str_len = val_len;
299  }
300 
301  if (!*next)
302  break;
303  next++;
304 
305  // get the part inside braces
306  ret = unescape(&val, &val_len, &next, '}');
307  if (ret < 0)
308  return ret;
309 
310  if (!val) {
312  "Empty formatting directive in: %s\n", fmt_spec);
313  return AVERROR(EINVAL);
314  }
315 
316  if (!*next) {
318  "Missing closing brace in: %s\n", fmt_spec);
319  ret = AVERROR(EINVAL);
320  goto fail;
321  }
322  next++;
323 
325  if (ret < 0)
326  goto fail;
327 
328  c = &es->components[es->nb_components - 1];
329 
330  for (size_t i = 0; i < FF_ARRAY_ELEMS(fmt_specs); i++) {
331  if (!strcmp(val, fmt_specs[i].str)) {
332  if ((pre && fmt_specs[i].post_only) || (!pre && fmt_specs[i].pre_only)) {
334  "Format directive '%s' may only be used %s-encoding\n",
335  val, pre ? "post" : "pre");
336  ret = AVERROR(EINVAL);
337  goto fail;
338  }
339 
340  c->type = fmt_specs[i].type;
341 
342  if (fmt_specs[i].need_input_data && !ost->ist) {
344  "Format directive '%s' is unavailable, because "
345  "this output stream has no associated input stream\n",
346  val);
347  }
348 
349  break;
350  }
351  }
352 
353  if (!c->type) {
354  av_log(NULL, AV_LOG_ERROR, "Invalid format directive: %s\n", val);
355  ret = AVERROR(EINVAL);
356  goto fail;
357  }
358 
359 fail:
360  av_freep(&val);
361  if (ret < 0)
362  return ret;
363  }
364 
365  ret = pthread_mutex_init(&es->lock, NULL);
366  if (ret)
367  return AVERROR(ret);
368  es->lock_initialized = 1;
369 
370  ret = enc_stats_get_file(&es->io, path);
371  if (ret < 0)
372  return ret;
373 
374  return 0;
375 }
376 
377 static const char *output_stream_item_name(void *obj)
378 {
379  const MuxStream *ms = obj;
380 
381  return ms->log_name;
382 }
383 
384 static const AVClass output_stream_class = {
385  .class_name = "OutputStream",
386  .version = LIBAVUTIL_VERSION_INT,
387  .item_name = output_stream_item_name,
388  .category = AV_CLASS_CATEGORY_MUXER,
389 };
390 
392 {
393  const char *type_str = av_get_media_type_string(type);
394  MuxStream *ms;
395 
396  ms = allocate_array_elem(&mux->of.streams, sizeof(*ms), &mux->of.nb_streams);
397  if (!ms)
398  return NULL;
399 
400  ms->ost.file = &mux->of;
401  ms->ost.index = mux->of.nb_streams - 1;
402  ms->ost.type = type;
403 
405 
406  ms->sch_idx = -1;
407  ms->sch_idx_enc = -1;
408 
409  snprintf(ms->log_name, sizeof(ms->log_name), "%cost#%d:%d",
410  type_str ? *type_str : '?', mux->of.index, ms->ost.index);
411 
412  return ms;
413 }
414 
416  OutputStream *ost, char **dst)
417 {
418  const char *filters = NULL;
419 #if FFMPEG_OPT_FILTER_SCRIPT
420  const char *filters_script = NULL;
421 
422  MATCH_PER_STREAM_OPT(filter_scripts, str, filters_script, oc, ost->st);
423 #endif
424  MATCH_PER_STREAM_OPT(filters, str, filters, oc, ost->st);
425 
426  if (!ost->enc) {
427  if (
429  filters_script ||
430 #endif
431  filters) {
433  "%s '%s' was specified, but codec copy was selected. "
434  "Filtering and streamcopy cannot be used together.\n",
436  filters ? "Filtergraph" : "Filtergraph script",
437  filters ? filters : filters_script
438 #else
439  "Filtergraph", filters
440 #endif
441  );
442  return AVERROR(ENOSYS);
443  }
444  return 0;
445  }
446 
447  if (!ost->ist) {
448  if (
450  filters_script ||
451 #endif
452  filters) {
454  "%s '%s' was specified for a stream fed from a complex "
455  "filtergraph. Simple and complex filtering cannot be used "
456  "together for the same stream.\n",
458  filters ? "Filtergraph" : "Filtergraph script",
459  filters ? filters : filters_script
460 #else
461  "Filtergraph", filters
462 #endif
463  );
464  return AVERROR(EINVAL);
465  }
466  return 0;
467  }
468 
469 #if FFMPEG_OPT_FILTER_SCRIPT
470  if (filters_script && filters) {
471  av_log(ost, AV_LOG_ERROR, "Both -filter and -filter_script set\n");
472  return AVERROR(EINVAL);
473  }
474 
475  if (filters_script)
476  *dst = file_read(filters_script);
477  else
478 #endif
479  if (filters)
480  *dst = av_strdup(filters);
481  else
482  *dst = av_strdup(ost->type == AVMEDIA_TYPE_VIDEO ? "null" : "anull");
483  return *dst ? 0 : AVERROR(ENOMEM);
484 }
485 
486 static int parse_matrix_coeffs(void *logctx, uint16_t *dest, const char *str)
487 {
488  const char *p = str;
489  for (int i = 0;; i++) {
490  dest[i] = atoi(p);
491  if (i == 63)
492  break;
493  p = strchr(p, ',');
494  if (!p) {
495  av_log(logctx, AV_LOG_FATAL,
496  "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
497  return AVERROR(EINVAL);
498  }
499  p++;
500  }
501 
502  return 0;
503 }
504 
505 static int fmt_in_list(const int *formats, int format)
506 {
507  for (; *formats != -1; formats++)
508  if (*formats == format)
509  return 1;
510  return 0;
511 }
512 
513 static enum AVPixelFormat
514 choose_pixel_fmt(const AVCodec *codec, enum AVPixelFormat target)
515 {
516  const enum AVPixelFormat *p = codec->pix_fmts;
518  //FIXME: This should check for AV_PIX_FMT_FLAG_ALPHA after PAL8 pixel format without alpha is implemented
519  int has_alpha = desc ? desc->nb_components % 2 == 0 : 0;
520  enum AVPixelFormat best= AV_PIX_FMT_NONE;
521 
522  for (; *p != AV_PIX_FMT_NONE; p++) {
523  best = av_find_best_pix_fmt_of_2(best, *p, target, has_alpha, NULL);
524  if (*p == target)
525  break;
526  }
527  if (*p == AV_PIX_FMT_NONE) {
528  if (target != AV_PIX_FMT_NONE)
530  "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
531  av_get_pix_fmt_name(target),
532  codec->name,
533  av_get_pix_fmt_name(best));
534  return best;
535  }
536  return target;
537 }
538 
539 static enum AVPixelFormat pix_fmt_parse(OutputStream *ost, const char *name)
540 {
541  const enum AVPixelFormat *fmts = ost->enc_ctx->codec->pix_fmts;
542  enum AVPixelFormat fmt;
543 
544  fmt = av_get_pix_fmt(name);
545  if (fmt == AV_PIX_FMT_NONE) {
546  av_log(ost, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", name);
547  return AV_PIX_FMT_NONE;
548  }
549 
550  /* when the user specified-format is an alias for an endianness-specific
551  * one (e.g. rgb48 -> rgb48be/le), it gets translated into the native
552  * endianness by av_get_pix_fmt();
553  * the following code handles the case when the native endianness is not
554  * supported by the encoder, but the other one is */
555  if (fmts && !fmt_in_list(fmts, fmt)) {
556  const char *name_canonical = av_get_pix_fmt_name(fmt);
557  int len = strlen(name_canonical);
558 
559  if (strcmp(name, name_canonical) &&
560  (!strcmp(name_canonical + len - 2, "le") ||
561  !strcmp(name_canonical + len - 2, "be"))) {
562  char name_other[64];
563  enum AVPixelFormat fmt_other;
564 
565  snprintf(name_other, sizeof(name_other), "%s%ce",
566  name, name_canonical[len - 2] == 'l' ? 'b' : 'l');
567  fmt_other = av_get_pix_fmt(name_other);
568  if (fmt_other != AV_PIX_FMT_NONE && fmt_in_list(fmts, fmt_other)) {
569  av_log(ost, AV_LOG_VERBOSE, "Mapping pixel format %s->%s\n",
570  name, name_other);
571  fmt = fmt_other;
572  }
573  }
574  }
575 
576  if (fmts && !fmt_in_list(fmts, fmt))
577  fmt = choose_pixel_fmt(ost->enc_ctx->codec, fmt);
578 
579  return fmt;
580 }
581 
582 static int new_stream_video(Muxer *mux, const OptionsContext *o,
583  OutputStream *ost)
584 {
585  AVFormatContext *oc = mux->fc;
586  AVStream *st;
587  char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
588  int ret = 0;
589 
590  st = ost->st;
591 
592  MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
593  if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
594  av_log(ost, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
595  return AVERROR(EINVAL);
596  }
597 
598  MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
599  if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
600  av_log(ost, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
601  return AVERROR(EINVAL);
602  }
603 
604  if (frame_rate && max_frame_rate) {
605  av_log(ost, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
606  return AVERROR(EINVAL);
607  }
608 
609  MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
610  if (frame_aspect_ratio) {
611  AVRational q;
612  if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
613  q.num <= 0 || q.den <= 0) {
614  av_log(ost, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
615  return AVERROR(EINVAL);
616  }
617  ost->frame_aspect_ratio = q;
618  }
619 
620  if (ost->enc_ctx) {
621  AVCodecContext *video_enc = ost->enc_ctx;
622  const char *p = NULL, *fps_mode = NULL;
623  char *frame_size = NULL;
624  char *frame_pix_fmt = NULL;
625  char *intra_matrix = NULL, *inter_matrix = NULL;
626  char *chroma_intra_matrix = NULL;
627  int do_pass = 0;
628  int i;
629 
631  if (frame_size) {
632  ret = av_parse_video_size(&video_enc->width, &video_enc->height, frame_size);
633  if (ret < 0) {
634  av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
635  return AVERROR(EINVAL);
636  }
637  }
638 
639  MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
640  if (frame_pix_fmt && *frame_pix_fmt == '+') {
641  ost->keep_pix_fmt = 1;
642  if (!*++frame_pix_fmt)
643  frame_pix_fmt = NULL;
644  }
645  if (frame_pix_fmt) {
646  video_enc->pix_fmt = pix_fmt_parse(ost, frame_pix_fmt);
647  if (video_enc->pix_fmt == AV_PIX_FMT_NONE)
648  return AVERROR(EINVAL);
649  }
650 
651  MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
652  if (intra_matrix) {
653  if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64)))
654  return AVERROR(ENOMEM);
655 
656  ret = parse_matrix_coeffs(ost, video_enc->intra_matrix, intra_matrix);
657  if (ret < 0)
658  return ret;
659  }
660  MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
661  if (chroma_intra_matrix) {
662  uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
663  if (!p)
664  return AVERROR(ENOMEM);
665  video_enc->chroma_intra_matrix = p;
666  ret = parse_matrix_coeffs(ost, p, chroma_intra_matrix);
667  if (ret < 0)
668  return ret;
669  }
670  MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
671  if (inter_matrix) {
672  if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64)))
673  return AVERROR(ENOMEM);
674  ret = parse_matrix_coeffs(ost, video_enc->inter_matrix, inter_matrix);
675  if (ret < 0)
676  return ret;
677  }
678 
679  MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
680  for (i = 0; p; i++) {
681  int start, end, q;
682  int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
683  if (e != 3) {
684  av_log(ost, AV_LOG_FATAL, "error parsing rc_override\n");
685  return AVERROR(EINVAL);
686  }
687  video_enc->rc_override =
688  av_realloc_array(video_enc->rc_override,
689  i + 1, sizeof(RcOverride));
690  if (!video_enc->rc_override) {
691  av_log(ost, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
692  return AVERROR(ENOMEM);
693  }
694  video_enc->rc_override[i].start_frame = start;
695  video_enc->rc_override[i].end_frame = end;
696  if (q > 0) {
697  video_enc->rc_override[i].qscale = q;
698  video_enc->rc_override[i].quality_factor = 1.0;
699  }
700  else {
701  video_enc->rc_override[i].qscale = 0;
702  video_enc->rc_override[i].quality_factor = -q/100.0;
703  }
704  p = strchr(p, '/');
705  if (p) p++;
706  }
707  video_enc->rc_override_count = i;
708 
709  /* two pass mode */
710  MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
711  if (do_pass) {
712  if (do_pass & 1) {
713  video_enc->flags |= AV_CODEC_FLAG_PASS1;
714  av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
715  }
716  if (do_pass & 2) {
717  video_enc->flags |= AV_CODEC_FLAG_PASS2;
718  av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
719  }
720  }
721 
722  MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
723  if (ost->logfile_prefix &&
724  !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
725  return AVERROR(ENOMEM);
726 
727  if (do_pass) {
728  int ost_idx = -1;
729  char logfilename[1024];
730  FILE *f;
731 
732  /* compute this stream's global index */
733  for (int i = 0; i <= ost->file->index; i++)
734  ost_idx += output_files[i]->nb_streams;
735 
736  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
737  ost->logfile_prefix ? ost->logfile_prefix :
738  DEFAULT_PASS_LOGFILENAME_PREFIX,
739  ost_idx);
740  if (!strcmp(ost->enc_ctx->codec->name, "libx264")) {
741  av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
742  } else {
743  if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
744  char *logbuffer = file_read(logfilename);
745 
746  if (!logbuffer) {
747  av_log(ost, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
748  logfilename);
749  return AVERROR(EIO);
750  }
751  video_enc->stats_in = logbuffer;
752  }
753  if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
754  f = fopen_utf8(logfilename, "wb");
755  if (!f) {
757  "Cannot write log file '%s' for pass-1 encoding: %s\n",
758  logfilename, strerror(errno));
759  return AVERROR(errno);
760  }
761  ost->logfile = f;
762  }
763  }
764  }
765 
766  MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
767 
768 #if FFMPEG_OPT_TOP
769  ost->top_field_first = -1;
770  MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
771  if (ost->top_field_first >= 0)
772  av_log(ost, AV_LOG_WARNING, "-top is deprecated, use the setfield filter instead\n");
773 #endif
774 
775 #if FFMPEG_OPT_VSYNC
776  ost->vsync_method = video_sync_method;
777 #else
778  ost->vsync_method = VSYNC_AUTO;
779 #endif
780  MATCH_PER_STREAM_OPT(fps_mode, str, fps_mode, oc, st);
781  if (fps_mode) {
782  ret = parse_and_set_vsync(fps_mode, &ost->vsync_method, ost->file->index, ost->index, 0);
783  if (ret < 0)
784  return ret;
785  }
786 
787  if ((ost->frame_rate.num || ost->max_frame_rate.num) &&
788  !(ost->vsync_method == VSYNC_AUTO ||
789  ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR)) {
790  av_log(ost, AV_LOG_FATAL, "One of -r/-fpsmax was specified "
791  "together a non-CFR -vsync/-fps_mode. This is contradictory.\n");
792  return AVERROR(EINVAL);
793  }
794 
795  if (ost->vsync_method == VSYNC_AUTO) {
796  if (ost->frame_rate.num || ost->max_frame_rate.num) {
797  ost->vsync_method = VSYNC_CFR;
798  } else if (!strcmp(oc->oformat->name, "avi")) {
799  ost->vsync_method = VSYNC_VFR;
800  } else {
801  ost->vsync_method = (oc->oformat->flags & AVFMT_VARIABLE_FPS) ?
802  ((oc->oformat->flags & AVFMT_NOTIMESTAMPS) ?
804  VSYNC_CFR;
805  }
806 
807  if (ost->ist && ost->vsync_method == VSYNC_CFR) {
808  const InputFile *ifile = ost->ist->file;
809 
810  if (ifile->nb_streams == 1 && ifile->input_ts_offset == 0)
811  ost->vsync_method = VSYNC_VSCFR;
812  }
813 
814  if (ost->vsync_method == VSYNC_CFR && copy_ts) {
815  ost->vsync_method = VSYNC_VSCFR;
816  }
817  }
818  ost->is_cfr = (ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR);
819  }
820 
821  return 0;
822 }
823 
824 static int new_stream_audio(Muxer *mux, const OptionsContext *o,
825  OutputStream *ost)
826 {
827  AVFormatContext *oc = mux->fc;
828  AVStream *st = ost->st;
829 
830  if (ost->enc_ctx) {
831  AVCodecContext *audio_enc = ost->enc_ctx;
832  int channels = 0;
833  char *layout = NULL;
834  char *sample_fmt = NULL;
835  const char *apad = NULL;
836 
838  if (channels) {
840  audio_enc->ch_layout.nb_channels = channels;
841  }
842 
843  MATCH_PER_STREAM_OPT(audio_ch_layouts, str, layout, oc, st);
844  if (layout && av_channel_layout_from_string(&audio_enc->ch_layout, layout) < 0) {
845  av_log(ost, AV_LOG_FATAL, "Unknown channel layout: %s\n", layout);
846  return AVERROR(EINVAL);
847  }
848 
849  MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
850  if (sample_fmt &&
851  (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
852  av_log(ost, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
853  return AVERROR(EINVAL);
854  }
855 
856  MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
857 
858  MATCH_PER_STREAM_OPT(apad, str, apad, oc, st);
859  if (apad) {
860  ost->apad = av_strdup(apad);
861  if (!ost->apad)
862  return AVERROR(ENOMEM);
863  }
864  }
865 
866  return 0;
867 }
868 
869 static int new_stream_subtitle(Muxer *mux, const OptionsContext *o,
870  OutputStream *ost)
871 {
872  AVStream *st;
873 
874  st = ost->st;
875 
876  if (ost->enc_ctx) {
877  AVCodecContext *subtitle_enc = ost->enc_ctx;
878 
879  AVCodecDescriptor const *input_descriptor =
880  avcodec_descriptor_get(ost->ist->par->codec_id);
881  AVCodecDescriptor const *output_descriptor =
882  avcodec_descriptor_get(subtitle_enc->codec_id);
883  int input_props = 0, output_props = 0;
884 
885  char *frame_size = NULL;
886 
888  if (frame_size) {
889  int ret = av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size);
890  if (ret < 0) {
891  av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
892  return ret;
893  }
894  }
895  if (input_descriptor)
896  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
897  if (output_descriptor)
898  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
899  if (input_props && output_props && input_props != output_props) {
901  "Subtitle encoding currently only possible from text to text "
902  "or bitmap to bitmap\n");
903  return AVERROR(EINVAL);
904  }
905  }
906 
907  return 0;
908 }
909 
910 static int streamcopy_init(const Muxer *mux, OutputStream *ost)
911 {
912  MuxStream *ms = ms_from_ost(ost);
913 
914  const InputStream *ist = ost->ist;
915  const InputFile *ifile = ist->file;
916 
917  AVCodecParameters *par = ost->par_in;
918  uint32_t codec_tag = par->codec_tag;
919 
920  AVCodecContext *codec_ctx = NULL;
922 
923  AVRational fr = ost->frame_rate;
924 
925  int ret = 0;
926 
927  codec_ctx = avcodec_alloc_context3(NULL);
928  if (!codec_ctx)
929  return AVERROR(ENOMEM);
930 
931  ret = avcodec_parameters_to_context(codec_ctx, ist->par);
932  if (ret >= 0)
933  ret = av_opt_set_dict(codec_ctx, &ost->encoder_opts);
934  if (ret < 0) {
936  "Error setting up codec context options.\n");
937  goto fail;
938  }
939 
940  ret = avcodec_parameters_from_context(par, codec_ctx);
941  if (ret < 0) {
943  "Error getting reference codec parameters.\n");
944  goto fail;
945  }
946 
947  if (!codec_tag) {
948  const struct AVCodecTag * const *ct = mux->fc->oformat->codec_tag;
949  unsigned int codec_tag_tmp;
950  if (!ct || av_codec_get_id (ct, par->codec_tag) == par->codec_id ||
951  !av_codec_get_tag2(ct, par->codec_id, &codec_tag_tmp))
952  codec_tag = par->codec_tag;
953  }
954 
955  par->codec_tag = codec_tag;
956 
957  if (!fr.num)
958  fr = ist->framerate;
959 
960  if (fr.num)
961  ost->st->avg_frame_rate = fr;
962  else
963  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
964 
966  ost->st, ist->st, copy_tb);
967  if (ret < 0)
968  goto fail;
969 
970  // copy timebase while removing common factors
971  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0) {
972  if (fr.num)
973  ost->st->time_base = av_inv_q(fr);
974  else
976  }
977 
978  if (!ms->copy_prior_start) {
979  ms->ts_copy_start = (mux->of.start_time == AV_NOPTS_VALUE) ?
980  0 : mux->of.start_time;
981  if (copy_ts && ifile->start_time != AV_NOPTS_VALUE) {
983  ifile->start_time + ifile->ts_offset);
984  }
985  }
986 
987  for (int i = 0; i < ist->st->codecpar->nb_coded_side_data; i++) {
988  const AVPacketSideData *sd_src = &ist->st->codecpar->coded_side_data[i];
989  AVPacketSideData *sd_dst;
990 
993  sd_src->type, sd_src->size, 0);
994  if (!sd_dst) {
995  ret = AVERROR(ENOMEM);
996  goto fail;
997  }
998  memcpy(sd_dst->data, sd_src->data, sd_src->size);
999  }
1000 
1001  switch (par->codec_type) {
1002  case AVMEDIA_TYPE_AUDIO:
1003  if ((par->block_align == 1 || par->block_align == 1152 || par->block_align == 576) &&
1004  par->codec_id == AV_CODEC_ID_MP3)
1005  par->block_align = 0;
1006  if (par->codec_id == AV_CODEC_ID_AC3)
1007  par->block_align = 0;
1008  break;
1009  case AVMEDIA_TYPE_VIDEO: {
1010  AVRational sar;
1011  if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
1012  sar =
1013  av_mul_q(ost->frame_aspect_ratio,
1014  (AVRational){ par->height, par->width });
1015  av_log(ost, AV_LOG_WARNING, "Overriding aspect ratio "
1016  "with stream copy may produce invalid files\n");
1017  }
1018  else if (ist->st->sample_aspect_ratio.num)
1019  sar = ist->st->sample_aspect_ratio;
1020  else
1021  sar = par->sample_aspect_ratio;
1022  ost->st->sample_aspect_ratio = par->sample_aspect_ratio = sar;
1023  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
1024  ost->st->r_frame_rate = ist->st->r_frame_rate;
1025  break;
1026  }
1027  }
1028 
1029 fail:
1030  avcodec_free_context(&codec_ctx);
1032  return ret;
1033 }
1034 
1035 static int ost_add(Muxer *mux, const OptionsContext *o, enum AVMediaType type,
1036  InputStream *ist, OutputFilter *ofilter,
1037  OutputStream **post)
1038 {
1039  AVFormatContext *oc = mux->fc;
1040  MuxStream *ms;
1041  OutputStream *ost;
1042  const AVCodec *enc;
1043  AVStream *st;
1044  int ret = 0;
1045  const char *bsfs = NULL, *time_base = NULL;
1046  char *filters = NULL, *next, *codec_tag = NULL;
1047  double qscale = -1;
1048 
1049  st = avformat_new_stream(oc, NULL);
1050  if (!st)
1051  return AVERROR(ENOMEM);
1052 
1053  ms = mux_stream_alloc(mux, type);
1054  if (!ms)
1055  return AVERROR(ENOMEM);
1056 
1057  // only streams with sources (i.e. not attachments)
1058  // are handled by the scheduler
1059  if (ist || ofilter) {
1061  if (ret < 0)
1062  return ret;
1063 
1064  ret = sch_add_mux_stream(mux->sch, mux->sch_idx);
1065  if (ret < 0)
1066  return ret;
1067 
1068  av_assert0(ret == mux->nb_sch_stream_idx - 1);
1069  mux->sch_stream_idx[ret] = ms->ost.index;
1070  ms->sch_idx = ret;
1071  }
1072 
1073  ost = &ms->ost;
1074 
1075  if (o->streamid) {
1076  AVDictionaryEntry *e;
1077  char idx[16], *p;
1078  snprintf(idx, sizeof(idx), "%d", ost->index);
1079 
1080  e = av_dict_get(o->streamid, idx, NULL, 0);
1081  if (e) {
1082  st->id = strtol(e->value, &p, 0);
1083  if (!e->value[0] || *p) {
1084  av_log(ost, AV_LOG_FATAL, "Invalid stream id: %s\n", e->value);
1085  return AVERROR(EINVAL);
1086  }
1087  }
1088  }
1089 
1090  ost->par_in = avcodec_parameters_alloc();
1091  if (!ost->par_in)
1092  return AVERROR(ENOMEM);
1093 
1095 
1096  ost->st = st;
1097  ost->ist = ist;
1098  ost->kf.ref_pts = AV_NOPTS_VALUE;
1099  ost->par_in->codec_type = type;
1100  st->codecpar->codec_type = type;
1101 
1102  ret = choose_encoder(o, oc, ost, &enc);
1103  if (ret < 0) {
1104  av_log(ost, AV_LOG_FATAL, "Error selecting an encoder\n");
1105  return ret;
1106  }
1107 
1108  if (enc) {
1109  ost->enc_ctx = avcodec_alloc_context3(enc);
1110  if (!ost->enc_ctx)
1111  return AVERROR(ENOMEM);
1112 
1114  ost->type == AVMEDIA_TYPE_SUBTITLE ? NULL : enc_open);
1115  if (ret < 0)
1116  return ret;
1117  ms->sch_idx_enc = ret;
1118 
1119  ret = enc_alloc(&ost->enc, enc, mux->sch, ms->sch_idx_enc);
1120  if (ret < 0)
1121  return ret;
1122 
1123  av_strlcat(ms->log_name, "/", sizeof(ms->log_name));
1124  av_strlcat(ms->log_name, enc->name, sizeof(ms->log_name));
1125  } else {
1126  if (ofilter) {
1128  "Streamcopy requested for output stream fed "
1129  "from a complex filtergraph. Filtering and streamcopy "
1130  "cannot be used together.\n");
1131  return AVERROR(EINVAL);
1132  }
1133 
1134  av_strlcat(ms->log_name, "/copy", sizeof(ms->log_name));
1135  }
1136 
1137  av_log(ost, AV_LOG_VERBOSE, "Created %s stream from ",
1139  if (ist)
1140  av_log(ost, AV_LOG_VERBOSE, "input stream %d:%d",
1141  ist->file->index, ist->index);
1142  else if (ofilter)
1143  av_log(ost, AV_LOG_VERBOSE, "complex filtergraph %d:[%s]\n",
1144  ofilter->graph->index, ofilter->name);
1145  else if (type == AVMEDIA_TYPE_ATTACHMENT)
1146  av_log(ost, AV_LOG_VERBOSE, "attached file");
1147  else av_assert0(0);
1148  av_log(ost, AV_LOG_VERBOSE, "\n");
1149 
1150  ms->pkt = av_packet_alloc();
1151  if (!ms->pkt)
1152  return AVERROR(ENOMEM);
1153 
1154  if (ost->enc_ctx) {
1155  AVCodecContext *enc = ost->enc_ctx;
1156  AVIOContext *s = NULL;
1157  char *buf = NULL, *arg = NULL, *preset = NULL;
1158  const char *enc_stats_pre = NULL, *enc_stats_post = NULL, *mux_stats = NULL;
1159  const char *enc_time_base = NULL;
1160 
1162  oc, st, enc->codec, &ost->encoder_opts);
1163  if (ret < 0)
1164  return ret;
1165 
1166  MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
1167  ost->autoscale = 1;
1168  MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
1169  if (preset && (!(ret = get_preset_file_2(preset, enc->codec->name, &s)))) {
1170  AVBPrint bprint;
1172  do {
1173  av_bprint_clear(&bprint);
1174  buf = get_line(s, &bprint);
1175  if (!buf) {
1176  ret = AVERROR(ENOMEM);
1177  break;
1178  }
1179 
1180  if (!buf[0] || buf[0] == '#')
1181  continue;
1182  if (!(arg = strchr(buf, '='))) {
1183  av_log(ost, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1184  ret = AVERROR(EINVAL);
1185  break;
1186  }
1187  *arg++ = 0;
1188  av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1189  } while (!s->eof_reached);
1190  av_bprint_finalize(&bprint, NULL);
1191  avio_closep(&s);
1192  }
1193  if (ret) {
1195  "Preset %s specified, but could not be opened.\n", preset);
1196  return ret;
1197  }
1198 
1199  MATCH_PER_STREAM_OPT(enc_stats_pre, str, enc_stats_pre, oc, st);
1200  if (enc_stats_pre &&
1202  const char *format = "{fidx} {sidx} {n} {t}";
1203 
1204  MATCH_PER_STREAM_OPT(enc_stats_pre_fmt, str, format, oc, st);
1205 
1206  ret = enc_stats_init(ost, &ost->enc_stats_pre, 1, enc_stats_pre, format);
1207  if (ret < 0)
1208  return ret;
1209  }
1210 
1211  MATCH_PER_STREAM_OPT(enc_stats_post, str, enc_stats_post, oc, st);
1212  if (enc_stats_post &&
1214  const char *format = "{fidx} {sidx} {n} {t}";
1215 
1216  MATCH_PER_STREAM_OPT(enc_stats_post_fmt, str, format, oc, st);
1217 
1218  ret = enc_stats_init(ost, &ost->enc_stats_post, 0, enc_stats_post, format);
1219  if (ret < 0)
1220  return ret;
1221  }
1222 
1223  MATCH_PER_STREAM_OPT(mux_stats, str, mux_stats, oc, st);
1224  if (mux_stats &&
1226  const char *format = "{fidx} {sidx} {n} {t}";
1227 
1228  MATCH_PER_STREAM_OPT(mux_stats_fmt, str, format, oc, st);
1229 
1230  ret = enc_stats_init(ost, &ms->stats, 0, mux_stats, format);
1231  if (ret < 0)
1232  return ret;
1233  }
1234 
1235  MATCH_PER_STREAM_OPT(enc_time_bases, str, enc_time_base, oc, st);
1236  if (enc_time_base) {
1237  AVRational q;
1238  if (!strcmp(enc_time_base, "demux")) {
1239  q = (AVRational){ ENC_TIME_BASE_DEMUX, 0 };
1240  } else if (!strcmp(enc_time_base, "filter")) {
1241  q = (AVRational){ ENC_TIME_BASE_FILTER, 0 };
1242  } else {
1243  ret = av_parse_ratio(&q, enc_time_base, INT_MAX, 0, NULL);
1244  if (ret < 0 || q.den <= 0
1246  || q.num < 0
1247 #endif
1248  ) {
1249  av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", enc_time_base);
1250  return ret < 0 ? ret : AVERROR(EINVAL);
1251  }
1252 #if FFMPEG_OPT_ENC_TIME_BASE_NUM
1253  if (q.num < 0)
1254  av_log(ost, AV_LOG_WARNING, "-enc_time_base -1 is deprecated,"
1255  " use -enc_timebase demux\n");
1256 #endif
1257  }
1258 
1259  ost->enc_timebase = q;
1260  }
1261  } else {
1263  NULL, &ost->encoder_opts);
1264  if (ret < 0)
1265  return ret;
1266  }
1267 
1268 
1269  if (o->bitexact) {
1270  ost->bitexact = 1;
1271  } else if (ost->enc_ctx) {
1272  ost->bitexact = check_opt_bitexact(ost->enc_ctx, ost->encoder_opts, "flags",
1274  }
1275 
1276  MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
1277  if (time_base) {
1278  AVRational q;
1279  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1280  q.num <= 0 || q.den <= 0) {
1281  av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1282  return AVERROR(EINVAL);
1283  }
1284  st->time_base = q;
1285  }
1286 
1287  ms->max_frames = INT64_MAX;
1288  MATCH_PER_STREAM_OPT(max_frames, i64, ms->max_frames, oc, st);
1289  for (int i = 0; i < o->max_frames.nb_opt; i++) {
1290  char *p = o->max_frames.opt[i].specifier;
1291  if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1292  av_log(ost, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1293  break;
1294  }
1295  }
1296 
1297  ms->copy_prior_start = -1;
1298  MATCH_PER_STREAM_OPT(copy_prior_start, i, ms->copy_prior_start, oc ,st);
1299 
1300  MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
1301  if (bsfs && *bsfs) {
1302  ret = av_bsf_list_parse_str(bsfs, &ms->bsf_ctx);
1303  if (ret < 0) {
1304  av_log(ost, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1305  return ret;
1306  }
1307  }
1308 
1309  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1310  if (codec_tag) {
1311  uint32_t tag = strtol(codec_tag, &next, 0);
1312  if (*next) {
1313  uint8_t buf[4] = { 0 };
1314  memcpy(buf, codec_tag, FFMIN(sizeof(buf), strlen(codec_tag)));
1315  tag = AV_RL32(buf);
1316  }
1317  ost->st->codecpar->codec_tag = tag;
1318  ost->par_in->codec_tag = tag;
1319  if (ost->enc_ctx)
1320  ost->enc_ctx->codec_tag = tag;
1321  }
1322 
1323  MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1324  if (ost->enc_ctx && qscale >= 0) {
1325  ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
1326  ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1327  }
1328 
1329  if (ms->sch_idx >= 0) {
1330  int max_muxing_queue_size = 128;
1331  int muxing_queue_data_threshold = 50 * 1024 * 1024;
1332 
1333  MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, max_muxing_queue_size, oc, st);
1334  MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, muxing_queue_data_threshold, oc, st);
1335 
1336  sch_mux_stream_buffering(mux->sch, mux->sch_idx, ms->sch_idx,
1337  max_muxing_queue_size, muxing_queue_data_threshold);
1338  }
1339 
1340  MATCH_PER_STREAM_OPT(bits_per_raw_sample, i, ost->bits_per_raw_sample,
1341  oc, st);
1342 
1343  MATCH_PER_STREAM_OPT(fix_sub_duration_heartbeat, i, ost->fix_sub_duration_heartbeat,
1344  oc, st);
1345 
1346  if (oc->oformat->flags & AVFMT_GLOBALHEADER && ost->enc_ctx)
1347  ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1348 
1349  av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
1350 
1351  av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1352  if (ost->enc_ctx && av_get_exact_bits_per_sample(ost->enc_ctx->codec_id) == 24)
1353  av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1354 
1355  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i,
1356  ms->copy_initial_nonkeyframes, oc, st);
1357 
1358  switch (type) {
1359  case AVMEDIA_TYPE_VIDEO: ret = new_stream_video (mux, o, ost); break;
1360  case AVMEDIA_TYPE_AUDIO: ret = new_stream_audio (mux, o, ost); break;
1361  case AVMEDIA_TYPE_SUBTITLE: ret = new_stream_subtitle (mux, o, ost); break;
1362  }
1363  if (ret < 0)
1364  return ret;
1365 
1367  ret = ost_get_filters(o, oc, ost, &filters);
1368  if (ret < 0)
1369  return ret;
1370  }
1371 
1372  if (ost->enc &&
1374  if (ofilter) {
1375  ost->filter = ofilter;
1376  ret = ofilter_bind_ost(ofilter, ost, ms->sch_idx_enc);
1377  if (ret < 0)
1378  return ret;
1379  } else {
1381  mux->sch, ms->sch_idx_enc);
1382  if (ret < 0) {
1384  "Error initializing a simple filtergraph\n");
1385  return ret;
1386  }
1387  }
1388 
1389  ret = sch_connect(mux->sch, SCH_ENC(ms->sch_idx_enc),
1390  SCH_MSTREAM(mux->sch_idx, ms->sch_idx));
1391  if (ret < 0)
1392  return ret;
1393  } else if (ost->ist) {
1394  int sched_idx = ist_output_add(ost->ist, ost);
1395  if (sched_idx < 0) {
1397  "Error binding an input stream\n");
1398  return sched_idx;
1399  }
1400  ms->sch_idx_src = sched_idx;
1401 
1402  if (ost->enc) {
1403  ret = sch_connect(mux->sch, SCH_DEC(sched_idx),
1404  SCH_ENC(ms->sch_idx_enc));
1405  if (ret < 0)
1406  return ret;
1407 
1408  ret = sch_connect(mux->sch, SCH_ENC(ms->sch_idx_enc),
1409  SCH_MSTREAM(mux->sch_idx, ms->sch_idx));
1410  if (ret < 0)
1411  return ret;
1412  } else {
1413  ret = sch_connect(mux->sch, SCH_DSTREAM(ost->ist->file->index, sched_idx),
1414  SCH_MSTREAM(ost->file->index, ms->sch_idx));
1415  if (ret < 0)
1416  return ret;
1417  }
1418  }
1419 
1420  if (ost->ist && !ost->enc) {
1421  ret = streamcopy_init(mux, ost);
1422  if (ret < 0)
1423  return ret;
1424  }
1425 
1426  // copy estimated duration as a hint to the muxer
1427  if (ost->ist && ost->ist->st->duration > 0) {
1428  ms->stream_duration = ist->st->duration;
1429  ms->stream_duration_tb = ist->st->time_base;
1430  }
1431 
1432  if (post)
1433  *post = ost;
1434 
1435  return 0;
1436 }
1437 
1438 static int map_auto_video(Muxer *mux, const OptionsContext *o)
1439 {
1440  AVFormatContext *oc = mux->fc;
1441  InputStream *best_ist = NULL;
1442  int best_score = 0;
1443  int qcr;
1444 
1445  /* video: highest resolution */
1447  return 0;
1448 
1449  qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
1450  for (int j = 0; j < nb_input_files; j++) {
1451  InputFile *ifile = input_files[j];
1452  InputStream *file_best_ist = NULL;
1453  int file_best_score = 0;
1454  for (int i = 0; i < ifile->nb_streams; i++) {
1455  InputStream *ist = ifile->streams[i];
1456  int score;
1457 
1458  if (ist->user_set_discard == AVDISCARD_ALL ||
1460  continue;
1461 
1462  score = ist->st->codecpar->width * ist->st->codecpar->height
1463  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
1464  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
1465  if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1466  score = 1;
1467 
1468  if (score > file_best_score) {
1469  if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1470  continue;
1471  file_best_score = score;
1472  file_best_ist = ist;
1473  }
1474  }
1475  if (file_best_ist) {
1476  if((qcr == MKTAG('A', 'P', 'I', 'C')) ||
1477  !(file_best_ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1478  file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
1479  if (file_best_score > best_score) {
1480  best_score = file_best_score;
1481  best_ist = file_best_ist;
1482  }
1483  }
1484  }
1485  if (best_ist)
1486  return ost_add(mux, o, AVMEDIA_TYPE_VIDEO, best_ist, NULL, NULL);
1487 
1488  return 0;
1489 }
1490 
1491 static int map_auto_audio(Muxer *mux, const OptionsContext *o)
1492 {
1493  AVFormatContext *oc = mux->fc;
1494  InputStream *best_ist = NULL;
1495  int best_score = 0;
1496 
1497  /* audio: most channels */
1499  return 0;
1500 
1501  for (int j = 0; j < nb_input_files; j++) {
1502  InputFile *ifile = input_files[j];
1503  InputStream *file_best_ist = NULL;
1504  int file_best_score = 0;
1505  for (int i = 0; i < ifile->nb_streams; i++) {
1506  InputStream *ist = ifile->streams[i];
1507  int score;
1508 
1509  if (ist->user_set_discard == AVDISCARD_ALL ||
1511  continue;
1512 
1513  score = ist->st->codecpar->ch_layout.nb_channels
1514  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
1515  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
1516  if (score > file_best_score) {
1517  file_best_score = score;
1518  file_best_ist = ist;
1519  }
1520  }
1521  if (file_best_ist) {
1522  file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
1523  if (file_best_score > best_score) {
1524  best_score = file_best_score;
1525  best_ist = file_best_ist;
1526  }
1527  }
1528  }
1529  if (best_ist)
1530  return ost_add(mux, o, AVMEDIA_TYPE_AUDIO, best_ist, NULL, NULL);
1531 
1532  return 0;
1533 }
1534 
1535 static int map_auto_subtitle(Muxer *mux, const OptionsContext *o)
1536 {
1537  AVFormatContext *oc = mux->fc;
1538  const char *subtitle_codec_name = NULL;
1539 
1540  /* subtitles: pick first */
1543  return 0;
1544 
1545  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist))
1546  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1547  AVCodecDescriptor const *input_descriptor =
1548  avcodec_descriptor_get(ist->st->codecpar->codec_id);
1549  AVCodecDescriptor const *output_descriptor = NULL;
1550  AVCodec const *output_codec =
1552  int input_props = 0, output_props = 0;
1553  if (ist->user_set_discard == AVDISCARD_ALL)
1554  continue;
1555  if (output_codec)
1556  output_descriptor = avcodec_descriptor_get(output_codec->id);
1557  if (input_descriptor)
1558  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1559  if (output_descriptor)
1560  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1561  if (subtitle_codec_name ||
1562  input_props & output_props ||
1563  // Map dvb teletext which has neither property to any output subtitle encoder
1564  input_descriptor && output_descriptor &&
1565  (!input_descriptor->props ||
1566  !output_descriptor->props)) {
1567  return ost_add(mux, o, AVMEDIA_TYPE_SUBTITLE, ist, NULL, NULL);
1568  }
1569  }
1570 
1571  return 0;
1572 }
1573 
1574 static int map_auto_data(Muxer *mux, const OptionsContext *o)
1575 {
1576  AVFormatContext *oc = mux->fc;
1577  /* Data only if codec id match */
1579 
1580  if (codec_id == AV_CODEC_ID_NONE)
1581  return 0;
1582 
1583  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
1584  if (ist->user_set_discard == AVDISCARD_ALL)
1585  continue;
1586  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
1587  ist->st->codecpar->codec_id == codec_id) {
1588  int ret = ost_add(mux, o, AVMEDIA_TYPE_DATA, ist, NULL, NULL);
1589  if (ret < 0)
1590  return ret;
1591  }
1592  }
1593 
1594  return 0;
1595 }
1596 
1597 static int map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
1598 {
1599  InputStream *ist;
1600  int ret;
1601 
1602  if (map->disabled)
1603  return 0;
1604 
1605  if (map->linklabel) {
1606  FilterGraph *fg;
1607  OutputFilter *ofilter = NULL;
1608  int j, k;
1609 
1610  for (j = 0; j < nb_filtergraphs; j++) {
1611  fg = filtergraphs[j];
1612  for (k = 0; k < fg->nb_outputs; k++) {
1613  const char *linklabel = fg->outputs[k]->linklabel;
1614  if (linklabel && !strcmp(linklabel, map->linklabel)) {
1615  ofilter = fg->outputs[k];
1616  goto loop_end;
1617  }
1618  }
1619  }
1620 loop_end:
1621  if (!ofilter) {
1622  av_log(mux, AV_LOG_FATAL, "Output with label '%s' does not exist "
1623  "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
1624  return AVERROR(EINVAL);
1625  }
1626 
1627  av_log(mux, AV_LOG_VERBOSE, "Creating output stream from an explicitly "
1628  "mapped complex filtergraph %d, output [%s]\n", fg->index, map->linklabel);
1629 
1630  ret = ost_add(mux, o, ofilter->type, NULL, ofilter, NULL);
1631  if (ret < 0)
1632  return ret;
1633  } else {
1634  ist = input_files[map->file_index]->streams[map->stream_index];
1635  if (ist->user_set_discard == AVDISCARD_ALL) {
1636  av_log(mux, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
1637  map->file_index, map->stream_index);
1638  return AVERROR(EINVAL);
1639  }
1641  return 0;
1643  return 0;
1645  return 0;
1646  if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1647  return 0;
1648 
1649  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
1652  "Cannot map stream #%d:%d - unsupported type.\n",
1653  map->file_index, map->stream_index);
1654  if (!ignore_unknown_streams) {
1655  av_log(mux, AV_LOG_FATAL,
1656  "If you want unsupported types ignored instead "
1657  "of failing, please use the -ignore_unknown option\n"
1658  "If you want them copied, please use -copy_unknown\n");
1659  return AVERROR(EINVAL);
1660  }
1661  return 0;
1662  }
1663 
1664  ret = ost_add(mux, o, ist->st->codecpar->codec_type, ist, NULL, NULL);
1665  if (ret < 0)
1666  return ret;
1667  }
1668 
1669  return 0;
1670 }
1671 
1672 static int of_add_attachments(Muxer *mux, const OptionsContext *o)
1673 {
1674  OutputStream *ost;
1675  int err;
1676 
1677  for (int i = 0; i < o->nb_attachments; i++) {
1678  AVIOContext *pb;
1679  uint8_t *attachment;
1680  char *attachment_filename;
1681  const char *p;
1682  int64_t len;
1683 
1684  if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
1685  av_log(mux, AV_LOG_FATAL, "Could not open attachment file %s.\n",
1686  o->attachments[i]);
1687  return err;
1688  }
1689  if ((len = avio_size(pb)) <= 0) {
1690  av_log(mux, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
1691  o->attachments[i]);
1692  err = len ? len : AVERROR_INVALIDDATA;
1693  goto read_fail;
1694  }
1695  if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
1696  av_log(mux, AV_LOG_FATAL, "Attachment %s too large.\n",
1697  o->attachments[i]);
1698  err = AVERROR(ERANGE);
1699  goto read_fail;
1700  }
1701 
1702  attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE);
1703  if (!attachment) {
1704  err = AVERROR(ENOMEM);
1705  goto read_fail;
1706  }
1707 
1708  err = avio_read(pb, attachment, len);
1709  if (err < 0)
1710  av_log(mux, AV_LOG_FATAL, "Error reading attachment file %s: %s\n",
1711  o->attachments[i], av_err2str(err));
1712  else if (err != len) {
1713  av_log(mux, AV_LOG_FATAL, "Could not read all %"PRId64" bytes for "
1714  "attachment file %s\n", len, o->attachments[i]);
1715  err = AVERROR(EIO);
1716  }
1717 
1718 read_fail:
1719  avio_closep(&pb);
1720  if (err < 0)
1721  return err;
1722 
1723  memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1724 
1725  av_log(mux, AV_LOG_VERBOSE, "Creating attachment stream from file %s\n",
1726  o->attachments[i]);
1727 
1728  attachment_filename = av_strdup(o->attachments[i]);
1729  if (!attachment_filename) {
1730  av_free(attachment);
1731  return AVERROR(ENOMEM);
1732  }
1733 
1734  err = ost_add(mux, o, AVMEDIA_TYPE_ATTACHMENT, NULL, NULL, &ost);
1735  if (err < 0) {
1736  av_free(attachment_filename);
1737  av_freep(&attachment);
1738  return err;
1739  }
1740 
1741  ost->attachment_filename = attachment_filename;
1742  ost->par_in->extradata = attachment;
1743  ost->par_in->extradata_size = len;
1744 
1745  p = strrchr(o->attachments[i], '/');
1746  av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
1747  }
1748 
1749  return 0;
1750 }
1751 
1752 static int create_streams(Muxer *mux, const OptionsContext *o)
1753 {
1754  static int (* const map_func[])(Muxer *mux, const OptionsContext *o) = {
1759  };
1760 
1761  AVFormatContext *oc = mux->fc;
1762 
1763  int auto_disable =
1764  o->video_disable * (1 << AVMEDIA_TYPE_VIDEO) |
1765  o->audio_disable * (1 << AVMEDIA_TYPE_AUDIO) |
1767  o->data_disable * (1 << AVMEDIA_TYPE_DATA);
1768 
1769  int ret;
1770 
1771  /* create streams for all unlabeled output pads */
1772  for (int i = 0; i < nb_filtergraphs; i++) {
1773  FilterGraph *fg = filtergraphs[i];
1774  for (int j = 0; j < fg->nb_outputs; j++) {
1775  OutputFilter *ofilter = fg->outputs[j];
1776 
1777  if (ofilter->linklabel || ofilter->ost)
1778  continue;
1779 
1780  auto_disable |= 1 << ofilter->type;
1781 
1782  av_log(mux, AV_LOG_VERBOSE, "Creating output stream from unlabeled "
1783  "output of complex filtergraph %d.", fg->index);
1784  if (!o->nb_stream_maps)
1785  av_log(mux, AV_LOG_VERBOSE, " This overrides automatic %s mapping.",
1786  av_get_media_type_string(ofilter->type));
1787  av_log(mux, AV_LOG_VERBOSE, "\n");
1788 
1789  ret = ost_add(mux, o, ofilter->type, NULL, ofilter, NULL);
1790  if (ret < 0)
1791  return ret;
1792  }
1793  }
1794 
1795  if (!o->nb_stream_maps) {
1796  av_log(mux, AV_LOG_VERBOSE, "No explicit maps, mapping streams automatically...\n");
1797 
1798  /* pick the "best" stream of each type */
1799  for (int i = 0; i < FF_ARRAY_ELEMS(map_func); i++) {
1800  if (!map_func[i] || auto_disable & (1 << i))
1801  continue;
1802  ret = map_func[i](mux, o);
1803  if (ret < 0)
1804  return ret;
1805  }
1806  } else {
1807  av_log(mux, AV_LOG_VERBOSE, "Adding streams from explicit maps...\n");
1808 
1809  for (int i = 0; i < o->nb_stream_maps; i++) {
1810  ret = map_manual(mux, o, &o->stream_maps[i]);
1811  if (ret < 0)
1812  return ret;
1813  }
1814  }
1815 
1816  ret = of_add_attachments(mux, o);
1817  if (ret < 0)
1818  return ret;
1819 
1820  // setup fix_sub_duration_heartbeat mappings
1821  for (unsigned i = 0; i < oc->nb_streams; i++) {
1822  MuxStream *src = ms_from_ost(mux->of.streams[i]);
1823 
1824  if (!src->ost.fix_sub_duration_heartbeat)
1825  continue;
1826 
1827  for (unsigned j = 0; j < oc->nb_streams; j++) {
1828  MuxStream *dst = ms_from_ost(mux->of.streams[j]);
1829 
1830  if (src == dst || dst->ost.type != AVMEDIA_TYPE_SUBTITLE ||
1831  !dst->ost.enc || !dst->ost.ist || !dst->ost.ist->fix_sub_duration)
1832  continue;
1833 
1834  ret = sch_mux_sub_heartbeat_add(mux->sch, mux->sch_idx, src->sch_idx,
1835  dst->sch_idx_src);
1836 
1837  }
1838  }
1839 
1840  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
1841  av_dump_format(oc, nb_output_files - 1, oc->url, 1);
1842  av_log(mux, AV_LOG_ERROR, "Output file does not contain any stream\n");
1843  return AVERROR(EINVAL);
1844  }
1845 
1846  return 0;
1847 }
1848 
1849 static int setup_sync_queues(Muxer *mux, AVFormatContext *oc, int64_t buf_size_us)
1850 {
1851  OutputFile *of = &mux->of;
1852  int nb_av_enc = 0, nb_audio_fs = 0, nb_interleaved = 0;
1853  int limit_frames = 0, limit_frames_av_enc = 0;
1854 
1855 #define IS_AV_ENC(ost, type) \
1856  (ost->enc_ctx && (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO))
1857 #define IS_INTERLEAVED(type) (type != AVMEDIA_TYPE_ATTACHMENT)
1858 
1859  for (int i = 0; i < oc->nb_streams; i++) {
1860  OutputStream *ost = of->streams[i];
1861  MuxStream *ms = ms_from_ost(ost);
1862  enum AVMediaType type = ost->type;
1863 
1864  ms->sq_idx_mux = -1;
1865 
1866  nb_interleaved += IS_INTERLEAVED(type);
1867  nb_av_enc += IS_AV_ENC(ost, type);
1868  nb_audio_fs += (ost->enc_ctx && type == AVMEDIA_TYPE_AUDIO &&
1869  !(ost->enc_ctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE));
1870 
1871  limit_frames |= ms->max_frames < INT64_MAX;
1872  limit_frames_av_enc |= (ms->max_frames < INT64_MAX) && IS_AV_ENC(ost, type);
1873  }
1874 
1875  if (!((nb_interleaved > 1 && of->shortest) ||
1876  (nb_interleaved > 0 && limit_frames) ||
1877  nb_audio_fs))
1878  return 0;
1879 
1880  /* we use a sync queue before encoding when:
1881  * - 'shortest' is in effect and we have two or more encoded audio/video
1882  * streams
1883  * - at least one encoded audio/video stream is frame-limited, since
1884  * that has similar semantics to 'shortest'
1885  * - at least one audio encoder requires constant frame sizes
1886  *
1887  * Note that encoding sync queues are handled in the scheduler, because
1888  * different encoders run in different threads and need external
1889  * synchronization, while muxer sync queues can be handled inside the muxer
1890  */
1891  if ((of->shortest && nb_av_enc > 1) || limit_frames_av_enc || nb_audio_fs) {
1892  int sq_idx, ret;
1893 
1894  sq_idx = sch_add_sq_enc(mux->sch, buf_size_us, mux);
1895  if (sq_idx < 0)
1896  return sq_idx;
1897 
1898  for (int i = 0; i < oc->nb_streams; i++) {
1899  OutputStream *ost = of->streams[i];
1900  MuxStream *ms = ms_from_ost(ost);
1901  enum AVMediaType type = ost->type;
1902 
1903  if (!IS_AV_ENC(ost, type))
1904  continue;
1905 
1906  ret = sch_sq_add_enc(mux->sch, sq_idx, ms->sch_idx_enc,
1907  of->shortest || ms->max_frames < INT64_MAX,
1908  ms->max_frames);
1909  if (ret < 0)
1910  return ret;
1911  }
1912  }
1913 
1914  /* if there are any additional interleaved streams, then ALL the streams
1915  * are also synchronized before sending them to the muxer */
1916  if (nb_interleaved > nb_av_enc) {
1917  mux->sq_mux = sq_alloc(SYNC_QUEUE_PACKETS, buf_size_us, mux);
1918  if (!mux->sq_mux)
1919  return AVERROR(ENOMEM);
1920 
1921  mux->sq_pkt = av_packet_alloc();
1922  if (!mux->sq_pkt)
1923  return AVERROR(ENOMEM);
1924 
1925  for (int i = 0; i < oc->nb_streams; i++) {
1926  OutputStream *ost = of->streams[i];
1927  MuxStream *ms = ms_from_ost(ost);
1928  enum AVMediaType type = ost->type;
1929 
1930  if (!IS_INTERLEAVED(type))
1931  continue;
1932 
1933  ms->sq_idx_mux = sq_add_stream(mux->sq_mux,
1934  of->shortest || ms->max_frames < INT64_MAX);
1935  if (ms->sq_idx_mux < 0)
1936  return ms->sq_idx_mux;
1937 
1938  if (ms->max_frames != INT64_MAX)
1939  sq_limit_frames(mux->sq_mux, ms->sq_idx_mux, ms->max_frames);
1940  }
1941  }
1942 
1943 #undef IS_AV_ENC
1944 #undef IS_INTERLEAVED
1945 
1946  return 0;
1947 }
1948 
1949 static int of_parse_iamf_audio_element_layers(Muxer *mux, AVStreamGroup *stg, char *ptr)
1950 {
1951  AVIAMFAudioElement *audio_element = stg->params.iamf_audio_element;
1952  AVDictionary *dict = NULL;
1953  const char *token;
1954  int ret = 0;
1955 
1956  audio_element->demixing_info =
1958  audio_element->recon_gain_info =
1960 
1961  if (!audio_element->demixing_info ||
1962  !audio_element->recon_gain_info)
1963  return AVERROR(ENOMEM);
1964 
1965  /* process manually set layers and parameters */
1966  token = av_strtok(NULL, ",", &ptr);
1967  while (token) {
1968  const AVDictionaryEntry *e;
1969  int demixing = 0, recon_gain = 0;
1970  int layer = 0;
1971 
1972  if (ptr)
1973  ptr += strspn(ptr, " \n\t\r");
1974  if (av_strstart(token, "layer=", &token))
1975  layer = 1;
1976  else if (av_strstart(token, "demixing=", &token))
1977  demixing = 1;
1978  else if (av_strstart(token, "recon_gain=", &token))
1979  recon_gain = 1;
1980 
1981  av_dict_free(&dict);
1982  ret = av_dict_parse_string(&dict, token, "=", ":", 0);
1983  if (ret < 0) {
1984  av_log(mux, AV_LOG_ERROR, "Error parsing audio element specification %s\n", token);
1985  goto fail;
1986  }
1987 
1988  if (layer) {
1989  AVIAMFLayer *audio_layer = av_iamf_audio_element_add_layer(audio_element);
1990  if (!audio_layer) {
1991  av_log(mux, AV_LOG_ERROR, "Error adding layer to stream group %d\n", stg->index);
1992  ret = AVERROR(ENOMEM);
1993  goto fail;
1994  }
1995  av_opt_set_dict(audio_layer, &dict);
1996  } else if (demixing || recon_gain) {
1997  AVIAMFParamDefinition *param = demixing ? audio_element->demixing_info
1998  : audio_element->recon_gain_info;
1999  void *subblock = av_iamf_param_definition_get_subblock(param, 0);
2000 
2001  av_opt_set_dict(param, &dict);
2002  av_opt_set_dict(subblock, &dict);
2003  }
2004 
2005  // make sure that no entries are left in the dict
2006  e = NULL;
2007  if (e = av_dict_iterate(dict, e)) {
2008  av_log(mux, AV_LOG_FATAL, "Unknown layer key %s.\n", e->key);
2009  ret = AVERROR(EINVAL);
2010  goto fail;
2011  }
2012  token = av_strtok(NULL, ",", &ptr);
2013  }
2014 
2015 fail:
2016  av_dict_free(&dict);
2017  if (!ret && !audio_element->nb_layers) {
2018  av_log(mux, AV_LOG_ERROR, "No layer in audio element specification\n");
2019  ret = AVERROR(EINVAL);
2020  }
2021 
2022  return ret;
2023 }
2024 
2025 static int of_parse_iamf_submixes(Muxer *mux, AVStreamGroup *stg, char *ptr)
2026 {
2027  AVFormatContext *oc = mux->fc;
2029  AVDictionary *dict = NULL;
2030  const char *token;
2031  char *submix_str = NULL;
2032  int ret = 0;
2033 
2034  /* process manually set submixes */
2035  token = av_strtok(NULL, ",", &ptr);
2036  while (token) {
2037  AVIAMFSubmix *submix = NULL;
2038  const char *subtoken;
2039  char *subptr = NULL;
2040 
2041  if (ptr)
2042  ptr += strspn(ptr, " \n\t\r");
2043  if (!av_strstart(token, "submix=", &token)) {
2044  av_log(mux, AV_LOG_ERROR, "No submix in mix presentation specification \"%s\"\n", token);
2045  goto fail;
2046  }
2047 
2048  submix_str = av_strdup(token);
2049  if (!submix_str)
2050  goto fail;
2051 
2053  if (!submix) {
2054  av_log(mux, AV_LOG_ERROR, "Error adding submix to stream group %d\n", stg->index);
2055  ret = AVERROR(ENOMEM);
2056  goto fail;
2057  }
2058  submix->output_mix_config =
2060  if (!submix->output_mix_config) {
2061  ret = AVERROR(ENOMEM);
2062  goto fail;
2063  }
2064 
2065  subptr = NULL;
2066  subtoken = av_strtok(submix_str, "|", &subptr);
2067  while (subtoken) {
2068  const AVDictionaryEntry *e;
2069  int element = 0, layout = 0;
2070 
2071  if (subptr)
2072  subptr += strspn(subptr, " \n\t\r");
2073  if (av_strstart(subtoken, "element=", &subtoken))
2074  element = 1;
2075  else if (av_strstart(subtoken, "layout=", &subtoken))
2076  layout = 1;
2077 
2078  av_dict_free(&dict);
2079  ret = av_dict_parse_string(&dict, subtoken, "=", ":", 0);
2080  if (ret < 0) {
2081  av_log(mux, AV_LOG_ERROR, "Error parsing submix specification \"%s\"\n", subtoken);
2082  goto fail;
2083  }
2084 
2085  if (element) {
2086  AVIAMFSubmixElement *submix_element;
2087  char *endptr = NULL;
2088  int64_t idx = -1;
2089 
2090  if (e = av_dict_get(dict, "stg", NULL, 0))
2091  idx = strtoll(e->value, &endptr, 0);
2092  if (!endptr || *endptr || idx < 0 || idx >= oc->nb_stream_groups - 1 ||
2094  av_log(mux, AV_LOG_ERROR, "Invalid or missing stream group index in "
2095  "submix element specification \"%s\"\n", subtoken);
2096  ret = AVERROR(EINVAL);
2097  goto fail;
2098  }
2099  submix_element = av_iamf_submix_add_element(submix);
2100  if (!submix_element) {
2101  av_log(mux, AV_LOG_ERROR, "Error adding element to submix\n");
2102  ret = AVERROR(ENOMEM);
2103  goto fail;
2104  }
2105 
2106  submix_element->audio_element_id = oc->stream_groups[idx]->id;
2107 
2108  submix_element->element_mix_config =
2110  if (!submix_element->element_mix_config)
2111  ret = AVERROR(ENOMEM);
2112  av_dict_set(&dict, "stg", NULL, 0);
2113  av_opt_set_dict2(submix_element, &dict, AV_OPT_SEARCH_CHILDREN);
2114  } else if (layout) {
2115  AVIAMFSubmixLayout *submix_layout = av_iamf_submix_add_layout(submix);
2116  if (!submix_layout) {
2117  av_log(mux, AV_LOG_ERROR, "Error adding layout to submix\n");
2118  ret = AVERROR(ENOMEM);
2119  goto fail;
2120  }
2121  av_opt_set_dict(submix_layout, &dict);
2122  } else
2123  av_opt_set_dict2(submix, &dict, AV_OPT_SEARCH_CHILDREN);
2124 
2125  if (ret < 0) {
2126  goto fail;
2127  }
2128 
2129  // make sure that no entries are left in the dict
2130  e = NULL;
2131  while (e = av_dict_iterate(dict, e)) {
2132  av_log(mux, AV_LOG_FATAL, "Unknown submix key %s.\n", e->key);
2133  ret = AVERROR(EINVAL);
2134  goto fail;
2135  }
2136  subtoken = av_strtok(NULL, "|", &subptr);
2137  }
2138  av_freep(&submix_str);
2139 
2140  if (!submix->nb_elements) {
2141  av_log(mux, AV_LOG_ERROR, "No audio elements in submix specification \"%s\"\n", token);
2142  ret = AVERROR(EINVAL);
2143  }
2144  token = av_strtok(NULL, ",", &ptr);
2145  }
2146 
2147 fail:
2148  av_dict_free(&dict);
2149  av_free(submix_str);
2150 
2151  return ret;
2152 }
2153 
2154 static int of_parse_group_token(Muxer *mux, const char *token, char *ptr)
2155 {
2156  AVFormatContext *oc = mux->fc;
2157  AVStreamGroup *stg;
2158  AVDictionary *dict = NULL, *tmp = NULL;
2159  const AVDictionaryEntry *e;
2160  const AVOption opts[] = {
2161  { "type", "Set group type", offsetof(AVStreamGroup, type), AV_OPT_TYPE_INT,
2162  { .i64 = 0 }, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, .unit = "type" },
2163  { "iamf_audio_element", NULL, 0, AV_OPT_TYPE_CONST,
2164  { .i64 = AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT }, .unit = "type" },
2165  { "iamf_mix_presentation", NULL, 0, AV_OPT_TYPE_CONST,
2166  { .i64 = AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION }, .unit = "type" },
2167  { NULL },
2168  };
2169  const AVClass class = {
2170  .class_name = "StreamGroupType",
2171  .item_name = av_default_item_name,
2172  .option = opts,
2173  .version = LIBAVUTIL_VERSION_INT,
2174  };
2175  const AVClass *pclass = &class;
2176  int type, ret;
2177 
2178  ret = av_dict_parse_string(&dict, token, "=", ":", AV_DICT_MULTIKEY);
2179  if (ret < 0) {
2180  av_log(mux, AV_LOG_ERROR, "Error parsing group specification %s\n", token);
2181  return ret;
2182  }
2183 
2184  // "type" is not a user settable AVOption in AVStreamGroup, so handle it here
2185  e = av_dict_get(dict, "type", NULL, 0);
2186  if (!e) {
2187  av_log(mux, AV_LOG_ERROR, "No type specified for Stream Group in \"%s\"\n", token);
2188  ret = AVERROR(EINVAL);
2189  goto end;
2190  }
2191 
2192  ret = av_opt_eval_int(&pclass, opts, e->value, &type);
2194  ret = AVERROR(EINVAL);
2195  if (ret < 0) {
2196  av_log(mux, AV_LOG_ERROR, "Invalid group type \"%s\"\n", e->value);
2197  goto end;
2198  }
2199 
2200  av_dict_copy(&tmp, dict, 0);
2201  stg = avformat_stream_group_create(oc, type, &tmp);
2202  if (!stg) {
2203  ret = AVERROR(ENOMEM);
2204  goto end;
2205  }
2206 
2207  e = NULL;
2208  while (e = av_dict_get(dict, "st", e, 0)) {
2209  char *endptr;
2210  int64_t idx = strtoll(e->value, &endptr, 0);
2211  if (*endptr || idx < 0 || idx >= oc->nb_streams) {
2212  av_log(mux, AV_LOG_ERROR, "Invalid stream index %"PRId64"\n", idx);
2213  ret = AVERROR(EINVAL);
2214  goto end;
2215  }
2216  ret = avformat_stream_group_add_stream(stg, oc->streams[idx]);
2217  if (ret < 0)
2218  goto end;
2219  }
2220  while (e = av_dict_get(dict, "stg", e, 0)) {
2221  char *endptr;
2222  int64_t idx = strtoll(e->value, &endptr, 0);
2223  if (*endptr || idx < 0 || idx >= oc->nb_stream_groups - 1) {
2224  av_log(mux, AV_LOG_ERROR, "Invalid stream group index %"PRId64"\n", idx);
2225  ret = AVERROR(EINVAL);
2226  goto end;
2227  }
2228  for (unsigned i = 0; i < oc->stream_groups[idx]->nb_streams; i++) {
2230  if (ret < 0)
2231  goto end;
2232  }
2233  }
2234 
2235  switch(type) {
2237  ret = of_parse_iamf_audio_element_layers(mux, stg, ptr);
2238  break;
2240  ret = of_parse_iamf_submixes(mux, stg, ptr);
2241  break;
2242  default:
2243  av_log(mux, AV_LOG_FATAL, "Unknown group type %d.\n", type);
2244  ret = AVERROR(EINVAL);
2245  break;
2246  }
2247 
2248  if (ret < 0)
2249  goto end;
2250 
2251  // make sure that nothing but "st" and "stg" entries are left in the dict
2252  e = NULL;
2253  av_dict_set(&tmp, "type", NULL, 0);
2254  while (e = av_dict_iterate(tmp, e)) {
2255  if (!strcmp(e->key, "st") || !strcmp(e->key, "stg"))
2256  continue;
2257 
2258  av_log(mux, AV_LOG_FATAL, "Unknown group key %s.\n", e->key);
2259  ret = AVERROR(EINVAL);
2260  goto end;
2261  }
2262 
2263  ret = 0;
2264 end:
2265  av_dict_free(&dict);
2266  av_dict_free(&tmp);
2267 
2268  return ret;
2269 }
2270 
2271 static int of_add_groups(Muxer *mux, const OptionsContext *o)
2272 {
2273  /* process manually set groups */
2274  for (int i = 0; i < o->stream_groups.nb_opt; i++) {
2275  const char *token;
2276  char *str, *ptr = NULL;
2277  int ret = 0;
2278 
2279  str = av_strdup(o->stream_groups.opt[i].u.str);
2280  if (!str)
2281  return ret;
2282 
2283  token = av_strtok(str, ",", &ptr);
2284  if (token) {
2285  if (ptr)
2286  ptr += strspn(ptr, " \n\t\r");
2287  ret = of_parse_group_token(mux, token, ptr);
2288  }
2289 
2290  av_free(str);
2291  if (ret < 0)
2292  return ret;
2293  }
2294 
2295  return 0;
2296 }
2297 
2298 static int of_add_programs(Muxer *mux, const OptionsContext *o)
2299 {
2300  AVFormatContext *oc = mux->fc;
2301  /* process manually set programs */
2302  for (int i = 0; i < o->program.nb_opt; i++) {
2303  AVDictionary *dict = NULL;
2304  const AVDictionaryEntry *e;
2305  AVProgram *program;
2306  int ret, progid = i + 1;
2307 
2308  ret = av_dict_parse_string(&dict, o->program.opt[i].u.str, "=", ":",
2310  if (ret < 0) {
2311  av_log(mux, AV_LOG_ERROR, "Error parsing program specification %s\n",
2312  o->program.opt[i].u.str);
2313  return ret;
2314  }
2315 
2316  e = av_dict_get(dict, "program_num", NULL, 0);
2317  if (e) {
2318  progid = strtol(e->value, NULL, 0);
2319  av_dict_set(&dict, e->key, NULL, 0);
2320  }
2321 
2322  program = av_new_program(oc, progid);
2323  if (!program) {
2324  ret = AVERROR(ENOMEM);
2325  goto fail;
2326  }
2327 
2328  e = av_dict_get(dict, "title", NULL, 0);
2329  if (e) {
2330  av_dict_set(&program->metadata, e->key, e->value, 0);
2331  av_dict_set(&dict, e->key, NULL, 0);
2332  }
2333 
2334  e = NULL;
2335  while (e = av_dict_get(dict, "st", e, 0)) {
2336  int st_num = strtol(e->value, NULL, 0);
2337  av_program_add_stream_index(oc, progid, st_num);
2338  }
2339 
2340  // make sure that nothing but "st" entries are left in the dict
2341  e = NULL;
2342  while (e = av_dict_iterate(dict, e)) {
2343  if (!strcmp(e->key, "st"))
2344  continue;
2345 
2346  av_log(mux, AV_LOG_FATAL, "Unknown program key %s.\n", e->key);
2347  ret = AVERROR(EINVAL);
2348  goto fail;
2349  }
2350 
2351 fail:
2352  av_dict_free(&dict);
2353  if (ret < 0)
2354  return ret;
2355  }
2356 
2357  return 0;
2358 }
2359 
2360 /**
2361  * Parse a metadata specifier passed as 'arg' parameter.
2362  * @param arg metadata string to parse
2363  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
2364  * @param index for type c/p, chapter/program index is written here
2365  * @param stream_spec for type s, the stream specifier is written here
2366  */
2367 static int parse_meta_type(void *logctx, const char *arg,
2368  char *type, int *index, const char **stream_spec)
2369 {
2370  if (*arg) {
2371  *type = *arg;
2372  switch (*arg) {
2373  case 'g':
2374  break;
2375  case 's':
2376  if (*(++arg) && *arg != ':') {
2377  av_log(logctx, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
2378  return AVERROR(EINVAL);
2379  }
2380  *stream_spec = *arg == ':' ? arg + 1 : "";
2381  break;
2382  case 'c':
2383  case 'p':
2384  if (*(++arg) == ':')
2385  *index = strtol(++arg, NULL, 0);
2386  break;
2387  default:
2388  av_log(logctx, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
2389  return AVERROR(EINVAL);
2390  }
2391  } else
2392  *type = 'g';
2393 
2394  return 0;
2395 }
2396 
2398  const OptionsContext *o)
2399 {
2400  for (int i = 0; i < o->metadata.nb_opt; i++) {
2401  AVDictionary **m;
2402  char type, *val;
2403  const char *stream_spec;
2404  int index = 0, ret = 0;
2405 
2406  val = strchr(o->metadata.opt[i].u.str, '=');
2407  if (!val) {
2408  av_log(of, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
2409  o->metadata.opt[i].u.str);
2410  return AVERROR(EINVAL);
2411  }
2412  *val++ = 0;
2413 
2414  ret = parse_meta_type(of, o->metadata.opt[i].specifier, &type, &index, &stream_spec);
2415  if (ret < 0)
2416  return ret;
2417 
2418  if (type == 's') {
2419  for (int j = 0; j < oc->nb_streams; j++) {
2420  if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
2421  av_dict_set(&oc->streams[j]->metadata, o->metadata.opt[i].u.str, *val ? val : NULL, 0);
2422  } else if (ret < 0)
2423  return ret;
2424  }
2425  } else {
2426  switch (type) {
2427  case 'g':
2428  m = &oc->metadata;
2429  break;
2430  case 'c':
2431  if (index < 0 || index >= oc->nb_chapters) {
2432  av_log(of, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
2433  return AVERROR(EINVAL);
2434  }
2435  m = &oc->chapters[index]->metadata;
2436  break;
2437  case 'p':
2438  if (index < 0 || index >= oc->nb_programs) {
2439  av_log(of, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
2440  return AVERROR(EINVAL);
2441  }
2442  m = &oc->programs[index]->metadata;
2443  break;
2444  default:
2445  av_log(of, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata.opt[i].specifier);
2446  return AVERROR(EINVAL);
2447  }
2448  av_dict_set(m, o->metadata.opt[i].u.str, *val ? val : NULL, 0);
2449  }
2450  }
2451 
2452  return 0;
2453 }
2454 
2455 static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os,
2456  int copy_metadata)
2457 {
2458  AVFormatContext *is = ifile->ctx;
2459  AVChapter **tmp;
2460 
2461  tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
2462  if (!tmp)
2463  return AVERROR(ENOMEM);
2464  os->chapters = tmp;
2465 
2466  for (int i = 0; i < is->nb_chapters; i++) {
2467  AVChapter *in_ch = is->chapters[i], *out_ch;
2468  int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
2469  int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
2470  AV_TIME_BASE_Q, in_ch->time_base);
2471  int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
2473 
2474 
2475  if (in_ch->end < ts_off)
2476  continue;
2477  if (rt != INT64_MAX && in_ch->start > rt + ts_off)
2478  break;
2479 
2480  out_ch = av_mallocz(sizeof(AVChapter));
2481  if (!out_ch)
2482  return AVERROR(ENOMEM);
2483 
2484  out_ch->id = in_ch->id;
2485  out_ch->time_base = in_ch->time_base;
2486  out_ch->start = FFMAX(0, in_ch->start - ts_off);
2487  out_ch->end = FFMIN(rt, in_ch->end - ts_off);
2488 
2489  if (copy_metadata)
2490  av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
2491 
2492  os->chapters[os->nb_chapters++] = out_ch;
2493  }
2494  return 0;
2495 }
2496 
2497 static int copy_metadata(Muxer *mux, AVFormatContext *ic,
2498  const char *outspec, const char *inspec,
2499  int *metadata_global_manual, int *metadata_streams_manual,
2500  int *metadata_chapters_manual)
2501 {
2502  AVFormatContext *oc = mux->fc;
2503  AVDictionary **meta_in = NULL;
2504  AVDictionary **meta_out = NULL;
2505  int i, ret = 0;
2506  char type_in, type_out;
2507  const char *istream_spec = NULL, *ostream_spec = NULL;
2508  int idx_in = 0, idx_out = 0;
2509 
2510  ret = parse_meta_type(mux, inspec, &type_in, &idx_in, &istream_spec);
2511  if (ret >= 0)
2512  ret = parse_meta_type(mux, outspec, &type_out, &idx_out, &ostream_spec);
2513  if (ret < 0)
2514  return ret;
2515 
2516  if (type_in == 'g' || type_out == 'g' || (!*outspec && !ic))
2517  *metadata_global_manual = 1;
2518  if (type_in == 's' || type_out == 's' || (!*outspec && !ic))
2519  *metadata_streams_manual = 1;
2520  if (type_in == 'c' || type_out == 'c' || (!*outspec && !ic))
2521  *metadata_chapters_manual = 1;
2522 
2523  /* ic is NULL when just disabling automatic mappings */
2524  if (!ic)
2525  return 0;
2526 
2527 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
2528  if ((index) < 0 || (index) >= (nb_elems)) {\
2529  av_log(mux, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
2530  (desc), (index));\
2531  return AVERROR(EINVAL);\
2532  }
2533 
2534 #define SET_DICT(type, meta, context, index)\
2535  switch (type) {\
2536  case 'g':\
2537  meta = &context->metadata;\
2538  break;\
2539  case 'c':\
2540  METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
2541  meta = &context->chapters[index]->metadata;\
2542  break;\
2543  case 'p':\
2544  METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
2545  meta = &context->programs[index]->metadata;\
2546  break;\
2547  case 's':\
2548  break; /* handled separately below */ \
2549  default: av_assert0(0);\
2550  }\
2551 
2552  SET_DICT(type_in, meta_in, ic, idx_in);
2553  SET_DICT(type_out, meta_out, oc, idx_out);
2554 
2555  /* for input streams choose first matching stream */
2556  if (type_in == 's') {
2557  for (i = 0; i < ic->nb_streams; i++) {
2558  if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
2559  meta_in = &ic->streams[i]->metadata;
2560  break;
2561  } else if (ret < 0)
2562  return ret;
2563  }
2564  if (!meta_in) {
2565  av_log(mux, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
2566  return AVERROR(EINVAL);
2567  }
2568  }
2569 
2570  if (type_out == 's') {
2571  for (i = 0; i < oc->nb_streams; i++) {
2572  if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
2573  meta_out = &oc->streams[i]->metadata;
2574  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
2575  } else if (ret < 0)
2576  return ret;
2577  }
2578  } else
2579  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
2580 
2581  return 0;
2582 }
2583 
2584 static int copy_meta(Muxer *mux, const OptionsContext *o)
2585 {
2586  OutputFile *of = &mux->of;
2587  AVFormatContext *oc = mux->fc;
2588  int chapters_input_file = o->chapters_input_file;
2589  int metadata_global_manual = 0;
2590  int metadata_streams_manual = 0;
2591  int metadata_chapters_manual = 0;
2592  int ret;
2593 
2594  /* copy metadata */
2595  for (int i = 0; i < o->metadata_map.nb_opt; i++) {
2596  char *p;
2597  int in_file_index = strtol(o->metadata_map.opt[i].u.str, &p, 0);
2598 
2599  if (in_file_index >= nb_input_files) {
2600  av_log(mux, AV_LOG_FATAL, "Invalid input file index %d while "
2601  "processing metadata maps\n", in_file_index);
2602  return AVERROR(EINVAL);
2603  }
2604  ret = copy_metadata(mux,
2605  in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL,
2606  o->metadata_map.opt[i].specifier, *p ? p + 1 : p,
2607  &metadata_global_manual, &metadata_streams_manual,
2608  &metadata_chapters_manual);
2609  if (ret < 0)
2610  return ret;
2611  }
2612 
2613  /* copy chapters */
2614  if (chapters_input_file >= nb_input_files) {
2615  if (chapters_input_file == INT_MAX) {
2616  /* copy chapters from the first input file that has them*/
2617  chapters_input_file = -1;
2618  for (int i = 0; i < nb_input_files; i++)
2619  if (input_files[i]->ctx->nb_chapters) {
2620  chapters_input_file = i;
2621  break;
2622  }
2623  } else {
2624  av_log(mux, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
2625  chapters_input_file);
2626  return AVERROR(EINVAL);
2627  }
2628  }
2629  if (chapters_input_file >= 0)
2630  copy_chapters(input_files[chapters_input_file], of, oc,
2631  !metadata_chapters_manual);
2632 
2633  /* copy global metadata by default */
2634  if (!metadata_global_manual && nb_input_files){
2637  if (of->recording_time != INT64_MAX)
2638  av_dict_set(&oc->metadata, "duration", NULL, 0);
2639  av_dict_set(&oc->metadata, "creation_time", NULL, 0);
2640  av_dict_set(&oc->metadata, "company_name", NULL, 0);
2641  av_dict_set(&oc->metadata, "product_name", NULL, 0);
2642  av_dict_set(&oc->metadata, "product_version", NULL, 0);
2643  }
2644  if (!metadata_streams_manual)
2645  for (int i = 0; i < of->nb_streams; i++) {
2646  OutputStream *ost = of->streams[i];
2647 
2648  if (!ost->ist) /* this is true e.g. for attached files */
2649  continue;
2651  if (ost->enc_ctx) {
2652  av_dict_set(&ost->st->metadata, "encoder", NULL, 0);
2653  }
2654  }
2655 
2656  return 0;
2657 }
2658 
2659 static int set_dispositions(Muxer *mux, const OptionsContext *o)
2660 {
2661  OutputFile *of = &mux->of;
2662  AVFormatContext *ctx = mux->fc;
2663 
2664  // indexed by type+1, because AVMEDIA_TYPE_UNKNOWN=-1
2665  int nb_streams[AVMEDIA_TYPE_NB + 1] = { 0 };
2666  int have_default[AVMEDIA_TYPE_NB + 1] = { 0 };
2667  int have_manual = 0;
2668  int ret = 0;
2669 
2670  const char **dispositions;
2671 
2672  dispositions = av_calloc(ctx->nb_streams, sizeof(*dispositions));
2673  if (!dispositions)
2674  return AVERROR(ENOMEM);
2675 
2676  // first, copy the input dispositions
2677  for (int i = 0; i < ctx->nb_streams; i++) {
2678  OutputStream *ost = of->streams[i];
2679 
2680  nb_streams[ost->type + 1]++;
2681 
2682  MATCH_PER_STREAM_OPT(disposition, str, dispositions[i], ctx, ost->st);
2683 
2684  have_manual |= !!dispositions[i];
2685 
2686  if (ost->ist) {
2687  ost->st->disposition = ost->ist->st->disposition;
2688 
2690  have_default[ost->type + 1] = 1;
2691  }
2692  }
2693 
2694  if (have_manual) {
2695  // process manually set dispositions - they override the above copy
2696  for (int i = 0; i < ctx->nb_streams; i++) {
2697  OutputStream *ost = of->streams[i];
2698  const char *disp = dispositions[i];
2699 
2700  if (!disp)
2701  continue;
2702 
2703  ret = av_opt_set(ost->st, "disposition", disp, 0);
2704  if (ret < 0)
2705  goto finish;
2706  }
2707  } else {
2708  // For each media type with more than one stream, find a suitable stream to
2709  // mark as default, unless one is already marked default.
2710  // "Suitable" means the first of that type, skipping attached pictures.
2711  for (int i = 0; i < ctx->nb_streams; i++) {
2712  OutputStream *ost = of->streams[i];
2713  enum AVMediaType type = ost->type;
2714 
2715  if (nb_streams[type + 1] < 2 || have_default[type + 1] ||
2717  continue;
2718 
2720  have_default[type + 1] = 1;
2721  }
2722  }
2723 
2724 finish:
2725  av_freep(&dispositions);
2726 
2727  return ret;
2728 }
2729 
2730 const char *const forced_keyframes_const_names[] = {
2731  "n",
2732  "n_forced",
2733  "prev_forced_n",
2734  "prev_forced_t",
2735  "t",
2736  NULL
2737 };
2738 
2739 static int compare_int64(const void *a, const void *b)
2740 {
2741  return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
2742 }
2743 
2745  const Muxer *mux, const char *spec)
2746 {
2747  const char *p;
2748  int n = 1, i, ret, size, index = 0;
2749  int64_t t, *pts;
2750 
2751  for (p = spec; *p; p++)
2752  if (*p == ',')
2753  n++;
2754  size = n;
2755  pts = av_malloc_array(size, sizeof(*pts));
2756  if (!pts)
2757  return AVERROR(ENOMEM);
2758 
2759  p = spec;
2760  for (i = 0; i < n; i++) {
2761  char *next = strchr(p, ',');
2762 
2763  if (next)
2764  *next++ = 0;
2765 
2766  if (strstr(p, "chapters") == p) {
2767  AVChapter * const *ch = mux->fc->chapters;
2768  unsigned int nb_ch = mux->fc->nb_chapters;
2769  int j;
2770 
2771  if (nb_ch > INT_MAX - size ||
2772  !(pts = av_realloc_f(pts, size += nb_ch - 1,
2773  sizeof(*pts))))
2774  return AVERROR(ENOMEM);
2775 
2776  if (p[8]) {
2777  ret = av_parse_time(&t, p + 8, 1);
2778  if (ret < 0) {
2780  "Invalid chapter time offset: %s\n", p + 8);
2781  goto fail;
2782  }
2783  } else
2784  t = 0;
2785 
2786  for (j = 0; j < nb_ch; j++) {
2787  const AVChapter *c = ch[j];
2788  av_assert1(index < size);
2789  pts[index++] = av_rescale_q(c->start, c->time_base,
2790  AV_TIME_BASE_Q) + t;
2791  }
2792 
2793  } else {
2794  av_assert1(index < size);
2795  ret = av_parse_time(&t, p, 1);
2796  if (ret < 0) {
2797  av_log(log, AV_LOG_ERROR, "Invalid keyframe time: %s\n", p);
2798  goto fail;
2799  }
2800 
2801  pts[index++] = t;
2802  }
2803 
2804  p = next;
2805  }
2806 
2807  av_assert0(index == size);
2808  qsort(pts, size, sizeof(*pts), compare_int64);
2809  kf->nb_pts = size;
2810  kf->pts = pts;
2811 
2812  return 0;
2813 fail:
2814  av_freep(&pts);
2815  return ret;
2816 }
2817 
2819 {
2820  for (int i = 0; i < mux->of.nb_streams; i++) {
2821  OutputStream *ost = mux->of.streams[i];
2822  const char *forced_keyframes = NULL;
2823 
2824  MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_keyframes, mux->fc, ost->st);
2825 
2826  if (!(ost->type == AVMEDIA_TYPE_VIDEO &&
2827  ost->enc_ctx && forced_keyframes))
2828  continue;
2829 
2830  if (!strncmp(forced_keyframes, "expr:", 5)) {
2831  int ret = av_expr_parse(&ost->kf.pexpr, forced_keyframes + 5,
2833  if (ret < 0) {
2835  "Invalid force_key_frames expression '%s'\n", forced_keyframes + 5);
2836  return ret;
2837  }
2838  ost->kf.expr_const_values[FKF_N] = 0;
2839  ost->kf.expr_const_values[FKF_N_FORCED] = 0;
2840  ost->kf.expr_const_values[FKF_PREV_FORCED_N] = NAN;
2841  ost->kf.expr_const_values[FKF_PREV_FORCED_T] = NAN;
2842 
2843  // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
2844  // parse it only for static kf timings
2845  } else if (!strcmp(forced_keyframes, "source")) {
2846  ost->kf.type = KF_FORCE_SOURCE;
2847 #if FFMPEG_OPT_FORCE_KF_SOURCE_NO_DROP
2848  } else if (!strcmp(forced_keyframes, "source_no_drop")) {
2849  av_log(ost, AV_LOG_WARNING, "The 'source_no_drop' value for "
2850  "-force_key_frames is deprecated, use just 'source'\n");
2851  ost->kf.type = KF_FORCE_SOURCE;
2852 #endif
2853  } else {
2854  int ret = parse_forced_key_frames(ost, &ost->kf, mux, forced_keyframes);
2855  if (ret < 0)
2856  return ret;
2857  }
2858  }
2859 
2860  return 0;
2861 }
2862 
2863 static int validate_enc_avopt(Muxer *mux, const AVDictionary *codec_avopt)
2864 {
2865  const AVClass *class = avcodec_get_class();
2866  const AVClass *fclass = avformat_get_class();
2867  const OutputFile *of = &mux->of;
2868 
2869  AVDictionary *unused_opts;
2870  const AVDictionaryEntry *e;
2871 
2872  unused_opts = strip_specifiers(codec_avopt);
2873  for (int i = 0; i < of->nb_streams; i++) {
2874  e = NULL;
2875  while ((e = av_dict_iterate(of->streams[i]->encoder_opts, e)))
2876  av_dict_set(&unused_opts, e->key, NULL, 0);
2877  }
2878 
2879  e = NULL;
2880  while ((e = av_dict_iterate(unused_opts, e))) {
2881  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
2883  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
2885  if (!option || foption)
2886  continue;
2887 
2888  if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
2889  av_log(mux, AV_LOG_ERROR, "Codec AVOption %s (%s) is not an "
2890  "encoding option.\n", e->key, option->help ? option->help : "");
2891  return AVERROR(EINVAL);
2892  }
2893 
2894  // gop_timecode is injected by generic code but not always used
2895  if (!strcmp(e->key, "gop_timecode"))
2896  continue;
2897 
2898  av_log(mux, AV_LOG_WARNING, "Codec AVOption %s (%s) has not been used "
2899  "for any stream. The most likely reason is either wrong type "
2900  "(e.g. a video option with no video streams) or that it is a "
2901  "private option of some encoder which was not actually used for "
2902  "any stream.\n", e->key, option->help ? option->help : "");
2903  }
2904  av_dict_free(&unused_opts);
2905 
2906  return 0;
2907 }
2908 
2909 static const char *output_file_item_name(void *obj)
2910 {
2911  const Muxer *mux = obj;
2912 
2913  return mux->log_name;
2914 }
2915 
2916 static const AVClass output_file_class = {
2917  .class_name = "OutputFile",
2918  .version = LIBAVUTIL_VERSION_INT,
2919  .item_name = output_file_item_name,
2920  .category = AV_CLASS_CATEGORY_MUXER,
2921 };
2922 
2923 static Muxer *mux_alloc(void)
2924 {
2925  Muxer *mux = allocate_array_elem(&output_files, sizeof(*mux), &nb_output_files);
2926 
2927  if (!mux)
2928  return NULL;
2929 
2930  mux->of.class = &output_file_class;
2931  mux->of.index = nb_output_files - 1;
2932 
2933  snprintf(mux->log_name, sizeof(mux->log_name), "out#%d", mux->of.index);
2934 
2935  return mux;
2936 }
2937 
2938 int of_open(const OptionsContext *o, const char *filename, Scheduler *sch)
2939 {
2940  Muxer *mux;
2941  AVFormatContext *oc;
2942  int err;
2943  OutputFile *of;
2944 
2945  int64_t recording_time = o->recording_time;
2946  int64_t stop_time = o->stop_time;
2947 
2948  mux = mux_alloc();
2949  if (!mux)
2950  return AVERROR(ENOMEM);
2951 
2952  of = &mux->of;
2953 
2954  if (stop_time != INT64_MAX && recording_time != INT64_MAX) {
2955  stop_time = INT64_MAX;
2956  av_log(mux, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
2957  }
2958 
2959  if (stop_time != INT64_MAX && recording_time == INT64_MAX) {
2961  if (stop_time <= start_time) {
2962  av_log(mux, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
2963  return AVERROR(EINVAL);
2964  } else {
2965  recording_time = stop_time - start_time;
2966  }
2967  }
2968 
2969  of->recording_time = recording_time;
2970  of->start_time = o->start_time;
2971  of->shortest = o->shortest;
2972 
2973  mux->limit_filesize = o->limit_filesize;
2974  av_dict_copy(&mux->opts, o->g->format_opts, 0);
2975 
2976  if (!strcmp(filename, "-"))
2977  filename = "pipe:";
2978 
2979  err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
2980  if (!oc) {
2981  av_log(mux, AV_LOG_FATAL, "Error initializing the muxer for %s: %s\n",
2982  filename, av_err2str(err));
2983  return err;
2984  }
2985  mux->fc = oc;
2986 
2987  av_strlcat(mux->log_name, "/", sizeof(mux->log_name));
2988  av_strlcat(mux->log_name, oc->oformat->name, sizeof(mux->log_name));
2989 
2990 
2991  of->format = oc->oformat;
2992  if (recording_time != INT64_MAX)
2993  oc->duration = recording_time;
2994 
2995  oc->interrupt_callback = int_cb;
2996 
2997  if (o->bitexact) {
2998  oc->flags |= AVFMT_FLAG_BITEXACT;
2999  of->bitexact = 1;
3000  } else {
3001  of->bitexact = check_opt_bitexact(oc, mux->opts, "fflags",
3003  }
3004 
3005  err = sch_add_mux(sch, muxer_thread, mux_check_init, mux,
3006  !strcmp(oc->oformat->name, "rtp"), o->thread_queue_size);
3007  if (err < 0)
3008  return err;
3009  mux->sch = sch;
3010  mux->sch_idx = err;
3011 
3012  /* create all output streams for this file */
3013  err = create_streams(mux, o);
3014  if (err < 0)
3015  return err;
3016 
3017  /* check if all codec options have been used */
3018  err = validate_enc_avopt(mux, o->g->codec_opts);
3019  if (err < 0)
3020  return err;
3021 
3022  /* check filename in case of an image number is expected */
3024  av_log(mux, AV_LOG_FATAL,
3025  "Output filename '%s' does not contain a numeric pattern like "
3026  "'%%d', which is required by output format '%s'.\n",
3027  oc->url, oc->oformat->name);
3028  return AVERROR(EINVAL);
3029  }
3030 
3031  if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3032  /* test if it already exists to avoid losing precious files */
3033  err = assert_file_overwrite(filename);
3034  if (err < 0)
3035  return err;
3036 
3037  /* open the file */
3038  if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
3039  &oc->interrupt_callback,
3040  &mux->opts)) < 0) {
3041  av_log(mux, AV_LOG_FATAL, "Error opening output %s: %s\n",
3042  filename, av_err2str(err));
3043  return err;
3044  }
3045  } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename)) {
3046  err = assert_file_overwrite(filename);
3047  if (err < 0)
3048  return err;
3049  }
3050 
3051  if (o->mux_preload) {
3052  av_dict_set_int(&mux->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
3053  }
3054  oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
3055 
3056  /* copy metadata and chapters from input files */
3057  err = copy_meta(mux, o);
3058  if (err < 0)
3059  return err;
3060 
3061  err = of_add_groups(mux, o);
3062  if (err < 0)
3063  return err;
3064 
3065  err = of_add_programs(mux, o);
3066  if (err < 0)
3067  return err;
3068 
3069  err = of_add_metadata(of, oc, o);
3070  if (err < 0)
3071  return err;
3072 
3073  err = set_dispositions(mux, o);
3074  if (err < 0) {
3075  av_log(mux, AV_LOG_FATAL, "Error setting output stream dispositions\n");
3076  return err;
3077  }
3078 
3079  // parse forced keyframe specifications;
3080  // must be done after chapters are created
3081  err = process_forced_keyframes(mux, o);
3082  if (err < 0) {
3083  av_log(mux, AV_LOG_FATAL, "Error processing forced keyframes\n");
3084  return err;
3085  }
3086 
3088  if (err < 0) {
3089  av_log(mux, AV_LOG_FATAL, "Error setting up output sync queues\n");
3090  return err;
3091  }
3092 
3093  of->url = filename;
3094 
3095  /* initialize streamcopy streams. */
3096  for (int i = 0; i < of->nb_streams; i++) {
3097  OutputStream *ost = of->streams[i];
3098 
3099  if (!ost->enc) {
3100  err = of_stream_init(of, ost);
3101  if (err < 0)
3102  return err;
3103  }
3104  }
3105 
3106  return 0;
3107 }
AV_OPT_SEARCH_CHILDREN
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition: opt.h:522
choose_encoder
static int choose_encoder(const OptionsContext *o, AVFormatContext *s, OutputStream *ost, const AVCodec **enc)
Definition: ffmpeg_mux_init.c:69
formats
formats
Definition: signature.h:48
KeyframeForceCtx::pts
int64_t * pts
Definition: ffmpeg.h:483
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:65
streamcopy_init
static int streamcopy_init(const Muxer *mux, OutputStream *ost)
Definition: ffmpeg_mux_init.c:910
map_manual
static int map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
Definition: ffmpeg_mux_init.c:1597
SYNC_QUEUE_PACKETS
@ SYNC_QUEUE_PACKETS
Definition: sync_queue.h:29
AVCodec
AVCodec.
Definition: codec.h:187
fix_sub_duration_heartbeat
static int fix_sub_duration_heartbeat(DecoderPriv *dp, int64_t signal_pts)
Definition: ffmpeg_dec.c:572
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
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:75
MuxStream::sch_idx_enc
int sch_idx_enc
Definition: ffmpeg_mux.h:50
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AVIAMFAudioElement::nb_layers
unsigned int nb_layers
Number of layers, or channel groups, in the Audio Element.
Definition: iamf.h:368
AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_UNLIMITED
InputFile::start_time
int64_t start_time
Definition: ffmpeg.h:403
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:71
Muxer::fc
AVFormatContext * fc
Definition: ffmpeg_mux.h:86
AVFormatContext::stream_groups
AVStreamGroup ** stream_groups
A list of all stream groups in the file.
Definition: avformat.h:1342
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:168
ost_get_filters
static int ost_get_filters(const OptionsContext *o, AVFormatContext *oc, OutputStream *ost, char **dst)
Definition: ffmpeg_mux_init.c:415
AVStreamGroup::id
int64_t id
Group type-specific group ID.
Definition: avformat.h:1109
AV_CODEC_ID_AC3
@ AV_CODEC_ID_AC3
Definition: codec_id.h:443
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:273
FKF_PREV_FORCED_T
@ FKF_PREV_FORCED_T
Definition: ffmpeg.h:416
VSYNC_VFR
@ VSYNC_VFR
Definition: ffmpeg.h:69
mix
static int mix(int c0, int c1)
Definition: 4xm.c:715
ms_from_ost
static MuxStream * ms_from_ost(OutputStream *ost)
Definition: ffmpeg_mux.h:108
AVOutputFormat::name
const char * name
Definition: avformat.h:510
AVChapter::metadata
AVDictionary * metadata
Definition: avformat.h:1218
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:126
opt.h
OutputStream::enc
AVCodecContext * enc
Definition: mux.c:55
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:51
MATCH_PER_STREAM_OPT
#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)
Definition: ffmpeg.h:831
ofilter_bind_ost
int ofilter_bind_ost(OutputFilter *ofilter, OutputStream *ost, unsigned sched_idx_enc)
Definition: ffmpeg_filter.c:765
MuxStream::sch_idx
int sch_idx
Definition: ffmpeg_mux.h:49
AVSTREAM_EVENT_FLAG_NEW_PACKETS
#define AVSTREAM_EVENT_FLAG_NEW_PACKETS
Definition: avformat.h:899
ENC_STATS_PTS
@ ENC_STATS_PTS
Definition: ffmpeg.h:432
Muxer::sch_stream_idx
int * sch_stream_idx
Definition: ffmpeg_mux.h:92
ENC_STATS_FRAME_NUM_IN
@ ENC_STATS_FRAME_NUM_IN
Definition: ffmpeg.h:429
AVCodecContext::sample_rate
int sample_rate
samples per second
Definition: avcodec.h:1050
FKF_PREV_FORCED_N
@ FKF_PREV_FORCED_N
Definition: ffmpeg.h:415
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:1355
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:47
Muxer::nb_sch_stream_idx
int nb_sch_stream_idx
Definition: ffmpeg_mux.h:93
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
sample_fmts
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:947
enc_open
int enc_open(void *opaque, const AVFrame *frame)
Definition: ffmpeg_enc.c:168
av_pix_fmt_desc_get
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2962
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:674
ENC_STATS_DTS
@ ENC_STATS_DTS
Definition: ffmpeg.h:436
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:649
pthread_mutex_init
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:104
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:1949
KeyframeForceCtx::nb_pts
int nb_pts
Definition: ffmpeg.h:484
AV_CODEC_FLAG_QSCALE
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition: avcodec.h:224
SCH_DSTREAM
#define SCH_DSTREAM(file, stream)
Definition: ffmpeg_sched.h:107
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:264
int64_t
long long int64_t
Definition: coverity.c:34
InputStream::user_set_discard
int user_set_discard
Definition: ffmpeg.h:354
FFMPEG_OPT_ENC_TIME_BASE_NUM
#define FFMPEG_OPT_ENC_TIME_BASE_NUM
Definition: ffmpeg.h:56
ENC_STATS_AVG_BITRATE
@ ENC_STATS_AVG_BITRATE
Definition: ffmpeg.h:442
AVCodecContext::intra_matrix
uint16_t * intra_matrix
custom intra quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition: avcodec.h:974
avformat_get_class
const AVClass * avformat_get_class(void)
Get the AVClass for AVFormatContext.
Definition: options.c:196
ist_iter
InputStream * ist_iter(InputStream *prev)
Definition: ffmpeg.c:397
parse_and_set_vsync
int parse_and_set_vsync(const char *arg, int *vsync_var, int file_idx, int st_idx, int is_global)
Definition: ffmpeg_opt.c:192
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:621
OptionsContext::nb_attachments
int nb_attachments
Definition: ffmpeg.h:163
AVCodec::pix_fmts
enum AVPixelFormat * pix_fmts
array of supported pixel formats, or NULL if unknown, array is terminated by -1
Definition: codec.h:209
OutputFile::start_time
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:586
avcodec_find_encoder
const AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
Definition: allcodecs.c:966
audio_channels
int audio_channels
Definition: rtp.c:40
InputFile::index
int index
Definition: ffmpeg.h:392
tmp
static uint8_t tmp[11]
Definition: aes_ctr.c:28
pixdesc.h
AVFormatContext::streams
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1323
OptionsContext::mux_max_delay
float mux_max_delay
Definition: ffmpeg.h:171
AVPacketSideData
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition: packet.h:373
subtitle_codec_name
static const char * subtitle_codec_name
Definition: ffplay.c:343
new_stream_video
static int new_stream_video(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:582
ENC_STATS_LITERAL
@ ENC_STATS_LITERAL
Definition: ffmpeg.h:425
OptionsContext::subtitle_disable
int subtitle_disable
Definition: ffmpeg.h:178
AVOption
AVOption.
Definition: opt.h:346
OutputStream::index
int index
Definition: ffmpeg.h:503
b
#define b
Definition: input.c:41
FilterGraph::index
int index
Definition: ffmpeg.h:288
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:832
AVChapter::start
int64_t start
Definition: avformat.h:1217
Muxer::of
OutputFile of
Definition: ffmpeg_mux.h:81
AV_DICT_APPEND
#define AV_DICT_APPEND
If the entry already exists, append to it.
Definition: dict.h:82
RcOverride::qscale
int qscale
Definition: avcodec.h:207
ffmpeg.h
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
base
uint8_t base
Definition: vp3data.h:128
freeenv_utf8
static void freeenv_utf8(char *var)
Definition: getenv_utf8.h:72
OptionGroup::swr_opts
AVDictionary * swr_opts
Definition: cmdutils.h:281
ost_add
static int ost_add(Muxer *mux, const OptionsContext *o, enum AVMediaType type, InputStream *ist, OutputFilter *ofilter, OutputStream **post)
Definition: ffmpeg_mux_init.c:1035
AVFormatContext::programs
AVProgram ** programs
Definition: avformat.h:1456
AVIAMFParamDefinition
Parameters as defined in section 3.6.1 of IAMF.
Definition: iamf.h:193
OptionsContext::bitexact
int bitexact
Definition: ffmpeg.h:174
AVCodecParameters::codec_tag
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:59
video_disable
static int video_disable
Definition: ffplay.c:318
AVDictionary
Definition: dict.c:34
AVChannelLayout::order
enum AVChannelOrder order
Channel order used in this layout.
Definition: channel_layout.h:308
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
MuxStream::copy_prior_start
int copy_prior_start
Definition: ffmpeg_mux.h:76
OptionsContext::format
const char * format
Definition: ffmpeg.h:130
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:2744
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:313
init_simple_filtergraph
int init_simple_filtergraph(InputStream *ist, OutputStream *ost, char *graph_desc, Scheduler *sch, unsigned sch_idx_enc)
Definition: ffmpeg_filter.c:1080
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:245
avio_size
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:322
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:486
OutputStream::ist
InputStream * ist
Definition: ffmpeg.h:514
set_dispositions
static int set_dispositions(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2659
MuxStream::ts_copy_start
int64_t ts_copy_start
Definition: ffmpeg_mux.h:60
OutputStream::file
struct OutputFile * file
Definition: ffmpeg.h:501
AVOutputFormat::subtitle_codec
enum AVCodecID subtitle_codec
default subtitle codec
Definition: avformat.h:522
MuxStream::stream_duration_tb
AVRational stream_duration_tb
Definition: ffmpeg_mux.h:67
ENC_STATS_TIMEBASE_IN
@ ENC_STATS_TIMEBASE_IN
Definition: ffmpeg.h:431
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:30
AV_CODEC_FLAG_GLOBAL_HEADER
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition: avcodec.h:338
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:125
OutputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:583
av_filename_number_test
int av_filename_number_test(const char *filename)
Check whether filename actually is a numbered sequence generator.
Definition: utils.c:126
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:711
Muxer
Definition: ffmpeg_mux.h:80
InputStream
Definition: ffmpeg.h:345
OptionsContext::chapters_input_file
int chapters_input_file
Definition: ffmpeg.h:165
AVPacketSideData::size
size_t size
Definition: packet.h:375
EncStatsFile
Definition: ffmpeg_mux_init.c:155
AVFormatContext::interrupt_callback
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1528
map_auto_subtitle
static int map_auto_subtitle(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1535
finish
static void finish(void)
Definition: movenc.c:342
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:454
of_parse_group_token
static int of_parse_group_token(Muxer *mux, const char *token, char *ptr)
Definition: ffmpeg_mux_init.c:2154
presets
static const Preset presets[]
Definition: vf_pseudocolor.c:286
OptionsContext::g
OptionGroup * g
Definition: ffmpeg.h:124
AVCodecContext::ch_layout
AVChannelLayout ch_layout
Audio channel layout.
Definition: avcodec.h:1065
mux_alloc
static Muxer * mux_alloc(void)
Definition: ffmpeg_mux_init.c:2923
fail
#define fail()
Definition: checkasm.h:179
AVIAMFSubmixLayout
Submix layout as defined in section 3.7.6 of IAMF.
Definition: iamf.h:510
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:644
copy_meta
static int copy_meta(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2584
AVCodecContext::flags
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:502
AVChapter
Definition: avformat.h:1214
val
static double val(void *priv, double ch)
Definition: aeval.c:78
SCH_ENC
#define SCH_ENC(encoder)
Definition: ffmpeg_sched.h:116
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:643
setup_sync_queues
static int setup_sync_queues(Muxer *mux, AVFormatContext *oc, int64_t buf_size_us)
Definition: ffmpeg_mux_init.c:1849
OptionsContext
Definition: ffmpeg.h:123
av_opt_set
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:738
av_new_program
AVProgram * av_new_program(AVFormatContext *ac, int id)
Definition: avformat.c:334
AV_CODEC_ID_MP3
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: codec_id.h:441
Muxer::sq_pkt
AVPacket * sq_pkt
Definition: ffmpeg_mux.h:103
AVStream::duration
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:802
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.
enc_stats_files
static EncStatsFile * enc_stats_files
Definition: ffmpeg_mux_init.c:160
AVRational::num
int num
Numerator.
Definition: rational.h:59
InputFile
Definition: ffmpeg.h:389
FFDIFFSIGN
#define FFDIFFSIGN(x, y)
Comparator.
Definition: macros.h:45
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:167
OptionsContext::nb_stream_maps
int nb_stream_maps
Definition: ffmpeg.h:161
OptionsContext::audio_disable
int audio_disable
Definition: ffmpeg.h:177
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:982
preset
preset
Definition: vf_curves.c:46
OutputFile::shortest
int shortest
Definition: ffmpeg.h:588
avassert.h
RcOverride::quality_factor
float quality_factor
Definition: avcodec.h:208
MuxStream::log_name
char log_name[32]
Definition: ffmpeg_mux.h:40
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
AVFormatContext::metadata
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1490
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
OptionGroup::codec_opts
AVDictionary * codec_opts
Definition: cmdutils.h:278
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:760
AVCodecTag
Definition: internal.h:42
ENC_STATS_PTS_IN
@ ENC_STATS_PTS_IN
Definition: ffmpeg.h:434
OptionsContext::metadata
SpecifierOptList metadata
Definition: ffmpeg.h:184
SpecifierOptList::nb_opt
int nb_opt
Definition: cmdutils.h:119
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:62
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:33
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:1083
output_stream_class
static const AVClass output_stream_class
Definition: ffmpeg_mux_init.c:384
VSYNC_VSCFR
@ VSYNC_VSCFR
Definition: ffmpeg.h:70
EncStats::components
EncStatsComponent * components
Definition: ffmpeg.h:454
of_parse_iamf_submixes
static int of_parse_iamf_submixes(Muxer *mux, AVStreamGroup *stg, char *ptr)
Definition: ffmpeg_mux_init.c:2025
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:614
AVChapter::end
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1217
SpecifierOpt::specifier
char * specifier
stream/chapter/program/...
Definition: cmdutils.h:106
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:391
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:620
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:1342
MuxStream::pkt
AVPacket * pkt
Definition: ffmpeg_mux.h:45
OptionsContext::stream_groups
SpecifierOptList stream_groups
Definition: ffmpeg.h:225
FilterGraph::outputs
OutputFilter ** outputs
Definition: ffmpeg.h:292
enc_stats_get_file
static int enc_stats_get_file(AVIOContext **io, const char *path)
Definition: ffmpeg_mux_init.c:163
of_add_groups
static int of_add_groups(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2271
InputStream::framerate
AVRational framerate
Definition: ffmpeg.h:366
av_realloc_array
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition: mem.c:215
AVFormatContext::flags
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1406
format
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 format(the sample packing is implied by the sample format) and sample rate. The lists are not just lists
AVCodecParameters::sample_aspect_ratio
AVRational sample_aspect_ratio
Video only.
Definition: codec_par.h:144
output_file_class
static const AVClass output_file_class
Definition: ffmpeg_mux_init.c:2916
AVFormatContext::nb_programs
unsigned int nb_programs
Definition: avformat.h:1455
RcOverride
Definition: avcodec.h:204
AVFormatContext::chapters
AVChapter ** chapters
Definition: avformat.h:1356
ENC_STATS_FILE_IDX
@ ENC_STATS_FILE_IDX
Definition: ffmpeg.h:426
AVDictionaryEntry::key
char * key
Definition: dict.h:90
frame_size
int frame_size
Definition: mxfenc.c:2422
OptionsContext::limit_filesize
int64_t limit_filesize
Definition: ffmpeg.h:169
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
AVCodecParameters::width
int width
Video only.
Definition: codec_par.h:134
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
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:112
OutputFilter::linklabel
uint8_t * linklabel
Definition: ffmpeg.h:278
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:178
get_line
static char * get_line(AVIOContext *s, AVBPrint *bprint)
Definition: ffmpeg_mux_init.c:112
filters
#define filters(fmt, type, inverse, clp, inverset, clip, one, clip_fn, packed)
Definition: af_crystalizer.c:54
ENC_STATS_BITRATE
@ ENC_STATS_BITRATE
Definition: ffmpeg.h:441
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
AVMEDIA_TYPE_NB
@ AVMEDIA_TYPE_NB
Definition: avutil.h:206
output_stream_item_name
static const char * output_stream_item_name(void *obj)
Definition: ffmpeg_mux_init.c:377
of_add_metadata
static int of_add_metadata(OutputFile *of, AVFormatContext *oc, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2397
AVIO_FLAG_WRITE
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:618
OutputFilter::ost
struct OutputStream * ost
Definition: ffmpeg.h:272
AVStreamGroup::index
unsigned int index
Group index in AVFormatContext.
Definition: avformat.h:1101
AVPacketSideData::data
uint8_t * data
Definition: packet.h:374
ignore_unknown_streams
int ignore_unknown_streams
Definition: ffmpeg_opt.c:91
ctx
AVFormatContext * ctx
Definition: movenc.c:48
RcOverride::start_frame
int start_frame
Definition: avcodec.h:205
channels
channels
Definition: aptx.h:31
nb_streams
static int nb_streams
Definition: ffprobe.c:383
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
choose_pixel_fmt
static enum AVPixelFormat choose_pixel_fmt(const AVCodec *codec, enum AVPixelFormat target)
Definition: ffmpeg_mux_init.c:514
KF_FORCE_SOURCE
@ KF_FORCE_SOURCE
Definition: ffmpeg.h:471
encoder_thread
int encoder_thread(void *arg)
Definition: ffmpeg_enc.c:881
OptionsContext::shortest
int shortest
Definition: ffmpeg.h:173
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:535
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:387
filter_codec_opts
int filter_codec_opts(const AVDictionary *opts, enum AVCodecID codec_id, AVFormatContext *s, AVStream *st, const AVCodec *codec, AVDictionary **dst)
Filter out options for given codec.
Definition: cmdutils.c:990
AVCodecParameters::nb_coded_side_data
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition: codec_par.h:86
AVMEDIA_TYPE_DATA
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition: avutil.h:203
NAN
#define NAN
Definition: mathematics.h:115
MuxStream::max_frames
int64_t max_frames
Definition: ffmpeg_mux.h:55
AVFMT_NEEDNUMBER
#define AVFMT_NEEDNUMBER
Needs 'd' in filename.
Definition: avformat.h:469
AVCodecContext::codec_id
enum AVCodecID codec_id
Definition: avcodec.h:455
Muxer::limit_filesize
int64_t limit_filesize
Definition: ffmpeg_mux.h:98
arg
const char * arg
Definition: jacosubdec.c:67
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
sq_add_stream
int sq_add_stream(SyncQueue *sq, int limiting)
Add a new stream to the sync queue.
Definition: sync_queue.c:620
option
option
Definition: libkvazaar.c:320
OptionsContext::start_time
int64_t start_time
Definition: ffmpeg.h:127
OutputStream::encoder_opts
AVDictionary * encoder_opts
Definition: ffmpeg.h:545
AVDISCARD_ALL
@ AVDISCARD_ALL
discard all
Definition: defs.h:219
AVFormatContext
Format I/O context.
Definition: avformat.h:1255
av_realloc_f
#define av_realloc_f(p, o, n)
Definition: tableprint_vlc.h:32
ENC_STATS_KEYFRAME
@ ENC_STATS_KEYFRAME
Definition: ffmpeg.h:443
OptionGroup::format_opts
AVDictionary * format_opts
Definition: cmdutils.h:279
opts
AVDictionary * opts
Definition: movenc.c:50
new_stream_subtitle
static int new_stream_subtitle(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:869
validate_enc_avopt
static int validate_enc_avopt(Muxer *mux, const AVDictionary *codec_avopt)
Definition: ffmpeg_mux_init.c:2863
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:766
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:66
avcodec_get_class
const AVClass * avcodec_get_class(void)
Get the AVClass for AVCodecContext.
Definition: options.c:185
OutputFilter::name
uint8_t * name
Definition: ffmpeg.h:274
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:2367
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:782
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:365
InputStream::st
AVStream * st
Definition: ffmpeg.h:353
AV_DICT_MULTIKEY
#define AV_DICT_MULTIKEY
Allow to store several equal keys in the dictionary.
Definition: dict.h:84
MuxStream::sch_idx_src
int sch_idx_src
Definition: ffmpeg_mux.h:51
map_auto_video
static int map_auto_video(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1438
nb_enc_stats_files
static int nb_enc_stats_files
Definition: ffmpeg_mux_init.c:161
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:761
ENC_STATS_PTS_TIME
@ ENC_STATS_PTS_TIME
Definition: ffmpeg.h:433
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
EncStats::lock
pthread_mutex_t lock
Definition: ffmpeg.h:459
AVPacketSideData::type
enum AVPacketSideDataType type
Definition: packet.h:376
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:237
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1297
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:103
parseutils.h
AVIAMFLayer
A layer defining a Channel Layout in the Audio Element.
Definition: iamf.h:294
EncStats
Definition: ffmpeg.h:453
OptionsContext::program
SpecifierOptList program
Definition: ffmpeg.h:224
EncStatsFile::io
AVIOContext * io
Definition: ffmpeg_mux_init.c:157
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:92
AVStream::metadata
AVDictionary * metadata
Definition: avformat.h:823
AV_OPT_SEARCH_FAKE_OBJ
#define AV_OPT_SEARCH_FAKE_OBJ
The obj passed to av_opt_find() is fake – only a double pointer to AVClass instead of a required poin...
Definition: opt.h:530
MuxStream::bsf_ctx
AVBSFContext * bsf_ctx
Definition: ffmpeg_mux.h:42
InputStream::fix_sub_duration
int fix_sub_duration
Definition: ffmpeg.h:373
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:128
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:589
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:185
Muxer::log_name
char log_name[32]
Definition: ffmpeg_mux.h:84
AVCodecParameters::ch_layout
AVChannelLayout ch_layout
Audio only.
Definition: codec_par.h:180
OutputFile::index
int index
Definition: ffmpeg.h:577
OutputFile::class
const AVClass * class
Definition: ffmpeg.h:575
FFMPEG_OPT_FILTER_SCRIPT
#define FFMPEG_OPT_FILTER_SCRIPT
Definition: ffmpeg.h:61
ENC_STATS_PTS_TIME_IN
@ ENC_STATS_PTS_TIME_IN
Definition: ffmpeg.h:435
FilterGraph::nb_outputs
int nb_outputs
Definition: ffmpeg.h:293
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:2497
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:269
index
int index
Definition: gxfenc.c:89
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:581
InputStream::par
AVCodecParameters * par
Codec parameters - to be used by the decoding/streamcopy code.
Definition: ffmpeg.h:361
input_files
InputFile ** input_files
Definition: ffmpeg.c:125
OutputFile::streams
OutputStream ** streams
Definition: ffmpeg.h:582
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
Scheduler
Definition: ffmpeg_sched.c:269
AVIAMFSubmixElement::audio_element_id
unsigned int audio_element_id
The id of the Audio Element this submix element references.
Definition: iamf.h:452
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:494
FilterGraph
Definition: ffmpeg.h:286
AVIAMFSubmix
Submix layout as defined in section 3.7 of IAMF.
Definition: iamf.h:552
file_read
char * file_read(const char *filename)
Definition: cmdutils.c:1132
AVFormatContext::nb_streams
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1311
ENC_TIME_BASE_DEMUX
@ ENC_TIME_BASE_DEMUX
Definition: ffmpeg.h:77
of_add_programs
static int of_add_programs(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2298
AVOutputFormat::flags
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS,...
Definition: avformat.h:529
codec_opts
AVDictionary * codec_opts
Definition: cmdutils.c:61
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:457
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:1950
frame_sizes
static const uint8_t frame_sizes[]
Definition: rtpdec_qcelp.c:24
f
f
Definition: af_crystalizer.c:121
AVIOContext
Bytestream IO Context.
Definition: avio.h:160
AVCodecContext::rc_override
RcOverride * rc_override
Definition: avcodec.h:1285
OptionsContext::thread_queue_size
int thread_queue_size
Definition: ffmpeg.h:148
AVMediaType
AVMediaType
Definition: avutil.h:199
Muxer::sq_mux
SyncQueue * sq_mux
Definition: ffmpeg_mux.h:102
av_bprint_finalize
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:240
output_files
OutputFile ** output_files
Definition: ffmpeg.c:128
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:121
start_time
static int64_t start_time
Definition: ffplay.c:329
AVFormatContext::url
char * url
input or output URL.
Definition: avformat.h:1371
EncStatsType
EncStatsType
Definition: ffmpeg.h:424
Muxer::sch
Scheduler * sch
Definition: ffmpeg_mux.h:88
AVCodecContext::sample_fmt
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1057
AV_SAMPLE_FMT_NONE
@ AV_SAMPLE_FMT_NONE
Definition: samplefmt.h:56
StreamMap
Definition: ffmpeg.h:116
ENC_STATS_NB_SAMPLES
@ ENC_STATS_NB_SAMPLES
Definition: ffmpeg.h:439
size
int size
Definition: twinvq_data.h:10344
copy_ts
int copy_ts
Definition: ffmpeg_opt.c:73
avio.h
copy_tb
int copy_tb
Definition: ffmpeg_opt.c:75
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
AVStreamGroup::iamf_audio_element
struct AVIAMFAudioElement * iamf_audio_element
Definition: avformat.h:1123
AVStream::event_flags
int event_flags
Flags indicating events happening on the stream, a combination of AVSTREAM_EVENT_FLAG_*.
Definition: avformat.h:886
OptionsContext::streamid
AVDictionary * streamid
Definition: ffmpeg.h:182
av_stream_get_codec_timebase
AVRational av_stream_get_codec_timebase(const AVStream *st)
Get the internal codec timebase from a stream.
Definition: avformat.c:848
OutputStream::type
enum AVMediaType type
Definition: ffmpeg.h:498
OutputFile::url
const char * url
Definition: ffmpeg.h:580
AVFMT_NOFILE
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:468
AVCodecContext::chroma_intra_matrix
uint16_t * chroma_intra_matrix
custom intra quantization matrix
Definition: avcodec.h:990
AVMEDIA_TYPE_UNKNOWN
@ AVMEDIA_TYPE_UNKNOWN
Usually treated as AVMEDIA_TYPE_DATA.
Definition: avutil.h:200
Muxer::opts
AVDictionary * opts
Definition: ffmpeg_mux.h:95
AVStream::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:821
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:1104
of_enc_stats_close
void of_enc_stats_close(void)
Definition: ffmpeg_mux_init.c:196
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:314
avio_r8
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:602
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:356
strip_specifiers
AVDictionary * strip_specifiers(const AVDictionary *dict)
Definition: ffmpeg_opt.c:162
SpecifierOptList::opt
SpecifierOpt * opt
Definition: cmdutils.h:118
SCH_DEC
#define SCH_DEC(decoder)
Definition: ffmpeg_sched.h:113
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.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:223
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
AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT
@ AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT
Definition: avformat.h:1082
AVStreamGroup::streams
AVStream ** streams
A list of streams in the group.
Definition: avformat.h:1156
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:89
ENC_STATS_FRAME_NUM
@ ENC_STATS_FRAME_NUM
Definition: ffmpeg.h:428
KeyframeForceCtx
Definition: ffmpeg.h:477
OutputFilter::type
enum AVMediaType type
Definition: ffmpeg.h:280
AVStreamGroup::iamf_mix_presentation
struct AVIAMFMixPresentation * iamf_mix_presentation
Definition: avformat.h:1124
mux_check_init
int mux_check_init(void *arg)
Definition: ffmpeg_mux.c:553
AVCodec::id
enum AVCodecID id
Definition: codec.h:201
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_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:56
flag
#define flag(name)
Definition: cbs_av1.c:474
avcodec_get_name
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:409
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:2938
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:302
bprint.h
map_auto_data
static int map_auto_data(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1574
AV_STREAM_GROUP_PARAMS_NONE
@ AV_STREAM_GROUP_PARAMS_NONE
Definition: avformat.h:1081
log.h
AVFMT_GLOBALHEADER
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:478
AV_CODEC_ID_NONE
@ AV_CODEC_ID_NONE
Definition: codec_id.h:50
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:255
RcOverride::end_frame
int end_frame
Definition: avcodec.h:206
AVChapter::id
int64_t id
unique ID to identify the chapter
Definition: avformat.h:1215
OptionsContext::codec_names
SpecifierOptList codec_names
Definition: ffmpeg.h:132
MuxStream::stats
EncStats stats
Definition: ffmpeg_mux.h:47
OptionsContext::stream_maps
StreamMap * stream_maps
Definition: ffmpeg.h:160
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:1921
pix_fmt_parse
static enum AVPixelFormat pix_fmt_parse(OutputStream *ost, const char *name)
Definition: ffmpeg_mux_init.c:539
AVCodecParameters::height
int height
Definition: codec_par.h:135
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:254
AVCodecParameters::block_align
int block_align
Audio only.
Definition: codec_par.h:191
VSYNC_CFR
@ VSYNC_CFR
Definition: ffmpeg.h:68
OptionsContext::shortest_buf_duration
float shortest_buf_duration
Definition: ffmpeg.h:172
av_malloc_array
#define av_malloc_array(a, b)
Definition: tableprint_vlc.h:31
AVProgram::metadata
AVDictionary * metadata
Definition: avformat.h:1185
OutputFile::bitexact
int bitexact
Definition: ffmpeg.h:589
display.h
AVIAMFMixPresentation
Information on how to render and mix one or more AVIAMFAudioElement to generate the final audio outpu...
Definition: iamf.h:609
av_assert1
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:56
AVMEDIA_TYPE_ATTACHMENT
@ AVMEDIA_TYPE_ATTACHMENT
Opaque data information usually sparse.
Definition: avutil.h:205
InputFile::ctx
AVFormatContext * ctx
Definition: ffmpeg.h:394
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AVFormatContext::max_delay
int max_delay
Definition: avformat.h:1400
av_mallocz
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:254
AVProgram
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1179
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:194
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
ENC_STATS_STREAM_IDX
@ ENC_STATS_STREAM_IDX
Definition: ffmpeg.h:427
filtergraphs
FilterGraph ** filtergraphs
Definition: ffmpeg.c:131
int_cb
const AVIOInterruptCB int_cb
Definition: ffmpeg.c:328
AVCodecContext::height
int height
Definition: avcodec.h:618
fmt_in_list
static int fmt_in_list(const int *formats, int format)
Definition: ffmpeg_mux_init.c:505
AVCodecParameters::coded_side_data
AVPacketSideData * coded_side_data
Additional data associated with the entire stream.
Definition: codec_par.h:81
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:657
ENC_STATS_SAMPLE_NUM
@ ENC_STATS_SAMPLE_NUM
Definition: ffmpeg.h:438
AVStreamGroup::params
union AVStreamGroup::@298 params
Group type-specific parameters.
av_calloc
void * av_calloc(size_t nmemb, size_t size)
Definition: mem.c:262
nb_output_files
int nb_output_files
Definition: ffmpeg.c:129
sch_connect
int sch_connect(Scheduler *sch, SchedulerNode src, SchedulerNode dst)
Definition: ffmpeg_sched.c:897
avcodec.h
OptionGroup::sws_dict
AVDictionary * sws_dict
Definition: cmdutils.h:280
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:812
tag
uint32_t tag
Definition: movenc.c:1791
OptionsContext::metadata_map
SpecifierOptList metadata_map
Definition: ffmpeg.h:204
AVStream::id
int id
Format-specific stream ID.
Definition: avformat.h:755
AVFMT_FLAG_BITEXACT
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1423
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:743
AV_LOG_FATAL
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:174
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:71
AVFormatContext::oformat
const struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1274
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:2909
av_opt_eval_int
int av_opt_eval_int(void *obj, const AVOption *o, const char *val, int *int_out)
AV_CODEC_PROP_TEXT_SUB
#define AV_CODEC_PROP_TEXT_SUB
Subtitle codec is text based.
Definition: codec_desc.h:108
InputFile::streams
InputStream ** streams
Definition: ffmpeg.h:408
avformat.h
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: avpacket.c:704
AV_INPUT_BUFFER_PADDING_SIZE
#define AV_INPUT_BUFFER_PADDING_SIZE
Definition: defs.h:40
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:116
SCH_MSTREAM
#define SCH_MSTREAM(file, stream)
Definition: ffmpeg_sched.h:110
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:2894
AVStreamGroup
Definition: avformat.h:1090
of_add_attachments
static int of_add_attachments(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1672
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:445
AVStream::index
int index
stream index in AVFormatContext
Definition: avformat.h:749
AV_CLASS_CATEGORY_MUXER
@ AV_CLASS_CATEGORY_MUXER
Definition: log.h:32
avformat_transfer_internal_stream_timing_info
int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt, AVStream *ost, const AVStream *ist, enum AVTimebaseSource copy_tb)
Transfer internal timing information from one stream to another.
Definition: avformat.c:773
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:3241
AVStreamGroup::nb_streams
unsigned int nb_streams
Number of elements in AVStreamGroup.streams.
Definition: avformat.h:1143
OptionsContext::mux_preload
float mux_preload
Definition: ffmpeg.h:170
ist_output_add
int ist_output_add(InputStream *ist, OutputStream *ost)
Definition: ffmpeg_demux.c:963
AVRational::den
int den
Denominator.
Definition: rational.h:60
InputStream::file
struct InputFile * file
Definition: ffmpeg.h:349
SpecifierOpt::str
uint8_t * str
Definition: cmdutils.h:108
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:72
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Definition: opt.h:235
avfilter.h
av_bprint_clear
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition: bprint.c:232
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:200
avio_read
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:611
OptionsContext::video_disable
int video_disable
Definition: ffmpeg.h:176
AVOutputFormat::video_codec
enum AVCodecID video_codec
default video codec
Definition: avformat.h:521
AVStream::r_frame_rate
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:909
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:460
AVFormatContext::duration
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1390
av_mul_q
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
video_sync_method
enum VideoSyncMethod video_sync_method
Definition: ffmpeg_opt.c:66
GROW_ARRAY
#define GROW_ARRAY(array, nb_elems)
Definition: cmdutils.h:465
InputFile::ts_offset
int64_t ts_offset
Definition: ffmpeg.h:401
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:66
OutputFilter
Definition: ffmpeg.h:271
map_auto_audio
static int map_auto_audio(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1491
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:167
AVIAMFSubmix::nb_elements
unsigned int nb_elements
Number of elements in the submix.
Definition: iamf.h:568
AVIO_FLAG_READ
#define AVIO_FLAG_READ
read-only
Definition: avio.h:617
av_strdup
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:270
desc
const char * desc
Definition: libsvtav1.c:75
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
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:206
avutil.h
AVIAMFAudioElement::demixing_info
AVIAMFParamDefinition * demixing_info
Demixing information used to reconstruct a scalable channel audio representation.
Definition: iamf.h:376
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:866
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:591
MuxStream::sq_idx_mux
int sq_idx_mux
Definition: ffmpeg_mux.h:53
AVStreamGroup::type
enum AVStreamGroupParamsType type
Group type.
Definition: avformat.h:1117
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:490
AV_CODEC_FLAG_BITEXACT
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition: avcodec.h:342
ffmpeg_mux.h
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:137
new_stream_audio
static int new_stream_audio(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:824
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:1162
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:421
InputStream::index
int index
Definition: ffmpeg.h:351
AVFormatContext::nb_stream_groups
unsigned int nb_stream_groups
Number of elements in AVFormatContext.stream_groups.
Definition: avformat.h:1330
ffmpeg_sched.h
EncStatsFile::path
char * path
Definition: ffmpeg_mux_init.c:156
compare_int64
static int compare_int64(const void *a, const void *b)
Definition: ffmpeg_mux_init.c:2739
av_free
#define av_free(p)
Definition: tableprint_vlc.h:33
FKF_N_FORCED
@ FKF_N_FORCED
Definition: ffmpeg.h:414
AVDictionaryEntry
Definition: dict.h:89
OptionsContext::attachments
const char ** attachments
Definition: ffmpeg.h:162
ENC_TIME_BASE_FILTER
@ ENC_TIME_BASE_FILTER
Definition: ffmpeg.h:78
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:55
audio_disable
static int audio_disable
Definition: ffplay.c:317
EncStatsComponent
Definition: ffmpeg.h:446
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:648
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
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:88
src
INIT_CLIP pixel * src
Definition: h264pred_template.c:418
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:237
AVCodecContext::inter_matrix
uint16_t * inter_matrix
custom inter quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition: avcodec.h:983
cmdutils.h
AVCodecContext::rc_override_count
int rc_override_count
ratecontrol override, see RcOverride
Definition: avcodec.h:1284
InputFile::input_ts_offset
int64_t input_ts_offset
Definition: ffmpeg.h:395
EncStats::nb_components
int nb_components
Definition: ffmpeg.h:455
OptionsContext::data_disable
int data_disable
Definition: ffmpeg.h:179
nb_filtergraphs
int nb_filtergraphs
Definition: ffmpeg.c:132
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:461
AVCodecContext::width
int width
picture width / height.
Definition: avcodec.h:618
muxer_thread
int muxer_thread(void *arg)
Definition: ffmpeg_mux.c:407
enc_alloc
int enc_alloc(Encoder **penc, const AVCodec *codec, Scheduler *sch, unsigned sch_idx)
Definition: ffmpeg_enc.c:74
AVIAMFSubmixElement
Submix element as defined in section 3.7 of IAMF.
Definition: iamf.h:446
ENC_STATS_PKT_SIZE
@ ENC_STATS_PKT_SIZE
Definition: ffmpeg.h:440
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_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
forced_keyframes_const_names
const char *const forced_keyframes_const_names[]
Definition: ffmpeg_mux_init.c:2730
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:2818
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:145
avcodec_descriptor_get
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:3727
OutputFile::format
const AVOutputFormat * format
Definition: ffmpeg.h:579
AVIAMFAudioElement::recon_gain_info
AVIAMFParamDefinition * recon_gain_info
Recon gain information used to reconstruct a scalable channel audio representation.
Definition: iamf.h:383
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:675
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:1945
AVDictionaryEntry::value
char * value
Definition: dict.h:91
avstring.h
FF_QP2LAMBDA
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
opt_match_per_type_str
const char * opt_match_per_type_str(const SpecifierOptList *sol, char mediatype)
Definition: ffmpeg_opt.c:179
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:1121
InputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:409
FKF_N
@ FKF_N
Definition: ffmpeg.h:413
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:93
ENC_STATS_DTS_TIME
@ ENC_STATS_DTS_TIME
Definition: ffmpeg.h:437
AVChapter::time_base
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1216
OutputFile::recording_time
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:585
int
int
Definition: ffmpeg_filter.c:409
of_stream_init
int of_stream_init(OutputFile *of, OutputStream *ost)
Definition: ffmpeg_mux.c:609
VSYNC_PASSTHROUGH
@ VSYNC_PASSTHROUGH
Definition: ffmpeg.h:67
AV_OPT_TYPE_CONST
@ AV_OPT_TYPE_CONST
Definition: opt.h:244
snprintf
#define snprintf
Definition: snprintf.h:34
EncStats::io
AVIOContext * io
Definition: ffmpeg.h:457
av_dict_iterate
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition: dict.c:44
copy_chapters
static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os, int copy_metadata)
Definition: ffmpeg_mux_init.c:2455
MuxStream::last_mux_dts
int64_t last_mux_dts
Definition: ffmpeg_mux.h:64
ENC_STATS_TIMEBASE
@ ENC_STATS_TIMEBASE
Definition: ffmpeg.h:430
create_streams
static int create_streams(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1752
MuxStream::stream_duration
int64_t stream_duration
Definition: ffmpeg_mux.h:66
OutputStream::class
const AVClass * class
Definition: ffmpeg.h:496
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:2882
AV_IAMF_PARAMETER_DEFINITION_DEMIXING
@ AV_IAMF_PARAMETER_DEFINITION_DEMIXING
Subblocks are of struct type AVIAMFDemixingInfo.
Definition: iamf.h:177
OutputFile
Definition: ffmpeg.h:574
AV_CODEC_FLAG_PASS1
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:310
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:841