2 * Various utilities for command line tools
3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
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. */
32 #include "compat/va_copy.h"
33 #include "libavformat/avformat.h"
34 #include "libavfilter/avfilter.h"
35 #include "libavdevice/avdevice.h"
36 #include "libavresample/avresample.h"
37 #include "libswscale/swscale.h"
38 #include "libswresample/swresample.h"
40 #include "libpostproc/postprocess.h"
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"
55 #include "libavformat/network.h"
57 #if HAVE_SYS_RESOURCE_H
59 #include <sys/resource.h>
62 static int init_report(const char *env);
64 struct SwsContext *sws_opts;
66 AVDictionary *format_opts, *codec_opts;
68 const int this_year = 2013;
70 static FILE *report_file;
76 sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
80 swr_opts = swr_alloc();
83 void uninit_opts(void)
86 sws_freeContext(sws_opts);
93 av_dict_free(&format_opts);
94 av_dict_free(&codec_opts);
97 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
99 vfprintf(stdout, fmt, vl);
102 static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
106 static int print_prefix = 1;
109 av_log_default_callback(ptr, level, fmt, vl);
110 av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
112 fputs(line, report_file);
116 double parse_number_or_die(const char *context, const char *numstr, int type,
117 double min, double max)
121 double d = av_strtod(numstr, &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";
132 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
137 int64_t parse_time_or_die(const char *context, const char *timestr,
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);
149 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
150 int rej_flags, int alt_flags)
156 for (po = options; po->name != NULL; po++) {
159 if (((po->flags & req_flags) != req_flags) ||
160 (alt_flags && !(po->flags & alt_flags)) ||
161 (po->flags & rej_flags))
168 av_strlcpy(buf, po->name, sizeof(buf));
170 av_strlcat(buf, " ", sizeof(buf));
171 av_strlcat(buf, po->argname, sizeof(buf));
173 printf("-%-17s %s\n", buf, po->help);
178 void show_help_children(const AVClass *class, int flags)
180 const AVClass *child = NULL;
182 av_opt_show2(&class, NULL, flags, 0);
186 while (child = av_opt_child_class_next(class, child))
187 show_help_children(child, flags);
190 static const OptionDef *find_option(const OptionDef *po, const char *name)
192 const char *p = strchr(name, ':');
193 int len = p ? p - name : strlen(name);
195 while (po->name != NULL) {
196 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
203 #if HAVE_COMMANDLINETOARGVW
205 #include <shellapi.h>
206 /* Will be leaked on exit */
207 static char** win32_argv_utf8 = NULL;
208 static int win32_argc = 0;
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.
217 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
221 int i, buffsize = 0, offset = 0;
223 if (win32_argv_utf8) {
224 *argc_ptr = win32_argc;
225 *argv_ptr = win32_argv_utf8;
230 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
231 if (win32_argc <= 0 || !argv_w)
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);
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) {
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);
252 win32_argv_utf8[i] = NULL;
255 *argc_ptr = win32_argc;
256 *argv_ptr = win32_argv_utf8;
259 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
263 #endif /* HAVE_COMMANDLINETOARGVW */
265 static int write_option(void *optctx, const OptionDef *po, const char *opt,
268 /* new-style options contain an offset into optctx, old-style address of
270 void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
271 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
274 if (po->flags & OPT_SPEC) {
275 SpecifierOpt **so = dst;
276 char *p = strchr(opt, ':');
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;
284 if (po->flags & OPT_STRING) {
286 str = av_strdup(arg);
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);
302 av_log(NULL, AV_LOG_ERROR,
303 "Failed to set value '%s' for option '%s'\n", arg, opt);
307 if (po->flags & OPT_EXIT)
313 int parse_option(void *optctx, const char *opt, const char *arg,
314 const OptionDef *options)
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)))
325 } else if (po->flags & OPT_BOOL)
329 po = find_option(options, "default");
331 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
332 return AVERROR(EINVAL);
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);
339 ret = write_option(optctx, po, opt, arg);
343 return !!(po->flags & HAS_ARG);
346 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
347 void (*parse_arg_function)(void *, const char*))
350 int optindex, handleoptions = 1, ret;
352 /* perform system-dependent conversions for arguments list */
353 prepare_app_arguments(&argc, &argv);
357 while (optindex < argc) {
358 opt = argv[optindex++];
360 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
361 if (opt[1] == '-' && opt[2] == '\0') {
367 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
371 if (parse_arg_function)
372 parse_arg_function(optctx, opt);
377 int parse_optgroup(void *optctx, OptionGroup *g)
381 av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
382 g->group_def->name, g->arg);
384 for (i = 0; i < g->nb_opts; i++) {
385 Option *o = &g->opts[i];
387 av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
388 o->key, o->opt->help, o->val);
390 ret = write_option(optctx, o->opt, o->key, o->val);
395 av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
400 int locate_option(int argc, char **argv, const OptionDef *options,
406 for (i = 1; i < argc; i++) {
407 const char *cur_opt = argv[i];
409 if (*cur_opt++ != '-')
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);
416 if ((!po->name && !strcmp(cur_opt, optname)) ||
417 (po->name && !strcmp(optname, po->name)))
420 if (po->flags & HAS_ARG)
426 static void dump_argument(const char *a)
428 const unsigned char *p;
431 if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
432 *p == '_' || (*p >= 'a' && *p <= 'z')))
435 fputs(a, report_file);
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);
445 fputc(*p, report_file);
447 fputc('"', report_file);
450 void parse_loglevel(int argc, char **argv, const OptionDef *options)
452 int idx = locate_option(argc, argv, options, "loglevel");
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) {
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);
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)
478 char opt_stripped[128];
480 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
481 const AVClass *sc, *swr_class;
483 if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))
484 av_log_set_level(AV_LOG_DEBUG);
486 if (!(p = strchr(opt, ':')))
487 p = opt + strlen(opt);
488 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
490 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
491 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
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);
497 if ((o = av_opt_find(&fc, opt, NULL, 0,
498 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
499 av_dict_set(&format_opts, opt, arg, FLAGS);
501 av_log(NULL, AV_LOG_VERBOSE, "Routing %s to codec and muxer layer\n", opt);
505 sc = sws_get_class();
506 if (!consumed && av_opt_find(&sc, opt, NULL, 0,
507 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
508 // XXX we only support sws_flags, not arbitrary sws options
509 int ret = av_opt_set(sws_opts, opt, arg, 0);
511 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
517 #if CONFIG_SWRESAMPLE
518 swr_class = swr_get_class();
519 if (!consumed && av_opt_find(&swr_class, opt, NULL, 0,
520 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
521 int ret = av_opt_set(swr_opts, opt, arg, 0);
523 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
532 return AVERROR_OPTION_NOT_FOUND;
536 * Check whether given option is a group separator.
538 * @return index of the group definition that matched or -1 if none
540 static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
545 for (i = 0; i < nb_groups; i++) {
546 const OptionGroupDef *p = &groups[i];
547 if (p->sep && !strcmp(p->sep, opt))
555 * Finish parsing an option group.
557 * @param group_idx which group definition should this group belong to
558 * @param arg argument of the group delimiting option
560 static void finish_group(OptionParseContext *octx, int group_idx,
563 OptionGroupList *l = &octx->groups[group_idx];
566 GROW_ARRAY(l->groups, l->nb_groups);
567 g = &l->groups[l->nb_groups - 1];
569 *g = octx->cur_group;
571 g->group_def = l->group_def;
573 g->sws_opts = sws_opts;
575 g->swr_opts = swr_opts;
576 g->codec_opts = codec_opts;
577 g->format_opts = format_opts;
587 memset(&octx->cur_group, 0, sizeof(octx->cur_group));
591 * Add an option instance to currently parsed group.
593 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
594 const char *key, const char *val)
596 int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
597 OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
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;
605 static void init_parse_context(OptionParseContext *octx,
606 const OptionGroupDef *groups, int nb_groups)
608 static const OptionGroupDef global_group = { "global" };
611 memset(octx, 0, sizeof(*octx));
613 octx->nb_groups = nb_groups;
614 octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
618 for (i = 0; i < octx->nb_groups; i++)
619 octx->groups[i].group_def = &groups[i];
621 octx->global_opts.group_def = &global_group;
622 octx->global_opts.arg = "";
627 void uninit_parse_context(OptionParseContext *octx)
631 for (i = 0; i < octx->nb_groups; i++) {
632 OptionGroupList *l = &octx->groups[i];
634 for (j = 0; j < l->nb_groups; j++) {
635 av_freep(&l->groups[j].opts);
636 av_dict_free(&l->groups[j].codec_opts);
637 av_dict_free(&l->groups[j].format_opts);
639 sws_freeContext(l->groups[j].sws_opts);
641 if(CONFIG_SWRESAMPLE)
642 swr_free(&l->groups[j].swr_opts);
644 av_freep(&l->groups);
646 av_freep(&octx->groups);
648 av_freep(&octx->cur_group.opts);
649 av_freep(&octx->global_opts.opts);
654 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
655 const OptionDef *options,
656 const OptionGroupDef *groups, int nb_groups)
661 /* perform system-dependent conversions for arguments list */
662 prepare_app_arguments(&argc, &argv);
664 init_parse_context(octx, groups, nb_groups);
665 av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
667 while (optindex < argc) {
668 const char *opt = argv[optindex++], *arg;
672 av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
674 if (opt[0] == '-' && opt[1] == '-' && !opt[2]) {
678 /* unnamed group separators, e.g. output filename */
679 if (opt[0] != '-' || !opt[1] || dashdash+1 == optindex) {
680 finish_group(octx, 0, opt);
681 av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
686 #define GET_ARG(arg) \
688 arg = argv[optindex++]; \
690 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
691 return AVERROR(EINVAL); \
695 /* named group separators, e.g. -i */
696 if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
698 finish_group(octx, ret, arg);
699 av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
700 groups[ret].name, arg);
705 po = find_option(options, opt);
707 if (po->flags & OPT_EXIT) {
708 /* optional argument, e.g. -h */
709 arg = argv[optindex++];
710 } else if (po->flags & HAS_ARG) {
716 add_opt(octx, po, opt, arg);
717 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
718 "argument '%s'.\n", po->name, po->help, arg);
723 if (argv[optindex]) {
724 ret = opt_default(NULL, opt, argv[optindex]);
726 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
727 "argument '%s'.\n", opt, argv[optindex]);
730 } else if (ret != AVERROR_OPTION_NOT_FOUND) {
731 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
732 "with argument '%s'.\n", opt, argv[optindex]);
737 /* boolean -nofoo options */
738 if (opt[0] == 'n' && opt[1] == 'o' &&
739 (po = find_option(options, opt + 2)) &&
740 po->name && po->flags & OPT_BOOL) {
741 add_opt(octx, po, opt, "0");
742 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
743 "argument 0.\n", po->name, po->help);
747 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
748 return AVERROR_OPTION_NOT_FOUND;
751 if (octx->cur_group.nb_opts || codec_opts || format_opts)
752 av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
755 av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
760 int opt_loglevel(void *optctx, const char *opt, const char *arg)
762 const struct { const char *name; int level; } log_levels[] = {
763 { "quiet" , AV_LOG_QUIET },
764 { "panic" , AV_LOG_PANIC },
765 { "fatal" , AV_LOG_FATAL },
766 { "error" , AV_LOG_ERROR },
767 { "warning", AV_LOG_WARNING },
768 { "info" , AV_LOG_INFO },
769 { "verbose", AV_LOG_VERBOSE },
770 { "debug" , AV_LOG_DEBUG },
776 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
777 if (!strcmp(log_levels[i].name, arg)) {
778 av_log_set_level(log_levels[i].level);
783 level = strtol(arg, &tail, 10);
785 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
786 "Possible levels are numbers or:\n", arg);
787 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
788 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
791 av_log_set_level(level);
795 static void expand_filename_template(AVBPrint *bp, const char *template,
800 while ((c = *(template++))) {
802 if (!(c = *(template++)))
806 av_bprintf(bp, "%s", program_name);
809 av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
810 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
811 tm->tm_hour, tm->tm_min, tm->tm_sec);
814 av_bprint_chars(bp, c, 1);
818 av_bprint_chars(bp, c, 1);
823 static int init_report(const char *env)
825 char *filename_template = NULL;
832 if (report_file) /* already opened */
835 tm = localtime(&now);
837 while (env && *env) {
838 if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
840 av_log(NULL, AV_LOG_ERROR,
841 "Failed to parse FFREPORT environment variable: %s\n",
848 if (!strcmp(key, "file")) {
849 av_free(filename_template);
850 filename_template = val;
853 av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
859 av_bprint_init(&filename, 0, 1);
860 expand_filename_template(&filename,
861 av_x_if_null(filename_template, "%p-%t.log"), tm);
862 av_free(filename_template);
863 if (!av_bprint_is_complete(&filename)) {
864 av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
865 return AVERROR(ENOMEM);
868 report_file = fopen(filename.str, "w");
870 av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
871 filename.str, strerror(errno));
872 return AVERROR(errno);
874 av_log_set_callback(log_callback_report);
875 av_log(NULL, AV_LOG_INFO,
876 "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
877 "Report written to \"%s\"\n",
879 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
880 tm->tm_hour, tm->tm_min, tm->tm_sec,
882 av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
883 av_bprint_finalize(&filename, NULL);
887 int opt_report(const char *opt)
889 return init_report(NULL);
892 int opt_max_alloc(void *optctx, const char *opt, const char *arg)
897 max = strtol(arg, &tail, 10);
899 av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
906 int opt_cpuflags(void *optctx, const char *opt, const char *arg)
909 unsigned flags = av_get_cpu_flags();
911 if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
914 av_force_cpu_flags(flags);
918 int opt_timelimit(void *optctx, const char *opt, const char *arg)
921 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
922 struct rlimit rl = { lim, lim + 1 };
923 if (setrlimit(RLIMIT_CPU, &rl))
926 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
931 void print_error(const char *filename, int err)
934 const char *errbuf_ptr = errbuf;
936 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
937 errbuf_ptr = strerror(AVUNERROR(err));
938 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
941 static int warned_cfg = 0;
944 #define SHOW_VERSION 2
945 #define SHOW_CONFIG 4
946 #define SHOW_COPYRIGHT 8
948 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
949 if (CONFIG_##LIBNAME) { \
950 const char *indent = flags & INDENT? " " : ""; \
951 if (flags & SHOW_VERSION) { \
952 unsigned int version = libname##_version(); \
953 av_log(NULL, level, \
954 "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n", \
956 LIB##LIBNAME##_VERSION_MAJOR, \
957 LIB##LIBNAME##_VERSION_MINOR, \
958 LIB##LIBNAME##_VERSION_MICRO, \
959 version >> 16, version >> 8 & 0xff, version & 0xff); \
961 if (flags & SHOW_CONFIG) { \
962 const char *cfg = libname##_configuration(); \
963 if (strcmp(FFMPEG_CONFIGURATION, cfg)) { \
965 av_log(NULL, level, \
966 "%sWARNING: library configuration mismatch\n", \
970 av_log(NULL, level, "%s%-11s configuration: %s\n", \
971 indent, #libname, cfg); \
976 static void print_all_libs_info(int flags, int level)
978 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
979 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
980 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
981 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
982 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
983 // PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
984 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
985 PRINT_LIB_INFO(swresample,SWRESAMPLE, flags, level);
987 PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
991 static void print_program_info(int flags, int level)
993 const char *indent = flags & INDENT? " " : "";
995 av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
996 if (flags & SHOW_COPYRIGHT)
997 av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
998 program_birth_year, this_year);
999 av_log(NULL, level, "\n");
1000 av_log(NULL, level, "%sbuilt on %s %s with %s\n",
1001 indent, __DATE__, __TIME__, CC_IDENT);
1003 av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
1006 void show_banner(int argc, char **argv, const OptionDef *options)
1008 int idx = locate_option(argc, argv, options, "version");
1012 print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
1013 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_INFO);
1014 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
1017 int show_version(void *optctx, const char *opt, const char *arg)
1019 av_log_set_callback(log_callback_help);
1020 print_program_info (0 , AV_LOG_INFO);
1021 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
1026 int show_license(void *optctx, const char *opt, const char *arg)
1030 "This version of %s has nonfree parts compiled in.\n"
1031 "Therefore it is not legally redistributable.\n",
1035 "%s is free software; you can redistribute it and/or modify\n"
1036 "it under the terms of the GNU General Public License as published by\n"
1037 "the Free Software Foundation; either version 3 of the License, or\n"
1038 "(at your option) any later version.\n"
1040 "%s is distributed in the hope that it will be useful,\n"
1041 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1042 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1043 "GNU General Public License for more details.\n"
1045 "You should have received a copy of the GNU General Public License\n"
1046 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
1047 program_name, program_name, program_name );
1050 "%s is free software; you can redistribute it and/or modify\n"
1051 "it under the terms of the GNU General Public License as published by\n"
1052 "the Free Software Foundation; either version 2 of the License, or\n"
1053 "(at your option) any later version.\n"
1055 "%s is distributed in the hope that it will be useful,\n"
1056 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1057 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1058 "GNU General Public License for more details.\n"
1060 "You should have received a copy of the GNU General Public License\n"
1061 "along with %s; if not, write to the Free Software\n"
1062 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1063 program_name, program_name, program_name );
1066 "%s is free software; you can redistribute it and/or modify\n"
1067 "it under the terms of the GNU Lesser General Public License as published by\n"
1068 "the Free Software Foundation; either version 3 of the License, or\n"
1069 "(at your option) any later version.\n"
1071 "%s is distributed in the hope that it will be useful,\n"
1072 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1073 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1074 "GNU Lesser General Public License for more details.\n"
1076 "You should have received a copy of the GNU Lesser General Public License\n"
1077 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
1078 program_name, program_name, program_name );
1081 "%s is free software; you can redistribute it and/or\n"
1082 "modify it under the terms of the GNU Lesser General Public\n"
1083 "License as published by the Free Software Foundation; either\n"
1084 "version 2.1 of the License, or (at your option) any later version.\n"
1086 "%s is distributed in the hope that it will be useful,\n"
1087 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1088 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
1089 "Lesser General Public License for more details.\n"
1091 "You should have received a copy of the GNU Lesser General Public\n"
1092 "License along with %s; if not, write to the Free Software\n"
1093 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1094 program_name, program_name, program_name );
1100 int show_formats(void *optctx, const char *opt, const char *arg)
1102 AVInputFormat *ifmt = NULL;
1103 AVOutputFormat *ofmt = NULL;
1104 const char *last_name;
1106 printf("File formats:\n"
1107 " D. = Demuxing supported\n"
1108 " .E = Muxing supported\n"
1114 const char *name = NULL;
1115 const char *long_name = NULL;
1117 while ((ofmt = av_oformat_next(ofmt))) {
1118 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
1119 strcmp(ofmt->name, last_name) > 0) {
1121 long_name = ofmt->long_name;
1125 while ((ifmt = av_iformat_next(ifmt))) {
1126 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
1127 strcmp(ifmt->name, last_name) > 0) {
1129 long_name = ifmt->long_name;
1132 if (name && strcmp(ifmt->name, name) == 0)
1139 printf(" %s%s %-15s %s\n",
1143 long_name ? long_name:" ");
1148 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
1149 if (codec->field) { \
1150 const type *p = codec->field; \
1152 printf(" Supported " list_name ":"); \
1153 while (*p != term) { \
1155 printf(" %s", name); \
1161 static void print_codec(const AVCodec *c)
1163 int encoder = av_codec_is_encoder(c);
1165 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
1166 c->long_name ? c->long_name : "");
1168 if (c->type == AVMEDIA_TYPE_VIDEO) {
1169 printf(" Threading capabilities: ");
1170 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
1171 CODEC_CAP_SLICE_THREADS)) {
1172 case CODEC_CAP_FRAME_THREADS |
1173 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
1174 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
1175 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
1176 default: printf("no"); break;
1181 if (c->supported_framerates) {
1182 const AVRational *fps = c->supported_framerates;
1184 printf(" Supported framerates:");
1186 printf(" %d/%d", fps->num, fps->den);
1191 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
1192 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
1193 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
1194 GET_SAMPLE_RATE_NAME);
1195 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
1196 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
1197 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
1198 0, GET_CH_LAYOUT_DESC);
1200 if (c->priv_class) {
1201 show_help_children(c->priv_class,
1202 AV_OPT_FLAG_ENCODING_PARAM |
1203 AV_OPT_FLAG_DECODING_PARAM);
1207 static char get_media_type_char(enum AVMediaType type)
1210 case AVMEDIA_TYPE_VIDEO: return 'V';
1211 case AVMEDIA_TYPE_AUDIO: return 'A';
1212 case AVMEDIA_TYPE_DATA: return 'D';
1213 case AVMEDIA_TYPE_SUBTITLE: return 'S';
1214 case AVMEDIA_TYPE_ATTACHMENT:return 'T';
1215 default: return '?';
1219 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
1222 while ((prev = av_codec_next(prev))) {
1223 if (prev->id == id &&
1224 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
1230 static int compare_codec_desc(const void *a, const void *b)
1232 const AVCodecDescriptor * const *da = a;
1233 const AVCodecDescriptor * const *db = b;
1235 return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
1236 strcmp((*da)->name, (*db)->name);
1239 static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
1241 const AVCodecDescriptor *desc = NULL;
1242 const AVCodecDescriptor **codecs;
1243 unsigned nb_codecs = 0, i = 0;
1245 while ((desc = avcodec_descriptor_next(desc)))
1247 if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
1248 av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
1252 while ((desc = avcodec_descriptor_next(desc)))
1254 av_assert0(i == nb_codecs);
1255 qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
1260 static void print_codecs_for_id(enum AVCodecID id, int encoder)
1262 const AVCodec *codec = NULL;
1264 printf(" (%s: ", encoder ? "encoders" : "decoders");
1266 while ((codec = next_codec_for_id(id, codec, encoder)))
1267 printf("%s ", codec->name);
1272 int show_codecs(void *optctx, const char *opt, const char *arg)
1274 const AVCodecDescriptor **codecs;
1275 unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1278 " D..... = Decoding supported\n"
1279 " .E.... = Encoding supported\n"
1280 " ..V... = Video codec\n"
1281 " ..A... = Audio codec\n"
1282 " ..S... = Subtitle codec\n"
1283 " ...I.. = Intra frame-only codec\n"
1284 " ....L. = Lossy compression\n"
1285 " .....S = Lossless compression\n"
1287 for (i = 0; i < nb_codecs; i++) {
1288 const AVCodecDescriptor *desc = codecs[i];
1289 const AVCodec *codec = NULL;
1292 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1293 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1295 printf("%c", get_media_type_char(desc->type));
1296 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1297 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
1298 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
1300 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1302 /* print decoders/encoders when there's more than one or their
1303 * names are different from codec name */
1304 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1305 if (strcmp(codec->name, desc->name)) {
1306 print_codecs_for_id(desc->id, 0);
1311 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1312 if (strcmp(codec->name, desc->name)) {
1313 print_codecs_for_id(desc->id, 1);
1324 static void print_codecs(int encoder)
1326 const AVCodecDescriptor **codecs;
1327 unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1332 " S..... = Subtitle\n"
1333 " .F.... = Frame-level multithreading\n"
1334 " ..S... = Slice-level multithreading\n"
1335 " ...X.. = Codec is experimental\n"
1336 " ....B. = Supports draw_horiz_band\n"
1337 " .....D = Supports direct rendering method 1\n"
1339 encoder ? "Encoders" : "Decoders");
1340 for (i = 0; i < nb_codecs; i++) {
1341 const AVCodecDescriptor *desc = codecs[i];
1342 const AVCodec *codec = NULL;
1344 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1345 printf(" %c", get_media_type_char(desc->type));
1346 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1347 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1348 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
1349 printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
1350 printf((codec->capabilities & CODEC_CAP_DR1) ? "D" : ".");
1352 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1353 if (strcmp(codec->name, desc->name))
1354 printf(" (codec %s)", desc->name);
1362 int show_decoders(void *optctx, const char *opt, const char *arg)
1368 int show_encoders(void *optctx, const char *opt, const char *arg)
1374 int show_bsfs(void *optctx, const char *opt, const char *arg)
1376 AVBitStreamFilter *bsf = NULL;
1378 printf("Bitstream filters:\n");
1379 while ((bsf = av_bitstream_filter_next(bsf)))
1380 printf("%s\n", bsf->name);
1385 int show_protocols(void *optctx, const char *opt, const char *arg)
1387 void *opaque = NULL;
1390 printf("Supported file protocols:\n"
1392 while ((name = avio_enum_protocols(&opaque, 0)))
1393 printf("%s\n", name);
1394 printf("Output:\n");
1395 while ((name = avio_enum_protocols(&opaque, 1)))
1396 printf("%s\n", name);
1400 int show_filters(void *optctx, const char *opt, const char *arg)
1402 AVFilter av_unused(**filter) = NULL;
1403 char descr[64], *descr_cur;
1405 const AVFilterPad *pad;
1407 printf("Filters:\n");
1409 while ((filter = av_filter_next(filter)) && *filter) {
1411 for (i = 0; i < 2; i++) {
1413 *(descr_cur++) = '-';
1414 *(descr_cur++) = '>';
1416 pad = i ? (*filter)->outputs : (*filter)->inputs;
1417 for (j = 0; pad && pad[j].name; j++) {
1418 if (descr_cur >= descr + sizeof(descr) - 4)
1420 *(descr_cur++) = get_media_type_char(pad[j].type);
1423 *(descr_cur++) = '|';
1426 printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
1432 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1434 const AVPixFmtDescriptor *pix_desc = NULL;
1436 printf("Pixel formats:\n"
1437 "I.... = Supported Input format for conversion\n"
1438 ".O... = Supported Output format for conversion\n"
1439 "..H.. = Hardware accelerated format\n"
1440 "...P. = Paletted format\n"
1441 "....B = Bitstream format\n"
1442 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
1446 # define sws_isSupportedInput(x) 0
1447 # define sws_isSupportedOutput(x) 0
1450 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1451 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1452 printf("%c%c%c%c%c %-16s %d %2d\n",
1453 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
1454 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
1455 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
1456 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
1457 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1459 pix_desc->nb_components,
1460 av_get_bits_per_pixel(pix_desc));
1465 int show_layouts(void *optctx, const char *opt, const char *arg)
1469 const char *name, *descr;
1471 printf("Individual channels:\n"
1472 "NAME DESCRIPTION\n");
1473 for (i = 0; i < 63; i++) {
1474 name = av_get_channel_name((uint64_t)1 << i);
1477 descr = av_get_channel_description((uint64_t)1 << i);
1478 printf("%-12s%s\n", name, descr);
1480 printf("\nStandard channel layouts:\n"
1481 "NAME DECOMPOSITION\n");
1482 for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
1484 printf("%-12s", name);
1485 for (j = 1; j; j <<= 1)
1487 printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
1494 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1498 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1499 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1503 static void show_help_codec(const char *name, int encoder)
1505 const AVCodecDescriptor *desc;
1506 const AVCodec *codec;
1509 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1513 codec = encoder ? avcodec_find_encoder_by_name(name) :
1514 avcodec_find_decoder_by_name(name);
1518 else if ((desc = avcodec_descriptor_get_by_name(name))) {
1521 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1527 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
1528 "but no %s for it are available. FFmpeg might need to be "
1529 "recompiled with additional external libraries.\n",
1530 name, encoder ? "encoders" : "decoders");
1533 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
1538 static void show_help_demuxer(const char *name)
1540 const AVInputFormat *fmt = av_find_input_format(name);
1543 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1547 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1549 if (fmt->extensions)
1550 printf(" Common extensions: %s.\n", fmt->extensions);
1552 if (fmt->priv_class)
1553 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1556 static void show_help_muxer(const char *name)
1558 const AVCodecDescriptor *desc;
1559 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1562 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1566 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1568 if (fmt->extensions)
1569 printf(" Common extensions: %s.\n", fmt->extensions);
1571 printf(" Mime type: %s.\n", fmt->mime_type);
1572 if (fmt->video_codec != AV_CODEC_ID_NONE &&
1573 (desc = avcodec_descriptor_get(fmt->video_codec))) {
1574 printf(" Default video codec: %s.\n", desc->name);
1576 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1577 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1578 printf(" Default audio codec: %s.\n", desc->name);
1580 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1581 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1582 printf(" Default subtitle codec: %s.\n", desc->name);
1585 if (fmt->priv_class)
1586 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1589 int show_help(void *optctx, const char *opt, const char *arg)
1592 av_log_set_callback(log_callback_help);
1594 topic = av_strdup(arg ? arg : "");
1595 par = strchr(topic, '=');
1600 show_help_default(topic, par);
1601 } else if (!strcmp(topic, "decoder")) {
1602 show_help_codec(par, 0);
1603 } else if (!strcmp(topic, "encoder")) {
1604 show_help_codec(par, 1);
1605 } else if (!strcmp(topic, "demuxer")) {
1606 show_help_demuxer(par);
1607 } else if (!strcmp(topic, "muxer")) {
1608 show_help_muxer(par);
1610 show_help_default(topic, par);
1617 int read_yesno(void)
1620 int yesno = (toupper(c) == 'Y');
1622 while (c != '\n' && c != EOF)
1628 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1631 FILE *f = fopen(filename, "rb");
1634 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1636 return AVERROR(errno);
1638 fseek(f, 0, SEEK_END);
1640 fseek(f, 0, SEEK_SET);
1641 if (*size == (size_t)-1) {
1642 av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
1644 return AVERROR(errno);
1646 *bufptr = av_malloc(*size + 1);
1648 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1650 return AVERROR(ENOMEM);
1652 ret = fread(*bufptr, 1, *size, f);
1656 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1657 filename, strerror(errno));
1658 ret = AVERROR(errno);
1663 (*bufptr)[(*size)++] = '\0';
1670 FILE *get_preset_file(char *filename, size_t filename_size,
1671 const char *preset_name, int is_path,
1672 const char *codec_name)
1676 const char *base[3] = { getenv("FFMPEG_DATADIR"),
1681 av_strlcpy(filename, preset_name, filename_size);
1682 f = fopen(filename, "r");
1685 char datadir[MAX_PATH], *ls;
1688 if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
1690 for (ls = datadir; ls < datadir + strlen(datadir); ls++)
1691 if (*ls == '\\') *ls = '/';
1693 if (ls = strrchr(datadir, '/'))
1696 strncat(datadir, "/ffpresets", sizeof(datadir) - 1 - strlen(datadir));
1701 for (i = 0; i < 3 && !f; i++) {
1704 snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1705 i != 1 ? "" : "/.ffmpeg", preset_name);
1706 f = fopen(filename, "r");
1707 if (!f && codec_name) {
1708 snprintf(filename, filename_size,
1709 "%s%s/%s-%s.ffpreset",
1710 base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1712 f = fopen(filename, "r");
1720 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1722 int ret = avformat_match_stream_specifier(s, st, spec);
1724 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1728 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1729 AVFormatContext *s, AVStream *st, AVCodec *codec)
1731 AVDictionary *ret = NULL;
1732 AVDictionaryEntry *t = NULL;
1733 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1734 : AV_OPT_FLAG_DECODING_PARAM;
1736 const AVClass *cc = avcodec_get_class();
1739 codec = s->oformat ? avcodec_find_encoder(codec_id)
1740 : avcodec_find_decoder(codec_id);
1744 switch (codec->type) {
1745 case AVMEDIA_TYPE_VIDEO:
1747 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1749 case AVMEDIA_TYPE_AUDIO:
1751 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1753 case AVMEDIA_TYPE_SUBTITLE:
1755 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1759 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1760 char *p = strchr(t->key, ':');
1762 /* check stream specification in opt name */
1764 switch (check_stream_specifier(s, st, p + 1)) {
1765 case 1: *p = 0; break;
1767 default: return NULL;
1770 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1771 (codec && codec->priv_class &&
1772 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1773 AV_OPT_SEARCH_FAKE_OBJ)))
1774 av_dict_set(&ret, t->key, t->value, 0);
1775 else if (t->key[0] == prefix &&
1776 av_opt_find(&cc, t->key + 1, NULL, flags,
1777 AV_OPT_SEARCH_FAKE_OBJ))
1778 av_dict_set(&ret, t->key + 1, t->value, 0);
1786 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1787 AVDictionary *codec_opts)
1790 AVDictionary **opts;
1794 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1796 av_log(NULL, AV_LOG_ERROR,
1797 "Could not alloc memory for stream options.\n");
1800 for (i = 0; i < s->nb_streams; i++)
1801 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1802 s, s->streams[i], NULL);
1806 void *grow_array(void *array, int elem_size, int *size, int new_size)
1808 if (new_size >= INT_MAX / elem_size) {
1809 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1812 if (*size < new_size) {
1813 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1815 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1818 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1825 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1827 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1831 int h_chroma_shift, v_chroma_shift;
1832 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1833 int w = s->width, h = s->height;
1836 return AVERROR(EINVAL);
1837 pixel_size = desc->comp[0].step_minus1 + 1;
1839 buf = av_mallocz(sizeof(*buf));
1841 return AVERROR(ENOMEM);
1843 avcodec_align_dimensions(s, &w, &h);
1845 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1850 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1851 s->pix_fmt, 32)) < 0) {
1853 av_log(s, AV_LOG_ERROR, "alloc_buffer: av_image_alloc() failed\n");
1856 /* XXX this shouldn't be needed, but some tests break without this line
1857 * those decoders are buggy and need to be fixed.
1858 * the following tests fail:
1859 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1861 memset(buf->base[0], 128, ret);
1863 avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1864 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1865 const int h_shift = i==0 ? 0 : h_chroma_shift;
1866 const int v_shift = i==0 ? 0 : v_chroma_shift;
1867 if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[i] || !buf->base[i])
1868 buf->data[i] = buf->base[i];
1870 buf->data[i] = buf->base[i] +
1871 FFALIGN((buf->linesize[i]*edge >> v_shift) +
1872 (pixel_size*edge >> h_shift), 32);
1876 buf->pix_fmt = s->pix_fmt;
1883 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1885 FrameBuffer **pool = s->opaque;
1889 if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0) {
1890 av_log(s, AV_LOG_ERROR, "codec_get_buffer: image parameters invalid\n");
1894 if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1900 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1901 av_freep(&buf->base[0]);
1903 if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1906 av_assert0(!buf->refcount);
1909 frame->opaque = buf;
1910 frame->type = FF_BUFFER_TYPE_USER;
1911 frame->extended_data = frame->data;
1913 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1914 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
1915 frame->data[i] = buf->data[i];
1916 frame->linesize[i] = buf->linesize[i];
1922 static void unref_buffer(FrameBuffer *buf)
1924 FrameBuffer **pool = buf->pool;
1926 av_assert0(buf->refcount > 0);
1928 if (!buf->refcount) {
1930 for(tmp= *pool; tmp; tmp= tmp->next)
1931 av_assert1(tmp != buf);
1938 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1940 FrameBuffer *buf = frame->opaque;
1943 if(frame->type!=FF_BUFFER_TYPE_USER) {
1944 avcodec_default_release_buffer(s, frame);
1948 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1949 frame->data[i] = NULL;
1954 void filter_release_buffer(AVFilterBuffer *fb)
1956 FrameBuffer *buf = fb->priv;
1961 void free_buffer_pool(FrameBuffer **pool)
1963 FrameBuffer *buf = *pool;
1966 av_freep(&buf->base[0]);