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