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