Merge remote-tracking branch 'libav/master'
[FFMpeg-mirror/mplayer-patches.git] / cmdutils.c
blob4655681e4a6b589e22938dfb8a3dc836167c8532
1 /*
2 * Various utilities for command line tools
3 * Copyright (c) 2000-2003 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include <string.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <math.h>
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. */
31 #include "config.h"
32 #include "libavformat/avformat.h"
33 #include "libavfilter/avfilter.h"
34 #include "libavdevice/avdevice.h"
35 #include "libavresample/avresample.h"
36 #include "libswscale/swscale.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/imgutils.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/pixdesc.h"
43 #include "libavutil/eval.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/opt.h"
46 #include "cmdutils.h"
47 #include "version.h"
48 #if CONFIG_NETWORK
49 #include "libavformat/network.h"
50 #endif
51 #if HAVE_SYS_RESOURCE_H
52 #include <sys/time.h>
53 #include <sys/resource.h>
54 #endif
56 struct SwsContext *sws_opts;
57 AVDictionary *format_opts, *codec_opts, *resample_opts;
59 static const int this_year = 2013;
61 void init_opts(void)
63 #if CONFIG_SWSCALE
64 sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
65 NULL, NULL, NULL);
66 #endif
69 void uninit_opts(void)
71 #if CONFIG_SWSCALE
72 sws_freeContext(sws_opts);
73 sws_opts = NULL;
74 #endif
75 av_dict_free(&format_opts);
76 av_dict_free(&codec_opts);
77 av_dict_free(&resample_opts);
80 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
82 vfprintf(stdout, fmt, vl);
85 double parse_number_or_die(const char *context, const char *numstr, int type,
86 double min, double max)
88 char *tail;
89 const char *error;
90 double d = av_strtod(numstr, &tail);
91 if (*tail)
92 error = "Expected number for %s but found: %s\n";
93 else if (d < min || d > max)
94 error = "The value for %s was %s which is not within %f - %f\n";
95 else if (type == OPT_INT64 && (int64_t)d != d)
96 error = "Expected int64 for %s but found %s\n";
97 else if (type == OPT_INT && (int)d != d)
98 error = "Expected int for %s but found %s\n";
99 else
100 return d;
101 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
102 exit(1);
103 return 0;
106 int64_t parse_time_or_die(const char *context, const char *timestr,
107 int is_duration)
109 int64_t us;
110 if (av_parse_time(&us, timestr, is_duration) < 0) {
111 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
112 is_duration ? "duration" : "date", context, timestr);
113 exit(1);
115 return us;
118 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
119 int rej_flags, int alt_flags)
121 const OptionDef *po;
122 int first;
124 first = 1;
125 for (po = options; po->name != NULL; po++) {
126 char buf[64];
128 if (((po->flags & req_flags) != req_flags) ||
129 (alt_flags && !(po->flags & alt_flags)) ||
130 (po->flags & rej_flags))
131 continue;
133 if (first) {
134 printf("%s\n", msg);
135 first = 0;
137 av_strlcpy(buf, po->name, sizeof(buf));
138 if (po->argname) {
139 av_strlcat(buf, " ", sizeof(buf));
140 av_strlcat(buf, po->argname, sizeof(buf));
142 printf("-%-17s %s\n", buf, po->help);
144 printf("\n");
147 void show_help_children(const AVClass *class, int flags)
149 const AVClass *child = NULL;
150 av_opt_show2(&class, NULL, flags, 0);
151 printf("\n");
153 while (child = av_opt_child_class_next(class, child))
154 show_help_children(child, flags);
157 static const OptionDef *find_option(const OptionDef *po, const char *name)
159 const char *p = strchr(name, ':');
160 int len = p ? p - name : strlen(name);
162 while (po->name != NULL) {
163 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
164 break;
165 po++;
167 return po;
170 #if HAVE_COMMANDLINETOARGVW
171 #include <windows.h>
172 #include <shellapi.h>
173 /* Will be leaked on exit */
174 static char** win32_argv_utf8 = NULL;
175 static int win32_argc = 0;
178 * Prepare command line arguments for executable.
179 * For Windows - perform wide-char to UTF-8 conversion.
180 * Input arguments should be main() function arguments.
181 * @param argc_ptr Arguments number (including executable)
182 * @param argv_ptr Arguments list.
184 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
186 char *argstr_flat;
187 wchar_t **argv_w;
188 int i, buffsize = 0, offset = 0;
190 if (win32_argv_utf8) {
191 *argc_ptr = win32_argc;
192 *argv_ptr = win32_argv_utf8;
193 return;
196 win32_argc = 0;
197 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
198 if (win32_argc <= 0 || !argv_w)
199 return;
201 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
202 for (i = 0; i < win32_argc; i++)
203 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
204 NULL, 0, NULL, NULL);
206 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
207 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
208 if (win32_argv_utf8 == NULL) {
209 LocalFree(argv_w);
210 return;
213 for (i = 0; i < win32_argc; i++) {
214 win32_argv_utf8[i] = &argstr_flat[offset];
215 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
216 &argstr_flat[offset],
217 buffsize - offset, NULL, NULL);
219 win32_argv_utf8[i] = NULL;
220 LocalFree(argv_w);
222 *argc_ptr = win32_argc;
223 *argv_ptr = win32_argv_utf8;
225 #else
226 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
228 /* nothing to do */
230 #endif /* HAVE_COMMANDLINETOARGVW */
232 static int write_option(void *optctx, const OptionDef *po, const char *opt,
233 const char *arg)
235 /* new-style options contain an offset into optctx, old-style address of
236 * a global var*/
237 void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
238 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
239 int *dstcount;
241 if (po->flags & OPT_SPEC) {
242 SpecifierOpt **so = dst;
243 char *p = strchr(opt, ':');
245 dstcount = (int *)(so + 1);
246 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
247 (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
248 dst = &(*so)[*dstcount - 1].u;
251 if (po->flags & OPT_STRING) {
252 char *str;
253 str = av_strdup(arg);
254 av_freep(dst);
255 *(char **)dst = str;
256 } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
257 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
258 } else if (po->flags & OPT_INT64) {
259 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
260 } else if (po->flags & OPT_TIME) {
261 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
262 } else if (po->flags & OPT_FLOAT) {
263 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
264 } else if (po->flags & OPT_DOUBLE) {
265 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
266 } else if (po->u.func_arg) {
267 int ret = po->u.func_arg(optctx, opt, arg);
268 if (ret < 0) {
269 av_log(NULL, AV_LOG_ERROR,
270 "Failed to set value '%s' for option '%s'\n", arg, opt);
271 return ret;
274 if (po->flags & OPT_EXIT)
275 exit(0);
277 return 0;
280 int parse_option(void *optctx, const char *opt, const char *arg,
281 const OptionDef *options)
283 const OptionDef *po;
284 int ret;
286 po = find_option(options, opt);
287 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
288 /* handle 'no' bool option */
289 po = find_option(options, opt + 2);
290 if ((po->name && (po->flags & OPT_BOOL)))
291 arg = "0";
292 } else if (po->flags & OPT_BOOL)
293 arg = "1";
295 if (!po->name)
296 po = find_option(options, "default");
297 if (!po->name) {
298 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
299 return AVERROR(EINVAL);
301 if (po->flags & HAS_ARG && !arg) {
302 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
303 return AVERROR(EINVAL);
306 ret = write_option(optctx, po, opt, arg);
307 if (ret < 0)
308 return ret;
310 return !!(po->flags & HAS_ARG);
313 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
314 void (*parse_arg_function)(void *, const char*))
316 const char *opt;
317 int optindex, handleoptions = 1, ret;
319 /* perform system-dependent conversions for arguments list */
320 prepare_app_arguments(&argc, &argv);
322 /* parse options */
323 optindex = 1;
324 while (optindex < argc) {
325 opt = argv[optindex++];
327 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
328 if (opt[1] == '-' && opt[2] == '\0') {
329 handleoptions = 0;
330 continue;
332 opt++;
334 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
335 exit(1);
336 optindex += ret;
337 } else {
338 if (parse_arg_function)
339 parse_arg_function(optctx, opt);
344 int parse_optgroup(void *optctx, OptionGroup *g)
346 int i, ret;
348 av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
349 g->group_def->name, g->arg);
351 for (i = 0; i < g->nb_opts; i++) {
352 Option *o = &g->opts[i];
354 av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
355 o->key, o->opt->help, o->val);
357 ret = write_option(optctx, o->opt, o->key, o->val);
358 if (ret < 0)
359 return ret;
362 av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
364 return 0;
367 int locate_option(int argc, char **argv, const OptionDef *options,
368 const char *optname)
370 const OptionDef *po;
371 int i;
373 for (i = 1; i < argc; i++) {
374 const char *cur_opt = argv[i];
376 if (*cur_opt++ != '-')
377 continue;
379 po = find_option(options, cur_opt);
380 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
381 po = find_option(options, cur_opt + 2);
383 if ((!po->name && !strcmp(cur_opt, optname)) ||
384 (po->name && !strcmp(optname, po->name)))
385 return i;
387 if (!po || po->flags & HAS_ARG)
388 i++;
390 return 0;
393 void parse_loglevel(int argc, char **argv, const OptionDef *options)
395 int idx = locate_option(argc, argv, options, "loglevel");
396 if (!idx)
397 idx = locate_option(argc, argv, options, "v");
398 if (idx && argv[idx + 1])
399 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
402 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
403 int opt_default(void *optctx, const char *opt, const char *arg)
405 const AVOption *o;
406 char opt_stripped[128];
407 const char *p;
408 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
409 #if CONFIG_AVRESAMPLE
410 const AVClass *rc = avresample_get_class();
411 #endif
412 #if CONFIG_SWSCALE
413 const AVClass *sc = sws_get_class();
414 #endif
416 if (!(p = strchr(opt, ':')))
417 p = opt + strlen(opt);
418 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
420 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
421 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
422 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
423 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
424 av_dict_set(&codec_opts, opt, arg, FLAGS);
425 else if ((o = av_opt_find(&fc, opt, NULL, 0,
426 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
427 av_dict_set(&format_opts, opt, arg, FLAGS);
428 #if CONFIG_AVRESAMPLE
429 else if ((o = av_opt_find(&rc, opt, NULL, 0,
430 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
431 av_dict_set(&resample_opts, opt, arg, FLAGS);
432 #endif
433 #if CONFIG_SWSCALE
434 else if ((o = av_opt_find(&sc, opt, NULL, 0,
435 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
436 // XXX we only support sws_flags, not arbitrary sws options
437 int ret = av_opt_set(sws_opts, opt, arg, 0);
438 if (ret < 0) {
439 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
440 return ret;
443 #endif
445 if (o)
446 return 0;
447 return AVERROR_OPTION_NOT_FOUND;
451 * Check whether given option is a group separator.
453 * @return index of the group definition that matched or -1 if none
455 static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
456 const char *opt)
458 int i;
460 for (i = 0; i < nb_groups; i++) {
461 const OptionGroupDef *p = &groups[i];
462 if (p->sep && !strcmp(p->sep, opt))
463 return i;
466 return -1;
470 * Finish parsing an option group.
472 * @param group_idx which group definition should this group belong to
473 * @param arg argument of the group delimiting option
475 static void finish_group(OptionParseContext *octx, int group_idx,
476 const char *arg)
478 OptionGroupList *l = &octx->groups[group_idx];
479 OptionGroup *g;
481 GROW_ARRAY(l->groups, l->nb_groups);
482 g = &l->groups[l->nb_groups - 1];
484 *g = octx->cur_group;
485 g->arg = arg;
486 g->group_def = l->group_def;
487 #if CONFIG_SWSCALE
488 g->sws_opts = sws_opts;
489 #endif
490 g->codec_opts = codec_opts;
491 g->format_opts = format_opts;
492 g->resample_opts = resample_opts;
494 codec_opts = NULL;
495 format_opts = NULL;
496 resample_opts = NULL;
497 #if CONFIG_SWSCALE
498 sws_opts = NULL;
499 #endif
500 init_opts();
502 memset(&octx->cur_group, 0, sizeof(octx->cur_group));
506 * Add an option instance to currently parsed group.
508 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
509 const char *key, const char *val)
511 int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
512 OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
514 GROW_ARRAY(g->opts, g->nb_opts);
515 g->opts[g->nb_opts - 1].opt = opt;
516 g->opts[g->nb_opts - 1].key = key;
517 g->opts[g->nb_opts - 1].val = val;
520 static void init_parse_context(OptionParseContext *octx,
521 const OptionGroupDef *groups, int nb_groups)
523 static const OptionGroupDef global_group = { "global" };
524 int i;
526 memset(octx, 0, sizeof(*octx));
528 octx->nb_groups = nb_groups;
529 octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
530 if (!octx->groups)
531 exit(1);
533 for (i = 0; i < octx->nb_groups; i++)
534 octx->groups[i].group_def = &groups[i];
536 octx->global_opts.group_def = &global_group;
537 octx->global_opts.arg = "";
539 init_opts();
542 void uninit_parse_context(OptionParseContext *octx)
544 int i, j;
546 for (i = 0; i < octx->nb_groups; i++) {
547 OptionGroupList *l = &octx->groups[i];
549 for (j = 0; j < l->nb_groups; j++) {
550 av_freep(&l->groups[j].opts);
551 av_dict_free(&l->groups[j].codec_opts);
552 av_dict_free(&l->groups[j].format_opts);
553 av_dict_free(&l->groups[j].resample_opts);
554 #if CONFIG_SWSCALE
555 sws_freeContext(l->groups[j].sws_opts);
556 #endif
558 av_freep(&l->groups);
560 av_freep(&octx->groups);
562 av_freep(&octx->cur_group.opts);
563 av_freep(&octx->global_opts.opts);
565 uninit_opts();
568 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
569 const OptionDef *options,
570 const OptionGroupDef *groups, int nb_groups)
572 int optindex = 1;
574 /* perform system-dependent conversions for arguments list */
575 prepare_app_arguments(&argc, &argv);
577 init_parse_context(octx, groups, nb_groups);
578 av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
580 while (optindex < argc) {
581 const char *opt = argv[optindex++], *arg;
582 const OptionDef *po;
583 int ret;
585 av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
587 /* unnamed group separators, e.g. output filename */
588 if (opt[0] != '-' || !opt[1]) {
589 finish_group(octx, 0, opt);
590 av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
591 continue;
593 opt++;
595 #define GET_ARG(arg) \
596 do { \
597 arg = argv[optindex++]; \
598 if (!arg) { \
599 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
600 return AVERROR(EINVAL); \
602 } while (0)
604 /* named group separators, e.g. -i */
605 if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
606 GET_ARG(arg);
607 finish_group(octx, ret, arg);
608 av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
609 groups[ret].name, arg);
610 continue;
613 /* normal options */
614 po = find_option(options, opt);
615 if (po->name) {
616 if (po->flags & OPT_EXIT) {
617 /* optional argument, e.g. -h */
618 arg = argv[optindex++];
619 } else if (po->flags & HAS_ARG) {
620 GET_ARG(arg);
621 } else {
622 arg = "1";
625 add_opt(octx, po, opt, arg);
626 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
627 "argument '%s'.\n", po->name, po->help, arg);
628 continue;
631 /* AVOptions */
632 if (argv[optindex]) {
633 ret = opt_default(NULL, opt, argv[optindex]);
634 if (ret >= 0) {
635 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
636 "argument '%s'.\n", opt, argv[optindex]);
637 optindex++;
638 continue;
639 } else if (ret != AVERROR_OPTION_NOT_FOUND) {
640 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
641 "with argument '%s'.\n", opt, argv[optindex]);
642 return ret;
646 /* boolean -nofoo options */
647 if (opt[0] == 'n' && opt[1] == 'o' &&
648 (po = find_option(options, opt + 2)) &&
649 po->name && po->flags & OPT_BOOL) {
650 add_opt(octx, po, opt, "0");
651 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
652 "argument 0.\n", po->name, po->help);
653 continue;
656 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
657 return AVERROR_OPTION_NOT_FOUND;
660 if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
661 av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
662 "commandline.\n");
664 av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
666 return 0;
669 int opt_loglevel(void *optctx, const char *opt, const char *arg)
671 const struct { const char *name; int level; } log_levels[] = {
672 { "quiet" , AV_LOG_QUIET },
673 { "panic" , AV_LOG_PANIC },
674 { "fatal" , AV_LOG_FATAL },
675 { "error" , AV_LOG_ERROR },
676 { "warning", AV_LOG_WARNING },
677 { "info" , AV_LOG_INFO },
678 { "verbose", AV_LOG_VERBOSE },
679 { "debug" , AV_LOG_DEBUG },
681 char *tail;
682 int level;
683 int i;
685 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
686 if (!strcmp(log_levels[i].name, arg)) {
687 av_log_set_level(log_levels[i].level);
688 return 0;
692 level = strtol(arg, &tail, 10);
693 if (*tail) {
694 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
695 "Possible levels are numbers or:\n", arg);
696 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
697 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
698 exit(1);
700 av_log_set_level(level);
701 return 0;
704 int opt_timelimit(void *optctx, const char *opt, const char *arg)
706 #if HAVE_SETRLIMIT
707 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
708 struct rlimit rl = { lim, lim + 1 };
709 if (setrlimit(RLIMIT_CPU, &rl))
710 perror("setrlimit");
711 #else
712 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
713 #endif
714 return 0;
717 void print_error(const char *filename, int err)
719 char errbuf[128];
720 const char *errbuf_ptr = errbuf;
722 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
723 errbuf_ptr = strerror(AVUNERROR(err));
724 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
727 static int warned_cfg = 0;
729 #define INDENT 1
730 #define SHOW_VERSION 2
731 #define SHOW_CONFIG 4
733 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
734 if (CONFIG_##LIBNAME) { \
735 const char *indent = flags & INDENT? " " : ""; \
736 if (flags & SHOW_VERSION) { \
737 unsigned int version = libname##_version(); \
738 av_log(NULL, level, \
739 "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
740 indent, #libname, \
741 LIB##LIBNAME##_VERSION_MAJOR, \
742 LIB##LIBNAME##_VERSION_MINOR, \
743 LIB##LIBNAME##_VERSION_MICRO, \
744 version >> 16, version >> 8 & 0xff, version & 0xff); \
746 if (flags & SHOW_CONFIG) { \
747 const char *cfg = libname##_configuration(); \
748 if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
749 if (!warned_cfg) { \
750 av_log(NULL, level, \
751 "%sWARNING: library configuration mismatch\n", \
752 indent); \
753 warned_cfg = 1; \
755 av_log(NULL, level, "%s%-11s configuration: %s\n", \
756 indent, #libname, cfg); \
761 static void print_all_libs_info(int flags, int level)
763 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
764 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
765 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
766 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
767 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
768 PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
769 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
772 void show_banner(void)
774 av_log(NULL, AV_LOG_INFO,
775 "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
776 program_name, program_birth_year, this_year);
777 av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
778 __DATE__, __TIME__, CC_IDENT);
779 av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
780 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
781 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
784 int show_version(void *optctx, const char *opt, const char *arg)
786 av_log_set_callback(log_callback_help);
787 printf("%s " LIBAV_VERSION "\n", program_name);
788 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
790 return 0;
793 int show_license(void *optctx, const char *opt, const char *arg)
795 printf(
796 #if CONFIG_NONFREE
797 "This version of %s has nonfree parts compiled in.\n"
798 "Therefore it is not legally redistributable.\n",
799 program_name
800 #elif CONFIG_GPLV3
801 "%s is free software; you can redistribute it and/or modify\n"
802 "it under the terms of the GNU General Public License as published by\n"
803 "the Free Software Foundation; either version 3 of the License, or\n"
804 "(at your option) any later version.\n"
805 "\n"
806 "%s is distributed in the hope that it will be useful,\n"
807 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
808 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
809 "GNU General Public License for more details.\n"
810 "\n"
811 "You should have received a copy of the GNU General Public License\n"
812 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
813 program_name, program_name, program_name
814 #elif CONFIG_GPL
815 "%s is free software; you can redistribute it and/or modify\n"
816 "it under the terms of the GNU General Public License as published by\n"
817 "the Free Software Foundation; either version 2 of the License, or\n"
818 "(at your option) any later version.\n"
819 "\n"
820 "%s is distributed in the hope that it will be useful,\n"
821 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
822 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
823 "GNU General Public License for more details.\n"
824 "\n"
825 "You should have received a copy of the GNU General Public License\n"
826 "along with %s; if not, write to the Free Software\n"
827 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
828 program_name, program_name, program_name
829 #elif CONFIG_LGPLV3
830 "%s is free software; you can redistribute it and/or modify\n"
831 "it under the terms of the GNU Lesser General Public License as published by\n"
832 "the Free Software Foundation; either version 3 of the License, or\n"
833 "(at your option) any later version.\n"
834 "\n"
835 "%s is distributed in the hope that it will be useful,\n"
836 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
837 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
838 "GNU Lesser General Public License for more details.\n"
839 "\n"
840 "You should have received a copy of the GNU Lesser General Public License\n"
841 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
842 program_name, program_name, program_name
843 #else
844 "%s is free software; you can redistribute it and/or\n"
845 "modify it under the terms of the GNU Lesser General Public\n"
846 "License as published by the Free Software Foundation; either\n"
847 "version 2.1 of the License, or (at your option) any later version.\n"
848 "\n"
849 "%s is distributed in the hope that it will be useful,\n"
850 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
851 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
852 "Lesser General Public License for more details.\n"
853 "\n"
854 "You should have received a copy of the GNU Lesser General Public\n"
855 "License along with %s; if not, write to the Free Software\n"
856 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
857 program_name, program_name, program_name
858 #endif
861 return 0;
864 int show_formats(void *optctx, const char *opt, const char *arg)
866 AVInputFormat *ifmt = NULL;
867 AVOutputFormat *ofmt = NULL;
868 const char *last_name;
870 printf("File formats:\n"
871 " D. = Demuxing supported\n"
872 " .E = Muxing supported\n"
873 " --\n");
874 last_name = "000";
875 for (;;) {
876 int decode = 0;
877 int encode = 0;
878 const char *name = NULL;
879 const char *long_name = NULL;
881 while ((ofmt = av_oformat_next(ofmt))) {
882 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
883 strcmp(ofmt->name, last_name) > 0) {
884 name = ofmt->name;
885 long_name = ofmt->long_name;
886 encode = 1;
889 while ((ifmt = av_iformat_next(ifmt))) {
890 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
891 strcmp(ifmt->name, last_name) > 0) {
892 name = ifmt->name;
893 long_name = ifmt->long_name;
894 encode = 0;
896 if (name && strcmp(ifmt->name, name) == 0)
897 decode = 1;
899 if (name == NULL)
900 break;
901 last_name = name;
903 printf(" %s%s %-15s %s\n",
904 decode ? "D" : " ",
905 encode ? "E" : " ",
906 name,
907 long_name ? long_name:" ");
909 return 0;
912 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
913 if (codec->field) { \
914 const type *p = c->field; \
916 printf(" Supported " list_name ":"); \
917 while (*p != term) { \
918 get_name(*p); \
919 printf(" %s", name); \
920 p++; \
922 printf("\n"); \
925 static void print_codec(const AVCodec *c)
927 int encoder = av_codec_is_encoder(c);
929 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
930 c->long_name ? c->long_name : "");
932 if (c->type == AVMEDIA_TYPE_VIDEO) {
933 printf(" Threading capabilities: ");
934 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
935 CODEC_CAP_SLICE_THREADS)) {
936 case CODEC_CAP_FRAME_THREADS |
937 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
938 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
939 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
940 default: printf("no"); break;
942 printf("\n");
945 if (c->supported_framerates) {
946 const AVRational *fps = c->supported_framerates;
948 printf(" Supported framerates:");
949 while (fps->num) {
950 printf(" %d/%d", fps->num, fps->den);
951 fps++;
953 printf("\n");
955 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
956 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
957 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
958 GET_SAMPLE_RATE_NAME);
959 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
960 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
961 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
962 0, GET_CH_LAYOUT_DESC);
964 if (c->priv_class) {
965 show_help_children(c->priv_class,
966 AV_OPT_FLAG_ENCODING_PARAM |
967 AV_OPT_FLAG_DECODING_PARAM);
971 static char get_media_type_char(enum AVMediaType type)
973 switch (type) {
974 case AVMEDIA_TYPE_VIDEO: return 'V';
975 case AVMEDIA_TYPE_AUDIO: return 'A';
976 case AVMEDIA_TYPE_SUBTITLE: return 'S';
977 default: return '?';
981 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
982 int encoder)
984 while ((prev = av_codec_next(prev))) {
985 if (prev->id == id &&
986 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
987 return prev;
989 return NULL;
992 static void print_codecs_for_id(enum AVCodecID id, int encoder)
994 const AVCodec *codec = NULL;
996 printf(" (%s: ", encoder ? "encoders" : "decoders");
998 while ((codec = next_codec_for_id(id, codec, encoder)))
999 printf("%s ", codec->name);
1001 printf(")");
1004 int show_codecs(void *optctx, const char *opt, const char *arg)
1006 const AVCodecDescriptor *desc = NULL;
1008 printf("Codecs:\n"
1009 " D..... = Decoding supported\n"
1010 " .E.... = Encoding supported\n"
1011 " ..V... = Video codec\n"
1012 " ..A... = Audio codec\n"
1013 " ..S... = Subtitle codec\n"
1014 " ...I.. = Intra frame-only codec\n"
1015 " ....L. = Lossy compression\n"
1016 " .....S = Lossless compression\n"
1017 " -------\n");
1018 while ((desc = avcodec_descriptor_next(desc))) {
1019 const AVCodec *codec = NULL;
1021 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1022 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1024 printf("%c", get_media_type_char(desc->type));
1025 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1026 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
1027 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
1029 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1031 /* print decoders/encoders when there's more than one or their
1032 * names are different from codec name */
1033 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1034 if (strcmp(codec->name, desc->name)) {
1035 print_codecs_for_id(desc->id, 0);
1036 break;
1039 codec = NULL;
1040 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1041 if (strcmp(codec->name, desc->name)) {
1042 print_codecs_for_id(desc->id, 1);
1043 break;
1047 printf("\n");
1049 return 0;
1052 static void print_codecs(int encoder)
1054 const AVCodecDescriptor *desc = NULL;
1056 printf("%s:\n"
1057 " V... = Video\n"
1058 " A... = Audio\n"
1059 " S... = Subtitle\n"
1060 " .F.. = Frame-level multithreading\n"
1061 " ..S. = Slice-level multithreading\n"
1062 " ...X = Codec is experimental\n"
1063 " ---\n",
1064 encoder ? "Encoders" : "Decoders");
1065 while ((desc = avcodec_descriptor_next(desc))) {
1066 const AVCodec *codec = NULL;
1068 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1069 printf("%c", get_media_type_char(desc->type));
1070 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1071 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1072 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
1074 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1075 if (strcmp(codec->name, desc->name))
1076 printf(" (codec %s)", desc->name);
1078 printf("\n");
1083 int show_decoders(void *optctx, const char *opt, const char *arg)
1085 print_codecs(0);
1086 return 0;
1089 int show_encoders(void *optctx, const char *opt, const char *arg)
1091 print_codecs(1);
1092 return 0;
1095 int show_bsfs(void *optctx, const char *opt, const char *arg)
1097 AVBitStreamFilter *bsf = NULL;
1099 printf("Bitstream filters:\n");
1100 while ((bsf = av_bitstream_filter_next(bsf)))
1101 printf("%s\n", bsf->name);
1102 printf("\n");
1103 return 0;
1106 int show_protocols(void *optctx, const char *opt, const char *arg)
1108 void *opaque = NULL;
1109 const char *name;
1111 printf("Supported file protocols:\n"
1112 "Input:\n");
1113 while ((name = avio_enum_protocols(&opaque, 0)))
1114 printf("%s\n", name);
1115 printf("Output:\n");
1116 while ((name = avio_enum_protocols(&opaque, 1)))
1117 printf("%s\n", name);
1118 return 0;
1121 int show_filters(void *optctx, const char *opt, const char *arg)
1123 AVFilter av_unused(**filter) = NULL;
1125 printf("Filters:\n");
1126 #if CONFIG_AVFILTER
1127 while ((filter = av_filter_next(filter)) && *filter)
1128 printf("%-16s %s\n", (*filter)->name, (*filter)->description);
1129 #endif
1130 return 0;
1133 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1135 const AVPixFmtDescriptor *pix_desc = NULL;
1137 printf("Pixel formats:\n"
1138 "I.... = Supported Input format for conversion\n"
1139 ".O... = Supported Output format for conversion\n"
1140 "..H.. = Hardware accelerated format\n"
1141 "...P. = Paletted format\n"
1142 "....B = Bitstream format\n"
1143 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
1144 "-----\n");
1146 #if !CONFIG_SWSCALE
1147 # define sws_isSupportedInput(x) 0
1148 # define sws_isSupportedOutput(x) 0
1149 #endif
1151 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1152 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1153 printf("%c%c%c%c%c %-16s %d %2d\n",
1154 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
1155 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
1156 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
1157 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
1158 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1159 pix_desc->name,
1160 pix_desc->nb_components,
1161 av_get_bits_per_pixel(pix_desc));
1163 return 0;
1166 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1168 int i;
1169 char fmt_str[128];
1170 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1171 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1172 return 0;
1175 static void show_help_codec(const char *name, int encoder)
1177 const AVCodecDescriptor *desc;
1178 const AVCodec *codec;
1180 if (!name) {
1181 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1182 return;
1185 codec = encoder ? avcodec_find_encoder_by_name(name) :
1186 avcodec_find_decoder_by_name(name);
1188 if (codec)
1189 print_codec(codec);
1190 else if ((desc = avcodec_descriptor_get_by_name(name))) {
1191 int printed = 0;
1193 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1194 printed = 1;
1195 print_codec(codec);
1198 if (!printed) {
1199 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
1200 "but no %s for it are available. Libav might need to be "
1201 "recompiled with additional external libraries.\n",
1202 name, encoder ? "encoders" : "decoders");
1204 } else {
1205 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
1206 name);
1210 static void show_help_demuxer(const char *name)
1212 const AVInputFormat *fmt = av_find_input_format(name);
1214 if (!fmt) {
1215 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1216 return;
1219 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1221 if (fmt->extensions)
1222 printf(" Common extensions: %s.\n", fmt->extensions);
1224 if (fmt->priv_class)
1225 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1228 static void show_help_muxer(const char *name)
1230 const AVCodecDescriptor *desc;
1231 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1233 if (!fmt) {
1234 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1235 return;
1238 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1240 if (fmt->extensions)
1241 printf(" Common extensions: %s.\n", fmt->extensions);
1242 if (fmt->mime_type)
1243 printf(" Mime type: %s.\n", fmt->mime_type);
1244 if (fmt->video_codec != AV_CODEC_ID_NONE &&
1245 (desc = avcodec_descriptor_get(fmt->video_codec))) {
1246 printf(" Default video codec: %s.\n", desc->name);
1248 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1249 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1250 printf(" Default audio codec: %s.\n", desc->name);
1252 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1253 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1254 printf(" Default subtitle codec: %s.\n", desc->name);
1257 if (fmt->priv_class)
1258 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1261 int show_help(void *optctx, const char *opt, const char *arg)
1263 char *topic, *par;
1264 av_log_set_callback(log_callback_help);
1266 topic = av_strdup(arg ? arg : "");
1267 par = strchr(topic, '=');
1268 if (par)
1269 *par++ = 0;
1271 if (!*topic) {
1272 show_help_default(topic, par);
1273 } else if (!strcmp(topic, "decoder")) {
1274 show_help_codec(par, 0);
1275 } else if (!strcmp(topic, "encoder")) {
1276 show_help_codec(par, 1);
1277 } else if (!strcmp(topic, "demuxer")) {
1278 show_help_demuxer(par);
1279 } else if (!strcmp(topic, "muxer")) {
1280 show_help_muxer(par);
1281 } else {
1282 show_help_default(topic, par);
1285 av_freep(&topic);
1286 return 0;
1289 int read_yesno(void)
1291 int c = getchar();
1292 int yesno = (av_toupper(c) == 'Y');
1294 while (c != '\n' && c != EOF)
1295 c = getchar();
1297 return yesno;
1300 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1302 int ret;
1303 FILE *f = fopen(filename, "rb");
1305 if (!f) {
1306 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1307 strerror(errno));
1308 return AVERROR(errno);
1310 fseek(f, 0, SEEK_END);
1311 *size = ftell(f);
1312 fseek(f, 0, SEEK_SET);
1313 *bufptr = av_malloc(*size + 1);
1314 if (!*bufptr) {
1315 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1316 fclose(f);
1317 return AVERROR(ENOMEM);
1319 ret = fread(*bufptr, 1, *size, f);
1320 if (ret < *size) {
1321 av_free(*bufptr);
1322 if (ferror(f)) {
1323 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1324 filename, strerror(errno));
1325 ret = AVERROR(errno);
1326 } else
1327 ret = AVERROR_EOF;
1328 } else {
1329 ret = 0;
1330 (*bufptr)[(*size)++] = '\0';
1333 fclose(f);
1334 return ret;
1337 void init_pts_correction(PtsCorrectionContext *ctx)
1339 ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1340 ctx->last_pts = ctx->last_dts = INT64_MIN;
1343 int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1344 int64_t dts)
1346 int64_t pts = AV_NOPTS_VALUE;
1348 if (dts != AV_NOPTS_VALUE) {
1349 ctx->num_faulty_dts += dts <= ctx->last_dts;
1350 ctx->last_dts = dts;
1352 if (reordered_pts != AV_NOPTS_VALUE) {
1353 ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1354 ctx->last_pts = reordered_pts;
1356 if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
1357 && reordered_pts != AV_NOPTS_VALUE)
1358 pts = reordered_pts;
1359 else
1360 pts = dts;
1362 return pts;
1365 FILE *get_preset_file(char *filename, size_t filename_size,
1366 const char *preset_name, int is_path,
1367 const char *codec_name)
1369 FILE *f = NULL;
1370 int i;
1371 const char *base[3] = { getenv("AVCONV_DATADIR"),
1372 getenv("HOME"),
1373 AVCONV_DATADIR, };
1375 if (is_path) {
1376 av_strlcpy(filename, preset_name, filename_size);
1377 f = fopen(filename, "r");
1378 } else {
1379 for (i = 0; i < 3 && !f; i++) {
1380 if (!base[i])
1381 continue;
1382 snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
1383 i != 1 ? "" : "/.avconv", preset_name);
1384 f = fopen(filename, "r");
1385 if (!f && codec_name) {
1386 snprintf(filename, filename_size,
1387 "%s%s/%s-%s.avpreset",
1388 base[i], i != 1 ? "" : "/.avconv", codec_name,
1389 preset_name);
1390 f = fopen(filename, "r");
1395 return f;
1398 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1400 if (*spec <= '9' && *spec >= '0') /* opt:index */
1401 return strtol(spec, NULL, 0) == st->index;
1402 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1403 *spec == 't') { /* opt:[vasdt] */
1404 enum AVMediaType type;
1406 switch (*spec++) {
1407 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
1408 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
1409 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1410 case 'd': type = AVMEDIA_TYPE_DATA; break;
1411 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1412 default: av_assert0(0);
1414 if (type != st->codec->codec_type)
1415 return 0;
1416 if (*spec++ == ':') { /* possibly followed by :index */
1417 int i, index = strtol(spec, NULL, 0);
1418 for (i = 0; i < s->nb_streams; i++)
1419 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1420 return i == st->index;
1421 return 0;
1423 return 1;
1424 } else if (*spec == 'p' && *(spec + 1) == ':') {
1425 int prog_id, i, j;
1426 char *endptr;
1427 spec += 2;
1428 prog_id = strtol(spec, &endptr, 0);
1429 for (i = 0; i < s->nb_programs; i++) {
1430 if (s->programs[i]->id != prog_id)
1431 continue;
1433 if (*endptr++ == ':') {
1434 int stream_idx = strtol(endptr, NULL, 0);
1435 return stream_idx >= 0 &&
1436 stream_idx < s->programs[i]->nb_stream_indexes &&
1437 st->index == s->programs[i]->stream_index[stream_idx];
1440 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1441 if (st->index == s->programs[i]->stream_index[j])
1442 return 1;
1444 return 0;
1445 } else if (!*spec) /* empty specifier, matches everything */
1446 return 1;
1448 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1449 return AVERROR(EINVAL);
1452 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1453 AVFormatContext *s, AVStream *st, AVCodec *codec)
1455 AVDictionary *ret = NULL;
1456 AVDictionaryEntry *t = NULL;
1457 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1458 : AV_OPT_FLAG_DECODING_PARAM;
1459 char prefix = 0;
1460 const AVClass *cc = avcodec_get_class();
1462 if (!codec)
1463 codec = s->oformat ? avcodec_find_encoder(codec_id)
1464 : avcodec_find_decoder(codec_id);
1466 switch (st->codec->codec_type) {
1467 case AVMEDIA_TYPE_VIDEO:
1468 prefix = 'v';
1469 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1470 break;
1471 case AVMEDIA_TYPE_AUDIO:
1472 prefix = 'a';
1473 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1474 break;
1475 case AVMEDIA_TYPE_SUBTITLE:
1476 prefix = 's';
1477 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1478 break;
1481 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1482 char *p = strchr(t->key, ':');
1484 /* check stream specification in opt name */
1485 if (p)
1486 switch (check_stream_specifier(s, st, p + 1)) {
1487 case 1: *p = 0; break;
1488 case 0: continue;
1489 default: return NULL;
1492 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1493 (codec && codec->priv_class &&
1494 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1495 AV_OPT_SEARCH_FAKE_OBJ)))
1496 av_dict_set(&ret, t->key, t->value, 0);
1497 else if (t->key[0] == prefix &&
1498 av_opt_find(&cc, t->key + 1, NULL, flags,
1499 AV_OPT_SEARCH_FAKE_OBJ))
1500 av_dict_set(&ret, t->key + 1, t->value, 0);
1502 if (p)
1503 *p = ':';
1505 return ret;
1508 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1509 AVDictionary *codec_opts)
1511 int i;
1512 AVDictionary **opts;
1514 if (!s->nb_streams)
1515 return NULL;
1516 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1517 if (!opts) {
1518 av_log(NULL, AV_LOG_ERROR,
1519 "Could not alloc memory for stream options.\n");
1520 return NULL;
1522 for (i = 0; i < s->nb_streams; i++)
1523 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1524 s, s->streams[i], NULL);
1525 return opts;
1528 void *grow_array(void *array, int elem_size, int *size, int new_size)
1530 if (new_size >= INT_MAX / elem_size) {
1531 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1532 exit(1);
1534 if (*size < new_size) {
1535 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1536 if (!tmp) {
1537 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1538 exit(1);
1540 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1541 *size = new_size;
1542 return tmp;
1544 return array;