FFmpegKit iOS / macOS / tvOS API  4.4
fftools_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 /*
22  * CHANGES 01.2020
23  * - ffprobe support changes
24  *
25  * CHANGES 12.2019
26  * - Concurrent execution support
27  *
28  * CHANGES 08.2018
29  * --------------------------------------------------------
30  * - fftools_ prefix added to file name and parent headers
31  *
32  * CHANGES 07.2018
33  * --------------------------------------------------------
34  * - Parentheses placed around assignments in condition to prevent -Wparentheses warning
35  */
36 
37 #include <stdint.h>
38 
39 #include "fftools_ffmpeg.h"
40 #include "fftools_cmdutils.h"
41 
42 #include "libavformat/avformat.h"
43 
44 #include "libavcodec/avcodec.h"
45 
46 #include "libavfilter/avfilter.h"
47 
48 #include "libavutil/avassert.h"
49 #include "libavutil/avstring.h"
50 #include "libavutil/avutil.h"
51 #include "libavutil/channel_layout.h"
52 #include "libavutil/intreadwrite.h"
53 #include "libavutil/fifo.h"
54 #include "libavutil/mathematics.h"
55 #include "libavutil/opt.h"
56 #include "libavutil/parseutils.h"
57 #include "libavutil/pixdesc.h"
58 #include "libavutil/pixfmt.h"
59 
60 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
61 
62 #define SPECIFIER_OPT_FMT_str "%s"
63 #define SPECIFIER_OPT_FMT_i "%i"
64 #define SPECIFIER_OPT_FMT_i64 "%"PRId64
65 #define SPECIFIER_OPT_FMT_ui64 "%"PRIu64
66 #define SPECIFIER_OPT_FMT_f "%f"
67 #define SPECIFIER_OPT_FMT_dbl "%lf"
68 
69 static const char *const opt_name_codec_names[] = {"c", "codec", "acodec", "vcodec", "scodec", "dcodec", NULL};
70 static const char *const opt_name_audio_channels[] = {"ac", NULL};
71 static const char *const opt_name_audio_sample_rate[] = {"ar", NULL};
72 static const char *const opt_name_frame_rates[] = {"r", NULL};
73 static const char *const opt_name_max_frame_rates[] = {"fpsmax", NULL};
74 static const char *const opt_name_frame_sizes[] = {"s", NULL};
75 static const char *const opt_name_frame_pix_fmts[] = {"pix_fmt", NULL};
76 static const char *const opt_name_ts_scale[] = {"itsscale", NULL};
77 static const char *const opt_name_hwaccels[] = {"hwaccel", NULL};
78 static const char *const opt_name_hwaccel_devices[] = {"hwaccel_device", NULL};
79 static const char *const opt_name_hwaccel_output_formats[] = {"hwaccel_output_format", NULL};
80 static const char *const opt_name_autorotate[] = {"autorotate", NULL};
81 static const char *const opt_name_autoscale[] = {"autoscale", NULL};
82 static const char *const opt_name_max_frames[] = {"frames", "aframes", "vframes", "dframes", NULL};
83 static const char *const opt_name_bitstream_filters[] = {"bsf", "absf", "vbsf", NULL};
84 static const char *const opt_name_codec_tags[] = {"tag", "atag", "vtag", "stag", NULL};
85 static const char *const opt_name_sample_fmts[] = {"sample_fmt", NULL};
86 static const char *const opt_name_qscale[] = {"q", "qscale", NULL};
87 static const char *const opt_name_forced_key_frames[] = {"forced_key_frames", NULL};
88 static const char *const opt_name_force_fps[] = {"force_fps", NULL};
89 static const char *const opt_name_frame_aspect_ratios[] = {"aspect", NULL};
90 static const char *const opt_name_rc_overrides[] = {"rc_override", NULL};
91 static const char *const opt_name_intra_matrices[] = {"intra_matrix", NULL};
92 static const char *const opt_name_inter_matrices[] = {"inter_matrix", NULL};
93 static const char *const opt_name_chroma_intra_matrices[] = {"chroma_intra_matrix", NULL};
94 static const char *const opt_name_top_field_first[] = {"top", NULL};
95 static const char *const opt_name_presets[] = {"pre", "apre", "vpre", "spre", NULL};
96 static const char *const opt_name_copy_initial_nonkeyframes[] = {"copyinkfr", NULL};
97 static const char *const opt_name_copy_prior_start[] = {"copypriorss", NULL};
98 static const char *const opt_name_filters[] = {"filter", "af", "vf", NULL};
99 static const char *const opt_name_filter_scripts[] = {"filter_script", NULL};
100 static const char *const opt_name_reinit_filters[] = {"reinit_filter", NULL};
101 static const char *const opt_name_fix_sub_duration[] = {"fix_sub_duration", NULL};
102 static const char *const opt_name_canvas_sizes[] = {"canvas_size", NULL};
103 static const char *const opt_name_pass[] = {"pass", NULL};
104 static const char *const opt_name_passlogfiles[] = {"passlogfile", NULL};
105 static const char *const opt_name_max_muxing_queue_size[] = {"max_muxing_queue_size", NULL};
106 static const char *const opt_name_muxing_queue_data_threshold[] = {"muxing_queue_data_threshold", NULL};
107 static const char *const opt_name_guess_layout_max[] = {"guess_layout_max", NULL};
108 static const char *const opt_name_apad[] = {"apad", NULL};
109 static const char *const opt_name_discard[] = {"discard", NULL};
110 static const char *const opt_name_disposition[] = {"disposition", NULL};
111 static const char *const opt_name_time_bases[] = {"time_base", NULL};
112 static const char *const opt_name_enc_time_bases[] = {"enc_time_base", 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 
151 const HWAccel hwaccels[] = {
152 #if CONFIG_VIDEOTOOLBOX
153  { "videotoolbox", videotoolbox_init, HWACCEL_VIDEOTOOLBOX, AV_PIX_FMT_VIDEOTOOLBOX },
154 #endif
155 #if CONFIG_LIBMFX
156  { "qsv", qsv_init, HWACCEL_QSV, AV_PIX_FMT_QSV },
157 #endif
158  { 0 },
159 };
161 
162 __thread char *vstats_filename;
163 __thread char *sdp_filename;
164 
165 __thread float audio_drift_threshold = 0.1;
166 __thread float dts_delta_threshold = 10;
167 __thread float dts_error_threshold = 3600*30;
168 
169 __thread int audio_volume = 256;
170 __thread int audio_sync_method = 0;
172 __thread float frame_drop_threshold = 0;
173 __thread int do_deinterlace = 0;
174 __thread int do_benchmark = 0;
175 __thread int do_benchmark_all = 0;
176 __thread int do_hex_dump = 0;
177 __thread int do_pkt_dump = 0;
178 __thread int copy_ts = 0;
179 __thread int start_at_zero = 0;
180 __thread int copy_tb = -1;
181 __thread int debug_ts = 0;
182 __thread int exit_on_error = 0;
183 __thread int abort_on_flags = 0;
184 __thread int print_stats = -1;
185 __thread int qp_hist = 0;
186 __thread int stdin_interaction = 1;
187 __thread int frame_bits_per_raw_sample = 0;
188 __thread float max_error_rate = 2.0/3;
189 __thread int filter_nbthreads = 0;
190 __thread int filter_complex_nbthreads = 0;
191 __thread int vstats_version = 2;
192 __thread int auto_conversion_filters = 1;
193 __thread int64_t stats_period = 500000;
194 
195 
196 __thread int intra_only = 0;
197 __thread int file_overwrite = 0;
198 __thread int no_file_overwrite = 0;
199 __thread int do_psnr = 0;
200 __thread int input_sync;
202 __thread int ignore_unknown_streams = 0;
203 __thread int copy_unknown_streams = 0;
204 __thread int find_stream_info = 1;
205 
206 extern __thread OptionDef *ffmpeg_options;
207 
209 {
210  const OptionDef *po = ffmpeg_options;
211  int i;
212 
213  /* all OPT_SPEC and OPT_STRING can be freed in generic way */
214  while (po->name) {
215  void *dst = (uint8_t*)o + po->u.off;
216 
217  if (po->flags & OPT_SPEC) {
218  SpecifierOpt **so = dst;
219  int i, *count = (int*)(so + 1);
220  for (i = 0; i < *count; i++) {
221  av_freep(&(*so)[i].specifier);
222  if (po->flags & OPT_STRING)
223  av_freep(&(*so)[i].u.str);
224  }
225  av_freep(so);
226  *count = 0;
227  } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
228  av_freep(dst);
229  po++;
230  }
231 
232  for (i = 0; i < o->nb_stream_maps; i++)
233  av_freep(&o->stream_maps[i].linklabel);
234  av_freep(&o->stream_maps);
235  av_freep(&o->audio_channel_maps);
236  av_freep(&o->streamid_map);
237  av_freep(&o->attachments);
238 }
239 
241 {
242  memset(o, 0, sizeof(*o));
243 
244  o->stop_time = INT64_MAX;
245  o->mux_max_delay = 0.7;
246  o->start_time = AV_NOPTS_VALUE;
247  o->start_time_eof = AV_NOPTS_VALUE;
248  o->recording_time = INT64_MAX;
249  o->limit_filesize = UINT64_MAX;
250  o->chapters_input_file = INT_MAX;
251  o->accurate_seek = 1;
252  o->thread_queue_size = -1;
253 }
254 
255 int show_hwaccels(void *optctx, const char *opt, const char *arg)
256 {
257  enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
258 
259  av_log(NULL, AV_LOG_STDERR, "Hardware acceleration methods:\n");
260  while ((type = av_hwdevice_iterate_types(type)) !=
261  AV_HWDEVICE_TYPE_NONE)
262  av_log(NULL, AV_LOG_STDERR, "%s\n", av_hwdevice_get_type_name(type));
263  av_log(NULL, AV_LOG_STDERR, "\n");
264  return 0;
265 }
266 
267 /* return a copy of the input with the stream specifiers removed from the keys */
268 AVDictionary *strip_specifiers(AVDictionary *dict)
269 {
270  AVDictionaryEntry *e = NULL;
271  AVDictionary *ret = NULL;
272 
273  while ((e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
274  char *p = strchr(e->key, ':');
275 
276  if (p)
277  *p = 0;
278  av_dict_set(&ret, e->key, e->value, 0);
279  if (p)
280  *p = ':';
281  }
282  return ret;
283 }
284 
285 int opt_abort_on(void *optctx, const char *opt, const char *arg)
286 {
287  const AVOption opts[] = {
288  { "abort_on" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, (double)INT64_MAX, .unit = "flags" },
289  { "empty_output" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT }, .unit = "flags" },
290  { "empty_output_stream", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM }, .unit = "flags" },
291  { NULL },
292  };
293  const AVClass class = {
294  .class_name = "",
295  .item_name = av_default_item_name,
296  .option = opts,
297  .version = LIBAVUTIL_VERSION_INT,
298  };
299  const AVClass *pclass = &class;
300 
301  return av_opt_eval_flags(&pclass, &opts[0], arg, &abort_on_flags);
302 }
303 
304 int opt_stats_period(void *optctx, const char *opt, const char *arg)
305 {
306  int64_t user_stats_period = parse_time_or_die(opt, arg, 1);
307 
308  if (user_stats_period <= 0) {
309  av_log(NULL, AV_LOG_ERROR, "stats_period %s must be positive.\n", arg);
310  return AVERROR(EINVAL);
311  }
312 
313  stats_period = user_stats_period;
314  av_log(NULL, AV_LOG_INFO, "ffmpeg stats and -progress period set to %s.\n", arg);
315 
316  return 0;
317 }
318 
319 int opt_sameq(void *optctx, const char *opt, const char *arg)
320 {
321  av_log(NULL, AV_LOG_ERROR, "Option '%s' was removed. "
322  "If you are looking for an option to preserve the quality (which is not "
323  "what -%s was for), use -qscale 0 or an equivalent quality factor option.\n",
324  opt, opt);
325  return AVERROR(EINVAL);
326 }
327 
328 int opt_video_channel(void *optctx, const char *opt, const char *arg)
329 {
330  av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
331  return opt_default(optctx, "channel", arg);
332 }
333 
334 int opt_video_standard(void *optctx, const char *opt, const char *arg)
335 {
336  av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
337  return opt_default(optctx, "standard", arg);
338 }
339 
340 int opt_audio_codec(void *optctx, const char *opt, const char *arg)
341 {
342  OptionsContext *o = optctx;
343  return parse_option(o, "codec:a", arg, ffmpeg_options);
344 }
345 
346 int opt_video_codec(void *optctx, const char *opt, const char *arg)
347 {
348  OptionsContext *o = optctx;
349  return parse_option(o, "codec:v", arg, ffmpeg_options);
350 }
351 
352 int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
353 {
354  OptionsContext *o = optctx;
355  return parse_option(o, "codec:s", arg, ffmpeg_options);
356 }
357 
358 int opt_data_codec(void *optctx, const char *opt, const char *arg)
359 {
360  OptionsContext *o = optctx;
361  return parse_option(o, "codec:d", arg, ffmpeg_options);
362 }
363 
364 int opt_map(void *optctx, const char *opt, const char *arg)
365 {
366  OptionsContext *o = optctx;
367  StreamMap *m = NULL;
368  int i, negative = 0, file_idx, disabled = 0;
369  int sync_file_idx = -1, sync_stream_idx = 0;
370  char *p, *sync;
371  char *map;
372  char *allow_unused;
373 
374  if (*arg == '-') {
375  negative = 1;
376  arg++;
377  }
378  map = av_strdup(arg);
379  if (!map)
380  return AVERROR(ENOMEM);
381 
382  /* parse sync stream first, just pick first matching stream */
383  if ((sync = strchr(map, ','))) {
384  *sync = 0;
385  sync_file_idx = strtol(sync + 1, &sync, 0);
386  if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
387  av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
388  exit_program(1);
389  }
390  if (*sync)
391  sync++;
392  for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
393  if (check_stream_specifier(input_files[sync_file_idx]->ctx,
394  input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
395  sync_stream_idx = i;
396  break;
397  }
398  if (i == input_files[sync_file_idx]->nb_streams) {
399  av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
400  "match any streams.\n", arg);
401  exit_program(1);
402  }
403  if (input_streams[input_files[sync_file_idx]->ist_index + sync_stream_idx]->user_set_discard == AVDISCARD_ALL) {
404  av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s matches a disabled input "
405  "stream.\n", arg);
406  exit_program(1);
407  }
408  }
409 
410 
411  if (map[0] == '[') {
412  /* this mapping refers to lavfi output */
413  const char *c = map + 1;
415  m = &o->stream_maps[o->nb_stream_maps - 1];
416  m->linklabel = av_get_token(&c, "]");
417  if (!m->linklabel) {
418  av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
419  exit_program(1);
420  }
421  } else {
422  if ((allow_unused = strchr(map, '?')))
423  *allow_unused = 0;
424  file_idx = strtol(map, &p, 0);
425  if (file_idx >= nb_input_files || file_idx < 0) {
426  av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
427  exit_program(1);
428  }
429  if (negative)
430  /* disable some already defined maps */
431  for (i = 0; i < o->nb_stream_maps; i++) {
432  m = &o->stream_maps[i];
433  if (file_idx == m->file_index &&
435  input_files[m->file_index]->ctx->streams[m->stream_index],
436  *p == ':' ? p + 1 : p) > 0)
437  m->disabled = 1;
438  }
439  else
440  for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
441  if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
442  *p == ':' ? p + 1 : p) <= 0)
443  continue;
444  if (input_streams[input_files[file_idx]->ist_index + i]->user_set_discard == AVDISCARD_ALL) {
445  disabled = 1;
446  continue;
447  }
449  m = &o->stream_maps[o->nb_stream_maps - 1];
450 
451  m->file_index = file_idx;
452  m->stream_index = i;
453 
454  if (sync_file_idx >= 0) {
455  m->sync_file_index = sync_file_idx;
456  m->sync_stream_index = sync_stream_idx;
457  } else {
458  m->sync_file_index = file_idx;
459  m->sync_stream_index = i;
460  }
461  }
462  }
463 
464  if (!m) {
465  if (allow_unused) {
466  av_log(NULL, AV_LOG_VERBOSE, "Stream map '%s' matches no streams; ignoring.\n", arg);
467  } else if (disabled) {
468  av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches disabled streams.\n"
469  "To ignore this, add a trailing '?' to the map.\n", arg);
470  exit_program(1);
471  } else {
472  av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n"
473  "To ignore this, add a trailing '?' to the map.\n", arg);
474  exit_program(1);
475  }
476  }
477 
478  av_freep(&map);
479  return 0;
480 }
481 
482 int opt_attach(void *optctx, const char *opt, const char *arg)
483 {
484  OptionsContext *o = optctx;
486  o->attachments[o->nb_attachments - 1] = arg;
487  return 0;
488 }
489 
490 int opt_map_channel(void *optctx, const char *opt, const char *arg)
491 {
492  OptionsContext *o = optctx;
493  int n;
494  AVStream *st;
495  AudioChannelMap *m;
496  char *allow_unused;
497  char *mapchan;
498  mapchan = av_strdup(arg);
499  if (!mapchan)
500  return AVERROR(ENOMEM);
501 
504 
505  /* muted channel syntax */
506  n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
507  if ((n == 1 || n == 3) && m->channel_idx == -1) {
508  m->file_idx = m->stream_idx = -1;
509  if (n == 1)
510  m->ofile_idx = m->ostream_idx = -1;
511  av_free(mapchan);
512  return 0;
513  }
514 
515  /* normal syntax */
516  n = sscanf(arg, "%d.%d.%d:%d.%d",
517  &m->file_idx, &m->stream_idx, &m->channel_idx,
518  &m->ofile_idx, &m->ostream_idx);
519 
520  if (n != 3 && n != 5) {
521  av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
522  "[file.stream.channel|-1][:syncfile:syncstream]\n");
523  exit_program(1);
524  }
525 
526  if (n != 5) // only file.stream.channel specified
527  m->ofile_idx = m->ostream_idx = -1;
528 
529  /* check input */
530  if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
531  av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
532  m->file_idx);
533  exit_program(1);
534  }
535  if (m->stream_idx < 0 ||
537  av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
538  m->file_idx, m->stream_idx);
539  exit_program(1);
540  }
541  st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
542  if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
543  av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
544  m->file_idx, m->stream_idx);
545  exit_program(1);
546  }
547  /* allow trailing ? to map_channel */
548  if ((allow_unused = strchr(mapchan, '?')))
549  *allow_unused = 0;
550  if (m->channel_idx < 0 || m->channel_idx >= st->codecpar->channels ||
552  if (allow_unused) {
553  av_log(NULL, AV_LOG_VERBOSE, "mapchan: invalid audio channel #%d.%d.%d\n",
554  m->file_idx, m->stream_idx, m->channel_idx);
555  } else {
556  av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n"
557  "To ignore this, add a trailing '?' to the map_channel.\n",
558  m->file_idx, m->stream_idx, m->channel_idx);
559  exit_program(1);
560  }
561 
562  }
563  av_free(mapchan);
564  return 0;
565 }
566 
567 int opt_sdp_file(void *optctx, const char *opt, const char *arg)
568 {
569  av_free(sdp_filename);
570  sdp_filename = av_strdup(arg);
571  return 0;
572 }
573 
574 #if CONFIG_VAAPI
575 int opt_vaapi_device(void *optctx, const char *opt, const char *arg)
576 {
577  const char *prefix = "vaapi:";
578  char *tmp;
579  int err;
580  tmp = av_asprintf("%s%s", prefix, arg);
581  if (!tmp)
582  return AVERROR(ENOMEM);
583  err = hw_device_init_from_string(tmp, NULL);
584  av_free(tmp);
585  return err;
586 }
587 #endif
588 
589 int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
590 {
591  if (!strcmp(arg, "list")) {
592  enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
593  av_log(NULL, AV_LOG_STDERR, "Supported hardware device types:\n");
594  while ((type = av_hwdevice_iterate_types(type)) !=
595  AV_HWDEVICE_TYPE_NONE)
596  av_log(NULL, AV_LOG_STDERR, "%s\n", av_hwdevice_get_type_name(type));
597  av_log(NULL, AV_LOG_STDERR, "\n");
598  exit_program(0);
599  } else {
600  return hw_device_init_from_string(arg, NULL);
601  }
602 }
603 
604 int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
605 {
606  if (filter_hw_device) {
607  av_log(NULL, AV_LOG_ERROR, "Only one filter device can be used.\n");
608  return AVERROR(EINVAL);
609  }
611  if (!filter_hw_device) {
612  av_log(NULL, AV_LOG_ERROR, "Invalid filter device %s.\n", arg);
613  return AVERROR(EINVAL);
614  }
615  return 0;
616 }
617 
625 void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
626 {
627  if (*arg) {
628  *type = *arg;
629  switch (*arg) {
630  case 'g':
631  break;
632  case 's':
633  if (*(++arg) && *arg != ':') {
634  av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
635  exit_program(1);
636  }
637  *stream_spec = *arg == ':' ? arg + 1 : "";
638  break;
639  case 'c':
640  case 'p':
641  if (*(++arg) == ':')
642  *index = strtol(++arg, NULL, 0);
643  break;
644  default:
645  av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
646  exit_program(1);
647  }
648  } else
649  *type = 'g';
650 }
651 
652 int fftools_copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
653 {
654  AVDictionary **meta_in = NULL;
655  AVDictionary **meta_out = NULL;
656  int i, ret = 0;
657  char type_in, type_out;
658  const char *istream_spec = NULL, *ostream_spec = NULL;
659  int idx_in = 0, idx_out = 0;
660 
661  parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
662  parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
663 
664  if (!ic) {
665  if (type_out == 'g' || !*outspec)
666  o->metadata_global_manual = 1;
667  if (type_out == 's' || !*outspec)
669  if (type_out == 'c' || !*outspec)
671  return 0;
672  }
673 
674  if (type_in == 'g' || type_out == 'g')
675  o->metadata_global_manual = 1;
676  if (type_in == 's' || type_out == 's')
678  if (type_in == 'c' || type_out == 'c')
680 
681  /* ic is NULL when just disabling automatic mappings */
682  if (!ic)
683  return 0;
684 
685 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
686  if ((index) < 0 || (index) >= (nb_elems)) {\
687  av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
688  (desc), (index));\
689  exit_program(1);\
690  }
691 
692 #define SET_DICT(type, meta, context, index)\
693  switch (type) {\
694  case 'g':\
695  meta = &context->metadata;\
696  break;\
697  case 'c':\
698  METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
699  meta = &context->chapters[index]->metadata;\
700  break;\
701  case 'p':\
702  METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
703  meta = &context->programs[index]->metadata;\
704  break;\
705  case 's':\
706  break; /* handled separately below */ \
707  default: av_assert0(0);\
708  }\
709 
710  SET_DICT(type_in, meta_in, ic, idx_in);
711  SET_DICT(type_out, meta_out, oc, idx_out);
712 
713  /* for input streams choose first matching stream */
714  if (type_in == 's') {
715  for (i = 0; i < ic->nb_streams; i++) {
716  if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
717  meta_in = &ic->streams[i]->metadata;
718  break;
719  } else if (ret < 0)
720  exit_program(1);
721  }
722  if (!meta_in) {
723  av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
724  exit_program(1);
725  }
726  }
727 
728  if (type_out == 's') {
729  for (i = 0; i < oc->nb_streams; i++) {
730  if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
731  meta_out = &oc->streams[i]->metadata;
732  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
733  } else if (ret < 0)
734  exit_program(1);
735  }
736  } else
737  av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
738 
739  return 0;
740 }
741 
742 int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
743 {
744  OptionsContext *o = optctx;
745  char buf[128];
746  int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
747  struct tm time = *gmtime((time_t*)&recording_timestamp);
748  if (!strftime(buf, sizeof(buf), "creation_time=%Y-%m-%dT%H:%M:%S%z", &time))
749  return -1;
750  parse_option(o, "metadata", buf, ffmpeg_options);
751 
752  av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
753  "tag instead.\n", opt);
754  return 0;
755 }
756 
757 AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
758 {
759  const AVCodecDescriptor *desc;
760  const char *codec_string = encoder ? "encoder" : "decoder";
761  AVCodec *codec;
762 
763  codec = encoder ?
764  avcodec_find_encoder_by_name(name) :
765  avcodec_find_decoder_by_name(name);
766 
767  if (!codec && (desc = avcodec_descriptor_get_by_name(name))) {
768  codec = encoder ? avcodec_find_encoder(desc->id) :
769  avcodec_find_decoder(desc->id);
770  if (codec)
771  av_log(NULL, AV_LOG_VERBOSE, "Matched %s '%s' for codec '%s'.\n",
772  codec_string, codec->name, desc->name);
773  }
774 
775  if (!codec) {
776  av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
777  exit_program(1);
778  }
779  if (codec->type != type) {
780  av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
781  exit_program(1);
782  }
783  return codec;
784 }
785 
786 AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
787 {
788  char *codec_name = NULL;
789 
790  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
791  if (codec_name) {
792  AVCodec *codec = find_codec_or_die(codec_name, st->codecpar->codec_type, 0);
793  st->codecpar->codec_id = codec->id;
794  return codec;
795  } else
796  return avcodec_find_decoder(st->codecpar->codec_id);
797 }
798 
799 /* Add all the streams from the given input file to the global
800  * list of input streams. */
801 void add_input_streams(OptionsContext *o, AVFormatContext *ic)
802 {
803  int i, ret;
804 
805  for (i = 0; i < ic->nb_streams; i++) {
806  AVStream *st = ic->streams[i];
807  AVCodecParameters *par = st->codecpar;
808  InputStream *ist = av_mallocz(sizeof(*ist));
809  char *framerate = NULL, *hwaccel_device = NULL;
810  const char *hwaccel = NULL;
811  char *hwaccel_output_format = NULL;
812  char *codec_tag = NULL;
813  char *next;
814  char *discard_str = NULL;
815  const AVClass *cc = avcodec_get_class();
816  const AVOption *discard_opt = av_opt_find(&cc, "skip_frame", NULL, 0, 0);
817 
818  if (!ist)
819  exit_program(1);
820 
822  input_streams[nb_input_streams - 1] = ist;
823 
824  ist->st = st;
825  ist->file_index = nb_input_files;
826  ist->discard = 1;
827  st->discard = AVDISCARD_ALL;
828  ist->nb_samples = 0;
829  ist->min_pts = INT64_MAX;
830  ist->max_pts = INT64_MIN;
831 
832  ist->ts_scale = 1.0;
833  MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
834 
835  ist->autorotate = 1;
836  MATCH_PER_STREAM_OPT(autorotate, i, ist->autorotate, ic, st);
837 
838  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
839  if (codec_tag) {
840  uint32_t tag = strtol(codec_tag, &next, 0);
841  if (*next)
842  tag = AV_RL32(codec_tag);
843  st->codecpar->codec_tag = tag;
844  }
845 
846  ist->dec = choose_decoder(o, ic, st);
847  ist->decoder_opts = filter_codec_opts(o->g->codec_opts, ist->st->codecpar->codec_id, ic, st, ist->dec);
848 
849  ist->reinit_filters = -1;
850  MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);
851 
852  MATCH_PER_STREAM_OPT(discard, str, discard_str, ic, st);
853  ist->user_set_discard = AVDISCARD_NONE;
854 
855  if ((o->video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ||
856  (o->audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ||
857  (o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) ||
858  (o->data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA))
859  ist->user_set_discard = AVDISCARD_ALL;
860 
861  if (discard_str && av_opt_eval_int(&cc, discard_opt, discard_str, &ist->user_set_discard) < 0) {
862  av_log(NULL, AV_LOG_ERROR, "Error parsing discard %s.\n",
863  discard_str);
864  exit_program(1);
865  }
866 
867  ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;
868 
869  ist->dec_ctx = avcodec_alloc_context3(ist->dec);
870  if (!ist->dec_ctx) {
871  av_log(NULL, AV_LOG_ERROR, "Error allocating the decoder context.\n");
872  exit_program(1);
873  }
874 
875  ret = avcodec_parameters_to_context(ist->dec_ctx, par);
876  if (ret < 0) {
877  av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
878  exit_program(1);
879  }
880 
881  if (o->bitexact)
882  ist->dec_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
883 
884  switch (par->codec_type) {
885  case AVMEDIA_TYPE_VIDEO:
886  if(!ist->dec)
887  ist->dec = avcodec_find_decoder(par->codec_id);
888 
889  // avformat_find_stream_info() doesn't set this for us anymore.
890  ist->dec_ctx->framerate = st->avg_frame_rate;
891 
892  MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
893  if (framerate && av_parse_video_rate(&ist->framerate,
894  framerate) < 0) {
895  av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
896  framerate);
897  exit_program(1);
898  }
899 
900  ist->top_field_first = -1;
901  MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
902 
903  MATCH_PER_STREAM_OPT(hwaccels, str, hwaccel, ic, st);
904  MATCH_PER_STREAM_OPT(hwaccel_output_formats, str,
905  hwaccel_output_format, ic, st);
906 
907  if (!hwaccel_output_format && hwaccel && !strcmp(hwaccel, "cuvid")) {
908  av_log(NULL, AV_LOG_WARNING,
909  "WARNING: defaulting hwaccel_output_format to cuda for compatibility "
910  "with old commandlines. This behaviour is DEPRECATED and will be removed "
911  "in the future. Please explicitly set \"-hwaccel_output_format cuda\".\n");
912  ist->hwaccel_output_format = AV_PIX_FMT_CUDA;
913  } else if (hwaccel_output_format) {
914  ist->hwaccel_output_format = av_get_pix_fmt(hwaccel_output_format);
915  if (ist->hwaccel_output_format == AV_PIX_FMT_NONE) {
916  av_log(NULL, AV_LOG_FATAL, "Unrecognised hwaccel output "
917  "format: %s", hwaccel_output_format);
918  }
919  } else {
920  ist->hwaccel_output_format = AV_PIX_FMT_NONE;
921  }
922 
923  if (hwaccel) {
924  // The NVDEC hwaccels use a CUDA device, so remap the name here.
925  if (!strcmp(hwaccel, "nvdec") || !strcmp(hwaccel, "cuvid"))
926  hwaccel = "cuda";
927 
928  if (!strcmp(hwaccel, "none"))
929  ist->hwaccel_id = HWACCEL_NONE;
930  else if (!strcmp(hwaccel, "auto"))
931  ist->hwaccel_id = HWACCEL_AUTO;
932  else {
933  enum AVHWDeviceType type;
934  int i;
935  for (i = 0; hwaccels[i].name; i++) {
936  if (!strcmp(hwaccels[i].name, hwaccel)) {
937  ist->hwaccel_id = hwaccels[i].id;
938  break;
939  }
940  }
941 
942  if (!ist->hwaccel_id) {
943  type = av_hwdevice_find_type_by_name(hwaccel);
944  if (type != AV_HWDEVICE_TYPE_NONE) {
946  ist->hwaccel_device_type = type;
947  }
948  }
949 
950  if (!ist->hwaccel_id) {
951  av_log(NULL, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",
952  hwaccel);
953  av_log(NULL, AV_LOG_FATAL, "Supported hwaccels: ");
954  type = AV_HWDEVICE_TYPE_NONE;
955  while ((type = av_hwdevice_iterate_types(type)) !=
956  AV_HWDEVICE_TYPE_NONE)
957  av_log(NULL, AV_LOG_FATAL, "%s ",
958  av_hwdevice_get_type_name(type));
959  av_log(NULL, AV_LOG_FATAL, "\n");
960  exit_program(1);
961  }
962  }
963  }
964 
965  MATCH_PER_STREAM_OPT(hwaccel_devices, str, hwaccel_device, ic, st);
966  if (hwaccel_device) {
967  ist->hwaccel_device = av_strdup(hwaccel_device);
968  if (!ist->hwaccel_device)
969  exit_program(1);
970  }
971 
972  ist->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
973 
974  break;
975  case AVMEDIA_TYPE_AUDIO:
976  ist->guess_layout_max = INT_MAX;
977  MATCH_PER_STREAM_OPT(guess_layout_max, i, ist->guess_layout_max, ic, st);
979  break;
980  case AVMEDIA_TYPE_DATA:
981  case AVMEDIA_TYPE_SUBTITLE: {
982  char *canvas_size = NULL;
983  if(!ist->dec)
984  ist->dec = avcodec_find_decoder(par->codec_id);
985  MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);
986  MATCH_PER_STREAM_OPT(canvas_sizes, str, canvas_size, ic, st);
987  if (canvas_size &&
988  av_parse_video_size(&ist->dec_ctx->width, &ist->dec_ctx->height, canvas_size) < 0) {
989  av_log(NULL, AV_LOG_FATAL, "Invalid canvas size: %s.\n", canvas_size);
990  exit_program(1);
991  }
992  break;
993  }
994  case AVMEDIA_TYPE_ATTACHMENT:
995  case AVMEDIA_TYPE_UNKNOWN:
996  break;
997  default:
998  abort();
999  }
1000 
1001  ret = avcodec_parameters_from_context(par, ist->dec_ctx);
1002  if (ret < 0) {
1003  av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
1004  exit_program(1);
1005  }
1006  }
1007 }
1008 
1009 void assert_file_overwrite(const char *filename)
1010 {
1011  const char *proto_name = avio_find_protocol_name(filename);
1012 
1014  fprintf(stderr, "Error, both -y and -n supplied. Exiting.\n");
1015  exit_program(1);
1016  }
1017 
1018  if (!file_overwrite) {
1019  if (proto_name && !strcmp(proto_name, "file") && avio_check(filename, 0) == 0) {
1021  fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
1022  fflush(stderr);
1023  term_exit();
1024  signal(SIGINT, SIG_DFL);
1025  if (!read_yesno()) {
1026  av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
1027  exit_program(1);
1028  }
1029  term_init();
1030  }
1031  else {
1032  av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
1033  exit_program(1);
1034  }
1035  }
1036  }
1037 
1038  if (proto_name && !strcmp(proto_name, "file")) {
1039  for (int i = 0; i < nb_input_files; i++) {
1040  InputFile *file = input_files[i];
1041  if (file->ctx->iformat->flags & AVFMT_NOFILE)
1042  continue;
1043  if (!strcmp(filename, file->ctx->url)) {
1044  av_log(NULL, AV_LOG_FATAL, "Output %s same as Input #%d - exiting\n", filename, i);
1045  av_log(NULL, AV_LOG_WARNING, "FFmpeg cannot edit existing files in-place.\n");
1046  exit_program(1);
1047  }
1048  }
1049  }
1050 }
1051 
1052 void dump_attachment(AVStream *st, const char *filename)
1053 {
1054  int ret;
1055  AVIOContext *out = NULL;
1056  AVDictionaryEntry *e;
1057 
1058  if (!st->codecpar->extradata_size) {
1059  av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
1060  nb_input_files - 1, st->index);
1061  return;
1062  }
1063  if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
1064  filename = e->value;
1065  if (!*filename) {
1066  av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
1067  "in stream #%d:%d.\n", nb_input_files - 1, st->index);
1068  exit_program(1);
1069  }
1070 
1071  assert_file_overwrite(filename);
1072 
1073  if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
1074  av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
1075  filename);
1076  exit_program(1);
1077  }
1078 
1079  avio_write(out, st->codecpar->extradata, st->codecpar->extradata_size);
1080  avio_flush(out);
1081  avio_close(out);
1082 }
1083 
1084 int open_input_file(OptionsContext *o, const char *filename)
1085 {
1086  InputFile *f;
1087  AVFormatContext *ic;
1088  AVInputFormat *file_iformat = NULL;
1089  int err, i, ret;
1090  int64_t timestamp;
1091  AVDictionary *unused_opts = NULL;
1092  AVDictionaryEntry *e = NULL;
1093  char * video_codec_name = NULL;
1094  char * audio_codec_name = NULL;
1095  char *subtitle_codec_name = NULL;
1096  char * data_codec_name = NULL;
1097  int scan_all_pmts_set = 0;
1098 
1099  if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
1100  o->stop_time = INT64_MAX;
1101  av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
1102  }
1103 
1104  if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
1105  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
1106  if (o->stop_time <= start_time) {
1107  av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
1108  exit_program(1);
1109  } else {
1110  o->recording_time = o->stop_time - start_time;
1111  }
1112  }
1113 
1114  if (o->format) {
1115  if (!(file_iformat = av_find_input_format(o->format))) {
1116  av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
1117  exit_program(1);
1118  }
1119  }
1120 
1121  if (!strcmp(filename, "-"))
1122  filename = "pipe:";
1123 
1124  stdin_interaction &= strncmp(filename, "pipe:", 5) &&
1125  strcmp(filename, "/dev/stdin");
1126 
1127  /* get default parameters from command line */
1128  ic = avformat_alloc_context();
1129  if (!ic) {
1130  print_error(filename, AVERROR(ENOMEM));
1131  exit_program(1);
1132  }
1133  if (o->nb_audio_sample_rate) {
1134  av_dict_set_int(&o->g->format_opts, "sample_rate", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i, 0);
1135  }
1136  if (o->nb_audio_channels) {
1137  /* because we set audio_channels based on both the "ac" and
1138  * "channel_layout" options, we need to check that the specified
1139  * demuxer actually has the "channels" option before setting it */
1140  if (file_iformat && file_iformat->priv_class &&
1141  av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
1142  AV_OPT_SEARCH_FAKE_OBJ)) {
1143  av_dict_set_int(&o->g->format_opts, "channels", o->audio_channels[o->nb_audio_channels - 1].u.i, 0);
1144  }
1145  }
1146  if (o->nb_frame_rates) {
1147  /* set the format-level framerate option;
1148  * this is important for video grabbers, e.g. x11 */
1149  if (file_iformat && file_iformat->priv_class &&
1150  av_opt_find(&file_iformat->priv_class, "framerate", NULL, 0,
1151  AV_OPT_SEARCH_FAKE_OBJ)) {
1152  av_dict_set(&o->g->format_opts, "framerate",
1153  o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
1154  }
1155  }
1156  if (o->nb_frame_sizes) {
1157  av_dict_set(&o->g->format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
1158  }
1159  if (o->nb_frame_pix_fmts)
1160  av_dict_set(&o->g->format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
1161 
1162  MATCH_PER_TYPE_OPT(codec_names, str, video_codec_name, ic, "v");
1163  MATCH_PER_TYPE_OPT(codec_names, str, audio_codec_name, ic, "a");
1164  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, ic, "s");
1165  MATCH_PER_TYPE_OPT(codec_names, str, data_codec_name, ic, "d");
1166 
1167  if (video_codec_name)
1168  ic->video_codec = find_codec_or_die(video_codec_name , AVMEDIA_TYPE_VIDEO , 0);
1169  if (audio_codec_name)
1170  ic->audio_codec = find_codec_or_die(audio_codec_name , AVMEDIA_TYPE_AUDIO , 0);
1171  if (subtitle_codec_name)
1172  ic->subtitle_codec = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0);
1173  if (data_codec_name)
1174  ic->data_codec = find_codec_or_die(data_codec_name , AVMEDIA_TYPE_DATA , 0);
1175 
1176  ic->video_codec_id = video_codec_name ? ic->video_codec->id : AV_CODEC_ID_NONE;
1177  ic->audio_codec_id = audio_codec_name ? ic->audio_codec->id : AV_CODEC_ID_NONE;
1178  ic->subtitle_codec_id = subtitle_codec_name ? ic->subtitle_codec->id : AV_CODEC_ID_NONE;
1179  ic->data_codec_id = data_codec_name ? ic->data_codec->id : AV_CODEC_ID_NONE;
1180 
1181  ic->flags |= AVFMT_FLAG_NONBLOCK;
1182  if (o->bitexact)
1183  ic->flags |= AVFMT_FLAG_BITEXACT;
1184  ic->interrupt_callback = int_cb;
1185 
1186  if (!av_dict_get(o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
1187  av_dict_set(&o->g->format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
1188  scan_all_pmts_set = 1;
1189  }
1190  /* open the input file with generic avformat function */
1191  err = avformat_open_input(&ic, filename, file_iformat, &o->g->format_opts);
1192  if (err < 0) {
1193  print_error(filename, err);
1194  if (err == AVERROR_PROTOCOL_NOT_FOUND)
1195  av_log(NULL, AV_LOG_ERROR, "Did you mean file:%s?\n", filename);
1196  exit_program(1);
1197  }
1198  if (scan_all_pmts_set)
1199  av_dict_set(&o->g->format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
1202 
1203  /* apply forced codec ids */
1204  for (i = 0; i < ic->nb_streams; i++)
1205  choose_decoder(o, ic, ic->streams[i]);
1206 
1207  if (find_stream_info) {
1208  AVDictionary **opts = setup_find_stream_info_opts(ic, o->g->codec_opts);
1209  int orig_nb_streams = ic->nb_streams;
1210 
1211  /* If not enough info to get the stream parameters, we decode the
1212  first frames to get it. (used in mpeg case for example) */
1213  ret = avformat_find_stream_info(ic, opts);
1214 
1215  for (i = 0; i < orig_nb_streams; i++)
1216  av_dict_free(&opts[i]);
1217  av_freep(&opts);
1218 
1219  if (ret < 0) {
1220  av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
1221  if (ic->nb_streams == 0) {
1222  avformat_close_input(&ic);
1223  exit_program(1);
1224  }
1225  }
1226  }
1227 
1228  if (o->start_time != AV_NOPTS_VALUE && o->start_time_eof != AV_NOPTS_VALUE) {
1229  av_log(NULL, AV_LOG_WARNING, "Cannot use -ss and -sseof both, using -ss for %s\n", filename);
1230  o->start_time_eof = AV_NOPTS_VALUE;
1231  }
1232 
1233  if (o->start_time_eof != AV_NOPTS_VALUE) {
1234  if (o->start_time_eof >= 0) {
1235  av_log(NULL, AV_LOG_ERROR, "-sseof value must be negative; aborting\n");
1236  exit_program(1);
1237  }
1238  if (ic->duration > 0) {
1239  o->start_time = o->start_time_eof + ic->duration;
1240  if (o->start_time < 0) {
1241  av_log(NULL, AV_LOG_WARNING, "-sseof value seeks to before start of file %s; ignored\n", filename);
1242  o->start_time = AV_NOPTS_VALUE;
1243  }
1244  } else
1245  av_log(NULL, AV_LOG_WARNING, "Cannot use -sseof, duration of %s not known\n", filename);
1246  }
1247  timestamp = (o->start_time == AV_NOPTS_VALUE) ? 0 : o->start_time;
1248  /* add the stream start time */
1249  if (!o->seek_timestamp && ic->start_time != AV_NOPTS_VALUE)
1250  timestamp += ic->start_time;
1251 
1252  /* if seeking requested, we execute it */
1253  if (o->start_time != AV_NOPTS_VALUE) {
1254  int64_t seek_timestamp = timestamp;
1255 
1256  if (!(ic->iformat->flags & AVFMT_SEEK_TO_PTS)) {
1257  int dts_heuristic = 0;
1258  for (i=0; i<ic->nb_streams; i++) {
1259  const AVCodecParameters *par = ic->streams[i]->codecpar;
1260  if (par->video_delay) {
1261  dts_heuristic = 1;
1262  break;
1263  }
1264  }
1265  if (dts_heuristic) {
1266  seek_timestamp -= 3*AV_TIME_BASE / 23;
1267  }
1268  }
1269  ret = avformat_seek_file(ic, -1, INT64_MIN, seek_timestamp, seek_timestamp, 0);
1270  if (ret < 0) {
1271  av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
1272  filename, (double)timestamp / AV_TIME_BASE);
1273  }
1274  }
1275 
1276  /* update the current parameters so that they match the one of the input stream */
1277  add_input_streams(o, ic);
1278 
1279  /* dump the file content */
1280  av_dump_format(ic, nb_input_files, filename, 0);
1281 
1283  f = av_mallocz(sizeof(*f));
1284  if (!f)
1285  exit_program(1);
1286  input_files[nb_input_files - 1] = f;
1287 
1288  f->ctx = ic;
1289  f->ist_index = nb_input_streams - ic->nb_streams;
1290  f->start_time = o->start_time;
1293  f->ts_offset = o->input_ts_offset - (copy_ts ? (start_at_zero && ic->start_time != AV_NOPTS_VALUE ? ic->start_time : 0) : timestamp);
1294  f->nb_streams = ic->nb_streams;
1295  f->rate_emu = o->rate_emu;
1296  f->accurate_seek = o->accurate_seek;
1297  f->loop = o->loop;
1298  f->duration = 0;
1299  f->time_base = (AVRational){ 1, 1 };
1300 #if HAVE_THREADS
1301  f->thread_queue_size = o->thread_queue_size;
1302 #endif
1303 
1304  /* check if all codec options have been used */
1305  unused_opts = strip_specifiers(o->g->codec_opts);
1306  for (i = f->ist_index; i < nb_input_streams; i++) {
1307  e = NULL;
1308  while ((e = av_dict_get(input_streams[i]->decoder_opts, "", e,
1309  AV_DICT_IGNORE_SUFFIX)))
1310  av_dict_set(&unused_opts, e->key, NULL, 0);
1311  }
1312 
1313  e = NULL;
1314  while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
1315  const AVClass *class = avcodec_get_class();
1316  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
1317  AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
1318  const AVClass *fclass = avformat_get_class();
1319  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
1320  AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
1321  if (!option || foption)
1322  continue;
1323 
1324 
1325  if (!(option->flags & AV_OPT_FLAG_DECODING_PARAM)) {
1326  av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
1327  "input file #%d (%s) is not a decoding option.\n", e->key,
1328  option->help ? option->help : "", nb_input_files - 1,
1329  filename);
1330  exit_program(1);
1331  }
1332 
1333  av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
1334  "input file #%d (%s) has not been used for any stream. The most "
1335  "likely reason is either wrong type (e.g. a video option with "
1336  "no video streams) or that it is a private option of some decoder "
1337  "which was not actually used for any stream.\n", e->key,
1338  option->help ? option->help : "", nb_input_files - 1, filename);
1339  }
1340  av_dict_free(&unused_opts);
1341 
1342  for (i = 0; i < o->nb_dump_attachment; i++) {
1343  int j;
1344 
1345  for (j = 0; j < ic->nb_streams; j++) {
1346  AVStream *st = ic->streams[j];
1347 
1348  if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
1349  dump_attachment(st, o->dump_attachment[i].u.str);
1350  }
1351  }
1352 
1354 
1355  return 0;
1356 }
1357 
1358 uint8_t *get_line(AVIOContext *s)
1359 {
1360  AVIOContext *line;
1361  uint8_t *buf;
1362  char c;
1363 
1364  if (avio_open_dyn_buf(&line) < 0) {
1365  av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
1366  exit_program(1);
1367  }
1368 
1369  while ((c = avio_r8(s)) && c != '\n')
1370  avio_w8(line, c);
1371  avio_w8(line, 0);
1372  avio_close_dyn_buf(line, &buf);
1373 
1374  return buf;
1375 }
1376 
1377 int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
1378 {
1379  int i, ret = -1;
1380  char filename[1000];
1381  const char *base[3] = { getenv("AVCONV_DATADIR"),
1382  getenv("HOME"),
1383  AVCONV_DATADIR,
1384  };
1385 
1386  for (i = 0; i < FF_ARRAY_ELEMS(base) && ret < 0; i++) {
1387  if (!base[i])
1388  continue;
1389  if (codec_name) {
1390  snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
1391  i != 1 ? "" : "/.avconv", codec_name, preset_name);
1392  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1393  }
1394  if (ret < 0) {
1395  snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
1396  i != 1 ? "" : "/.avconv", preset_name);
1397  ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
1398  }
1399  }
1400  return ret;
1401 }
1402 
1403 int choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
1404 {
1405  enum AVMediaType type = ost->st->codecpar->codec_type;
1406  char *codec_name = NULL;
1407 
1408  if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO || type == AVMEDIA_TYPE_SUBTITLE) {
1409  MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
1410  if (!codec_name) {
1411  ost->st->codecpar->codec_id = av_guess_codec(s->oformat, NULL, s->url,
1412  NULL, ost->st->codecpar->codec_type);
1413  ost->enc = avcodec_find_encoder(ost->st->codecpar->codec_id);
1414  if (!ost->enc) {
1415  av_log(NULL, AV_LOG_FATAL, "Automatic encoder selection failed for "
1416  "output stream #%d:%d. Default encoder for format %s (codec %s) is "
1417  "probably disabled. Please choose an encoder manually.\n",
1418  ost->file_index, ost->index, s->oformat->name,
1419  avcodec_get_name(ost->st->codecpar->codec_id));
1420  return AVERROR_ENCODER_NOT_FOUND;
1421  }
1422  } else if (!strcmp(codec_name, "copy"))
1423  ost->stream_copy = 1;
1424  else {
1425  ost->enc = find_codec_or_die(codec_name, ost->st->codecpar->codec_type, 1);
1426  ost->st->codecpar->codec_id = ost->enc->id;
1427  }
1428  ost->encoding_needed = !ost->stream_copy;
1429  } else {
1430  /* no encoding supported for other media types */
1431  ost->stream_copy = 1;
1432  ost->encoding_needed = 0;
1433  }
1434 
1435  return 0;
1436 }
1437 
1438 OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
1439 {
1440  OutputStream *ost;
1441  AVStream *st = avformat_new_stream(oc, NULL);
1442  int idx = oc->nb_streams - 1, ret = 0;
1443  const char *bsfs = NULL, *time_base = NULL;
1444  char *next, *codec_tag = NULL;
1445  double qscale = -1;
1446  int i;
1447 
1448  if (!st) {
1449  av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
1450  exit_program(1);
1451  }
1452 
1453  if (oc->nb_streams - 1 < o->nb_streamid_map)
1454  st->id = o->streamid_map[oc->nb_streams - 1];
1455 
1457  if (!(ost = av_mallocz(sizeof(*ost))))
1458  exit_program(1);
1459  output_streams[nb_output_streams - 1] = ost;
1460 
1461  ost->file_index = nb_output_files - 1;
1462  ost->index = idx;
1463  ost->st = st;
1464  ost->forced_kf_ref_pts = AV_NOPTS_VALUE;
1465  st->codecpar->codec_type = type;
1466 
1467  ret = choose_encoder(o, oc, ost);
1468  if (ret < 0) {
1469  av_log(NULL, AV_LOG_FATAL, "Error selecting an encoder for stream "
1470  "%d:%d\n", ost->file_index, ost->index);
1471  exit_program(1);
1472  }
1473 
1474  ost->enc_ctx = avcodec_alloc_context3(ost->enc);
1475  if (!ost->enc_ctx) {
1476  av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding context.\n");
1477  exit_program(1);
1478  }
1479  ost->enc_ctx->codec_type = type;
1480 
1481  ost->ref_par = avcodec_parameters_alloc();
1482  if (!ost->ref_par) {
1483  av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding parameters.\n");
1484  exit_program(1);
1485  }
1486 
1487  if (ost->enc) {
1488  AVIOContext *s = NULL;
1489  char *buf = NULL, *arg = NULL, *preset = NULL;
1490 
1491  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, ost->enc->id, oc, st, ost->enc);
1492 
1493  MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
1494  ost->autoscale = 1;
1495  MATCH_PER_STREAM_OPT(autoscale, i, ost->autoscale, oc, st);
1496  if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
1497  do {
1498  buf = get_line(s);
1499  if (!buf[0] || buf[0] == '#') {
1500  av_free(buf);
1501  continue;
1502  }
1503  if (!(arg = strchr(buf, '='))) {
1504  av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
1505  exit_program(1);
1506  }
1507  *arg++ = 0;
1508  av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);
1509  av_free(buf);
1510  } while (!s->eof_reached);
1511  avio_closep(&s);
1512  }
1513  if (ret) {
1514  av_log(NULL, AV_LOG_FATAL,
1515  "Preset %s specified for stream %d:%d, but could not be opened.\n",
1516  preset, ost->file_index, ost->index);
1517  exit_program(1);
1518  }
1519  } else {
1520  ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);
1521  }
1522 
1523 
1524  if (o->bitexact)
1525  ost->enc_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
1526 
1527  MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);
1528  if (time_base) {
1529  AVRational q;
1530  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1531  q.num <= 0 || q.den <= 0) {
1532  av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1533  exit_program(1);
1534  }
1535  st->time_base = q;
1536  }
1537 
1538  MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);
1539  if (time_base) {
1540  AVRational q;
1541  if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||
1542  q.den <= 0) {
1543  av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);
1544  exit_program(1);
1545  }
1546  ost->enc_timebase = q;
1547  }
1548 
1549  ost->max_frames = INT64_MAX;
1550  MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
1551  for (i = 0; i<o->nb_max_frames; i++) {
1552  char *p = o->max_frames[i].specifier;
1553  if (!*p && type != AVMEDIA_TYPE_VIDEO) {
1554  av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");
1555  break;
1556  }
1557  }
1558 
1559  ost->copy_prior_start = -1;
1560  MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);
1561 
1562  MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);
1563  if (bsfs && *bsfs) {
1564  ret = av_bsf_list_parse_str(bsfs, &ost->bsf_ctx);
1565  if (ret < 0) {
1566  av_log(NULL, AV_LOG_ERROR, "Error parsing bitstream filter sequence '%s': %s\n", bsfs, av_err2str(ret));
1567  exit_program(1);
1568  }
1569  }
1570 
1571  MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
1572  if (codec_tag) {
1573  uint32_t tag = strtol(codec_tag, &next, 0);
1574  if (*next)
1575  tag = AV_RL32(codec_tag);
1576  ost->st->codecpar->codec_tag =
1577  ost->enc_ctx->codec_tag = tag;
1578  }
1579 
1580  MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
1581  if (qscale >= 0) {
1582  ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;
1583  ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;
1584  }
1585 
1586  MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);
1587  ost->disposition = av_strdup(ost->disposition);
1588 
1589  ost->max_muxing_queue_size = 128;
1590  MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ost->max_muxing_queue_size, oc, st);
1591  ost->max_muxing_queue_size *= sizeof(AVPacket);
1592 
1593  ost->muxing_queue_data_size = 0;
1594 
1595  ost->muxing_queue_data_threshold = 50*1024*1024;
1596  MATCH_PER_STREAM_OPT(muxing_queue_data_threshold, i, ost->muxing_queue_data_threshold, oc, st);
1597 
1598  if (oc->oformat->flags & AVFMT_GLOBALHEADER)
1599  ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1600 
1601  av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);
1602 
1603  av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);
1604  if (ost->enc && av_get_exact_bits_per_sample(ost->enc->id) == 24)
1605  av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);
1606 
1607  av_dict_copy(&ost->resample_opts, o->g->resample_opts, 0);
1608 
1609  ost->source_index = source_index;
1610  if (source_index >= 0) {
1611  ost->sync_ist = input_streams[source_index];
1612  input_streams[source_index]->discard = 0;
1613  input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;
1614  }
1615  ost->last_mux_dts = AV_NOPTS_VALUE;
1616 
1617  ost->muxing_queue = av_fifo_alloc(8 * sizeof(AVPacket));
1618  if (!ost->muxing_queue)
1619  exit_program(1);
1620 
1621  return ost;
1622 }
1623 
1624 void parse_matrix_coeffs(uint16_t *dest, const char *str)
1625 {
1626  int i;
1627  const char *p = str;
1628  for (i = 0;; i++) {
1629  dest[i] = atoi(p);
1630  if (i == 63)
1631  break;
1632  p = strchr(p, ',');
1633  if (!p) {
1634  av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
1635  exit_program(1);
1636  }
1637  p++;
1638  }
1639 }
1640 
1641 /* read file contents into a string */
1642 uint8_t *fftools_read_file(const char *filename)
1643 {
1644  AVIOContext *pb = NULL;
1645  AVIOContext *dyn_buf = NULL;
1646  int ret = avio_open(&pb, filename, AVIO_FLAG_READ);
1647  uint8_t buf[1024], *str;
1648 
1649  if (ret < 0) {
1650  av_log(NULL, AV_LOG_ERROR, "Error opening file %s.\n", filename);
1651  return NULL;
1652  }
1653 
1654  ret = avio_open_dyn_buf(&dyn_buf);
1655  if (ret < 0) {
1656  avio_closep(&pb);
1657  return NULL;
1658  }
1659  while ((ret = avio_read(pb, buf, sizeof(buf))) > 0)
1660  avio_write(dyn_buf, buf, ret);
1661  avio_w8(dyn_buf, 0);
1662  avio_closep(&pb);
1663 
1664  ret = avio_close_dyn_buf(dyn_buf, &str);
1665  if (ret < 0)
1666  return NULL;
1667  return str;
1668 }
1669 
1670 char *get_ost_filters(OptionsContext *o, AVFormatContext *oc,
1671  OutputStream *ost)
1672 {
1673  AVStream *st = ost->st;
1674 
1675  if (ost->filters_script && ost->filters) {
1676  av_log(NULL, AV_LOG_ERROR, "Both -filter and -filter_script set for "
1677  "output stream #%d:%d.\n", nb_output_files, st->index);
1678  exit_program(1);
1679  }
1680 
1681  if (ost->filters_script)
1682  return fftools_read_file(ost->filters_script);
1683  else if (ost->filters)
1684  return av_strdup(ost->filters);
1685 
1686  return av_strdup(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ?
1687  "null" : "anull");
1688 }
1689 
1690 void check_streamcopy_filters(OptionsContext *o, AVFormatContext *oc,
1691  const OutputStream *ost, enum AVMediaType type)
1692 {
1693  if (ost->filters_script || ost->filters) {
1694  av_log(NULL, AV_LOG_ERROR,
1695  "%s '%s' was defined for %s output stream %d:%d but codec copy was selected.\n"
1696  "Filtering and streamcopy cannot be used together.\n",
1697  ost->filters ? "Filtergraph" : "Filtergraph script",
1698  ost->filters ? ost->filters : ost->filters_script,
1699  av_get_media_type_string(type), ost->file_index, ost->index);
1700  exit_program(1);
1701  }
1702 }
1703 
1704 OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1705 {
1706  AVStream *st;
1707  OutputStream *ost;
1708  AVCodecContext *video_enc;
1709  char *frame_rate = NULL, *max_frame_rate = NULL, *frame_aspect_ratio = NULL;
1710 
1711  ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
1712  st = ost->st;
1713  video_enc = ost->enc_ctx;
1714 
1715  MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
1716  if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
1717  av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
1718  exit_program(1);
1719  }
1720 
1721  MATCH_PER_STREAM_OPT(max_frame_rates, str, max_frame_rate, oc, st);
1722  if (max_frame_rate && av_parse_video_rate(&ost->max_frame_rate, max_frame_rate) < 0) {
1723  av_log(NULL, AV_LOG_FATAL, "Invalid maximum framerate value: %s\n", max_frame_rate);
1724  exit_program(1);
1725  }
1726 
1727  if (frame_rate && max_frame_rate) {
1728  av_log(NULL, AV_LOG_ERROR, "Only one of -fpsmax and -r can be set for a stream.\n");
1729  exit_program(1);
1730  }
1731 
1732  if ((frame_rate || max_frame_rate) &&
1734  av_log(NULL, AV_LOG_ERROR, "Using -vsync 0 and -r/-fpsmax can produce invalid output files\n");
1735 
1736  MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
1737  if (frame_aspect_ratio) {
1738  AVRational q;
1739  if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
1740  q.num <= 0 || q.den <= 0) {
1741  av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
1742  exit_program(1);
1743  }
1744  ost->frame_aspect_ratio = q;
1745  }
1746 
1747  MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1748  MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
1749 
1750  if (!ost->stream_copy) {
1751  const char *p = NULL;
1752  char *frame_size = NULL;
1753  char *frame_pix_fmt = NULL;
1754  char *intra_matrix = NULL, *inter_matrix = NULL;
1755  char *chroma_intra_matrix = NULL;
1756  int do_pass = 0;
1757  int i;
1758 
1759  MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
1760  if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
1761  av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
1762  exit_program(1);
1763  }
1764 
1765  video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
1766  MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
1767  if (frame_pix_fmt && *frame_pix_fmt == '+') {
1768  ost->keep_pix_fmt = 1;
1769  if (!*++frame_pix_fmt)
1770  frame_pix_fmt = NULL;
1771  }
1772  if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == AV_PIX_FMT_NONE) {
1773  av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
1774  exit_program(1);
1775  }
1776  st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
1777 
1778  if (intra_only)
1779  video_enc->gop_size = 0;
1780  MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
1781  if (intra_matrix) {
1782  if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
1783  av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1784  exit_program(1);
1785  }
1786  parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
1787  }
1788  MATCH_PER_STREAM_OPT(chroma_intra_matrices, str, chroma_intra_matrix, oc, st);
1789  if (chroma_intra_matrix) {
1790  uint16_t *p = av_mallocz(sizeof(*video_enc->chroma_intra_matrix) * 64);
1791  if (!p) {
1792  av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
1793  exit_program(1);
1794  }
1795  video_enc->chroma_intra_matrix = p;
1796  parse_matrix_coeffs(p, chroma_intra_matrix);
1797  }
1798  MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
1799  if (inter_matrix) {
1800  if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
1801  av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
1802  exit_program(1);
1803  }
1804  parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
1805  }
1806 
1807  MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
1808  for (i = 0; p; i++) {
1809  int start, end, q;
1810  int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
1811  if (e != 3) {
1812  av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
1813  exit_program(1);
1814  }
1815  video_enc->rc_override =
1816  av_realloc_array(video_enc->rc_override,
1817  i + 1, sizeof(RcOverride));
1818  if (!video_enc->rc_override) {
1819  av_log(NULL, AV_LOG_FATAL, "Could not (re)allocate memory for rc_override.\n");
1820  exit_program(1);
1821  }
1822  video_enc->rc_override[i].start_frame = start;
1823  video_enc->rc_override[i].end_frame = end;
1824  if (q > 0) {
1825  video_enc->rc_override[i].qscale = q;
1826  video_enc->rc_override[i].quality_factor = 1.0;
1827  }
1828  else {
1829  video_enc->rc_override[i].qscale = 0;
1830  video_enc->rc_override[i].quality_factor = -q/100.0;
1831  }
1832  p = strchr(p, '/');
1833  if (p) p++;
1834  }
1835  video_enc->rc_override_count = i;
1836 
1837  if (do_psnr)
1838  video_enc->flags|= AV_CODEC_FLAG_PSNR;
1839 
1840  /* two pass mode */
1841  MATCH_PER_STREAM_OPT(pass, i, do_pass, oc, st);
1842  if (do_pass) {
1843  if (do_pass & 1) {
1844  video_enc->flags |= AV_CODEC_FLAG_PASS1;
1845  av_dict_set(&ost->encoder_opts, "flags", "+pass1", AV_DICT_APPEND);
1846  }
1847  if (do_pass & 2) {
1848  video_enc->flags |= AV_CODEC_FLAG_PASS2;
1849  av_dict_set(&ost->encoder_opts, "flags", "+pass2", AV_DICT_APPEND);
1850  }
1851  }
1852 
1853  MATCH_PER_STREAM_OPT(passlogfiles, str, ost->logfile_prefix, oc, st);
1854  if (ost->logfile_prefix &&
1855  !(ost->logfile_prefix = av_strdup(ost->logfile_prefix)))
1856  exit_program(1);
1857 
1858  if (do_pass) {
1859  char logfilename[1024];
1860  FILE *f;
1861 
1862  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1863  ost->logfile_prefix ? ost->logfile_prefix :
1865  i);
1866  if (!strcmp(ost->enc->name, "libx264")) {
1867  av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
1868  } else {
1869  if (video_enc->flags & AV_CODEC_FLAG_PASS2) {
1870  char *logbuffer = fftools_read_file(logfilename);
1871 
1872  if (!logbuffer) {
1873  av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
1874  logfilename);
1875  exit_program(1);
1876  }
1877  video_enc->stats_in = logbuffer;
1878  }
1879  if (video_enc->flags & AV_CODEC_FLAG_PASS1) {
1880  f = av_fopen_utf8(logfilename, "wb");
1881  if (!f) {
1882  av_log(NULL, AV_LOG_FATAL,
1883  "Cannot write log file '%s' for pass-1 encoding: %s\n",
1884  logfilename, strerror(errno));
1885  exit_program(1);
1886  }
1887  ost->logfile = f;
1888  }
1889  }
1890  }
1891 
1892  MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
1893  if (ost->forced_keyframes)
1894  ost->forced_keyframes = av_strdup(ost->forced_keyframes);
1895 
1896  MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
1897 
1898  ost->top_field_first = -1;
1899  MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
1900 
1901 
1902  ost->avfilter = get_ost_filters(o, oc, ost);
1903  if (!ost->avfilter)
1904  exit_program(1);
1905  } else {
1906  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
1907  }
1908 
1909  if (ost->stream_copy)
1910  check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_VIDEO);
1911 
1912  return ost;
1913 }
1914 
1915 OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1916 {
1917  int n;
1918  AVStream *st;
1919  OutputStream *ost;
1920  AVCodecContext *audio_enc;
1921 
1922  ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
1923  st = ost->st;
1924 
1925  audio_enc = ost->enc_ctx;
1926  audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
1927 
1928  MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);
1929  MATCH_PER_STREAM_OPT(filters, str, ost->filters, oc, st);
1930 
1931  if (!ost->stream_copy) {
1932  char *sample_fmt = NULL;
1933 
1934  MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
1935 
1936  MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
1937  if (sample_fmt &&
1938  (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
1939  av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
1940  exit_program(1);
1941  }
1942 
1943  MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
1944 
1945  MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);
1946  ost->apad = av_strdup(ost->apad);
1947 
1948  ost->avfilter = get_ost_filters(o, oc, ost);
1949  if (!ost->avfilter)
1950  exit_program(1);
1951 
1952  /* check for channel mapping for this audio stream */
1953  for (n = 0; n < o->nb_audio_channel_maps; n++) {
1954  AudioChannelMap *map = &o->audio_channel_maps[n];
1955  if ((map->ofile_idx == -1 || ost->file_index == map->ofile_idx) &&
1956  (map->ostream_idx == -1 || ost->st->index == map->ostream_idx)) {
1957  InputStream *ist;
1958 
1959  if (map->channel_idx == -1) {
1960  ist = NULL;
1961  } else if (ost->source_index < 0) {
1962  av_log(NULL, AV_LOG_FATAL, "Cannot determine input stream for channel mapping %d.%d\n",
1963  ost->file_index, ost->st->index);
1964  continue;
1965  } else {
1966  ist = input_streams[ost->source_index];
1967  }
1968 
1969  if (!ist || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) {
1970  if (av_reallocp_array(&ost->audio_channels_map,
1971  ost->audio_channels_mapped + 1,
1972  sizeof(*ost->audio_channels_map)
1973  ) < 0 )
1974  exit_program(1);
1975 
1977  }
1978  }
1979  }
1980  }
1981 
1982  if (ost->stream_copy)
1983  check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_AUDIO);
1984 
1985  return ost;
1986 }
1987 
1988 OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
1989 {
1990  OutputStream *ost;
1991 
1992  ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
1993  if (!ost->stream_copy) {
1994  av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
1995  exit_program(1);
1996  }
1997 
1998  return ost;
1999 }
2000 
2001 OutputStream *new_unknown_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2002 {
2003  OutputStream *ost;
2004 
2005  ost = new_output_stream(o, oc, AVMEDIA_TYPE_UNKNOWN, source_index);
2006  if (!ost->stream_copy) {
2007  av_log(NULL, AV_LOG_FATAL, "Unknown stream encoding not supported yet (only streamcopy)\n");
2008  exit_program(1);
2009  }
2010 
2011  return ost;
2012 }
2013 
2014 OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2015 {
2016  OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
2017  ost->stream_copy = 1;
2018  ost->finished = 1;
2019  return ost;
2020 }
2021 
2022 OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
2023 {
2024  AVStream *st;
2025  OutputStream *ost;
2026  AVCodecContext *subtitle_enc;
2027 
2028  ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
2029  st = ost->st;
2030  subtitle_enc = ost->enc_ctx;
2031 
2032  subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
2033 
2034  MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
2035 
2036  if (!ost->stream_copy) {
2037  char *frame_size = NULL;
2038 
2039  MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
2040  if (frame_size && av_parse_video_size(&subtitle_enc->width, &subtitle_enc->height, frame_size) < 0) {
2041  av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
2042  exit_program(1);
2043  }
2044  }
2045 
2046  return ost;
2047 }
2048 
2049 /* arg format is "output-stream-index:streamid-value". */
2050 int opt_streamid(void *optctx, const char *opt, const char *arg)
2051 {
2052  OptionsContext *o = optctx;
2053  int idx;
2054  char *p;
2055  char idx_str[16];
2056 
2057  av_strlcpy(idx_str, arg, sizeof(idx_str));
2058  p = strchr(idx_str, ':');
2059  if (!p) {
2060  av_log(NULL, AV_LOG_FATAL,
2061  "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
2062  arg, opt);
2063  exit_program(1);
2064  }
2065  *p++ = '\0';
2066  idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
2067  o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
2068  o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
2069  return 0;
2070 }
2071 
2072 int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
2073 {
2074  AVFormatContext *is = ifile->ctx;
2075  AVFormatContext *os = ofile->ctx;
2076  AVChapter **tmp;
2077  int i;
2078 
2079  tmp = av_realloc_f(os->chapters, is->nb_chapters + os->nb_chapters, sizeof(*os->chapters));
2080  if (!tmp)
2081  return AVERROR(ENOMEM);
2082  os->chapters = tmp;
2083 
2084  for (i = 0; i < is->nb_chapters; i++) {
2085  AVChapter *in_ch = is->chapters[i], *out_ch;
2086  int64_t start_time = (ofile->start_time == AV_NOPTS_VALUE) ? 0 : ofile->start_time;
2087  int64_t ts_off = av_rescale_q(start_time - ifile->ts_offset,
2088  AV_TIME_BASE_Q, in_ch->time_base);
2089  int64_t rt = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
2090  av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
2091 
2092 
2093  if (in_ch->end < ts_off)
2094  continue;
2095  if (rt != INT64_MAX && in_ch->start > rt + ts_off)
2096  break;
2097 
2098  out_ch = av_mallocz(sizeof(AVChapter));
2099  if (!out_ch)
2100  return AVERROR(ENOMEM);
2101 
2102  out_ch->id = in_ch->id;
2103  out_ch->time_base = in_ch->time_base;
2104  out_ch->start = FFMAX(0, in_ch->start - ts_off);
2105  out_ch->end = FFMIN(rt, in_ch->end - ts_off);
2106 
2107  if (copy_metadata)
2108  av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
2109 
2110  os->chapters[os->nb_chapters++] = out_ch;
2111  }
2112  return 0;
2113 }
2114 
2116  AVFormatContext *oc)
2117 {
2118  OutputStream *ost;
2119 
2120  switch (ofilter->type) {
2121  case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
2122  case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
2123  default:
2124  av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
2125  "currently.\n");
2126  exit_program(1);
2127  }
2128 
2129  ost->source_index = -1;
2130  ost->filter = ofilter;
2131 
2132  ofilter->ost = ost;
2133  ofilter->format = -1;
2134 
2135  if (ost->stream_copy) {
2136  av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
2137  "which is fed from a complex filtergraph. Filtering and streamcopy "
2138  "cannot be used together.\n", ost->file_index, ost->index);
2139  exit_program(1);
2140  }
2141 
2142  if (ost->avfilter && (ost->filters || ost->filters_script)) {
2143  const char *opt = ost->filters ? "-vf/-af/-filter" : "-filter_script";
2144  av_log(NULL, AV_LOG_ERROR,
2145  "%s '%s' was specified through the %s option "
2146  "for output stream %d:%d, which is fed from a complex filtergraph.\n"
2147  "%s and -filter_complex cannot be used together for the same stream.\n",
2148  ost->filters ? "Filtergraph" : "Filtergraph script",
2149  ost->filters ? ost->filters : ost->filters_script,
2150  opt, ost->file_index, ost->index, opt);
2151  exit_program(1);
2152  }
2153 
2154  avfilter_inout_free(&ofilter->out_tmp);
2155 }
2156 
2158 {
2159  int i, ret = 0;
2160 
2161  for (i = 0; i < nb_filtergraphs; i++) {
2163  if (ret < 0)
2164  return ret;
2165  }
2166  return 0;
2167 }
2168 
2169 int open_output_file(OptionsContext *o, const char *filename)
2170 {
2171  AVFormatContext *oc;
2172  int i, j, err;
2173  OutputFile *of;
2174  OutputStream *ost;
2175  InputStream *ist;
2176  AVDictionary *unused_opts = NULL;
2177  AVDictionaryEntry *e = NULL;
2178  int format_flags = 0;
2179 
2180  if (o->stop_time != INT64_MAX && o->recording_time != INT64_MAX) {
2181  o->stop_time = INT64_MAX;
2182  av_log(NULL, AV_LOG_WARNING, "-t and -to cannot be used together; using -t.\n");
2183  }
2184 
2185  if (o->stop_time != INT64_MAX && o->recording_time == INT64_MAX) {
2186  int64_t start_time = o->start_time == AV_NOPTS_VALUE ? 0 : o->start_time;
2187  if (o->stop_time <= start_time) {
2188  av_log(NULL, AV_LOG_ERROR, "-to value smaller than -ss; aborting.\n");
2189  exit_program(1);
2190  } else {
2191  o->recording_time = o->stop_time - start_time;
2192  }
2193  }
2194 
2196  of = av_mallocz(sizeof(*of));
2197  if (!of)
2198  exit_program(1);
2199  output_files[nb_output_files - 1] = of;
2200 
2202  of->recording_time = o->recording_time;
2203  of->start_time = o->start_time;
2204  of->limit_filesize = o->limit_filesize;
2205  of->shortest = o->shortest;
2206  av_dict_copy(&of->opts, o->g->format_opts, 0);
2207 
2208  if (!strcmp(filename, "-"))
2209  filename = "pipe:";
2210 
2211  err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
2212  if (!oc) {
2213  print_error(filename, err);
2214  exit_program(1);
2215  }
2216 
2217  of->ctx = oc;
2218  if (o->recording_time != INT64_MAX)
2219  oc->duration = o->recording_time;
2220 
2221  oc->interrupt_callback = int_cb;
2222 
2223  e = av_dict_get(o->g->format_opts, "fflags", NULL, 0);
2224  if (e) {
2225  const AVOption *o = av_opt_find(oc, "fflags", NULL, 0, 0);
2226  av_opt_eval_flags(oc, o, e->value, &format_flags);
2227  }
2228  if (o->bitexact) {
2229  format_flags |= AVFMT_FLAG_BITEXACT;
2230  oc->flags |= AVFMT_FLAG_BITEXACT;
2231  }
2232 
2233  /* create streams for all unlabeled output pads */
2234  for (i = 0; i < nb_filtergraphs; i++) {
2235  FilterGraph *fg = filtergraphs[i];
2236  for (j = 0; j < fg->nb_outputs; j++) {
2237  OutputFilter *ofilter = fg->outputs[j];
2238 
2239  if (!ofilter->out_tmp || ofilter->out_tmp->name)
2240  continue;
2241 
2242  switch (ofilter->type) {
2243  case AVMEDIA_TYPE_VIDEO: o->video_disable = 1; break;
2244  case AVMEDIA_TYPE_AUDIO: o->audio_disable = 1; break;
2245  case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
2246  }
2247  init_output_filter(ofilter, o, oc);
2248  }
2249  }
2250 
2251  if (!o->nb_stream_maps) {
2252  char *subtitle_codec_name = NULL;
2253  /* pick the "best" stream of each type */
2254 
2255  /* video: highest resolution */
2256  if (!o->video_disable && av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_VIDEO) != AV_CODEC_ID_NONE) {
2257  int best_score = 0, idx = -1;
2258  int qcr = avformat_query_codec(oc->oformat, oc->oformat->video_codec, 0);
2259  for (i = 0; i < nb_input_streams; i++) {
2260  int score;
2261  ist = input_streams[i];
2262  score = ist->st->codecpar->width * ist->st->codecpar->height
2263  + 100000000 * !!(ist->st->event_flags & AVSTREAM_EVENT_FLAG_NEW_PACKETS)
2264  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2265  if (ist->user_set_discard == AVDISCARD_ALL)
2266  continue;
2267  if((qcr!=MKTAG('A', 'P', 'I', 'C')) && (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2268  score = 1;
2269  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2270  score > best_score) {
2271  if((qcr==MKTAG('A', 'P', 'I', 'C')) && !(ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC))
2272  continue;
2273  best_score = score;
2274  idx = i;
2275  }
2276  }
2277  if (idx >= 0)
2278  new_video_stream(o, oc, idx);
2279  }
2280 
2281  /* audio: most channels */
2282  if (!o->audio_disable && av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_AUDIO) != AV_CODEC_ID_NONE) {
2283  int best_score = 0, idx = -1;
2284  for (i = 0; i < nb_input_streams; i++) {
2285  int score;
2286  ist = input_streams[i];
2287  score = ist->st->codecpar->channels + 100000000*!!ist->st->codec_info_nb_frames
2288  + 5000000*!!(ist->st->disposition & AV_DISPOSITION_DEFAULT);
2289  if (ist->user_set_discard == AVDISCARD_ALL)
2290  continue;
2291  if (ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
2292  score > best_score) {
2293  best_score = score;
2294  idx = i;
2295  }
2296  }
2297  if (idx >= 0)
2298  new_audio_stream(o, oc, idx);
2299  }
2300 
2301  /* subtitles: pick first */
2302  MATCH_PER_TYPE_OPT(codec_names, str, subtitle_codec_name, oc, "s");
2303  if (!o->subtitle_disable && (avcodec_find_encoder(oc->oformat->subtitle_codec) || subtitle_codec_name)) {
2304  for (i = 0; i < nb_input_streams; i++)
2305  if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2306  AVCodecDescriptor const *input_descriptor =
2307  avcodec_descriptor_get(input_streams[i]->st->codecpar->codec_id);
2308  AVCodecDescriptor const *output_descriptor = NULL;
2309  AVCodec const *output_codec =
2310  avcodec_find_encoder(oc->oformat->subtitle_codec);
2311  int input_props = 0, output_props = 0;
2312  if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2313  continue;
2314  if (output_codec)
2315  output_descriptor = avcodec_descriptor_get(output_codec->id);
2316  if (input_descriptor)
2317  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2318  if (output_descriptor)
2319  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
2320  if (subtitle_codec_name ||
2321  input_props & output_props ||
2322  // Map dvb teletext which has neither property to any output subtitle encoder
2323  (input_descriptor && output_descriptor &&
2324  (!input_descriptor->props ||
2325  !output_descriptor->props))) {
2326  new_subtitle_stream(o, oc, i);
2327  break;
2328  }
2329  }
2330  }
2331  /* Data only if codec id match */
2332  if (!o->data_disable ) {
2333  enum AVCodecID codec_id = av_guess_codec(oc->oformat, NULL, filename, NULL, AVMEDIA_TYPE_DATA);
2334  for (i = 0; codec_id != AV_CODEC_ID_NONE && i < nb_input_streams; i++) {
2335  if (input_streams[i]->user_set_discard == AVDISCARD_ALL)
2336  continue;
2337  if (input_streams[i]->st->codecpar->codec_type == AVMEDIA_TYPE_DATA
2338  && input_streams[i]->st->codecpar->codec_id == codec_id )
2339  new_data_stream(o, oc, i);
2340  }
2341  }
2342  } else {
2343  for (i = 0; i < o->nb_stream_maps; i++) {
2344  StreamMap *map = &o->stream_maps[i];
2345 
2346  if (map->disabled)
2347  continue;
2348 
2349  if (map->linklabel) {
2350  FilterGraph *fg;
2351  OutputFilter *ofilter = NULL;
2352  int j, k;
2353 
2354  for (j = 0; j < nb_filtergraphs; j++) {
2355  fg = filtergraphs[j];
2356  for (k = 0; k < fg->nb_outputs; k++) {
2357  AVFilterInOut *out = fg->outputs[k]->out_tmp;
2358  if (out && !strcmp(out->name, map->linklabel)) {
2359  ofilter = fg->outputs[k];
2360  goto loop_end;
2361  }
2362  }
2363  }
2364 loop_end:
2365  if (!ofilter) {
2366  av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
2367  "in any defined filter graph, or was already used elsewhere.\n", map->linklabel);
2368  exit_program(1);
2369  }
2370  init_output_filter(ofilter, o, oc);
2371  } else {
2372  int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
2373 
2375  if (ist->user_set_discard == AVDISCARD_ALL) {
2376  av_log(NULL, AV_LOG_FATAL, "Stream #%d:%d is disabled and cannot be mapped.\n",
2377  map->file_index, map->stream_index);
2378  exit_program(1);
2379  }
2380  if(o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
2381  continue;
2382  if(o-> audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
2383  continue;
2384  if(o-> video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
2385  continue;
2386  if(o-> data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
2387  continue;
2388 
2389  ost = NULL;
2390  switch (ist->st->codecpar->codec_type) {
2391  case AVMEDIA_TYPE_VIDEO: ost = new_video_stream (o, oc, src_idx); break;
2392  case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream (o, oc, src_idx); break;
2393  case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream (o, oc, src_idx); break;
2394  case AVMEDIA_TYPE_DATA: ost = new_data_stream (o, oc, src_idx); break;
2395  case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
2396  case AVMEDIA_TYPE_UNKNOWN:
2397  if (copy_unknown_streams) {
2398  ost = new_unknown_stream (o, oc, src_idx);
2399  break;
2400  }
2401  default:
2402  av_log(NULL, ignore_unknown_streams ? AV_LOG_WARNING : AV_LOG_FATAL,
2403  "Cannot map stream #%d:%d - unsupported type.\n",
2404  map->file_index, map->stream_index);
2405  if (!ignore_unknown_streams) {
2406  av_log(NULL, AV_LOG_FATAL,
2407  "If you want unsupported types ignored instead "
2408  "of failing, please use the -ignore_unknown option\n"
2409  "If you want them copied, please use -copy_unknown\n");
2410  exit_program(1);
2411  }
2412  }
2413  if (ost)
2415  + map->sync_stream_index];
2416  }
2417  }
2418  }
2419 
2420  /* handle attached files */
2421  for (i = 0; i < o->nb_attachments; i++) {
2422  AVIOContext *pb;
2423  uint8_t *attachment;
2424  const char *p;
2425  int64_t len;
2426 
2427  if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
2428  av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
2429  o->attachments[i]);
2430  exit_program(1);
2431  }
2432  if ((len = avio_size(pb)) <= 0) {
2433  av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
2434  o->attachments[i]);
2435  exit_program(1);
2436  }
2437  if (len > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE ||
2438  !(attachment = av_malloc(len + AV_INPUT_BUFFER_PADDING_SIZE))) {
2439  av_log(NULL, AV_LOG_FATAL, "Attachment %s too large.\n",
2440  o->attachments[i]);
2441  exit_program(1);
2442  }
2443  avio_read(pb, attachment, len);
2444  memset(attachment + len, 0, AV_INPUT_BUFFER_PADDING_SIZE);
2445 
2446  ost = new_attachment_stream(o, oc, -1);
2447  ost->stream_copy = 0;
2448  ost->attachment_filename = o->attachments[i];
2449  ost->st->codecpar->extradata = attachment;
2450  ost->st->codecpar->extradata_size = len;
2451 
2452  p = strrchr(o->attachments[i], '/');
2453  av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
2454  avio_closep(&pb);
2455  }
2456 
2457 #if FF_API_LAVF_AVCTX
2458  for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
2459  AVDictionaryEntry *e;
2460  ost = output_streams[i];
2461 
2462  if ((ost->stream_copy || ost->attachment_filename)
2463  && (e = av_dict_get(o->g->codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
2464  && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
2465  if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
2466  exit_program(1);
2467  }
2468 #endif
2469 
2470  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2471  av_dump_format(oc, nb_output_files - 1, oc->url, 1);
2472  av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", nb_output_files - 1);
2473  exit_program(1);
2474  }
2475 
2476  /* check if all codec options have been used */
2477  unused_opts = strip_specifiers(o->g->codec_opts);
2478  for (i = of->ost_index; i < nb_output_streams; i++) {
2479  e = NULL;
2480  while ((e = av_dict_get(output_streams[i]->encoder_opts, "", e,
2481  AV_DICT_IGNORE_SUFFIX)))
2482  av_dict_set(&unused_opts, e->key, NULL, 0);
2483  }
2484 
2485  e = NULL;
2486  while ((e = av_dict_get(unused_opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
2487  const AVClass *class = avcodec_get_class();
2488  const AVOption *option = av_opt_find(&class, e->key, NULL, 0,
2489  AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
2490  const AVClass *fclass = avformat_get_class();
2491  const AVOption *foption = av_opt_find(&fclass, e->key, NULL, 0,
2492  AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
2493  if (!option || foption)
2494  continue;
2495 
2496 
2497  if (!(option->flags & AV_OPT_FLAG_ENCODING_PARAM)) {
2498  av_log(NULL, AV_LOG_ERROR, "Codec AVOption %s (%s) specified for "
2499  "output file #%d (%s) is not an encoding option.\n", e->key,
2500  option->help ? option->help : "", nb_output_files - 1,
2501  filename);
2502  exit_program(1);
2503  }
2504 
2505  // gop_timecode is injected by generic code but not always used
2506  if (!strcmp(e->key, "gop_timecode"))
2507  continue;
2508 
2509  av_log(NULL, AV_LOG_WARNING, "Codec AVOption %s (%s) specified for "
2510  "output file #%d (%s) has not been used for any stream. The most "
2511  "likely reason is either wrong type (e.g. a video option with "
2512  "no video streams) or that it is a private option of some encoder "
2513  "which was not actually used for any stream.\n", e->key,
2514  option->help ? option->help : "", nb_output_files - 1, filename);
2515  }
2516  av_dict_free(&unused_opts);
2517 
2518  /* set the decoding_needed flags and create simple filtergraphs */
2519  for (i = of->ost_index; i < nb_output_streams; i++) {
2520  OutputStream *ost = output_streams[i];
2521 
2522  if (ost->encoding_needed && ost->source_index >= 0) {
2523  InputStream *ist = input_streams[ost->source_index];
2525 
2526  if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2527  ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2528  err = init_simple_filtergraph(ist, ost);
2529  if (err < 0) {
2530  av_log(NULL, AV_LOG_ERROR,
2531  "Error initializing a simple filtergraph between streams "
2532  "%d:%d->%d:%d\n", ist->file_index, ost->source_index,
2533  nb_output_files - 1, ost->st->index);
2534  exit_program(1);
2535  }
2536  }
2537  }
2538 
2539  /* set the filter output constraints */
2540  if (ost->filter) {
2541  OutputFilter *f = ost->filter;
2542  int count;
2543  switch (ost->enc_ctx->codec_type) {
2544  case AVMEDIA_TYPE_VIDEO:
2545  f->frame_rate = ost->frame_rate;
2546  f->width = ost->enc_ctx->width;
2547  f->height = ost->enc_ctx->height;
2548  if (ost->enc_ctx->pix_fmt != AV_PIX_FMT_NONE) {
2549  f->format = ost->enc_ctx->pix_fmt;
2550  } else if (ost->enc->pix_fmts) {
2551  count = 0;
2552  while (ost->enc->pix_fmts[count] != AV_PIX_FMT_NONE)
2553  count++;
2554  f->formats = av_mallocz_array(count + 1, sizeof(*f->formats));
2555  if (!f->formats)
2556  exit_program(1);
2557  memcpy(f->formats, ost->enc->pix_fmts, (count + 1) * sizeof(*f->formats));
2558  }
2559  break;
2560  case AVMEDIA_TYPE_AUDIO:
2561  if (ost->enc_ctx->sample_fmt != AV_SAMPLE_FMT_NONE) {
2562  f->format = ost->enc_ctx->sample_fmt;
2563  } else if (ost->enc->sample_fmts) {
2564  count = 0;
2565  while (ost->enc->sample_fmts[count] != AV_SAMPLE_FMT_NONE)
2566  count++;
2567  f->formats = av_mallocz_array(count + 1, sizeof(*f->formats));
2568  if (!f->formats)
2569  exit_program(1);
2570  memcpy(f->formats, ost->enc->sample_fmts, (count + 1) * sizeof(*f->formats));
2571  }
2572  if (ost->enc_ctx->sample_rate) {
2573  f->sample_rate = ost->enc_ctx->sample_rate;
2574  } else if (ost->enc->supported_samplerates) {
2575  count = 0;
2576  while (ost->enc->supported_samplerates[count])
2577  count++;
2578  f->sample_rates = av_mallocz_array(count + 1, sizeof(*f->sample_rates));
2579  if (!f->sample_rates)
2580  exit_program(1);
2581  memcpy(f->sample_rates, ost->enc->supported_samplerates,
2582  (count + 1) * sizeof(*f->sample_rates));
2583  }
2584  if (ost->enc_ctx->channels) {
2585  f->channel_layout = av_get_default_channel_layout(ost->enc_ctx->channels);
2586  } else if (ost->enc->channel_layouts) {
2587  count = 0;
2588  while (ost->enc->channel_layouts[count])
2589  count++;
2590  f->channel_layouts = av_mallocz_array(count + 1, sizeof(*f->channel_layouts));
2591  if (!f->channel_layouts)
2592  exit_program(1);
2593  memcpy(f->channel_layouts, ost->enc->channel_layouts,
2594  (count + 1) * sizeof(*f->channel_layouts));
2595  }
2596  break;
2597  }
2598  }
2599  }
2600 
2601  /* check filename in case of an image number is expected */
2602  if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
2603  if (!av_filename_number_test(oc->url)) {
2604  print_error(oc->url, AVERROR(EINVAL));
2605  exit_program(1);
2606  }
2607  }
2608 
2609  if (!(oc->oformat->flags & AVFMT_NOSTREAMS) && !input_stream_potentially_available) {
2610  av_log(NULL, AV_LOG_ERROR,
2611  "No input streams but output needs an input stream\n");
2612  exit_program(1);
2613  }
2614 
2615  if (!(oc->oformat->flags & AVFMT_NOFILE)) {
2616  /* test if it already exists to avoid losing precious files */
2617  assert_file_overwrite(filename);
2618 
2619  /* open the file */
2620  if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
2621  &oc->interrupt_callback,
2622  &of->opts)) < 0) {
2623  print_error(filename, err);
2624  exit_program(1);
2625  }
2626  } else if (strcmp(oc->oformat->name, "image2")==0 && !av_filename_number_test(filename))
2627  assert_file_overwrite(filename);
2628 
2629  if (o->mux_preload) {
2630  av_dict_set_int(&of->opts, "preload", o->mux_preload*AV_TIME_BASE, 0);
2631  }
2632  oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
2633 
2634  /* copy metadata */
2635  for (i = 0; i < o->nb_metadata_map; i++) {
2636  char *p;
2637  int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
2638 
2639  if (in_file_index >= nb_input_files) {
2640  av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
2641  exit_program(1);
2642  }
2643  fftools_copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc,
2644  in_file_index >= 0 ?
2645  input_files[in_file_index]->ctx : NULL, o);
2646  }
2647 
2648  /* copy chapters */
2649  if (o->chapters_input_file >= nb_input_files) {
2650  if (o->chapters_input_file == INT_MAX) {
2651  /* copy chapters from the first input file that has them*/
2652  o->chapters_input_file = -1;
2653  for (i = 0; i < nb_input_files; i++)
2654  if (input_files[i]->ctx->nb_chapters) {
2655  o->chapters_input_file = i;
2656  break;
2657  }
2658  } else {
2659  av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
2660  o->chapters_input_file);
2661  exit_program(1);
2662  }
2663  }
2664  if (o->chapters_input_file >= 0)
2667 
2668  /* copy global metadata by default */
2670  av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
2671  AV_DICT_DONT_OVERWRITE);
2672  if(o->recording_time != INT64_MAX)
2673  av_dict_set(&oc->metadata, "duration", NULL, 0);
2674  av_dict_set(&oc->metadata, "creation_time", NULL, 0);
2675  av_dict_set(&oc->metadata, "company_name", NULL, 0);
2676  av_dict_set(&oc->metadata, "product_name", NULL, 0);
2677  av_dict_set(&oc->metadata, "product_version", NULL, 0);
2678  }
2679  if (!o->metadata_streams_manual)
2680  for (i = of->ost_index; i < nb_output_streams; i++) {
2681  InputStream *ist;
2682  if (output_streams[i]->source_index < 0) /* this is true e.g. for attached files */
2683  continue;
2685  av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
2686  if (!output_streams[i]->stream_copy) {
2687  av_dict_set(&output_streams[i]->st->metadata, "encoder", NULL, 0);
2688  }
2689  }
2690 
2691  /* process manually set programs */
2692  for (i = 0; i < o->nb_program; i++) {
2693  const char *p = o->program[i].u.str;
2694  int progid = i+1;
2695  AVProgram *program;
2696 
2697  while(*p) {
2698  const char *p2 = av_get_token(&p, ":");
2699  const char *to_dealloc = p2;
2700  char *key;
2701  if (!p2)
2702  break;
2703 
2704  if(*p) p++;
2705 
2706  key = av_get_token(&p2, "=");
2707  if (!key || !*p2) {
2708  av_freep(&to_dealloc);
2709  av_freep(&key);
2710  break;
2711  }
2712  p2++;
2713 
2714  if (!strcmp(key, "program_num"))
2715  progid = strtol(p2, NULL, 0);
2716  av_freep(&to_dealloc);
2717  av_freep(&key);
2718  }
2719 
2720  program = av_new_program(oc, progid);
2721 
2722  p = o->program[i].u.str;
2723  while(*p) {
2724  const char *p2 = av_get_token(&p, ":");
2725  const char *to_dealloc = p2;
2726  char *key;
2727  if (!p2)
2728  break;
2729  if(*p) p++;
2730 
2731  key = av_get_token(&p2, "=");
2732  if (!key) {
2733  av_log(NULL, AV_LOG_FATAL,
2734  "No '=' character in program string %s.\n",
2735  p2);
2736  exit_program(1);
2737  }
2738  if (!*p2)
2739  exit_program(1);
2740  p2++;
2741 
2742  if (!strcmp(key, "title")) {
2743  av_dict_set(&program->metadata, "title", p2, 0);
2744  } else if (!strcmp(key, "program_num")) {
2745  } else if (!strcmp(key, "st")) {
2746  int st_num = strtol(p2, NULL, 0);
2747  av_program_add_stream_index(oc, progid, st_num);
2748  } else {
2749  av_log(NULL, AV_LOG_FATAL, "Unknown program key %s.\n", key);
2750  exit_program(1);
2751  }
2752  av_freep(&to_dealloc);
2753  av_freep(&key);
2754  }
2755  }
2756 
2757  /* process manually set metadata */
2758  for (i = 0; i < o->nb_metadata; i++) {
2759  AVDictionary **m;
2760  char type, *val;
2761  const char *stream_spec;
2762  int index = 0, j, ret = 0;
2763 
2764  val = strchr(o->metadata[i].u.str, '=');
2765  if (!val) {
2766  av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
2767  o->metadata[i].u.str);
2768  exit_program(1);
2769  }
2770  *val++ = 0;
2771 
2772  parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
2773  if (type == 's') {
2774  for (j = 0; j < oc->nb_streams; j++) {
2775  ost = output_streams[nb_output_streams - oc->nb_streams + j];
2776  if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
2777  if (!strcmp(o->metadata[i].u.str, "rotate")) {
2778  char *tail;
2779  double theta = av_strtod(val, &tail);
2780  if (!*tail) {
2781  ost->rotate_overridden = 1;
2782  ost->rotate_override_value = theta;
2783  }
2784  } else {
2785  av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
2786  }
2787  } else if (ret < 0)
2788  exit_program(1);
2789  }
2790  }
2791  else {
2792  switch (type) {
2793  case 'g':
2794  m = &oc->metadata;
2795  break;
2796  case 'c':
2797  if (index < 0 || index >= oc->nb_chapters) {
2798  av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
2799  exit_program(1);
2800  }
2801  m = &oc->chapters[index]->metadata;
2802  break;
2803  case 'p':
2804  if (index < 0 || index >= oc->nb_programs) {
2805  av_log(NULL, AV_LOG_FATAL, "Invalid program index %d in metadata specifier.\n", index);
2806  exit_program(1);
2807  }
2808  m = &oc->programs[index]->metadata;
2809  break;
2810  default:
2811  av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
2812  exit_program(1);
2813  }
2814  av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
2815  }
2816  }
2817 
2818  return 0;
2819 }
2820 
2821 int opt_target(void *optctx, const char *opt, const char *arg)
2822 {
2823  const OptionDef *options = ffmpeg_options;
2824  OptionsContext *o = optctx;
2825  enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
2826  const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
2827 
2828  if (!strncmp(arg, "pal-", 4)) {
2829  norm = PAL;
2830  arg += 4;
2831  } else if (!strncmp(arg, "ntsc-", 5)) {
2832  norm = NTSC;
2833  arg += 5;
2834  } else if (!strncmp(arg, "film-", 5)) {
2835  norm = FILM;
2836  arg += 5;
2837  } else {
2838  /* Try to determine PAL/NTSC by peeking in the input files */
2839  if (nb_input_files) {
2840  int i, j;
2841  for (j = 0; j < nb_input_files; j++) {
2842  for (i = 0; i < input_files[j]->nb_streams; i++) {
2843  AVStream *st = input_files[j]->ctx->streams[i];
2844  int64_t fr;
2845  if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
2846  continue;
2847  fr = st->time_base.den * 1000LL / st->time_base.num;
2848  if (fr == 25000) {
2849  norm = PAL;
2850  break;
2851  } else if ((fr == 29970) || (fr == 23976)) {
2852  norm = NTSC;
2853  break;
2854  }
2855  }
2856  if (norm != UNKNOWN)
2857  break;
2858  }
2859  }
2860  if (norm != UNKNOWN)
2861  av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
2862  }
2863 
2864  if (norm == UNKNOWN) {
2865  av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
2866  av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
2867  av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
2868  exit_program(1);
2869  }
2870 
2871  if (!strcmp(arg, "vcd")) {
2872  opt_video_codec(o, "c:v", "mpeg1video");
2873  opt_audio_codec(o, "c:a", "mp2");
2874  parse_option(o, "f", "vcd", options);
2875 
2876  parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
2877  parse_option(o, "r", frame_rates[norm], options);
2878  opt_default(NULL, "g", norm == PAL ? "15" : "18");
2879 
2880  opt_default(NULL, "b:v", "1150000");
2881  opt_default(NULL, "maxrate:v", "1150000");
2882  opt_default(NULL, "minrate:v", "1150000");
2883  opt_default(NULL, "bufsize:v", "327680"); // 40*1024*8;
2884 
2885  opt_default(NULL, "b:a", "224000");
2886  parse_option(o, "ar", "44100", options);
2887  parse_option(o, "ac", "2", options);
2888 
2889  opt_default(NULL, "packetsize", "2324");
2890  opt_default(NULL, "muxrate", "1411200"); // 2352 * 75 * 8;
2891 
2892  /* We have to offset the PTS, so that it is consistent with the SCR.
2893  SCR starts at 36000, but the first two packs contain only padding
2894  and the first pack from the other stream, respectively, may also have
2895  been written before.
2896  So the real data starts at SCR 36000+3*1200. */
2897  o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
2898  } else if (!strcmp(arg, "svcd")) {
2899 
2900  opt_video_codec(o, "c:v", "mpeg2video");
2901  opt_audio_codec(o, "c:a", "mp2");
2902  parse_option(o, "f", "svcd", options);
2903 
2904  parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
2905  parse_option(o, "r", frame_rates[norm], options);
2906  parse_option(o, "pix_fmt", "yuv420p", options);
2907  opt_default(NULL, "g", norm == PAL ? "15" : "18");
2908 
2909  opt_default(NULL, "b:v", "2040000");
2910  opt_default(NULL, "maxrate:v", "2516000");
2911  opt_default(NULL, "minrate:v", "0"); // 1145000;
2912  opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
2913  opt_default(NULL, "scan_offset", "1");
2914 
2915  opt_default(NULL, "b:a", "224000");
2916  parse_option(o, "ar", "44100", options);
2917 
2918  opt_default(NULL, "packetsize", "2324");
2919 
2920  } else if (!strcmp(arg, "dvd")) {
2921 
2922  opt_video_codec(o, "c:v", "mpeg2video");
2923  opt_audio_codec(o, "c:a", "ac3");
2924  parse_option(o, "f", "dvd", options);
2925 
2926  parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
2927  parse_option(o, "r", frame_rates[norm], options);
2928  parse_option(o, "pix_fmt", "yuv420p", options);
2929  opt_default(NULL, "g", norm == PAL ? "15" : "18");
2930 
2931  opt_default(NULL, "b:v", "6000000");
2932  opt_default(NULL, "maxrate:v", "9000000");
2933  opt_default(NULL, "minrate:v", "0"); // 1500000;
2934  opt_default(NULL, "bufsize:v", "1835008"); // 224*1024*8;
2935 
2936  opt_default(NULL, "packetsize", "2048"); // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
2937  opt_default(NULL, "muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
2938 
2939  opt_default(NULL, "b:a", "448000");
2940  parse_option(o, "ar", "48000", options);
2941 
2942  } else if (!strncmp(arg, "dv", 2)) {
2943 
2944  parse_option(o, "f", "dv", options);
2945 
2946  parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
2947  parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
2948  norm == PAL ? "yuv420p" : "yuv411p", options);
2949  parse_option(o, "r", frame_rates[norm], options);
2950 
2951  parse_option(o, "ar", "48000", options);
2952  parse_option(o, "ac", "2", options);
2953 
2954  } else {
2955  av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
2956  return AVERROR(EINVAL);
2957  }
2958 
2959  av_dict_copy(&o->g->codec_opts, codec_opts, AV_DICT_DONT_OVERWRITE);
2960  av_dict_copy(&o->g->format_opts, format_opts, AV_DICT_DONT_OVERWRITE);
2961 
2962  return 0;
2963 }
2964 
2965 int opt_vstats_file(void *optctx, const char *opt, const char *arg)
2966 {
2967  av_free (vstats_filename);
2968  vstats_filename = av_strdup (arg);
2969  return 0;
2970 }
2971 
2972 int opt_vstats(void *optctx, const char *opt, const char *arg)
2973 {
2974  char filename[40];
2975  time_t today2 = time(NULL);
2976  struct tm *today = localtime(&today2);
2977 
2978  if (!today) { // maybe tomorrow
2979  av_log(NULL, AV_LOG_FATAL, "Unable to get current time: %s\n", strerror(errno));
2980  exit_program(1);
2981  }
2982 
2983  snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
2984  today->tm_sec);
2985  return opt_vstats_file(NULL, opt, filename);
2986 }
2987 
2988 int opt_video_frames(void *optctx, const char *opt, const char *arg)
2989 {
2990  OptionsContext *o = optctx;
2991  return parse_option(o, "frames:v", arg, ffmpeg_options);
2992 }
2993 
2994 int opt_audio_frames(void *optctx, const char *opt, const char *arg)
2995 {
2996  OptionsContext *o = optctx;
2997  return parse_option(o, "frames:a", arg, ffmpeg_options);
2998 }
2999 
3000 int opt_data_frames(void *optctx, const char *opt, const char *arg)
3001 {
3002  OptionsContext *o = optctx;
3003  return parse_option(o, "frames:d", arg, ffmpeg_options);
3004 }
3005 
3006 int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
3007 {
3008  int ret;
3009  AVDictionary *cbak = codec_opts;
3010  AVDictionary *fbak = format_opts;
3011  codec_opts = NULL;
3012  format_opts = NULL;
3013 
3014  ret = opt_default(NULL, opt, arg);
3015 
3016  av_dict_copy(&o->g->codec_opts , codec_opts, 0);
3017  av_dict_copy(&o->g->format_opts, format_opts, 0);
3018  av_dict_free(&codec_opts);
3019  av_dict_free(&format_opts);
3020  codec_opts = cbak;
3021  format_opts = fbak;
3022 
3023  return ret;
3024 }
3025 
3026 int opt_preset(void *optctx, const char *opt, const char *arg)
3027 {
3028  OptionsContext *o = optctx;
3029  FILE *f=NULL;
3030  char filename[1000], line[1000], tmp_line[1000];
3031  const char *codec_name = NULL;
3032 
3033  tmp_line[0] = *opt;
3034  tmp_line[1] = 0;
3035  MATCH_PER_TYPE_OPT(codec_names, str, codec_name, NULL, tmp_line);
3036 
3037  if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
3038  if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
3039  av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
3040  }else
3041  av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
3042  exit_program(1);
3043  }
3044 
3045  while (fgets(line, sizeof(line), f)) {
3046  char *key = tmp_line, *value, *endptr;
3047 
3048  if (strcspn(line, "#\n\r") == 0)
3049  continue;
3050  av_strlcpy(tmp_line, line, sizeof(tmp_line));
3051  if (!av_strtok(key, "=", &value) ||
3052  !av_strtok(value, "\r\n", &endptr)) {
3053  av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
3054  exit_program(1);
3055  }
3056  av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
3057 
3058  if (!strcmp(key, "acodec")) opt_audio_codec (o, key, value);
3059  else if (!strcmp(key, "vcodec")) opt_video_codec (o, key, value);
3060  else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
3061  else if (!strcmp(key, "dcodec")) opt_data_codec (o, key, value);
3062  else if (opt_default_new(o, key, value) < 0) {
3063  av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
3064  filename, line, key, value);
3065  exit_program(1);
3066  }
3067  }
3068 
3069  fclose(f);
3070 
3071  return 0;
3072 }
3073 
3074 int opt_old2new(void *optctx, const char *opt, const char *arg)
3075 {
3076  OptionsContext *o = optctx;
3077  int ret;
3078  char *s = av_asprintf("%s:%c", opt + 1, *opt);
3079  if (!s)
3080  return AVERROR(ENOMEM);
3081  ret = parse_option(o, s, arg, ffmpeg_options);
3082  av_free(s);
3083  return ret;
3084 }
3085 
3086 int opt_bitrate(void *optctx, const char *opt, const char *arg)
3087 {
3088  OptionsContext *o = optctx;
3089 
3090  if(!strcmp(opt, "ab")){
3091  av_dict_set(&o->g->codec_opts, "b:a", arg, 0);
3092  return 0;
3093  } else if(!strcmp(opt, "b")){
3094  av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
3095  av_dict_set(&o->g->codec_opts, "b:v", arg, 0);
3096  return 0;
3097  }
3098  av_dict_set(&o->g->codec_opts, opt, arg, 0);
3099  return 0;
3100 }
3101 
3102 int opt_qscale(void *optctx, const char *opt, const char *arg)
3103 {
3104  OptionDef *options = ffmpeg_options;
3105  OptionsContext *o = optctx;
3106  char *s;
3107  int ret;
3108  if(!strcmp(opt, "qscale")){
3109  av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
3110  return parse_option(o, "q:v", arg, options);
3111  }
3112  s = av_asprintf("q%s", opt + 6);
3113  if (!s)
3114  return AVERROR(ENOMEM);
3115  ret = parse_option(o, s, arg, options);
3116  av_free(s);
3117  return ret;
3118 }
3119 
3120 int opt_profile(void *optctx, const char *opt, const char *arg)
3121 {
3122  OptionsContext *o = optctx;
3123  if(!strcmp(opt, "profile")){
3124  av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
3125  av_dict_set(&o->g->codec_opts, "profile:v", arg, 0);
3126  return 0;
3127  }
3128  av_dict_set(&o->g->codec_opts, opt, arg, 0);
3129  return 0;
3130 }
3131 
3132 int opt_video_filters(void *optctx, const char *opt, const char *arg)
3133 {
3134  OptionsContext *o = optctx;
3135  return parse_option(o, "filter:v", arg, ffmpeg_options);
3136 }
3137 
3138 int opt_audio_filters(void *optctx, const char *opt, const char *arg)
3139 {
3140  OptionsContext *o = optctx;
3141  return parse_option(o, "filter:a", arg, ffmpeg_options);
3142 }
3143 
3144 int opt_vsync(void *optctx, const char *opt, const char *arg)
3145 {
3146  if (!av_strcasecmp(arg, "cfr")) video_sync_method = VSYNC_CFR;
3147  else if (!av_strcasecmp(arg, "vfr")) video_sync_method = VSYNC_VFR;
3148  else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
3149  else if (!av_strcasecmp(arg, "drop")) video_sync_method = VSYNC_DROP;
3150 
3153  return 0;
3154 }
3155 
3156 int opt_timecode(void *optctx, const char *opt, const char *arg)
3157 {
3158  OptionsContext *o = optctx;
3159  int ret;
3160  char *tcr = av_asprintf("timecode=%s", arg);
3161  if (!tcr)
3162  return AVERROR(ENOMEM);
3163  ret = parse_option(o, "metadata:g", tcr, ffmpeg_options);
3164  if (ret >= 0)
3165  ret = av_dict_set(&o->g->codec_opts, "gop_timecode", arg, 0);
3166  av_free(tcr);
3167  return ret;
3168 }
3169 
3170 int opt_channel_layout(void *optctx, const char *opt, const char *arg)
3171 {
3172  OptionsContext *o = optctx;
3173  char layout_str[32];
3174  char *stream_str;
3175  char *ac_str;
3176  int ret, channels, ac_str_size;
3177  uint64_t layout;
3178 
3179  layout = av_get_channel_layout(arg);
3180  if (!layout) {
3181  av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
3182  return AVERROR(EINVAL);
3183  }
3184  snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
3185  ret = opt_default_new(o, opt, layout_str);
3186  if (ret < 0)
3187  return ret;
3188 
3189  /* set 'ac' option based on channel layout */
3190  channels = av_get_channel_layout_nb_channels(layout);
3191  snprintf(layout_str, sizeof(layout_str), "%d", channels);
3192  stream_str = strchr(opt, ':');
3193  ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
3194  ac_str = av_mallocz(ac_str_size);
3195  if (!ac_str)
3196  return AVERROR(ENOMEM);
3197  av_strlcpy(ac_str, "ac", 3);
3198  if (stream_str)
3199  av_strlcat(ac_str, stream_str, ac_str_size);
3200  ret = parse_option(o, ac_str, layout_str, ffmpeg_options);
3201  av_free(ac_str);
3202 
3203  return ret;
3204 }
3205 
3206 int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
3207 {
3208  OptionsContext *o = optctx;
3209  return parse_option(o, "q:a", arg, ffmpeg_options);
3210 }
3211 
3212 int opt_filter_complex(void *optctx, const char *opt, const char *arg)
3213 {
3215  if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
3216  return AVERROR(ENOMEM);
3218  filtergraphs[nb_filtergraphs - 1]->graph_desc = av_strdup(arg);
3219  if (!filtergraphs[nb_filtergraphs - 1]->graph_desc)
3220  return AVERROR(ENOMEM);
3221 
3223 
3224  return 0;
3225 }
3226 
3227 int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
3228 {
3229  uint8_t *graph_desc = fftools_read_file(arg);
3230  if (!graph_desc)
3231  return AVERROR(EINVAL);
3232 
3234  if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
3235  return AVERROR(ENOMEM);
3237  filtergraphs[nb_filtergraphs - 1]->graph_desc = graph_desc;
3238 
3240 
3241  return 0;
3242 }
3243 
3244 void show_help_default_ffmpeg(const char *opt, const char *arg)
3245 {
3246  OptionDef *options = ffmpeg_options;
3247  /* per-file options have at least one of those set */
3248  const int per_file = OPT_SPEC | OPT_OFFSET | OPT_PERFILE;
3249  int show_advanced = 0, show_avoptions = 0;
3250 
3251  if (opt && *opt) {
3252  if (!strcmp(opt, "long"))
3253  show_advanced = 1;
3254  else if (!strcmp(opt, "full"))
3255  show_advanced = show_avoptions = 1;
3256  else
3257  av_log(NULL, AV_LOG_ERROR, "Unknown help option '%s'.\n", opt);
3258  }
3259 
3260  show_usage();
3261 
3262  av_log(NULL, AV_LOG_STDERR, "Getting help:\n"
3263  " -h -- print basic options\n"
3264  " -h long -- print more options\n"
3265  " -h full -- print all options (including all format and codec specific options, very long)\n"
3266  " -h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter/bsf/protocol\n"
3267  " See man %s for detailed description of the options.\n"
3268  "\n", program_name);
3269 
3270  show_help_options(options, "Print help / information / capabilities:",
3271  OPT_EXIT, 0, 0);
3272 
3273  show_help_options(options, "Global options (affect whole program "
3274  "instead of just one file):",
3275  0, per_file | OPT_EXIT | OPT_EXPERT, 0);
3276  if (show_advanced)
3277  show_help_options(options, "Advanced global options:", OPT_EXPERT,
3278  per_file | OPT_EXIT, 0);
3279 
3280  show_help_options(options, "Per-file main options:", 0,
3282  OPT_EXIT, per_file);
3283  if (show_advanced)
3284  show_help_options(options, "Advanced per-file options:",
3285  OPT_EXPERT, OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE, per_file);
3286 
3287  show_help_options(options, "Video options:",
3289  if (show_advanced)
3290  show_help_options(options, "Advanced Video options:",
3292 
3293  show_help_options(options, "Audio options:",
3295  if (show_advanced)
3296  show_help_options(options, "Advanced Audio options:",
3298  show_help_options(options, "Subtitle options:",
3299  OPT_SUBTITLE, 0, 0);
3300  av_log(NULL, AV_LOG_STDERR, "\n");
3301 
3302  if (show_avoptions) {
3303  int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
3304  show_help_children(avcodec_get_class(), flags);
3305  show_help_children(avformat_get_class(), flags);
3306 #if CONFIG_SWSCALE
3307  show_help_children(sws_get_class(), flags);
3308 #endif
3309 #if CONFIG_SWRESAMPLE
3310  show_help_children(swr_get_class(), AV_OPT_FLAG_AUDIO_PARAM);
3311 #endif
3312  show_help_children(avfilter_get_class(), AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_FILTERING_PARAM);
3313  show_help_children(av_bsf_get_class(), AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_BSF_PARAM);
3314  }
3315 }
3316 
3317 void show_usage(void)
3318 {
3319  av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
3320  av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
3321  av_log(NULL, AV_LOG_INFO, "\n");
3322 }
3323 
3324 enum OptGroup {
3325  GROUP_OUTFILE,
3326  GROUP_INFILE,
3327 };
3328 
3329 const OptionGroupDef groups[] = {
3330  [GROUP_OUTFILE] = { "output url", NULL, OPT_OUTPUT },
3331  [GROUP_INFILE] = { "input url", "i", OPT_INPUT },
3332 };
3333 
3334 int open_files(OptionGroupList *l, const char *inout,
3335  int (*open_file)(OptionsContext*, const char*))
3336 {
3337  int i, ret;
3338 
3339  for (i = 0; i < l->nb_groups; i++) {
3340  OptionGroup *g = &l->groups[i];
3341  OptionsContext o;
3342 
3343  init_options(&o);
3344  o.g = g;
3345 
3346  ret = parse_optgroup(&o, g);
3347  if (ret < 0) {
3348  av_log(NULL, AV_LOG_ERROR, "Error parsing options for %s file "
3349  "%s.\n", inout, g->arg);
3350  uninit_options(&o);
3351  return ret;
3352  }
3353 
3354  av_log(NULL, AV_LOG_DEBUG, "Opening an %s file: %s.\n", inout, g->arg);
3355  ret = open_file(&o, g->arg);
3356  uninit_options(&o);
3357  if (ret < 0) {
3358  av_log(NULL, AV_LOG_ERROR, "Error opening %s file %s.\n",
3359  inout, g->arg);
3360  return ret;
3361  }
3362  av_log(NULL, AV_LOG_DEBUG, "Successfully opened the file.\n");
3363  }
3364 
3365  return 0;
3366 }
3367 
3368 int ffmpeg_parse_options(int argc, char **argv)
3369 {
3370  OptionParseContext octx;
3371  uint8_t error[128];
3372  int ret;
3373 
3374  memset(&octx, 0, sizeof(octx));
3375 
3376  /* split the commandline into an internal representation */
3377  ret = split_commandline(&octx, argc, argv, ffmpeg_options, groups,
3378  FF_ARRAY_ELEMS(groups));
3379  if (ret < 0) {
3380  av_log(NULL, AV_LOG_FATAL, "Error splitting the argument list: ");
3381  goto fail;
3382  }
3383 
3384  /* apply global options */
3385  ret = parse_optgroup(NULL, &octx.global_opts);
3386  if (ret < 0) {
3387  av_log(NULL, AV_LOG_FATAL, "Error parsing global options: ");
3388  goto fail;
3389  }
3390 
3391  /* configure terminal and setup signal handlers */
3392  term_init();
3393 
3394  /* open input files */
3395  ret = open_files(&octx.groups[GROUP_INFILE], "input", open_input_file);
3396  if (ret < 0) {
3397  av_log(NULL, AV_LOG_FATAL, "Error opening input files: ");
3398  goto fail;
3399  }
3400 
3401  /* create the complex filtergraphs */
3402  ret = init_complex_filters();
3403  if (ret < 0) {
3404  av_log(NULL, AV_LOG_FATAL, "Error initializing complex filters.\n");
3405  goto fail;
3406  }
3407 
3408  /* open output files */
3409  ret = open_files(&octx.groups[GROUP_OUTFILE], "output", open_output_file);
3410  if (ret < 0) {
3411  av_log(NULL, AV_LOG_FATAL, "Error opening output files: ");
3412  goto fail;
3413  }
3414 
3416 
3417 fail:
3418  uninit_parse_context(&octx);
3419  if (ret < 0) {
3420  av_strerror(ret, error, sizeof(error));
3421  av_log(NULL, AV_LOG_FATAL, "%s\n", error);
3422  }
3423  return ret;
3424 }
3425 
3426 int opt_progress(void *optctx, const char *opt, const char *arg)
3427 {
3428  AVIOContext *avio = NULL;
3429  int ret;
3430 
3431  if (!strcmp(arg, "-"))
3432  arg = "pipe:";
3433  ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
3434  if (ret < 0) {
3435  av_log(NULL, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
3436  arg, av_err2str(ret));
3437  return ret;
3438  }
3439  progress_avio = avio;
3440  return 0;
3441 }
void exit_program(int ret)
void show_help_children(const AVClass *class, int flags)
__thread AVDictionary * codec_opts
int parse_option(void *optctx, const char *opt, const char *arg, const OptionDef *options)
void show_help_options(const OptionDef *options, const char *msg, int req_flags, int rej_flags, int alt_flags)
__thread AVDictionary * format_opts
int opt_default(void *optctx, const char *opt, const char *arg)
void print_error(const char *filename, int err)
int read_yesno(void)
FILE * get_preset_file(char *filename, size_t filename_size, const char *preset_name, int is_path, const char *codec_name)
void * grow_array(void *array, int elem_size, int *size, int new_size)
AVDictionary ** setup_find_stream_info_opts(AVFormatContext *s, AVDictionary *codec_opts)
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
__thread char * program_name
void uninit_parse_context(OptionParseContext *octx)
int split_commandline(OptionParseContext *octx, int argc, char *argv[], const OptionDef *options, const OptionGroupDef *groups, int nb_groups)
AVDictionary * filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id, AVFormatContext *s, AVStream *st, AVCodec *codec)
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
int parse_optgroup(void *optctx, OptionGroup *g)
double parse_number_or_die(const char *context, const char *numstr, int type, double min, double max)
#define OPT_VIDEO
#define OPT_SPEC
#define OPT_PERFILE
#define OPT_INT
#define AV_LOG_STDERR
#define OPT_INPUT
#define OPT_STRING
#define GROW_ARRAY(array, nb_elems)
#define OPT_AUDIO
#define OPT_SUBTITLE
#define OPT_EXPERT
#define OPT_EXIT
#define OPT_OUTPUT
#define OPT_OFFSET
__thread InputStream ** input_streams
__thread const AVIOInterruptCB int_cb
__thread int nb_input_streams
void term_exit(void)
__thread OutputStream ** output_streams
__thread OutputFile ** output_files
__thread int nb_output_streams
int guess_input_channel_layout(InputStream *ist)
__thread int nb_input_files
__thread int nb_output_files
__thread AVIOContext * progress_avio
__thread InputFile ** input_files
__thread FilterGraph ** filtergraphs
void remove_avoptions(AVDictionary **a, AVDictionary *b)
__thread int nb_filtergraphs
void term_init(void)
int opt_progress(void *optctx, const char *opt, const char *arg)
void assert_avoptions(AVDictionary *m)
@ HWACCEL_NONE
@ HWACCEL_QSV
@ HWACCEL_GENERIC
@ HWACCEL_AUTO
@ HWACCEL_VIDEOTOOLBOX
#define VSYNC_DROP
int videotoolbox_init(AVCodecContext *s)
#define MAX_STREAMS
#define VSYNC_CFR
#define VSYNC_AUTO
int init_simple_filtergraph(InputStream *ist, OutputStream *ost)
int open_files(OptionGroupList *l, const char *inout, int(*open_file)(OptionsContext *, const char *))
int ffmpeg_parse_options(int argc, char **argv)
#define ABORT_ON_FLAG_EMPTY_OUTPUT
int qsv_init(AVCodecContext *s)
#define DECODING_FOR_OST
int hw_device_init_from_string(const char *arg, HWDevice **dev)
void check_filter_outputs(void)
#define VSYNC_PASSTHROUGH
HWDevice * hw_device_get_by_name(const char *name)
#define VSYNC_VFR
#define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM
int init_complex_filtergraph(FilterGraph *fg)
__thread float dts_delta_threshold
#define SET_DICT(type, meta, context, index)
int opt_channel_layout(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_frame_aspect_ratios[]
void uninit_options(OptionsContext *o)
int choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
static const char *const opt_name_max_frames[]
__thread int copy_tb
static const char *const opt_name_audio_channels[]
int opt_sdp_file(void *optctx, const char *opt, const char *arg)
OutputStream * new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
__thread int frame_bits_per_raw_sample
int opt_timecode(void *optctx, const char *opt, const char *arg)
__thread OptionDef * ffmpeg_options
static const char *const opt_name_fix_sub_duration[]
int opt_vstats_file(void *optctx, const char *opt, const char *arg)
void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
OutputStream * new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
__thread int64_t stats_period
int opt_data_codec(void *optctx, const char *opt, const char *arg)
int opt_streamid(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_canvas_sizes[]
int opt_qscale(void *optctx, const char *opt, const char *arg)
int opt_sameq(void *optctx, const char *opt, const char *arg)
OutputStream * new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
__thread char * sdp_filename
static const char *const opt_name_top_field_first[]
int opt_filter_complex(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_autorotate[]
static const char *const opt_name_inter_matrices[]
int opt_vsync(void *optctx, const char *opt, const char *arg)
uint8_t * fftools_read_file(const char *filename)
__thread int print_stats
__thread int video_sync_method
__thread int filter_complex_nbthreads
__thread int abort_on_flags
static const char *const opt_name_sample_fmts[]
static const char *const opt_name_codec_tags[]
static const char *const opt_name_force_fps[]
__thread int audio_volume
__thread float max_error_rate
static const char *const opt_name_passlogfiles[]
static const char *const opt_name_max_muxing_queue_size[]
static const char *const opt_name_muxing_queue_data_threshold[]
static const char *const opt_name_apad[]
static const char *const opt_name_hwaccels[]
__thread int copy_ts
__thread int stdin_interaction
static const char *const opt_name_copy_prior_start[]
static const char *const opt_name_presets[]
int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
#define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)
__thread float dts_error_threshold
int opt_video_standard(void *optctx, const char *opt, const char *arg)
#define DEFAULT_PASS_LOGFILENAME_PREFIX
static const char *const opt_name_frame_rates[]
int open_input_file(OptionsContext *o, const char *filename)
int opt_profile(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_max_frame_rates[]
char * get_ost_filters(OptionsContext *o, AVFormatContext *oc, OutputStream *ost)
AVCodec * find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
__thread int filter_nbthreads
int opt_abort_on(void *optctx, const char *opt, const char *arg)
void show_usage(void)
static const char *const opt_name_hwaccel_devices[]
__thread int copy_unknown_streams
int opt_video_codec(void *optctx, const char *opt, const char *arg)
int opt_data_frames(void *optctx, const char *opt, const char *arg)
uint8_t * get_line(AVIOContext *s)
int opt_video_filters(void *optctx, const char *opt, const char *arg)
__thread int input_sync
int opt_attach(void *optctx, const char *opt, const char *arg)
__thread int do_benchmark
int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
__thread float frame_drop_threshold
__thread int vstats_version
__thread char * vstats_filename
__thread int do_deinterlace
int opt_audio_frames(void *optctx, const char *opt, const char *arg)
__thread int no_file_overwrite
int opt_target(void *optctx, const char *opt, const char *arg)
void check_streamcopy_filters(OptionsContext *o, AVFormatContext *oc, const OutputStream *ost, enum AVMediaType type)
static const char *const opt_name_discard[]
static const char *const opt_name_rc_overrides[]
static const char *const opt_name_forced_key_frames[]
__thread int audio_sync_method
int init_complex_filters(void)
OutputStream * new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
static const char *const opt_name_time_bases[]
__thread int file_overwrite
int opt_map(void *optctx, const char *opt, const char *arg)
__thread float audio_drift_threshold
static const char *const opt_name_frame_sizes[]
static const char *const opt_name_audio_sample_rate[]
static const char *const opt_name_filter_scripts[]
__thread int do_benchmark_all
int opt_vstats(void *optctx, const char *opt, const char *arg)
AVCodec * choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
int opt_video_channel(void *optctx, const char *opt, const char *arg)
__thread int start_at_zero
static const char *const opt_name_enc_time_bases[]
void parse_matrix_coeffs(uint16_t *dest, const char *str)
static const char *const opt_name_reinit_filters[]
__thread int find_stream_info
int opt_video_frames(void *optctx, const char *opt, const char *arg)
void assert_file_overwrite(const char *filename)
int opt_audio_filters(void *optctx, const char *opt, const char *arg)
__thread int exit_on_error
static const char *const opt_name_guess_layout_max[]
int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
void init_output_filter(OutputFilter *ofilter, OptionsContext *o, AVFormatContext *oc)
OutputStream * new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
AVDictionary * strip_specifiers(AVDictionary *dict)
int show_hwaccels(void *optctx, const char *opt, const char *arg)
__thread HWDevice * filter_hw_device
int opt_preset(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_hwaccel_output_formats[]
static const char *const opt_name_chroma_intra_matrices[]
int opt_old2new(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_filters[]
static const char *const opt_name_copy_initial_nonkeyframes[]
int opt_stats_period(void *optctx, const char *opt, const char *arg)
static const char *const opt_name_intra_matrices[]
#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)
void add_input_streams(OptionsContext *o, AVFormatContext *ic)
static const char *const opt_name_bitstream_filters[]
__thread int qp_hist
static const char *const opt_name_qscale[]
int opt_bitrate(void *optctx, const char *opt, const char *arg)
OutputStream * new_unknown_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
static const char *const opt_name_codec_names[]
int fftools_copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
int opt_default_new(OptionsContext *o, const char *opt, const char *arg)
OutputStream * new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
__thread int do_psnr
__thread int do_hex_dump
static const char *const opt_name_autoscale[]
__thread int do_pkt_dump
const HWAccel hwaccels[]
void dump_attachment(AVStream *st, const char *filename)
void init_options(OptionsContext *o)
__thread int debug_ts
int opt_map_channel(void *optctx, const char *opt, const char *arg)
int open_output_file(OptionsContext *o, const char *filename)
int opt_audio_codec(void *optctx, const char *opt, const char *arg)
int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
__thread int auto_conversion_filters
static const char *const opt_name_ts_scale[]
static const char *const opt_name_disposition[]
void show_help_default_ffmpeg(const char *opt, const char *arg)
__thread int input_stream_potentially_available
static const char *const opt_name_frame_pix_fmts[]
__thread int ignore_unknown_streams
__thread int intra_only
static const char *const opt_name_pass[]
int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
__thread int nb_streams
OutputFilter ** outputs
const char * graph_desc
enum HWAccelID id
const char * name
int64_t ts_offset
int64_t duration
InputStream * streams
AVFormatContext * ctx
int64_t input_ts_offset
int64_t recording_time
AVRational time_base
int64_t start_time
enum AVPixelFormat hwaccel_pix_fmt
enum AVPixelFormat hwaccel_output_format
AVCodecContext * dec_ctx
AVCodec * dec
enum HWAccelID hwaccel_id
int64_t filter_in_rescale_delta_last
int64_t max_pts
AVStream * st
char * hwaccel_device
AVDictionary * decoder_opts
int64_t min_pts
enum AVHWDeviceType hwaccel_device_type
int64_t nb_samples
AVRational framerate
union OptionDef::@1 u
const char * name
AVDictionary * codec_opts
AVDictionary * swr_opts
AVDictionary * sws_dict
const char * arg
AVDictionary * format_opts
AVDictionary * resample_opts
OptionGroup * groups
OptionGroupList * groups
SpecifierOpt * metadata_map
SpecifierOpt * frame_pix_fmts
SpecifierOpt * dump_attachment
const char * format
int64_t input_ts_offset
SpecifierOpt * audio_sample_rate
SpecifierOpt * max_frames
StreamMap * stream_maps
SpecifierOpt * frame_sizes
SpecifierOpt * metadata
int64_t recording_time
uint64_t limit_filesize
SpecifierOpt * audio_channels
int64_t start_time_eof
SpecifierOpt * frame_rates
int metadata_chapters_manual
const char ** attachments
SpecifierOpt * program
AudioChannelMap * audio_channel_maps
OptionGroup * g
uint64_t limit_filesize
AVFormatContext * ctx
int64_t start_time
start time in microseconds == AV_TIME_BASE units
AVDictionary * opts
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
AVFilterInOut * out_tmp
struct OutputStream * ost
uint64_t * channel_layouts
AVRational frame_rate
uint64_t channel_layout
enum AVMediaType type
int max_muxing_queue_size
AVDictionary * swr_opts
int copy_initial_nonkeyframes
int64_t last_mux_dts
OSTFinished finished
int * audio_channels_map
AVRational frame_aspect_ratio
double rotate_override_value
int audio_channels_mapped
int64_t max_frames
size_t muxing_queue_data_threshold
AVDictionary * resample_opts
AVRational max_frame_rate
AVRational enc_timebase
AVFifoBuffer * muxing_queue
AVCodecParameters * ref_par
char * forced_keyframes
const char * attachment_filename
AVRational frame_rate
AVCodecContext * enc_ctx
struct InputStream * sync_ist
AVDictionary * encoder_opts
AVStream * st
char * filters
filtergraph associated to the -filter option
int64_t forced_kf_ref_pts
char * filters_script
filtergraph script associated to the -filter_script option
AVBSFContext * bsf_ctx
AVCodec * enc
AVDictionary * sws_dict
OutputFilter * filter
char * disposition
size_t muxing_queue_data_size
char * logfile_prefix
union SpecifierOpt::@0 u
int sync_stream_index
char * linklabel
int sync_file_index