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