FFmpeg
ffmpeg_opt.c
Go to the documentation of this file.
1 
2 /*
3  * ffmpeg option parsing
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <stdint.h>
23 
24 #include "ffmpeg.h"
25 #include "cmdutils.h"
26 
27 #include "libavformat/avformat.h"
28 
29 #include "libavcodec/avcodec.h"
30 #include "libavcodec/bsf.h"
31 
32 #include "libavfilter/avfilter.h"
33 
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/avutil.h"
38 #include "libavutil/intreadwrite.h"
39 #include "libavutil/fifo.h"
40 #include "libavutil/mathematics.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/parseutils.h"
43 #include "libavutil/pixdesc.h"
44 #include "libavutil/pixfmt.h"
45 
46 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
47 
48 #define SPECIFIER_OPT_FMT_str "%s"
49 #define SPECIFIER_OPT_FMT_i "%i"
50 #define SPECIFIER_OPT_FMT_i64 "%"PRId64
51 #define SPECIFIER_OPT_FMT_ui64 "%"PRIu64
52 #define SPECIFIER_OPT_FMT_f "%f"
53 #define SPECIFIER_OPT_FMT_dbl "%lf"
54 
55 static const char *const opt_name_codec_names[] = {"c", "codec", "acodec", "vcodec", "scodec", "dcodec", NULL};
56 static const char *const opt_name_audio_channels[] = {"ac", NULL};
57 static const char *const opt_name_audio_sample_rate[] = {"ar", NULL};
58 static const char *const opt_name_frame_rates[] = {"r", NULL};
59 static const char *const opt_name_max_frame_rates[] = {"fpsmax", NULL};
60 static const char *const opt_name_frame_sizes[] = {"s", NULL};
61 static const char *const opt_name_frame_pix_fmts[] = {"pix_fmt", NULL};
62 static const char *const opt_name_ts_scale[] = {"itsscale", NULL};
63 static const char *const opt_name_hwaccels[] = {"hwaccel", NULL};
64 static const char *const opt_name_hwaccel_devices[] = {"hwaccel_device", NULL};
65 static const char *const opt_name_hwaccel_output_formats[] = {"hwaccel_output_format", NULL};
66 static const char *const opt_name_autorotate[] = {"autorotate", NULL};
67 static const char *const opt_name_autoscale[] = {"autoscale", NULL};
68 static const char *const opt_name_max_frames[] = {"frames", "aframes", "vframes", "dframes", NULL};
69 static const char *const opt_name_bitstream_filters[] = {"bsf", "absf", "vbsf", NULL};
70 static const char *const opt_name_codec_tags[] = {"tag", "atag", "vtag", "stag", NULL};
71 static const char *const opt_name_sample_fmts[] = {"sample_fmt", NULL};
72 static const char *const opt_name_qscale[] = {"q", "qscale", NULL};
73 static const char *const opt_name_forced_key_frames[] = {"forced_key_frames", NULL};
74 static const char *const opt_name_force_fps[] = {"force_fps", NULL};
75 static const char *const opt_name_frame_aspect_ratios[] = {"aspect", NULL};
76 static const char *const opt_name_rc_overrides[] = {"rc_override", NULL};
77 static const char *const opt_name_intra_matrices[] = {"intra_matrix", NULL};
78 static const char *const opt_name_inter_matrices[] = {"inter_matrix", NULL};
79 static const char *const opt_name_chroma_intra_matrices[] = {"chroma_intra_matrix", NULL};
80 static const char *const opt_name_top_field_first[] = {"top", NULL};
81 static const char *const opt_name_presets[] = {"pre", "apre", "vpre", "spre", NULL};
82 static const char *const opt_name_copy_initial_nonkeyframes[] = {"copyinkfr", NULL};
83 static const char *const opt_name_copy_prior_start[] = {"copypriorss", NULL};
84 static const char *const opt_name_filters[] = {"filter", "af", "vf", NULL};
85 static const char *const opt_name_filter_scripts[] = {"filter_script", NULL};
86 static const char *const opt_name_reinit_filters[] = {"reinit_filter", NULL};
87 static const char *const opt_name_fix_sub_duration[] = {"fix_sub_duration", NULL};
88 static const char *const opt_name_canvas_sizes[] = {"canvas_size", NULL};
89 static const char *const opt_name_pass[] = {"pass", NULL};
90 static const char *const opt_name_passlogfiles[] = {"passlogfile", NULL};
91 static const char *const opt_name_max_muxing_queue_size[] = {"max_muxing_queue_size", NULL};
92 static const char *const opt_name_muxing_queue_data_threshold[] = {"muxing_queue_data_threshold", NULL};
93 static const char *const opt_name_guess_layout_max[] = {"guess_layout_max", NULL};
94 static const char *const opt_name_apad[] = {"apad", NULL};
95 static const char *const opt_name_discard[] = {"discard", NULL};
96 static const char *const opt_name_disposition[] = {"disposition", NULL};
97 static const char *const opt_name_time_bases[] = {"time_base", NULL};
98 static const char *const opt_name_enc_time_bases[] = {"enc_time_base", NULL};
99 
100 #define WARN_MULTIPLE_OPT_USAGE(name, type, so, st)\
101 {\
102  char namestr[128] = "";\
103  const char *spec = so->specifier && so->specifier[0] ? so->specifier : "";\
104  for (i = 0; opt_name_##name[i]; i++)\
105  av_strlcatf(namestr, sizeof(namestr), "-%s%s", opt_name_##name[i], opt_name_##name[i+1] ? (opt_name_##name[i+2] ? ", " : " or ") : "");\
106  av_log(NULL, AV_LOG_WARNING, "Multiple %s options specified for stream %d, only the last option '-%s%s%s "SPECIFIER_OPT_FMT_##type"' will be used.\n",\
107  namestr, st->index, opt_name_##name[0], spec[0] ? ":" : "", spec, so->u.type);\
108 }
109 
110 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
111 {\
112  int i, ret, matches = 0;\
113  SpecifierOpt *so;\
114  for (i = 0; i < o->nb_ ## name; i++) {\
115  char *spec = o->name[i].specifier;\
116  if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0) {\
117  outvar = o->name[i].u.type;\
118  so = &o->name[i];\
119  matches++;\
120  } else if (ret < 0)\
121  exit_program(1);\
122  }\
123  if (matches > 1)\
124  WARN_MULTIPLE_OPT_USAGE(name, type, so, st);\
125 }
126 
127 #define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)\
128 {\
129  int i;\
130  for (i = 0; i < o->nb_ ## name; i++) {\
131  char *spec = o->name[i].specifier;\
132  if (!strcmp(spec, mediatype))\
133  outvar = o->name[i].u.type;\
134  }\
135 }
136 
137 const HWAccel hwaccels[] = {
138 #if CONFIG_VIDEOTOOLBOX
140 #endif
141 #if CONFIG_LIBMFX
142  { "qsv", qsv_init, HWACCEL_QSV, AV_PIX_FMT_QSV },
143 #endif
144  { 0 },
145 };
147 
150 
153 float dts_error_threshold = 3600*30;
154 
155 int audio_volume = 256;
160 int do_benchmark = 0;
162 int do_hex_dump = 0;
163 int do_pkt_dump = 0;
164 int copy_ts = 0;
166 int copy_tb = -1;
167 int debug_ts = 0;
170 int print_stats = -1;
171 int qp_hist = 0;
174 float max_error_rate = 2.0/3;
179 int64_t stats_period = 500000;
180 
181 
182 static int intra_only = 0;
183 static int file_overwrite = 0;
184 static int no_file_overwrite = 0;
185 static int do_psnr = 0;
186 static int input_sync;
188 static int ignore_unknown_streams = 0;
189 static int copy_unknown_streams = 0;
190 static int recast_media = 0;
191 static int find_stream_info = 1;
192 
194 {
195  const OptionDef *po = options;
196  int i;
197 
198  /* all OPT_SPEC and OPT_STRING can be freed in generic way */
199  while (po->name) {
200  void *dst = (uint8_t*)o + po->u.off;
201 
202  if (po->flags & OPT_SPEC) {
203  SpecifierOpt **so = dst;
204  int i, *count = (int*)(so + 1);
205  for (i = 0; i < *count; i++) {
206  av_freep(&(*so)[i].specifier);
207  if (po->flags & OPT_STRING)
208  av_freep(&(*so)[i].u.str);
209  }
210  av_freep(so);
211  *count = 0;
212  } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
213  av_freep(dst);
214  po++;
215  }
216 
217  for (i = 0; i < o->nb_stream_maps; i++)
219  av_freep(&o->stream_maps);
221  av_freep(&o->streamid_map);
222  av_freep(&o->attachments);
223 }
224 
226 {
227  memset(o, 0, sizeof(*o));
228 
229  o->stop_time = INT64_MAX;
230  o->mux_max_delay = 0.7;
233  o->recording_time = INT64_MAX;
234  o->limit_filesize = UINT64_MAX;
235  o->chapters_input_file = INT_MAX;
236  o->accurate_seek = 1;
237  o->thread_queue_size = -1;
238 }
239 
240 static int show_hwaccels(void *optctx, const char *opt, const char *arg)
241 {
243 
244  printf("Hardware acceleration methods:\n");
245  while ((type = av_hwdevice_iterate_types(type)) !=
248  printf("\n");
249  return 0;
250 }
251 
252 /* return a copy of the input with the stream specifiers removed from the keys */
254 {
255  AVDictionaryEntry *e = NULL;
256  AVDictionary *ret = NULL;
257 
258  while ((e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
259  char *p = strchr(e->key, ':');
260 
261  if (p)
262  *p = 0;
263  av_dict_set(&ret, e->key, e->value, 0);
264  if (p)
265  *p = ':';
266  }
267  return ret;
268 }
269 
270 static int opt_abort_on(void *optctx, const char *opt, const char *arg)
271 {
272  static const AVOption opts[] = {
273  { "abort_on" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
274  { "empty_output" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT }, .unit = "flags" },
275  { "empty_output_stream", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM }, .unit = "flags" },
276  { NULL },
277  };
278  static const AVClass class = {
279  .class_name = "",
280  .item_name = av_default_item_name,
281  .option = opts,
282  .version = LIBAVUTIL_VERSION_INT,
283  };
284  const AVClass *pclass = &class;
285 
286  return av_opt_eval_flags(&pclass, &opts[0], arg, &abort_on_flags);
287 }
288 
289 static int opt_stats_period(void *optctx, const char *opt, const char *arg)
290 {
291  int64_t user_stats_period = parse_time_or_die(opt, arg, 1);
292 
293  if (user_stats_period <= 0) {
294  av_log(NULL, AV_LOG_ERROR, "stats_period %s must be positive.\n", arg);
295  return AVERROR(EINVAL);
296  }
297 
298  stats_period = user_stats_period;
299  av_log(NULL, AV_LOG_INFO, "ffmpeg stats and -progress period set to %s.\n", arg);
300 
301  return 0;
302 }
303 
304 static int opt_sameq(void *optctx, const char *opt, const char *arg)
305 {
306  av_log(NULL, AV_LOG_ERROR, "Option '%s' was removed. "
307  "If you are looking for an option to preserve the quality (which is not "
308  "what -%s was for), use -qscale 0 or an equivalent quality factor option.\n",
309  opt, opt);
310  return AVERROR(EINVAL);
311 }
312 
313 static int opt_video_channel(void *optctx, const char *opt, const char *arg)
314 {
315  av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
316  return opt_default(optctx, "channel", arg);
317 }
318 
319 static int opt_video_standard(void *optctx, const char *opt, const char *arg)
320 {
321  av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
322  return opt_default(optctx, "standard", arg);
323 }
324 
325 static int opt_audio_codec(void *optctx, const char *opt, const char *arg)
326 {
327  OptionsContext *o = optctx;
328  return parse_option(o, "codec:a", arg, options);
329 }
330 
331 static int opt_video_codec(void *optctx, const char *opt, const char *arg)
332 {
333  OptionsContext *o = optctx;
334  return parse_option(o, "codec:v", arg, options);
335 }
336 
337 static int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
338 {
339  OptionsContext *o = optctx;
340  return parse_option(o, "codec:s", arg, options);
341 }
342 
343 static int opt_data_codec(void *optctx, const char *opt, const char *arg)
344 {
345  OptionsContext *o = optctx;
346  return parse_option(o, "codec:d", arg, options);
347 }
348 
349 static int opt_map(void *optctx, const char *opt, const char *arg)
350 {
351  OptionsContext *o = optctx;
352  StreamMap *m = NULL;
353  int i, negative = 0, file_idx, disabled = 0;
354  int sync_file_idx = -1, sync_stream_idx = 0;
355  char *p, *sync;
356  char *map;
357  char *allow_unused;
358 
359  if (*arg == '-') {
360  negative = 1;
361  arg++;
362  }
363  map = av_strdup(arg);
364  if (!map)
365  return AVERROR(ENOMEM);
366 
367  /* parse sync stream first, just pick first matching stream */
368  if (sync = strchr(map, ',')) {
369  *sync = 0;
370  sync_file_idx = strtol(sync + 1, &sync, 0);
371  if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
372  av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
373  exit_program(1);
374  }
375  if (*sync)
376  sync++;
377  for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
378  if (check_stream_specifier(input_files[sync_file_idx]->ctx,
379  input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
380  sync_stream_idx = i;
381  break;
382  }
383  if (i == input_files[sync_file_idx]->nb_streams) {
384  av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
385  "match any streams.\n", arg);
386  exit_program(1);
387  }
388  if (input_streams[input_files[sync_file_idx]->ist_index + sync_stream_idx]->user_set_discard == AVDISCARD_ALL) {
389  av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s matches a disabled input "
390  "stream.\n", arg);
391  exit_program(1);
392  }
393  }
394 
395 
396  if (map[0] == '[') {
397  /* this mapping refers to lavfi output */
398  const char *c = map + 1;
400  m = &o->stream_maps[o->nb_stream_maps - 1];
401  m->linklabel = av_get_token(&c, "]");
402  if (!m->linklabel) {
403  av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
404  exit_program(1);
405  }
406  } else {
407  if (allow_unused = strchr(map, '?'))
408  *allow_unused = 0;
409  file_idx = strtol(map, &p, 0);
410  if (file_idx >= nb_input_files || file_idx < 0) {
411  av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
412  exit_program(1);
413  }
414  if (negative)
415  /* disable some already defined maps */
416  for (i = 0; i < o->nb_stream_maps; i++) {
417  m = &o->stream_maps[i];
418  if (file_idx == m->file_index &&
421  *p == ':' ? p + 1 : p) > 0)
422  m->disabled = 1;
423  }
424  else
425  for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
426  if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
427  *p == ':' ? p + 1 : p) <= 0)
428  continue;
429  if (input_streams[input_files[file_idx]->ist_index + i]->user_set_discard == AVDISCARD_ALL) {
430  disabled = 1;
431  continue;
432  }
434  m = &o->stream_maps[o->nb_stream_maps - 1];
435 
436  m->file_index = file_idx;
437  m->stream_index = i;
438 
439  if (sync_file_idx >= 0) {
440  m->sync_file_index = sync_file_idx;
441  m->sync_stream_index = sync_stream_idx;
442  } else {
443  m->sync_file_index = file_idx;
444  m->sync_stream_index = i;
445  }
446  }
447  }
448 
449  if (!m) {
450  if (allow_unused) {
451  av_log(NULL, AV_LOG_VERBOSE, "Stream map '%s' matches no streams; ignoring.\n", arg);
452  } else if (disabled) {
453  av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches disabled streams.\n"
454  "To ignore this, add a trailing '?' to the map.\n", arg);
455  exit_program(1);
456  } else {
457  av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n"
458  "To ignore this, add a trailing '?' to the map.\n", arg);
459  exit_program(1);
460  }
461  }
462 
463  av_freep(&map);
464  return 0;
465 }
466 
467 static int opt_attach(void *optctx, const char *opt, const char *arg)
468 {
469  OptionsContext *o = optctx;
471  o->attachments[o->nb_attachments - 1] = arg;
472  return 0;
473 }
474 
475 static int opt_map_channel(void *optctx, const char *opt, const char *arg)
476 {
477  OptionsContext *o = optctx;
478  int n;
479  AVStream *st;
480  AudioChannelMap *m;
481  char *allow_unused;
482  char *mapchan;
483  mapchan = av_strdup(arg);
484  if (!mapchan)
485  return AVERROR(ENOMEM);
486 
489 
490  /* muted channel syntax */
491  n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
492  if ((n == 1 || n == 3) && m->channel_idx == -1) {
493  m->file_idx = m->stream_idx = -1;
494  if (n == 1)
495  m->ofile_idx = m->ostream_idx = -1;
496  av_free(mapchan);
497  return 0;
498  }
499 
500  /* normal syntax */
501  n = sscanf(arg, "%d.%d.%d:%d.%d",
502  &m->file_idx, &m->stream_idx, &m->channel_idx,
503  &m->ofile_idx, &m->ostream_idx);
504 
505  if (n != 3 && n != 5) {
506  av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
507  "[file.stream.channel|-1][:syncfile:syncstream]\n");
508  exit_program(1);
509  }
510 
511  if (n != 5) // only file.stream.channel specified
512  m->ofile_idx = m->ostream_idx = -1;
513 
514  /* check input */
515  if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
516  av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
517  m->file_idx);
518  exit_program(1);
519  }
520  if (m->stream_idx < 0 ||
522  av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
523  m->file_idx, m->stream_idx);
524  exit_program(1);
525  }
526  st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
527  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
528  av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
529  m->file_idx, m->stream_idx);
530  exit_program(1);
531  }
532  /* allow trailing ? to map_channel */
533  if (allow_unused = strchr(mapchan, '?'))
534  *allow_unused = 0;
535  if (m->channel_idx < 0 || m->channel_idx >= st->codecpar->channels ||
537  if (allow_unused) {
538  av_log(NULL, AV_LOG_VERBOSE, "mapchan: invalid audio channel #%d.%d.%d\n",
539  m->file_idx, m->stream_idx, m->channel_idx);
540  } else {
541  av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n"
542  "To ignore this, add a trailing '?' to the map_channel.\n",
543  m->file_idx, m->stream_idx, m->channel_idx);
544  exit_program(1);
545  }
546 
547  }
548  av_free(mapchan);
549  return 0;
550 }
551 
552 static int opt_sdp_file(void *optctx, const char *opt, const char *arg)
553 {
556  return 0;
557 }
558 
559 #if CONFIG_VAAPI
560 static int opt_vaapi_device(void *optctx, const char *opt, const char *arg)
561 {
562  const char *prefix = "vaapi:";
563  char *tmp;
564  int err;
565  tmp = av_asprintf("%s%s", prefix, arg);
566  if (!tmp)
567  return AVERROR(ENOMEM);
569  av_free(tmp);
570  return err;
571 }
572 #endif
573 
574 static int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
575 {
576  if (!strcmp(arg, "list")) {
578  printf("Supported hardware device types:\n");
579  while ((type = av_hwdevice_iterate_types(type)) !=
582  printf("\n");
583  exit_program(0);
584  } else {
586  }
587 }
588 
589 static int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
590 {
591  if (filter_hw_device) {
592  av_log(NULL, AV_LOG_ERROR, "Only one filter device can be used.\n");
593  return AVERROR(EINVAL);
594  }
596  if (!filter_hw_device) {
597  av_log(NULL, AV_LOG_ERROR, "Invalid filter device %s.\n", arg);
598  return AVERROR(EINVAL);
599  }
600  return 0;
601 }
602 
603 /**
604  * Parse a metadata specifier passed as 'arg' parameter.
605  * @param arg metadata string to parse
606  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
607  * @param index for type c/p, chapter/program index is written here
608  * @param stream_spec for type s, the stream specifier is written here
609  */
610 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
611 {
612  if (*arg) {
613  *type = *arg;
614  switch (*arg) {
615  case 'g':
616  break;
617  case 's':
618  if (*(++arg) && *arg != ':') {
619  av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
620  exit_program(1);
621  }
622  *stream_spec = *arg == ':' ? arg + 1 : "";
623  break;
624  case 'c':
625  case 'p':
626  if (*(++arg) == ':')
627  *index = strtol(++arg, NULL, 0);
628  break;
629  default:
630  av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
631  exit_program(1);
632  }
633  } else
634  *type = 'g';
635 }
636 
637 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
638 {
639  AVDictionary **meta_in = NULL;
640  AVDictionary **meta_out = NULL;
641  int i, ret = 0;
642  char type_in, type_out;
643  const char *istream_spec = NULL, *ostream_spec = NULL;
644  int idx_in = 0, idx_out = 0;
645 
646  parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
647  parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
648 
649  if (!ic) {
650  if (type_out == 'g' || !*outspec)
651  o->metadata_global_manual = 1;
652  if (type_out == 's' || !*outspec)
654  if (type_out == 'c' || !*outspec)
656  return 0;
657  }
658 
659  if (type_in == 'g' || type_out == 'g')
660  o->metadata_global_manual = 1;
661  if (type_in == 's' || type_out == 's')
663  if (type_in == 'c' || type_out == 'c')
665 
666  /* ic is NULL when just disabling automatic mappings */
667  if (!ic)
668  return 0;
669 
670 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
671  if ((index) < 0 || (index) >= (nb_elems)) {\
672  av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
673  (desc), (index));\
674  exit_program(1);\
675  }
676 
677 #define SET_DICT(type, meta, context, index)\
678  switch (type) {\
679  case 'g':\
680  meta = &context->metadata;\
681  break;\
682  case 'c':\
683  METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
684  meta = &context->chapters[index]->metadata;\
685  break;\
686  case 'p':\
687  METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
688  meta = &context->programs[index]->metadata;\
689  break;\
690  case 's':\
691  break; /* handled separately below */ \
692  default: av_assert0(0);\
693  }\
694 
695  SET_DICT(type_in, meta_in, ic, idx_in);
696  SET_DICT(type_out, meta_out, oc, idx_out);
697 
698  /* for input streams choose first matching stream */
699  if (type_in == 's') {
700  for (i = 0; i < ic->nb_streams; i++) {
701  if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
702  meta_in = &ic->streams[i]->metadata;
703  break;
704  } else if (ret < 0)
705  exit_program(1);
706  }
707  if (!meta_in) {
708  av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
709  exit_program(1);
710  }
711  }
712 
713  if (type_out == 's') {
714  for (i = 0; i < oc->nb_streams; i++) {
715  if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
716  meta_out = &oc->streams[i]->metadata;
717  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
718  } else if (ret < 0)
719  exit_program(1);
720  }
721  } else
722  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
723 
724  return 0;
725 }
726 
727 static int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
728 {
729  OptionsContext *o = optctx;
730  char buf[128];
731  int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
732  struct tm time = *gmtime((time_t*)&recording_timestamp);
733  if (!strftime(buf, sizeof(buf), "creation_time=%Y-%m-%dT%H:%M:%S%z", &time))
734  return -1;
735  parse_option(o, "metadata", buf, options);
736 
737  av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
738  "tag instead.\n", opt);
739  return 0;
740 }
741 
742 static const AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
743 {
744  const AVCodecDescriptor *desc;
745  const char *codec_string = encoder ? "encoder" : "decoder";
746  const AVCodec *codec;
747 
748  codec = encoder ?
751 
752  if (!codec && (desc = avcodec_descriptor_get_by_name(name))) {
753  codec = encoder ? avcodec_find_encoder(desc->id) :
755  if (codec)
756  av_log(NULL, AV_LOG_VERBOSE, "Matched %s '%s' for codec '%s'.\n",
757  codec_string, codec->name, desc->name);
758  }
759 
760  if (!codec) {
761  av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
762  exit_program(1);
763  }
764  if (codec->type != type && !recast_media) {
765  av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
766  exit_program(1);
767  }
768  return codec;
769 }
770 
772 {
773  char *codec_name = NULL;
774 
775  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
776  if (codec_name) {
777  const AVCodec *codec = find_codec_or_die(codec_name, st->codecpar->codec_type, 0);
778  st->codecpar->codec_id = codec->id;
779  if (recast_media && st->codecpar->codec_type != codec->type)
780  st->codecpar->codec_type = codec->type;
781  return codec;
782  } else
784 }
785 
786 /* Add all the streams from the given input file to the global
787  * list of input streams. */
789 {
790  int i, ret;
791 
792  for (i = 0; i < ic->nb_streams; i++) {
793  AVStream *st = ic->streams[i];
794  AVCodecParameters *par = st->codecpar;
795  InputStream *ist = av_mallocz(sizeof(*ist));
796  char *framerate = NULL, *hwaccel_device = NULL;
797  const char *hwaccel = NULL;
798  char *hwaccel_output_format = NULL;
799  char *codec_tag = NULL;
800  char *next;
801  char *discard_str = NULL;
802  const AVClass *cc = avcodec_get_class();
803  const AVOption *discard_opt = av_opt_find(&cc, "skip_frame", NULL, 0, 0);
804 
805  if (!ist)
806  exit_program(1);
807 
810 
811  ist->st = st;
812  ist->file_index = nb_input_files;
813  ist->discard = 1;
814  st->discard = AVDISCARD_ALL;
815  ist->nb_samples = 0;
816  ist->first_dts = AV_NOPTS_VALUE;
817  ist->min_pts = INT64_MAX;
818  ist->max_pts = INT64_MIN;
819 
820  ist->ts_scale = 1.0;
821  MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
822 
823  ist->autorotate = 1;
824  MATCH_PER_STREAM_OPT(autorotate, i, ist->autorotate, ic, st);
825 
826  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
827  if (codec_tag) {
828  uint32_t tag = strtol(codec_tag, &next, 0);
829  if (*next)
830  tag = AV_RL32(codec_tag);
831  st->codecpar->codec_tag = tag;
832  }
833 
834  ist->dec = choose_decoder(o, ic, st);
835  ist->decoder_opts = filter_codec_opts(o->g->codec_opts, ist->st->codecpar->codec_id, ic, st, ist->dec);
836 
837  ist->reinit_filters = -1;
838  MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);
839 
840  MATCH_PER_STREAM_OPT(discard, str, discard_str, ic, st);
841  ist->user_set_discard = AVDISCARD_NONE;
842 
843  if ((o->video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ||
844  (o->audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ||
845  (o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) ||
846  (o->data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA))
847  ist->user_set_discard = AVDISCARD_ALL;
848 
849  if (discard_str && av_opt_eval_int(&cc, discard_opt, discard_str, &ist->user_set_discard) < 0) {
850  av_log(NULL, AV_LOG_ERROR, "Error parsing discard %s.\n",
851  discard_str);
852  exit_program(1);
853  }
854 
855  ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;
856 
857  ist->dec_ctx = avcodec_alloc_context3(ist->dec);
858  if (!ist->dec_ctx) {
859  av_log(NULL, AV_LOG_ERROR, "Error allocating the decoder context.\n");
860  exit_program(1);
861  }
862 
863  ret = avcodec_parameters_to_context(ist->dec_ctx, par);
864  if (ret < 0) {
865  av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
866  exit_program(1);
867  }
868 
869  if (o->bitexact)
870  ist->dec_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
871 
872  switch (par->codec_type) {
873  case AVMEDIA_TYPE_VIDEO:
874  if(!ist->dec)
875  ist->dec = avcodec_find_decoder(par->codec_id);
876 
877  // avformat_find_stream_info() doesn't set this for us anymore.
878  ist->dec_ctx->framerate = st->avg_frame_rate;
879 
880  MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
881  if (framerate && av_parse_video_rate(&ist->framerate,
882  framerate) < 0) {
883  av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
884  framerate);
885  exit_program(1);
886  }
887 
888  ist->top_field_first = -1;
889  MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
890 
891  MATCH_PER_STREAM_OPT(hwaccels, str, hwaccel, ic, st);
892  MATCH_PER_STREAM_OPT(hwaccel_output_formats, str,
893  hwaccel_output_format, ic, st);
894 
895  if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "cuvid")) {
897  "WARNING: defaulting hwaccel_output_format to cuda for compatibility "
898  "with old commandlines. This behaviour is DEPRECATED and will be removed "
899  "in the future. Please explicitly set \"-hwaccel_output_format cuda\".\n");
900  ist->hwaccel_output_format = AV_PIX_FMT_CUDA;
901  } else if (hwaccel_output_format) {
902  ist->hwaccel_output_format = av_get_pix_fmt(hwaccel_output_format);
903  if (ist->hwaccel_output_format == AV_PIX_FMT_NONE) {
904  av_log(NULL, AV_LOG_FATAL, "Unrecognised hwaccel output "
905  "format: %s", hwaccel_output_format);
906  }
907  } else {
908  ist->hwaccel_output_format = AV_PIX_FMT_NONE;
909  }
910 
911  if (hwaccel) {
912  // The NVDEC hwaccels use a CUDA device, so remap the name here.
913  if (!strcmp(hwaccel, "nvdec") || !strcmp(hwaccel, "cuvid"))
914  hwaccel = "cuda";
915 
916  if (!strcmp(hwaccel, "none"))
917  ist->hwaccel_id = HWACCEL_NONE;
918  else if (!strcmp(hwaccel, "auto"))
919  ist->hwaccel_id = HWACCEL_AUTO;
920  else {
921  enum AVHWDeviceType type;
922  int i;
923  for (i = 0; hwaccels[i].name; i++) {
924  if (!strcmp(hwaccels[i].name, hwaccel)) {
925  ist->hwaccel_id = hwaccels[i].id;
926  break;
927  }
928  }
929 
930  if (!ist->hwaccel_id) {
932  if (type != AV_HWDEVICE_TYPE_NONE) {
933  ist->hwaccel_id = HWACCEL_GENERIC;
934  ist->hwaccel_device_type = type;
935  }
936  }
937 
938  if (!ist->hwaccel_id) {
939  av_log(NULL, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",
940  hwaccel);
941  av_log(NULL, AV_LOG_FATAL, "Supported hwaccels: ");
943  while ((type = av_hwdevice_iterate_types(type)) !=
945  av_log(NULL, AV_LOG_FATAL, "%s ",
947  av_log(NULL, AV_LOG_FATAL, "\n");
948  exit_program(1);
949  }
950  }
951  }
952 
953  MATCH_PER_STREAM_OPT(hwaccel_devices, str, hwaccel_device, ic, st);
954  if (hwaccel_device) {
955  ist->hwaccel_device = av_strdup(hwaccel_device);
956  if (!ist->hwaccel_device)
957  exit_program(1);
958  }
959 
960  ist->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
961 
962  break;
963  case AVMEDIA_TYPE_AUDIO:
964  ist->guess_layout_max = INT_MAX;
965  MATCH_PER_STREAM_OPT(guess_layout_max, i, ist->guess_layout_max, ic, st);
967  break;
968  case AVMEDIA_TYPE_DATA:
969  case AVMEDIA_TYPE_SUBTITLE: {
970  char *canvas_size = NULL;
971  if(!ist->dec)
972  ist->dec = avcodec_find_decoder(par->codec_id);
973  MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);
974  MATCH_PER_STREAM_OPT(canvas_sizes, str, canvas_size, ic, st);
975  if (canvas_size &&
976  av_parse_video_size(&ist->dec_ctx->width, &ist->dec_ctx->height, canvas_size) < 0) {
977  av_log(NULL, AV_LOG_FATAL, "Invalid canvas size: %s.\n", canvas_size);
978  exit_program(1);
979  }
980  break;
981  }
984  break;
985  default:
986  abort();
987  }
988 
989  ret = avcodec_parameters_from_context(par, ist->dec_ctx);
990  if (ret < 0) {
991  av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
992  exit_program(1);
993  }
994  }
995 }
996 
997 static void assert_file_overwrite(const char *filename)
998 {
999  const char *proto_name = avio_find_protocol_name(filename);
1000 
1002  fprintf(stderr, "Error, both -y and -n supplied. Exiting.\n");
1003  exit_program(1);
1004  }
1005 
1006  if (!file_overwrite) {
1007  if (proto_name && !strcmp(proto_name, "file") && avio_check(filename, 0) == 0) {
1009  fprintf(stderr,"File '%s' already exists. Overwrite? [y/N] ", filename);
1010  fflush(stderr);
1011  term_exit();
1012  signal(SIGINT, SIG_DFL);
1013  if (!read_yesno()) {
1014  av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
1015  exit_program(1);
1016  }
1017  term_init();
1018  }
1019  else {
1020  av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
1021  exit_program(1);
1022  }
1023  }
1024  }
1025 
1026  if (proto_name && !strcmp(proto_name, "file")) {
1027  for (int i = 0; i < nb_input_files; i++) {
1028  InputFile *file = input_files[i];
1029  if (file->ctx->iformat->flags & AVFMT_NOFILE)
1030  continue;
1031  if (!strcmp(filename, file->ctx->url)) {
1032  av_log(NULL, AV_LOG_FATAL, "Output %s same as Input #%d - exiting\n", filename, i);
1033  av_log(NULL, AV_LOG_WARNING, "FFmpeg cannot edit existing files in-place.\n");
1034  exit_program(1);
1035  }
1036  }
1037  }
1038 }
1039 
1040 static void dump_attachment(AVStream *st, const char *filename)
1041 {
1042  int ret;
1043  AVIOContext *out = NULL;
1044  AVDictionaryEntry *e;
1045 
1046  if (!st->codecpar->extradata_size) {
1047  av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
1048  nb_input_files - 1, st->index);
1049  return;
1050  }
1051  if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
1052  filename = e->value;
1053  if (!*filename) {
1054  av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
1055  "in stream #%d:%d.\n", nb_input_files - 1, st->index);
1056  exit_program(1);
1057  }
1058 
1059  assert_file_overwrite(filename);
1060 
1061  if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
1062  av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
1063  filename);
1064  exit_program(1);
1065  }
1066 
1068  avio_flush(out);
1069  avio_close(out);
1070 }
1071 
1072 static int open_input_file(OptionsContext *o, const char *filename)
1073 {
1074  InputFile *f;
1075  AVFormatContext *ic;
1076  const AVInputFormat *file_iformat = NULL;
1077  int err, i, ret;
1078  int64_t timestamp;
1079  AVDictionary *unused_opts = NULL;
1080  AVDictionaryEntry *e = NULL;
1081  char * video_codec_name = NULL;
1082  char * audio_codec_name = NULL;
1083  char *subtitle_codec_name = NULL;
1084  char * data_codec_name = NULL;
1085  int scan_all_pmts_set = 0;
1086 
1087  if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
1088  o->stop_time = INT64_MAX;
1089  av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
1090  }
1091 
1092  if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
1093  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
1094  if (o->stop_time <= start_time) {
1095  av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
1096  exit_program(1);
1097  } else {
1099  }
1100  }
1101 
1102  if (o->format) {
1103  if (!(file_iformat = av_find_input_format(o->format))) {
1104  av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
1105  exit_program(1);
1106  }
1107  }
1108 
1109  if (!strcmp(filename, "-"))
1110  filename = "pipe:";
1111 
1112  stdin_interaction &= strncmp(filename, "pipe:", 5) &&
1113  strcmp(filename, "/dev/stdin");
1114 
1115  /* get default parameters from command line */
1116  ic = avformat_alloc_context();
1117  if (!ic) {
1118  print_error(filename, AVERROR(ENOMEM));
1119  exit_program(1);
1120  }
1121  if (o->nb_audio_sample_rate) {
1122  av_dict_set_int(&o->g->format_opts, "sample_rate", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i, 0);
1123  }
1124  if (o->nb_audio_channels) {
1125  const AVClass *priv_class;
1126  /* because we set audio_channels based on both the "ac" and
1127  * "channel_layout" options, we need to check that the specified
1128  * demuxer actually has the "channels" option before setting it */
1129  if (file_iformat && (priv_class = file_iformat->priv_class) &&
1130  av_opt_find(&priv_class, "channels", NULL, 0,
1132  av_dict_set_int(&o->g->format_opts, "channels", o->audio_channels[o->nb_audio_channels - 1].u.i, 0);
1133  }
1134  }
1135  if (o->nb_frame_rates) {
1136  const AVClass *priv_class;
1137  /* set the format-level framerate option;
1138  * this is important for video grabbers, e.g. x11 */
1139  if (file_iformat && (priv_class = file_iformat->priv_class) &&
1140  av_opt_find(&priv_class, "framerate", NULL, 0,
1142  av_dict_set(&o->g->format_opts, "framerate",
1143  o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
1144  }
1145  }
1146  if (o->nb_frame_sizes) {
1147  av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
1148  }
1149  if (o->nb_frame_pix_fmts)
1150  av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
1151 
1152  MATCH_PER_TYPE_OPT(codec_names, str, video_codec_name, ic, "v");
1153  MATCH_PER_TYPE_OPT(codec_names, str, audio_codec_name, ic, "a");
1154  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, ic, "s");
1155  MATCH_PER_TYPE_OPT(codec_names, str, data_codec_name, ic, "d");
1156 
1157  if (video_codec_name)
1159  if (audio_codec_name)
1161  if (subtitle_codec_name)
1163  if (data_codec_name)
1164  ic->data_codec = find_codec_or_die(data_codec_name , AVMEDIA_TYPE_DATA , 0);
1165 
1169  ic->data_codec_id = data_codec_name ? ic->data_codec->id : AV_CODEC_ID_NONE;
1170 
1171  ic->flags |= AVFMT_FLAG_NONBLOCK;
1172  if (o->bitexact)
1173  ic->flags |= AVFMT_FLAG_BITEXACT;
1174  ic->interrupt_callback = int_cb;
1175 
1176  if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
1177  av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
1178  scan_all_pmts_set = 1;
1179  }
1180  /* open the input file with generic avformat function */
1181  err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
1182  if (err < 0) {
1183  print_error(filename, err);
1184  if (err == AVERROR_PROTOCOL_NOT_FOUND)
1185  av_log(NULL, AV_LOG_ERROR, "Did you mean file:%s?\n", filename);
1186  exit_program(1);
1187  }
1188  if (scan_all_pmts_set)
1189  av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
1192 
1193  /* apply forced codec ids */
1194  for (i = 0; i < ic->nb_streams; i++)
1195  choose_decoder(o, ic, ic->streams[i]);
1196 
1197  if (find_stream_info) {
1199  int orig_nb_streams = ic->nb_streams;
1200 
1201  /* If not enough info to get the stream parameters, we decode the
1202  first frames to get it. (used in mpeg case for example) */
1204 
1205  for (i = 0; i < orig_nb_streams; i++)
1206  av_dict_free(&opts[i]);
1207  av_freep(&opts);
1208 
1209  if (ret < 0) {
1210  av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
1211  if (ic->nb_streams == 0) {
1212  avformat_close_input(&ic);
1213  exit_program(1);
1214  }
1215  }
1216  }
1217 
1219  av_log(NULL, AV_LOG_WARNING, "Cannot use -ss and -sseof both, using -ss for %s\n", filename);
1221  }
1222 
1223  if (o->start_time_eof != AV_NOPTS_VALUE) {
1224  if (o->start_time_eof >= 0) {
1225  av_log(NULL, AV_LOG_ERROR, "-sseof value must be negative; aborting\n");
1226  exit_program(1);
1227  }
1228  if (ic->duration > 0) {
1229  o->start_time = o->start_time_eof + ic->duration;
1230  if (o->start_time < 0) {
1231  av_log(NULL, AV_LOG_WARNING, "-sseof value seeks to before start of file %s; ignored\n", filename);
1233  }
1234  } else
1235  av_log(NULL, AV_LOG_WARNING, "Cannot use -sseof, duration of %s not known\n", filename);
1236  }
1237  timestamp = (o->start_time == AV_NOPTS_VALUE) ? 0 : o->start_time;
1238  /* add the stream start time */
1239  if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
1240  timestamp += ic->start_time;
1241 
1242  /* if seeking requested, we execute it */
1243  if (o->start_time != AV_NOPTS_VALUE) {
1244  int64_t seek_timestamp = timestamp;
1245 
1246  if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
1247  int dts_heuristic = 0;
1248  for (i=0; i<ic->nb_streams; i++) {
1249  const AVCodecParameters *par = ic->streams[i]->codecpar;
1250  if (par->video_delay) {
1251  dts_heuristic = 1;
1252  break;
1253  }
1254  }
1255  if (dts_heuristic) {
1256  seek_timestamp -= 3*AV_TIME_BASE / 23;
1257  }
1258  }
1259  ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
1260  if (ret < 0) {
1261  av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
1262  filename, (double)timestamp / AV_TIME_BASE);
1263  }
1264  }
1265 
1266  /* update the current parameters so that they match the one of the input stream */
1267  add_input_streams(o, ic);
1268 
1269  /* dump the file content */
1270  av_dump_format(ic, nb_input_files, filename, 0);
1271 
1273  f = av_mallocz(sizeof(*f));
1274  if (!f)
1275  exit_program(1);
1276  input_files[nb_input_files - 1] = f;
1277 
1278  f->ctx = ic;
1279  f->ist_index = nb_input_streams - ic->nb_streams;
1280  f->start_time = o->start_time;
1281  f->recording_time = o->recording_time;
1282  f->input_ts_offset = o->input_ts_offset;
1283  f->ts_offset = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
1284  f->nb_streams = ic->nb_streams;
1285  f->rate_emu = o->rate_emu;
1286  f->accurate_seek = o->accurate_seek;
1287  f->loop = o->loop;
1288  f->duration = 0;
1289  f->time_base = (AVRational){ 1, 1 };
1290 
1291  f->readrate = o->readrate ? o->readrate : 0.0;
1292  if (f->readrate < 0.0f) {
1293  av_log(NULL, AV_LOG_ERROR, "Option -readrate for Input #%d is %0.3f; it must be non-negative.\n", nb_input_files, f->readrate);
1294  exit_program(1);
1295  }
1296  if (f->readrate && f->rate_emu) {
1297  av_log(NULL, AV_LOG_WARNING, "Both -readrate and -re set for Input #%d. Using -readrate %0.3f.\n", nb_input_files, f->readrate);
1298  f->rate_emu = 0;
1299  }
1300 
1301  f->pkt = av_packet_alloc();
1302  if (!f->pkt)
1303  exit_program(1);
1304 #if HAVE_THREADS
1305  f->thread_queue_size = o->thread_queue_size;
1306 #endif
1307 
1308  /* check if all codec options have been used */
1309  unused_opts = strip_specifiers(o->g->codec_opts);
1310  for (i = f->ist_index; i < nb_input_streams; i++) {
1311  e = NULL;
1312  while ((e = av_dict_get(input_streams[i]->decoder_opts, "", e,
1314  av_dict_set(&unused_opts, e->key, NULL, 0);
1315  }
1316 
1317  e = NULL;
1318  while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
1319  const AVClass *class = avcodec_get_class();
1320  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
1322  const AVClass *fclass = avformat_get_class();
1323  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
1325  if (!option || foption)
1326  continue;
1327 
1328 
1329  if (!(option->flags & AV_OPT_FLAG_DECODING_PARAM)) {
1330  av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
1331  "input file #%d (%s) is not a decoding option.\n", e->key,
1332  option->help ? option->help : "", nb_input_files - 1,
1333  filename);
1334  exit_program(1);
1335  }
1336 
1337  av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
1338  "input file #%d (%s) has not been used for any stream. The most "
1339  "likely reason is either wrong type (e.g. a video option with "
1340  "no video streams) or that it is a private option of some decoder "
1341  "which was not actually used for any stream.\n", e->key,
1342  option->help ? option->help : "", nb_input_files - 1, filename);
1343  }
1344  av_dict_free(&unused_opts);
1345 
1346  for (i = 0; i < o->nb_dump_attachment; i++) {
1347  int j;
1348 
1349  for (j = 0; j < ic->nb_streams; j++) {
1350  AVStream *st = ic->streams[j];
1351 
1352  if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
1354  }
1355  }
1356 
1358 
1359  return 0;
1360 }
1361 
1362 static uint8_t *get_line(AVIOContext *s)
1363 {
1364  AVIOContext *line;
1365  uint8_t *buf;
1366  char c;
1367 
1368  if (avio_open_dyn_buf(&line) < 0) {
1369  av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
1370  exit_program(1);
1371  }
1372 
1373  while ((c = avio_r8(s)) && c != '\n')
1374  avio_w8(line, c);
1375  avio_w8(line, 0);
1376  avio_close_dyn_buf(line, &buf);
1377 
1378  return buf;
1379 }
1380 
1381 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
1382 {
1383  int i, ret = -1;
1384  char filename[1000];
1385  const char *base[3] = { getenv("AVCONV_DATADIR"),
1386  getenv("HOME"),
1387  AVCONV_DATADIR,
1388  };
1389 
1390  for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
1391  if (!base[i])
1392  continue;
1393  if (codec_name) {
1394  snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
1395  i != 1 ? "" : "/.avconv", codec_name, preset_name);
1396  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1397  }
1398  if (ret < 0) {
1399  snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
1400  i != 1 ? "" : "/.avconv", preset_name);
1401  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1402  }
1403  }
1404  return ret;
1405 }
1406 
1408 {
1410  char *codec_name = NULL;
1411 
1413  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
1414  if (!codec_name) {
1415  ost->st->codecpar->codec_id = av_guess_codec(s->oformat, NULL, s->url,
1416  NULL, ost->st->codecpar->codec_type);
1418  if (!ost->enc) {
1419  av_log(NULL, AV_LOG_FATAL, "Automatic encoder selection failed for "
1420  "output stream #%d:%d. Default encoder for format %s (codec %s) is "
1421  "probably disabled. Please choose an encoder manually.\n",
1422  ost->file_index, ost->index, s->oformat->name,
1425  }
1426  } else if (!strcmp(codec_name, "copy"))
1427  ost->stream_copy = 1;
1428  else {
1429  ost->enc = find_codec_or_die(codec_name, ost->st->codecpar->codec_type, 1);
1430  ost->st->codecpar->codec_id = ost->enc->id;
1431  }
1433  } else {
1434  /* no encoding supported for other media types */
1435  ost->stream_copy = 1;
1436  ost->encoding_needed = 0;
1437  }
1438 
1439  return 0;
1440 }
1441 
1443 {
1444  OutputStream *ost;
1445  AVStream *st = avformat_new_stream(oc, NULL);
1446  int idx = oc->nb_streams - 1, ret = 0;
1447  const char *bsfs = NULL, *time_base = NULL;
1448  char *next, *codec_tag = NULL;
1449  double qscale = -1;
1450  int i;
1451 
1452  if (!st) {
1453  av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
1454  exit_program(1);
1455  }
1456 
1457  if (oc->nb_streams - 1 < o->nb_streamid_map)
1458  st->id = o->streamid_map[oc->nb_streams - 1];
1459 
1461  if (!(ost = av_mallocz(sizeof(*ost))))
1462  exit_program(1);
1464 
1466  ost->index = idx;
1467  ost->st = st;
1469  st->codecpar->codec_type = type;
1470 
1471  ret = choose_encoder(o, oc, ost);
1472  if (ret < 0) {
1473  av_log(NULL, AV_LOG_FATAL, "Error selecting an encoder for stream "
1474  "%d:%d\n", ost->file_index, ost->index);
1475  exit_program(1);
1476  }
1477 
1479  if (!ost->enc_ctx) {
1480  av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding context.\n");
1481  exit_program(1);
1482  }
1483  ost->enc_ctx->codec_type = type;
1484 
1486  if (!ost->ref_par) {
1487  av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding parameters.\n");
1488  exit_program(1);
1489  }
1490 
1491  if (ost->enc) {
1492  AVIOContext *s = NULL;
1493  char *buf = NULL, *arg = NULL, *preset = NULL;
1494 
1495  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, ost->enc->id, oc, st, ost->enc);
1496 
1498  ost->autoscale = 1;
1499  MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
1500  if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
1501  do {
1502  buf = get_line(s);
1503  if (!buf[0] || buf[0] == '#') {
1504  av_free(buf);
1505  continue;
1506  }
1507  if (!(arg = strchr(buf, '='))) {
1508  av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1509  exit_program(1);
1510  }
1511  *arg++ = 0;
1513  av_free(buf);
1514  } while (!s->eof_reached);
1515  avio_closep(&s);
1516  }
1517  if (ret) {
1519  "Preset %s specified for stream %d:%d, but could not be opened.\n",
1520  preset, ost->file_index, ost->index);
1521  exit_program(1);
1522  }
1523  } else {
1525  }
1526 
1527 
1528  if (o->bitexact)
1530 
1531  MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
1532  if (time_base) {
1533  AVRational q;
1534  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1535  q.num <= 0 || q.den <= 0) {
1536  av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1537  exit_program(1);
1538  }
1539  st->time_base = q;
1540  }
1541 
1542  MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);
1543  if (time_base) {
1544  AVRational q;
1545  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1546  q.den <= 0) {
1547  av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1548  exit_program(1);
1549  }
1550  ost->enc_timebase = q;
1551  }
1552 
1553  ost->max_frames = INT64_MAX;
1554  MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
1555  for (i = 0; i<o->nb_max_frames; i++) {
1556  char *p = o->max_frames[i].specifier;
1557  if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1558  av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1559  break;
1560  }
1561  }
1562 
1563  ost->copy_prior_start = -1;
1564  MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);
1565 
1566  MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
1567  if (bsfs && *bsfs) {
1568  ret = av_bsf_list_parse_str(bsfs, &ost->bsf_ctx);
1569  if (ret < 0) {
1570  av_log(NULL, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1571  exit_program(1);
1572  }
1573  }
1574 
1575  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1576  if (codec_tag) {
1577  uint32_t tag = strtol(codec_tag, &next, 0);
1578  if (*next)
1579  tag = AV_RL32(codec_tag);
1580  ost->st->codecpar->codec_tag =
1581  ost->enc_ctx->codec_tag = tag;
1582  }
1583 
1584  MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1585  if (qscale >= 0) {
1587  ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1588  }
1589 
1590  MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);
1592 
1593  ost->max_muxing_queue_size = 128;
1594  MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ost->max_muxing_queue_size, oc, st);
1595  ost->max_muxing_queue_size *= sizeof(ost->pkt);
1596 
1598 
1599  ost->muxing_queue_data_threshold = 50*1024*1024;
1600  MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, ost->muxing_queue_data_threshold, oc, st);
1601 
1602  if (oc->oformat->flags & AVFMT_GLOBALHEADER)
1604 
1605  av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
1606 
1607  av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1608  if (ost->enc && av_get_exact_bits_per_sample(ost->enc->id) == 24)
1609  av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1610 
1612 
1613  ost->source_index = source_index;
1614  if (source_index >= 0) {
1615  ost->sync_ist = input_streams[source_index];
1616  input_streams[source_index]->discard = 0;
1617  input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;
1618  }
1620 
1621  ost->muxing_queue = av_fifo_alloc(8 * sizeof(AVPacket));
1622  if (!ost->muxing_queue)
1623  exit_program(1);
1624 
1625  return ost;
1626 }
1627 
1628 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
1629 {
1630  int i;
1631  const char *p = str;
1632  for (i = 0;; i++) {
1633  dest[i] = atoi(p);
1634  if (i == 63)
1635  break;
1636  p = strchr(p, ',');
1637  if (!p) {
1638  av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
1639  exit_program(1);
1640  }
1641  p++;
1642  }
1643 }
1644 
1645 /* read file contents into a string */
1646 static uint8_t *read_file(const char *filename)
1647 {
1648  AVIOContext *pb = NULL;
1649  AVIOContext *dyn_buf = NULL;
1650  int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
1651  uint8_t buf[1024], *str;
1652 
1653  if (ret < 0) {
1654  av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
1655  return NULL;
1656  }
1657 
1658  ret = avio_open_dyn_buf(&dyn_buf);
1659  if (ret < 0) {
1660  avio_closep(&pb);
1661  return NULL;
1662  }
1663  while ((ret = avio_read(pb, buf, sizeof(buf))) > 0)
1664  avio_write(dyn_buf, buf, ret);
1665  avio_w8(dyn_buf, 0);
1666  avio_closep(&pb);
1667 
1668  ret = avio_close_dyn_buf(dyn_buf, &str);
1669  if (ret < 0)
1670  return NULL;
1671  return str;
1672 }
1673 
1675  OutputStream *ost)
1676 {
1677  AVStream *st = ost->st;
1678 
1679  if (ost->filters_script && ost->filters) {
1680  av_log(NULL, AV_LOG_ERROR, "Both -filter and -filter_script set for "
1681  "output stream #%d:%d.\n", nb_output_files, st->index);
1682  exit_program(1);
1683  }
1684 
1685  if (ost->filters_script)
1686  return read_file(ost->filters_script);
1687  else if (ost->filters)
1688  return av_strdup(ost->filters);
1689 
1691  "null" : "anull");
1692 }
1693 
1695  const OutputStream *ost, enum AVMediaType type)
1696 {
1697  if (ost->filters_script || ost->filters) {
1699  "%s '%s' was defined for %s output stream %d:%d but codec copy was selected.\n"
1700  "Filtering and streamcopy cannot be used together.\n",
1701  ost->filters ? "Filtergraph" : "Filtergraph script",
1704  exit_program(1);
1705  }
1706 }
1707 
1709 {
1710  AVStream *st;
1711  OutputStream *ost;
1712  AVCodecContext *video_enc;
1713  char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
1714 
1715  ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
1716  st = ost->st;
1717  video_enc = ost->enc_ctx;
1718 
1719  MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
1720  if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
1721  av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
1722  exit_program(1);
1723  }
1724 
1725  MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
1726  if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
1727  av_log(NULL, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
1728  exit_program(1);
1729  }
1730 
1731  if (frame_rate && max_frame_rate) {
1732  av_log(NULL, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
1733  exit_program(1);
1734  }
1735 
1736  if ((frame_rate || max_frame_rate) &&
1738  av_log(NULL, AV_LOG_ERROR, "Using -vsync 0 and -r/-fpsmax can produce invalid output files\n");
1739 
1740  MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
1741  if (frame_aspect_ratio) {
1742  AVRational q;
1743  if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
1744  q.num <= 0 || q.den <= 0) {
1745  av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
1746  exit_program(1);
1747  }
1748  ost->frame_aspect_ratio = q;
1749  }
1750 
1751  MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1753 
1754  if (!ost->stream_copy) {
1755  const char *p = NULL;
1756  char *frame_size = NULL;
1757  char *frame_pix_fmt = NULL;
1758  char *intra_matrix = NULL, *inter_matrix = NULL;
1759  char *chroma_intra_matrix = NULL;
1760  int do_pass = 0;
1761  int i;
1762 
1764  if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
1765  av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1766  exit_program(1);
1767  }
1768 
1770  MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
1771  if (frame_pix_fmt && *frame_pix_fmt == '+') {
1772  ost->keep_pix_fmt = 1;
1773  if (!*++frame_pix_fmt)
1774  frame_pix_fmt = NULL;
1775  }
1776  if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
1777  av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
1778  exit_program(1);
1779  }
1780  st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
1781 
1782  if (intra_only)
1783  video_enc->gop_size = 0;
1784  MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
1785  if (intra_matrix) {
1786  if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
1787  av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1788  exit_program(1);
1789  }
1790  parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
1791  }
1792  MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
1793  if (chroma_intra_matrix) {
1794  uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
1795  if (!p) {
1796  av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1797  exit_program(1);
1798  }
1799  video_enc->chroma_intra_matrix = p;
1800  parse_matrix_coeffs(p, chroma_intra_matrix);
1801  }
1802  MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
1803  if (inter_matrix) {
1804  if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
1805  av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
1806  exit_program(1);
1807  }
1808  parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
1809  }
1810 
1811  MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
1812  for (i = 0; p; i++) {
1813  int start, end, q;
1814  int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
1815  if (e != 3) {
1816  av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
1817  exit_program(1);
1818  }
1819  video_enc->rc_override =
1820  av_realloc_array(video_enc->rc_override,
1821  i + 1, sizeof(RcOverride));
1822  if (!video_enc->rc_override) {
1823  av_log(NULL, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
1824  exit_program(1);
1825  }
1826  video_enc->rc_override[i].start_frame = start;
1827  video_enc->rc_override[i].end_frame = end;
1828  if (q > 0) {
1829  video_enc->rc_override[i].qscale = q;
1830  video_enc->rc_override[i].quality_factor = 1.0;
1831  }
1832  else {
1833  video_enc->rc_override[i].qscale = 0;
1834  video_enc->rc_override[i].quality_factor = -q/100.0;
1835  }
1836  p = strchr(p, '/');
1837  if (p) p++;
1838  }
1839  video_enc->rc_override_count = i;
1840 
1841  if (do_psnr)
1842  video_enc->flags|= AV_CODEC_FLAG_PSNR;
1843 
1844  /* two pass mode */
1845  MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
1846  if (do_pass) {
1847  if (do_pass & 1) {
1848  video_enc->flags |= AV_CODEC_FLAG_PASS1;
1849  av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
1850  }
1851  if (do_pass & 2) {
1852  video_enc->flags |= AV_CODEC_FLAG_PASS2;
1853  av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
1854  }
1855  }
1856 
1857  MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
1858  if (ost->logfile_prefix &&
1860  exit_program(1);
1861 
1862  if (do_pass) {
1863  char logfilename[1024];
1864  FILE *f;
1865 
1866  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1869  i);
1870  if (!strcmp(ost->enc->name, "libx264")) {
1871  av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
1872  } else {
1873  if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
1874  char *logbuffer = read_file(logfilename);
1875 
1876  if (!logbuffer) {
1877  av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
1878  logfilename);
1879  exit_program(1);
1880  }
1881  video_enc->stats_in = logbuffer;
1882  }
1883  if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
1884  f = av_fopen_utf8(logfilename, "wb");
1885  if (!f) {
1887  "Cannot write log file '%s' for pass-1 encoding: %s\n",
1888  logfilename, strerror(errno));
1889  exit_program(1);
1890  }
1891  ost->logfile = f;
1892  }
1893  }
1894  }
1895 
1896  MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
1897  if (ost->forced_keyframes)
1899 
1900  MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
1901 
1902  ost->top_field_first = -1;
1903  MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
1904 
1905 
1906  ost->avfilter = get_ost_filters(o, oc, ost);
1907  if (!ost->avfilter)
1908  exit_program(1);
1909  } else {
1910  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
1911  }
1912 
1913  if (ost->stream_copy)
1915 
1916  return ost;
1917 }
1918 
1920 {
1921  int n;
1922  AVStream *st;
1923  OutputStream *ost;
1924  AVCodecContext *audio_enc;
1925 
1926  ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
1927  st = ost->st;
1928 
1929  audio_enc = ost->enc_ctx;
1930  audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
1931 
1932  MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1934 
1935  if (!ost->stream_copy) {
1936  char *sample_fmt = NULL;
1937 
1938  MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
1939 
1940  MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
1941  if (sample_fmt &&
1942  (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
1943  av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
1944  exit_program(1);
1945  }
1946 
1947  MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
1948 
1949  MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
1950  ost->apad = av_strdup(ost->apad);
1951 
1952  ost->avfilter = get_ost_filters(o, oc, ost);
1953  if (!ost->avfilter)
1954  exit_program(1);
1955 
1956  /* check for channel mapping for this audio stream */
1957  for (n = 0; n < o->nb_audio_channel_maps; n++) {
1959  if ((map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
1960  (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
1961  InputStream *ist;
1962 
1963  if (map->channel_idx == -1) {
1964  ist = NULL;
1965  } else if (ost->source_index < 0) {
1966  av_log(NULL, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
1967  ost->file_index, ost->st->index);
1968  continue;
1969  } else {
1971  }
1972 
1973  if (!ist || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) {
1976  sizeof(*ost->audio_channels_map)
1977  ) < 0 )
1978  exit_program(1);
1979 
1980  ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
1981  }
1982  }
1983  }
1984  }
1985 
1986  if (ost->stream_copy)
1988 
1989  return ost;
1990 }
1991 
1993 {
1994  OutputStream *ost;
1995 
1996  ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
1997  if (!ost->stream_copy) {
1998  av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
1999  exit_program(1);
2000  }
2001 
2002  return ost;
2003 }
2004 
2006 {
2007  OutputStream *ost;
2008 
2009  ost = new_output_stream(o, oc, AVMEDIA_TYPE_UNKNOWN, source_index);
2010  if (!ost->stream_copy) {
2011  av_log(NULL, AV_LOG_FATAL, "Unknown stream encoding not supported yet (only streamcopy)\n");
2012  exit_program(1);
2013  }
2014 
2015  return ost;
2016 }
2017 
2019 {
2020  OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
2021  ost->stream_copy = 1;
2022  ost->finished = 1;
2023  return ost;
2024 }
2025 
2027 {
2028  AVStream *st;
2029  OutputStream *ost;
2030  AVCodecContext *subtitle_enc;
2031 
2032  ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
2033  st = ost->st;
2034  subtitle_enc = ost->enc_ctx;
2035 
2036  subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2037 
2038  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
2039 
2040  if (!ost->stream_copy) {
2041  char *frame_size = NULL;
2042 
2044  if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
2045  av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
2046  exit_program(1);
2047  }
2048  }
2049 
2050  return ost;
2051 }
2052 
2053 /* arg format is "output-stream-index:streamid-value". */
2054 static int opt_streamid(void *optctx, const char *opt, const char *arg)
2055 {
2056  OptionsContext *o = optctx;
2057  int idx;
2058  char *p;
2059  char idx_str[16];
2060 
2061  av_strlcpy(idx_str, arg, sizeof(idx_str));
2062  p = strchr(idx_str, ':');
2063  if (!p) {
2065  "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
2066  arg, opt);
2067  exit_program(1);
2068  }
2069  *p++ = '\0';
2070  idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
2071  o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
2072  o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
2073  return 0;
2074 }
2075 
2077 {
2078  AVFormatContext *is = ifile->ctx;
2079  AVFormatContext *os = ofile->ctx;
2080  AVChapter **tmp;
2081  int i;
2082 
2083  tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
2084  if (!tmp)
2085  return AVERROR(ENOMEM);
2086  os->chapters = tmp;
2087 
2088  for (i = 0; i < is->nb_chapters; i++) {
2089  AVChapter *in_ch = is->chapters[i], *out_ch;
2090  int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
2091  int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
2092  AV_TIME_BASE_Q, in_ch->time_base);
2093  int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
2094  av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
2095 
2096 
2097  if (in_ch->end < ts_off)
2098  continue;
2099  if (rt != INT64_MAX && in_ch->start > rt + ts_off)
2100  break;
2101 
2102  out_ch = av_mallocz(sizeof(AVChapter));
2103  if (!out_ch)
2104  return AVERROR(ENOMEM);
2105 
2106  out_ch->id = in_ch->id;
2107  out_ch->time_base = in_ch->time_base;
2108  out_ch->start = FFMAX(0, in_ch->start - ts_off);
2109  out_ch->end = FFMIN(rt, in_ch->end - ts_off);
2110 
2111  if (copy_metadata)
2112  av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
2113 
2114  os->chapters[os->nb_chapters++] = out_ch;
2115  }
2116  return 0;
2117 }
2118 
2120  AVFormatContext *oc)
2121 {
2122  OutputStream *ost;
2123 
2124  switch (ofilter->type) {
2125  case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
2126  case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
2127  default:
2128  av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
2129  "currently.\n");
2130  exit_program(1);
2131  }
2132 
2133  ost->source_index = -1;
2134  ost->filter = ofilter;
2135 
2136  ofilter->ost = ost;
2137  ofilter->format = -1;
2138 
2139  if (ost->stream_copy) {
2140  av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
2141  "which is fed from a complex filtergraph. Filtering and streamcopy "
2142  "cannot be used together.\n", ost->file_index, ost->index);
2143  exit_program(1);
2144  }
2145 
2146  if (ost->avfilter && (ost->filters || ost->filters_script)) {
2147  const char *opt = ost->filters ? "-vf/-af/-filter" : "-filter_script";
2149  "%s '%s' was specified through the %s option "
2150  "for output stream %d:%d, which is fed from a complex filtergraph.\n"
2151  "%s and -filter_complex cannot be used together for the same stream.\n",
2152  ost->filters ? "Filtergraph" : "Filtergraph script",
2154  opt, ost->file_index, ost->index, opt);
2155  exit_program(1);
2156  }
2157 
2158  avfilter_inout_free(&ofilter->out_tmp);
2159 }
2160 
2161 static int init_complex_filters(void)
2162 {
2163  int i, ret = 0;
2164 
2165  for (i = 0; i < nb_filtergraphs; i++) {
2167  if (ret < 0)
2168  return ret;
2169  }
2170  return 0;
2171 }
2172 
2173 static int open_output_file(OptionsContext *o, const char *filename)
2174 {
2175  AVFormatContext *oc;
2176  int i, j, err;
2177  OutputFile *of;
2178  OutputStream *ost;
2179  InputStream *ist;
2180  AVDictionary *unused_opts = NULL;
2181  AVDictionaryEntry *e = NULL;
2182  int format_flags = 0;
2183 
2184  if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
2185  o->stop_time = INT64_MAX;
2186  av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
2187  }
2188 
2189  if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
2190  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
2191  if (o->stop_time <= start_time) {
2192  av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
2193  exit_program(1);
2194  } else {
2196  }
2197  }
2198 
2200  of = av_mallocz(sizeof(*of));
2201  if (!of)
2202  exit_program(1);
2203  output_files[nb_output_files - 1] = of;
2204 
2206  of->recording_time = o->recording_time;
2207  of->start_time = o->start_time;
2208  of->limit_filesize = o->limit_filesize;
2209  of->shortest = o->shortest;
2210  av_dict_copy(&of->opts, o->g->format_opts, 0);
2211 
2212  if (!strcmp(filename, "-"))
2213  filename = "pipe:";
2214 
2215  err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
2216  if (!oc) {
2217  print_error(filename, err);
2218  exit_program(1);
2219  }
2220 
2221  of->ctx = oc;
2222  if (o->recording_time != INT64_MAX)
2223  oc->duration = o->recording_time;
2224 
2225  oc->interrupt_callback = int_cb;
2226 
2227  e = av_dict_get(o->g->format_opts, "fflags", NULL, 0);
2228  if (e) {
2229  const AVOption *o = av_opt_find(oc, "fflags", NULL, 0, 0);
2230  av_opt_eval_flags(oc, o, e->value, &format_flags);
2231  }
2232  if (o->bitexact) {
2233  format_flags |= AVFMT_FLAG_BITEXACT;
2234  oc->flags |= AVFMT_FLAG_BITEXACT;
2235  }
2236 
2237  /* create streams for all unlabeled output pads */
2238  for (i = 0; i < nb_filtergraphs; i++) {
2239  FilterGraph *fg = filtergraphs[i];
2240  for (j = 0; j < fg->nb_outputs; j++) {
2241  OutputFilter *ofilter = fg->outputs[j];
2242 
2243  if (!ofilter->out_tmp || ofilter->out_tmp->name)
2244  continue;
2245 
2246  switch (ofilter->type) {
2247  case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
2248  case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
2249  case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
2250  }
2251  init_output_filter(ofilter, o, oc);
2252  }
2253  }
2254 
2255  if (!o->nb_stream_maps) {
2256  char *subtitle_codec_name = NULL;
2257  /* pick the "best" stream of each type */
2258 
2259  /* video: highest resolution */
2261  int best_score = 0, idx = -1;
2262  int qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
2263  for (j = 0; j < nb_input_files; j++) {
2264  InputFile *ifile = input_files[j];
2265  int file_best_score = 0, file_best_idx = -1;
2266  for (i = 0; i < ifile->nb_streams; i++) {
2267  int score;
2268  ist = input_streams[ifile->ist_index + i];
2269  score = ist->st->codecpar->width * ist->st->codecpar->height
2270  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2271  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2272  if (ist->user_set_discard == AVDISCARD_ALL)
2273  continue;
2274  if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2275  score = 1;
2276  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2277  score > file_best_score) {
2278  if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2279  continue;
2280  file_best_score = score;
2281  file_best_idx = ifile->ist_index + i;
2282  }
2283  }
2284  if (file_best_idx >= 0) {
2285  if((qcr == MKTAG('A', 'P', 'I', 'C')) || !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2286  file_best_score -= 5000000*!!(input_streams[file_best_idx]->st->disposition & AV_DISPOSITION_DEFAULT);
2287  if (file_best_score > best_score) {
2288  best_score = file_best_score;
2289  idx = file_best_idx;
2290  }
2291  }
2292  }
2293  if (idx >= 0)
2294  new_video_stream(o, oc, idx);
2295  }
2296 
2297  /* audio: most channels */
2299  int best_score = 0, idx = -1;
2300  for (j = 0; j < nb_input_files; j++) {
2301  InputFile *ifile = input_files[j];
2302  int file_best_score = 0, file_best_idx = -1;
2303  for (i = 0; i < ifile->nb_streams; i++) {
2304  int score;
2305  ist = input_streams[ifile->ist_index + i];
2306  score = ist->st->codecpar->channels
2307  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2308  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2309  if (ist->user_set_discard == AVDISCARD_ALL)
2310  continue;
2311  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2312  score > file_best_score) {
2313  file_best_score = score;
2314  file_best_idx = ifile->ist_index + i;
2315  }
2316  }
2317  if (file_best_idx >= 0) {
2318  file_best_score -= 5000000*!!(input_streams[file_best_idx]->st->disposition & AV_DISPOSITION_DEFAULT);
2319  if (file_best_score > best_score) {
2320  best_score = file_best_score;
2321  idx = file_best_idx;
2322  }
2323  }
2324  }
2325  if (idx >= 0)
2326  new_audio_stream(o, oc, idx);
2327  }
2328 
2329  /* subtitles: pick first */
2330  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
2332  for (i = 0; i < nb_input_streams; i++)
2333  if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2334  AVCodecDescriptor const *input_descriptor =
2335  avcodec_descriptor_get(input_streams[i]->st->codecpar->codec_id);
2336  AVCodecDescriptor const *output_descriptor = NULL;
2337  AVCodec const *output_codec =
2339  int input_props = 0, output_props = 0;
2340  if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2341  continue;
2342  if (output_codec)
2343  output_descriptor = avcodec_descriptor_get(output_codec->id);
2344  if (input_descriptor)
2345  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2346  if (output_descriptor)
2347  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2348  if (subtitle_codec_name ||
2349  input_props & output_props ||
2350  // Map dvb teletext which has neither property to any output subtitle encoder
2351  input_descriptor && output_descriptor &&
2352  (!input_descriptor->props ||
2353  !output_descriptor->props)) {
2354  new_subtitle_stream(o, oc, i);
2355  break;
2356  }
2357  }
2358  }
2359  /* Data only if codec id match */
2360  if (!o->data_disable ) {
2362  for (i = 0; codec_id != AV_CODEC_ID_NONE && i < nb_input_streams; i++) {
2363  if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2364  continue;
2365  if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_DATA
2367  new_data_stream(o, oc, i);
2368  }
2369  }
2370  } else {
2371  for (i = 0; i < o->nb_stream_maps; i++) {
2372  StreamMap *map = &o->stream_maps[i];
2373 
2374  if (map->disabled)
2375  continue;
2376 
2377  if (map->linklabel) {
2378  FilterGraph *fg;
2379  OutputFilter *ofilter = NULL;
2380  int j, k;
2381 
2382  for (j = 0; j < nb_filtergraphs; j++) {
2383  fg = filtergraphs[j];
2384  for (k = 0; k < fg->nb_outputs; k++) {
2385  AVFilterInOut *out = fg->outputs[k]->out_tmp;
2386  if (out && !strcmp(out->name, map->linklabel)) {
2387  ofilter = fg->outputs[k];
2388  goto loop_end;
2389  }
2390  }
2391  }
2392 loop_end:
2393  if (!ofilter) {
2394  av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
2395  "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
2396  exit_program(1);
2397  }
2398  init_output_filter(ofilter, o, oc);
2399  } else {
2400  int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
2401 
2402  ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
2403  if (ist->user_set_discard == AVDISCARD_ALL) {
2404  av_log(NULL, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
2405  map->file_index, map->stream_index);
2406  exit_program(1);
2407  }
2408  if(o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
2409  continue;
2410  if(o-> audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2411  continue;
2412  if(o-> video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2413  continue;
2414  if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2415  continue;
2416 
2417  ost = NULL;
2418  switch (ist->st->codecpar->codec_type) {
2419  case AVMEDIA_TYPE_VIDEO: ost = new_video_stream (o, oc, src_idx); break;
2420  case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream (o, oc, src_idx); break;
2421  case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream (o, oc, src_idx); break;
2422  case AVMEDIA_TYPE_DATA: ost = new_data_stream (o, oc, src_idx); break;
2423  case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
2424  case AVMEDIA_TYPE_UNKNOWN:
2425  if (copy_unknown_streams) {
2426  ost = new_unknown_stream (o, oc, src_idx);
2427  break;
2428  }
2429  default:
2431  "Cannot map stream #%d:%d - unsupported type.\n",
2432  map->file_index, map->stream_index);
2433  if (!ignore_unknown_streams) {
2435  "If you want unsupported types ignored instead "
2436  "of failing, please use the -ignore_unknown option\n"
2437  "If you want them copied, please use -copy_unknown\n");
2438  exit_program(1);
2439  }
2440  }
2441  if (ost)
2442  ost->sync_ist = input_streams[ input_files[map->sync_file_index]->ist_index
2443  + map->sync_stream_index];
2444  }
2445  }
2446  }
2447 
2448  /* handle attached files */
2449  for (i = 0; i < o->nb_attachments; i++) {
2450  AVIOContext *pb;
2451  uint8_t *attachment;
2452  const char *p;
2453  int64_t len;
2454 
2455  if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
2456  av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
2457  o->attachments[i]);
2458  exit_program(1);
2459  }
2460  if ((len = avio_size(pb)) <= 0) {
2461  av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
2462  o->attachments[i]);
2463  exit_program(1);
2464  }
2465  if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ||
2466  !(attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE))) {
2467  av_log(NULL, AV_LOG_FATAL, "Attachment %s too large.\n",
2468  o->attachments[i]);
2469  exit_program(1);
2470  }
2471  avio_read(pb, attachment, len);
2472  memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2473 
2474  ost = new_attachment_stream(o, oc, -1);
2475  ost->stream_copy = 0;
2477  ost->st->codecpar->extradata = attachment;
2479 
2480  p = strrchr(o->attachments[i], '/');
2481  av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
2482  avio_closep(&pb);
2483  }
2484 
2485  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2486  av_dump_format(oc, nb_output_files - 1, oc->url, 1);
2487  av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", nb_output_files - 1);
2488  exit_program(1);
2489  }
2490 
2491  /* check if all codec options have been used */
2492  unused_opts = strip_specifiers(o->g->codec_opts);
2493  for (i = of->ost_index; i < nb_output_streams; i++) {
2494  e = NULL;
2495  while ((e = av_dict_get(output_streams[i]->encoder_opts, "", e,
2497  av_dict_set(&unused_opts, e->key, NULL, 0);
2498  }
2499 
2500  e = NULL;
2501  while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
2502  const AVClass *class = avcodec_get_class();
2503  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
2505  const AVClass *fclass = avformat_get_class();
2506  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
2508  if (!option || foption)
2509  continue;
2510 
2511 
2512  if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
2513  av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
2514  "output file #%d (%s) is not an encoding option.\n", e->key,
2515  option->help ? option->help : "", nb_output_files - 1,
2516  filename);
2517  exit_program(1);
2518  }
2519 
2520  // gop_timecode is injected by generic code but not always used
2521  if (!strcmp(e->key, "gop_timecode"))
2522  continue;
2523 
2524  av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
2525  "output file #%d (%s) has not been used for any stream. The most "
2526  "likely reason is either wrong type (e.g. a video option with "
2527  "no video streams) or that it is a private option of some encoder "
2528  "which was not actually used for any stream.\n", e->key,
2529  option->help ? option->help : "", nb_output_files - 1, filename);
2530  }
2531  av_dict_free(&unused_opts);
2532 
2533  /* set the decoding_needed flags and create simple filtergraphs */
2534  for (i = of->ost_index; i < nb_output_streams; i++) {
2536 
2537  if (ost->encoding_needed && ost->source_index >= 0) {
2539  ist->decoding_needed |= DECODING_FOR_OST;
2540 
2544  if (err < 0) {
2546  "Error initializing a simple filtergraph between streams "
2547  "%d:%d->%d:%d\n", ist->file_index, ost->source_index,
2548  nb_output_files - 1, ost->st->index);
2549  exit_program(1);
2550  }
2551  }
2552  }
2553 
2554  /* set the filter output constraints */
2555  if (ost->filter) {
2556  OutputFilter *f = ost->filter;
2557  int count;
2558  switch (ost->enc_ctx->codec_type) {
2559  case AVMEDIA_TYPE_VIDEO:
2560  f->frame_rate = ost->frame_rate;
2561  f->width = ost->enc_ctx->width;
2562  f->height = ost->enc_ctx->height;
2563  if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
2564  f->format = ost->enc_ctx->pix_fmt;
2565  } else if (ost->enc->pix_fmts) {
2566  count = 0;
2567  while (ost->enc->pix_fmts[count] != AV_PIX_FMT_NONE)
2568  count++;
2569  f->formats = av_mallocz_array(count + 1, sizeof(*f->formats));
2570  if (!f->formats)
2571  exit_program(1);
2572  memcpy(f->formats, ost->enc->pix_fmts, (count + 1) * sizeof(*f->formats));
2573  }
2574  break;
2575  case AVMEDIA_TYPE_AUDIO:
2577  f->format = ost->enc_ctx->sample_fmt;
2578  } else if (ost->enc->sample_fmts) {
2579  count = 0;
2580  while (ost->enc->sample_fmts[count] != AV_SAMPLE_FMT_NONE)
2581  count++;
2582  f->formats = av_mallocz_array(count + 1, sizeof(*f->formats));
2583  if (!f->formats)
2584  exit_program(1);
2585  memcpy(f->formats, ost->enc->sample_fmts, (count + 1) * sizeof(*f->formats));
2586  }
2587  if (ost->enc_ctx->sample_rate) {
2588  f->sample_rate = ost->enc_ctx->sample_rate;
2589  } else if (ost->enc->supported_samplerates) {
2590  count = 0;
2591  while (ost->enc->supported_samplerates[count])
2592  count++;
2593  f->sample_rates = av_mallocz_array(count + 1, sizeof(*f->sample_rates));
2594  if (!f->sample_rates)
2595  exit_program(1);
2596  memcpy(f->sample_rates, ost->enc->supported_samplerates,
2597  (count + 1) * sizeof(*f->sample_rates));
2598  }
2599  if (ost->enc_ctx->channels) {
2600  f->channel_layout = av_get_default_channel_layout(ost->enc_ctx->channels);
2601  } else if (ost->enc->channel_layouts) {
2602  count = 0;
2603  while (ost->enc->channel_layouts[count])
2604  count++;
2605  f->channel_layouts = av_mallocz_array(count + 1, sizeof(*f->channel_layouts));
2606  if (!f->channel_layouts)
2607  exit_program(1);
2608  memcpy(f->channel_layouts, ost->enc->channel_layouts,
2609  (count + 1) * sizeof(*f->channel_layouts));
2610  }
2611  break;
2612  }
2613  }
2614  }
2615 
2616  /* check filename in case of an image number is expected */
2617  if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2618  if (!av_filename_number_test(oc->url)) {
2619  print_error(oc->url, AVERROR(EINVAL));
2620  exit_program(1);
2621  }
2622  }
2623 
2626  "No input streams but output needs an input stream\n");
2627  exit_program(1);
2628  }
2629 
2630  if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2631  /* test if it already exists to avoid losing precious files */
2632  assert_file_overwrite(filename);
2633 
2634  /* open the file */
2635  if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
2636  &oc->interrupt_callback,
2637  &of->opts)) < 0) {
2638  print_error(filename, err);
2639  exit_program(1);
2640  }
2641  } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
2642  assert_file_overwrite(filename);
2643 
2644  if (o->mux_preload) {
2645  av_dict_set_int(&of->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
2646  }
2647  oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
2648 
2649  /* copy metadata */
2650  for (i = 0; i < o->nb_metadata_map; i++) {
2651  char *p;
2652  int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
2653 
2654  if (in_file_index >= nb_input_files) {
2655  av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
2656  exit_program(1);
2657  }
2658  copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,
2659  in_file_index >= 0 ?
2660  input_files[in_file_index]->ctx : NULL, o);
2661  }
2662 
2663  /* copy chapters */
2664  if (o->chapters_input_file >= nb_input_files) {
2665  if (o->chapters_input_file == INT_MAX) {
2666  /* copy chapters from the first input file that has them*/
2667  o->chapters_input_file = -1;
2668  for (i = 0; i < nb_input_files; i++)
2669  if (input_files[i]->ctx->nb_chapters) {
2670  o->chapters_input_file = i;
2671  break;
2672  }
2673  } else {
2674  av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
2675  o->chapters_input_file);
2676  exit_program(1);
2677  }
2678  }
2679  if (o->chapters_input_file >= 0)
2682 
2683  /* copy global metadata by default */
2687  if(o->recording_time != INT64_MAX)
2688  av_dict_set(&oc->metadata, "duration", NULL, 0);
2689  av_dict_set(&oc->metadata, "creation_time", NULL, 0);
2690  av_dict_set(&oc->metadata, "company_name", NULL, 0);
2691  av_dict_set(&oc->metadata, "product_name", NULL, 0);
2692  av_dict_set(&oc->metadata, "product_version", NULL, 0);
2693  }
2694  if (!o->metadata_streams_manual)
2695  for (i = of->ost_index; i < nb_output_streams; i++) {
2696  InputStream *ist;
2697  if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
2698  continue;
2701  if (!output_streams[i]->stream_copy) {
2702  av_dict_set(&output_streams[i]->st->metadata, "encoder", NULL, 0);
2703  }
2704  }
2705 
2706  /* process manually set programs */
2707  for (i = 0; i < o->nb_program; i++) {
2708  const char *p = o->program[i].u.str;
2709  int progid = i+1;
2710  AVProgram *program;
2711 
2712  while(*p) {
2713  const char *p2 = av_get_token(&p, ":");
2714  const char *to_dealloc = p2;
2715  char *key;
2716  if (!p2)
2717  break;
2718 
2719  if(*p) p++;
2720 
2721  key = av_get_token(&p2, "=");
2722  if (!key || !*p2) {
2723  av_freep(&to_dealloc);
2724  av_freep(&key);
2725  break;
2726  }
2727  p2++;
2728 
2729  if (!strcmp(key, "program_num"))
2730  progid = strtol(p2, NULL, 0);
2731  av_freep(&to_dealloc);
2732  av_freep(&key);
2733  }
2734 
2735  program = av_new_program(oc, progid);
2736 
2737  p = o->program[i].u.str;
2738  while(*p) {
2739  const char *p2 = av_get_token(&p, ":");
2740  const char *to_dealloc = p2;
2741  char *key;
2742  if (!p2)
2743  break;
2744  if(*p) p++;
2745 
2746  key = av_get_token(&p2, "=");
2747  if (!key) {
2749  "No '=' character in program string %s.\n",
2750  p2);
2751  exit_program(1);
2752  }
2753  if (!*p2)
2754  exit_program(1);
2755  p2++;
2756 
2757  if (!strcmp(key, "title")) {
2758  av_dict_set(&program->metadata, "title", p2, 0);
2759  } else if (!strcmp(key, "program_num")) {
2760  } else if (!strcmp(key, "st")) {
2761  int st_num = strtol(p2, NULL, 0);
2762  av_program_add_stream_index(oc, progid, st_num);
2763  } else {
2764  av_log(NULL, AV_LOG_FATAL, "Unknown program key %s.\n", key);
2765  exit_program(1);
2766  }
2767  av_freep(&to_dealloc);
2768  av_freep(&key);
2769  }
2770  }
2771 
2772  /* process manually set metadata */
2773  for (i = 0; i < o->nb_metadata; i++) {
2774  AVDictionary **m;
2775  char type, *val;
2776  const char *stream_spec;
2777  int index = 0, j, ret = 0;
2778 
2779  val = strchr(o->metadata[i].u.str, '=');
2780  if (!val) {
2781  av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
2782  o->metadata[i].u.str);
2783  exit_program(1);
2784  }
2785  *val++ = 0;
2786 
2787  parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
2788  if (type == 's') {
2789  for (j = 0; j < oc->nb_streams; j++) {
2791  if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
2792  if (!strcmp(o->metadata[i].u.str, "rotate")) {
2793  char *tail;
2794  double theta = av_strtod(val, &tail);
2795  if (!*tail) {
2796  ost->rotate_overridden = 1;
2797  ost->rotate_override_value = theta;
2798  }
2799  } else {
2800  av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
2801  }
2802  } else if (ret < 0)
2803  exit_program(1);
2804  }
2805  }
2806  else {
2807  switch (type) {
2808  case 'g':
2809  m = &oc->metadata;
2810  break;
2811  case 'c':
2812  if (index < 0 || index >= oc->nb_chapters) {
2813  av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
2814  exit_program(1);
2815  }
2816  m = &oc->chapters[index]->metadata;
2817  break;
2818  case 'p':
2819  if (index < 0 || index >= oc->nb_programs) {
2820  av_log(NULL, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
2821  exit_program(1);
2822  }
2823  m = &oc->programs[index]->metadata;
2824  break;
2825  default:
2826  av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
2827  exit_program(1);
2828  }
2829  av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
2830  }
2831  }
2832 
2833  return 0;
2834 }
2835 
2836 static int opt_target(void *optctx, const char *opt, const char *arg)
2837 {
2838  OptionsContext *o = optctx;
2839  enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
2840  static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
2841 
2842  if (!strncmp(arg, "pal-", 4)) {
2843  norm = PAL;
2844  arg += 4;
2845  } else if (!strncmp(arg, "ntsc-", 5)) {
2846  norm = NTSC;
2847  arg += 5;
2848  } else if (!strncmp(arg, "film-", 5)) {
2849  norm = FILM;
2850  arg += 5;
2851  } else {
2852  /* Try to determine PAL/NTSC by peeking in the input files */
2853  if (nb_input_files) {
2854  int i, j;
2855  for (j = 0; j < nb_input_files; j++) {
2856  for (i = 0; i < input_files[j]->nb_streams; i++) {
2857  AVStream *st = input_files[j]->ctx->streams[i];
2858  int64_t fr;
2860  continue;
2861  fr = st->time_base.den * 1000LL / st->time_base.num;
2862  if (fr == 25000) {
2863  norm = PAL;
2864  break;
2865  } else if ((fr == 29970) || (fr == 23976)) {
2866  norm = NTSC;
2867  break;
2868  }
2869  }
2870  if (norm != UNKNOWN)
2871  break;
2872  }
2873  }
2874  if (norm != UNKNOWN)
2875  av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
2876  }
2877 
2878  if (norm == UNKNOWN) {
2879  av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
2880  av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
2881  av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
2882  exit_program(1);
2883  }
2884 
2885  if (!strcmp(arg, "vcd")) {
2886  opt_video_codec(o, "c:v", "mpeg1video");
2887  opt_audio_codec(o, "c:a", "mp2");
2888  parse_option(o, "f", "vcd", options);
2889 
2890  parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
2891  parse_option(o, "r", frame_rates[norm], options);
2892  opt_default(NULL, "g", norm == PAL ? "15" : "18");
2893 
2894  opt_default(NULL, "b:v", "1150000");
2895  opt_default(NULL, "maxrate:v", "1150000");
2896  opt_default(NULL, "minrate:v", "1150000");
2897  opt_default(NULL, "bufsize:v", "327680"); // 40*1024*8;
2898 
2899  opt_default(NULL, "b:a", "224000");
2900  parse_option(o, "ar", "44100", options);
2901  parse_option(o, "ac", "2", options);
2902 
2903  opt_default(NULL, "packetsize", "2324");
2904  opt_default(NULL, "muxrate", "1411200"); // 2352 * 75 * 8;
2905 
2906  /* We have to offset the PTS, so that it is consistent with the SCR.
2907  SCR starts at 36000, but the first two packs contain only padding
2908  and the first pack from the other stream, respectively, may also have
2909  been written before.
2910  So the real data starts at SCR 36000+3*1200. */
2911  o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
2912  } else if (!strcmp(arg, "svcd")) {
2913 
2914  opt_video_codec(o, "c:v", "mpeg2video");
2915  opt_audio_codec(o, "c:a", "mp2");
2916  parse_option(o, "f", "svcd", options);
2917 
2918  parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
2919  parse_option(o, "r", frame_rates[norm], options);
2920  parse_option(o, "pix_fmt", "yuv420p", options);
2921  opt_default(NULL, "g", norm == PAL ? "15" : "18");
2922 
2923  opt_default(NULL, "b:v", "2040000");
2924  opt_default(NULL, "maxrate:v", "2516000");
2925  opt_default(NULL, "minrate:v", "0"); // 1145000;
2926  opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
2927  opt_default(NULL, "scan_offset", "1");
2928 
2929  opt_default(NULL, "b:a", "224000");
2930  parse_option(o, "ar", "44100", options);
2931 
2932  opt_default(NULL, "packetsize", "2324");
2933 
2934  } else if (!strcmp(arg, "dvd")) {
2935 
2936  opt_video_codec(o, "c:v", "mpeg2video");
2937  opt_audio_codec(o, "c:a", "ac3");
2938  parse_option(o, "f", "dvd", options);
2939 
2940  parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
2941  parse_option(o, "r", frame_rates[norm], options);
2942  parse_option(o, "pix_fmt", "yuv420p", options);
2943  opt_default(NULL, "g", norm == PAL ? "15" : "18");
2944 
2945  opt_default(NULL, "b:v", "6000000");
2946  opt_default(NULL, "maxrate:v", "9000000");
2947  opt_default(NULL, "minrate:v", "0"); // 1500000;
2948  opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
2949 
2950  opt_default(NULL, "packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
2951  opt_default(NULL, "muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
2952 
2953  opt_default(NULL, "b:a", "448000");
2954  parse_option(o, "ar", "48000", options);
2955 
2956  } else if (!strncmp(arg, "dv", 2)) {
2957 
2958  parse_option(o, "f", "dv", options);
2959 
2960  parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
2961  parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
2962  norm == PAL ? "yuv420p" : "yuv411p", options);
2963  parse_option(o, "r", frame_rates[norm], options);
2964 
2965  parse_option(o, "ar", "48000", options);
2966  parse_option(o, "ac", "2", options);
2967 
2968  } else {
2969  av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
2970  return AVERROR(EINVAL);
2971  }
2972 
2975 
2976  return 0;
2977 }
2978 
2979 static int opt_vstats_file(void *optctx, const char *opt, const char *arg)
2980 {
2983  return 0;
2984 }
2985 
2986 static int opt_vstats(void *optctx, const char *opt, const char *arg)
2987 {
2988  char filename[40];
2989  time_t today2 = time(NULL);
2990  struct tm *today = localtime(&today2);
2991 
2992  if (!today) { // maybe tomorrow
2993  av_log(NULL, AV_LOG_FATAL, "Unable to get current time: %s\n", strerror(errno));
2994  exit_program(1);
2995  }
2996 
2997  snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
2998  today->tm_sec);
2999  return opt_vstats_file(NULL, opt, filename);
3000 }
3001 
3002 static int opt_video_frames(void *optctx, const char *opt, const char *arg)
3003 {
3004  OptionsContext *o = optctx;
3005  return parse_option(o, "frames:v", arg, options);
3006 }
3007 
3008 static int opt_audio_frames(void *optctx, const char *opt, const char *arg)
3009 {
3010  OptionsContext *o = optctx;
3011  return parse_option(o, "frames:a", arg, options);
3012 }
3013 
3014 static int opt_data_frames(void *optctx, const char *opt, const char *arg)
3015 {
3016  OptionsContext *o = optctx;
3017  return parse_option(o, "frames:d", arg, options);
3018 }
3019 
3020 static int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
3021 {
3022  int ret;
3023  AVDictionary *cbak = codec_opts;
3024  AVDictionary *fbak = format_opts;
3025  codec_opts = NULL;
3026  format_opts = NULL;
3027 
3028  ret = opt_default(NULL, opt, arg);
3029 
3030  av_dict_copy(&o->g->codec_opts , codec_opts, 0);
3034  codec_opts = cbak;
3035  format_opts = fbak;
3036 
3037  return ret;
3038 }
3039 
3040 static int opt_preset(void *optctx, const char *opt, const char *arg)
3041 {
3042  OptionsContext *o = optctx;
3043  FILE *f=NULL;
3044  char filename[1000], line[1000], tmp_line[1000];
3045  const char *codec_name = NULL;
3046 
3047  tmp_line[0] = *opt;
3048  tmp_line[1] = 0;
3049  MATCH_PER_TYPE_OPT(codec_names, str, codec_name, NULL, tmp_line);
3050 
3051  if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
3052  if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
3053  av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
3054  }else
3055  av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
3056  exit_program(1);
3057  }
3058 
3059  while (fgets(line, sizeof(line), f)) {
3060  char *key = tmp_line, *value, *endptr;
3061 
3062  if (strcspn(line, "#\n\r") == 0)
3063  continue;
3064  av_strlcpy(tmp_line, line, sizeof(tmp_line));
3065  if (!av_strtok(key, "=", &value) ||
3066  !av_strtok(value, "\r\n", &endptr)) {
3067  av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
3068  exit_program(1);
3069  }
3070  av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
3071 
3072  if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
3073  else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
3074  else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
3075  else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
3076  else if (opt_default_new(o, key, value) < 0) {
3077  av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
3078  filename, line, key, value);
3079  exit_program(1);
3080  }
3081  }
3082 
3083  fclose(f);
3084 
3085  return 0;
3086 }
3087 
3088 static int opt_old2new(void *optctx, const char *opt, const char *arg)
3089 {
3090  OptionsContext *o = optctx;
3091  int ret;
3092  char *s = av_asprintf("%s:%c", opt + 1, *opt);
3093  if (!s)
3094  return AVERROR(ENOMEM);
3095  ret = parse_option(o, s, arg, options);
3096  av_free(s);
3097  return ret;
3098 }
3099 
3100 static int opt_bitrate(void *optctx, const char *opt, const char *arg)
3101 {
3102  OptionsContext *o = optctx;
3103 
3104  if(!strcmp(opt, "ab")){
3105  av_dict_set(&o->g->codec_opts, "b:a", arg, 0);
3106  return 0;
3107  } else if(!strcmp(opt, "b")){
3108  av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
3109  av_dict_set(&o->g->codec_opts, "b:v", arg, 0);
3110  return 0;
3111  }
3112  av_dict_set(&o->g->codec_opts, opt, arg, 0);
3113  return 0;
3114 }
3115 
3116 static int opt_qscale(void *optctx, const char *opt, const char *arg)
3117 {
3118  OptionsContext *o = optctx;
3119  char *s;
3120  int ret;
3121  if(!strcmp(opt, "qscale")){
3122  av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
3123  return parse_option(o, "q:v", arg, options);
3124  }
3125  s = av_asprintf("q%s", opt + 6);
3126  if (!s)
3127  return AVERROR(ENOMEM);
3128  ret = parse_option(o, s, arg, options);
3129  av_free(s);
3130  return ret;
3131 }
3132 
3133 static int opt_profile(void *optctx, const char *opt, const char *arg)
3134 {
3135  OptionsContext *o = optctx;
3136  if(!strcmp(opt, "profile")){
3137  av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
3138  av_dict_set(&o->g->codec_opts, "profile:v", arg, 0);
3139  return 0;
3140  }
3141  av_dict_set(&o->g->codec_opts, opt, arg, 0);
3142  return 0;
3143 }
3144 
3145 static int opt_video_filters(void *optctx, const char *opt, const char *arg)
3146 {
3147  OptionsContext *o = optctx;
3148  return parse_option(o, "filter:v", arg, options);
3149 }
3150 
3151 static int opt_audio_filters(void *optctx, const char *opt, const char *arg)
3152 {
3153  OptionsContext *o = optctx;
3154  return parse_option(o, "filter:a", arg, options);
3155 }
3156 
3157 static int opt_vsync(void *optctx, const char *opt, const char *arg)
3158 {
3159  if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
3160  else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
3161  else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
3162  else if (!av_strcasecmp(arg, "drop")) video_sync_method = VSYNC_DROP;
3163 
3166  return 0;
3167 }
3168 
3169 static int opt_timecode(void *optctx, const char *opt, const char *arg)
3170 {
3171  OptionsContext *o = optctx;
3172  int ret;
3173  char *tcr = av_asprintf("timecode=%s", arg);
3174  if (!tcr)
3175  return AVERROR(ENOMEM);
3176  ret = parse_option(o, "metadata:g", tcr, options);
3177  if (ret >= 0)
3178  ret = av_dict_set(&o->g->codec_opts, "gop_timecode", arg, 0);
3179  av_free(tcr);
3180  return ret;
3181 }
3182 
3183 static int opt_channel_layout(void *optctx, const char *opt, const char *arg)
3184 {
3185  OptionsContext *o = optctx;
3186  char layout_str[32];
3187  char *stream_str;
3188  char *ac_str;
3189  int ret, channels, ac_str_size;
3190  uint64_t layout;
3191 
3193  if (!layout) {
3194  av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
3195  return AVERROR(EINVAL);
3196  }
3197  snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
3198  ret = opt_default_new(o, opt, layout_str);
3199  if (ret < 0)
3200  return ret;
3201 
3202  /* set 'ac' option based on channel layout */
3204  snprintf(layout_str, sizeof(layout_str), "%d", channels);
3205  stream_str = strchr(opt, ':');
3206  ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
3207  ac_str = av_mallocz(ac_str_size);
3208  if (!ac_str)
3209  return AVERROR(ENOMEM);
3210  av_strlcpy(ac_str, "ac", 3);
3211  if (stream_str)
3212  av_strlcat(ac_str, stream_str, ac_str_size);
3213  ret = parse_option(o, ac_str, layout_str, options);
3214  av_free(ac_str);
3215 
3216  return ret;
3217 }
3218 
3219 static int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
3220 {
3221  OptionsContext *o = optctx;
3222  return parse_option(o, "q:a", arg, options);
3223 }
3224 
3225 static int opt_filter_complex(void *optctx, const char *opt, const char *arg)
3226 {
3228  if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
3229  return AVERROR(ENOMEM);
3232  if (!filtergraphs[nb_filtergraphs - 1]->graph_desc)
3233  return AVERROR(ENOMEM);
3234 
3236 
3237  return 0;
3238 }
3239 
3240 static int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
3241 {
3242  uint8_t *graph_desc = read_file(arg);
3243  if (!graph_desc)
3244  return AVERROR(EINVAL);
3245 
3247  if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
3248  return AVERROR(ENOMEM);
3250  filtergraphs[nb_filtergraphs - 1]->graph_desc = graph_desc;
3251 
3253 
3254  return 0;
3255 }
3256 
3257 void show_help_default(const char *opt, const char *arg)
3258 {
3259  /* per-file options have at least one of those set */
3260  const int per_file = OPT_SPEC | OPT_OFFSET | OPT_PERFILE;
3261  int show_advanced = 0, show_avoptions = 0;
3262 
3263  if (opt && *opt) {
3264  if (!strcmp(opt, "long"))
3265  show_advanced = 1;
3266  else if (!strcmp(opt, "full"))
3267  show_advanced = show_avoptions = 1;
3268  else
3269  av_log(NULL, AV_LOG_ERROR, "Unknown help option '%s'.\n", opt);
3270  }
3271 
3272  show_usage();
3273 
3274  printf("Getting help:\n"
3275  " -h -- print basic options\n"
3276  " -h long -- print more options\n"
3277  " -h full -- print all options (including all format and codec specific options, very long)\n"
3278  " -h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter/bsf/protocol\n"
3279  " See man %s for detailed description of the options.\n"
3280  "\n", program_name);
3281 
3282  show_help_options(options, "Print help / information / capabilities:",
3283  OPT_EXIT, 0, 0);
3284 
3285  show_help_options(options, "Global options (affect whole program "
3286  "instead of just one file):",
3287  0, per_file | OPT_EXIT | OPT_EXPERT, 0);
3288  if (show_advanced)
3289  show_help_options(options, "Advanced global options:", OPT_EXPERT,
3290  per_file | OPT_EXIT, 0);
3291 
3292  show_help_options(options, "Per-file main options:", 0,
3294  OPT_EXIT, per_file);
3295  if (show_advanced)
3296  show_help_options(options, "Advanced per-file options:",
3297  OPT_EXPERT, OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE, per_file);
3298 
3299  show_help_options(options, "Video options:",
3301  if (show_advanced)
3302  show_help_options(options, "Advanced Video options:",
3304 
3305  show_help_options(options, "Audio options:",
3307  if (show_advanced)
3308  show_help_options(options, "Advanced Audio options:",
3310  show_help_options(options, "Subtitle options:",
3311  OPT_SUBTITLE, 0, 0);
3312  printf("\n");
3313 
3314  if (show_avoptions) {
3318 #if CONFIG_SWSCALE
3320 #endif
3321 #if CONFIG_SWRESAMPLE
3323 #endif
3326  }
3327 }
3328 
3329 void show_usage(void)
3330 {
3331  av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
3332  av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
3333  av_log(NULL, AV_LOG_INFO, "\n");
3334 }
3335 
3336 enum OptGroup {
3337  GROUP_OUTFILE,
3338  GROUP_INFILE,
3339 };
3340 
3341 static const OptionGroupDef groups[] = {
3342  [GROUP_OUTFILE] = { "output url", NULL, OPT_OUTPUT },
3343  [GROUP_INFILE] = { "input url", "i", OPT_INPUT },
3344 };
3345 
3346 static int open_files(OptionGroupList *l, const char *inout,
3347  int (*open_file)(OptionsContext*, const char*))
3348 {
3349  int i, ret;
3350 
3351  for (i = 0; i < l->nb_groups; i++) {
3352  OptionGroup *g = &l->groups[i];
3353  OptionsContext o;
3354 
3355  init_options(&o);
3356  o.g = g;
3357 
3358  ret = parse_optgroup(&o, g);
3359  if (ret < 0) {
3360  av_log(NULL, AV_LOG_ERROR, "Error parsing options for %s file "
3361  "%s.\n", inout, g->arg);
3362  uninit_options(&o);
3363  return ret;
3364  }
3365 
3366  av_log(NULL, AV_LOG_DEBUG, "Opening an %s file: %s.\n", inout, g->arg);
3367  ret = open_file(&o, g->arg);
3368  uninit_options(&o);
3369  if (ret < 0) {
3370  av_log(NULL, AV_LOG_ERROR, "Error opening %s file %s.\n",
3371  inout, g->arg);
3372  return ret;
3373  }
3374  av_log(NULL, AV_LOG_DEBUG, "Successfully opened the file.\n");
3375  }
3376 
3377  return 0;
3378 }
3379 
3380 int ffmpeg_parse_options(int argc, char **argv)
3381 {
3382  OptionParseContext octx;
3383  uint8_t error[128];
3384  int ret;
3385 
3386  memset(&octx, 0, sizeof(octx));
3387 
3388  /* split the commandline into an internal representation */
3389  ret = split_commandline(&octx, argc, argv, options, groups,
3390  FF_ARRAY_ELEMS(groups));
3391  if (ret < 0) {
3392  av_log(NULL, AV_LOG_FATAL, "Error splitting the argument list: ");
3393  goto fail;
3394  }
3395 
3396  /* apply global options */
3397  ret = parse_optgroup(NULL, &octx.global_opts);
3398  if (ret < 0) {
3399  av_log(NULL, AV_LOG_FATAL, "Error parsing global options: ");
3400  goto fail;
3401  }
3402 
3403  /* configure terminal and setup signal handlers */
3404  term_init();
3405 
3406  /* open input files */
3407  ret = open_files(&octx.groups[GROUP_INFILE], "input", open_input_file);
3408  if (ret < 0) {
3409  av_log(NULL, AV_LOG_FATAL, "Error opening input files: ");
3410  goto fail;
3411  }
3412 
3413  /* create the complex filtergraphs */
3415  if (ret < 0) {
3416  av_log(NULL, AV_LOG_FATAL, "Error initializing complex filters.\n");
3417  goto fail;
3418  }
3419 
3420  /* open output files */
3421  ret = open_files(&octx.groups[GROUP_OUTFILE], "output", open_output_file);
3422  if (ret < 0) {
3423  av_log(NULL, AV_LOG_FATAL, "Error opening output files: ");
3424  goto fail;
3425  }
3426 
3428 
3429 fail:
3430  uninit_parse_context(&octx);
3431  if (ret < 0) {
3432  av_strerror(ret, error, sizeof(error));
3433  av_log(NULL, AV_LOG_FATAL, "%s\n", error);
3434  }
3435  return ret;
3436 }
3437 
3438 static int opt_progress(void *optctx, const char *opt, const char *arg)
3439 {
3440  AVIOContext *avio = NULL;
3441  int ret;
3442 
3443  if (!strcmp(arg, "-"))
3444  arg = "pipe:";
3445  ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
3446  if (ret < 0) {
3447  av_log(NULL, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
3448  arg, av_err2str(ret));
3449  return ret;
3450  }
3451  progress_avio = avio;
3452  return 0;
3453 }
3454 
3455 #define OFFSET(x) offsetof(OptionsContext, x)
3456 const OptionDef options[] = {
3457  /* main options */
3459  { "f", HAS_ARG | OPT_STRING | OPT_OFFSET |
3460  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(format) },
3461  "force format", "fmt" },
3462  { "y", OPT_BOOL, { &file_overwrite },
3463  "overwrite output files" },
3464  { "n", OPT_BOOL, { &no_file_overwrite },
3465  "never overwrite output files" },
3466  { "ignore_unknown", OPT_BOOL, { &ignore_unknown_streams },
3467  "Ignore unknown stream types" },
3468  { "copy_unknown", OPT_BOOL | OPT_EXPERT, { &copy_unknown_streams },
3469  "Copy unknown stream types" },
3470  { "recast_media", OPT_BOOL | OPT_EXPERT, { &recast_media },
3471  "allow recasting stream type in order to force a decoder of different media type" },
3472  { "c", HAS_ARG | OPT_STRING | OPT_SPEC |
3473  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(codec_names) },
3474  "codec name", "codec" },
3475  { "codec", HAS_ARG | OPT_STRING | OPT_SPEC |
3476  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(codec_names) },
3477  "codec name", "codec" },
3478  { "pre", HAS_ARG | OPT_STRING | OPT_SPEC |
3479  OPT_OUTPUT, { .off = OFFSET(presets) },
3480  "preset name", "preset" },
3481  { "map", HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3482  OPT_OUTPUT, { .func_arg = opt_map },
3483  "set input stream mapping",
3484  "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
3485  { "map_channel", HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_map_channel },
3486  "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
3487  { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC |
3488  OPT_OUTPUT, { .off = OFFSET(metadata_map) },
3489  "set metadata information of outfile from infile",
3490  "outfile[,metadata]:infile[,metadata]" },
3491  { "map_chapters", HAS_ARG | OPT_INT | OPT_EXPERT | OPT_OFFSET |
3492  OPT_OUTPUT, { .off = OFFSET(chapters_input_file) },
3493  "set chapters mapping", "input_file_index" },
3494  { "t", HAS_ARG | OPT_TIME | OPT_OFFSET |
3495  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(recording_time) },
3496  "record or transcode \"duration\" seconds of audio/video",
3497  "duration" },
3498  { "to", HAS_ARG | OPT_TIME | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(stop_time) },
3499  "record or transcode stop time", "time_stop" },
3500  { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(limit_filesize) },
3501  "set the limit file size in bytes", "limit_size" },
3502  { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET |
3503  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(start_time) },
3504  "set the start time offset", "time_off" },
3505  { "sseof", HAS_ARG | OPT_TIME | OPT_OFFSET |
3506  OPT_INPUT, { .off = OFFSET(start_time_eof) },
3507  "set the start time offset relative to EOF", "time_off" },
3508  { "seek_timestamp", HAS_ARG | OPT_INT | OPT_OFFSET |
3509  OPT_INPUT, { .off = OFFSET(seek_timestamp) },
3510  "enable/disable seeking by timestamp with -ss" },
3511  { "accurate_seek", OPT_BOOL | OPT_OFFSET | OPT_EXPERT |
3512  OPT_INPUT, { .off = OFFSET(accurate_seek) },
3513  "enable/disable accurate seeking with -ss" },
3514  { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET |
3515  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(input_ts_offset) },
3516  "set the input ts offset", "time_off" },
3517  { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC |
3518  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(ts_scale) },
3519  "set the input ts scale", "scale" },
3520  { "timestamp", HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_recording_timestamp },
3521  "set the recording timestamp ('now' to set the current time)", "time" },
3522  { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(metadata) },
3523  "add metadata", "string=string" },
3524  { "program", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(program) },
3525  "add program with specified streams", "title=string:st=number..." },
3526  { "dframes", HAS_ARG | OPT_PERFILE | OPT_EXPERT |
3527  OPT_OUTPUT, { .func_arg = opt_data_frames },
3528  "set the number of data frames to output", "number" },
3529  { "benchmark", OPT_BOOL | OPT_EXPERT, { &do_benchmark },
3530  "add timings for benchmarking" },
3531  { "benchmark_all", OPT_BOOL | OPT_EXPERT, { &do_benchmark_all },
3532  "add timings for each task" },
3533  { "progress", HAS_ARG | OPT_EXPERT, { .func_arg = opt_progress },
3534  "write program-readable progress information", "url" },
3535  { "stdin", OPT_BOOL | OPT_EXPERT, { &stdin_interaction },
3536  "enable or disable interaction on standard input" },
3537  { "timelimit", HAS_ARG | OPT_EXPERT, { .func_arg = opt_timelimit },
3538  "set max runtime in seconds in CPU user time", "limit" },
3539  { "dump", OPT_BOOL | OPT_EXPERT, { &do_pkt_dump },
3540  "dump each input packet" },
3541  { "hex", OPT_BOOL | OPT_EXPERT, { &do_hex_dump },
3542  "when dumping packets, also dump the payload" },
3543  { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
3544  OPT_INPUT, { .off = OFFSET(rate_emu) },
3545  "read input at native frame rate; equivalent to -readrate 1", "" },
3546  { "readrate", HAS_ARG | OPT_FLOAT | OPT_OFFSET |
3547  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(readrate) },
3548  "read input at specified rate", "speed" },
3549  { "target", HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_target },
3550  "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
3551  "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")", "type" },
3552  { "vsync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_vsync },
3553  "video sync method", "" },
3554  { "frame_drop_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &frame_drop_threshold },
3555  "frame drop threshold", "" },
3556  { "async", HAS_ARG | OPT_INT | OPT_EXPERT, { &audio_sync_method },
3557  "audio sync method", "" },
3558  { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &audio_drift_threshold },
3559  "audio drift threshold", "threshold" },
3560  { "copyts", OPT_BOOL | OPT_EXPERT, { &copy_ts },
3561  "copy timestamps" },
3562  { "start_at_zero", OPT_BOOL | OPT_EXPERT, { &start_at_zero },
3563  "shift input timestamps to start at 0 when using copyts" },
3564  { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, { &copy_tb },
3565  "copy input stream time base when stream copying", "mode" },
3566  { "shortest", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
3567  OPT_OUTPUT, { .off = OFFSET(shortest) },
3568  "finish encoding within shortest input" },
3569  { "bitexact", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
3570  OPT_OUTPUT | OPT_INPUT, { .off = OFFSET(bitexact) },
3571  "bitexact mode" },
3572  { "apad", OPT_STRING | HAS_ARG | OPT_SPEC |
3573  OPT_OUTPUT, { .off = OFFSET(apad) },
3574  "audio pad", "" },
3575  { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &dts_delta_threshold },
3576  "timestamp discontinuity delta threshold", "threshold" },
3577  { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &dts_error_threshold },
3578  "timestamp error delta threshold", "threshold" },
3579  { "xerror", OPT_BOOL | OPT_EXPERT, { &exit_on_error },
3580  "exit on error", "error" },
3581  { "abort_on", HAS_ARG | OPT_EXPERT, { .func_arg = opt_abort_on },
3582  "abort on the specified condition flags", "flags" },
3583  { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC |
3584  OPT_OUTPUT, { .off = OFFSET(copy_initial_nonkeyframes) },
3585  "copy initial non-keyframes" },
3586  { "copypriorss", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(copy_prior_start) },
3587  "copy or discard frames before start time" },
3588  { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(max_frames) },
3589  "set the number of frames to output", "number" },
3590  { "tag", OPT_STRING | HAS_ARG | OPT_SPEC |
3591  OPT_EXPERT | OPT_OUTPUT | OPT_INPUT, { .off = OFFSET(codec_tags) },
3592  "force codec tag/fourcc", "fourcc/tag" },
3593  { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE |
3594  OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(qscale) },
3595  "use fixed quality scale (VBR)", "q" },
3596  { "qscale", HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3597  OPT_OUTPUT, { .func_arg = opt_qscale },
3598  "use fixed quality scale (VBR)", "q" },
3599  { "profile", HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_profile },
3600  "set profile", "profile" },
3601  { "filter", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filters) },
3602  "set stream filtergraph", "filter_graph" },
3603  { "filter_threads", HAS_ARG | OPT_INT, { &filter_nbthreads },
3604  "number of non-complex filter threads" },
3605  { "filter_script", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filter_scripts) },
3606  "read stream filtergraph description from a file", "filename" },
3607  { "reinit_filter", HAS_ARG | OPT_INT | OPT_SPEC | OPT_INPUT, { .off = OFFSET(reinit_filters) },
3608  "reinit filtergraph on input parameter changes", "" },
3609  { "filter_complex", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex },
3610  "create a complex filtergraph", "graph_description" },
3611  { "filter_complex_threads", HAS_ARG | OPT_INT, { &filter_complex_nbthreads },
3612  "number of threads for -filter_complex" },
3613  { "lavfi", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex },
3614  "create a complex filtergraph", "graph_description" },
3615  { "filter_complex_script", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex_script },
3616  "read complex filtergraph description from a file", "filename" },
3617  { "auto_conversion_filters", OPT_BOOL | OPT_EXPERT, { &auto_conversion_filters },
3618  "enable automatic conversion filters globally" },
3619  { "stats", OPT_BOOL, { &print_stats },
3620  "print progress report during encoding", },
3621  { "stats_period", HAS_ARG | OPT_EXPERT, { .func_arg = opt_stats_period },
3622  "set the period at which ffmpeg updates stats and -progress output", "time" },
3623  { "attach", HAS_ARG | OPT_PERFILE | OPT_EXPERT |
3624  OPT_OUTPUT, { .func_arg = opt_attach },
3625  "add an attachment to the output file", "filename" },
3626  { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC |
3627  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(dump_attachment) },
3628  "extract an attachment into a file", "filename" },
3629  { "stream_loop", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_INPUT |
3630  OPT_OFFSET, { .off = OFFSET(loop) }, "set number of times input stream shall be looped", "loop count" },
3631  { "debug_ts", OPT_BOOL | OPT_EXPERT, { &debug_ts },
3632  "print timestamp debugging info" },
3633  { "max_error_rate", HAS_ARG | OPT_FLOAT, { &max_error_rate },
3634  "ratio of decoding errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.", "maximum error rate" },
3635  { "discard", OPT_STRING | HAS_ARG | OPT_SPEC |
3636  OPT_INPUT, { .off = OFFSET(discard) },
3637  "discard", "" },
3638  { "disposition", OPT_STRING | HAS_ARG | OPT_SPEC |
3639  OPT_OUTPUT, { .off = OFFSET(disposition) },
3640  "disposition", "" },
3641  { "thread_queue_size", HAS_ARG | OPT_INT | OPT_OFFSET | OPT_EXPERT | OPT_INPUT,
3642  { .off = OFFSET(thread_queue_size) },
3643  "set the maximum number of queued packets from the demuxer" },
3644  { "find_stream_info", OPT_BOOL | OPT_PERFILE | OPT_INPUT | OPT_EXPERT, { &find_stream_info },
3645  "read and decode the streams to fill missing information with heuristics" },
3646 
3647  /* video options */
3648  { "vframes", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_video_frames },
3649  "set the number of video frames to output", "number" },
3650  { "r", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
3651  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_rates) },
3652  "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3653  { "fpsmax", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
3654  OPT_OUTPUT, { .off = OFFSET(max_frame_rates) },
3655  "set max frame rate (Hz value, fraction or abbreviation)", "rate" },
3657  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_sizes) },
3658  "set frame size (WxH or abbreviation)", "size" },
3659  { "aspect", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
3660  OPT_OUTPUT, { .off = OFFSET(frame_aspect_ratios) },
3661  "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3662  { "pix_fmt", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
3663  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_pix_fmts) },
3664  "set pixel format", "format" },
3665  { "bits_per_raw_sample", OPT_VIDEO | OPT_INT | HAS_ARG, { &frame_bits_per_raw_sample },
3666  "set the number of bits per raw sample", "number" },
3667  { "intra", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &intra_only },
3668  "deprecated use -g 1" },
3670  "disable video" },
3671  { "rc_override", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
3672  OPT_OUTPUT, { .off = OFFSET(rc_overrides) },
3673  "rate control override for specific intervals", "override" },
3674  { "vcodec", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_INPUT |
3675  OPT_OUTPUT, { .func_arg = opt_video_codec },
3676  "force video codec ('copy' to copy stream)", "codec" },
3677  { "sameq", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_sameq },
3678  "Removed" },
3679  { "same_quant", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_sameq },
3680  "Removed" },
3681  { "timecode", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_timecode },
3682  "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
3683  { "pass", OPT_VIDEO | HAS_ARG | OPT_SPEC | OPT_INT | OPT_OUTPUT, { .off = OFFSET(pass) },
3684  "select the pass number (1 to 3)", "n" },
3685  { "passlogfile", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC |
3686  OPT_OUTPUT, { .off = OFFSET(passlogfiles) },
3687  "select two pass log file name prefix", "prefix" },
3688  { "deinterlace", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &do_deinterlace },
3689  "this option is deprecated, use the yadif filter instead" },
3690  { "psnr", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &do_psnr },
3691  "calculate PSNR of compressed frames" },
3692  { "vstats", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_vstats },
3693  "dump video coding statistics to file" },
3694  { "vstats_file", OPT_VIDEO | HAS_ARG | OPT_EXPERT , { .func_arg = opt_vstats_file },
3695  "dump video coding statistics to file", "file" },
3696  { "vstats_version", OPT_VIDEO | OPT_INT | HAS_ARG | OPT_EXPERT , { &vstats_version },
3697  "Version of the vstats format to use."},
3698  { "vf", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_video_filters },
3699  "set video filters", "filter_graph" },
3700  { "intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
3701  OPT_OUTPUT, { .off = OFFSET(intra_matrices) },
3702  "specify intra matrix coeffs", "matrix" },
3703  { "inter_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
3704  OPT_OUTPUT, { .off = OFFSET(inter_matrices) },
3705  "specify inter matrix coeffs", "matrix" },
3706  { "chroma_intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
3707  OPT_OUTPUT, { .off = OFFSET(chroma_intra_matrices) },
3708  "specify intra matrix coeffs", "matrix" },
3709  { "top", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_INT| OPT_SPEC |
3710  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(top_field_first) },
3711  "top=1/bottom=0/auto=-1 field first", "" },
3712  { "vtag", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3713  OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_old2new },
3714  "force video tag/fourcc", "fourcc/tag" },
3715  { "qphist", OPT_VIDEO | OPT_BOOL | OPT_EXPERT , { &qp_hist },
3716  "show QP histogram" },
3717  { "force_fps", OPT_VIDEO | OPT_BOOL | OPT_EXPERT | OPT_SPEC |
3718  OPT_OUTPUT, { .off = OFFSET(force_fps) },
3719  "force the selected framerate, disable the best supported framerate selection" },
3720  { "streamid", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3721  OPT_OUTPUT, { .func_arg = opt_streamid },
3722  "set the value of an outfile streamid", "streamIndex:value" },
3723  { "force_key_frames", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3724  OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(forced_key_frames) },
3725  "force key frames at specified timestamps", "timestamps" },
3726  { "ab", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_bitrate },
3727  "audio bitrate (please use -b:a)", "bitrate" },
3728  { "b", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_bitrate },
3729  "video bitrate (please use -b:v)", "bitrate" },
3730  { "hwaccel", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3731  OPT_SPEC | OPT_INPUT, { .off = OFFSET(hwaccels) },
3732  "use HW accelerated decoding", "hwaccel name" },
3733  { "hwaccel_device", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3734  OPT_SPEC | OPT_INPUT, { .off = OFFSET(hwaccel_devices) },
3735  "select a device for HW acceleration", "devicename" },
3736  { "hwaccel_output_format", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
3737  OPT_SPEC | OPT_INPUT, { .off = OFFSET(hwaccel_output_formats) },
3738  "select output format used with HW accelerated decoding", "format" },
3739 #if CONFIG_VIDEOTOOLBOX
3740  { "videotoolbox_pixfmt", HAS_ARG | OPT_STRING | OPT_EXPERT, { &videotoolbox_pixfmt}, "" },
3741 #endif
3742  { "hwaccels", OPT_EXIT, { .func_arg = show_hwaccels },
3743  "show available HW acceleration methods" },
3744  { "autorotate", HAS_ARG | OPT_BOOL | OPT_SPEC |
3745  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(autorotate) },
3746  "automatically insert correct rotate filters" },
3747  { "autoscale", HAS_ARG | OPT_BOOL | OPT_SPEC |
3748  OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(autoscale) },
3749  "automatically insert a scale filter at the end of the filter graph" },
3750 
3751  /* audio options */
3752  { "aframes", OPT_AUDIO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_audio_frames },
3753  "set the number of audio frames to output", "number" },
3754  { "aq", OPT_AUDIO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_audio_qscale },
3755  "set audio quality (codec-specific)", "quality", },
3756  { "ar", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC |
3757  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(audio_sample_rate) },
3758  "set audio sampling rate (in Hz)", "rate" },
3759  { "ac", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC |
3760  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(audio_channels) },
3761  "set number of audio channels", "channels" },
3763  "disable audio" },
3764  { "acodec", OPT_AUDIO | HAS_ARG | OPT_PERFILE |
3765  OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_audio_codec },
3766  "force audio codec ('copy' to copy stream)", "codec" },
3767  { "atag", OPT_AUDIO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3768  OPT_OUTPUT, { .func_arg = opt_old2new },
3769  "force audio tag/fourcc", "fourcc/tag" },
3770  { "vol", OPT_AUDIO | HAS_ARG | OPT_INT, { &audio_volume },
3771  "change audio volume (256=normal)" , "volume" },
3772  { "sample_fmt", OPT_AUDIO | HAS_ARG | OPT_EXPERT | OPT_SPEC |
3774  "set sample format", "format" },
3775  { "channel_layout", OPT_AUDIO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3776  OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_channel_layout },
3777  "set channel layout", "layout" },
3778  { "af", OPT_AUDIO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_audio_filters },
3779  "set audio filters", "filter_graph" },
3780  { "guess_layout_max", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC | OPT_EXPERT | OPT_INPUT, { .off = OFFSET(guess_layout_max) },
3781  "set the maximum number of channels to try to guess the channel layout" },
3782 
3783  /* subtitle options */
3785  "disable subtitle" },
3786  { "scodec", OPT_SUBTITLE | HAS_ARG | OPT_PERFILE | OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_subtitle_codec },
3787  "force subtitle codec ('copy' to copy stream)", "codec" },
3788  { "stag", OPT_SUBTITLE | HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new }
3789  , "force subtitle tag/fourcc", "fourcc/tag" },
3790  { "fix_sub_duration", OPT_BOOL | OPT_EXPERT | OPT_SUBTITLE | OPT_SPEC | OPT_INPUT, { .off = OFFSET(fix_sub_duration) },
3791  "fix subtitles duration" },
3792  { "canvas_size", OPT_SUBTITLE | HAS_ARG | OPT_STRING | OPT_SPEC | OPT_INPUT, { .off = OFFSET(canvas_sizes) },
3793  "set canvas size (WxH or abbreviation)", "size" },
3794 
3795  /* grab options */
3796  { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_channel },
3797  "deprecated, use -channel", "channel" },
3798  { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_standard },
3799  "deprecated, use -standard", "standard" },
3800  { "isync", OPT_BOOL | OPT_EXPERT, { &input_sync }, "this option is deprecated and does nothing", "" },
3801 
3802  /* muxer options */
3803  { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(mux_max_delay) },
3804  "set the maximum demux-decode delay", "seconds" },
3805  { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(mux_preload) },
3806  "set the initial demux-decode delay", "seconds" },
3807  { "sdp_file", HAS_ARG | OPT_EXPERT | OPT_OUTPUT, { .func_arg = opt_sdp_file },
3808  "specify a file in which to print sdp information", "file" },
3809 
3810  { "time_base", HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(time_bases) },
3811  "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)", "ratio" },
3812  { "enc_time_base", HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(enc_time_bases) },
3813  "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
3814  "two special values are defined - "
3815  "0 = use frame rate (video) or sample rate (audio),"
3816  "-1 = match source time base", "ratio" },
3817 
3818  { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(bitstream_filters) },
3819  "A comma-separated list of bitstream filters", "bitstream_filters" },
3820  { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new },
3821  "deprecated", "audio bitstream_filters" },
3822  { "vbsf", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new },
3823  "deprecated", "video bitstream_filters" },
3824 
3825  { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
3826  "set the audio options to the indicated preset", "preset" },
3827  { "vpre", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
3828  "set the video options to the indicated preset", "preset" },
3829  { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
3830  "set the subtitle options to the indicated preset", "preset" },
3831  { "fpre", HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
3832  "set options from indicated preset file", "filename" },
3833 
3834  { "max_muxing_queue_size", HAS_ARG | OPT_INT | OPT_SPEC | OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(max_muxing_queue_size) },
3835  "maximum number of packets that can be buffered while waiting for all streams to initialize", "packets" },
3836  { "muxing_queue_data_threshold", HAS_ARG | OPT_INT | OPT_SPEC | OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(muxing_queue_data_threshold) },
3837  "set the threshold after which max_muxing_queue_size is taken into account", "bytes" },
3838 
3839  /* data codec support */
3840  { "dcodec", HAS_ARG | OPT_DATA | OPT_PERFILE | OPT_EXPERT | OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_data_codec },
3841  "force data codec ('copy' to copy stream)", "codec" },
3842  { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(data_disable) },
3843  "disable data" },
3844 
3845 #if CONFIG_VAAPI
3846  { "vaapi_device", HAS_ARG | OPT_EXPERT, { .func_arg = opt_vaapi_device },
3847  "set VAAPI hardware device (DRM path or X11 display name)", "device" },
3848 #endif
3849 
3850 #if CONFIG_QSV
3851  { "qsv_device", HAS_ARG | OPT_STRING | OPT_EXPERT, { &qsv_device },
3852  "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)", "device"},
3853 #endif
3854 
3855  { "init_hw_device", HAS_ARG | OPT_EXPERT, { .func_arg = opt_init_hw_device },
3856  "initialise hardware device", "args" },
3857  { "filter_hw_device", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_hw_device },
3858  "set hardware device used when filtering", "device" },
3859 
3860  { NULL, },
3861 };
error
static void error(const char *err)
Definition: target_bsf_fuzzer.c:31
OptionsContext::readrate
float readrate
Definition: ffmpeg.h:123
OPT_FLOAT
#define OPT_FLOAT
Definition: cmdutils.h:174
OPT_EXIT
#define OPT_EXIT
Definition: cmdutils.h:177
AVCodec
AVCodec.
Definition: codec.h:197
OptionsContext::input_ts_offset
int64_t input_ts_offset
Definition: ffmpeg.h:120
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AV_PIX_FMT_CUDA
@ AV_PIX_FMT_CUDA
HW acceleration through CUDA.
Definition: pixfmt.h:225
ignore_unknown_streams
static int ignore_unknown_streams
Definition: ffmpeg_opt.c:188
AVCodecParameters::extradata
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
name
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default minimum maximum flags name is the option name
Definition: writing_filters.txt:88
OptionsContext::stop_time
int64_t stop_time
Definition: ffmpeg.h:154
StreamMap::file_index
int file_index
Definition: ffmpeg.h:83
new_output_stream
static OutputStream * new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
Definition: ffmpeg_opt.c:1442
show_hwaccels
static int show_hwaccels(void *optctx, const char *opt, const char *arg)
Definition: ffmpeg_opt.c:240
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
opt_abort_on
static int opt_abort_on(void *optctx, const char *opt, const char *arg)
Definition: ffmpeg_opt.c:270
AVOutputFormat::name
const char * name
Definition: avformat.h:496
AVChapter::metadata
AVDictionary * metadata
Definition: avformat.h:1068
OptionsContext::dump_attachment
SpecifierOpt * dump_attachment
Definition: ffmpeg.h:129
VSYNC_PASSTHROUGH
#define VSYNC_PASSTHROUGH
Definition: ffmpeg.h:51
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 obj