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