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  report_and_exit(AVERROR(ENOMEM));
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  report_and_exit(AVERROR(ENOMEM));
1032 
1034  if (ret < 0) {
1035  av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
1036  exit_program(1);
1037  }
1038 
1039  ist->decoded_frame = av_frame_alloc();
1040  if (!ist->decoded_frame)
1041  report_and_exit(AVERROR(ENOMEM));
1042 
1043  ist->pkt = av_packet_alloc();
1044  if (!ist->pkt)
1045  report_and_exit(AVERROR(ENOMEM));
1046 
1047  if (o->bitexact)
1049 
1050  switch (par->codec_type) {
1051  case AVMEDIA_TYPE_VIDEO:
1052  // avformat_find_stream_info() doesn't set this for us anymore.
1053  ist->dec_ctx->framerate = st->avg_frame_rate;
1054 
1055  MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
1057  framerate) < 0) {
1058  av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
1059  framerate);
1060  exit_program(1);
1061  }
1062 
1063  ist->top_field_first = -1;
1064  MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
1065 
1066  ist->framerate_guessed = av_guess_frame_rate(ic, st, NULL);
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 
1093  ist->par = avcodec_parameters_alloc();
1094  if (!ist->par)
1095  report_and_exit(AVERROR(ENOMEM));
1096 
1098  if (ret < 0) {
1099  av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
1100  exit_program(1);
1101  }
1102  }
1103 }
1104 
1105 static void assert_file_overwrite(const char *filename)
1106 {
1107  const char *proto_name = avio_find_protocol_name(filename);
1108 
1110  fprintf(stderr, "Error, both -y and -n supplied. Exiting.\n");
1111  exit_program(1);
1112  }
1113 
1114  if (!file_overwrite) {
1115  if (proto_name && !strcmp(proto_name, "file") && avio_check(filename, 0) == 0) {
1117  fprintf(stderr,"File '%s' already exists. Overwrite? [y/N] ", filename);
1118  fflush(stderr);
1119  term_exit();
1120  signal(SIGINT, SIG_DFL);
1121  if (!read_yesno()) {
1122  av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
1123  exit_program(1);
1124  }
1125  term_init();
1126  }
1127  else {
1128  av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
1129  exit_program(1);
1130  }
1131  }
1132  }
1133 
1134  if (proto_name && !strcmp(proto_name, "file")) {
1135  for (int i = 0; i < nb_input_files; i++) {
1136  InputFile *file = input_files[i];
1137  if (file->ctx->iformat->flags & AVFMT_NOFILE)
1138  continue;
1139  if (!strcmp(filename, file->ctx->url)) {
1140  av_log(NULL, AV_LOG_FATAL, "Output %s same as Input #%d - exiting\n", filename, i);
1141  av_log(NULL, AV_LOG_WARNING, "FFmpeg cannot edit existing files in-place.\n");
1142  exit_program(1);
1143  }
1144  }
1145  }
1146 }
1147 
1148 static void dump_attachment(AVStream *st, const char *filename)
1149 {
1150  int ret;
1151  AVIOContext *out = NULL;
1152  const AVDictionaryEntry *e;
1153 
1154  if (!st->codecpar->extradata_size) {
1155  av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
1156  nb_input_files - 1, st->index);
1157  return;
1158  }
1159  if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
1160  filename = e->value;
1161  if (!*filename) {
1162  av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
1163  "in stream #%d:%d.\n", nb_input_files - 1, st->index);
1164  exit_program(1);
1165  }
1166 
1167  assert_file_overwrite(filename);
1168 
1169  if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
1170  av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
1171  filename);
1172  exit_program(1);
1173  }
1174 
1176  avio_flush(out);
1177  avio_close(out);
1178 }
1179 
1180 static int open_input_file(OptionsContext *o, const char *filename)
1181 {
1182  InputFile *f;
1183  AVFormatContext *ic;
1184  const AVInputFormat *file_iformat = NULL;
1185  int err, i, ret;
1186  int64_t timestamp;
1187  AVDictionary *unused_opts = NULL;
1188  const AVDictionaryEntry *e = NULL;
1189  char * video_codec_name = NULL;
1190  char * audio_codec_name = NULL;
1191  char *subtitle_codec_name = NULL;
1192  char * data_codec_name = NULL;
1193  int scan_all_pmts_set = 0;
1194 
1195  if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
1196  o->stop_time = INT64_MAX;
1197  av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
1198  }
1199 
1200  if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
1201  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
1202  if (o->stop_time <= start_time) {
1203  av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
1204  exit_program(1);
1205  } else {
1207  }
1208  }
1209 
1210  if (o->format) {
1211  if (!(file_iformat = av_find_input_format(o->format))) {
1212  av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
1213  exit_program(1);
1214  }
1215  }
1216 
1217  if (!strcmp(filename, "-"))
1218  filename = "pipe:";
1219 
1220  stdin_interaction &= strncmp(filename, "pipe:", 5) &&
1221  strcmp(filename, "/dev/stdin");
1222 
1223  /* get default parameters from command line */
1224  ic = avformat_alloc_context();
1225  if (!ic)
1226  report_and_exit(AVERROR(ENOMEM));
1227  if (o->nb_audio_sample_rate) {
1228  av_dict_set_int(&o->g->format_opts, "sample_rate", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i, 0);
1229  }
1230  if (o->nb_audio_channels) {
1231  const AVClass *priv_class;
1232  if (file_iformat && (priv_class = file_iformat->priv_class) &&
1233  av_opt_find(&priv_class, "ch_layout", NULL, 0,
1235  char buf[32];
1236  snprintf(buf, sizeof(buf), "%dC", o->audio_channels[o->nb_audio_channels - 1].u.i);
1237  av_dict_set(&o->g->format_opts, "ch_layout", buf, 0);
1238  }
1239  }
1240  if (o->nb_audio_ch_layouts) {
1241  const AVClass *priv_class;
1242  if (file_iformat && (priv_class = file_iformat->priv_class) &&
1243  av_opt_find(&priv_class, "ch_layout", NULL, 0,
1245  av_dict_set(&o->g->format_opts, "ch_layout", o->audio_ch_layouts[o->nb_audio_ch_layouts - 1].u.str, 0);
1246  }
1247  }
1248  if (o->nb_frame_rates) {
1249  const AVClass *priv_class;
1250  /* set the format-level framerate option;
1251  * this is important for video grabbers, e.g. x11 */
1252  if (file_iformat && (priv_class = file_iformat->priv_class) &&
1253  av_opt_find(&priv_class, "framerate", NULL, 0,
1255  av_dict_set(&o->g->format_opts, "framerate",
1256  o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
1257  }
1258  }
1259  if (o->nb_frame_sizes) {
1260  av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
1261  }
1262  if (o->nb_frame_pix_fmts)
1263  av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
1264 
1265  MATCH_PER_TYPE_OPT(codec_names, str, video_codec_name, ic, "v");
1266  MATCH_PER_TYPE_OPT(codec_names, str, audio_codec_name, ic, "a");
1267  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, ic, "s");
1268  MATCH_PER_TYPE_OPT(codec_names, str, data_codec_name, ic, "d");
1269 
1270  if (video_codec_name)
1272  if (audio_codec_name)
1274  if (subtitle_codec_name)
1276  if (data_codec_name)
1277  ic->data_codec = find_codec_or_die(data_codec_name , AVMEDIA_TYPE_DATA , 0);
1278 
1282  ic->data_codec_id = data_codec_name ? ic->data_codec->id : AV_CODEC_ID_NONE;
1283 
1284  ic->flags |= AVFMT_FLAG_NONBLOCK;
1285  if (o->bitexact)
1286  ic->flags |= AVFMT_FLAG_BITEXACT;
1287  ic->interrupt_callback = int_cb;
1288 
1289  if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
1290  av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
1291  scan_all_pmts_set = 1;
1292  }
1293  /* open the input file with generic avformat function */
1294  err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
1295  if (err < 0) {
1296  print_error(filename, err);
1297  if (err == AVERROR_PROTOCOL_NOT_FOUND)
1298  av_log(NULL, AV_LOG_ERROR, "Did you mean file:%s?\n", filename);
1299  exit_program(1);
1300  }
1301  if (scan_all_pmts_set)
1302  av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
1305 
1306  /* apply forced codec ids */
1307  for (i = 0; i < ic->nb_streams; i++)
1309 
1310  if (find_stream_info) {
1312  int orig_nb_streams = ic->nb_streams;
1313 
1314  /* If not enough info to get the stream parameters, we decode the
1315  first frames to get it. (used in mpeg case for example) */
1317 
1318  for (i = 0; i < orig_nb_streams; i++)
1319  av_dict_free(&opts[i]);
1320  av_freep(&opts);
1321 
1322  if (ret < 0) {
1323  av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
1324  if (ic->nb_streams == 0) {
1325  avformat_close_input(&ic);
1326  exit_program(1);
1327  }
1328  }
1329  }
1330 
1332  av_log(NULL, AV_LOG_WARNING, "Cannot use -ss and -sseof both, using -ss for %s\n", filename);
1334  }
1335 
1336  if (o->start_time_eof != AV_NOPTS_VALUE) {
1337  if (o->start_time_eof >= 0) {
1338  av_log(NULL, AV_LOG_ERROR, "-sseof value must be negative; aborting\n");
1339  exit_program(1);
1340  }
1341  if (ic->duration > 0) {
1342  o->start_time = o->start_time_eof + ic->duration;
1343  if (o->start_time < 0) {
1344  av_log(NULL, AV_LOG_WARNING, "-sseof value seeks to before start of file %s; ignored\n", filename);
1346  }
1347  } else
1348  av_log(NULL, AV_LOG_WARNING, "Cannot use -sseof, duration of %s not known\n", filename);
1349  }
1350  timestamp = (o->start_time == AV_NOPTS_VALUE) ? 0 : o->start_time;
1351  /* add the stream start time */
1352  if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
1353  timestamp += ic->start_time;
1354 
1355  /* if seeking requested, we execute it */
1356  if (o->start_time != AV_NOPTS_VALUE) {
1357  int64_t seek_timestamp = timestamp;
1358 
1359  if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
1360  int dts_heuristic = 0;
1361  for (i=0; i<ic->nb_streams; i++) {
1362  const AVCodecParameters *par = ic->streams[i]->codecpar;
1363  if (par->video_delay) {
1364  dts_heuristic = 1;
1365  break;
1366  }
1367  }
1368  if (dts_heuristic) {
1369  seek_timestamp -= 3*AV_TIME_BASE / 23;
1370  }
1371  }
1372  ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
1373  if (ret < 0) {
1374  av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
1375  filename, (double)timestamp / AV_TIME_BASE);
1376  }
1377  }
1378 
1379  /* update the current parameters so that they match the one of the input stream */
1380  add_input_streams(o, ic);
1381 
1382  /* dump the file content */
1383  av_dump_format(ic, nb_input_files, filename, 0);
1384 
1386 
1387  f->ctx = ic;
1388  f->index = nb_input_files - 1;
1389  f->ist_index = nb_input_streams - ic->nb_streams;
1390  f->start_time = o->start_time;
1391  f->recording_time = o->recording_time;
1392  f->input_sync_ref = o->input_sync_ref;
1393  f->input_ts_offset = o->input_ts_offset;
1394  f->ts_offset = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
1395  f->nb_streams = ic->nb_streams;
1396  f->rate_emu = o->rate_emu;
1397  f->accurate_seek = o->accurate_seek;
1398  f->loop = o->loop;
1399  f->duration = 0;
1400  f->time_base = (AVRational){ 1, 1 };
1401 
1402  f->readrate = o->readrate ? o->readrate : 0.0;
1403  if (f->readrate < 0.0f) {
1404  av_log(NULL, AV_LOG_ERROR, "Option -readrate for Input #%d is %0.3f; it must be non-negative.\n", f->index, f->readrate);
1405  exit_program(1);
1406  }
1407  if (f->readrate && f->rate_emu) {
1408  av_log(NULL, AV_LOG_WARNING, "Both -readrate and -re set for Input #%d. Using -readrate %0.3f.\n", f->index, f->readrate);
1409  f->rate_emu = 0;
1410  }
1411 
1412  f->thread_queue_size = o->thread_queue_size;
1413 
1414  /* check if all codec options have been used */
1415  unused_opts = strip_specifiers(o->g->codec_opts);
1416  for (i = f->ist_index; i < nb_input_streams; i++) {
1417  e = NULL;
1418  while ((e = av_dict_get(input_streams[i]->decoder_opts, "", e,
1420  av_dict_set(&unused_opts, e->key, NULL, 0);
1421  }
1422 
1423  e = NULL;
1424  while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
1425  const AVClass *class = avcodec_get_class();
1426  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
1428  const AVClass *fclass = avformat_get_class();
1429  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
1431  if (!option || foption)
1432  continue;
1433 
1434 
1435  if (!(option->flags & AV_OPT_FLAG_DECODING_PARAM)) {
1436  av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
1437  "input file #%d (%s) is not a decoding option.\n", e->key,
1438  option->help ? option->help : "", f->index,
1439  filename);
1440  exit_program(1);
1441  }
1442 
1443  av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
1444  "input file #%d (%s) has not been used for any stream. The most "
1445  "likely reason is either wrong type (e.g. a video option with "
1446  "no video streams) or that it is a private option of some decoder "
1447  "which was not actually used for any stream.\n", e->key,
1448  option->help ? option->help : "", f->index, filename);
1449  }
1450  av_dict_free(&unused_opts);
1451 
1452  for (i = 0; i < o->nb_dump_attachment; i++) {
1453  int j;
1454 
1455  for (j = 0; j < ic->nb_streams; j++) {
1456  AVStream *st = ic->streams[j];
1457 
1458  if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
1460  }
1461  }
1462 
1464 
1465  return 0;
1466 }
1467 
1468 static char *get_line(AVIOContext *s, AVBPrint *bprint)
1469 {
1470  char c;
1471 
1472  while ((c = avio_r8(s)) && c != '\n')
1473  av_bprint_chars(bprint, c, 1);
1474 
1475  if (!av_bprint_is_complete(bprint))
1476  report_and_exit(AVERROR(ENOMEM));
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  OutputStream *ost, const AVCodec **enc)
1512 {
1513  enum AVMediaType type = ost->st->codecpar->codec_type;
1514  char *codec_name = NULL;
1515 
1516  *enc = NULL;
1517 
1519  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
1520  if (!codec_name) {
1521  ost->st->codecpar->codec_id = av_guess_codec(s->oformat, NULL, s->url,
1522  NULL, ost->st->codecpar->codec_type);
1523  *enc = avcodec_find_encoder(ost->st->codecpar->codec_id);
1524  if (!*enc) {
1525  av_log(NULL, AV_LOG_FATAL, "Automatic encoder selection failed for "
1526  "output stream #%d:%d. Default encoder for format %s (codec %s) is "
1527  "probably disabled. Please choose an encoder manually.\n",
1528  ost->file_index, ost->index, s->oformat->name,
1531  }
1532  } else if (strcmp(codec_name, "copy")) {
1533  *enc = find_codec_or_die(codec_name, ost->st->codecpar->codec_type, 1);
1534  ost->st->codecpar->codec_id = (*enc)->id;
1535  }
1536  }
1537 
1538  return 0;
1539 }
1540 
1541 static int check_opt_bitexact(void *ctx, const AVDictionary *opts,
1542  const char *opt_name, int flag)
1543 {
1544  const AVDictionaryEntry *e = av_dict_get(opts, opt_name, NULL, 0);
1545 
1546  if (e) {
1547  const AVOption *o = av_opt_find(ctx, opt_name, NULL, 0, 0);
1548  int val = 0;
1549  if (!o)
1550  return 0;
1551  av_opt_eval_flags(ctx, o, e->value, &val);
1552  return !!(val & flag);
1553  }
1554  return 0;
1555 }
1556 
1558 {
1559  OutputStream *ost;
1560  const AVCodec *enc;
1561  AVStream *st = avformat_new_stream(oc, NULL);
1562  int idx = oc->nb_streams - 1, ret = 0;
1563  const char *bsfs = NULL, *time_base = NULL;
1564  char *next, *codec_tag = NULL;
1565  double qscale = -1;
1566  int i;
1567 
1568  if (!st)
1569  report_and_exit(AVERROR(ENOMEM));
1570 
1571  if (oc->nb_streams - 1 < o->nb_streamid_map)
1572  st->id = o->streamid_map[oc->nb_streams - 1];
1573 
1575 
1576  ost->file_index = nb_output_files - 1;
1577  ost->index = idx;
1578  ost->st = st;
1579  ost->forced_kf_ref_pts = AV_NOPTS_VALUE;
1580  st->codecpar->codec_type = type;
1581 
1582  ret = choose_encoder(o, oc, ost, &enc);
1583  if (ret < 0) {
1584  av_log(NULL, AV_LOG_FATAL, "Error selecting an encoder for stream "
1585  "%d:%d\n", ost->file_index, ost->index);
1586  exit_program(1);
1587  }
1588 
1589  if (enc) {
1590  ost->enc_ctx = avcodec_alloc_context3(enc);
1591  if (!ost->enc_ctx)
1592  report_and_exit(AVERROR(ENOMEM));
1593  }
1594 
1595  ost->filtered_frame = av_frame_alloc();
1596  if (!ost->filtered_frame)
1597  report_and_exit(AVERROR(ENOMEM));
1598 
1599  ost->pkt = av_packet_alloc();
1600  if (!ost->pkt)
1601  report_and_exit(AVERROR(ENOMEM));
1602 
1603  if (ost->enc_ctx) {
1604  AVCodecContext *enc = ost->enc_ctx;
1605  AVIOContext *s = NULL;
1606  char *buf = NULL, *arg = NULL, *preset = NULL;
1607 
1608  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, enc->codec_id,
1609  oc, st, enc->codec);
1610 
1612  ost->autoscale = 1;
1613  MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
1614  if (preset && (!(ret = get_preset_file_2(preset, enc->codec->name, &s)))) {
1615  AVBPrint bprint;
1617  do {
1618  av_bprint_clear(&bprint);
1619  buf = get_line(s, &bprint);
1620  if (!buf[0] || buf[0] == '#')
1621  continue;
1622  if (!(arg = strchr(buf, '='))) {
1623  av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1624  exit_program(1);
1625  }
1626  *arg++ = 0;
1627  av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1628  } while (!s->eof_reached);
1629  av_bprint_finalize(&bprint, NULL);
1630  avio_closep(&s);
1631  }
1632  if (ret) {
1634  "Preset %s specified for stream %d:%d, but could not be opened.\n",
1635  preset, ost->file_index, ost->index);
1636  exit_program(1);
1637  }
1638  } else {
1639  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);
1640  }
1641 
1642 
1643  if (o->bitexact) {
1644  ost->bitexact = 1;
1645  } else if (ost->enc_ctx) {
1646  ost->bitexact = check_opt_bitexact(ost->enc_ctx, ost->encoder_opts, "flags",
1648  }
1649 
1650  MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
1651  if (time_base) {
1652  AVRational q;
1653  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1654  q.num <= 0 || q.den <= 0) {
1655  av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1656  exit_program(1);
1657  }
1658  st->time_base = q;
1659  }
1660 
1661  MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);
1662  if (time_base) {
1663  AVRational q;
1664  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1665  q.den <= 0) {
1666  av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1667  exit_program(1);
1668  }
1669  ost->enc_timebase = q;
1670  }
1671 
1672  ost->max_frames = INT64_MAX;
1673  MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
1674  for (i = 0; i<o->nb_max_frames; i++) {
1675  char *p = o->max_frames[i].specifier;
1676  if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1677  av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1678  break;
1679  }
1680  }
1681 
1682  ost->copy_prior_start = -1;
1683  MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);
1684 
1685  MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
1686  if (bsfs && *bsfs) {
1687  ret = av_bsf_list_parse_str(bsfs, &ost->bsf_ctx);
1688  if (ret < 0) {
1689  av_log(NULL, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1690  exit_program(1);
1691  }
1692  }
1693 
1694  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1695  if (codec_tag) {
1696  uint32_t tag = strtol(codec_tag, &next, 0);
1697  if (*next)
1698  tag = AV_RL32(codec_tag);
1699  ost->st->codecpar->codec_tag = tag;
1700  if (ost->enc_ctx)
1701  ost->enc_ctx->codec_tag = tag;
1702  }
1703 
1704  MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1705  if (ost->enc_ctx && qscale >= 0) {
1706  ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
1707  ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1708  }
1709 
1710  MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);
1712 
1713  ost->max_muxing_queue_size = 128;
1714  MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ost->max_muxing_queue_size, oc, st);
1715 
1716  ost->muxing_queue_data_threshold = 50*1024*1024;
1717  MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, ost->muxing_queue_data_threshold, oc, st);
1718 
1719  MATCH_PER_STREAM_OPT(bits_per_raw_sample, i, ost->bits_per_raw_sample,
1720  oc, st);
1721 
1722  if (oc->oformat->flags & AVFMT_GLOBALHEADER && ost->enc_ctx)
1723  ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1724 
1725  av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
1726 
1727  av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1728  if (ost->enc_ctx && av_get_exact_bits_per_sample(ost->enc_ctx->codec_id) == 24)
1729  av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1730 
1731  ost->source_index = source_index;
1732  if (source_index >= 0) {
1733  input_streams[source_index]->discard = 0;
1734  input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;
1735  }
1736  ost->last_mux_dts = AV_NOPTS_VALUE;
1737  ost->last_filter_pts = AV_NOPTS_VALUE;
1738 
1739  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i,
1740  ost->copy_initial_nonkeyframes, oc, st);
1741 
1742  return ost;
1743 }
1744 
1745 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
1746 {
1747  int i;
1748  const char *p = str;
1749  for (i = 0;; i++) {
1750  dest[i] = atoi(p);
1751  if (i == 63)
1752  break;
1753  p = strchr(p, ',');
1754  if (!p) {
1755  av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
1756  exit_program(1);
1757  }
1758  p++;
1759  }
1760 }
1761 
1762 /* read file contents into a string */
1763 static char *read_file(const char *filename)
1764 {
1765  AVIOContext *pb = NULL;
1766  int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
1767  AVBPrint bprint;
1768  char *str;
1769 
1770  if (ret < 0) {
1771  av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
1772  return NULL;
1773  }
1774 
1776  ret = avio_read_to_bprint(pb, &bprint, SIZE_MAX);
1777  avio_closep(&pb);
1778  if (ret < 0) {
1779  av_bprint_finalize(&bprint, NULL);
1780  return NULL;
1781  }
1782  ret = av_bprint_finalize(&bprint, &str);
1783  if (ret < 0)
1784  return NULL;
1785  return str;
1786 }
1787 
1789  OutputStream *ost)
1790 {
1791  AVStream *st = ost->st;
1792 
1793  if (ost->filters_script && ost->filters) {
1794  av_log(NULL, AV_LOG_ERROR, "Both -filter and -filter_script set for "
1795  "output stream #%d:%d.\n", nb_output_files, st->index);
1796  exit_program(1);
1797  }
1798 
1799  if (ost->filters_script)
1800  return read_file(ost->filters_script);
1801  else if (ost->filters)
1802  return av_strdup(ost->filters);
1803 
1805  "null" : "anull");
1806 }
1807 
1809  const OutputStream *ost, enum AVMediaType type)
1810 {
1811  if (ost->filters_script || ost->filters) {
1813  "%s '%s' was defined for %s output stream %d:%d but codec copy was selected.\n"
1814  "Filtering and streamcopy cannot be used together.\n",
1815  ost->filters ? "Filtergraph" : "Filtergraph script",
1816  ost->filters ? ost->filters : ost->filters_script,
1817  av_get_media_type_string(type), ost->file_index, ost->index);
1818  exit_program(1);
1819  }
1820 }
1821 
1823 {
1824  AVStream *st;
1825  OutputStream *ost;
1826  char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
1827 
1828  ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
1829  st = ost->st;
1830 
1831  MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
1832  if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
1833  av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
1834  exit_program(1);
1835  }
1836 
1837  MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
1838  if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
1839  av_log(NULL, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
1840  exit_program(1);
1841  }
1842 
1843  if (frame_rate && max_frame_rate) {
1844  av_log(NULL, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
1845  exit_program(1);
1846  }
1847 
1848  if ((frame_rate || max_frame_rate) &&
1850  av_log(NULL, AV_LOG_ERROR, "Using -vsync passthrough and -r/-fpsmax can produce invalid output files\n");
1851 
1852  MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
1853  if (frame_aspect_ratio) {
1854  AVRational q;
1855  if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
1856  q.num <= 0 || q.den <= 0) {
1857  av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
1858  exit_program(1);
1859  }
1860  ost->frame_aspect_ratio = q;
1861  }
1862 
1863  MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1864  MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
1865 
1866  if (ost->enc_ctx) {
1867  AVCodecContext *video_enc = ost->enc_ctx;
1868  const char *p = NULL, *fps_mode = NULL;
1869  char *frame_size = NULL;
1870  char *frame_pix_fmt = NULL;
1871  char *intra_matrix = NULL, *inter_matrix = NULL;
1872  char *chroma_intra_matrix = NULL;
1873  int do_pass = 0;
1874  int i;
1875 
1877  if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
1878  av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1879  exit_program(1);
1880  }
1881 
1882  MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
1883  if (frame_pix_fmt && *frame_pix_fmt == '+') {
1884  ost->keep_pix_fmt = 1;
1885  if (!*++frame_pix_fmt)
1886  frame_pix_fmt = NULL;
1887  }
1888  if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
1889  av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
1890  exit_program(1);
1891  }
1892  st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
1893 
1894  MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
1895  if (intra_matrix) {
1896  if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64)))
1897  report_and_exit(AVERROR(ENOMEM));
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  report_and_exit(AVERROR(ENOMEM));
1905  video_enc->chroma_intra_matrix = p;
1906  parse_matrix_coeffs(p, chroma_intra_matrix);
1907  }
1908  MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
1909  if (inter_matrix) {
1910  if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64)))
1911  report_and_exit(AVERROR(ENOMEM));
1912  parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
1913  }
1914 
1915  MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
1916  for (i = 0; p; i++) {
1917  int start, end, q;
1918  int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
1919  if (e != 3) {
1920  av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
1921  exit_program(1);
1922  }
1923  video_enc->rc_override =
1924  av_realloc_array(video_enc->rc_override,
1925  i + 1, sizeof(RcOverride));
1926  if (!video_enc->rc_override) {
1927  av_log(NULL, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
1928  exit_program(1);
1929  }
1930  video_enc->rc_override[i].start_frame = start;
1931  video_enc->rc_override[i].end_frame = end;
1932  if (q > 0) {
1933  video_enc->rc_override[i].qscale = q;
1934  video_enc->rc_override[i].quality_factor = 1.0;
1935  }
1936  else {
1937  video_enc->rc_override[i].qscale = 0;
1938  video_enc->rc_override[i].quality_factor = -q/100.0;
1939  }
1940  p = strchr(p, '/');
1941  if (p) p++;
1942  }
1943  video_enc->rc_override_count = i;
1944 
1945 #if FFMPEG_OPT_PSNR
1946  if (do_psnr) {
1947  av_log(NULL, AV_LOG_WARNING, "The -psnr option is deprecated, use -flags +psnr\n");
1948  video_enc->flags|= AV_CODEC_FLAG_PSNR;
1949  }
1950 #endif
1951 
1952  /* two pass mode */
1953  MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
1954  if (do_pass) {
1955  if (do_pass & 1) {
1956  video_enc->flags |= AV_CODEC_FLAG_PASS1;
1957  av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
1958  }
1959  if (do_pass & 2) {
1960  video_enc->flags |= AV_CODEC_FLAG_PASS2;
1961  av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
1962  }
1963  }
1964 
1965  MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
1966  if (ost->logfile_prefix &&
1967  !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
1968  report_and_exit(AVERROR(ENOMEM));
1969 
1970  if (do_pass) {
1971  char logfilename[1024];
1972  FILE *f;
1973 
1974  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1975  ost->logfile_prefix ? ost->logfile_prefix :
1977  nb_output_streams - 1);
1978  if (!strcmp(ost->enc_ctx->codec->name, "libx264")) {
1979  av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
1980  } else {
1981  if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
1982  char *logbuffer = read_file(logfilename);
1983 
1984  if (!logbuffer) {
1985  av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
1986  logfilename);
1987  exit_program(1);
1988  }
1989  video_enc->stats_in = logbuffer;
1990  }
1991  if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
1992  f = fopen_utf8(logfilename, "wb");
1993  if (!f) {
1995  "Cannot write log file '%s' for pass-1 encoding: %s\n",
1996  logfilename, strerror(errno));
1997  exit_program(1);
1998  }
1999  ost->logfile = f;
2000  }
2001  }
2002  }
2003 
2004  MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
2005  if (ost->forced_keyframes)
2006  ost->forced_keyframes = av_strdup(ost->forced_keyframes);
2007 
2008  MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
2009 
2010  ost->top_field_first = -1;
2011  MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
2012 
2013  ost->vsync_method = video_sync_method;
2014  MATCH_PER_STREAM_OPT(fps_mode, str, fps_mode, oc, st);
2015  if (fps_mode)
2016  parse_and_set_vsync(fps_mode, &ost->vsync_method, ost->file_index, ost->index, 0);
2017 
2018  if (ost->vsync_method == VSYNC_AUTO) {
2019  if (!strcmp(oc->oformat->name, "avi")) {
2020  ost->vsync_method = VSYNC_VFR;
2021  } else {
2022  ost->vsync_method = (oc->oformat->flags & AVFMT_VARIABLE_FPS) ?
2023  ((oc->oformat->flags & AVFMT_NOTIMESTAMPS) ?
2025  VSYNC_CFR;
2026  }
2027 
2028  if (ost->source_index >= 0 && ost->vsync_method == VSYNC_CFR) {
2029  const InputStream *ist = input_streams[ost->source_index];
2030  const InputFile *ifile = input_files[ist->file_index];
2031 
2032  if (ifile->nb_streams == 1 && ifile->input_ts_offset == 0)
2033  ost->vsync_method = VSYNC_VSCFR;
2034  }
2035 
2036  if (ost->vsync_method == VSYNC_CFR && copy_ts) {
2037  ost->vsync_method = VSYNC_VSCFR;
2038  }
2039  }
2040  ost->is_cfr = (ost->vsync_method == VSYNC_CFR || ost->vsync_method == VSYNC_VSCFR);
2041 
2042  ost->avfilter = get_ost_filters(o, oc, ost);
2043  if (!ost->avfilter)
2044  exit_program(1);
2045 
2046  ost->last_frame = av_frame_alloc();
2047  if (!ost->last_frame)
2048  report_and_exit(AVERROR(ENOMEM));
2049  } else
2051 
2052  return ost;
2053 }
2054 
2056 {
2057  AVStream *st;
2058  OutputStream *ost;
2059 
2060  ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
2061  st = ost->st;
2062 
2063 
2064  MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
2065  MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
2066 
2067  if (ost->enc_ctx) {
2068  AVCodecContext *audio_enc = ost->enc_ctx;
2069  int channels = 0;
2070  char *layout = NULL;
2071  char *sample_fmt = NULL;
2072 
2074  if (channels) {
2076  audio_enc->ch_layout.nb_channels = channels;
2077  }
2078 
2079  MATCH_PER_STREAM_OPT(audio_ch_layouts, str, layout, oc, st);
2080  if (layout) {
2081  if (av_channel_layout_from_string(&audio_enc->ch_layout, layout) < 0) {
2082 #if FF_API_OLD_CHANNEL_LAYOUT
2083  uint64_t mask;
2086  })
2087  if (!mask) {
2088 #endif
2089  av_log(NULL, AV_LOG_FATAL, "Unknown channel layout: %s\n", layout);
2090  exit_program(1);
2091 #if FF_API_OLD_CHANNEL_LAYOUT
2092  }
2093  av_log(NULL, AV_LOG_WARNING, "Channel layout '%s' uses a deprecated syntax.\n",
2094  layout);
2096 #endif
2097  }
2098  }
2099 
2100  MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
2101  if (sample_fmt &&
2102  (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
2103  av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
2104  exit_program(1);
2105  }
2106 
2107  MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
2108 
2109  MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
2110  ost->apad = av_strdup(ost->apad);
2111 
2112  ost->avfilter = get_ost_filters(o, oc, ost);
2113  if (!ost->avfilter)
2114  exit_program(1);
2115 
2116 #if FFMPEG_OPT_MAP_CHANNEL
2117  /* check for channel mapping for this audio stream */
2118  for (int n = 0; n < o->nb_audio_channel_maps; n++) {
2120  if ((map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
2121  (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
2122  InputStream *ist;
2123 
2124  if (map->channel_idx == -1) {
2125  ist = NULL;
2126  } else if (ost->source_index < 0) {
2127  av_log(NULL, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
2128  ost->file_index, ost->st->index);
2129  continue;
2130  } else {
2131  ist = input_streams[ost->source_index];
2132  }
2133 
2134  if (!ist || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) {
2135  if (av_reallocp_array(&ost->audio_channels_map,
2136  ost->audio_channels_mapped + 1,
2137  sizeof(*ost->audio_channels_map)
2138  ) < 0 )
2139  report_and_exit(AVERROR(ENOMEM));
2140 
2141  ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
2142  }
2143  }
2144  }
2145 #endif
2146  } else
2148 
2149  return ost;
2150 }
2151 
2153 {
2154  OutputStream *ost;
2155 
2156  ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
2157  if (ost->enc_ctx) {
2158  av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
2159  exit_program(1);
2160  }
2161 
2162  return ost;
2163 }
2164 
2166 {
2167  OutputStream *ost;
2168 
2169  ost = new_output_stream(o, oc, AVMEDIA_TYPE_UNKNOWN, source_index);
2170  if (ost->enc_ctx) {
2171  av_log(NULL, AV_LOG_FATAL, "Unknown stream encoding not supported yet (only streamcopy)\n");
2172  exit_program(1);
2173  }
2174 
2175  return ost;
2176 }
2177 
2179 {
2180  OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
2181  ost->finished = 1;
2182  return ost;
2183 }
2184 
2186 {
2187  AVStream *st;
2188  OutputStream *ost;
2189 
2190  ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
2191  st = ost->st;
2192 
2193  if (ost->enc_ctx) {
2194  AVCodecContext *subtitle_enc = ost->enc_ctx;
2195  char *frame_size = NULL;
2196 
2198  if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
2199  av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
2200  exit_program(1);
2201  }
2202  }
2203 
2204  return ost;
2205 }
2206 
2207 /* arg format is "output-stream-index:streamid-value". */
2208 static int opt_streamid(void *optctx, const char *opt, const char *arg)
2209 {
2210  OptionsContext *o = optctx;
2211  int idx;
2212  char *p;
2213  char idx_str[16];
2214 
2215  av_strlcpy(idx_str, arg, sizeof(idx_str));
2216  p = strchr(idx_str, ':');
2217  if (!p) {
2219  "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
2220  arg, opt);
2221  exit_program(1);
2222  }
2223  *p++ = '\0';
2224  idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
2225  o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
2226  o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
2227  return 0;
2228 }
2229 
2231  int copy_metadata)
2232 {
2233  AVFormatContext *is = ifile->ctx;
2234  AVChapter **tmp;
2235  int i;
2236 
2237  tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
2238  if (!tmp)
2239  return AVERROR(ENOMEM);
2240  os->chapters = tmp;
2241 
2242  for (i = 0; i < is->nb_chapters; i++) {
2243  AVChapter *in_ch = is->chapters[i], *out_ch;
2244  int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
2245  int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
2246  AV_TIME_BASE_Q, in_ch->time_base);
2247  int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
2248  av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
2249 
2250 
2251  if (in_ch->end < ts_off)
2252  continue;
2253  if (rt != INT64_MAX && in_ch->start > rt + ts_off)
2254  break;
2255 
2256  out_ch = av_mallocz(sizeof(AVChapter));
2257  if (!out_ch)
2258  return AVERROR(ENOMEM);
2259 
2260  out_ch->id = in_ch->id;
2261  out_ch->time_base = in_ch->time_base;
2262  out_ch->start = FFMAX(0, in_ch->start - ts_off);
2263  out_ch->end = FFMIN(rt, in_ch->end - ts_off);
2264 
2265  if (copy_metadata)
2266  av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
2267 
2268  os->chapters[os->nb_chapters++] = out_ch;
2269  }
2270  return 0;
2271 }
2272 
2274 {
2275  int nb_streams[AVMEDIA_TYPE_NB] = { 0 };
2276  int have_default[AVMEDIA_TYPE_NB] = { 0 };
2277  int have_manual = 0;
2278 
2279  // first, copy the input dispositions
2280  for (int i = 0; i < ctx->nb_streams; i++) {
2282 
2283  nb_streams[ost->st->codecpar->codec_type]++;
2284 
2285  have_manual |= !!ost->disposition;
2286 
2287  if (ost->source_index >= 0) {
2288  ost->st->disposition = input_streams[ost->source_index]->st->disposition;
2289 
2291  have_default[ost->st->codecpar->codec_type] = 1;
2292  }
2293  }
2294 
2295  if (have_manual) {
2296  // process manually set dispositions - they override the above copy
2297  for (int i = 0; i < ctx->nb_streams; i++) {
2299  int ret;
2300 
2301  if (!ost->disposition)
2302  continue;
2303 
2304 #if LIBAVFORMAT_VERSION_MAJOR >= 60
2305  ret = av_opt_set(ost->st, "disposition", ost->disposition, 0);
2306 #else
2307  {
2308  const AVClass *class = av_stream_get_class();
2309  const AVOption *o = av_opt_find(&class, "disposition", NULL, 0, AV_OPT_SEARCH_FAKE_OBJ);
2310 
2311  av_assert0(o);
2312  ret = av_opt_eval_flags(&class, o, ost->disposition, &ost->st->disposition);
2313  }
2314 #endif
2315 
2316  if (ret < 0)
2317  return ret;
2318  }
2319  } else {
2320  // For each media type with more than one stream, find a suitable stream to
2321  // mark as default, unless one is already marked default.
2322  // "Suitable" means the first of that type, skipping attached pictures.
2323  for (int i = 0; i < ctx->nb_streams; i++) {
2325  enum AVMediaType type = ost->st->codecpar->codec_type;
2326 
2327  if (nb_streams[type] < 2 || have_default[type] ||
2329  continue;
2330 
2332  have_default[type] = 1;
2333  }
2334  }
2335 
2336  return 0;
2337 }
2338 
2340  AVFormatContext *oc)
2341 {
2342  OutputStream *ost;
2343 
2344  switch (ofilter->type) {
2345  case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
2346  case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
2347  default:
2348  av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
2349  "currently.\n");
2350  exit_program(1);
2351  }
2352 
2353  ost->filter = ofilter;
2354 
2355  ofilter->ost = ost;
2356  ofilter->format = -1;
2357 
2358  if (!ost->enc_ctx) {
2359  av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
2360  "which is fed from a complex filtergraph. Filtering and streamcopy "
2361  "cannot be used together.\n", ost->file_index, ost->index);
2362  exit_program(1);
2363  }
2364 
2365  if (ost->avfilter && (ost->filters || ost->filters_script)) {
2366  const char *opt = ost->filters ? "-vf/-af/-filter" : "-filter_script";
2368  "%s '%s' was specified through the %s option "
2369  "for output stream %d:%d, which is fed from a complex filtergraph.\n"
2370  "%s and -filter_complex cannot be used together for the same stream.\n",
2371  ost->filters ? "Filtergraph" : "Filtergraph script",
2372  ost->filters ? ost->filters : ost->filters_script,
2373  opt, ost->file_index, ost->index, opt);
2374  exit_program(1);
2375  }
2376 
2377  avfilter_inout_free(&ofilter->out_tmp);
2378 }
2379 
2380 static int init_complex_filters(void)
2381 {
2382  int i, ret = 0;
2383 
2384  for (i = 0; i < nb_filtergraphs; i++) {
2386  if (ret < 0)
2387  return ret;
2388  }
2389  return 0;
2390 }
2391 
2392 static int setup_sync_queues(OutputFile *of, AVFormatContext *oc, int64_t buf_size_us)
2393 {
2394  int nb_av_enc = 0, nb_interleaved = 0;
2395  int limit_frames = 0, limit_frames_av_enc = 0;
2396 
2397 #define IS_AV_ENC(ost, type) \
2398  (ost->enc_ctx && (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO))
2399 #define IS_INTERLEAVED(type) (type != AVMEDIA_TYPE_ATTACHMENT)
2400 
2401  for (int i = 0; i < oc->nb_streams; i++) {
2403  enum AVMediaType type = ost->st->codecpar->codec_type;
2404 
2405  ost->sq_idx_encode = -1;
2406  ost->sq_idx_mux = -1;
2407 
2408  nb_interleaved += IS_INTERLEAVED(type);
2409  nb_av_enc += IS_AV_ENC(ost, type);
2410 
2411  limit_frames |= ost->max_frames < INT64_MAX;
2412  limit_frames_av_enc |= (ost->max_frames < INT64_MAX) && IS_AV_ENC(ost, type);
2413  }
2414 
2415  if (!((nb_interleaved > 1 && of->shortest) ||
2416  (nb_interleaved > 0 && limit_frames)))
2417  return 0;
2418 
2419  /* if we have more than one encoded audio/video streams, or at least
2420  * one encoded audio/video stream is frame-limited, then we
2421  * synchronize them before encoding */
2422  if ((of->shortest && nb_av_enc > 1) || limit_frames_av_enc) {
2423  of->sq_encode = sq_alloc(SYNC_QUEUE_FRAMES, buf_size_us);
2424  if (!of->sq_encode)
2425  return AVERROR(ENOMEM);
2426 
2427  for (int i = 0; i < oc->nb_streams; i++) {
2429  enum AVMediaType type = ost->st->codecpar->codec_type;
2430 
2431  if (!IS_AV_ENC(ost, type))
2432  continue;
2433 
2434  ost->sq_idx_encode = sq_add_stream(of->sq_encode,
2435  of->shortest || ost->max_frames < INT64_MAX);
2436  if (ost->sq_idx_encode < 0)
2437  return ost->sq_idx_encode;
2438 
2439  ost->sq_frame = av_frame_alloc();
2440  if (!ost->sq_frame)
2441  return AVERROR(ENOMEM);
2442 
2443  if (ost->max_frames != INT64_MAX)
2444  sq_limit_frames(of->sq_encode, ost->sq_idx_encode, ost->max_frames);
2445  }
2446  }
2447 
2448  /* if there are any additional interleaved streams, then ALL the streams
2449  * are also synchronized before sending them to the muxer */
2450  if (nb_interleaved > nb_av_enc) {
2451  of->sq_mux = sq_alloc(SYNC_QUEUE_PACKETS, buf_size_us);
2452  if (!of->sq_mux)
2453  return AVERROR(ENOMEM);
2454 
2455  for (int i = 0; i < oc->nb_streams; i++) {
2457  enum AVMediaType type = ost->st->codecpar->codec_type;
2458 
2459  if (!IS_INTERLEAVED(type))
2460  continue;
2461 
2462  ost->sq_idx_mux = sq_add_stream(of->sq_mux,
2463  of->shortest || ost->max_frames < INT64_MAX);
2464  if (ost->sq_idx_mux < 0)
2465  return ost->sq_idx_mux;
2466 
2467  if (ost->max_frames != INT64_MAX)
2468  sq_limit_frames(of->sq_mux, ost->sq_idx_mux, ost->max_frames);
2469  }
2470  }
2471 
2472 #undef IS_AV_ENC
2473 #undef IS_INTERLEAVED
2474 
2475  return 0;
2476 }
2477 
2479  OptionsContext *o)
2480 {
2481  InputStream *ist;
2482  int best_score = 0, idx = -1;
2483  int qcr;
2484 
2485  /* video: highest resolution */
2487  return;
2488 
2489  qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
2490  for (int j = 0; j < nb_input_files; j++) {
2491  InputFile *ifile = input_files[j];
2492  int file_best_score = 0, file_best_idx = -1;
2493  for (int i = 0; i < ifile->nb_streams; i++) {
2494  int score;
2495  ist = input_streams[ifile->ist_index + i];
2496  score = ist->st->codecpar->width * ist->st->codecpar->height
2497  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2498  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2499  if (ist->user_set_discard == AVDISCARD_ALL)
2500  continue;
2501  if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2502  score = 1;
2503  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2504  score > file_best_score) {
2505  if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2506  continue;
2507  file_best_score = score;
2508  file_best_idx = ifile->ist_index + i;
2509  }
2510  }
2511  if (file_best_idx >= 0) {
2512  if((qcr == MKTAG('A', 'P', 'I', 'C')) || !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2513  file_best_score -= 5000000*!!(input_streams[file_best_idx]->st->disposition & AV_DISPOSITION_DEFAULT);
2514  if (file_best_score > best_score) {
2515  best_score = file_best_score;
2516  idx = file_best_idx;
2517  }
2518  }
2519  }
2520  if (idx >= 0)
2521  new_video_stream(o, oc, idx);
2522 }
2523 
2525  OptionsContext *o)
2526 {
2527  InputStream *ist;
2528  int best_score = 0, idx = -1;
2529 
2530  /* audio: most channels */
2532  return;
2533 
2534  for (int j = 0; j < nb_input_files; j++) {
2535  InputFile *ifile = input_files[j];
2536  int file_best_score = 0, file_best_idx = -1;
2537  for (int i = 0; i < ifile->nb_streams; i++) {
2538  int score;
2539  ist = input_streams[ifile->ist_index + i];
2540  score = ist->st->codecpar->ch_layout.nb_channels
2541  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2542  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2543  if (ist->user_set_discard == AVDISCARD_ALL)
2544  continue;
2545  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2546  score > file_best_score) {
2547  file_best_score = score;
2548  file_best_idx = ifile->ist_index + i;
2549  }
2550  }
2551  if (file_best_idx >= 0) {
2552  file_best_score -= 5000000*!!(input_streams[file_best_idx]->st->disposition & AV_DISPOSITION_DEFAULT);
2553  if (file_best_score > best_score) {
2554  best_score = file_best_score;
2555  idx = file_best_idx;
2556  }
2557  }
2558  }
2559  if (idx >= 0)
2560  new_audio_stream(o, oc, idx);
2561 }
2562 
2564  OptionsContext *o)
2565 {
2566  char *subtitle_codec_name = NULL;
2567 
2568  /* subtitles: pick first */
2569  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
2571  return;
2572 
2573  for (int i = 0; i < nb_input_streams; i++)
2574  if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2575  AVCodecDescriptor const *input_descriptor =
2576  avcodec_descriptor_get(input_streams[i]->st->codecpar->codec_id);
2577  AVCodecDescriptor const *output_descriptor = NULL;
2578  AVCodec const *output_codec =
2580  int input_props = 0, output_props = 0;
2581  if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2582  continue;
2583  if (output_codec)
2584  output_descriptor = avcodec_descriptor_get(output_codec->id);
2585  if (input_descriptor)
2586  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2587  if (output_descriptor)
2588  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2589  if (subtitle_codec_name ||
2590  input_props & output_props ||
2591  // Map dvb teletext which has neither property to any output subtitle encoder
2592  input_descriptor && output_descriptor &&
2593  (!input_descriptor->props ||
2594  !output_descriptor->props)) {
2595  new_subtitle_stream(o, oc, i);
2596  break;
2597  }
2598  }
2599 }
2600 
2602  OptionsContext *o)
2603 {
2604  /* Data only if codec id match */
2606  for (int i = 0; codec_id != AV_CODEC_ID_NONE && i < nb_input_streams; i++) {
2607  if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2608  continue;
2609  if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_DATA
2611  new_data_stream(o, oc, i);
2612  }
2613 }
2614 
2616  OptionsContext *o, const StreamMap *map)
2617 {
2618  InputStream *ist;
2619 
2620  if (map->disabled)
2621  return;
2622 
2623  if (map->linklabel) {
2624  FilterGraph *fg;
2625  OutputFilter *ofilter = NULL;
2626  int j, k;
2627 
2628  for (j = 0; j < nb_filtergraphs; j++) {
2629  fg = filtergraphs[j];
2630  for (k = 0; k < fg->nb_outputs; k++) {
2631  AVFilterInOut *out = fg->outputs[k]->out_tmp;
2632  if (out && !strcmp(out->name, map->linklabel)) {
2633  ofilter = fg->outputs[k];
2634  goto loop_end;
2635  }
2636  }
2637  }
2638 loop_end:
2639  if (!ofilter) {
2640  av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
2641  "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
2642  exit_program(1);
2643  }
2644  init_output_filter(ofilter, o, oc);
2645  } else {
2646  int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
2647 
2648  ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
2649  if (ist->user_set_discard == AVDISCARD_ALL) {
2650  av_log(NULL, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
2651  map->file_index, map->stream_index);
2652  exit_program(1);
2653  }
2655  return;
2657  return;
2659  return;
2660  if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2661  return;
2662 
2663  switch (ist->st->codecpar->codec_type) {
2664  case AVMEDIA_TYPE_VIDEO: new_video_stream (o, oc, src_idx); break;
2665  case AVMEDIA_TYPE_AUDIO: new_audio_stream (o, oc, src_idx); break;
2666  case AVMEDIA_TYPE_SUBTITLE: new_subtitle_stream (o, oc, src_idx); break;
2667  case AVMEDIA_TYPE_DATA: new_data_stream (o, oc, src_idx); break;
2668  case AVMEDIA_TYPE_ATTACHMENT: new_attachment_stream(o, oc, src_idx); break;
2669  case AVMEDIA_TYPE_UNKNOWN:
2670  if (copy_unknown_streams) {
2671  new_unknown_stream (o, oc, src_idx);
2672  break;
2673  }
2674  default:
2676  "Cannot map stream #%d:%d - unsupported type.\n",
2677  map->file_index, map->stream_index);
2678  if (!ignore_unknown_streams) {
2680  "If you want unsupported types ignored instead "
2681  "of failing, please use the -ignore_unknown option\n"
2682  "If you want them copied, please use -copy_unknown\n");
2683  exit_program(1);
2684  }
2685  }
2686  }
2687 }
2688 
2690 {
2691  OutputStream *ost;
2692  int err;
2693 
2694  for (int i = 0; i < o->nb_attachments; i++) {
2695  AVIOContext *pb;
2696  uint8_t *attachment;
2697  const char *p;
2698  int64_t len;
2699 
2700  if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
2701  av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
2702  o->attachments[i]);
2703  exit_program(1);
2704  }
2705  if ((len = avio_size(pb)) <= 0) {
2706  av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
2707  o->attachments[i]);
2708  exit_program(1);
2709  }
2710  if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ||
2711  !(attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE))) {
2712  av_log(NULL, AV_LOG_FATAL, "Attachment %s too large.\n",
2713  o->attachments[i]);
2714  exit_program(1);
2715  }
2716  avio_read(pb, attachment, len);
2717  memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2718 
2719  ost = new_attachment_stream(o, oc, -1);
2720  ost->attachment_filename = o->attachments[i];
2721  ost->st->codecpar->extradata = attachment;
2722  ost->st->codecpar->extradata_size = len;
2723 
2724  p = strrchr(o->attachments[i], '/');
2725  av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
2726  avio_closep(&pb);
2727  }
2728 }
2729 
2731 {
2732  /* process manually set programs */
2733  for (int i = 0; i < o->nb_program; i++) {
2734  const char *p = o->program[i].u.str;
2735  int progid = i+1;
2736  AVProgram *program;
2737 
2738  while(*p) {
2739  const char *p2 = av_get_token(&p, ":");
2740  const char *to_dealloc = p2;
2741  char *key;
2742  if (!p2)
2743  break;
2744 
2745  if(*p) p++;
2746 
2747  key = av_get_token(&p2, "=");
2748  if (!key || !*p2) {
2749  av_freep(&to_dealloc);
2750  av_freep(&key);
2751  break;
2752  }
2753  p2++;
2754 
2755  if (!strcmp(key, "program_num"))
2756  progid = strtol(p2, NULL, 0);
2757  av_freep(&to_dealloc);
2758  av_freep(&key);
2759  }
2760 
2761  program = av_new_program(oc, progid);
2762  if (!program)
2763  report_and_exit(AVERROR(ENOMEM));
2764 
2765  p = o->program[i].u.str;
2766  while(*p) {
2767  const char *p2 = av_get_token(&p, ":");
2768  const char *to_dealloc = p2;
2769  char *key;
2770  if (!p2)
2771  break;
2772  if(*p) p++;
2773 
2774  key = av_get_token(&p2, "=");
2775  if (!key) {
2777  "No '=' character in program string %s.\n",
2778  p2);
2779  exit_program(1);
2780  }
2781  if (!*p2)
2782  exit_program(1);
2783  p2++;
2784 
2785  if (!strcmp(key, "title")) {
2786  av_dict_set(&program->metadata, "title", p2, 0);
2787  } else if (!strcmp(key, "program_num")) {
2788  } else if (!strcmp(key, "st")) {
2789  int st_num = strtol(p2, NULL, 0);
2790  av_program_add_stream_index(oc, progid, st_num);
2791  } else {
2792  av_log(NULL, AV_LOG_FATAL, "Unknown program key %s.\n", key);
2793  exit_program(1);
2794  }
2795  av_freep(&to_dealloc);
2796  av_freep(&key);
2797  }
2798  }
2799 }
2800 
2802 {
2803  for (int i = 0; i < o->nb_metadata; i++) {
2804  AVDictionary **m;
2805  char type, *val;
2806  const char *stream_spec;
2807  int index = 0, ret = 0;
2808 
2809  val = strchr(o->metadata[i].u.str, '=');
2810  if (!val) {
2811  av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
2812  o->metadata[i].u.str);
2813  exit_program(1);
2814  }
2815  *val++ = 0;
2816 
2817  parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
2818  if (type == 's') {
2819  for (int j = 0; j < oc->nb_streams; j++) {
2821  if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
2822  if (!strcmp(o->metadata[i].u.str, "rotate")) {
2823  char *tail;
2824  double theta = av_strtod(val, &tail);
2825  if (!*tail) {
2826  ost->rotate_overridden = 1;
2827  ost->rotate_override_value = theta;
2828  }
2829  } else {
2830  av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
2831  }
2832  } else if (ret < 0)
2833  exit_program(1);
2834  }
2835  } else {
2836  switch (type) {
2837  case 'g':
2838  m = &oc->metadata;
2839  break;
2840  case 'c':
2841  if (index < 0 || index >= oc->nb_chapters) {
2842  av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
2843  exit_program(1);
2844  }
2845  m = &oc->chapters[index]->metadata;
2846  break;
2847  case 'p':
2848  if (index < 0 || index >= oc->nb_programs) {
2849  av_log(NULL, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
2850  exit_program(1);
2851  }
2852  m = &oc->programs[index]->metadata;
2853  break;
2854  default:
2855  av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
2856  exit_program(1);
2857  }
2858  av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
2859  }
2860  }
2861 }
2863 {
2864  const AVCodec *c = ost->enc_ctx->codec;
2865  int i, err;
2866 
2867  if (ost->enc_ctx->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
2868  /* Pass the layout through for all orders but UNSPEC */
2869  err = av_channel_layout_copy(&f->ch_layout, &ost->enc_ctx->ch_layout);
2870  if (err < 0)
2871  report_and_exit(AVERROR(ENOMEM));
2872  return;
2873  }
2874 
2875  /* Requested layout is of order UNSPEC */
2876  if (!c->ch_layouts) {
2877  /* Use the default native layout for the requested amount of channels when the
2878  encoder doesn't have a list of supported layouts */
2879  av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
2880  return;
2881  }
2882  /* Encoder has a list of supported layouts. Pick the first layout in it with the
2883  same amount of channels as the requested layout */
2884  for (i = 0; c->ch_layouts[i].nb_channels; i++) {
2885  if (c->ch_layouts[i].nb_channels == ost->enc_ctx->ch_layout.nb_channels)
2886  break;
2887  }
2888  if (c->ch_layouts[i].nb_channels) {
2889  /* Use it if one is found */
2890  err = av_channel_layout_copy(&f->ch_layout, &c->ch_layouts[i]);
2891  if (err < 0)
2892  report_and_exit(AVERROR(ENOMEM));
2893  return;
2894  }
2895  /* If no layout for the amount of channels requested was found, use the default
2896  native layout for it. */
2897  av_channel_layout_default(&f->ch_layout, ost->enc_ctx->ch_layout.nb_channels);
2898 }
2899 
2900 static int open_output_file(OptionsContext *o, const char *filename)
2901 {
2902  AVFormatContext *oc;
2903  int i, j, err;
2904  OutputFile *of;
2905  AVDictionary *unused_opts = NULL, *format_opts = NULL;
2906  const AVDictionaryEntry *e = NULL;
2907 
2908  if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
2909  o->stop_time = INT64_MAX;
2910  av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
2911  }
2912 
2913  if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
2914  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
2915  if (o->stop_time <= start_time) {
2916  av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
2917  exit_program(1);
2918  } else {
2920  }
2921  }
2922 
2924 
2925  of->index = nb_output_files - 1;
2927  of->recording_time = o->recording_time;
2928  of->start_time = o->start_time;
2929  of->shortest = o->shortest;
2931 
2932  if (!strcmp(filename, "-"))
2933  filename = "pipe:";
2934 
2935  err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
2936  if (!oc) {
2937  print_error(filename, err);
2938  exit_program(1);
2939  }
2940 
2941  of->format = oc->oformat;
2942  if (o->recording_time != INT64_MAX)
2943  oc->duration = o->recording_time;
2944 
2945  oc->interrupt_callback = int_cb;
2946 
2947  if (o->bitexact) {
2948  oc->flags |= AVFMT_FLAG_BITEXACT;
2949  of->bitexact = 1;
2950  } else {
2951  of->bitexact = check_opt_bitexact(oc, format_opts, "fflags",
2953  }
2954 
2955  /* create streams for all unlabeled output pads */
2956  for (i = 0; i < nb_filtergraphs; i++) {
2957  FilterGraph *fg = filtergraphs[i];
2958  for (j = 0; j < fg->nb_outputs; j++) {
2959  OutputFilter *ofilter = fg->outputs[j];
2960 
2961  if (!ofilter->out_tmp || ofilter->out_tmp->name)
2962  continue;
2963 
2964  switch (ofilter->type) {
2965  case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
2966  case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
2967  case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
2968  }
2969  init_output_filter(ofilter, o, oc);
2970  }
2971  }
2972 
2973  if (!o->nb_stream_maps) {
2974  /* pick the "best" stream of each type */
2975  if (!o->video_disable)
2976  map_auto_video(of, oc, o);
2977  if (!o->audio_disable)
2978  map_auto_audio(of, oc, o);
2979  if (!o->subtitle_disable)
2980  map_auto_subtitle(of, oc, o);
2981  if (!o->data_disable)
2982  map_auto_data(of, oc, o);
2983  } else {
2984  for (int i = 0; i < o->nb_stream_maps; i++)
2985  map_manual(of, oc, o, &o->stream_maps[i]);
2986  }
2987 
2988  of_add_attachments(oc, o);
2989 
2990  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2991  av_dump_format(oc, nb_output_files - 1, oc->url, 1);
2992  av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", nb_output_files - 1);
2993  exit_program(1);
2994  }
2995 
2996  /* check if all codec options have been used */
2997  unused_opts = strip_specifiers(o->g->codec_opts);
2998  for (i = of->ost_index; i < nb_output_streams; i++) {
2999  e = NULL;
3000  while ((e = av_dict_get(output_streams[i]->encoder_opts, "", e,
3002  av_dict_set(&unused_opts, e->key, NULL, 0);
3003  }
3004 
3005  e = NULL;
3006  while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
3007  const AVClass *class = avcodec_get_class();
3008  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
3010  const AVClass *fclass = avformat_get_class();
3011  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
3013  if (!option || foption)
3014  continue;
3015 
3016 
3017  if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
3018  av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
3019  "output file #%d (%s) is not an encoding option.\n", e->key,
3020  option->help ? option->help : "", nb_output_files - 1,
3021  filename);
3022  exit_program(1);
3023  }
3024 
3025  // gop_timecode is injected by generic code but not always used
3026  if (!strcmp(e->key, "gop_timecode"))
3027  continue;
3028 
3029  av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
3030  "output file #%d (%s) has not been used for any stream. The most "
3031  "likely reason is either wrong type (e.g. a video option with "
3032  "no video streams) or that it is a private option of some encoder "
3033  "which was not actually used for any stream.\n", e->key,
3034  option->help ? option->help : "", nb_output_files - 1, filename);
3035  }
3036  av_dict_free(&unused_opts);
3037 
3038  /* set the decoding_needed flags and create simple filtergraphs */
3039  for (i = of->ost_index; i < nb_output_streams; i++) {
3041 
3042  if (ost->enc_ctx && ost->source_index >= 0) {
3043  InputStream *ist = input_streams[ost->source_index];
3045  ist->processing_needed = 1;
3046 
3047  if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
3049  err = init_simple_filtergraph(ist, ost);
3050  if (err < 0) {
3052  "Error initializing a simple filtergraph between streams "
3053  "%d:%d->%d:%d\n", ist->file_index, ost->source_index,
3054  nb_output_files - 1, ost->st->index);
3055  exit_program(1);
3056  }
3057  }
3058  } else if (ost->source_index >= 0) {
3059  InputStream *ist = input_streams[ost->source_index];
3060  ist->processing_needed = 1;
3061  }
3062 
3063  /* set the filter output constraints */
3064  if (ost->filter) {
3065  const AVCodec *c = ost->enc_ctx->codec;
3066  OutputFilter *f = ost->filter;
3067  switch (ost->enc_ctx->codec_type) {
3068  case AVMEDIA_TYPE_VIDEO:
3069  f->frame_rate = ost->frame_rate;
3070  f->width = ost->enc_ctx->width;
3071  f->height = ost->enc_ctx->height;
3072  if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
3073  f->format = ost->enc_ctx->pix_fmt;
3074  } else {
3075  f->formats = c->pix_fmts;
3076  }
3077  break;
3078  case AVMEDIA_TYPE_AUDIO:
3079  if (ost->enc_ctx->sample_fmt != AV_SAMPLE_FMT_NONE) {
3080  f->format = ost->enc_ctx->sample_fmt;
3081  } else {
3082  f->formats = c->sample_fmts;
3083  }
3084  if (ost->enc_ctx->sample_rate) {
3085  f->sample_rate = ost->enc_ctx->sample_rate;
3086  } else {
3087  f->sample_rates = c->supported_samplerates;
3088  }
3089  if (ost->enc_ctx->ch_layout.nb_channels) {
3091  } else if (c->ch_layouts) {
3092  f->ch_layouts = c->ch_layouts;
3093  }
3094  break;
3095  }
3096  }
3097  }
3098 
3099  /* check filename in case of an image number is expected */
3100  if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3101  if (!av_filename_number_test(oc->url)) {
3102  print_error(oc->url, AVERROR(EINVAL));
3103  exit_program(1);
3104  }
3105  }
3106 
3109  "No input streams but output needs an input stream\n");
3110  exit_program(1);
3111  }
3112 
3113  if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3114  /* test if it already exists to avoid losing precious files */
3115  assert_file_overwrite(filename);
3116 
3117  /* open the file */
3118  if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
3119  &oc->interrupt_callback,
3120  &format_opts)) < 0) {
3121  print_error(filename, err);
3122  exit_program(1);
3123  }
3124  } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
3125  assert_file_overwrite(filename);
3126 
3127  if (o->mux_preload) {
3129  }
3130  oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
3131 
3132  /* copy metadata */
3133  for (i = 0; i < o->nb_metadata_map; i++) {
3134  char *p;
3135  int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
3136 
3137  if (in_file_index >= nb_input_files) {
3138  av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
3139  exit_program(1);
3140  }
3141  copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,
3142  in_file_index >= 0 ?
3143  input_files[in_file_index]->ctx : NULL, o);
3144  }
3145 
3146  /* copy chapters */
3147  if (o->chapters_input_file >= nb_input_files) {
3148  if (o->chapters_input_file == INT_MAX) {
3149  /* copy chapters from the first input file that has them*/
3150  o->chapters_input_file = -1;
3151  for (i = 0; i < nb_input_files; i++)
3152  if (input_files[i]->ctx->nb_chapters) {
3153  o->chapters_input_file = i;
3154  break;
3155  }
3156  } else {
3157  av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
3158  o->chapters_input_file);
3159  exit_program(1);
3160  }
3161  }
3162  if (o->chapters_input_file >= 0)
3165 
3166  /* copy global metadata by default */
3170  if(o->recording_time != INT64_MAX)
3171  av_dict_set(&oc->metadata, "duration", NULL, 0);
3172  av_dict_set(&oc->metadata, "creation_time", NULL, 0);
3173  av_dict_set(&oc->metadata, "company_name", NULL, 0);
3174  av_dict_set(&oc->metadata, "product_name", NULL, 0);
3175  av_dict_set(&oc->metadata, "product_version", NULL, 0);
3176  }
3177  if (!o->metadata_streams_manual)
3178  for (i = of->ost_index; i < nb_output_streams; i++) {
3179  InputStream *ist;
3180  if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
3181  continue;
3184  if (output_streams[i]->enc_ctx) {
3185  av_dict_set(&output_streams[i]->st->metadata, "encoder", NULL, 0);
3186  }
3187  }
3188 
3189  of_add_programs(oc, o);
3190  of_add_metadata(oc, o);
3191 
3192  err = set_dispositions(of, oc);
3193  if (err < 0) {
3194  av_log(NULL, AV_LOG_FATAL, "Error setting output stream dispositions\n");
3195  exit_program(1);
3196  }
3197 
3199  if (err < 0) {
3200  av_log(NULL, AV_LOG_FATAL, "Error setting up output sync queues\n");
3201  exit_program(1);
3202  }
3203 
3204  of->nb_streams = oc->nb_streams;
3205  of->url = filename;
3206 
3208  if (err < 0) {
3209  av_log(NULL, AV_LOG_FATAL, "Error initializing internal muxing state\n");
3210  exit_program(1);
3211  }
3212 
3213  return 0;
3214 }
3215 
3216 static int opt_target(void *optctx, const char *opt, const char *arg)
3217 {
3218  OptionsContext *o = optctx;
3219  enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
3220  static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
3221 
3222  if (!strncmp(arg, "pal-", 4)) {
3223  norm = PAL;
3224  arg += 4;
3225  } else if (!strncmp(arg, "ntsc-", 5)) {
3226  norm = NTSC;
3227  arg += 5;
3228  } else if (!strncmp(arg, "film-", 5)) {
3229  norm = FILM;
3230  arg += 5;
3231  } else {
3232  /* Try to determine PAL/NTSC by peeking in the input files */
3233  if (nb_input_files) {
3234  int i, j;
3235  for (j = 0; j < nb_input_files; j++) {
3236  for (i = 0; i < input_files[j]->nb_streams; i++) {
3237  AVStream *st = input_files[j]->ctx->streams[i];
3238  int64_t fr;
3240  continue;
3241  fr = st->time_base.den * 1000LL / st->time_base.num;
3242  if (fr == 25000) {
3243  norm = PAL;
3244  break;
3245  } else if ((fr == 29970) || (fr == 23976)) {
3246  norm = NTSC;
3247  break;
3248  }
3249  }
3250  if (norm != UNKNOWN)
3251  break;
3252  }
3253  }
3254  if (norm != UNKNOWN)
3255  av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
3256  }
3257 
3258  if (norm == UNKNOWN) {
3259  av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3260  av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3261  av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
3262  exit_program(1);
3263  }
3264 
3265  if (!strcmp(arg, "vcd")) {
3266  opt_video_codec(o, "c:v", "mpeg1video");
3267  opt_audio_codec(o, "c:a", "mp2");
3268  parse_option(o, "f", "vcd", options);
3269 
3270  parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
3271  parse_option(o, "r", frame_rates[norm], options);
3272  opt_default(NULL, "g", norm == PAL ? "15" : "18");
3273 
3274  opt_default(NULL, "b:v", "1150000");
3275  opt_default(NULL, "maxrate:v", "1150000");
3276  opt_default(NULL, "minrate:v", "1150000");
3277  opt_default(NULL, "bufsize:v", "327680"); // 40*1024*8;
3278 
3279  opt_default(NULL, "b:a", "224000");
3280  parse_option(o, "ar", "44100", options);
3281  parse_option(o, "ac", "2", options);
3282 
3283  opt_default(NULL, "packetsize", "2324");
3284  opt_default(NULL, "muxrate", "1411200"); // 2352 * 75 * 8;
3285 
3286  /* We have to offset the PTS, so that it is consistent with the SCR.
3287  SCR starts at 36000, but the first two packs contain only padding
3288  and the first pack from the other stream, respectively, may also have
3289  been written before.
3290  So the real data starts at SCR 36000+3*1200. */
3291  o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
3292  } else if (!strcmp(arg, "svcd")) {
3293 
3294  opt_video_codec(o, "c:v", "mpeg2video");
3295  opt_audio_codec(o, "c:a", "mp2");
3296  parse_option(o, "f", "svcd", options);
3297 
3298  parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
3299  parse_option(o, "r", frame_rates[norm], options);
3300  parse_option(o, "pix_fmt", "yuv420p", options);
3301  opt_default(NULL, "g", norm == PAL ? "15" : "18");
3302 
3303  opt_default(NULL, "b:v", "2040000");
3304  opt_default(NULL, "maxrate:v", "2516000");
3305  opt_default(NULL, "minrate:v", "0"); // 1145000;
3306  opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
3307  opt_default(NULL, "scan_offset", "1");
3308 
3309  opt_default(NULL, "b:a", "224000");
3310  parse_option(o, "ar", "44100", options);
3311 
3312  opt_default(NULL, "packetsize", "2324");
3313 
3314  } else if (!strcmp(arg, "dvd")) {
3315 
3316  opt_video_codec(o, "c:v", "mpeg2video");
3317  opt_audio_codec(o, "c:a", "ac3");
3318  parse_option(o, "f", "dvd", options);
3319 
3320  parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
3321  parse_option(o, "r", frame_rates[norm], options);
3322  parse_option(o, "pix_fmt", "yuv420p", options);
3323  opt_default(NULL, "g", norm == PAL ? "15" : "18");
3324 
3325  opt_default(NULL, "b:v", "6000000");
3326  opt_default(NULL, "maxrate:v", "9000000");
3327  opt_default(NULL, "minrate:v", "0"); // 1500000;
3328  opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
3329 
3330  opt_default(NULL, "packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3331  opt_default(NULL, "muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3332 
3333  opt_default(NULL, "b:a", "448000");
3334  parse_option(o, "ar", "48000", options);
3335 
3336  } else if (!strncmp(arg, "dv", 2)) {
3337 
3338  parse_option(o, "f", "dv", options);
3339 
3340  parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
3341  parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
3342  norm == PAL ? "yuv420p" : "yuv411p", options);
3343  parse_option(o, "r", frame_rates[norm], options);
3344 
3345  parse_option(o, "ar", "48000", options);
3346  parse_option(o, "ac", "2", options);
3347 
3348  } else {
3349  av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
3350  return AVERROR(EINVAL);
3351  }
3352 
3355 
3356  return 0;
3357 }
3358 
3359 static int opt_vstats_file(void *optctx, const char *opt, const char *arg)
3360 {
3363  return 0;
3364 }
3365 
3366 static int opt_vstats(void *optctx, const char *opt, const char *arg)
3367 {
3368  char filename[40];
3369  time_t today2 = time(NULL);
3370  struct tm *today = localtime(&today2);
3371 
3372  if (!today) { // maybe tomorrow
3373  av_log(NULL, AV_LOG_FATAL, "Unable to get current time: %s\n", strerror(errno));
3374  exit_program(1);
3375  }
3376 
3377  snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
3378  today->tm_sec);
3379  return opt_vstats_file(NULL, opt, filename);
3380 }
3381 
3382 static int opt_video_frames(void *optctx, const char *opt, const char *arg)
3383 {
3384  OptionsContext *o = optctx;
3385  return parse_option(o, "frames:v", arg, options);
3386 }
3387 
3388 static int opt_audio_frames(void *optctx, const char *opt, const char *arg)
3389 {
3390  OptionsContext *o = optctx;
3391  return parse_option(o, "frames:a", arg, options);
3392 }
3393 
3394 static int opt_data_frames(void *optctx, const char *opt, const char *arg)
3395 {
3396  OptionsContext *o = optctx;
3397  return parse_option(o, "frames:d", arg, options);
3398 }
3399 
3400 static int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
3401 {
3402  int ret;
3403  AVDictionary *cbak = codec_opts;
3404  AVDictionary *fbak = format_opts;
3405  codec_opts = NULL;
3406  format_opts = NULL;
3407 
3408  ret = opt_default(NULL, opt, arg);
3409 
3410  av_dict_copy(&o->g->codec_opts , codec_opts, 0);
3414  codec_opts = cbak;
3415  format_opts = fbak;
3416 
3417  return ret;
3418 }
3419 
3420 static int opt_preset(void *optctx, const char *opt, const char *arg)
3421 {
3422  OptionsContext *o = optctx;
3423  FILE *f=NULL;
3424  char filename[1000], line[1000], tmp_line[1000];
3425  const char *codec_name = NULL;
3426 
3427  tmp_line[0] = *opt;
3428  tmp_line[1] = 0;
3429  MATCH_PER_TYPE_OPT(codec_names, str, codec_name, NULL, tmp_line);
3430 
3431  if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
3432  if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
3433  av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
3434  }else
3435  av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
3436  exit_program(1);
3437  }
3438 
3439  while (fgets(line, sizeof(line), f)) {
3440  char *key = tmp_line, *value, *endptr;
3441 
3442  if (strcspn(line, "#\n\r") == 0)
3443  continue;
3444  av_strlcpy(tmp_line, line, sizeof(tmp_line));
3445  if (!av_strtok(key, "=", &value) ||
3446  !av_strtok(value, "\r\n", &endptr)) {
3447  av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
3448  exit_program(1);
3449  }
3450  av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
3451 
3452  if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
3453  else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
3454  else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
3455  else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
3456  else if (opt_default_new(o, key, value) < 0) {
3457  av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
3458  filename, line, key, value);
3459  exit_program(1);
3460  }
3461  }
3462 
3463  fclose(f);
3464 
3465  return 0;
3466 }
3467 
3468 static int opt_old2new(void *optctx, const char *opt, const char *arg)
3469 {
3470  OptionsContext *o = optctx;
3471  int ret;
3472  char *s = av_asprintf("%s:%c", opt + 1, *opt);
3473  if (!s)
3474  return AVERROR(ENOMEM);
3475  ret = parse_option(o, s, arg, options);
3476  av_free(s);
3477  return ret;
3478 }
3479 
3480 static int opt_bitrate(void *optctx, const char *opt, const char *arg)
3481 {
3482  OptionsContext *o = optctx;
3483 
3484  if(!strcmp(opt, "ab")){
3485  av_dict_set(&o->g->codec_opts, "b:a", arg, 0);
3486  return 0;
3487  } else if(!strcmp(opt, "b")){
3488  av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
3489  av_dict_set(&o->g->codec_opts, "b:v", arg, 0);
3490  return 0;
3491  }
3492  av_dict_set(&o->g->codec_opts, opt, arg, 0);
3493  return 0;
3494 }
3495 
3496 static int opt_qscale(void *optctx, const char *opt, const char *arg)
3497 {
3498  OptionsContext *o = optctx;
3499  char *s;
3500  int ret;
3501  if(!strcmp(opt, "qscale")){
3502  av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
3503  return parse_option(o, "q:v", arg, options);
3504  }
3505  s = av_asprintf("q%s", opt + 6);
3506  if (!s)
3507  return AVERROR(ENOMEM);
3508  ret = parse_option(o, s, arg, options);
3509  av_free(s);
3510  return ret;
3511 }
3512 
3513 static int opt_profile(void *optctx, const char *opt, const char *arg)
3514 {
3515  OptionsContext *o = optctx;
3516  if(!strcmp(opt, "profile")){
3517  av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
3518  av_dict_set(&o->g->codec_opts, "profile:v", arg, 0);
3519  return 0;
3520  }
3521  av_dict_set(&o->g->codec_opts, opt, arg, 0);
3522  return 0;
3523 }
3524 
3525 static int opt_video_filters(void *optctx, const char *opt, const char *arg)
3526 {
3527  OptionsContext *o = optctx;
3528  return parse_option(o, "filter:v", arg, options);
3529 }
3530 
3531 static int opt_audio_filters(void *optctx, const char *opt, const char *arg)
3532 {
3533  OptionsContext *o = optctx;
3534  return parse_option(o, "filter:a", arg, options);
3535 }
3536 
3537 static int opt_vsync(void *optctx, const char *opt, const char *arg)
3538 {
3539  av_log(NULL, AV_LOG_WARNING, "-vsync is deprecated. Use -fps_mode\n");
3541  return 0;
3542 }
3543 
3544 static int opt_timecode(void *optctx, const char *opt, const char *arg)
3545 {
3546  OptionsContext *o = optctx;
3547  int ret;
3548  char *tcr = av_asprintf("timecode=%s", arg);
3549  if (!tcr)
3550  return AVERROR(ENOMEM);
3551  ret = parse_option(o, "metadata:g", tcr, options);
3552  if (ret >= 0)
3553  ret = av_dict_set(&o->g->codec_opts, "gop_timecode", arg, 0);
3554  av_free(tcr);
3555  return ret;
3556 }
3557 
3558 static int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
3559 {
3560  OptionsContext *o = optctx;
3561  return parse_option(o, "q:a", arg, options);
3562 }
3563 
3564 static int opt_filter_complex(void *optctx, const char *opt, const char *arg)
3565 {
3567 
3568  fg->index = nb_filtergraphs - 1;
3569  fg->graph_desc = av_strdup(arg);
3570  if (!fg->graph_desc)
3571  return AVERROR(ENOMEM);
3572 
3574 
3575  return 0;
3576 }
3577 
3578 static int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
3579 {
3580  FilterGraph *fg;
3581  char *graph_desc = read_file(arg);
3582  if (!graph_desc)
3583  return AVERROR(EINVAL);
3584 
3586  fg->index = nb_filtergraphs - 1;
3587  fg->graph_desc = graph_desc;
3588 
3590 
3591  return 0;
3592 }
3593 
3594 void show_help_default(const char *opt, const char *arg)
3595 {
3596  /* per-file options have at least one of those set */
3597  const int per_file = OPT_SPEC | OPT_OFFSET | OPT_PERFILE;
3598  int show_advanced = 0, show_avoptions = 0;
3599 
3600  if (opt && *opt) {
3601  if (!strcmp(opt, "long"))
3602  show_advanced = 1;
3603  else if (!strcmp(opt, "full"))
3604  show_advanced = show_avoptions = 1;
3605  else
3606  av_log(NULL, AV_LOG_ERROR, "Unknown help option '%s'.\n", opt);
3607  }
3608 
3609  show_usage();
3610 
3611  printf("Getting help:\n"
3612  " -h -- print basic options\n"
3613  " -h long -- print more options\n"
3614  " -h full -- print all options (including all format and codec specific options, very long)\n"
3615  " -h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter/bsf/protocol\n"
3616  " See man %s for detailed description of the options.\n"
3617  "\n", program_name);
3618 
3619  show_help_options(options, "Print help / information / capabilities:",
3620  OPT_EXIT, 0, 0);
3621 
3622  show_help_options(options, "Global options (affect whole program "
3623  "instead of just one file):",
3624  0, per_file | OPT_EXIT | OPT_EXPERT, 0);
3625  if (show_advanced)
3626  show_help_options(options, "Advanced global options:", OPT_EXPERT,
3627  per_file | OPT_EXIT, 0);
3628 
3629  show_help_options(options, "Per-file main options:", 0,
3631  OPT_EXIT, per_file);
3632  if (show_advanced)
3633  show_help_options(options, "Advanced per-file options:",
3634  OPT_EXPERT, OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE, per_file);
3635 
3636  show_help_options(options, "Video options:",
3638  if (show_advanced)
3639  show_help_options(options, "Advanced Video options:",
3641 
3642  show_help_options(options, "Audio options:",
3644  if (show_advanced)
3645  show_help_options(options, "Advanced Audio options:",
3647  show_help_options(options, "Subtitle options:",
3648  OPT_SUBTITLE, 0, 0);
3649  printf("\n");
3650 
3651  if (show_avoptions) {
3655 #if CONFIG_SWSCALE
3657 #endif
3658 #if CONFIG_SWRESAMPLE
3660 #endif
3663  }
3664 }
3665 
3666 void show_usage(void)
3667 {
3668  av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
3669  av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
3670  av_log(NULL, AV_LOG_INFO, "\n");
3671 }
3672 
3673 enum OptGroup {
3674  GROUP_OUTFILE,
3675  GROUP_INFILE,
3676 };
3677 
3678 static const OptionGroupDef groups[] = {
3679  [GROUP_OUTFILE] = { "output url", NULL, OPT_OUTPUT },
3680  [GROUP_INFILE] = { "input url", "i", OPT_INPUT },
3681 };
3682 
3683 static int open_files(OptionGroupList *l, const char *inout,
3684  int (*open_file)(OptionsContext*, const char*))
3685 {
3686  int i, ret;
3687 
3688  for (i = 0; i < l->nb_groups; i++) {
3689  OptionGroup *g = &l->groups[i];
3690  OptionsContext o;
3691 
3692  init_options(&o);
3693  o.g = g;
3694 
3695  ret = parse_optgroup(&o, g);
3696  if (ret < 0) {
3697  av_log(NULL, AV_LOG_ERROR, "Error parsing options for %s file "
3698  "%s.\n", inout, g->arg);
3699  uninit_options(&o);
3700  return ret;
3701  }
3702 
3703  av_log(NULL, AV_LOG_DEBUG, "Opening an %s file: %s.\n", inout, g->arg);
3704  ret = open_file(&o, g->arg);
3705  uninit_options(&o);
3706  if (ret < 0) {
3707  av_log(NULL, AV_LOG_ERROR, "Error opening %s file %s.\n",
3708  inout, g->arg);
3709  return ret;
3710  }
3711  av_log(NULL, AV_LOG_DEBUG, "Successfully opened the file.\n");
3712  }
3713 
3714  return 0;
3715 }
3716 
3717 int ffmpeg_parse_options(int argc, char **argv)
3718 {
3719  OptionParseContext octx;
3720  uint8_t error[128];
3721  int ret;
3722 
3723  memset(&octx, 0, sizeof(octx));
3724 
3725  /* split the commandline into an internal representation */
3726  ret = split_commandline(&octx, argc, argv, options, groups,
3727  FF_ARRAY_ELEMS(groups));
3728  if (ret < 0) {
3729  av_log(NULL, AV_LOG_FATAL, "Error splitting the argument list: ");
3730  goto fail;
3731  }
3732 
3733  /* apply global options */
3734  ret = parse_optgroup(NULL, &octx.global_opts);
3735  if (ret < 0) {
3736  av_log(NULL, AV_LOG_FATAL, "Error parsing global options: ");
3737  goto fail;
3738  }
3739 
3740  /* configure terminal and setup signal handlers */
3741  term_init();
3742 
3743  /* open input files */
3744  ret = open_files(&octx.groups[GROUP_INFILE], "input", open_input_file);
3745  if (ret < 0) {
3746  av_log(NULL, AV_LOG_FATAL, "Error opening input files: ");
3747  goto fail;
3748  }
3749 
3751 
3752  /* create the complex filtergraphs */
3754  if (ret < 0) {
3755  av_log(NULL, AV_LOG_FATAL, "Error initializing complex filters.\n");
3756  goto fail;
3757  }
3758 
3759  /* open output files */
3760  ret = open_files(&octx.groups[GROUP_OUTFILE], "output", open_output_file);
3761  if (ret < 0) {
3762  av_log(NULL, AV_LOG_FATAL, "Error opening output files: ");
3763  goto fail;
3764  }
3765 
3767 
3768 fail:
3769  uninit_parse_context(&octx);
3770  if (ret < 0) {
3771  av_strerror(ret, error, sizeof(error));
3772  av_log(NULL, AV_LOG_FATAL, "%s\n", error);
3773  }
3774  return ret;
3775 }
3776 
3777 static int opt_progress(void *optctx, const char *opt, const char *arg)
3778 {
3779  AVIOContext *avio = NULL;
3780  int ret;
3781 
3782  if (!strcmp(arg, "-"))
3783  arg = "pipe:";
3784  ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
3785  if (ret < 0) {
3786  av_log(NULL, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
3787  arg, av_err2str(ret));
3788  return ret;
3789  }
3790  progress_avio = avio;
3791  return 0;
3792 }
3793 
3794 int opt_timelimit(void *optctx, const char *opt, const char *arg)
3795 {
3796 #if HAVE_SETRLIMIT
3797  int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
3798  struct rlimit rl = { lim, lim + 1 };
3799  if (setrlimit(RLIMIT_CPU, &rl))
3800  perror("setrlimit");
3801 #else
3802  av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
3803 #endif
3804  return 0;
3805 }
3806 
3807 #define OFFSET(x) offsetof(OptionsContext, x)
3808 const OptionDef options[] = {
3809  /* main options */
3811  { "f", HAS_ARG | OPT_STRING | OPT_OFFSET |
3812  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(format) },
3813  "force format", "fmt" },
3814  { "y", OPT_BOOL, { &file_overwrite },
3815  "overwrite output files" },
3816  { "n", OPT_BOOL, { &no_file_overwrite },
3817  "never overwrite output files" },
3818  { "ignore_unknown", OPT_BOOL, { &ignore_unknown_streams },
3819  "Ignore unknown stream types" },
3820  { "copy_unknown", OPT_BOOL | OPT_EXPERT, { &copy_unknown_streams },
3821  "Copy unknown stream types" },
3822  { "recast_media", OPT_BOOL | OPT_EXPERT, { &recast_media },
3823  "allow recasting stream type in order to force a decoder of different media type" },
3824  { "c", HAS_ARG | OPT_STRING | OPT_SPEC |
3825  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(codec_names) },
3826  "codec name", "codec" },
3827  { "codec", HAS_ARG | OPT_STRING | OPT_SPEC |
3828  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(codec_names) },
3829  "codec name", "codec" },
3830  { "pre", HAS_ARG | OPT_STRING | OPT_SPEC |
3831  OPT_OUTPUT, { .off = OFFSET(presets) },
3832  "preset name", "preset" },
3833  { "map", HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3834  OPT_OUTPUT, { .func_arg = opt_map },
3835  "set input stream mapping",
3836  "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
3837 #if FFMPEG_OPT_MAP_CHANNEL
3838  { "map_channel", HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_map_channel },
3839  "map an audio channel from one stream to another (deprecated)", "file.stream.channel[:syncfile.syncstream]" },
3840 #endif
3841  { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC |
3842  OPT_OUTPUT, { .off = OFFSET(metadata_map) },
3843  "set metadata information of outfile from infile",
3844  "outfile[,metadata]:infile[,metadata]" },
3845  { "map_chapters", HAS_ARG | OPT_INT | OPT_EXPERT | OPT_OFFSET |
3846  OPT_OUTPUT, { .off = OFFSET(chapters_input_file) },
3847  "set chapters mapping", "input_file_index" },
3848  { "t", HAS_ARG | OPT_TIME | OPT_OFFSET |
3849  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(recording_time) },
3850  "record or transcode \"duration\" seconds of audio/video",
3851  "duration" },
3852  { "to", HAS_ARG | OPT_TIME | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(stop_time) },
3853  "record or transcode stop time", "time_stop" },
3854  { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(limit_filesize) },
3855  "set the limit file size in bytes", "limit_size" },
3856  { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET |
3857  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(start_time) },
3858  "set the start time offset", "time_off" },
3859  { "sseof", HAS_ARG | OPT_TIME | OPT_OFFSET |
3860  OPT_INPUT, { .off = OFFSET(start_time_eof) },
3861  "set the start time offset relative to EOF", "time_off" },
3862  { "seek_timestamp", HAS_ARG | OPT_INT | OPT_OFFSET |
3863  OPT_INPUT, { .off = OFFSET(seek_timestamp) },
3864  "enable/disable seeking by timestamp with -ss" },
3865  { "accurate_seek", OPT_BOOL | OPT_OFFSET | OPT_EXPERT |
3866  OPT_INPUT, { .off = OFFSET(accurate_seek) },
3867  "enable/disable accurate seeking with -ss" },
3868  { "isync", HAS_ARG | OPT_INT | OPT_OFFSET |
3869  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(input_sync_ref) },
3870  "Indicate the input index for sync reference", "sync ref" },
3871  { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET |
3872  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(input_ts_offset) },
3873  "set the input ts offset", "time_off" },
3874  { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC |
3875  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(ts_scale) },
3876  "set the input ts scale", "scale" },
3877  { "timestamp", HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_recording_timestamp },
3878  "set the recording timestamp ('now' to set the current time)", "time" },
3879  { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(metadata) },
3880  "add metadata", "string=string" },
3881  { "program", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(program) },
3882  "add program with specified streams", "title=string:st=number..." },
3883  { "dframes", HAS_ARG | OPT_PERFILE | OPT_EXPERT |
3884  OPT_OUTPUT, { .func_arg = opt_data_frames },
3885  "set the number of data frames to output", "number" },
3886  { "benchmark", OPT_BOOL | OPT_EXPERT, { &do_benchmark },
3887  "add timings for benchmarking" },
3888  { "benchmark_all", OPT_BOOL | OPT_EXPERT, { &do_benchmark_all },
3889  "add timings for each task" },
3890  { "progress", HAS_ARG | OPT_EXPERT, { .func_arg = opt_progress },
3891  "write program-readable progress information", "url" },
3892  { "stdin", OPT_BOOL | OPT_EXPERT, { &stdin_interaction },
3893  "enable or disable interaction on standard input" },
3894  { "timelimit", HAS_ARG | OPT_EXPERT, { .func_arg = opt_timelimit },
3895  "set max runtime in seconds in CPU user time", "limit" },
3896  { "dump", OPT_BOOL | OPT_EXPERT, { &do_pkt_dump },
3897  "dump each input packet" },
3898  { "hex", OPT_BOOL | OPT_EXPERT, { &do_hex_dump },
3899  "when dumping packets, also dump the payload" },
3900  { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
3901  OPT_INPUT, { .off = OFFSET(rate_emu) },
3902  "read input at native frame rate; equivalent to -readrate 1", "" },
3903  { "readrate", HAS_ARG | OPT_FLOAT | OPT_OFFSET |
3904  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(readrate) },
3905  "read input at specified rate", "speed" },
3906  { "target", HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_target },
3907  "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
3908  "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")", "type" },
3909  { "vsync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_vsync },
3910  "set video sync method globally; deprecated, use -fps_mode", "" },
3911  { "frame_drop_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &frame_drop_threshold },
3912  "frame drop threshold", "" },
3913  { "async", HAS_ARG | OPT_INT | OPT_EXPERT, { &audio_sync_method },
3914  "audio sync method", "" },
3915  { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &audio_drift_threshold },
3916  "audio drift threshold", "threshold" },
3917  { "copyts", OPT_BOOL | OPT_EXPERT, { &copy_ts },
3918  "copy timestamps" },
3919  { "start_at_zero", OPT_BOOL | OPT_EXPERT, { &start_at_zero },
3920  "shift input timestamps to start at 0 when using copyts" },
3921  { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, { &copy_tb },
3922  "copy input stream time base when stream copying", "mode" },
3923  { "shortest", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
3924  OPT_OUTPUT, { .off = OFFSET(shortest) },
3925  "finish encoding within shortest input" },
3926  { "shortest_buf_duration", HAS_ARG | OPT_FLOAT | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(shortest_buf_duration) },
3927  "maximum buffering duration (in seconds) for the -shortest option" },
3928  { "bitexact", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
3929  OPT_OUTPUT | OPT_INPUT, { .off = OFFSET(bitexact) },
3930  "bitexact mode" },
3931  { "apad", OPT_STRING | HAS_ARG | OPT_SPEC |
3932  OPT_OUTPUT, { .off = OFFSET(apad) },
3933  "audio pad", "" },
3934  { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &dts_delta_threshold },
3935  "timestamp discontinuity delta threshold", "threshold" },
3936  { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &dts_error_threshold },
3937  "timestamp error delta threshold", "threshold" },
3938  { "xerror", OPT_BOOL | OPT_EXPERT, { &exit_on_error },
3939  "exit on error", "error" },
3940  { "abort_on", HAS_ARG | OPT_EXPERT, { .func_arg = opt_abort_on },
3941  "abort on the specified condition flags", "flags" },
3942  { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC |
3943  OPT_OUTPUT, { .off = OFFSET(copy_initial_nonkeyframes) },
3944  "copy initial non-keyframes" },
3945  { "copypriorss", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(copy_prior_start) },
3946  "copy or discard frames before start time" },
3947  { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(max_frames) },
3948  "set the number of frames to output", "number" },
3949  { "tag", OPT_STRING | HAS_ARG | OPT_SPEC |
3950  OPT_EXPERT | OPT_OUTPUT | OPT_INPUT, { .off = OFFSET(codec_tags) },
3951  "force codec tag/fourcc", "fourcc/tag" },
3952  { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE |
3953  OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(qscale) },
3954  "use fixed quality scale (VBR)", "q" },
3955  { "qscale", HAS_ARG | OPT_EXPERT | OPT_PERFILE |
3956  OPT_OUTPUT, { .func_arg = opt_qscale },
3957  "use fixed quality scale (VBR)", "q" },
3958  { "profile", HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_profile },
3959  "set profile", "profile" },
3960  { "filter", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filters) },
3961  "set stream filtergraph", "filter_graph" },
3962  { "filter_threads", HAS_ARG, { .func_arg = opt_filter_threads },
3963  "number of non-complex filter threads" },
3964  { "filter_script", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filter_scripts) },
3965  "read stream filtergraph description from a file", "filename" },
3966  { "reinit_filter", HAS_ARG | OPT_INT | OPT_SPEC | OPT_INPUT, { .off = OFFSET(reinit_filters) },
3967  "reinit filtergraph on input parameter changes", "" },
3968  { "filter_complex", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex },
3969  "create a complex filtergraph", "graph_description" },
3970  { "filter_complex_threads", HAS_ARG | OPT_INT, { &filter_complex_nbthreads },
3971  "number of threads for -filter_complex" },
3972  { "lavfi", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex },
3973  "create a complex filtergraph", "graph_description" },
3974  { "filter_complex_script", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex_script },
3975  "read complex filtergraph description from a file", "filename" },
3976  { "auto_conversion_filters", OPT_BOOL | OPT_EXPERT, { &auto_conversion_filters },
3977  "enable automatic conversion filters globally" },
3978  { "stats", OPT_BOOL, { &print_stats },
3979  "print progress report during encoding", },
3980  { "stats_period", HAS_ARG | OPT_EXPERT, { .func_arg = opt_stats_period },
3981  "set the period at which ffmpeg updates stats and -progress output", "time" },
3982  { "attach", HAS_ARG | OPT_PERFILE | OPT_EXPERT |
3983  OPT_OUTPUT, { .func_arg = opt_attach },
3984  "add an attachment to the output file", "filename" },
3985  { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC |
3986  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(dump_attachment) },
3987  "extract an attachment into a file", "filename" },
3988  { "stream_loop", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_INPUT |
3989  OPT_OFFSET, { .off = OFFSET(loop) }, "set number of times input stream shall be looped", "loop count" },
3990  { "debug_ts", OPT_BOOL | OPT_EXPERT, { &debug_ts },
3991  "print timestamp debugging info" },
3992  { "max_error_rate", HAS_ARG | OPT_FLOAT, { &max_error_rate },
3993  "ratio of decoding errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.", "maximum error rate" },
3994  { "discard", OPT_STRING | HAS_ARG | OPT_SPEC |
3995  OPT_INPUT, { .off = OFFSET(discard) },
3996  "discard", "" },
3997  { "disposition", OPT_STRING | HAS_ARG | OPT_SPEC |
3998  OPT_OUTPUT, { .off = OFFSET(disposition) },
3999  "disposition", "" },
4000  { "thread_queue_size", HAS_ARG | OPT_INT | OPT_OFFSET | OPT_EXPERT | OPT_INPUT | OPT_OUTPUT,
4001  { .off = OFFSET(thread_queue_size) },
4002  "set the maximum number of queued packets from the demuxer" },
4003  { "find_stream_info", OPT_BOOL | OPT_PERFILE | OPT_INPUT | OPT_EXPERT, { &find_stream_info },
4004  "read and decode the streams to fill missing information with heuristics" },
4005  { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT,
4006  { .off = OFFSET(bits_per_raw_sample) },
4007  "set the number of bits per raw sample", "number" },
4008 
4009  /* video options */
4010  { "vframes", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_video_frames },
4011  "set the number of video frames to output", "number" },
4012  { "r", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
4013  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_rates) },
4014  "set frame rate (Hz value, fraction or abbreviation)", "rate" },
4015  { "fpsmax", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
4016  OPT_OUTPUT, { .off = OFFSET(max_frame_rates) },
4017  "set max frame rate (Hz value, fraction or abbreviation)", "rate" },
4019  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_sizes) },
4020  "set frame size (WxH or abbreviation)", "size" },
4021  { "aspect", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
4022  OPT_OUTPUT, { .off = OFFSET(frame_aspect_ratios) },
4023  "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
4024  { "pix_fmt", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
4025  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_pix_fmts) },
4026  "set pixel format", "format" },
4028  "disable video" },
4029  { "rc_override", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
4030  OPT_OUTPUT, { .off = OFFSET(rc_overrides) },
4031  "rate control override for specific intervals", "override" },
4032  { "vcodec", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_INPUT |
4033  OPT_OUTPUT, { .func_arg = opt_video_codec },
4034  "force video codec ('copy' to copy stream)", "codec" },
4035  { "timecode", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_timecode },
4036  "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
4037  { "pass", OPT_VIDEO | HAS_ARG | OPT_SPEC | OPT_INT | OPT_OUTPUT, { .off = OFFSET(pass) },
4038  "select the pass number (1 to 3)", "n" },
4039  { "passlogfile", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC |
4040  OPT_OUTPUT, { .off = OFFSET(passlogfiles) },
4041  "select two pass log file name prefix", "prefix" },
4042 #if FFMPEG_OPT_PSNR
4043  { "psnr", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &do_psnr },
4044  "calculate PSNR of compressed frames (deprecated, use -flags +psnr)" },
4045 #endif
4046  { "vstats", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_vstats },
4047  "dump video coding statistics to file" },
4048  { "vstats_file", OPT_VIDEO | HAS_ARG | OPT_EXPERT , { .func_arg = opt_vstats_file },
4049  "dump video coding statistics to file", "file" },
4050  { "vstats_version", OPT_VIDEO | OPT_INT | HAS_ARG | OPT_EXPERT , { &vstats_version },
4051  "Version of the vstats format to use."},
4052  { "vf", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_video_filters },
4053  "set video filters", "filter_graph" },
4054  { "intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING |