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