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 "fopen_utf8.h"
27 
28 #include "libavformat/avformat.h"
29 #include "libavformat/avio.h"
30 
31 #include "libavcodec/avcodec.h"
32 
33 #include "libavfilter/avfilter.h"
34 
35 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/avutil.h"
38 #include "libavutil/bprint.h"
39 #include "libavutil/dict.h"
40 #include "libavutil/display.h"
41 #include "libavutil/getenv_utf8.h"
42 #include "libavutil/intreadwrite.h"
43 #include "libavutil/log.h"
44 #include "libavutil/mem.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/parseutils.h"
47 #include "libavutil/pixdesc.h"
48 
49 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
50 
51 static const char *const opt_name_apad[] = {"apad", NULL};
52 static const char *const opt_name_autoscale[] = {"autoscale", NULL};
53 static const char *const opt_name_bits_per_raw_sample[] = {"bits_per_raw_sample", NULL};
54 static const char *const opt_name_bitstream_filters[] = {"bsf", "absf", "vbsf", NULL};
55 static const char *const opt_name_copy_initial_nonkeyframes[] = {"copyinkf", NULL};
56 static const char *const opt_name_copy_prior_start[] = {"copypriorss", NULL};
57 static const char *const opt_name_disposition[] = {"disposition", NULL};
58 static const char *const opt_name_enc_time_bases[] = {"enc_time_base", NULL};
59 static const char *const opt_name_enc_stats_pre[] = {"enc_stats_pre", NULL};
60 static const char *const opt_name_enc_stats_post[] = {"enc_stats_post", NULL};
61 static const char *const opt_name_mux_stats[] = {"mux_stats", NULL};
62 static const char *const opt_name_enc_stats_pre_fmt[] = {"enc_stats_pre_fmt", NULL};
63 static const char *const opt_name_enc_stats_post_fmt[] = {"enc_stats_post_fmt", NULL};
64 static const char *const opt_name_mux_stats_fmt[] = {"mux_stats_fmt", NULL};
65 static const char *const opt_name_filters[] = {"filter", "af", "vf", NULL};
66 static const char *const opt_name_filter_scripts[] = {"filter_script", NULL};
67 static const char *const opt_name_fix_sub_duration_heartbeat[] = {"fix_sub_duration_heartbeat", NULL};
68 static const char *const opt_name_fps_mode[] = {"fps_mode", NULL};
69 static const char *const opt_name_force_fps[] = {"force_fps", NULL};
70 static const char *const opt_name_forced_key_frames[] = {"forced_key_frames", NULL};
71 static const char *const opt_name_frame_aspect_ratios[] = {"aspect", NULL};
72 static const char *const opt_name_intra_matrices[] = {"intra_matrix", NULL};
73 static const char *const opt_name_inter_matrices[] = {"inter_matrix", NULL};
74 static const char *const opt_name_chroma_intra_matrices[] = {"chroma_intra_matrix", NULL};
75 static const char *const opt_name_max_frame_rates[] = {"fpsmax", NULL};
76 static const char *const opt_name_max_frames[] = {"frames", "aframes", "vframes", "dframes", NULL};
77 static const char *const opt_name_max_muxing_queue_size[] = {"max_muxing_queue_size", NULL};
78 static const char *const opt_name_muxing_queue_data_threshold[] = {"muxing_queue_data_threshold", NULL};
79 static const char *const opt_name_pass[] = {"pass", NULL};
80 static const char *const opt_name_passlogfiles[] = {"passlogfile", NULL};
81 static const char *const opt_name_presets[] = {"pre", "apre", "vpre", "spre", NULL};
82 static const char *const opt_name_qscale[] = {"q", "qscale", NULL};
83 static const char *const opt_name_rc_overrides[] = {"rc_override", NULL};
84 static const char *const opt_name_time_bases[] = {"time_base", NULL};
85 static const char *const opt_name_audio_channels[] = {"ac", NULL};
86 static const char *const opt_name_audio_ch_layouts[] = {"channel_layout", "ch_layout", NULL};
87 static const char *const opt_name_audio_sample_rate[] = {"ar", NULL};
88 static const char *const opt_name_frame_sizes[] = {"s", NULL};
89 static const char *const opt_name_frame_pix_fmts[] = {"pix_fmt", NULL};
90 static const char *const opt_name_sample_fmts[] = {"sample_fmt", NULL};
91 
92 static int check_opt_bitexact(void *ctx, const AVDictionary *opts,
93  const char *opt_name, int flag)
94 {
95  const AVDictionaryEntry *e = av_dict_get(opts, opt_name, NULL, 0);
96 
97  if (e) {
98  const AVOption *o = av_opt_find(ctx, opt_name, NULL, 0, 0);
99  int val = 0;
100  if (!o)
101  return 0;
102  av_opt_eval_flags(ctx, o, e->value, &val);
103  return !!(val & flag);
104  }
105  return 0;
106 }
107 
109  OutputStream *ost, const AVCodec **enc)
110 {
111  enum AVMediaType type = ost->type;
112  char *codec_name = NULL;
113 
114  *enc = NULL;
115 
116  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
117 
118  if (type != AVMEDIA_TYPE_VIDEO &&
121  if (codec_name && strcmp(codec_name, "copy")) {
122  const char *type_str = av_get_media_type_string(type);
124  "Encoder '%s' specified, but only '-codec copy' supported "
125  "for %s streams\n", codec_name, type_str);
126  return AVERROR(ENOSYS);
127  }
128  return 0;
129  }
130 
131  if (!codec_name) {
132  ost->par_in->codec_id = av_guess_codec(s->oformat, NULL, s->url, NULL, ost->type);
133  *enc = avcodec_find_encoder(ost->par_in->codec_id);
134  if (!*enc) {
135  av_log(ost, AV_LOG_FATAL, "Automatic encoder selection failed "
136  "Default encoder for format %s (codec %s) is "
137  "probably disabled. Please choose an encoder manually.\n",
138  s->oformat->name, avcodec_get_name(ost->par_in->codec_id));
140  }
141  } else if (strcmp(codec_name, "copy")) {
142  *enc = find_codec_or_die(ost, codec_name, ost->type, 1);
143  ost->par_in->codec_id = (*enc)->id;
144  }
145 
146  return 0;
147 }
148 
149 static char *get_line(AVIOContext *s, AVBPrint *bprint)
150 {
151  char c;
152 
153  while ((c = avio_r8(s)) && c != '\n')
154  av_bprint_chars(bprint, c, 1);
155 
156  if (!av_bprint_is_complete(bprint))
157  report_and_exit(AVERROR(ENOMEM));
158  return bprint->str;
159 }
160 
161 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
162 {
163  int i, ret = -1;
164  char filename[1000];
165  char *env_avconv_datadir = getenv_utf8("AVCONV_DATADIR");
166  char *env_home = getenv_utf8("HOME");
167  const char *base[3] = { env_avconv_datadir,
168  env_home,
169  AVCONV_DATADIR,
170  };
171 
172  for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
173  if (!base[i])
174  continue;
175  if (codec_name) {
176  snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
177  i != 1 ? "" : "/.avconv", codec_name, preset_name);
178  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
179  }
180  if (ret < 0) {
181  snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
182  i != 1 ? "" : "/.avconv", preset_name);
183  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
184  }
185  }
186  freeenv_utf8(env_home);
187  freeenv_utf8(env_avconv_datadir);
188  return ret;
189 }
190 
191 typedef struct EncStatsFile {
192  char *path;
194 } EncStatsFile;
195 
198 
199 static int enc_stats_get_file(AVIOContext **io, const char *path)
200 {
201  EncStatsFile *esf;
202  int ret;
203 
204  for (int i = 0; i < nb_enc_stats_files; i++)
205  if (!strcmp(path, enc_stats_files[i].path)) {
206  *io = enc_stats_files[i].io;
207  return 0;
208  }
209 
211 
213 
214  ret = avio_open2(&esf->io, path, AVIO_FLAG_WRITE, &int_cb, NULL);
215  if (ret < 0) {
216  av_log(NULL, AV_LOG_ERROR, "Error opening stats file '%s': %s\n",
217  path, av_err2str(ret));
218  return ret;
219  }
220 
221  esf->path = av_strdup(path);
222  if (!esf->path)
223  return AVERROR(ENOMEM);
224 
225  *io = esf->io;
226 
227  return 0;
228 }
229 
231 {
232  for (int i = 0; i < nb_enc_stats_files; i++) {
233  av_freep(&enc_stats_files[i].path);
235  }
237  nb_enc_stats_files = 0;
238 }
239 
240 static int unescape(char **pdst, size_t *dst_len,
241  const char **pstr, char delim)
242 {
243  const char *str = *pstr;
244  char *dst;
245  size_t len, idx;
246 
247  *pdst = NULL;
248 
249  len = strlen(str);
250  if (!len)
251  return 0;
252 
253  dst = av_malloc(len + 1);
254  if (!dst)
255  return AVERROR(ENOMEM);
256 
257  for (idx = 0; *str; idx++, str++) {
258  if (str[0] == '\\' && str[1])
259  str++;
260  else if (*str == delim)
261  break;
262 
263  dst[idx] = *str;
264  }
265  if (!idx) {
266  av_freep(&dst);
267  return 0;
268  }
269 
270  dst[idx] = 0;
271 
272  *pdst = dst;
273  *dst_len = idx;
274  *pstr = str;
275 
276  return 0;
277 }
278 
279 static int enc_stats_init(OutputStream *ost, EncStats *es, int pre,
280  const char *path, const char *fmt_spec)
281 {
282  static const struct {
283  enum EncStatsType type;
284  const char *str;
285  int pre_only:1;
286  int post_only:1;
287  int need_input_data:1;
288  } fmt_specs[] = {
289  { ENC_STATS_FILE_IDX, "fidx" },
290  { ENC_STATS_STREAM_IDX, "sidx" },
291  { ENC_STATS_FRAME_NUM, "n" },
292  { ENC_STATS_FRAME_NUM_IN, "ni", 0, 0, 1 },
293  { ENC_STATS_TIMEBASE, "tb" },
294  { ENC_STATS_TIMEBASE_IN, "tbi", 0, 0, 1 },
295  { ENC_STATS_PTS, "pts" },
296  { ENC_STATS_PTS_TIME, "t" },
297  { ENC_STATS_PTS_IN, "ptsi", 0, 0, 1 },
298  { ENC_STATS_PTS_TIME_IN, "ti", 0, 0, 1 },
299  { ENC_STATS_DTS, "dts", 0, 1 },
300  { ENC_STATS_DTS_TIME, "dt", 0, 1 },
301  { ENC_STATS_SAMPLE_NUM, "sn", 1 },
302  { ENC_STATS_NB_SAMPLES, "samp", 1 },
303  { ENC_STATS_PKT_SIZE, "size", 0, 1 },
304  { ENC_STATS_BITRATE, "br", 0, 1 },
305  { ENC_STATS_AVG_BITRATE, "abr", 0, 1 },
306  };
307  const char *next = fmt_spec;
308 
309  int ret;
310 
311  while (*next) {
313  char *val;
314  size_t val_len;
315 
316  // get the sequence up until next opening brace
317  ret = unescape(&val, &val_len, &next, '{');
318  if (ret < 0)
319  return ret;
320 
321  if (val) {
323 
324  c = &es->components[es->nb_components - 1];
325  c->type = ENC_STATS_LITERAL;
326  c->str = val;
327  c->str_len = val_len;
328  }
329 
330  if (!*next)
331  break;
332  next++;
333 
334  // get the part inside braces
335  ret = unescape(&val, &val_len, &next, '}');
336  if (ret < 0)
337  return ret;
338 
339  if (!val) {
341  "Empty formatting directive in: %s\n", fmt_spec);
342  return AVERROR(EINVAL);
343  }
344 
345  if (!*next) {
347  "Missing closing brace in: %s\n", fmt_spec);
348  ret = AVERROR(EINVAL);
349  goto fail;
350  }
351  next++;
352 
354  c = &es->components[es->nb_components - 1];
355 
356  for (size_t i = 0; i < FF_ARRAY_ELEMS(fmt_specs); i++) {
357  if (!strcmp(val, fmt_specs[i].str)) {
358  if ((pre && fmt_specs[i].post_only) || (!pre && fmt_specs[i].pre_only)) {
360  "Format directive '%s' may only be used %s-encoding\n",
361  val, pre ? "post" : "pre");
362  ret = AVERROR(EINVAL);
363  goto fail;
364  }
365 
366  c->type = fmt_specs[i].type;
367 
368  if (fmt_specs[i].need_input_data) {
369  if (ost->ist)
370  ost->ist->want_frame_data = 1;
371  else {
373  "Format directive '%s' is unavailable, because "
374  "this output stream has no associated input stream\n",
375  val);
376  }
377  }
378 
379  break;
380  }
381  }
382 
383  if (!c->type) {
384  av_log(NULL, AV_LOG_ERROR, "Invalid format directive: %s\n", val);
385  ret = AVERROR(EINVAL);
386  goto fail;
387  }
388 
389 fail:
390  av_freep(&val);
391  if (ret < 0)
392  return ret;
393  }
394 
395  ret = enc_stats_get_file(&es->io, path);
396  if (ret < 0)
397  return ret;
398 
399  return 0;
400 }
401 
402 static const char *output_stream_item_name(void *obj)
403 {
404  const MuxStream *ms = obj;
405 
406  return ms->log_name;
407 }
408 
409 static const AVClass output_stream_class = {
410  .class_name = "OutputStream",
411  .version = LIBAVUTIL_VERSION_INT,
412  .item_name = output_stream_item_name,
413  .category = AV_CLASS_CATEGORY_MUXER,
414 };
415 
417 {
418  const char *type_str = av_get_media_type_string(type);
419  MuxStream *ms = allocate_array_elem(&mux->of.streams, sizeof(*ms),
420  &mux->of.nb_streams);
421 
422  ms->ost.file_index = mux->of.index;
423  ms->ost.index = mux->of.nb_streams - 1;
424  ms->ost.type = type;
425 
427 
428  snprintf(ms->log_name, sizeof(ms->log_name), "%cost#%d:%d",
429  type_str ? *type_str : '?', mux->of.index, ms->ost.index);
430 
431  return ms;
432 }
433 
435  OutputStream *ost)
436 {
437  const char *filters = NULL, *filters_script = NULL;
438 
439  MATCH_PER_STREAM_OPT(filter_scripts, str, filters_script, oc, ost->st);
440  MATCH_PER_STREAM_OPT(filters, str, filters, oc, ost->st);
441 
442  if (!ost->enc) {
443  if (filters_script || filters) {
445  "%s '%s' was specified, but codec copy was selected. "
446  "Filtering and streamcopy cannot be used together.\n",
447  filters ? "Filtergraph" : "Filtergraph script",
448  filters ? filters : filters_script);
449  return AVERROR(ENOSYS);
450  }
451  return 0;
452  }
453 
454  if (!ost->ist) {
455  if (filters_script || filters) {
457  "%s '%s' was specified for a stream fed from a complex "
458  "filtergraph. Simple and complex filtering cannot be used "
459  "together for the same stream.\n",
460  filters ? "Filtergraph" : "Filtergraph script",
461  filters ? filters : filters_script);
462  return AVERROR(EINVAL);
463  }
464  return 0;
465  }
466 
467  if (filters_script && filters) {
468  av_log(ost, AV_LOG_ERROR, "Both -filter and -filter_script set\n");
469  exit_program(1);
470  }
471 
472  if (filters_script)
473  ost->avfilter = file_read(filters_script);
474  else if (filters)
475  ost->avfilter = av_strdup(filters);
476  else
477  ost->avfilter = av_strdup(ost->type == AVMEDIA_TYPE_VIDEO ? "null" : "anull");
478  return ost->avfilter ? 0 : AVERROR(ENOMEM);
479 }
480 
481 static void parse_matrix_coeffs(void *logctx, uint16_t *dest, const char *str)
482 {
483  int i;
484  const char *p = str;
485  for (i = 0;; i++) {
486  dest[i] = atoi(p);
487  if (i == 63)
488  break;
489  p = strchr(p, ',');
490  if (!p) {
491  av_log(logctx, AV_LOG_FATAL,
492  "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
493  exit_program(1);
494  }
495  p++;
496  }
497 }
498 
499 static void new_stream_video(Muxer *mux, const OptionsContext *o,
500  OutputStream *ost)
501 {
502  AVFormatContext *oc = mux->fc;
503  AVStream *st;
504  char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
505 
506  st = ost->st;
507 
508  MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
509  if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
510  av_log(ost, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
511  exit_program(1);
512  }
513 
514  MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
515  if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
516  av_log(ost, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
517  exit_program(1);
518  }
519 
520  if (frame_rate && max_frame_rate) {
521  av_log(ost, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
522  exit_program(1);
523  }
524 
525  MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
526  if (frame_aspect_ratio) {
527  AVRational q;
528  if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
529  q.num <= 0 || q.den <= 0) {
530  av_log(ost, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
531  exit_program(1);
532  }
533  ost->frame_aspect_ratio = q;
534  }
535 
536  if (ost->enc_ctx) {
537  AVCodecContext *video_enc = ost->enc_ctx;
538  const char *p = NULL, *fps_mode = NULL;
539  char *frame_size = NULL;
540  char *frame_pix_fmt = NULL;
541  char *intra_matrix = NULL, *inter_matrix = NULL;
542  char *chroma_intra_matrix = NULL;
543  int do_pass = 0;
544  int i;
545 
547  if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
548  av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
549  exit_program(1);
550  }
551 
552  MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
553  if (frame_pix_fmt && *frame_pix_fmt == '+') {
554  ost->keep_pix_fmt = 1;
555  if (!*++frame_pix_fmt)
556  frame_pix_fmt = NULL;
557  }
558  if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
559  av_log(ost, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
560  exit_program(1);
561  }
562  st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
563 
564  MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
565  if (intra_matrix) {
566  if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64)))
567  report_and_exit(AVERROR(ENOMEM));
568  parse_matrix_coeffs(ost, video_enc->intra_matrix, intra_matrix);
569  }
570  MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
571  if (chroma_intra_matrix) {
572  uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
573  if (!p)
574  report_and_exit(AVERROR(ENOMEM));
575  video_enc->chroma_intra_matrix = p;
576  parse_matrix_coeffs(ost, p, chroma_intra_matrix);
577  }
578  MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
579  if (inter_matrix) {
580  if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64)))
581  report_and_exit(AVERROR(ENOMEM));
582  parse_matrix_coeffs(ost, video_enc->inter_matrix, inter_matrix);
583  }
584 
585  MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
586  for (i = 0; p; i++) {
587  int start, end, q;
588  int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
589  if (e != 3) {
590  av_log(ost, AV_LOG_FATAL, "error parsing rc_override\n");
591  exit_program(1);
592  }
593  video_enc->rc_override =
594  av_realloc_array(video_enc->rc_override,
595  i + 1, sizeof(RcOverride));
596  if (!video_enc->rc_override) {
597  av_log(ost, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
598  exit_program(1);
599  }
600  video_enc->rc_override[i].start_frame = start;
601  video_enc->rc_override[i].end_frame = end;
602  if (q > 0) {
603  video_enc->rc_override[i].qscale = q;
604  video_enc->rc_override[i].quality_factor = 1.0;
605  }
606  else {
607  video_enc->rc_override[i].qscale = 0;
608  video_enc->rc_override[i].quality_factor = -q/100.0;
609  }
610  p = strchr(p, '/');
611  if (p) p++;
612  }
613  video_enc->rc_override_count = i;
614 
615 #if FFMPEG_OPT_PSNR
616  if (do_psnr) {
617  av_log(ost, AV_LOG_WARNING, "The -psnr option is deprecated, use -flags +psnr\n");
618  video_enc->flags|= AV_CODEC_FLAG_PSNR;
619  }
620 #endif
621 
622  /* two pass mode */
623  MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
624  if (do_pass) {
625  if (do_pass & 1) {
626  video_enc->flags |= AV_CODEC_FLAG_PASS1;
627  av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
628  }
629  if (do_pass & 2) {
630  video_enc->flags |= AV_CODEC_FLAG_PASS2;
631  av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
632  }
633  }
634 
635  MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
636  if (ost->logfile_prefix &&
637  !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
638  report_and_exit(AVERROR(ENOMEM));
639 
640  if (do_pass) {
641  int ost_idx = -1;
642  char logfilename[1024];
643  FILE *f;
644 
645  /* compute this stream's global index */
646  for (int i = 0; i <= ost->file_index; i++)
647  ost_idx += output_files[i]->nb_streams;
648 
649  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
650  ost->logfile_prefix ? ost->logfile_prefix :
652  ost_idx);
653  if (!strcmp(ost->enc_ctx->codec->name, "libx264")) {
654  av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
655  } else {
656  if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
657  char *logbuffer = file_read(logfilename);
658 
659  if (!logbuffer) {
660  av_log(ost, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
661  logfilename);
662  exit_program(1);
663  }
664  video_enc->stats_in = logbuffer;
665  }
666  if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
667  f = fopen_utf8(logfilename, "wb");
668  if (!f) {
670  "Cannot write log file '%s' for pass-1 encoding: %s\n",
671  logfilename, strerror(errno));
672  exit_program(1);
673  }
674  ost->logfile = f;
675  }
676  }
677  }
678 
679  MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
680 
681  ost->top_field_first = -1;
682  MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
683 
684  ost->vsync_method = video_sync_method;
685  MATCH_PER_STREAM_OPT(fps_mode, str, fps_mode, oc, st);
686  if (fps_mode)
687  parse_and_set_vsync(fps_mode, &ost->vsync_method, ost->file_index, ost->index, 0);
688 
689  if ((ost->frame_rate.num || ost->max_frame_rate.num) &&
690  !(ost->vsync_method == VSYNC_AUTO ||
691  ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR)) {
692  av_log(ost, AV_LOG_FATAL, "One of -r/-fpsmax was specified "
693  "together a non-CFR -vsync/-fps_mode. This is contradictory.\n");
694  exit_program(1);
695  }
696 
697  if (ost->vsync_method == VSYNC_AUTO) {
698  if (ost->frame_rate.num || ost->max_frame_rate.num) {
699  ost->vsync_method = VSYNC_CFR;
700  } else if (!strcmp(oc->oformat->name, "avi")) {
701  ost->vsync_method = VSYNC_VFR;
702  } else {
703  ost->vsync_method = (oc->oformat->flags & AVFMT_VARIABLE_FPS) ?
704  ((oc->oformat->flags & AVFMT_NOTIMESTAMPS) ?
706  VSYNC_CFR;
707  }
708 
709  if (ost->ist && ost->vsync_method == VSYNC_CFR) {
710  const InputFile *ifile = input_files[ost->ist->file_index];
711 
712  if (ifile->nb_streams == 1 && ifile->input_ts_offset == 0)
713  ost->vsync_method = VSYNC_VSCFR;
714  }
715 
716  if (ost->vsync_method == VSYNC_CFR && copy_ts) {
717  ost->vsync_method = VSYNC_VSCFR;
718  }
719  }
720  ost->is_cfr = (ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR);
721  }
722 }
723 
724 static void new_stream_audio(Muxer *mux, const OptionsContext *o,
725  OutputStream *ost)
726 {
727  AVFormatContext *oc = mux->fc;
728  AVStream *st;
729 
730  st = ost->st;
731 
732  if (ost->enc_ctx) {
733  AVCodecContext *audio_enc = ost->enc_ctx;
734  int channels = 0;
735  char *layout = NULL;
736  char *sample_fmt = NULL;
737 
739  if (channels) {
741  audio_enc->ch_layout.nb_channels = channels;
742  }
743 
744  MATCH_PER_STREAM_OPT(audio_ch_layouts, str, layout, oc, st);
745  if (layout) {
746  if (av_channel_layout_from_string(&audio_enc->ch_layout, layout) < 0) {
747 #if FF_API_OLD_CHANNEL_LAYOUT
748  uint64_t mask;
751  })
752  if (!mask) {
753 #endif
754  av_log(ost, AV_LOG_FATAL, "Unknown channel layout: %s\n", layout);
755  exit_program(1);
756 #if FF_API_OLD_CHANNEL_LAYOUT
757  }
758  av_log(ost, AV_LOG_WARNING, "Channel layout '%s' uses a deprecated syntax.\n",
759  layout);
761 #endif
762  }
763  }
764 
765  MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
766  if (sample_fmt &&
767  (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
768  av_log(ost, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
769  exit_program(1);
770  }
771 
772  MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
773 
774  MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
775  ost->apad = av_strdup(ost->apad);
776 
777 #if FFMPEG_OPT_MAP_CHANNEL
778  /* check for channel mapping for this audio stream */
779  for (int n = 0; n < o->nb_audio_channel_maps; n++) {
781  if ((map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
782  (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
783  InputStream *ist;
784 
785  if (map->channel_idx == -1) {
786  ist = NULL;
787  } else if (!ost->ist) {
788  av_log(ost, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
789  ost->file_index, ost->st->index);
790  continue;
791  } else {
792  ist = ost->ist;
793  }
794 
795  if (!ist || (ist->file_index == map->file_idx && ist->index == map->stream_idx)) {
796  if (av_reallocp_array(&ost->audio_channels_map,
797  ost->audio_channels_mapped + 1,
798  sizeof(*ost->audio_channels_map)
799  ) < 0 )
800  report_and_exit(AVERROR(ENOMEM));
801 
802  ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
803  }
804  }
805  }
806 #endif
807  }
808 }
809 
810 static void new_stream_attachment(Muxer *mux, const OptionsContext *o,
811  OutputStream *ost)
812 {
813  ost->finished = 1;
814 }
815 
816 static void new_stream_subtitle(Muxer *mux, const OptionsContext *o,
817  OutputStream *ost)
818 {
819  AVStream *st;
820 
821  st = ost->st;
822 
823  if (ost->enc_ctx) {
824  AVCodecContext *subtitle_enc = ost->enc_ctx;
825 
826  AVCodecDescriptor const *input_descriptor =
827  avcodec_descriptor_get(ost->ist->par->codec_id);
828  AVCodecDescriptor const *output_descriptor =
829  avcodec_descriptor_get(subtitle_enc->codec_id);
830  int input_props = 0, output_props = 0;
831 
832  char *frame_size = NULL;
833 
835  if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
836  av_log(ost, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
837  exit_program(1);
838  }
839  if (input_descriptor)
840  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
841  if (output_descriptor)
842  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
843  if (input_props && output_props && input_props != output_props) {
845  "Subtitle encoding currently only possible from text to text "
846  "or bitmap to bitmap\n");
847  exit_program(1);
848  }
849  }
850 }
851 
852 static int streamcopy_init(const Muxer *mux, OutputStream *ost)
853 {
854  MuxStream *ms = ms_from_ost(ost);
855 
856  const InputStream *ist = ost->ist;
857  const InputFile *ifile = input_files[ist->file_index];
858 
859  AVCodecParameters *par = ost->par_in;
860  uint32_t codec_tag = par->codec_tag;
861 
862  AVCodecContext *codec_ctx = NULL;
864  int ret = 0;
865 
866  codec_ctx = avcodec_alloc_context3(NULL);
867  if (!codec_ctx)
868  return AVERROR(ENOMEM);
869 
870  ret = avcodec_parameters_to_context(codec_ctx, ist->par);
871  if (ret >= 0)
872  ret = av_opt_set_dict(codec_ctx, &ost->encoder_opts);
873  if (ret < 0) {
875  "Error setting up codec context options.\n");
876  goto fail;
877  }
878 
879  ret = avcodec_parameters_from_context(par, codec_ctx);
880  if (ret < 0) {
882  "Error getting reference codec parameters.\n");
883  goto fail;
884  }
885 
886  if (!codec_tag) {
887  const struct AVCodecTag * const *ct = mux->fc->oformat->codec_tag;
888  unsigned int codec_tag_tmp;
889  if (!ct || av_codec_get_id (ct, par->codec_tag) == par->codec_id ||
890  !av_codec_get_tag2(ct, par->codec_id, &codec_tag_tmp))
891  codec_tag = par->codec_tag;
892  }
893 
894  par->codec_tag = codec_tag;
895 
896  if (!ost->frame_rate.num)
897  ost->frame_rate = ist->framerate;
898 
899  if (ost->frame_rate.num)
900  ost->st->avg_frame_rate = ost->frame_rate;
901  else
902  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
903 
905  ost->st, ist->st, copy_tb);
906  if (ret < 0)
907  goto fail;
908 
909  // copy timebase while removing common factors
910  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0) {
911  if (ost->frame_rate.num)
912  ost->st->time_base = av_inv_q(ost->frame_rate);
913  else
915  }
916 
917  // copy estimated duration as a hint to the muxer
918  if (ost->st->duration <= 0 && ist->st->duration > 0)
919  ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
920 
921  if (!ms->copy_prior_start) {
922  ms->ts_copy_start = (mux->of.start_time == AV_NOPTS_VALUE) ?
923  0 : mux->of.start_time;
924  if (copy_ts && ifile->start_time != AV_NOPTS_VALUE) {
926  ifile->start_time + ifile->ts_offset);
927  }
928  }
929 
930  for (int i = 0; i < ist->st->nb_side_data; i++) {
931  const AVPacketSideData *sd_src = &ist->st->side_data[i];
932  uint8_t *dst_data;
933 
934  dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
935  if (!dst_data) {
936  ret = AVERROR(ENOMEM);
937  goto fail;
938  }
939  memcpy(dst_data, sd_src->data, sd_src->size);
940  }
941 
942 #if FFMPEG_ROTATION_METADATA
943  if (ost->rotate_overridden) {
945  sizeof(int32_t) * 9);
946  if (sd)
947  av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
948  }
949 #endif
950 
951  switch (par->codec_type) {
952  case AVMEDIA_TYPE_AUDIO:
953  if ((par->block_align == 1 || par->block_align == 1152 || par->block_align == 576) &&
954  par->codec_id == AV_CODEC_ID_MP3)
955  par->block_align = 0;
956  if (par->codec_id == AV_CODEC_ID_AC3)
957  par->block_align = 0;
958  break;
959  case AVMEDIA_TYPE_VIDEO: {
960  AVRational sar;
961  if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
962  sar =
963  av_mul_q(ost->frame_aspect_ratio,
964  (AVRational){ par->height, par->width });
965  av_log(ost, AV_LOG_WARNING, "Overriding aspect ratio "
966  "with stream copy may produce invalid files\n");
967  }
968  else if (ist->st->sample_aspect_ratio.num)
969  sar = ist->st->sample_aspect_ratio;
970  else
971  sar = par->sample_aspect_ratio;
972  ost->st->sample_aspect_ratio = par->sample_aspect_ratio = sar;
973  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
974  ost->st->r_frame_rate = ist->st->r_frame_rate;
975  break;
976  }
977  }
978 
979  ost->mux_timebase = ist->st->time_base;
980 
981 fail:
982  avcodec_free_context(&codec_ctx);
984  return ret;
985 }
986 
987 static OutputStream *ost_add(Muxer *mux, const OptionsContext *o,
988  enum AVMediaType type, InputStream *ist)
989 {
990  AVFormatContext *oc = mux->fc;
991  MuxStream *ms;
992  OutputStream *ost;
993  const AVCodec *enc;
994  AVStream *st = avformat_new_stream(oc, NULL);
995  int ret = 0;
996  const char *bsfs = NULL, *time_base = NULL;
997  char *next, *codec_tag = NULL;
998  double qscale = -1;
999  int i;
1000 
1001  if (!st)
1002  report_and_exit(AVERROR(ENOMEM));
1003 
1004  if (oc->nb_streams - 1 < o->nb_streamid_map)
1005  st->id = o->streamid_map[oc->nb_streams - 1];
1006 
1007  ms = mux_stream_alloc(mux, type);
1008  ost = &ms->ost;
1009 
1010  ost->par_in = avcodec_parameters_alloc();
1011  if (!ost->par_in)
1012  report_and_exit(AVERROR(ENOMEM));
1013 
1014  ms->muxing_queue = av_fifo_alloc2(8, sizeof(AVPacket*), 0);
1015  if (!ms->muxing_queue)
1016  report_and_exit(AVERROR(ENOMEM));
1018 
1019  ost->st = st;
1020  ost->ist = ist;
1021  ost->kf.ref_pts = AV_NOPTS_VALUE;
1022  ost->par_in->codec_type = type;
1023  st->codecpar->codec_type = type;
1024 
1025  ret = choose_encoder(o, oc, ost, &enc);
1026  if (ret < 0) {
1027  av_log(ost, AV_LOG_FATAL, "Error selecting an encoder\n");
1028  exit_program(1);
1029  }
1030 
1031  if (enc) {
1032  ost->enc_ctx = avcodec_alloc_context3(enc);
1033  if (!ost->enc_ctx)
1034  report_and_exit(AVERROR(ENOMEM));
1035 
1036  ret = enc_alloc(&ost->enc, enc);
1037  if (ret < 0)
1039 
1040  av_strlcat(ms->log_name, "/", sizeof(ms->log_name));
1041  av_strlcat(ms->log_name, enc->name, sizeof(ms->log_name));
1042  } else {
1043  av_strlcat(ms->log_name, "/copy", sizeof(ms->log_name));
1044  }
1045 
1046  ost->pkt = av_packet_alloc();
1047  if (!ost->pkt)
1048  report_and_exit(AVERROR(ENOMEM));
1049 
1050  if (ost->enc_ctx) {
1051  AVCodecContext *enc = ost->enc_ctx;
1052  AVIOContext *s = NULL;
1053  char *buf = NULL, *arg = NULL, *preset = NULL;
1054  const char *enc_stats_pre = NULL, *enc_stats_post = NULL, *mux_stats = NULL;
1055 
1056  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, enc->codec_id,
1057  oc, st, enc->codec);
1058 
1059  MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
1060  ost->autoscale = 1;
1061  MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
1062  if (preset && (!(ret = get_preset_file_2(preset, enc->codec->name, &s)))) {
1063  AVBPrint bprint;
1065  do {
1066  av_bprint_clear(&bprint);
1067  buf = get_line(s, &bprint);
1068  if (!buf[0] || buf[0] == '#')
1069  continue;
1070  if (!(arg = strchr(buf, '='))) {
1071  av_log(ost, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1072  exit_program(1);
1073  }
1074  *arg++ = 0;
1075  av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1076  } while (!s->eof_reached);
1077  av_bprint_finalize(&bprint, NULL);
1078  avio_closep(&s);
1079  }
1080  if (ret) {
1082  "Preset %s specified, but could not be opened.\n", preset);
1083  exit_program(1);
1084  }
1085 
1086  MATCH_PER_STREAM_OPT(enc_stats_pre, str, enc_stats_pre, oc, st);
1087  if (enc_stats_pre &&
1089  const char *format = "{fidx} {sidx} {n} {t}";
1090 
1091  MATCH_PER_STREAM_OPT(enc_stats_pre_fmt, str, format, oc, st);
1092 
1093  ret = enc_stats_init(ost, &ost->enc_stats_pre, 1, enc_stats_pre, format);
1094  if (ret < 0)
1095  exit_program(1);
1096  }
1097 
1098  MATCH_PER_STREAM_OPT(enc_stats_post, str, enc_stats_post, oc, st);
1099  if (enc_stats_post &&
1101  const char *format = "{fidx} {sidx} {n} {t}";
1102 
1103  MATCH_PER_STREAM_OPT(enc_stats_post_fmt, str, format, oc, st);
1104 
1105  ret = enc_stats_init(ost, &ost->enc_stats_post, 0, enc_stats_post, format);
1106  if (ret < 0)
1107  exit_program(1);
1108  }
1109 
1110  MATCH_PER_STREAM_OPT(mux_stats, str, mux_stats, oc, st);
1111  if (mux_stats &&
1113  const char *format = "{fidx} {sidx} {n} {t}";
1114 
1115  MATCH_PER_STREAM_OPT(mux_stats_fmt, str, format, oc, st);
1116 
1117  ret = enc_stats_init(ost, &ms->stats, 0, mux_stats, format);
1118  if (ret < 0)
1119  exit_program(1);
1120  }
1121  } else {
1122  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);
1123  }
1124 
1125 
1126  if (o->bitexact) {
1127  ost->bitexact = 1;
1128  } else if (ost->enc_ctx) {
1129  ost->bitexact = check_opt_bitexact(ost->enc_ctx, ost->encoder_opts, "flags",
1131  }
1132 
1133  MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
1134  if (time_base) {
1135  AVRational q;
1136  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1137  q.num <= 0 || q.den <= 0) {
1138  av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1139  exit_program(1);
1140  }
1141  st->time_base = q;
1142  }
1143 
1144  MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);
1145  if (time_base) {
1146  AVRational q;
1147  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1148  q.den <= 0) {
1149  av_log(ost, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1150  exit_program(1);
1151  }
1152  ost->enc_timebase = q;
1153  }
1154 
1155  ms->max_frames = INT64_MAX;
1156  MATCH_PER_STREAM_OPT(max_frames, i64, ms->max_frames, oc, st);
1157  for (i = 0; i<o->nb_max_frames; i++) {
1158  char *p = o->max_frames[i].specifier;
1159  if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1160  av_log(ost, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1161  break;
1162  }
1163  }
1164 
1165  ms->copy_prior_start = -1;
1166  MATCH_PER_STREAM_OPT(copy_prior_start, i, ms->copy_prior_start, oc ,st);
1167 
1168  MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
1169  if (bsfs && *bsfs) {
1170  ret = av_bsf_list_parse_str(bsfs, &ms->bsf_ctx);
1171  if (ret < 0) {
1172  av_log(ost, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1173  exit_program(1);
1174  }
1175  }
1176 
1177  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1178  if (codec_tag) {
1179  uint32_t tag = strtol(codec_tag, &next, 0);
1180  if (*next) {
1181  uint8_t buf[4] = { 0 };
1182  memcpy(buf, codec_tag, FFMIN(sizeof(buf), strlen(codec_tag)));
1183  tag = AV_RL32(buf);
1184  }
1185  ost->st->codecpar->codec_tag = tag;
1186  ost->par_in->codec_tag = tag;
1187  if (ost->enc_ctx)
1188  ost->enc_ctx->codec_tag = tag;
1189  }
1190 
1191  MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1192  if (ost->enc_ctx && qscale >= 0) {
1193  ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
1194  ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1195  }
1196 
1197  ms->max_muxing_queue_size = 128;
1198  MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ms->max_muxing_queue_size, oc, st);
1199 
1200  ms->muxing_queue_data_threshold = 50*1024*1024;
1201  MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, ms->muxing_queue_data_threshold, oc, st);
1202 
1203  MATCH_PER_STREAM_OPT(bits_per_raw_sample, i, ost->bits_per_raw_sample,
1204  oc, st);
1205 
1206  MATCH_PER_STREAM_OPT(fix_sub_duration_heartbeat, i, ost->fix_sub_duration_heartbeat,
1207  oc, st);
1208 
1209  if (oc->oformat->flags & AVFMT_GLOBALHEADER && ost->enc_ctx)
1210  ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1211 
1212  av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
1213 
1214  av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1215  if (ost->enc_ctx && av_get_exact_bits_per_sample(ost->enc_ctx->codec_id) == 24)
1216  av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1217 
1218  ost->last_mux_dts = AV_NOPTS_VALUE;
1219 
1220  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i,
1221  ms->copy_initial_nonkeyframes, oc, st);
1222 
1223  switch (type) {
1224  case AVMEDIA_TYPE_VIDEO: new_stream_video (mux, o, ost); break;
1225  case AVMEDIA_TYPE_AUDIO: new_stream_audio (mux, o, ost); break;
1226  case AVMEDIA_TYPE_SUBTITLE: new_stream_subtitle (mux, o, ost); break;
1227  case AVMEDIA_TYPE_ATTACHMENT: new_stream_attachment(mux, o, ost); break;
1228  }
1229 
1231  ret = ost_get_filters(o, oc, ost);
1232  if (ret < 0)
1233  exit_program(1);
1234  }
1235 
1236  if (ost->ist) {
1237  if (ost->enc &&
1240  if (ret < 0) {
1242  "Error initializing a simple filtergraph\n");
1243  exit_program(1);
1244  }
1245  } else {
1246  ret = ist_output_add(ost->ist, ost);
1247  if (ret < 0) {
1249  "Error binding an input stream\n");
1250  exit_program(1);
1251  }
1252  }
1253  }
1254 
1255  if (ost->ist && !ost->enc) {
1256  ret = streamcopy_init(mux, ost);
1257  if (ret < 0)
1258  exit_program(1);
1259  }
1260 
1261  return ost;
1262 }
1263 
1264 // add a new output stream fed by the provided filtergraph output
1265 static void ost_add_from_filter(OutputFilter *ofilter, const OptionsContext *o,
1266  Muxer *mux)
1267 {
1268  OutputStream *ost = ost_add(mux, o, ofilter->type, NULL);
1269 
1270  ost->filter = ofilter;
1271 
1272  ofilter->ost = ost;
1273 
1274  if (!ost->enc_ctx) {
1275  av_log(ost, AV_LOG_ERROR, "Streamcopy requested for output stream fed "
1276  "from a complex filtergraph. Filtering and streamcopy "
1277  "cannot be used together.\n");
1278  exit_program(1);
1279  }
1280 
1281  avfilter_inout_free(&ofilter->out_tmp);
1282 }
1283 
1284 static void map_auto_video(Muxer *mux, const OptionsContext *o)
1285 {
1286  AVFormatContext *oc = mux->fc;
1287  InputStream *best_ist = NULL;
1288  int best_score = 0;
1289  int qcr;
1290 
1291  /* video: highest resolution */
1293  return;
1294 
1295  qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
1296  for (int j = 0; j < nb_input_files; j++) {
1297  InputFile *ifile = input_files[j];
1298  InputStream *file_best_ist = NULL;
1299  int file_best_score = 0;
1300  for (int i = 0; i < ifile->nb_streams; i++) {
1301  InputStream *ist = ifile->streams[i];
1302  int score;
1303 
1304  if (ist->user_set_discard == AVDISCARD_ALL ||
1306  continue;
1307 
1308  score = ist->st->codecpar->width * ist->st->codecpar->height
1309  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
1310  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
1311  if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1312  score = 1;
1313 
1314  if (score > file_best_score) {
1315  if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1316  continue;
1317  file_best_score = score;
1318  file_best_ist = ist;
1319  }
1320  }
1321  if (file_best_ist) {
1322  if((qcr == MKTAG('A', 'P', 'I', 'C')) ||
1323  !(file_best_ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
1324  file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
1325  if (file_best_score > best_score) {
1326  best_score = file_best_score;
1327  best_ist = file_best_ist;
1328  }
1329  }
1330  }
1331  if (best_ist)
1332  ost_add(mux, o, AVMEDIA_TYPE_VIDEO, best_ist);
1333 }
1334 
1335 static void map_auto_audio(Muxer *mux, const OptionsContext *o)
1336 {
1337  AVFormatContext *oc = mux->fc;
1338  InputStream *best_ist = NULL;
1339  int best_score = 0;
1340 
1341  /* audio: most channels */
1343  return;
1344 
1345  for (int j = 0; j < nb_input_files; j++) {
1346  InputFile *ifile = input_files[j];
1347  InputStream *file_best_ist = NULL;
1348  int file_best_score = 0;
1349  for (int i = 0; i < ifile->nb_streams; i++) {
1350  InputStream *ist = ifile->streams[i];
1351  int score;
1352 
1353  if (ist->user_set_discard == AVDISCARD_ALL ||
1355  continue;
1356 
1357  score = ist->st->codecpar->ch_layout.nb_channels
1358  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
1359  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
1360  if (score > file_best_score) {
1361  file_best_score = score;
1362  file_best_ist = ist;
1363  }
1364  }
1365  if (file_best_ist) {
1366  file_best_score -= 5000000*!!(file_best_ist->st->disposition & AV_DISPOSITION_DEFAULT);
1367  if (file_best_score > best_score) {
1368  best_score = file_best_score;
1369  best_ist = file_best_ist;
1370  }
1371  }
1372  }
1373  if (best_ist)
1374  ost_add(mux, o, AVMEDIA_TYPE_AUDIO, best_ist);
1375 }
1376 
1377 static void map_auto_subtitle(Muxer *mux, const OptionsContext *o)
1378 {
1379  AVFormatContext *oc = mux->fc;
1380  char *subtitle_codec_name = NULL;
1381 
1382  /* subtitles: pick first */
1383  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
1385  return;
1386 
1387  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist))
1388  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1389  AVCodecDescriptor const *input_descriptor =
1390  avcodec_descriptor_get(ist->st->codecpar->codec_id);
1391  AVCodecDescriptor const *output_descriptor = NULL;
1392  AVCodec const *output_codec =
1394  int input_props = 0, output_props = 0;
1395  if (ist->user_set_discard == AVDISCARD_ALL)
1396  continue;
1397  if (output_codec)
1398  output_descriptor = avcodec_descriptor_get(output_codec->id);
1399  if (input_descriptor)
1400  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1401  if (output_descriptor)
1402  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
1403  if (subtitle_codec_name ||
1404  input_props & output_props ||
1405  // Map dvb teletext which has neither property to any output subtitle encoder
1406  input_descriptor && output_descriptor &&
1407  (!input_descriptor->props ||
1408  !output_descriptor->props)) {
1409  ost_add(mux, o, AVMEDIA_TYPE_SUBTITLE, ist);
1410  break;
1411  }
1412  }
1413 }
1414 
1415 static void map_auto_data(Muxer *mux, const OptionsContext *o)
1416 {
1417  AVFormatContext *oc = mux->fc;
1418  /* Data only if codec id match */
1420 
1421  if (codec_id == AV_CODEC_ID_NONE)
1422  return;
1423 
1424  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
1425  if (ist->user_set_discard == AVDISCARD_ALL)
1426  continue;
1427  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA &&
1428  ist->st->codecpar->codec_id == codec_id )
1429  ost_add(mux, o, AVMEDIA_TYPE_DATA, ist);
1430  }
1431 }
1432 
1433 static void map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
1434 {
1435  InputStream *ist;
1436 
1437  if (map->disabled)
1438  return;
1439 
1440  if (map->linklabel) {
1441  FilterGraph *fg;
1442  OutputFilter *ofilter = NULL;
1443  int j, k;
1444 
1445  for (j = 0; j < nb_filtergraphs; j++) {
1446  fg = filtergraphs[j];
1447  for (k = 0; k < fg->nb_outputs; k++) {
1448  AVFilterInOut *out = fg->outputs[k]->out_tmp;
1449  if (out && !strcmp(out->name, map->linklabel)) {
1450  ofilter = fg->outputs[k];
1451  goto loop_end;
1452  }
1453  }
1454  }
1455 loop_end:
1456  if (!ofilter) {
1457  av_log(mux, AV_LOG_FATAL, "Output with label '%s' does not exist "
1458  "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
1459  exit_program(1);
1460  }
1461  ost_add_from_filter(ofilter, o, mux);
1462  } else {
1463  ist = input_files[map->file_index]->streams[map->stream_index];
1464  if (ist->user_set_discard == AVDISCARD_ALL) {
1465  av_log(mux, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
1466  map->file_index, map->stream_index);
1467  exit_program(1);
1468  }
1470  return;
1472  return;
1474  return;
1475  if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
1476  return;
1477 
1478  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN &&
1481  "Cannot map stream #%d:%d - unsupported type.\n",
1482  map->file_index, map->stream_index);
1483  if (!ignore_unknown_streams) {
1484  av_log(mux, AV_LOG_FATAL,
1485  "If you want unsupported types ignored instead "
1486  "of failing, please use the -ignore_unknown option\n"
1487  "If you want them copied, please use -copy_unknown\n");
1488  exit_program(1);
1489  }
1490  return;
1491  }
1492 
1493  ost_add(mux, o, ist->st->codecpar->codec_type, ist);
1494  }
1495 }
1496 
1497 static void of_add_attachments(Muxer *mux, const OptionsContext *o)
1498 {
1499  OutputStream *ost;
1500  int err;
1501 
1502  for (int i = 0; i < o->nb_attachments; i++) {
1503  AVIOContext *pb;
1504  uint8_t *attachment;
1505  const char *p;
1506  int64_t len;
1507 
1508  if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
1509  av_log(mux, AV_LOG_FATAL, "Could not open attachment file %s.\n",
1510  o->attachments[i]);
1511  exit_program(1);
1512  }
1513  if ((len = avio_size(pb)) <= 0) {
1514  av_log(mux, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
1515  o->attachments[i]);
1516  exit_program(1);
1517  }
1518  if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ||
1519  !(attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE))) {
1520  av_log(mux, AV_LOG_FATAL, "Attachment %s too large.\n",
1521  o->attachments[i]);
1522  exit_program(1);
1523  }
1524  avio_read(pb, attachment, len);
1525  memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
1526 
1528  ost->attachment_filename = o->attachments[i];
1529  ost->par_in->extradata = attachment;
1530  ost->par_in->extradata_size = len;
1531 
1532  p = strrchr(o->attachments[i], '/');
1533  av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
1534  avio_closep(&pb);
1535  }
1536 }
1537 
1538 static void create_streams(Muxer *mux, const OptionsContext *o)
1539 {
1540  AVFormatContext *oc = mux->fc;
1541  int auto_disable_v = o->video_disable;
1542  int auto_disable_a = o->audio_disable;
1543  int auto_disable_s = o->subtitle_disable;
1544  int auto_disable_d = o->data_disable;
1545 
1546  /* create streams for all unlabeled output pads */
1547  for (int i = 0; i < nb_filtergraphs; i++) {
1548  FilterGraph *fg = filtergraphs[i];
1549  for (int j = 0; j < fg->nb_outputs; j++) {
1550  OutputFilter *ofilter = fg->outputs[j];
1551 
1552  if (!ofilter->out_tmp || ofilter->out_tmp->name)
1553  continue;
1554 
1555  switch (ofilter->type) {
1556  case AVMEDIA_TYPE_VIDEO: auto_disable_v = 1; break;
1557  case AVMEDIA_TYPE_AUDIO: auto_disable_a = 1; break;
1558  case AVMEDIA_TYPE_SUBTITLE: auto_disable_s = 1; break;
1559  }
1560  ost_add_from_filter(ofilter, o, mux);
1561  }
1562  }
1563 
1564  if (!o->nb_stream_maps) {
1565  /* pick the "best" stream of each type */
1566  if (!auto_disable_v)
1567  map_auto_video(mux, o);
1568  if (!auto_disable_a)
1569  map_auto_audio(mux, o);
1570  if (!auto_disable_s)
1571  map_auto_subtitle(mux, o);
1572  if (!auto_disable_d)
1573  map_auto_data(mux, o);
1574  } else {
1575  for (int i = 0; i < o->nb_stream_maps; i++)
1576  map_manual(mux, o, &o->stream_maps[i]);
1577  }
1578 
1579  of_add_attachments(mux, o);
1580 
1581  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
1582  av_dump_format(oc, nb_output_files - 1, oc->url, 1);
1583  av_log(mux, AV_LOG_ERROR, "Output file does not contain any stream\n");
1584  exit_program(1);
1585  }
1586 }
1587 
1588 static int setup_sync_queues(Muxer *mux, AVFormatContext *oc, int64_t buf_size_us)
1589 {
1590  OutputFile *of = &mux->of;
1591  int nb_av_enc = 0, nb_audio_fs = 0, nb_interleaved = 0;
1592  int limit_frames = 0, limit_frames_av_enc = 0;
1593 
1594 #define IS_AV_ENC(ost, type) \
1595  (ost->enc_ctx && (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO))
1596 #define IS_INTERLEAVED(type) (type != AVMEDIA_TYPE_ATTACHMENT)
1597 
1598  for (int i = 0; i < oc->nb_streams; i++) {
1599  OutputStream *ost = of->streams[i];
1600  MuxStream *ms = ms_from_ost(ost);
1601  enum AVMediaType type = ost->type;
1602 
1603  ost->sq_idx_encode = -1;
1604  ost->sq_idx_mux = -1;
1605 
1606  nb_interleaved += IS_INTERLEAVED(type);
1607  nb_av_enc += IS_AV_ENC(ost, type);
1608  nb_audio_fs += (ost->enc_ctx && type == AVMEDIA_TYPE_AUDIO &&
1609  !(ost->enc_ctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE));
1610 
1611  limit_frames |= ms->max_frames < INT64_MAX;
1612  limit_frames_av_enc |= (ms->max_frames < INT64_MAX) && IS_AV_ENC(ost, type);
1613  }
1614 
1615  if (!((nb_interleaved > 1 && of->shortest) ||
1616  (nb_interleaved > 0 && limit_frames) ||
1617  nb_audio_fs))
1618  return 0;
1619 
1620  /* we use a sync queue before encoding when:
1621  * - 'shortest' is in effect and we have two or more encoded audio/video
1622  * streams
1623  * - at least one encoded audio/video stream is frame-limited, since
1624  * that has similar semantics to 'shortest'
1625  * - at least one audio encoder requires constant frame sizes
1626  */
1627  if ((of->shortest && nb_av_enc > 1) || limit_frames_av_enc || nb_audio_fs) {
1628  of->sq_encode = sq_alloc(SYNC_QUEUE_FRAMES, buf_size_us, mux);
1629  if (!of->sq_encode)
1630  return AVERROR(ENOMEM);
1631 
1632  for (int i = 0; i < oc->nb_streams; i++) {
1633  OutputStream *ost = of->streams[i];
1634  MuxStream *ms = ms_from_ost(ost);
1635  enum AVMediaType type = ost->type;
1636 
1637  if (!IS_AV_ENC(ost, type))
1638  continue;
1639 
1640  ost->sq_idx_encode = sq_add_stream(of->sq_encode,
1641  of->shortest || ms->max_frames < INT64_MAX);
1642  if (ost->sq_idx_encode < 0)
1643  return ost->sq_idx_encode;
1644 
1645  if (ms->max_frames != INT64_MAX)
1646  sq_limit_frames(of->sq_encode, ost->sq_idx_encode, ms->max_frames);
1647  }
1648  }
1649 
1650  /* if there are any additional interleaved streams, then ALL the streams
1651  * are also synchronized before sending them to the muxer */
1652  if (nb_interleaved > nb_av_enc) {
1653  mux->sq_mux = sq_alloc(SYNC_QUEUE_PACKETS, buf_size_us, mux);
1654  if (!mux->sq_mux)
1655  return AVERROR(ENOMEM);
1656 
1657  mux->sq_pkt = av_packet_alloc();
1658  if (!mux->sq_pkt)
1659  return AVERROR(ENOMEM);
1660 
1661  for (int i = 0; i < oc->nb_streams; i++) {
1662  OutputStream *ost = of->streams[i];
1663  MuxStream *ms = ms_from_ost(ost);
1664  enum AVMediaType type = ost->type;
1665 
1666  if (!IS_INTERLEAVED(type))
1667  continue;
1668 
1669  ost->sq_idx_mux = sq_add_stream(mux->sq_mux,
1670  of->shortest || ms->max_frames < INT64_MAX);
1671  if (ost->sq_idx_mux < 0)
1672  return ost->sq_idx_mux;
1673 
1674  if (ms->max_frames != INT64_MAX)
1675  sq_limit_frames(mux->sq_mux, ost->sq_idx_mux, ms->max_frames);
1676  }
1677  }
1678 
1679 #undef IS_AV_ENC
1680 #undef IS_INTERLEAVED
1681 
1682  return 0;
1683 }
1684 
1685 static void of_add_programs(Muxer *mux, const OptionsContext *o)
1686 {
1687  AVFormatContext *oc = mux->fc;
1688  /* process manually set programs */
1689  for (int i = 0; i < o->nb_program; i++) {
1690  const char *p = o->program[i].u.str;
1691  int progid = i+1;
1692  AVProgram *program;
1693 
1694  while(*p) {
1695  const char *p2 = av_get_token(&p, ":");
1696  const char *to_dealloc = p2;
1697  char *key;
1698  if (!p2)
1699  break;
1700 
1701  if(*p) p++;
1702 
1703  key = av_get_token(&p2, "=");
1704  if (!key || !*p2) {
1705  av_freep(&to_dealloc);
1706  av_freep(&key);
1707  break;
1708  }
1709  p2++;
1710 
1711  if (!strcmp(key, "program_num"))
1712  progid = strtol(p2, NULL, 0);
1713  av_freep(&to_dealloc);
1714  av_freep(&key);
1715  }
1716 
1717  program = av_new_program(oc, progid);
1718  if (!program)
1719  report_and_exit(AVERROR(ENOMEM));
1720 
1721  p = o->program[i].u.str;
1722  while(*p) {
1723  const char *p2 = av_get_token(&p, ":");
1724  const char *to_dealloc = p2;
1725  char *key;
1726  if (!p2)
1727  break;
1728  if(*p) p++;
1729 
1730  key = av_get_token(&p2, "=");
1731  if (!key) {
1732  av_log(mux, AV_LOG_FATAL,
1733  "No '=' character in program string %s.\n",
1734  p2);
1735  exit_program(1);
1736  }
1737  if (!*p2)
1738  exit_program(1);
1739  p2++;
1740 
1741  if (!strcmp(key, "title")) {
1742  av_dict_set(&program->metadata, "title", p2, 0);
1743  } else if (!strcmp(key, "program_num")) {
1744  } else if (!strcmp(key, "st")) {
1745  int st_num = strtol(p2, NULL, 0);
1746  av_program_add_stream_index(oc, progid, st_num);
1747  } else {
1748  av_log(mux, AV_LOG_FATAL, "Unknown program key %s.\n", key);
1749  exit_program(1);
1750  }
1751  av_freep(&to_dealloc);
1752  av_freep(&key);
1753  }
1754  }
1755 }
1756 
1757 /**
1758  * Parse a metadata specifier passed as 'arg' parameter.
1759  * @param arg metadata string to parse
1760  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
1761  * @param index for type c/p, chapter/program index is written here
1762  * @param stream_spec for type s, the stream specifier is written here
1763  */
1764 static void parse_meta_type(void *logctx, const char *arg,
1765  char *type, int *index, const char **stream_spec)
1766 {
1767  if (*arg) {
1768  *type = *arg;
1769  switch (*arg) {
1770  case 'g':
1771  break;
1772  case 's':
1773  if (*(++arg) && *arg != ':') {
1774  av_log(logctx, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
1775  exit_program(1);
1776  }
1777  *stream_spec = *arg == ':' ? arg + 1 : "";
1778  break;
1779  case 'c':
1780  case 'p':
1781  if (*(++arg) == ':')
1782  *index = strtol(++arg, NULL, 0);
1783  break;
1784  default:
1785  av_log(logctx, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
1786  exit_program(1);
1787  }
1788  } else
1789  *type = 'g';
1790 }
1791 
1793  const OptionsContext *o)
1794 {
1795  for (int i = 0; i < o->nb_metadata; i++) {
1796  AVDictionary **m;
1797  char type, *val;
1798  const char *stream_spec;
1799  int index = 0, ret = 0;
1800 
1801  val = strchr(o->metadata[i].u.str, '=');
1802  if (!val) {
1803  av_log(of, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
1804  o->metadata[i].u.str);
1805  exit_program(1);
1806  }
1807  *val++ = 0;
1808 
1809  parse_meta_type(of, o->metadata[i].specifier, &type, &index, &stream_spec);
1810  if (type == 's') {
1811  for (int j = 0; j < oc->nb_streams; j++) {
1812  OutputStream *ost = of->streams[j];
1813  if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
1814 #if FFMPEG_ROTATION_METADATA
1815  if (!strcmp(o->metadata[i].u.str, "rotate")) {
1816  char *tail;
1817  double theta = av_strtod(val, &tail);
1818  if (!*tail) {
1819  ost->rotate_overridden = 1;
1820  ost->rotate_override_value = theta;
1821  }
1822 
1824  "Conversion of a 'rotate' metadata key to a "
1825  "proper display matrix rotation is deprecated. "
1826  "See -display_rotation for setting rotation "
1827  "instead.");
1828  } else {
1829 #endif
1830  av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
1831 #if FFMPEG_ROTATION_METADATA
1832  }
1833 #endif
1834  } else if (ret < 0)
1835  exit_program(1);
1836  }
1837  } else {
1838  switch (type) {
1839  case 'g':
1840  m = &oc->metadata;
1841  break;
1842  case 'c':
1843  if (index < 0 || index >= oc->nb_chapters) {
1844  av_log(of, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
1845  exit_program(1);
1846  }
1847  m = &oc->chapters[index]->metadata;
1848  break;
1849  case 'p':
1850  if (index < 0 || index >= oc->nb_programs) {
1851  av_log(of, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
1852  exit_program(1);
1853  }
1854  m = &oc->programs[index]->metadata;
1855  break;
1856  default:
1857  av_log(of, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
1858  exit_program(1);
1859  }
1860  av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
1861  }
1862  }
1863 }
1864 
1866 {
1867  const AVCodec *c = ost->enc_ctx->codec;
1868  int i, err;
1869 
1870  if (ost->enc_ctx->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
1871  /* Pass the layout through for all orders but UNSPEC */
1872  err = av_channel_layout_copy(&f->ch_layout, &ost->enc_ctx->ch_layout);
1873  if (err < 0)
1874  report_and_exit(AVERROR(ENOMEM));
1875  return;
1876  }
1877 
1878  /* Requested layout is of order UNSPEC */
1879  if (!c->ch_layouts) {
1880  /* Use the default native layout for the requested amount of channels when the
1881  encoder doesn't have a list of supported layouts */
1882  av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
1883  return;
1884  }
1885  /* Encoder has a list of supported layouts. Pick the first layout in it with the
1886  same amount of channels as the requested layout */
1887  for (i = 0; c->ch_layouts[i].nb_channels; i++) {
1888  if (c->ch_layouts[i].nb_channels == ost->enc_ctx->ch_layout.nb_channels)
1889  break;
1890  }
1891  if (c->ch_layouts[i].nb_channels) {
1892  /* Use it if one is found */
1893  err = av_channel_layout_copy(&f->ch_layout, &c->ch_layouts[i]);
1894  if (err < 0)
1895  report_and_exit(AVERROR(ENOMEM));
1896  return;
1897  }
1898  /* If no layout for the amount of channels requested was found, use the default
1899  native layout for it. */
1900  av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
1901 }
1902 
1903 static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os,
1904  int copy_metadata)
1905 {
1906  AVFormatContext *is = ifile->ctx;
1907  AVChapter **tmp;
1908  int i;
1909 
1910  tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
1911  if (!tmp)
1912  return AVERROR(ENOMEM);
1913  os->chapters = tmp;
1914 
1915  for (i = 0; i < is->nb_chapters; i++) {
1916  AVChapter *in_ch = is->chapters[i], *out_ch;
1917  int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
1918  int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
1919  AV_TIME_BASE_Q, in_ch->time_base);
1920  int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
1922 
1923 
1924  if (in_ch->end < ts_off)
1925  continue;
1926  if (rt != INT64_MAX && in_ch->start > rt + ts_off)
1927  break;
1928 
1929  out_ch = av_mallocz(sizeof(AVChapter));
1930  if (!out_ch)
1931  return AVERROR(ENOMEM);
1932 
1933  out_ch->id = in_ch->id;
1934  out_ch->time_base = in_ch->time_base;
1935  out_ch->start = FFMAX(0, in_ch->start - ts_off);
1936  out_ch->end = FFMIN(rt, in_ch->end - ts_off);
1937 
1938  if (copy_metadata)
1939  av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
1940 
1941  os->chapters[os->nb_chapters++] = out_ch;
1942  }
1943  return 0;
1944 }
1945 
1946 static int copy_metadata(Muxer *mux, AVFormatContext *ic,
1947  const char *outspec, const char *inspec,
1948  int *metadata_global_manual, int *metadata_streams_manual,
1949  int *metadata_chapters_manual)
1950 {
1951  AVFormatContext *oc = mux->fc;
1952  AVDictionary **meta_in = NULL;
1953  AVDictionary **meta_out = NULL;
1954  int i, ret = 0;
1955  char type_in, type_out;
1956  const char *istream_spec = NULL, *ostream_spec = NULL;
1957  int idx_in = 0, idx_out = 0;
1958 
1959  parse_meta_type(mux, inspec, &type_in, &idx_in, &istream_spec);
1960  parse_meta_type(mux, outspec, &type_out, &idx_out, &ostream_spec);
1961 
1962  if (type_in == 'g' || type_out == 'g' || !*outspec)
1963  *metadata_global_manual = 1;
1964  if (type_in == 's' || type_out == 's' || !*outspec)
1965  *metadata_streams_manual = 1;
1966  if (type_in == 'c' || type_out == 'c' || !*outspec)
1967  *metadata_chapters_manual = 1;
1968 
1969  /* ic is NULL when just disabling automatic mappings */
1970  if (!ic)
1971  return 0;
1972 
1973 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
1974  if ((index) < 0 || (index) >= (nb_elems)) {\
1975  av_log(mux, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
1976  (desc), (index));\
1977  exit_program(1);\
1978  }
1979 
1980 #define SET_DICT(type, meta, context, index)\
1981  switch (type) {\
1982  case 'g':\
1983  meta = &context->metadata;\
1984  break;\
1985  case 'c':\
1986  METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
1987  meta = &context->chapters[index]->metadata;\
1988  break;\
1989  case 'p':\
1990  METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
1991  meta = &context->programs[index]->metadata;\
1992  break;\
1993  case 's':\
1994  break; /* handled separately below */ \
1995  default: av_assert0(0);\
1996  }\
1997 
1998  SET_DICT(type_in, meta_in, ic, idx_in);
1999  SET_DICT(type_out, meta_out, oc, idx_out);
2000 
2001  /* for input streams choose first matching stream */
2002  if (type_in == 's') {
2003  for (i = 0; i < ic->nb_streams; i++) {
2004  if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
2005  meta_in = &ic->streams[i]->metadata;
2006  break;
2007  } else if (ret < 0)
2008  exit_program(1);
2009  }
2010  if (!meta_in) {
2011  av_log(mux, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
2012  exit_program(1);
2013  }
2014  }
2015 
2016  if (type_out == 's') {
2017  for (i = 0; i < oc->nb_streams; i++) {
2018  if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
2019  meta_out = &oc->streams[i]->metadata;
2020  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
2021  } else if (ret < 0)
2022  exit_program(1);
2023  }
2024  } else
2025  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
2026 
2027  return 0;
2028 }
2029 
2030 static void copy_meta(Muxer *mux, const OptionsContext *o)
2031 {
2032  OutputFile *of = &mux->of;
2033  AVFormatContext *oc = mux->fc;
2034  int chapters_input_file = o->chapters_input_file;
2035  int metadata_global_manual = 0;
2036  int metadata_streams_manual = 0;
2037  int metadata_chapters_manual = 0;
2038 
2039  /* copy metadata */
2040  for (int i = 0; i < o->nb_metadata_map; i++) {
2041  char *p;
2042  int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
2043 
2044  if (in_file_index >= nb_input_files) {
2045  av_log(mux, AV_LOG_FATAL, "Invalid input file index %d while "
2046  "processing metadata maps\n", in_file_index);
2047  exit_program(1);
2048  }
2049  copy_metadata(mux,
2050  in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL,
2051  o->metadata_map[i].specifier, *p ? p + 1 : p,
2052  &metadata_global_manual, &metadata_streams_manual,
2053  &metadata_chapters_manual);
2054  }
2055 
2056  /* copy chapters */
2057  if (chapters_input_file >= nb_input_files) {
2058  if (chapters_input_file == INT_MAX) {
2059  /* copy chapters from the first input file that has them*/
2060  chapters_input_file = -1;
2061  for (int i = 0; i < nb_input_files; i++)
2062  if (input_files[i]->ctx->nb_chapters) {
2063  chapters_input_file = i;
2064  break;
2065  }
2066  } else {
2067  av_log(mux, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
2068  chapters_input_file);
2069  exit_program(1);
2070  }
2071  }
2072  if (chapters_input_file >= 0)
2073  copy_chapters(input_files[chapters_input_file], of, oc,
2074  !metadata_chapters_manual);
2075 
2076  /* copy global metadata by default */
2077  if (!metadata_global_manual && nb_input_files){
2080  if (of->recording_time != INT64_MAX)
2081  av_dict_set(&oc->metadata, "duration", NULL, 0);
2082  av_dict_set(&oc->metadata, "creation_time", NULL, 0);
2083  av_dict_set(&oc->metadata, "company_name", NULL, 0);
2084  av_dict_set(&oc->metadata, "product_name", NULL, 0);
2085  av_dict_set(&oc->metadata, "product_version", NULL, 0);
2086  }
2087  if (!metadata_streams_manual)
2088  for (int i = 0; i < of->nb_streams; i++) {
2089  OutputStream *ost = of->streams[i];
2090 
2091  if (!ost->ist) /* this is true e.g. for attached files */
2092  continue;
2094  if (ost->enc_ctx) {
2095  av_dict_set(&ost->st->metadata, "encoder", NULL, 0);
2096  }
2097  }
2098 }
2099 
2100 static int set_dispositions(Muxer *mux, const OptionsContext *o)
2101 {
2102  OutputFile *of = &mux->of;
2103  AVFormatContext *ctx = mux->fc;
2104 
2105  int nb_streams[AVMEDIA_TYPE_NB] = { 0 };
2106  int have_default[AVMEDIA_TYPE_NB] = { 0 };
2107  int have_manual = 0;
2108  int ret = 0;
2109 
2110  const char **dispositions;
2111 
2112  dispositions = av_calloc(ctx->nb_streams, sizeof(*dispositions));
2113  if (!dispositions)
2114  return AVERROR(ENOMEM);
2115 
2116  // first, copy the input dispositions
2117  for (int i = 0; i < ctx->nb_streams; i++) {
2118  OutputStream *ost = of->streams[i];
2119 
2120  nb_streams[ost->type]++;
2121 
2122  MATCH_PER_STREAM_OPT(disposition, str, dispositions[i], ctx, ost->st);
2123 
2124  have_manual |= !!dispositions[i];
2125 
2126  if (ost->ist) {
2127  ost->st->disposition = ost->ist->st->disposition;
2128 
2130  have_default[ost->type] = 1;
2131  }
2132  }
2133 
2134  if (have_manual) {
2135  // process manually set dispositions - they override the above copy
2136  for (int i = 0; i < ctx->nb_streams; i++) {
2137  OutputStream *ost = of->streams[i];
2138  const char *disp = dispositions[i];
2139 
2140  if (!disp)
2141  continue;
2142 
2143  ret = av_opt_set(ost->st, "disposition", disp, 0);
2144  if (ret < 0)
2145  goto finish;
2146  }
2147  } else {
2148  // For each media type with more than one stream, find a suitable stream to
2149  // mark as default, unless one is already marked default.
2150  // "Suitable" means the first of that type, skipping attached pictures.
2151  for (int i = 0; i < ctx->nb_streams; i++) {
2152  OutputStream *ost = of->streams[i];
2153  enum AVMediaType type = ost->type;
2154 
2155  if (nb_streams[type] < 2 || have_default[type] ||
2157  continue;
2158 
2160  have_default[type] = 1;
2161  }
2162  }
2163 
2164 finish:
2165  av_freep(&dispositions);
2166 
2167  return ret;
2168 }
2169 
2170 const char *const forced_keyframes_const_names[] = {
2171  "n",
2172  "n_forced",
2173  "prev_forced_n",
2174  "prev_forced_t",
2175  "t",
2176  NULL
2177 };
2178 
2179 static int compare_int64(const void *a, const void *b)
2180 {
2181  return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
2182 }
2183 
2184 static void parse_forced_key_frames(KeyframeForceCtx *kf, const Muxer *mux,
2185  const char *spec)
2186 {
2187  const char *p;
2188  int n = 1, i, size, index = 0;
2189  int64_t t, *pts;
2190 
2191  for (p = spec; *p; p++)
2192  if (*p == ',')
2193  n++;
2194  size = n;
2195  pts = av_malloc_array(size, sizeof(*pts));
2196  if (!pts)
2197  report_and_exit(AVERROR(ENOMEM));
2198 
2199  p = spec;
2200  for (i = 0; i < n; i++) {
2201  char *next = strchr(p, ',');
2202 
2203  if (next)
2204  *next++ = 0;
2205 
2206  if (strstr(p, "chapters") == p) {
2207  AVChapter * const *ch = mux->fc->chapters;
2208  unsigned int nb_ch = mux->fc->nb_chapters;
2209  int j;
2210 
2211  if (nb_ch > INT_MAX - size ||
2212  !(pts = av_realloc_f(pts, size += nb_ch - 1,
2213  sizeof(*pts))))
2214  report_and_exit(AVERROR(ENOMEM));
2215  t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2216 
2217  for (j = 0; j < nb_ch; j++) {
2218  const AVChapter *c = ch[j];
2219  av_assert1(index < size);
2220  pts[index++] = av_rescale_q(c->start, c->time_base,
2221  AV_TIME_BASE_Q) + t;
2222  }
2223 
2224  } else {
2225  av_assert1(index < size);
2226  pts[index++] = parse_time_or_die("force_key_frames", p, 1);
2227  }
2228 
2229  p = next;
2230  }
2231 
2232  av_assert0(index == size);
2233  qsort(pts, size, sizeof(*pts), compare_int64);
2234  kf->nb_pts = size;
2235  kf->pts = pts;
2236 }
2237 
2239 {
2240  for (int i = 0; i < mux->of.nb_streams; i++) {
2241  OutputStream *ost = mux->of.streams[i];
2242  const char *forced_keyframes = NULL;
2243 
2244  MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_keyframes, mux->fc, ost->st);
2245 
2246  if (!(ost->type == AVMEDIA_TYPE_VIDEO &&
2247  ost->enc_ctx && forced_keyframes))
2248  continue;
2249 
2250  if (!strncmp(forced_keyframes, "expr:", 5)) {
2251  int ret = av_expr_parse(&ost->kf.pexpr, forced_keyframes + 5,
2253  if (ret < 0) {
2255  "Invalid force_key_frames expression '%s'\n", forced_keyframes + 5);
2256  return ret;
2257  }
2258  ost->kf.expr_const_values[FKF_N] = 0;
2259  ost->kf.expr_const_values[FKF_N_FORCED] = 0;
2260  ost->kf.expr_const_values[FKF_PREV_FORCED_N] = NAN;
2261  ost->kf.expr_const_values[FKF_PREV_FORCED_T] = NAN;
2262 
2263  // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
2264  // parse it only for static kf timings
2265  } else if (!strcmp(forced_keyframes, "source")) {
2266  ost->kf.type = KF_FORCE_SOURCE;
2267  } else if (!strcmp(forced_keyframes, "source_no_drop")) {
2268  ost->kf.type = KF_FORCE_SOURCE_NO_DROP;
2269  } else {
2270  parse_forced_key_frames(&ost->kf, mux, forced_keyframes);
2271  }
2272  }
2273 
2274  return 0;
2275 }
2276 
2277 static void validate_enc_avopt(Muxer *mux, const AVDictionary *codec_avopt)
2278 {
2279  const AVClass *class = avcodec_get_class();
2280  const AVClass *fclass = avformat_get_class();
2281  const OutputFile *of = &mux->of;
2282 
2283  AVDictionary *unused_opts;
2284  const AVDictionaryEntry *e;
2285 
2286  unused_opts = strip_specifiers(codec_avopt);
2287  for (int i = 0; i < of->nb_streams; i++) {
2288  e = NULL;
2289  while ((e = av_dict_iterate(of->streams[i]->encoder_opts, e)))
2290  av_dict_set(&unused_opts, e->key, NULL, 0);
2291  }
2292 
2293  e = NULL;
2294  while ((e = av_dict_iterate(unused_opts, e))) {
2295  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
2297  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
2299  if (!option || foption)
2300  continue;
2301 
2302  if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
2303  av_log(mux, AV_LOG_ERROR, "Codec AVOption %s (%s) is not an "
2304  "encoding option.\n", e->key, option->help ? option->help : "");
2305  exit_program(1);
2306  }
2307 
2308  // gop_timecode is injected by generic code but not always used
2309  if (!strcmp(e->key, "gop_timecode"))
2310  continue;
2311 
2312  av_log(mux, AV_LOG_WARNING, "Codec AVOption %s (%s) has not been used "
2313  "for any stream. The most likely reason is either wrong type "
2314  "(e.g. a video option with no video streams) or that it is a "
2315  "private option of some encoder which was not actually used for "
2316  "any stream.\n", e->key, option->help ? option->help : "");
2317  }
2318  av_dict_free(&unused_opts);
2319 }
2320 
2322 {
2323  int ret = 0;
2324 
2325  if (ost->enc_ctx) {
2326  ret = enc_open(ost, NULL);
2327  if (ret < 0)
2328  return ret;
2329  } else {
2330  ret = of_stream_init(output_files[ost->file_index], ost);
2331  if (ret < 0)
2332  return ret;
2333  }
2334 
2335  return ret;
2336 }
2337 
2338 static const char *output_file_item_name(void *obj)
2339 {
2340  const Muxer *mux = obj;
2341 
2342  return mux->log_name;
2343 }
2344 
2345 static const AVClass output_file_class = {
2346  .class_name = "OutputFile",
2347  .version = LIBAVUTIL_VERSION_INT,
2348  .item_name = output_file_item_name,
2349  .category = AV_CLASS_CATEGORY_MUXER,
2350 };
2351 
2352 static Muxer *mux_alloc(void)
2353 {
2354  Muxer *mux = allocate_array_elem(&output_files, sizeof(*mux), &nb_output_files);
2355 
2356  mux->of.class = &output_file_class;
2357  mux->of.index = nb_output_files - 1;
2358 
2359  snprintf(mux->log_name, sizeof(mux->log_name), "out#%d", mux->of.index);
2360 
2361  return mux;
2362 }
2363 
2364 int of_open(const OptionsContext *o, const char *filename)
2365 {
2366  Muxer *mux;
2367  AVFormatContext *oc;
2368  int err;
2369  OutputFile *of;
2370 
2371  int64_t recording_time = o->recording_time;
2372  int64_t stop_time = o->stop_time;
2373 
2374  mux = mux_alloc();
2375  of = &mux->of;
2376 
2377  if (stop_time != INT64_MAX && recording_time != INT64_MAX) {
2378  stop_time = INT64_MAX;
2379  av_log(mux, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
2380  }
2381 
2382  if (stop_time != INT64_MAX && recording_time == INT64_MAX) {
2383  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
2384  if (stop_time <= start_time) {
2385  av_log(mux, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
2386  exit_program(1);
2387  } else {
2388  recording_time = stop_time - start_time;
2389  }
2390  }
2391 
2392  of->recording_time = recording_time;
2393  of->start_time = o->start_time;
2394  of->shortest = o->shortest;
2395 
2396  mux->thread_queue_size = o->thread_queue_size > 0 ? o->thread_queue_size : 8;
2397  mux->limit_filesize = o->limit_filesize;
2398  av_dict_copy(&mux->opts, o->g->format_opts, 0);
2399 
2400  if (!strcmp(filename, "-"))
2401  filename = "pipe:";
2402 
2403  err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
2404  if (!oc) {
2405  av_log(mux, AV_LOG_FATAL, "Error initializing the muxer for %s: %s\n",
2406  filename, av_err2str(err));
2407  exit_program(1);
2408  }
2409  mux->fc = oc;
2410 
2411  av_strlcat(mux->log_name, "/", sizeof(mux->log_name));
2412  av_strlcat(mux->log_name, oc->oformat->name, sizeof(mux->log_name));
2413 
2414  if (strcmp(oc->oformat->name, "rtp"))
2415  want_sdp = 0;
2416 
2417  of->format = oc->oformat;
2418  if (recording_time != INT64_MAX)
2419  oc->duration = recording_time;
2420 
2421  oc->interrupt_callback = int_cb;
2422 
2423  if (o->bitexact) {
2424  oc->flags |= AVFMT_FLAG_BITEXACT;
2425  of->bitexact = 1;
2426  } else {
2427  of->bitexact = check_opt_bitexact(oc, mux->opts, "fflags",
2429  }
2430 
2431  /* create all output streams for this file */
2432  create_streams(mux, o);
2433 
2434  /* check if all codec options have been used */
2435  validate_enc_avopt(mux, o->g->codec_opts);
2436 
2437  for (int i = 0; i < of->nb_streams; i++) {
2438  OutputStream *ost = of->streams[i];
2439 
2440  /* set the filter output constraints */
2441  if (ost->filter) {
2442  const AVCodec *c = ost->enc_ctx->codec;
2443  OutputFilter *f = ost->filter;
2444  switch (ost->enc_ctx->codec_type) {
2445  case AVMEDIA_TYPE_VIDEO:
2446  f->frame_rate = ost->frame_rate;
2447  f->width = ost->enc_ctx->width;
2448  f->height = ost->enc_ctx->height;
2449  if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
2450  f->format = ost->enc_ctx->pix_fmt;
2451  } else {
2452  f->formats = c->pix_fmts;
2453  }
2454  break;
2455  case AVMEDIA_TYPE_AUDIO:
2456  if (ost->enc_ctx->sample_fmt != AV_SAMPLE_FMT_NONE) {
2457  f->format = ost->enc_ctx->sample_fmt;
2458  } else {
2459  f->formats = c->sample_fmts;
2460  }
2461  if (ost->enc_ctx->sample_rate) {
2462  f->sample_rate = ost->enc_ctx->sample_rate;
2463  } else {
2464  f->sample_rates = c->supported_samplerates;
2465  }
2466  if (ost->enc_ctx->ch_layout.nb_channels) {
2468  } else if (c->ch_layouts) {
2469  f->ch_layouts = c->ch_layouts;
2470  }
2471  break;
2472  }
2473  }
2474  }
2475 
2476  /* check filename in case of an image number is expected */
2478  av_log(mux, AV_LOG_FATAL,
2479  "Output filename '%s' does not contain a numeric pattern like "
2480  "'%%d', which is required by output format '%s'.\n",
2481  oc->url, oc->oformat->name);
2482  exit_program(1);
2483  }
2484 
2485  if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2486  /* test if it already exists to avoid losing precious files */
2487  assert_file_overwrite(filename);
2488 
2489  /* open the file */
2490  if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
2491  &oc->interrupt_callback,
2492  &mux->opts)) < 0) {
2493  av_log(mux, AV_LOG_FATAL, "Error opening output %s: %s\n",
2494  filename, av_err2str(err));
2495  exit_program(1);
2496  }
2497  } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
2498  assert_file_overwrite(filename);
2499 
2500  if (o->mux_preload) {
2501  av_dict_set_int(&mux->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
2502  }
2503  oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
2504 
2505  /* copy metadata and chapters from input files */
2506  copy_meta(mux, o);
2507 
2508  of_add_programs(mux, o);
2509  of_add_metadata(of, oc, o);
2510 
2511  err = set_dispositions(mux, o);
2512  if (err < 0) {
2513  av_log(mux, AV_LOG_FATAL, "Error setting output stream dispositions\n");
2514  exit_program(1);
2515  }
2516 
2517  // parse forced keyframe specifications;
2518  // must be done after chapters are created
2519  err = process_forced_keyframes(mux, o);
2520  if (err < 0) {
2521  av_log(mux, AV_LOG_FATAL, "Error processing forced keyframes\n");
2522  exit_program(1);
2523  }
2524 
2526  if (err < 0) {
2527  av_log(mux, AV_LOG_FATAL, "Error setting up output sync queues\n");
2528  exit_program(1);
2529  }
2530 
2531  of->url = filename;
2532 
2533  /* initialize stream copy and subtitle/data streams.
2534  * Encoded AVFrame based streams will get initialized when the first AVFrame
2535  * is received in do_video_out
2536  */
2537  for (int i = 0; i < of->nb_streams; i++) {
2538  OutputStream *ost = of->streams[i];
2539 
2540  if (ost->filter)
2541  continue;
2542 
2544  if (err < 0)
2545  report_and_exit(err);
2546  }
2547 
2548  /* write the header for files with no streams */
2549  if (of->format->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
2550  int ret = mux_check_init(mux);
2551  if (ret < 0)
2552  return ret;
2553  }
2554 
2555  return 0;
2556 }
choose_encoder
static int choose_encoder(const OptionsContext *o, AVFormatContext *s, OutputStream *ost, const AVCodec **enc)
Definition: ffmpeg_mux_init.c:108
KeyframeForceCtx::pts
int64_t * pts
Definition: ffmpeg.h:518
MuxStream::ost
OutputStream ost
Definition: ffmpeg_mux.h:38
parse_forced_key_frames
static void parse_forced_key_frames(KeyframeForceCtx *kf, const Muxer *mux, const char *spec)
Definition: ffmpeg_mux_init.c:2184
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:852
SYNC_QUEUE_PACKETS
@ SYNC_QUEUE_PACKETS
Definition: sync_queue.h:29
opt_name_filters
static const char *const opt_name_filters[]
Definition: ffmpeg_mux_init.c:65
AVCodec
AVCodec.
Definition: codec.h:187
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:78
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AV_BPRINT_SIZE_UNLIMITED
#define AV_BPRINT_SIZE_UNLIMITED
InputFile::start_time
int64_t start_time
Definition: ffmpeg.h:435
Muxer::fc
AVFormatContext * fc
Definition: ffmpeg_mux.h:89
OptionsContext::stop_time
int64_t stop_time
Definition: ffmpeg.h:167
opt_name_max_muxing_queue_size
static const char *const opt_name_max_muxing_queue_size[]
Definition: ffmpeg_mux_init.c:77
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
FKF_PREV_FORCED_T
@ FKF_PREV_FORCED_T
Definition: ffmpeg.h:457
VSYNC_VFR
@ VSYNC_VFR
Definition: ffmpeg.h:64
ms_from_ost
static MuxStream * ms_from_ost(OutputStream *ost)
Definition: ffmpeg_mux.h:112
AVOutputFormat::name
const char * name
Definition: avformat.h:508
AVChapter::metadata
AVDictionary * metadata
Definition: avformat.h:1067
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:215
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:130
opt.h
avformat_new_stream
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: options.c:243
AVCodecParameters::codec_type
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:58
MATCH_PER_STREAM_OPT
#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)
Definition: ffmpeg.h:926
opt_name_muxing_queue_data_threshold
static const char *const opt_name_muxing_queue_data_threshold[]
Definition: ffmpeg_mux_init.c:78
AVSTREAM_EVENT_FLAG_NEW_PACKETS
#define AVSTREAM_EVENT_FLAG_NEW_PACKETS
Definition: avformat.h:986
ENC_STATS_PTS
@ ENC_STATS_PTS
Definition: ffmpeg.h:473
out
FILE * out
Definition: movenc.c:54
ENC_STATS_FRAME_NUM_IN
@ ENC_STATS_FRAME_NUM_IN
Definition: ffmpeg.h:470
AVCodecContext::sample_rate
int sample_rate
samples per second
Definition: avcodec.h:1058
KF_FORCE_SOURCE_NO_DROP
@ KF_FORCE_SOURCE_NO_DROP
Definition: ffmpeg.h:509
FKF_PREV_FORCED_N
@ FKF_PREV_FORCED_N
Definition: ffmpeg.h:456
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:1319
AVCodecParameters
This struct describes the properties of an encoded stream.
Definition: codec_par.h:54
opt_name_enc_stats_pre
static const char *const opt_name_enc_stats_pre[]
Definition: ffmpeg_mux_init.c:59
sample_fmts
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:947
parse_matrix_coeffs
static void parse_matrix_coeffs(void *logctx, uint16_t *dest, const char *str)
Definition: ffmpeg_mux_init.c:481
AVFMT_VARIABLE_FPS
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:482
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:769
ENC_STATS_DTS
@ ENC_STATS_DTS
Definition: ffmpeg.h:477
MATCH_PER_TYPE_OPT
#define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)
Definition: ffmpeg.h:943
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
MuxStream::muxing_queue
AVFifo * muxing_queue
Definition: ffmpeg_mux.h:44
avcodec_parameters_from_context
int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec)
Fill the parameters struct based on the values from the supplied codec context.
Definition: codec_par.c:100
KeyframeForceCtx::nb_pts
int nb_pts
Definition: ffmpeg.h:519
IS_INTERLEAVED
#define IS_INTERLEAVED(type)
AV_CODEC_FLAG_QSCALE
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition: avcodec.h:216
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:260
InputStream::user_set_discard
int user_set_discard
Definition: ffmpeg.h:337
OptionsContext::nb_metadata
int nb_metadata
Definition: ffmpeg.h:185
ENC_STATS_AVG_BITRATE
@ ENC_STATS_AVG_BITRATE
Definition: ffmpeg.h:483
AVCodecContext::intra_matrix
uint16_t * intra_matrix
custom intra quantization matrix Must be allocated with the av_malloc() family of functions,...
Definition: avcodec.h:931
avformat_get_class
const AVClass * avformat_get_class(void)
Get the AVClass for AVFormatContext.
Definition: options.c:203
ist_iter
InputStream * ist_iter(InputStream *prev)
Definition: ffmpeg.c:539
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:183
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:716
OptionsContext::nb_attachments
int nb_attachments
Definition: ffmpeg.h:162
MuxStream::max_muxing_queue_size
int max_muxing_queue_size
Definition: ffmpeg_mux.h:58
OutputFile::start_time
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:650
avcodec_find_encoder
const AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
Definition: allcodecs.c:965
Muxer::thread_queue_size
int thread_queue_size
Definition: ffmpeg_mux.h:96
audio_channels
int audio_channels
Definition: rtp.c:40
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:1172
OptionsContext::mux_max_delay
float mux_max_delay
Definition: ffmpeg.h:170
AVPacketSideData
Definition: packet.h:315
map_auto_video
static void map_auto_video(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1284
MuxStream::muxing_queue_data_threshold
size_t muxing_queue_data_threshold
Definition: ffmpeg_mux.h:61
subtitle_codec_name
static const char * subtitle_codec_name
Definition: ffplay.c:340
ENC_STATS_LITERAL
@ ENC_STATS_LITERAL
Definition: ffmpeg.h:466
OptionsContext::subtitle_disable
int subtitle_disable
Definition: ffmpeg.h:177
opt_name_disposition
static const char *const opt_name_disposition[]
Definition: ffmpeg_mux_init.c:57
AVOption
AVOption.
Definition: opt.h:251
OutputStream::index
int index
Definition: ffmpeg.h:536
opt_name_sample_fmts
static const char *const opt_name_sample_fmts[]
Definition: ffmpeg_mux_init.c:90
b
#define b
Definition: input.c:41
fix_sub_duration_heartbeat
static int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts)
Definition: ffmpeg.c:837
ost_add
static OutputStream * ost_add(Muxer *mux, const OptionsContext *o, enum AVMediaType type, InputStream *ist)
Definition: ffmpeg_mux_init.c:987
AVStream::avg_frame_rate
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:927
opt_name_max_frames
static const char *const opt_name_max_frames[]
Definition: ffmpeg_mux_init.c:76
AVChapter::start
int64_t start
Definition: avformat.h:1066
Muxer::of
OutputFile of
Definition: ffmpeg_mux.h:84
opt_name_mux_stats
static const char *const opt_name_mux_stats[]
Definition: ffmpeg_mux_init.c:61
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:199
ffmpeg.h
opt_name_fix_sub_duration_heartbeat
static const char *const opt_name_fix_sub_duration_heartbeat[]
Definition: ffmpeg_mux_init.c:67
base
uint8_t base
Definition: vp3data.h:128
freeenv_utf8
static void freeenv_utf8(char *var)
Definition: getenv_utf8.h:72
AV_NOWARN_DEPRECATED
#define AV_NOWARN_DEPRECATED(code)
Disable warnings about deprecated features This is useful for sections of code kept for backward comp...
Definition: attributes.h:126
OptionGroup::swr_opts
AVDictionary * swr_opts
Definition: cmdutils.h:260
AVFormatContext::programs
AVProgram ** programs
Definition: avformat.h:1270
IS_AV_ENC
#define IS_AV_ENC(ost, type)
OptionsContext::bitexact
int bitexact
Definition: ffmpeg.h:173
av_display_rotation_set
void av_display_rotation_set(int32_t matrix[9], double angle)
Initialize a transformation matrix describing a pure clockwise rotation by the specified angle (in de...
Definition: display.c:51
AVCodecParameters::codec_tag
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:66
opt_name_qscale
static const char *const opt_name_qscale[]
Definition: ffmpeg_mux_init.c:82
video_disable
static int video_disable
Definition: ffplay.c:315
AVDictionary
Definition: dict.c:32
set_channel_layout
static void set_channel_layout(OutputFilter *f, OutputStream *ost)
Definition: ffmpeg_mux_init.c:1865
AVChannelLayout::order
enum AVChannelOrder order
Channel order used in this layout.
Definition: channel_layout.h:306
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
AV_CODEC_FLAG_PSNR
#define AV_CODEC_FLAG_PSNR
error[?] variables will be set during encoding.
Definition: avcodec.h:314
MuxStream::copy_prior_start
int copy_prior_start
Definition: ffmpeg_mux.h:79
OptionsContext::format
const char * format
Definition: ffmpeg.h:111
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:311
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:279
avio_size
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:344
ost
static AVStream * ost
Definition: vaapi_transcode.c:42
opt_name_apad
static const char *const opt_name_apad[]
Definition: ffmpeg_mux_init.c:51
set_dispositions
static int set_dispositions(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2100
new_stream_audio
static void new_stream_audio(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:724
MuxStream::ts_copy_start
int64_t ts_copy_start
Definition: ffmpeg_mux.h:66
AVOutputFormat::subtitle_codec
enum AVCodecID subtitle_codec
default subtitle codec
Definition: avformat.h:520
ENC_STATS_TIMEBASE_IN
@ ENC_STATS_TIMEBASE_IN
Definition: ffmpeg.h:472
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:326
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:161
init_simple_filtergraph
int init_simple_filtergraph(InputStream *ist, OutputStream *ost)
Definition: ffmpeg_filter.c:353
of_add_programs
static void of_add_programs(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1685
OutputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:645
av_filename_number_test
int av_filename_number_test(const char *filename)
Check whether filename actually is a numbered sequence generator.
Definition: utils.c:125
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:685
exit_program
void exit_program(int ret)
Wraps exit with a program-specific cleanup routine.
Definition: cmdutils.c:99
Muxer
Definition: ffmpeg_mux.h:83
InputStream
Definition: ffmpeg.h:329
OptionsContext::chapters_input_file
int chapters_input_file
Definition: ffmpeg.h:164
AVPacketSideData::size
size_t size
Definition: packet.h:317
SET_DICT
#define SET_DICT(type, meta, context, index)
EncStatsFile
Definition: ffmpeg_mux_init.c:191
AVFormatContext::interrupt_callback
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1368
of_add_metadata
static void of_add_metadata(OutputFile *of, AVFormatContext *oc, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1792
avio_open2
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:1241
finish
static void finish(void)
Definition: movenc.c:342
fopen_utf8.h
assert_file_overwrite
void assert_file_overwrite(const char *filename)
Definition: ffmpeg_opt.c:655
AVCodecContext::codec
const struct AVCodec * codec
Definition: avcodec.h:444
presets
static const Preset presets[]
Definition: vf_pseudocolor.c:186
opt_name_audio_channels
static const char *const opt_name_audio_channels[]
Definition: ffmpeg_mux_init.c:85
ost_add_from_filter
static void ost_add_from_filter(OutputFilter *ofilter, const OptionsContext *o, Muxer *mux)
Definition: ffmpeg_mux_init.c:1265
OptionsContext::g
OptionGroup * g
Definition: ffmpeg.h:105
AVCodecContext::ch_layout
AVChannelLayout ch_layout
Audio channel layout.
Definition: avcodec.h:2089
report_and_exit
void report_and_exit(int ret)
Reports an error corresponding to the provided AVERROR code and calls exit_program() with the corresp...
Definition: cmdutils.c:93
mux_alloc
static Muxer * mux_alloc(void)
Definition: ffmpeg_mux_init.c:2352
fail
#define fail()
Definition: checkasm.h:137
opt_name_audio_ch_layouts
static const char *const opt_name_audio_ch_layouts[]
Definition: ffmpeg_mux_init.c:86
opt_name_audio_sample_rate
static const char *const opt_name_audio_sample_rate[]
Definition: ffmpeg_mux_init.c:87
AVCodecContext::flags
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:515
AVChapter
Definition: avformat.h:1063
val
static double val(void *priv, double ch)
Definition: aeval.c:77
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
want_sdp
int want_sdp
Definition: ffmpeg_mux.c:41
setup_sync_queues
static int setup_sync_queues(Muxer *mux, AVFormatContext *oc, int64_t buf_size_us)
Definition: ffmpeg_mux_init.c:1588
OptionsContext
Definition: ffmpeg.h:104
AV_PKT_DATA_DISPLAYMATRIX
@ AV_PKT_DATA_DISPLAYMATRIX
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition: packet.h:109
av_opt_set
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:487
av_new_program
AVProgram * av_new_program(AVFormatContext *ac, int id)
Definition: avformat.c:305
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:104
AVStream::duration
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:897
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:196
AVRational::num
int num
Numerator.
Definition: rational.h:59
OptionsContext::nb_audio_channel_maps
int nb_audio_channel_maps
Definition: ffmpeg.h:159
InputFile
Definition: ffmpeg.h:417
FFDIFFSIGN
#define FFDIFFSIGN(x, y)
Comparator.
Definition: macros.h:45
OptionsContext::recording_time
int64_t recording_time
Definition: ffmpeg.h:166
OptionsContext::nb_stream_maps
int nb_stream_maps
Definition: ffmpeg.h:156
OptionsContext::audio_disable
int audio_disable
Definition: ffmpeg.h:176
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:887
preset
preset
Definition: vf_curves.c:46
OutputFile::shortest
int shortest
Definition: ffmpeg.h:652
avfilter_inout_free
void avfilter_inout_free(AVFilterInOut **inout)
Free the supplied list of AVFilterInOut and set *inout to NULL.
Definition: graphparser.c:75
avassert.h
RcOverride::quality_factor
float quality_factor
Definition: avcodec.h:200
MuxStream::log_name
char log_name[32]
Definition: ffmpeg_mux.h:41
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
AudioChannelMap
Definition: ffmpeg.h:92
AVFormatContext::metadata
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1330
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
OptionGroup::codec_opts
AVDictionary * codec_opts
Definition: cmdutils.h:257
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:629
AVCodecTag
Definition: internal.h:50
ENC_STATS_PTS_IN
@ ENC_STATS_PTS_IN
Definition: ffmpeg.h:475
mask
static const uint16_t mask[17]
Definition: lzw.c:38
OptionsContext::nb_program
int nb_program
Definition: ffmpeg.h:257
av_dict_get
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:60
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:1767
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:43
output_stream_class
static const AVClass output_stream_class
Definition: ffmpeg_mux_init.c:409
VSYNC_VSCFR
@ VSYNC_VSCFR
Definition: ffmpeg.h:65
EncStats::components
EncStatsComponent * components
Definition: ffmpeg.h:494
avcodec_alloc_context3
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:153
AVChapter::end
int64_t end
chapter start/end time in time_base units
Definition: avformat.h:1066
SpecifierOpt::specifier
char * specifier
stream/chapter/program/...
Definition: cmdutils.h:135
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:416
intreadwrite.h
opt_name_enc_stats_post_fmt
static const char *const opt_name_enc_stats_post_fmt[]
Definition: ffmpeg_mux_init.c:63
s
#define s(width, name)
Definition: cbs_vp9.c:256
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:1328
mux_check_init
int mux_check_init(Muxer *mux)
Definition: ffmpeg_mux.c:580
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:281
FilterGraph::outputs
OutputFilter ** outputs
Definition: ffmpeg.h:323
enc_stats_get_file
static int enc_stats_get_file(AVIOContext **io, const char *path)
Definition: ffmpeg_mux_init.c:199
InputStream::framerate
AVRational framerate
Definition: ffmpeg.h:360
do_psnr
int do_psnr
Definition: ffmpeg_opt.c:95
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:1222
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:138
output_file_class
static const AVClass output_file_class
Definition: ffmpeg_mux_init.c:2345
AVFormatContext::nb_programs
unsigned int nb_programs
Definition: avformat.h:1269
RcOverride
Definition: avcodec.h:196
AVFormatContext::chapters
AVChapter ** chapters
Definition: avformat.h:1320
ENC_STATS_FILE_IDX
@ ENC_STATS_FILE_IDX
Definition: ffmpeg.h:467
AVDictionaryEntry::key
char * key
Definition: dict.h:90
frame_size
int frame_size
Definition: mxfenc.c:2307
OptionsContext::limit_filesize
int64_t limit_filesize
Definition: ffmpeg.h:168
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
AVCodecParameters::width
int width
Video only.
Definition: codec_par.h:128
of_add_attachments
static void of_add_attachments(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1497
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
av_channel_layout_from_mask
FF_ENABLE_DEPRECATION_WARNINGS int av_channel_layout_from_mask(AVChannelLayout *channel_layout, uint64_t mask)
Initialize a native channel layout from a bitmask indicating which channels are present.
Definition: channel_layout.c:391
get_line
static char * get_line(AVIOContext *s, AVBPrint *bprint)
Definition: ffmpeg_mux_init.c:149
filters
#define filters(fmt, type, inverse, clp, inverset, clip, one, clip_fn, packed)
Definition: af_crystalizer.c:55
ENC_STATS_BITRATE
@ ENC_STATS_BITRATE
Definition: ffmpeg.h:482
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
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:402
AVIO_FLAG_WRITE
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:624
OutputFilter::ost
struct OutputStream * ost
Definition: ffmpeg.h:288
AVPacketSideData::data
uint8_t * data
Definition: packet.h:316
ignore_unknown_streams
int ignore_unknown_streams
Definition: ffmpeg_opt.c:97
ctx
AVFormatContext * ctx
Definition: movenc.c:48
RcOverride::start_frame
int start_frame
Definition: avcodec.h:197
channels
channels
Definition: aptx.h:31
nb_streams
static int nb_streams
Definition: ffprobe.c:315
opt_name_enc_stats_pre_fmt
static const char *const opt_name_enc_stats_pre_fmt[]
Definition: ffmpeg_mux_init.c:62
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
opt_name_intra_matrices
static const char *const opt_name_intra_matrices[]
Definition: ffmpeg_mux_init.c:72
OptionsContext::shortest
int shortest
Definition: ffmpeg.h:172
AVOutputFormat::codec_tag
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "better choice first".
Definition: avformat.h:533
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:388
key
const char * key
Definition: hwcontext_opencl.c:174
create_streams
static void create_streams(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1538
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:50
pass
#define pass
Definition: fft_template.c:608
AVFMT_NEEDNUMBER
#define AVFMT_NEEDNUMBER
Needs 'd' in filename.
Definition: avformat.h:469
AVCodecContext::codec_id
enum AVCodecID codec_id
Definition: avcodec.h:445
Muxer::limit_filesize
int64_t limit_filesize
Definition: ffmpeg_mux.h:99
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:1772
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:313
OptionsContext::start_time
int64_t start_time
Definition: ffmpeg.h:108
OutputStream::encoder_opts
AVDictionary * encoder_opts
Definition: ffmpeg.h:595
AVDISCARD_ALL
@ AVDISCARD_ALL
discard all
Definition: defs.h:76
AVFormatContext
Format I/O context.
Definition: avformat.h:1104
av_realloc_f
#define av_realloc_f(p, o, n)
Definition: tableprint_vlc.h:32
OptionGroup::format_opts
AVDictionary * format_opts
Definition: cmdutils.h:258
opts
AVDictionary * opts
Definition: movenc.c:50
AVStream::codecpar
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:861
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:187
opt_name_inter_matrices
static const char *const opt_name_inter_matrices[]
Definition: ffmpeg_mux_init.c:73
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:877
DEFAULT_PASS_LOGFILENAME_PREFIX
#define DEFAULT_PASS_LOGFILENAME_PREFIX
Definition: ffmpeg_mux_init.c:49
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:336
InputStream::st
AVStream * st
Definition: ffmpeg.h:335
map_manual
static void map_manual(Muxer *mux, const OptionsContext *o, const StreamMap *map)
Definition: ffmpeg_mux_init.c:1433
nb_enc_stats_files
static int nb_enc_stats_files
Definition: ffmpeg_mux_init.c:197
ENC_STATS_PTS_TIME
@ ENC_STATS_PTS_TIME
Definition: ffmpeg.h:474
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:168
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
AVPacketSideData::type
enum AVPacketSideDataType type
Definition: packet.h:318
opt_name_forced_key_frames
static const char *const opt_name_forced_key_frames[]
Definition: ffmpeg_mux_init.c:70
AVFormatContext::pb
AVIOContext * pb
I/O context.
Definition: avformat.h:1146
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
EncStats
Definition: ffmpeg.h:493
EncStatsFile::io
AVIOContext * io
Definition: ffmpeg_mux_init.c:193
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:98
opt_name_time_bases
static const char *const opt_name_time_bases[]
Definition: ffmpeg_mux_init.c:84
AVStream::metadata
AVDictionary * metadata
Definition: avformat.h:918
MuxStream::bsf_ctx
AVBSFContext * bsf_ctx
Definition: ffmpeg_mux.h:46
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
validate_enc_avopt
static void validate_enc_avopt(Muxer *mux, const AVDictionary *codec_avopt)
Definition: ffmpeg_mux_init.c:2277
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
SpecifierOpt * max_frames
Definition: ffmpeg.h:186
av_get_channel_layout
uint64_t av_get_channel_layout(const char *name)
Return a channel layout id that matches name, or 0 if no match is found.
Definition: channel_layout.c:239
Muxer::log_name
char log_name[32]
Definition: ffmpeg_mux.h:87
ost_get_filters
static int ost_get_filters(const OptionsContext *o, AVFormatContext *oc, OutputStream *ost)
Definition: ffmpeg_mux_init.c:434
AVCodecParameters::ch_layout
AVChannelLayout ch_layout
Audio only.
Definition: codec_par.h:213
OutputFile::index
int index
Definition: ffmpeg.h:639
OptionsContext::program
SpecifierOpt * program
Definition: ffmpeg.h:256
OutputFile::class
const AVClass * class
Definition: ffmpeg.h:637
ENC_STATS_PTS_TIME_IN
@ ENC_STATS_PTS_TIME_IN
Definition: ffmpeg.h:476
FilterGraph::nb_outputs
int nb_outputs
Definition: ffmpeg.h:324
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:1946
of_open
int of_open(const OptionsContext *o, const char *filename)
Definition: ffmpeg_mux_init.c:2364
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
OptionsContext::nb_metadata_map
int nb_metadata_map
Definition: ffmpeg.h:221
opt_name_chroma_intra_matrices
static const char *const opt_name_chroma_intra_matrices[]
Definition: ffmpeg_mux_init.c:74
InputStream::par
AVCodecParameters * par
Codec parameters - to be used by the decoding/streamcopy code.
Definition: ffmpeg.h:349
input_files
InputFile ** input_files
Definition: ffmpeg.c:129
OutputFile::streams
OutputStream ** streams
Definition: ffmpeg.h:644
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:571
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
opt_name_frame_pix_fmts
static const char *const opt_name_frame_pix_fmts[]
Definition: ffmpeg_mux_init.c:89
FilterGraph
Definition: ffmpeg.h:313
AVFormatContext::nb_streams
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1160
new_stream_attachment
static void new_stream_attachment(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:810
AVOutputFormat::flags
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS,...
Definition: avformat.h:527
codec_opts
AVDictionary * codec_opts
Definition: cmdutils.c:60
opt_name_filter_scripts
static const char *const opt_name_filter_scripts[]
Definition: ffmpeg_mux_init.c:66
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:490
frame_sizes
static const uint8_t frame_sizes[]
Definition: rtpdec_qcelp.c:24
opt_name_mux_stats_fmt
static const char *const opt_name_mux_stats_fmt[]
Definition: ffmpeg_mux_init.c:64
f
f
Definition: af_crystalizer.c:122
AVIOContext
Bytestream IO Context.
Definition: avio.h:166
AVCodecContext::rc_override
RcOverride * rc_override
Definition: avcodec.h:1271
OptionsContext::thread_queue_size
int thread_queue_size
Definition: ffmpeg.h:137
AVMediaType
AVMediaType
Definition: avutil.h:199
Muxer::sq_mux
SyncQueue * sq_mux
Definition: ffmpeg_mux.h:103
opt_name_bits_per_raw_sample
static const char *const opt_name_bits_per_raw_sample[]
Definition: ffmpeg_mux_init.c:53
av_bprint_finalize
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:235
InputStream::file_index
int file_index
Definition: ffmpeg.h:332
output_files
OutputFile ** output_files
Definition: ffmpeg.c:132
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
opt_name_frame_sizes
static const char *const opt_name_frame_sizes[]
Definition: ffmpeg_mux_init.c:88
start_time
static int64_t start_time
Definition: ffplay.c:326
AVFormatContext::url
char * url
input or output URL.
Definition: avformat.h:1187
EncStatsType
EncStatsType
Definition: ffmpeg.h:465
AVCodecContext::sample_fmt
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1074
AV_SAMPLE_FMT_NONE
@ AV_SAMPLE_FMT_NONE
Definition: samplefmt.h:56
StreamMap
Definition: ffmpeg.h:84
ENC_STATS_NB_SAMPLES
@ ENC_STATS_NB_SAMPLES
Definition: ffmpeg.h:480
init_output_stream_nofilter
static int init_output_stream_nofilter(OutputStream *ost)
Definition: ffmpeg_mux_init.c:2321
size
int size
Definition: twinvq_data.h:10344
copy_ts
int copy_ts
Definition: ffmpeg_opt.c:76
avio.h
copy_tb
int copy_tb
Definition: ffmpeg_opt.c:78
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
AVStream::event_flags
int event_flags
Flags indicating events happening on the stream, a combination of AVSTREAM_EVENT_FLAG_*.
Definition: avformat.h:973
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:779
opt_name_pass
static const char *const opt_name_pass[]
Definition: ffmpeg_mux_init.c:79
OutputStream::type
enum AVMediaType type
Definition: ffmpeg.h:533
OutputFile::url
const char * url
Definition: ffmpeg.h:642
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:1863
AVMEDIA_TYPE_UNKNOWN
@ AVMEDIA_TYPE_UNKNOWN
Usually treated as AVMEDIA_TYPE_DATA.
Definition: avutil.h:200
Muxer::opts
AVDictionary * opts
Definition: ffmpeg_mux.h:94
AVStream::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:916
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:987
of_enc_stats_close
void of_enc_stats_close(void)
Definition: ffmpeg_mux_init.c:230
AV_OPT_SEARCH_CHILDREN
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition: opt.h:563
MuxStream
Definition: ffmpeg_mux.h:37
AV_CODEC_FLAG_PASS2
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition: avcodec.h:302
avio_r8
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:624
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
enc_alloc
int enc_alloc(Encoder **penc, const AVCodec *codec)
Definition: ffmpeg_enc.c:82
av_reallocp_array
int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate an array through a pointer to a pointer.
Definition: mem.c:223
strip_specifiers
AVDictionary * strip_specifiers(const AVDictionary *dict)
Definition: ffmpeg_opt.c:166
OptionsContext::metadata
SpecifierOpt * metadata
Definition: ffmpeg.h:184
av_packet_alloc
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:62
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
opt_name_enc_stats_post
static const char *const opt_name_enc_stats_post[]
Definition: ffmpeg_mux_init.c:60
OutputFile::sq_encode
SyncQueue * sq_encode
Definition: ffmpeg.h:647
KF_FORCE_SOURCE
@ KF_FORCE_SOURCE
Definition: ffmpeg.h:508
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
ENC_STATS_FRAME_NUM
@ ENC_STATS_FRAME_NUM
Definition: ffmpeg.h:469
KeyframeForceCtx
Definition: ffmpeg.h:512
OutputFilter::type
enum AVMediaType type
Definition: ffmpeg.h:294
opt_name_autoscale
static const char *const opt_name_autoscale[]
Definition: ffmpeg_mux_init.c:52
AVStream::side_data
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:956
AVCodec::id
enum AVCodecID id
Definition: codec.h:201
av_channel_layout_default
void av_channel_layout_default(AVChannelLayout *ch_layout, int nb_channels)
Get the default channel layout for a given number of channels.
Definition: channel_layout.c:962
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:54
flag
#define flag(name)
Definition: cbs_av1.c:553
avcodec_get_name
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:442
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
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: aviobuf.c:1280
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:404
bprint.h
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:269
RcOverride::end_frame
int end_frame
Definition: avcodec.h:198
OptionsContext::metadata_map
SpecifierOpt * metadata_map
Definition: ffmpeg.h:220
AVChapter::id
int64_t id
unique ID to identify the chapter
Definition: avformat.h:1064
new_stream_subtitle
static void new_stream_subtitle(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:816
MuxStream::stats
EncStats stats
Definition: ffmpeg_mux.h:48
OptionsContext::stream_maps
StreamMap * stream_maps
Definition: ffmpeg.h:155
AVCodecParameters::height
int height
Definition: codec_par.h:129
avcodec_parameters_to_context
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
Definition: codec_par.c:184
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:185
find_codec_or_die
const AVCodec * find_codec_or_die(void *logctx, const char *name, enum AVMediaType type, int encoder)
Definition: ffmpeg_opt.c:625
VSYNC_CFR
@ VSYNC_CFR
Definition: ffmpeg.h:63
OptionsContext::shortest_buf_duration
float shortest_buf_duration
Definition: ffmpeg.h:171
av_malloc_array
#define av_malloc_array(a, b)
Definition: tableprint_vlc.h:31
AVProgram::metadata
AVDictionary * metadata
Definition: avformat.h:1034
map_auto_audio
static void map_auto_audio(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1335
OutputFile::bitexact
int bitexact
Definition: ffmpeg.h:653
display.h
opt_name_frame_aspect_ratios
static const char *const opt_name_frame_aspect_ratios[]
Definition: ffmpeg_mux_init.c:71
av_assert1
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
opt_name_enc_time_bases
static const char *const opt_name_enc_time_bases[]
Definition: ffmpeg_mux_init.c:58
filter_codec_opts
AVDictionary * filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id, AVFormatContext *s, AVStream *st, const AVCodec *codec)
Filter out options for given codec.
Definition: cmdutils.c:895
AVMEDIA_TYPE_ATTACHMENT
@ AVMEDIA_TYPE_ATTACHMENT
Opaque data information usually sparse.
Definition: avutil.h:205
InputFile::ctx
AVFormatContext * ctx
Definition: ffmpeg.h:425
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AVFormatContext::max_delay
int max_delay
Definition: avformat.h:1216
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:1028
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:468
filtergraphs
FilterGraph ** filtergraphs
Definition: ffmpeg.c:135
int_cb
const AVIOInterruptCB int_cb
Definition: ffmpeg.c:471
AVCodecContext::height
int height
Definition: avcodec.h:615
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:652
ENC_STATS_SAMPLE_NUM
@ ENC_STATS_SAMPLE_NUM
Definition: ffmpeg.h:479
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:133
OptionsContext::streamid_map
int * streamid_map
Definition: ffmpeg.h:181
avcodec.h
OptionGroup::sws_dict
AVDictionary * sws_dict
Definition: cmdutils.h:259
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:907
tag
uint32_t tag
Definition: movenc.c:1709
AVStream::id
int id
Format-specific stream ID.
Definition: avformat.h:850
AVFMT_FLAG_BITEXACT
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1239
ret
ret
Definition: filter_design.txt:187
AVStream
Stream structure.
Definition: avformat.h:838
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
av_strtod
double av_strtod(const char *numstr, char **tail)
Parse the string in numstr and return its value as a double.
Definition: eval.c:106
AVFormatContext::oformat
const struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1123
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:96
OptionsContext::nb_streamid_map
int nb_streamid_map
Definition: ffmpeg.h:182
output_file_item_name
static const char * output_file_item_name(void *obj)
Definition: ffmpeg_mux_init.c:2338
AVStream::nb_side_data
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:960
AV_CODEC_PROP_TEXT_SUB
#define AV_CODEC_PROP_TEXT_SUB
Subtitle codec is text based.
Definition: codec_desc.h:108
OptionsContext::audio_channel_maps
AudioChannelMap * audio_channel_maps
Definition: ffmpeg.h:158
InputFile::streams
InputStream ** streams
Definition: ffmpeg.h:441
avformat.h
dict.h
av_fifo_alloc2
AVFifo * av_fifo_alloc2(size_t nb_elems, size_t elem_size, unsigned int flags)
Allocate and initialize an AVFifo with a given element size.
Definition: fifo.c:47
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:114
AV_RL32
uint64_t_TMPL AV_WL64 unsigned int_TMPL AV_RL32
Definition: bytestream.h:92
av_get_pix_fmt
enum AVPixelFormat av_get_pix_fmt(const char *name)
Return the pixel format corresponding to name.
Definition: pixdesc.c:2868
OptionsContext::nb_max_frames
int nb_max_frames
Definition: ffmpeg.h:187
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:435
AVStream::index
int index
stream index in AVFormatContext
Definition: avformat.h:844
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:701
OptionsContext::mux_preload
float mux_preload
Definition: ffmpeg.h:169
map_auto_subtitle
static void map_auto_subtitle(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1377
map_auto_data
static void map_auto_data(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:1415
ist_output_add
int ist_output_add(InputStream *ist, OutputStream *ost)
Definition: ffmpeg_demux.c:877
AVRational::den
int den
Denominator.
Definition: rational.h:60
SpecifierOpt::str
uint8_t * str
Definition: cmdutils.h:137
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
avfilter.h
av_get_token
char * av_get_token(const char **buf, const char *term)
Unescape the given string until a non escaped terminating char, and return the token corresponding to...
Definition: avstring.c:144
av_bprint_clear
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition: bprint.c:227
avio_read
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:633
OptionsContext::video_disable
int video_disable
Definition: ffmpeg.h:175
AVOutputFormat::video_codec
enum AVCodecID video_codec
default video codec
Definition: avformat.h:519
AVStream::r_frame_rate
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:996
new_stream_video
static void new_stream_video(Muxer *mux, const OptionsContext *o, OutputStream *ost)
Definition: ffmpeg_mux_init.c:499
opt_name_passlogfiles
static const char *const opt_name_passlogfiles[]
Definition: ffmpeg_mux_init.c:80
opt_name_rc_overrides
static const char *const opt_name_rc_overrides[]
Definition: ffmpeg_mux_init.c:83
AVFormatContext::duration
int64_t duration
Duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:1206
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:70
GROW_ARRAY
#define GROW_ARRAY(array, nb_elems)
Definition: cmdutils.h:442
InputFile::ts_offset
int64_t ts_offset
Definition: ffmpeg.h:434
VSYNC_AUTO
@ VSYNC_AUTO
Definition: ffmpeg.h:61
av_channel_layout_copy
int av_channel_layout_copy(AVChannelLayout *dst, const AVChannelLayout *src)
Make a copy of a channel layout.
Definition: channel_layout.c:639
OutputFilter
Definition: ffmpeg.h:286
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
AVIO_FLAG_READ
#define AVIO_FLAG_READ
read-only
Definition: avio.h:623
av_strdup
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:270
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:527
unescape
static int unescape(char **pdst, size_t *dst_len, const char **pstr, char delim)
Definition: ffmpeg_mux_init.c:240
avutil.h
mem.h
SpecifierOpt::u
union SpecifierOpt::@0 u
OutputStream::file_index
int file_index
Definition: ffmpeg.h:535
AV_CODEC_FLAG_BITEXACT
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition: avcodec.h:330
OutputFilter::out_tmp
AVFilterInOut * out_tmp
Definition: ffmpeg.h:293
ffmpeg_mux.h
map
const VDPAUPixFmtMap * map
Definition: hwcontext_vdpau.c:71
InputStream::index
int index
Definition: ffmpeg.h:333
EncStatsFile::path
char * path
Definition: ffmpeg_mux_init.c:192
compare_int64
static int compare_int64(const void *a, const void *b)
Definition: ffmpeg_mux_init.c:2179
copy_meta
static void copy_meta(Muxer *mux, const OptionsContext *o)
Definition: ffmpeg_mux_init.c:2030
FKF_N_FORCED
@ FKF_N_FORCED
Definition: ffmpeg.h:455
AVDictionaryEntry
Definition: dict.h:89
OptionsContext::attachments
const char ** attachments
Definition: ffmpeg.h:161
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:62
AVPacket
This structure stores compressed data.
Definition: packet.h:351
audio_disable
static int audio_disable
Definition: ffplay.c:314
EncStatsComponent
Definition: ffmpeg.h:486
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:86
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:940
cmdutils.h
AVCodecContext::rc_override_count
int rc_override_count
ratecontrol override, see RcOverride
Definition: avcodec.h:1270
InputFile::input_ts_offset
int64_t input_ts_offset
Definition: ffmpeg.h:428
file_read
char * file_read(const char *filename)
Definition: ffmpeg_opt.c:699
EncStats::nb_components
int nb_components
Definition: ffmpeg.h:495
OptionsContext::data_disable
int data_disable
Definition: ffmpeg.h:178
av_stream_new_side_data
uint8_t * av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type, size_t size)
Allocate new information from stream.
Definition: avformat.c:191
nb_filtergraphs
int nb_filtergraphs
Definition: ffmpeg.c:136
AVFilterInOut::name
char * name
unique name for this input/output in the list
Definition: avfilter.h:1026
AVCodecContext::width
int width
picture width / height.
Definition: avcodec.h:615
int32_t
int32_t
Definition: audioconvert.c:56
parse_time_or_die
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
Parse a string specifying a time and return its corresponding value as a number of microseconds.
Definition: cmdutils.c:128
ENC_STATS_PKT_SIZE
@ ENC_STATS_PKT_SIZE
Definition: ffmpeg.h:481
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:92
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:2170
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:2238
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:140
avcodec_descriptor_get
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:3694
SYNC_QUEUE_FRAMES
@ SYNC_QUEUE_FRAMES
Definition: sync_queue.h:30
OutputFile::format
const AVOutputFormat * format
Definition: ffmpeg.h:641
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
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_name_copy_initial_nonkeyframes
static const char *const opt_name_copy_initial_nonkeyframes[]
Definition: ffmpeg_mux_init.c:55
InputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:442
FKF_N
@ FKF_N
Definition: ffmpeg.h:454
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:91
ENC_STATS_DTS_TIME
@ ENC_STATS_DTS_TIME
Definition: ffmpeg.h:478
AVChapter::time_base
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:1065
OutputFile::recording_time
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:649
int
int
Definition: ffmpeg_filter.c:224
of_stream_init
int of_stream_init(OutputFile *of, OutputStream *ost)
Definition: ffmpeg_mux.c:657
AVFilterInOut
A linked-list of the inputs/outputs of the filter chain.
Definition: avfilter.h:1024
VSYNC_PASSTHROUGH
@ VSYNC_PASSTHROUGH
Definition: ffmpeg.h:62
opt_name_fps_mode
static const char *const opt_name_fps_mode[]
Definition: ffmpeg_mux_init.c:68
snprintf
#define snprintf
Definition: snprintf.h:34
EncStats::io
AVIOContext * io
Definition: ffmpeg.h:497
enc_open
int enc_open(OutputStream *ost, AVFrame *frame)
Definition: ffmpeg_enc.c:203
opt_name_bitstream_filters
static const char *const opt_name_bitstream_filters[]
Definition: ffmpeg_mux_init.c:54
AVCodecContext::sample_aspect_ratio
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition: avcodec.h:816
parse_meta_type
static void 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:1764
av_dict_iterate
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition: dict.c:42
opt_name_presets
static const char *const opt_name_presets[]
Definition: ffmpeg_mux_init.c:81
copy_chapters
static int copy_chapters(InputFile *ifile, OutputFile *ofile, AVFormatContext *os, int copy_metadata)
Definition: ffmpeg_mux_init.c:1903
MuxStream::last_mux_dts
int64_t last_mux_dts
Definition: ffmpeg_mux.h:70
opt_name_max_frame_rates
static const char *const opt_name_max_frame_rates[]
Definition: ffmpeg_mux_init.c:75
ENC_STATS_TIMEBASE
@ ENC_STATS_TIMEBASE
Definition: ffmpeg.h:471
OutputStream::class
const AVClass * class
Definition: ffmpeg.h:531
opt_name_copy_prior_start
static const char *const opt_name_copy_prior_start[]
Definition: ffmpeg_mux_init.c:56
opt_name_force_fps
static const char *const opt_name_force_fps[]
Definition: ffmpeg_mux_init.c:69
OutputFile
Definition: ffmpeg.h:636
AV_CODEC_FLAG_PASS1
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:298