FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
cmdutils.c
Go to the documentation of this file.
1 /*
2  * Various utilities for command line tools
3  * Copyright (c) 2000-2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <string.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <math.h>
26 
27 /* Include only the enabled headers since some compilers (namely, Sun
28  Studio) will not omit unused inline functions and create undefined
29  references to libraries that are not being built. */
30 
31 #include "config.h"
32 #include "compat/va_copy.h"
33 #include "libavformat/avformat.h"
34 #include "libavfilter/avfilter.h"
35 #include "libavdevice/avdevice.h"
37 #include "libswscale/swscale.h"
40 #include "libavutil/avassert.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/bprint.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/imgutils.h"
45 #include "libavutil/parseutils.h"
46 #include "libavutil/pixdesc.h"
47 #include "libavutil/eval.h"
48 #include "libavutil/dict.h"
49 #include "libavutil/opt.h"
50 #include "cmdutils.h"
51 #include "version.h"
52 #if CONFIG_NETWORK
53 #include "libavformat/network.h"
54 #endif
55 #if HAVE_SYS_RESOURCE_H
56 #include <sys/time.h>
57 #include <sys/resource.h>
58 #endif
59 #if CONFIG_OPENCL
60 #include "libavutil/opencl.h"
61 #endif
62 
63 
64 static int init_report(const char *env);
65 
69 
70 const int this_year = 2013;
71 
72 static FILE *report_file;
73 
74 void init_opts(void)
75 {
76 
77  if(CONFIG_SWSCALE)
78  sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
79  NULL, NULL, NULL);
80 }
81 
82 void uninit_opts(void)
83 {
84 #if CONFIG_SWSCALE
85  sws_freeContext(sws_opts);
86  sws_opts = NULL;
87 #endif
88 
89  av_dict_free(&swr_opts);
90  av_dict_free(&format_opts);
91  av_dict_free(&codec_opts);
92  av_dict_free(&resample_opts);
93 }
94 
95 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
96 {
97  vfprintf(stdout, fmt, vl);
98 }
99 
100 static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
101 {
102  va_list vl2;
103  char line[1024];
104  static int print_prefix = 1;
105 
106  va_copy(vl2, vl);
107  av_log_default_callback(ptr, level, fmt, vl);
108  av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
109  va_end(vl2);
110  fputs(line, report_file);
111  fflush(report_file);
112 }
113 
114 static void (*program_exit)(int ret);
115 
116 void register_exit(void (*cb)(int ret))
117 {
118  program_exit = cb;
119 }
120 
121 void exit_program(int ret)
122 {
123  if (program_exit)
124  program_exit(ret);
125 
126  exit(ret);
127 }
128 
129 double parse_number_or_die(const char *context, const char *numstr, int type,
130  double min, double max)
131 {
132  char *tail;
133  const char *error;
134  double d = av_strtod(numstr, &tail);
135  if (*tail)
136  error = "Expected number for %s but found: %s\n";
137  else if (d < min || d > max)
138  error = "The value for %s was %s which is not within %f - %f\n";
139  else if (type == OPT_INT64 && (int64_t)d != d)
140  error = "Expected int64 for %s but found %s\n";
141  else if (type == OPT_INT && (int)d != d)
142  error = "Expected int for %s but found %s\n";
143  else
144  return d;
145  av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
146  exit_program(1);
147  return 0;
148 }
149 
150 int64_t parse_time_or_die(const char *context, const char *timestr,
151  int is_duration)
152 {
153  int64_t us;
154  if (av_parse_time(&us, timestr, is_duration) < 0) {
155  av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
156  is_duration ? "duration" : "date", context, timestr);
157  exit_program(1);
158  }
159  return us;
160 }
161 
162 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
163  int rej_flags, int alt_flags)
164 {
165  const OptionDef *po;
166  int first;
167 
168  first = 1;
169  for (po = options; po->name != NULL; po++) {
170  char buf[64];
171 
172  if (((po->flags & req_flags) != req_flags) ||
173  (alt_flags && !(po->flags & alt_flags)) ||
174  (po->flags & rej_flags))
175  continue;
176 
177  if (first) {
178  printf("%s\n", msg);
179  first = 0;
180  }
181  av_strlcpy(buf, po->name, sizeof(buf));
182  if (po->argname) {
183  av_strlcat(buf, " ", sizeof(buf));
184  av_strlcat(buf, po->argname, sizeof(buf));
185  }
186  printf("-%-17s %s\n", buf, po->help);
187  }
188  printf("\n");
189 }
190 
191 void show_help_children(const AVClass *class, int flags)
192 {
193  const AVClass *child = NULL;
194  if (class->option) {
195  av_opt_show2(&class, NULL, flags, 0);
196  printf("\n");
197  }
198 
199  while (child = av_opt_child_class_next(class, child))
200  show_help_children(child, flags);
201 }
202 
203 static const OptionDef *find_option(const OptionDef *po, const char *name)
204 {
205  const char *p = strchr(name, ':');
206  int len = p ? p - name : strlen(name);
207 
208  while (po->name != NULL) {
209  if (!strncmp(name, po->name, len) && strlen(po->name) == len)
210  break;
211  po++;
212  }
213  return po;
214 }
215 
216 #if HAVE_COMMANDLINETOARGVW
217 #include <windows.h>
218 #include <shellapi.h>
219 /* Will be leaked on exit */
220 static char** win32_argv_utf8 = NULL;
221 static int win32_argc = 0;
222 
223 /**
224  * Prepare command line arguments for executable.
225  * For Windows - perform wide-char to UTF-8 conversion.
226  * Input arguments should be main() function arguments.
227  * @param argc_ptr Arguments number (including executable)
228  * @param argv_ptr Arguments list.
229  */
230 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
231 {
232  char *argstr_flat;
233  wchar_t **argv_w;
234  int i, buffsize = 0, offset = 0;
235 
236  if (win32_argv_utf8) {
237  *argc_ptr = win32_argc;
238  *argv_ptr = win32_argv_utf8;
239  return;
240  }
241 
242  win32_argc = 0;
243  argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
244  if (win32_argc <= 0 || !argv_w)
245  return;
246 
247  /* determine the UTF-8 buffer size (including NULL-termination symbols) */
248  for (i = 0; i < win32_argc; i++)
249  buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
250  NULL, 0, NULL, NULL);
251 
252  win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
253  argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
254  if (win32_argv_utf8 == NULL) {
255  LocalFree(argv_w);
256  return;
257  }
258 
259  for (i = 0; i < win32_argc; i++) {
260  win32_argv_utf8[i] = &argstr_flat[offset];
261  offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
262  &argstr_flat[offset],
263  buffsize - offset, NULL, NULL);
264  }
265  win32_argv_utf8[i] = NULL;
266  LocalFree(argv_w);
267 
268  *argc_ptr = win32_argc;
269  *argv_ptr = win32_argv_utf8;
270 }
271 #else
272 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
273 {
274  /* nothing to do */
275 }
276 #endif /* HAVE_COMMANDLINETOARGVW */
277 
278 static int write_option(void *optctx, const OptionDef *po, const char *opt,
279  const char *arg)
280 {
281  /* new-style options contain an offset into optctx, old-style address of
282  * a global var*/
283  void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
284  (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
285  int *dstcount;
286 
287  if (po->flags & OPT_SPEC) {
288  SpecifierOpt **so = dst;
289  char *p = strchr(opt, ':');
290 
291  dstcount = (int *)(so + 1);
292  *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
293  (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
294  dst = &(*so)[*dstcount - 1].u;
295  }
296 
297  if (po->flags & OPT_STRING) {
298  char *str;
299  str = av_strdup(arg);
300  av_freep(dst);
301  *(char **)dst = str;
302  } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
303  *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
304  } else if (po->flags & OPT_INT64) {
305  *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
306  } else if (po->flags & OPT_TIME) {
307  *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
308  } else if (po->flags & OPT_FLOAT) {
309  *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
310  } else if (po->flags & OPT_DOUBLE) {
311  *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
312  } else if (po->u.func_arg) {
313  int ret = po->u.func_arg(optctx, opt, arg);
314  if (ret < 0) {
315  av_log(NULL, AV_LOG_ERROR,
316  "Failed to set value '%s' for option '%s': %s\n",
317  arg, opt, av_err2str(ret));
318  return ret;
319  }
320  }
321  if (po->flags & OPT_EXIT)
322  exit_program(0);
323 
324  return 0;
325 }
326 
327 int parse_option(void *optctx, const char *opt, const char *arg,
328  const OptionDef *options)
329 {
330  const OptionDef *po;
331  int ret;
332 
333  po = find_option(options, opt);
334  if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
335  /* handle 'no' bool option */
336  po = find_option(options, opt + 2);
337  if ((po->name && (po->flags & OPT_BOOL)))
338  arg = "0";
339  } else if (po->flags & OPT_BOOL)
340  arg = "1";
341 
342  if (!po->name)
343  po = find_option(options, "default");
344  if (!po->name) {
345  av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
346  return AVERROR(EINVAL);
347  }
348  if (po->flags & HAS_ARG && !arg) {
349  av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
350  return AVERROR(EINVAL);
351  }
352 
353  ret = write_option(optctx, po, opt, arg);
354  if (ret < 0)
355  return ret;
356 
357  return !!(po->flags & HAS_ARG);
358 }
359 
360 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
361  void (*parse_arg_function)(void *, const char*))
362 {
363  const char *opt;
364  int optindex, handleoptions = 1, ret;
365 
366  /* perform system-dependent conversions for arguments list */
367  prepare_app_arguments(&argc, &argv);
368 
369  /* parse options */
370  optindex = 1;
371  while (optindex < argc) {
372  opt = argv[optindex++];
373 
374  if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
375  if (opt[1] == '-' && opt[2] == '\0') {
376  handleoptions = 0;
377  continue;
378  }
379  opt++;
380 
381  if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
382  exit_program(1);
383  optindex += ret;
384  } else {
385  if (parse_arg_function)
386  parse_arg_function(optctx, opt);
387  }
388  }
389 }
390 
391 int parse_optgroup(void *optctx, OptionGroup *g)
392 {
393  int i, ret;
394 
395  av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
396  g->group_def->name, g->arg);
397 
398  for (i = 0; i < g->nb_opts; i++) {
399  Option *o = &g->opts[i];
400 
401  if (g->group_def->flags &&
402  !(g->group_def->flags & o->opt->flags)) {
403  av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
404  "%s %s -- you are trying to apply an input option to an "
405  "output file or vice versa. Move this option before the "
406  "file it belongs to.\n", o->key, o->opt->help,
407  g->group_def->name, g->arg);
408  return AVERROR(EINVAL);
409  }
410 
411  av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
412  o->key, o->opt->help, o->val);
413 
414  ret = write_option(optctx, o->opt, o->key, o->val);
415  if (ret < 0)
416  return ret;
417  }
418 
419  av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
420 
421  return 0;
422 }
423 
424 int locate_option(int argc, char **argv, const OptionDef *options,
425  const char *optname)
426 {
427  const OptionDef *po;
428  int i;
429 
430  for (i = 1; i < argc; i++) {
431  const char *cur_opt = argv[i];
432 
433  if (*cur_opt++ != '-')
434  continue;
435 
436  po = find_option(options, cur_opt);
437  if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
438  po = find_option(options, cur_opt + 2);
439 
440  if ((!po->name && !strcmp(cur_opt, optname)) ||
441  (po->name && !strcmp(optname, po->name)))
442  return i;
443 
444  if (po->flags & HAS_ARG)
445  i++;
446  }
447  return 0;
448 }
449 
450 static void dump_argument(const char *a)
451 {
452  const unsigned char *p;
453 
454  for (p = a; *p; p++)
455  if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
456  *p == '_' || (*p >= 'a' && *p <= 'z')))
457  break;
458  if (!*p) {
459  fputs(a, report_file);
460  return;
461  }
462  fputc('"', report_file);
463  for (p = a; *p; p++) {
464  if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
465  fprintf(report_file, "\\%c", *p);
466  else if (*p < ' ' || *p > '~')
467  fprintf(report_file, "\\x%02x", *p);
468  else
469  fputc(*p, report_file);
470  }
471  fputc('"', report_file);
472 }
473 
474 void parse_loglevel(int argc, char **argv, const OptionDef *options)
475 {
476  int idx = locate_option(argc, argv, options, "loglevel");
477  const char *env;
478  if (!idx)
479  idx = locate_option(argc, argv, options, "v");
480  if (idx && argv[idx + 1])
481  opt_loglevel(NULL, "loglevel", argv[idx + 1]);
482  idx = locate_option(argc, argv, options, "report");
483  if ((env = getenv("FFREPORT")) || idx) {
484  init_report(env);
485  if (report_file) {
486  int i;
487  fprintf(report_file, "Command line:\n");
488  for (i = 0; i < argc; i++) {
489  dump_argument(argv[i]);
490  fputc(i < argc - 1 ? ' ' : '\n', report_file);
491  }
492  fflush(report_file);
493  }
494  }
495 }
496 
497 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
498 int opt_default(void *optctx, const char *opt, const char *arg)
499 {
500  const AVOption *o;
501  int consumed = 0;
502  char opt_stripped[128];
503  const char *p;
504  const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
505 #if CONFIG_AVRESAMPLE
506  const AVClass *rc = avresample_get_class();
507 #endif
508  const AVClass *sc, *swr_class;
509 
510  if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
512 
513  if (!(p = strchr(opt, ':')))
514  p = opt + strlen(opt);
515  av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
516 
517  if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
519  ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
520  (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
521  av_dict_set(&codec_opts, opt, arg, FLAGS);
522  consumed = 1;
523  }
524  if ((o = av_opt_find(&fc, opt, NULL, 0,
526  av_dict_set(&format_opts, opt, arg, FLAGS);
527  if (consumed)
528  av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);
529  consumed = 1;
530  }
531 #if CONFIG_SWSCALE
532  sc = sws_get_class();
533  if (!consumed && av_opt_find(&sc, opt, NULL, 0,
535  // XXX we only support sws_flags, not arbitrary sws options
536  int ret = av_opt_set(sws_opts, opt, arg, 0);
537  if (ret < 0) {
538  av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
539  return ret;
540  }
541  consumed = 1;
542  }
543 #endif
544 #if CONFIG_SWRESAMPLE
545  swr_class = swr_get_class();
546  if (!consumed && (o=av_opt_find(&swr_class, opt, NULL, 0,
548  struct SwrContext *swr = swr_alloc();
549  int ret = av_opt_set(swr, opt, arg, 0);
550  swr_free(&swr);
551  if (ret < 0) {
552  av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
553  return ret;
554  }
555  av_dict_set(&swr_opts, opt, arg, FLAGS);
556  consumed = 1;
557  }
558 #endif
559 #if CONFIG_AVRESAMPLE
560  if ((o=av_opt_find(&rc, opt, NULL, 0,
562  av_dict_set(&resample_opts, opt, arg, FLAGS);
563  consumed = 1;
564  }
565 #endif
566 
567  if (consumed)
568  return 0;
570 }
571 
572 /*
573  * Check whether given option is a group separator.
574  *
575  * @return index of the group definition that matched or -1 if none
576  */
577 static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
578  const char *opt)
579 {
580  int i;
581 
582  for (i = 0; i < nb_groups; i++) {
583  const OptionGroupDef *p = &groups[i];
584  if (p->sep && !strcmp(p->sep, opt))
585  return i;
586  }
587 
588  return -1;
589 }
590 
591 /*
592  * Finish parsing an option group.
593  *
594  * @param group_idx which group definition should this group belong to
595  * @param arg argument of the group delimiting option
596  */
597 static void finish_group(OptionParseContext *octx, int group_idx,
598  const char *arg)
599 {
600  OptionGroupList *l = &octx->groups[group_idx];
601  OptionGroup *g;
602 
603  GROW_ARRAY(l->groups, l->nb_groups);
604  g = &l->groups[l->nb_groups - 1];
605 
606  *g = octx->cur_group;
607  g->arg = arg;
608  g->group_def = l->group_def;
609 #if CONFIG_SWSCALE
610  g->sws_opts = sws_opts;
611 #endif
612  g->swr_opts = swr_opts;
613  g->codec_opts = codec_opts;
616 
617  codec_opts = NULL;
618  format_opts = NULL;
619  resample_opts = NULL;
620 #if CONFIG_SWSCALE
621  sws_opts = NULL;
622 #endif
623  swr_opts = NULL;
624  init_opts();
625 
626  memset(&octx->cur_group, 0, sizeof(octx->cur_group));
627 }
628 
629 /*
630  * Add an option instance to currently parsed group.
631  */
632 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
633  const char *key, const char *val)
634 {
635  int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
636  OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
637 
638  GROW_ARRAY(g->opts, g->nb_opts);
639  g->opts[g->nb_opts - 1].opt = opt;
640  g->opts[g->nb_opts - 1].key = key;
641  g->opts[g->nb_opts - 1].val = val;
642 }
643 
645  const OptionGroupDef *groups, int nb_groups)
646 {
647  static const OptionGroupDef global_group = { "global" };
648  int i;
649 
650  memset(octx, 0, sizeof(*octx));
651 
652  octx->nb_groups = nb_groups;
653  octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
654  if (!octx->groups)
655  exit_program(1);
656 
657  for (i = 0; i < octx->nb_groups; i++)
658  octx->groups[i].group_def = &groups[i];
659 
660  octx->global_opts.group_def = &global_group;
661  octx->global_opts.arg = "";
662 
663  init_opts();
664 }
665 
667 {
668  int i, j;
669 
670  for (i = 0; i < octx->nb_groups; i++) {
671  OptionGroupList *l = &octx->groups[i];
672 
673  for (j = 0; j < l->nb_groups; j++) {
674  av_freep(&l->groups[j].opts);
678 #if CONFIG_SWSCALE
680 #endif
681  av_dict_free(&l->groups[j].swr_opts);
682  }
683  av_freep(&l->groups);
684  }
685  av_freep(&octx->groups);
686 
687  av_freep(&octx->cur_group.opts);
688  av_freep(&octx->global_opts.opts);
689 
690  uninit_opts();
691 }
692 
693 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
694  const OptionDef *options,
695  const OptionGroupDef *groups, int nb_groups)
696 {
697  int optindex = 1;
698  int dashdash = -2;
699 
700  /* perform system-dependent conversions for arguments list */
701  prepare_app_arguments(&argc, &argv);
702 
703  init_parse_context(octx, groups, nb_groups);
704  av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
705 
706  while (optindex < argc) {
707  const char *opt = argv[optindex++], *arg;
708  const OptionDef *po;
709  int ret;
710 
711  av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
712 
713  if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
714  dashdash = optindex;
715  continue;
716  }
717  /* unnamed group separators, e.g. output filename */
718  if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
719  finish_group(octx, 0, opt);
720  av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
721  continue;
722  }
723  opt++;
724 
725 #define GET_ARG(arg) \
726 do { \
727  arg = argv[optindex++]; \
728  if (!arg) { \
729  av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
730  return AVERROR(EINVAL); \
731  } \
732 } while (0)
733 
734  /* named group separators, e.g. -i */
735  if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
736  GET_ARG(arg);
737  finish_group(octx, ret, arg);
738  av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
739  groups[ret].name, arg);
740  continue;
741  }
742 
743  /* normal options */
744  po = find_option(options, opt);
745  if (po->name) {
746  if (po->flags & OPT_EXIT) {
747  /* optional argument, e.g. -h */
748  arg = argv[optindex++];
749  } else if (po->flags & HAS_ARG) {
750  GET_ARG(arg);
751  } else {
752  arg = "1";
753  }
754 
755  add_opt(octx, po, opt, arg);
756  av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
757  "argument '%s'.\n", po->name, po->help, arg);
758  continue;
759  }
760 
761  /* AVOptions */
762  if (argv[optindex]) {
763  ret = opt_default(NULL, opt, argv[optindex]);
764  if (ret >= 0) {
765  av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
766  "argument '%s'.\n", opt, argv[optindex]);
767  optindex++;
768  continue;
769  } else if (ret != AVERROR_OPTION_NOT_FOUND) {
770  av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
771  "with argument '%s'.\n", opt, argv[optindex]);
772  return ret;
773  }
774  }
775 
776  /* boolean -nofoo options */
777  if (opt[0] == 'n' && opt[1] == 'o' &&
778  (po = find_option(options, opt + 2)) &&
779  po->name && po->flags & OPT_BOOL) {
780  add_opt(octx, po, opt, "0");
781  av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
782  "argument 0.\n", po->name, po->help);
783  continue;
784  }
785 
786  av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
788  }
789 
790  if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
791  av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
792  "commandline.\n");
793 
794  av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
795 
796  return 0;
797 }
798 
799 int opt_loglevel(void *optctx, const char *opt, const char *arg)
800 {
801  const struct { const char *name; int level; } log_levels[] = {
802  { "quiet" , AV_LOG_QUIET },
803  { "panic" , AV_LOG_PANIC },
804  { "fatal" , AV_LOG_FATAL },
805  { "error" , AV_LOG_ERROR },
806  { "warning", AV_LOG_WARNING },
807  { "info" , AV_LOG_INFO },
808  { "verbose", AV_LOG_VERBOSE },
809  { "debug" , AV_LOG_DEBUG },
810  };
811  char *tail;
812  int level;
813  int i;
814 
815  tail = strstr(arg, "repeat");
817  if (tail == arg)
818  arg += 6 + (arg[6]=='+');
819  if(tail && !*arg)
820  return 0;
821 
822  for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
823  if (!strcmp(log_levels[i].name, arg)) {
824  av_log_set_level(log_levels[i].level);
825  return 0;
826  }
827  }
828 
829  level = strtol(arg, &tail, 10);
830  if (*tail) {
831  av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
832  "Possible levels are numbers or:\n", arg);
833  for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
834  av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
835  exit_program(1);
836  }
837  av_log_set_level(level);
838  return 0;
839 }
840 
841 static void expand_filename_template(AVBPrint *bp, const char *template,
842  struct tm *tm)
843 {
844  int c;
845 
846  while ((c = *(template++))) {
847  if (c == '%') {
848  if (!(c = *(template++)))
849  break;
850  switch (c) {
851  case 'p':
852  av_bprintf(bp, "%s", program_name);
853  break;
854  case 't':
855  av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
856  tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
857  tm->tm_hour, tm->tm_min, tm->tm_sec);
858  break;
859  case '%':
860  av_bprint_chars(bp, c, 1);
861  break;
862  }
863  } else {
864  av_bprint_chars(bp, c, 1);
865  }
866  }
867 }
868 
869 static int init_report(const char *env)
870 {
871  char *filename_template = NULL;
872  char *key, *val;
873  int ret, count = 0;
874  time_t now;
875  struct tm *tm;
876  AVBPrint filename;
877 
878  if (report_file) /* already opened */
879  return 0;
880  time(&now);
881  tm = localtime(&now);
882 
883  while (env && *env) {
884  if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
885  if (count)
886  av_log(NULL, AV_LOG_ERROR,
887  "Failed to parse FFREPORT environment variable: %s\n",
888  av_err2str(ret));
889  break;
890  }
891  if (*env)
892  env++;
893  count++;
894  if (!strcmp(key, "file")) {
895  av_free(filename_template);
896  filename_template = val;
897  val = NULL;
898  } else {
899  av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
900  }
901  av_free(val);
902  av_free(key);
903  }
904 
905  av_bprint_init(&filename, 0, 1);
906  expand_filename_template(&filename,
907  av_x_if_null(filename_template, "%p-%t.log"), tm);
908  av_free(filename_template);
909  if (!av_bprint_is_complete(&filename)) {
910  av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
911  return AVERROR(ENOMEM);
912  }
913 
914  report_file = fopen(filename.str, "w");
915  if (!report_file) {
916  av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
917  filename.str, strerror(errno));
918  return AVERROR(errno);
919  }
921  av_log(NULL, AV_LOG_INFO,
922  "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
923  "Report written to \"%s\"\n",
924  program_name,
925  tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
926  tm->tm_hour, tm->tm_min, tm->tm_sec,
927  filename.str);
928  av_bprint_finalize(&filename, NULL);
929  return 0;
930 }
931 
932 int opt_report(const char *opt)
933 {
934  return init_report(NULL);
935 }
936 
937 int opt_max_alloc(void *optctx, const char *opt, const char *arg)
938 {
939  char *tail;
940  size_t max;
941 
942  max = strtol(arg, &tail, 10);
943  if (*tail) {
944  av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
945  exit_program(1);
946  }
947  av_max_alloc(max);
948  return 0;
949 }
950 
951 int opt_cpuflags(void *optctx, const char *opt, const char *arg)
952 {
953  int ret;
954  unsigned flags = av_get_cpu_flags();
955 
956  if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
957  return ret;
958 
959  av_force_cpu_flags(flags);
960  return 0;
961 }
962 
963 int opt_timelimit(void *optctx, const char *opt, const char *arg)
964 {
965 #if HAVE_SETRLIMIT
966  int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
967  struct rlimit rl = { lim, lim + 1 };
968  if (setrlimit(RLIMIT_CPU, &rl))
969  perror("setrlimit");
970 #else
971  av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
972 #endif
973  return 0;
974 }
975 
976 #if CONFIG_OPENCL
977 int opt_opencl(void *optctx, const char *opt, const char *arg)
978 {
979  char *key, *value;
980  const char *opts = arg;
981  int ret = 0;
982  while (*opts) {
983  ret = av_opt_get_key_value(&opts, "=", ":", 0, &key, &value);
984  if (ret < 0)
985  return ret;
986  ret = av_opencl_set_option(key, value);
987  if (ret < 0)
988  return ret;
989  if (*opts)
990  opts++;
991  }
992  return ret;
993 }
994 #endif
995 
996 void print_error(const char *filename, int err)
997 {
998  char errbuf[128];
999  const char *errbuf_ptr = errbuf;
1000 
1001  if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
1002  errbuf_ptr = strerror(AVUNERROR(err));
1003  av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
1004 }
1005 
1006 static int warned_cfg = 0;
1007 
1008 #define INDENT 1
1009 #define SHOW_VERSION 2
1010 #define SHOW_CONFIG 4
1011 #define SHOW_COPYRIGHT 8
1012 
1013 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
1014  if (CONFIG_##LIBNAME) { \
1015  const char *indent = flags & INDENT? " " : ""; \
1016  if (flags & SHOW_VERSION) { \
1017  unsigned int version = libname##_version(); \
1018  av_log(NULL, level, \
1019  "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
1020  indent, #libname, \
1021  LIB##LIBNAME##_VERSION_MAJOR, \
1022  LIB##LIBNAME##_VERSION_MINOR, \
1023  LIB##LIBNAME##_VERSION_MICRO, \
1024  version >> 16, version >> 8 & 0xff, version & 0xff); \
1025  } \
1026  if (flags & SHOW_CONFIG) { \
1027  const char *cfg = libname##_configuration(); \
1028  if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
1029  if (!warned_cfg) { \
1030  av_log(NULL, level, \
1031  "%sWARNING: library configuration mismatch\n", \
1032  indent); \
1033  warned_cfg = 1; \
1034  } \
1035  av_log(NULL, level, "%s%-11s configuration: %s\n", \
1036  indent, #libname, cfg); \
1037  } \
1038  } \
1039  } \
1040 
1041 static void print_all_libs_info(int flags, int level)
1042 {
1043  PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
1044  PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
1045  PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
1046  PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
1047  PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
1048  PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
1049  PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
1050  PRINT_LIB_INFO(swresample,SWRESAMPLE, flags, level);
1051  PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
1052 }
1053 
1054 static void print_program_info(int flags, int level)
1055 {
1056  const char *indent = flags & INDENT? " " : "";
1057 
1058  av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
1059  if (flags & SHOW_COPYRIGHT)
1060  av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
1062  av_log(NULL, level, "\n");
1063  av_log(NULL, level, "%sbuilt on %s %s with %s\n",
1064  indent, __DATE__, __TIME__, CC_IDENT);
1065 
1066  av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
1067 }
1068 
1069 void show_banner(int argc, char **argv, const OptionDef *options)
1070 {
1071  int idx = locate_option(argc, argv, options, "version");
1072  if (idx)
1073  return;
1074 
1078 }
1079 
1080 int show_version(void *optctx, const char *opt, const char *arg)
1081 {
1085 
1086  return 0;
1087 }
1088 
1089 int show_license(void *optctx, const char *opt, const char *arg)
1090 {
1091 #if CONFIG_NONFREE
1092  printf(
1093  "This version of %s has nonfree parts compiled in.\n"
1094  "Therefore it is not legally redistributable.\n",
1095  program_name );
1096 #elif CONFIG_GPLV3
1097  printf(
1098  "%s is free software; you can redistribute it and/or modify\n"
1099  "it under the terms of the GNU General Public License as published by\n"
1100  "the Free Software Foundation; either version 3 of the License, or\n"
1101  "(at your option) any later version.\n"
1102  "\n"
1103  "%s is distributed in the hope that it will be useful,\n"
1104  "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1105  "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1106  "GNU General Public License for more details.\n"
1107  "\n"
1108  "You should have received a copy of the GNU General Public License\n"
1109  "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
1111 #elif CONFIG_GPL
1112  printf(
1113  "%s is free software; you can redistribute it and/or modify\n"
1114  "it under the terms of the GNU General Public License as published by\n"
1115  "the Free Software Foundation; either version 2 of the License, or\n"
1116  "(at your option) any later version.\n"
1117  "\n"
1118  "%s is distributed in the hope that it will be useful,\n"
1119  "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1120  "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1121  "GNU General Public License for more details.\n"
1122  "\n"
1123  "You should have received a copy of the GNU General Public License\n"
1124  "along with %s; if not, write to the Free Software\n"
1125  "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1127 #elif CONFIG_LGPLV3
1128  printf(
1129  "%s is free software; you can redistribute it and/or modify\n"
1130  "it under the terms of the GNU Lesser General Public License as published by\n"
1131  "the Free Software Foundation; either version 3 of the License, or\n"
1132  "(at your option) any later version.\n"
1133  "\n"
1134  "%s is distributed in the hope that it will be useful,\n"
1135  "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1136  "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1137  "GNU Lesser General Public License for more details.\n"
1138  "\n"
1139  "You should have received a copy of the GNU Lesser General Public License\n"
1140  "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
1142 #else
1143  printf(
1144  "%s is free software; you can redistribute it and/or\n"
1145  "modify it under the terms of the GNU Lesser General Public\n"
1146  "License as published by the Free Software Foundation; either\n"
1147  "version 2.1 of the License, or (at your option) any later version.\n"
1148  "\n"
1149  "%s is distributed in the hope that it will be useful,\n"
1150  "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1151  "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1152  "Lesser General Public License for more details.\n"
1153  "\n"
1154  "You should have received a copy of the GNU Lesser General Public\n"
1155  "License along with %s; if not, write to the Free Software\n"
1156  "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1158 #endif
1159 
1160  return 0;
1161 }
1162 
1163 int show_formats(void *optctx, const char *opt, const char *arg)
1164 {
1165  AVInputFormat *ifmt = NULL;
1166  AVOutputFormat *ofmt = NULL;
1167  const char *last_name;
1168 
1169  printf("File formats:\n"
1170  " D. = Demuxing supported\n"
1171  " .E = Muxing supported\n"
1172  " --\n");
1173  last_name = "000";
1174  for (;;) {
1175  int decode = 0;
1176  int encode = 0;
1177  const char *name = NULL;
1178  const char *long_name = NULL;
1179 
1180  while ((ofmt = av_oformat_next(ofmt))) {
1181  if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
1182  strcmp(ofmt->name, last_name) > 0) {
1183  name = ofmt->name;
1184  long_name = ofmt->long_name;
1185  encode = 1;
1186  }
1187  }
1188  while ((ifmt = av_iformat_next(ifmt))) {
1189  if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
1190  strcmp(ifmt->name, last_name) > 0) {
1191  name = ifmt->name;
1192  long_name = ifmt->long_name;
1193  encode = 0;
1194  }
1195  if (name && strcmp(ifmt->name, name) == 0)
1196  decode = 1;
1197  }
1198  if (name == NULL)
1199  break;
1200  last_name = name;
1201 
1202  printf(" %s%s %-15s %s\n",
1203  decode ? "D" : " ",
1204  encode ? "E" : " ",
1205  name,
1206  long_name ? long_name:" ");
1207  }
1208  return 0;
1209 }
1210 
1211 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
1212  if (codec->field) { \
1213  const type *p = codec->field; \
1214  \
1215  printf(" Supported " list_name ":"); \
1216  while (*p != term) { \
1217  get_name(*p); \
1218  printf(" %s", name); \
1219  p++; \
1220  } \
1221  printf("\n"); \
1222  } \
1223 
1224 static void print_codec(const AVCodec *c)
1225 {
1226  int encoder = av_codec_is_encoder(c);
1227 
1228  printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
1229  c->long_name ? c->long_name : "");
1230 
1231  if (c->type == AVMEDIA_TYPE_VIDEO ||
1232  c->type == AVMEDIA_TYPE_AUDIO) {
1233  printf(" Threading capabilities: ");
1234  switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
1237  CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
1238  case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
1239  case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
1240  default: printf("no"); break;
1241  }
1242  printf("\n");
1243  }
1244 
1245  if (c->supported_framerates) {
1246  const AVRational *fps = c->supported_framerates;
1247 
1248  printf(" Supported framerates:");
1249  while (fps->num) {
1250  printf(" %d/%d", fps->num, fps->den);
1251  fps++;
1252  }
1253  printf("\n");
1254  }
1255  PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
1257  PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
1259  PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
1261  PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
1262  0, GET_CH_LAYOUT_DESC);
1263 
1264  if (c->priv_class) {
1268  }
1269 }
1270 
1271 static char get_media_type_char(enum AVMediaType type)
1272 {
1273  switch (type) {
1274  case AVMEDIA_TYPE_VIDEO: return 'V';
1275  case AVMEDIA_TYPE_AUDIO: return 'A';
1276  case AVMEDIA_TYPE_DATA: return 'D';
1277  case AVMEDIA_TYPE_SUBTITLE: return 'S';
1278  case AVMEDIA_TYPE_ATTACHMENT:return 'T';
1279  default: return '?';
1280  }
1281 }
1282 
1283 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
1284  int encoder)
1285 {
1286  while ((prev = av_codec_next(prev))) {
1287  if (prev->id == id &&
1288  (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
1289  return prev;
1290  }
1291  return NULL;
1292 }
1293 
1294 static int compare_codec_desc(const void *a, const void *b)
1295 {
1296  const AVCodecDescriptor * const *da = a;
1297  const AVCodecDescriptor * const *db = b;
1298 
1299  return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
1300  strcmp((*da)->name, (*db)->name);
1301 }
1302 
1303 static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
1304 {
1305  const AVCodecDescriptor *desc = NULL;
1306  const AVCodecDescriptor **codecs;
1307  unsigned nb_codecs = 0, i = 0;
1308 
1309  while ((desc = avcodec_descriptor_next(desc)))
1310  nb_codecs++;
1311  if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
1312  av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
1313  exit_program(1);
1314  }
1315  desc = NULL;
1316  while ((desc = avcodec_descriptor_next(desc)))
1317  codecs[i++] = desc;
1318  av_assert0(i == nb_codecs);
1319  qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
1320  *rcodecs = codecs;
1321  return nb_codecs;
1322 }
1323 
1324 static void print_codecs_for_id(enum AVCodecID id, int encoder)
1325 {
1326  const AVCodec *codec = NULL;
1327 
1328  printf(" (%s: ", encoder ? "encoders" : "decoders");
1329 
1330  while ((codec = next_codec_for_id(id, codec, encoder)))
1331  printf("%s ", codec->name);
1332 
1333  printf(")");
1334 }
1335 
1336 int show_codecs(void *optctx, const char *opt, const char *arg)
1337 {
1338  const AVCodecDescriptor **codecs;
1339  unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1340 
1341  printf("Codecs:\n"
1342  " D..... = Decoding supported\n"
1343  " .E.... = Encoding supported\n"
1344  " ..V... = Video codec\n"
1345  " ..A... = Audio codec\n"
1346  " ..S... = Subtitle codec\n"
1347  " ...I.. = Intra frame-only codec\n"
1348  " ....L. = Lossy compression\n"
1349  " .....S = Lossless compression\n"
1350  " -------\n");
1351  for (i = 0; i < nb_codecs; i++) {
1352  const AVCodecDescriptor *desc = codecs[i];
1353  const AVCodec *codec = NULL;
1354 
1355  printf(" ");
1356  printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1357  printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1358 
1359  printf("%c", get_media_type_char(desc->type));
1360  printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1361  printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
1362  printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
1363 
1364  printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1365 
1366  /* print decoders/encoders when there's more than one or their
1367  * names are different from codec name */
1368  while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1369  if (strcmp(codec->name, desc->name)) {
1370  print_codecs_for_id(desc->id, 0);
1371  break;
1372  }
1373  }
1374  codec = NULL;
1375  while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1376  if (strcmp(codec->name, desc->name)) {
1377  print_codecs_for_id(desc->id, 1);
1378  break;
1379  }
1380  }
1381 
1382  printf("\n");
1383  }
1384  av_free(codecs);
1385  return 0;
1386 }
1387 
1388 static void print_codecs(int encoder)
1389 {
1390  const AVCodecDescriptor **codecs;
1391  unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1392 
1393  printf("%s:\n"
1394  " V..... = Video\n"
1395  " A..... = Audio\n"
1396  " S..... = Subtitle\n"
1397  " .F.... = Frame-level multithreading\n"
1398  " ..S... = Slice-level multithreading\n"
1399  " ...X.. = Codec is experimental\n"
1400  " ....B. = Supports draw_horiz_band\n"
1401  " .....D = Supports direct rendering method 1\n"
1402  " ------\n",
1403  encoder ? "Encoders" : "Decoders");
1404  for (i = 0; i < nb_codecs; i++) {
1405  const AVCodecDescriptor *desc = codecs[i];
1406  const AVCodec *codec = NULL;
1407 
1408  while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1409  printf(" %c", get_media_type_char(desc->type));
1410  printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1411  printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1412  printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
1413  printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
1414  printf((codec->capabilities & CODEC_CAP_DR1) ? "D" : ".");
1415 
1416  printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1417  if (strcmp(codec->name, desc->name))
1418  printf(" (codec %s)", desc->name);
1419 
1420  printf("\n");
1421  }
1422  }
1423  av_free(codecs);
1424 }
1425 
1426 int show_decoders(void *optctx, const char *opt, const char *arg)
1427 {
1428  print_codecs(0);
1429  return 0;
1430 }
1431 
1432 int show_encoders(void *optctx, const char *opt, const char *arg)
1433 {
1434  print_codecs(1);
1435  return 0;
1436 }
1437 
1438 int show_bsfs(void *optctx, const char *opt, const char *arg)
1439 {
1440  AVBitStreamFilter *bsf = NULL;
1441 
1442  printf("Bitstream filters:\n");
1443  while ((bsf = av_bitstream_filter_next(bsf)))
1444  printf("%s\n", bsf->name);
1445  printf("\n");
1446  return 0;
1447 }
1448 
1449 int show_protocols(void *optctx, const char *opt, const char *arg)
1450 {
1451  void *opaque = NULL;
1452  const char *name;
1453 
1454  printf("Supported file protocols:\n"
1455  "Input:\n");
1456  while ((name = avio_enum_protocols(&opaque, 0)))
1457  printf("%s\n", name);
1458  printf("Output:\n");
1459  while ((name = avio_enum_protocols(&opaque, 1)))
1460  printf("%s\n", name);
1461  return 0;
1462 }
1463 
1464 int show_filters(void *optctx, const char *opt, const char *arg)
1465 {
1466  const AVFilter av_unused(*filter) = NULL;
1467  char descr[64], *descr_cur;
1468  int i, j;
1469  const AVFilterPad *pad;
1470 
1471  printf("Filters:\n"
1472  " T. = Timeline support\n"
1473  " .S = Slice threading\n"
1474  " A = Audio input/output\n"
1475  " V = Video input/output\n"
1476  " N = Dynamic number and/or type of input/output\n"
1477  " | = Source or sink filter\n");
1478 #if CONFIG_AVFILTER
1479  while ((filter = avfilter_next(filter))) {
1480  descr_cur = descr;
1481  for (i = 0; i < 2; i++) {
1482  if (i) {
1483  *(descr_cur++) = '-';
1484  *(descr_cur++) = '>';
1485  }
1486  pad = i ? filter->outputs : filter->inputs;
1487  for (j = 0; pad && pad[j].name; j++) {
1488  if (descr_cur >= descr + sizeof(descr) - 4)
1489  break;
1490  *(descr_cur++) = get_media_type_char(pad[j].type);
1491  }
1492  if (!j)
1493  *(descr_cur++) = ((!i && (filter->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)) ||
1494  ( i && (filter->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS))) ? 'N' : '|';
1495  }
1496  *descr_cur = 0;
1497  printf(" %c%c %-16s %-10s %s\n",
1498  filter->flags & AVFILTER_FLAG_SUPPORT_TIMELINE ? 'T' : '.',
1499  filter->flags & AVFILTER_FLAG_SLICE_THREADS ? 'S' : '.',
1500  filter->name, descr, filter->description);
1501  }
1502 #endif
1503  return 0;
1504 }
1505 
1506 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1507 {
1508  const AVPixFmtDescriptor *pix_desc = NULL;
1509 
1510  printf("Pixel formats:\n"
1511  "I.... = Supported Input format for conversion\n"
1512  ".O... = Supported Output format for conversion\n"
1513  "..H.. = Hardware accelerated format\n"
1514  "...P. = Paletted format\n"
1515  "....B = Bitstream format\n"
1516  "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
1517  "-----\n");
1518 
1519 #if !CONFIG_SWSCALE
1520 # define sws_isSupportedInput(x) 0
1521 # define sws_isSupportedOutput(x) 0
1522 #endif
1523 
1524  while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1525  enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1526  printf("%c%c%c%c%c %-16s %d %2d\n",
1527  sws_isSupportedInput (pix_fmt) ? 'I' : '.',
1528  sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
1529  pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL ? 'H' : '.',
1530  pix_desc->flags & AV_PIX_FMT_FLAG_PAL ? 'P' : '.',
1531  pix_desc->flags & AV_PIX_FMT_FLAG_BITSTREAM ? 'B' : '.',
1532  pix_desc->name,
1533  pix_desc->nb_components,
1534  av_get_bits_per_pixel(pix_desc));
1535  }
1536  return 0;
1537 }
1538 
1539 int show_layouts(void *optctx, const char *opt, const char *arg)
1540 {
1541  int i = 0;
1542  uint64_t layout, j;
1543  const char *name, *descr;
1544 
1545  printf("Individual channels:\n"
1546  "NAME DESCRIPTION\n");
1547  for (i = 0; i < 63; i++) {
1548  name = av_get_channel_name((uint64_t)1 << i);
1549  if (!name)
1550  continue;
1551  descr = av_get_channel_description((uint64_t)1 << i);
1552  printf("%-12s%s\n", name, descr);
1553  }
1554  printf("\nStandard channel layouts:\n"
1555  "NAME DECOMPOSITION\n");
1556  for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
1557  if (name) {
1558  printf("%-12s", name);
1559  for (j = 1; j; j <<= 1)
1560  if ((layout & j))
1561  printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
1562  printf("\n");
1563  }
1564  }
1565  return 0;
1566 }
1567 
1568 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1569 {
1570  int i;
1571  char fmt_str[128];
1572  for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1573  printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1574  return 0;
1575 }
1576 
1577 static void show_help_codec(const char *name, int encoder)
1578 {
1579  const AVCodecDescriptor *desc;
1580  const AVCodec *codec;
1581 
1582  if (!name) {
1583  av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1584  return;
1585  }
1586 
1587  codec = encoder ? avcodec_find_encoder_by_name(name) :
1589 
1590  if (codec)
1591  print_codec(codec);
1592  else if ((desc = avcodec_descriptor_get_by_name(name))) {
1593  int printed = 0;
1594 
1595  while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1596  printed = 1;
1597  print_codec(codec);
1598  }
1599 
1600  if (!printed) {
1601  av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
1602  "but no %s for it are available. FFmpeg might need to be "
1603  "recompiled with additional external libraries.\n",
1604  name, encoder ? "encoders" : "decoders");
1605  }
1606  } else {
1607  av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
1608  name);
1609  }
1610 }
1611 
1612 static void show_help_demuxer(const char *name)
1613 {
1614  const AVInputFormat *fmt = av_find_input_format(name);
1615 
1616  if (!fmt) {
1617  av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1618  return;
1619  }
1620 
1621  printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1622 
1623  if (fmt->extensions)
1624  printf(" Common extensions: %s.\n", fmt->extensions);
1625 
1626  if (fmt->priv_class)
1628 }
1629 
1630 static void show_help_muxer(const char *name)
1631 {
1632  const AVCodecDescriptor *desc;
1633  const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1634 
1635  if (!fmt) {
1636  av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1637  return;
1638  }
1639 
1640  printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1641 
1642  if (fmt->extensions)
1643  printf(" Common extensions: %s.\n", fmt->extensions);
1644  if (fmt->mime_type)
1645  printf(" Mime type: %s.\n", fmt->mime_type);
1646  if (fmt->video_codec != AV_CODEC_ID_NONE &&
1647  (desc = avcodec_descriptor_get(fmt->video_codec))) {
1648  printf(" Default video codec: %s.\n", desc->name);
1649  }
1650  if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1651  (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1652  printf(" Default audio codec: %s.\n", desc->name);
1653  }
1654  if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1655  (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1656  printf(" Default subtitle codec: %s.\n", desc->name);
1657  }
1658 
1659  if (fmt->priv_class)
1661 }
1662 
1663 #if CONFIG_AVFILTER
1664 static void show_help_filter(const char *name)
1665 {
1666 #if CONFIG_AVFILTER
1667  const AVFilter *f = avfilter_get_by_name(name);
1668  int i, count;
1669 
1670  if (!name) {
1671  av_log(NULL, AV_LOG_ERROR, "No filter name specified.\n");
1672  return;
1673  } else if (!f) {
1674  av_log(NULL, AV_LOG_ERROR, "Unknown filter '%s'.\n", name);
1675  return;
1676  }
1677 
1678  printf("Filter %s\n", f->name);
1679  if (f->description)
1680  printf(" %s\n", f->description);
1681 
1683  printf(" slice threading supported\n");
1684 
1685  printf(" Inputs:\n");
1686  count = avfilter_pad_count(f->inputs);
1687  for (i = 0; i < count; i++) {
1688  printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->inputs, i),
1690  }
1692  printf(" dynamic (depending on the options)\n");
1693  else if (!count)
1694  printf(" none (source filter)\n");
1695 
1696  printf(" Outputs:\n");
1697  count = avfilter_pad_count(f->outputs);
1698  for (i = 0; i < count; i++) {
1699  printf(" #%d: %s (%s)\n", i, avfilter_pad_get_name(f->outputs, i),
1701  }
1703  printf(" dynamic (depending on the options)\n");
1704  else if (!count)
1705  printf(" none (sink filter)\n");
1706 
1707  if (f->priv_class)
1711  printf("This filter has support for timeline through the 'enable' option.\n");
1712 #else
1713  av_log(NULL, AV_LOG_ERROR, "Build without libavfilter; "
1714  "can not to satisfy request\n");
1715 #endif
1716 }
1717 #endif
1718 
1719 int show_help(void *optctx, const char *opt, const char *arg)
1720 {
1721  char *topic, *par;
1723 
1724  topic = av_strdup(arg ? arg : "");
1725  par = strchr(topic, '=');
1726  if (par)
1727  *par++ = 0;
1728 
1729  if (!*topic) {
1730  show_help_default(topic, par);
1731  } else if (!strcmp(topic, "decoder")) {
1732  show_help_codec(par, 0);
1733  } else if (!strcmp(topic, "encoder")) {
1734  show_help_codec(par, 1);
1735  } else if (!strcmp(topic, "demuxer")) {
1736  show_help_demuxer(par);
1737  } else if (!strcmp(topic, "muxer")) {
1738  show_help_muxer(par);
1739 #if CONFIG_AVFILTER
1740  } else if (!strcmp(topic, "filter")) {
1741  show_help_filter(par);
1742 #endif
1743  } else {
1744  show_help_default(topic, par);
1745  }
1746 
1747  av_freep(&topic);
1748  return 0;
1749 }
1750 
1751 int read_yesno(void)
1752 {
1753  int c = getchar();
1754  int yesno = (av_toupper(c) == 'Y');
1755 
1756  while (c != '\n' && c != EOF)
1757  c = getchar();
1758 
1759  return yesno;
1760 }
1761 
1762 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1763 {
1764  int ret;
1765  FILE *f = fopen(filename, "rb");
1766 
1767  if (!f) {
1768  av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1769  strerror(errno));
1770  return AVERROR(errno);
1771  }
1772  fseek(f, 0, SEEK_END);
1773  *size = ftell(f);
1774  fseek(f, 0, SEEK_SET);
1775  if (*size == (size_t)-1) {
1776  av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
1777  fclose(f);
1778  return AVERROR(errno);
1779  }
1780  *bufptr = av_malloc(*size + 1);
1781  if (!*bufptr) {
1782  av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1783  fclose(f);
1784  return AVERROR(ENOMEM);
1785  }
1786  ret = fread(*bufptr, 1, *size, f);
1787  if (ret < *size) {
1788  av_free(*bufptr);
1789  if (ferror(f)) {
1790  av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1791  filename, strerror(errno));
1792  ret = AVERROR(errno);
1793  } else
1794  ret = AVERROR_EOF;
1795  } else {
1796  ret = 0;
1797  (*bufptr)[(*size)++] = '\0';
1798  }
1799 
1800  fclose(f);
1801  return ret;
1802 }
1803 
1804 FILE *get_preset_file(char *filename, size_t filename_size,
1805  const char *preset_name, int is_path,
1806  const char *codec_name)
1807 {
1808  FILE *f = NULL;
1809  int i;
1810  const char *base[3] = { getenv("FFMPEG_DATADIR"),
1811  getenv("HOME"),
1812  FFMPEG_DATADIR, };
1813 
1814  if (is_path) {
1815  av_strlcpy(filename, preset_name, filename_size);
1816  f = fopen(filename, "r");
1817  } else {
1818 #ifdef _WIN32
1819  char datadir[MAX_PATH], *ls;
1820  base[2] = NULL;
1821 
1822  if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
1823  {
1824  for (ls = datadir; ls < datadir + strlen(datadir); ls++)
1825  if (*ls == '\\') *ls = '/';
1826 
1827  if (ls = strrchr(datadir, '/'))
1828  {
1829  *ls = 0;
1830  strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
1831  base[2] = datadir;
1832  }
1833  }
1834 #endif
1835  for (i = 0; i < 3 && !f; i++) {
1836  if (!base[i])
1837  continue;
1838  snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1839  i != 1 ? "" : "/.ffmpeg", preset_name);
1840  f = fopen(filename, "r");
1841  if (!f && codec_name) {
1842  snprintf(filename, filename_size,
1843  "%s%s/%s-%s.ffpreset",
1844  base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1845  preset_name);
1846  f = fopen(filename, "r");
1847  }
1848  }
1849  }
1850 
1851  return f;
1852 }
1853 
1854 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1855 {
1856  int ret = avformat_match_stream_specifier(s, st, spec);
1857  if (ret < 0)
1858  av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1859  return ret;
1860 }
1861 
1863  AVFormatContext *s, AVStream *st, AVCodec *codec)
1864 {
1865  AVDictionary *ret = NULL;
1866  AVDictionaryEntry *t = NULL;
1869  char prefix = 0;
1870  const AVClass *cc = avcodec_get_class();
1871 
1872  if (!codec)
1873  codec = s->oformat ? avcodec_find_encoder(codec_id)
1874  : avcodec_find_decoder(codec_id);
1875 
1876  switch (st->codec->codec_type) {
1877  case AVMEDIA_TYPE_VIDEO:
1878  prefix = 'v';
1879  flags |= AV_OPT_FLAG_VIDEO_PARAM;
1880  break;
1881  case AVMEDIA_TYPE_AUDIO:
1882  prefix = 'a';
1883  flags |= AV_OPT_FLAG_AUDIO_PARAM;
1884  break;
1885  case AVMEDIA_TYPE_SUBTITLE:
1886  prefix = 's';
1887  flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1888  break;
1889  }
1890 
1891  while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1892  char *p = strchr(t->key, ':');
1893 
1894  /* check stream specification in opt name */
1895  if (p)
1896  switch (check_stream_specifier(s, st, p + 1)) {
1897  case 1: *p = 0; break;
1898  case 0: continue;
1899  default: return NULL;
1900  }
1901 
1902  if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1903  (codec && codec->priv_class &&
1904  av_opt_find(&codec->priv_class, t->key, NULL, flags,
1906  av_dict_set(&ret, t->key, t->value, 0);
1907  else if (t->key[0] == prefix &&
1908  av_opt_find(&cc, t->key + 1, NULL, flags,
1910  av_dict_set(&ret, t->key + 1, t->value, 0);
1911 
1912  if (p)
1913  *p = ':';
1914  }
1915  return ret;
1916 }
1917 
1919  AVDictionary *codec_opts)
1920 {
1921  int i;
1922  AVDictionary **opts;
1923 
1924  if (!s->nb_streams)
1925  return NULL;
1926  opts = av_mallocz(s->nb_streams * sizeof(*opts));
1927  if (!opts) {
1928  av_log(NULL, AV_LOG_ERROR,
1929  "Could not alloc memory for stream options.\n");
1930  return NULL;
1931  }
1932  for (i = 0; i < s->nb_streams; i++)
1933  opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1934  s, s->streams[i], NULL);
1935  return opts;
1936 }
1937 
1938 void *grow_array(void *array, int elem_size, int *size, int new_size)
1939 {
1940  if (new_size >= INT_MAX / elem_size) {
1941  av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1942  exit_program(1);
1943  }
1944  if (*size < new_size) {
1945  uint8_t *tmp = av_realloc(array, new_size*elem_size);
1946  if (!tmp) {
1947  av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1948  exit_program(1);
1949  }
1950  memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1951  *size = new_size;
1952  return tmp;
1953  }
1954  return array;
1955 }