cmdutils: pass number of groups to split_commandline().
[libav.git] / cmdutils.c
CommitLineData
01310af2
FB
1/*
2 * Various utilities for command line tools
3 * Copyright (c) 2000-2003 Fabrice Bellard
4 *
2912e87a 5 * This file is part of Libav.
b78e7197 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
01310af2
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
01310af2 11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
01310af2
FB
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
2912e87a 18 * License along with Libav; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
01310af2 20 */
364a9607 21
0f4e8165
RB
22#include <string.h>
23#include <stdlib.h>
24#include <errno.h>
7c84b8bc 25#include <math.h>
0f4e8165 26
2cd39dbf
DP
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
63d026b1 31#include "config.h"
245976da
DB
32#include "libavformat/avformat.h"
33#include "libavfilter/avfilter.h"
34#include "libavdevice/avdevice.h"
bcb82fe1 35#include "libavresample/avresample.h"
db6d50c7 36#include "libswscale/swscale.h"
7cf78b34 37#include "libavutil/avassert.h"
245976da 38#include "libavutil/avstring.h"
85770d6e 39#include "libavutil/mathematics.h"
d55c2e05 40#include "libavutil/imgutils.h"
f6c7375a 41#include "libavutil/parseutils.h"
9cb5c760 42#include "libavutil/pixdesc.h"
25e25617 43#include "libavutil/eval.h"
9ba38229 44#include "libavutil/dict.h"
41d0eb1c 45#include "libavutil/opt.h"
01310af2 46#include "cmdutils.h"
86074ed1 47#include "version.h"
da2dc39e 48#if CONFIG_NETWORK
245976da 49#include "libavformat/network.h"
da2dc39e 50#endif
ffcc6e24 51#if HAVE_SYS_RESOURCE_H
3f65eff4 52#include <sys/time.h>
ffcc6e24
MR
53#include <sys/resource.h>
54#endif
01310af2 55
85663ef3 56struct SwsContext *sws_opts;
8c8eab8b 57AVDictionary *format_opts, *codec_opts;
086ab001 58
21d0d1d6 59static const int this_year = 2012;
ef4c0bb1 60
a5c33faa
RD
61void init_opts(void)
62{
be4876ea 63#if CONFIG_SWSCALE
cbaef7d1
AD
64 sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
65 NULL, NULL, NULL);
be4876ea 66#endif
a5c33faa
RD
67}
68
69void uninit_opts(void)
70{
be4876ea 71#if CONFIG_SWSCALE
faf8d3dd
RB
72 sws_freeContext(sws_opts);
73 sws_opts = NULL;
be4876ea 74#endif
9ba38229 75 av_dict_free(&format_opts);
8c8eab8b 76 av_dict_free(&codec_opts);
a5c33faa
RD
77}
78
cbaef7d1 79void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
1790d3b3
SS
80{
81 vfprintf(stdout, fmt, vl);
82}
83
cbaef7d1
AD
84double parse_number_or_die(const char *context, const char *numstr, int type,
85 double min, double max)
086ab001
MN
86{
87 char *tail;
88 const char *error;
25e25617 89 double d = av_strtod(numstr, &tail);
086ab001 90 if (*tail)
cbaef7d1 91 error = "Expected number for %s but found: %s\n";
086ab001 92 else if (d < min || d > max)
cbaef7d1
AD
93 error = "The value for %s was %s which is not within %f - %f\n";
94 else if (type == OPT_INT64 && (int64_t)d != d)
95 error = "Expected int64 for %s but found %s\n";
3372ec32 96 else if (type == OPT_INT && (int)d != d)
cbaef7d1 97 error = "Expected int for %s but found %s\n";
086ab001
MN
98 else
99 return d;
1c5e9551 100 av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
5e3f9979 101 exit(1);
dad09ff9 102 return 0;
086ab001
MN
103}
104
cbaef7d1
AD
105int64_t parse_time_or_die(const char *context, const char *timestr,
106 int is_duration)
7542157d 107{
f6c7375a
SS
108 int64_t us;
109 if (av_parse_time(&us, timestr, is_duration) < 0) {
1c5e9551
AK
110 av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
111 is_duration ? "duration" : "date", context, timestr);
5e3f9979 112 exit(1);
7542157d
SS
113 }
114 return us;
115}
116
7c501212 117void show_help_options(const OptionDef *options, const char *msg, int req_flags,
f9fada27 118 int rej_flags, int alt_flags)
01310af2
FB
119{
120 const OptionDef *po;
02d504a7 121 int first;
01310af2 122
02d504a7 123 first = 1;
cbaef7d1 124 for (po = options; po->name != NULL; po++) {
02d504a7 125 char buf[64];
7c501212
AK
126
127 if (((po->flags & req_flags) != req_flags) ||
f9fada27 128 (alt_flags && !(po->flags & alt_flags)) ||
7c501212
AK
129 (po->flags & rej_flags))
130 continue;
131
132 if (first) {
133 printf("%s\n", msg);
134 first = 0;
135 }
136 av_strlcpy(buf, po->name, sizeof(buf));
a3ad68d3 137 if (po->argname) {
7c501212
AK
138 av_strlcat(buf, " ", sizeof(buf));
139 av_strlcat(buf, po->argname, sizeof(buf));
01310af2 140 }
7c501212 141 printf("-%-17s %s\n", buf, po->help);
01310af2 142 }
dc4c24a3 143 printf("\n");
01310af2
FB
144}
145
7a6cd995
AK
146void show_help_children(const AVClass *class, int flags)
147{
148 const AVClass *child = NULL;
149 av_opt_show2(&class, NULL, flags, 0);
150 printf("\n");
151
152 while (child = av_opt_child_class_next(class, child))
153 show_help_children(child, flags);
154}
155
cbaef7d1
AD
156static const OptionDef *find_option(const OptionDef *po, const char *name)
157{
d70e5122
AK
158 const char *p = strchr(name, ':');
159 int len = p ? p - name : strlen(name);
160
8bbf6db9 161 while (po->name != NULL) {
d70e5122 162 if (!strncmp(name, po->name, len) && strlen(po->name) == len)
8bbf6db9
MN
163 break;
164 po++;
165 }
166 return po;
167}
168
15caccb9 169#if HAVE_COMMANDLINETOARGVW
ba9327ea 170#include <windows.h>
66a29797 171#include <shellapi.h>
b1ac139d
KG
172/* Will be leaked on exit */
173static char** win32_argv_utf8 = NULL;
174static int win32_argc = 0;
175
176/**
177 * Prepare command line arguments for executable.
178 * For Windows - perform wide-char to UTF-8 conversion.
179 * Input arguments should be main() function arguments.
180 * @param argc_ptr Arguments number (including executable)
181 * @param argv_ptr Arguments list.
182 */
183static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
184{
185 char *argstr_flat;
186 wchar_t **argv_w;
187 int i, buffsize = 0, offset = 0;
188
189 if (win32_argv_utf8) {
190 *argc_ptr = win32_argc;
191 *argv_ptr = win32_argv_utf8;
192 return;
193 }
194
195 win32_argc = 0;
196 argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
197 if (win32_argc <= 0 || !argv_w)
198 return;
199
200 /* determine the UTF-8 buffer size (including NULL-termination symbols) */
201 for (i = 0; i < win32_argc; i++)
202 buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
203 NULL, 0, NULL, NULL);
204
cbaef7d1
AD
205 win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
206 argstr_flat = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
b1ac139d
KG
207 if (win32_argv_utf8 == NULL) {
208 LocalFree(argv_w);
209 return;
210 }
211
212 for (i = 0; i < win32_argc; i++) {
213 win32_argv_utf8[i] = &argstr_flat[offset];
214 offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
215 &argstr_flat[offset],
216 buffsize - offset, NULL, NULL);
217 }
218 win32_argv_utf8[i] = NULL;
219 LocalFree(argv_w);
220
221 *argc_ptr = win32_argc;
222 *argv_ptr = win32_argv_utf8;
223}
224#else
225static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
226{
227 /* nothing to do */
228}
15caccb9 229#endif /* HAVE_COMMANDLINETOARGVW */
b1ac139d 230
a01c02bc
AK
231static int write_option(void *optctx, const OptionDef *po, const char *opt,
232 const char *arg)
2f8e586d 233{
2f8e586d
AK
234 /* new-style options contain an offset into optctx, old-style address of
235 * a global var*/
a01c02bc
AK
236 void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
237 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
238 int *dstcount;
6361c5e1
AK
239
240 if (po->flags & OPT_SPEC) {
241 SpecifierOpt **so = dst;
242 char *p = strchr(opt, ':');
243
cbaef7d1 244 dstcount = (int *)(so + 1);
6361c5e1
AK
245 *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
246 (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
247 dst = &(*so)[*dstcount - 1].u;
248 }
2f8e586d
AK
249
250 if (po->flags & OPT_STRING) {
251 char *str;
252 str = av_strdup(arg);
a1bcc76e 253 av_freep(dst);
cbaef7d1 254 *(char **)dst = str;
a01c02bc 255 } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
cbaef7d1 256 *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
2f8e586d 257 } else if (po->flags & OPT_INT64) {
cbaef7d1 258 *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
6b779ccc 259 } else if (po->flags & OPT_TIME) {
cbaef7d1 260 *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
2f8e586d 261 } else if (po->flags & OPT_FLOAT) {
cbaef7d1 262 *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
33f75d72 263 } else if (po->flags & OPT_DOUBLE) {
cbaef7d1 264 *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
2f8e586d 265 } else if (po->u.func_arg) {
11d957fb 266 int ret = po->u.func_arg(optctx, opt, arg);
2f8e586d 267 if (ret < 0) {
cbaef7d1
AD
268 av_log(NULL, AV_LOG_ERROR,
269 "Failed to set value '%s' for option '%s'\n", arg, opt);
2f8e586d
AK
270 return ret;
271 }
272 }
273 if (po->flags & OPT_EXIT)
5e3f9979 274 exit(0);
a01c02bc
AK
275
276 return 0;
277}
278
279int parse_option(void *optctx, const char *opt, const char *arg,
280 const OptionDef *options)
281{
282 const OptionDef *po;
283 int ret;
284
285 po = find_option(options, opt);
286 if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
287 /* handle 'no' bool option */
288 po = find_option(options, opt + 2);
289 if ((po->name && (po->flags & OPT_BOOL)))
290 arg = "0";
291 } else if (po->flags & OPT_BOOL)
292 arg = "1";
293
294 if (!po->name)
295 po = find_option(options, "default");
296 if (!po->name) {
297 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
298 return AVERROR(EINVAL);
299 }
300 if (po->flags & HAS_ARG && !arg) {
301 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
302 return AVERROR(EINVAL);
303 }
304
305 ret = write_option(optctx, po, opt, arg);
306 if (ret < 0)
307 return ret;
308
2f8e586d
AK
309 return !!(po->flags & HAS_ARG);
310}
311
7cc8d638 312void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
cbaef7d1 313 void (*parse_arg_function)(void *, const char*))
01310af2 314{
2f8e586d
AK
315 const char *opt;
316 int optindex, handleoptions = 1, ret;
01310af2 317
b1ac139d
KG
318 /* perform system-dependent conversions for arguments list */
319 prepare_app_arguments(&argc, &argv);
320
01310af2
FB
321 /* parse options */
322 optindex = 1;
323 while (optindex < argc) {
324 opt = argv[optindex++];
115329f1 325
84bf226b 326 if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
3749076c
SS
327 if (opt[1] == '-' && opt[2] == '\0') {
328 handleoptions = 0;
329 continue;
330 }
c3c78324 331 opt++;
2f8e586d
AK
332
333 if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
5e3f9979 334 exit(1);
2f8e586d 335 optindex += ret;
01310af2 336 } else {
60a9966e 337 if (parse_arg_function)
7cc8d638 338 parse_arg_function(optctx, opt);
01310af2
FB
339 }
340 }
341}
342
8c9af5b2
AK
343int parse_optgroup(void *optctx, OptionGroup *g)
344{
345 int i, ret;
346
347 av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
348 g->group_def->name, g->arg);
349
350 for (i = 0; i < g->nb_opts; i++) {
351 Option *o = &g->opts[i];
352
353 av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
354 o->key, o->opt->help, o->val);
355
356 ret = write_option(optctx, o->opt, o->key, o->val);
357 if (ret < 0)
358 return ret;
359 }
360
361 av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
362
363 return 0;
364}
365
4138cd29
AK
366int locate_option(int argc, char **argv, const OptionDef *options,
367 const char *optname)
182cbe43
AK
368{
369 const OptionDef *po;
370 int i;
371
372 for (i = 1; i < argc; i++) {
373 const char *cur_opt = argv[i];
374
375 if (*cur_opt++ != '-')
376 continue;
377
378 po = find_option(options, cur_opt);
379 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
380 po = find_option(options, cur_opt + 2);
381
382 if ((!po->name && !strcmp(cur_opt, optname)) ||
383 (po->name && !strcmp(optname, po->name)))
384 return i;
385
386 if (!po || po->flags & HAS_ARG)
387 i++;
388 }
389 return 0;
390}
391
392void parse_loglevel(int argc, char **argv, const OptionDef *options)
393{
394 int idx = locate_option(argc, argv, options, "loglevel");
8124d8ad
MR
395 if (!idx)
396 idx = locate_option(argc, argv, options, "v");
182cbe43 397 if (idx && argv[idx + 1])
11d957fb 398 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
182cbe43
AK
399}
400
145f741e 401#define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
11d957fb 402int opt_default(void *optctx, const char *opt, const char *arg)
9ba38229
AK
403{
404 const AVOption *o;
d4863fc1
AK
405 char opt_stripped[128];
406 const char *p;
ab799664
DB
407 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
408#if CONFIG_SWSCALE
409 const AVClass *sc = sws_get_class();
410#endif
d4863fc1
AK
411
412 if (!(p = strchr(opt, ':')))
413 p = opt + strlen(opt);
414 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
415
cbaef7d1
AD
416 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
417 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
418 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
419 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
8c8eab8b 420 av_dict_set(&codec_opts, opt, arg, FLAGS);
cbaef7d1
AD
421 else if ((o = av_opt_find(&fc, opt, NULL, 0,
422 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
9ba38229 423 av_dict_set(&format_opts, opt, arg, FLAGS);
ab799664 424#if CONFIG_SWSCALE
cbaef7d1
AD
425 else if ((o = av_opt_find(&sc, opt, NULL, 0,
426 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
9ba38229 427 // XXX we only support sws_flags, not arbitrary sws options
3b3ea346 428 int ret = av_opt_set(sws_opts, opt, arg, 0);
9ba38229
AK
429 if (ret < 0) {
430 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
431 return ret;
432 }
433 }
ab799664 434#endif
9ba38229 435
9ba38229
AK
436 if (o)
437 return 0;
9ba38229
AK
438 return AVERROR_OPTION_NOT_FOUND;
439}
440
8c9af5b2
AK
441/*
442 * Check whether given option is a group separator.
443 *
444 * @return index of the group definition that matched or -1 if none
445 */
c661cb66
AK
446static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
447 const char *opt)
8c9af5b2 448{
c661cb66 449 int i;
8c9af5b2 450
c661cb66
AK
451 for (i = 0; i < nb_groups; i++) {
452 const OptionGroupDef *p = &groups[i];
8c9af5b2 453 if (p->sep && !strcmp(p->sep, opt))
c661cb66 454 return i;
8c9af5b2
AK
455 }
456
457 return -1;
458}
459
460/*
461 * Finish parsing an option group.
462 *
463 * @param group_idx which group definition should this group belong to
464 * @param arg argument of the group delimiting option
465 */
466static void finish_group(OptionParseContext *octx, int group_idx,
467 const char *arg)
468{
469 OptionGroupList *l = &octx->groups[group_idx];
470 OptionGroup *g;
471
472 GROW_ARRAY(l->groups, l->nb_groups);
473 g = &l->groups[l->nb_groups - 1];
474
475 *g = octx->cur_group;
476 g->arg = arg;
477 g->group_def = l->group_def;
478#if CONFIG_SWSCALE
479 g->sws_opts = sws_opts;
480#endif
481 g->codec_opts = codec_opts;
482 g->format_opts = format_opts;
483
484 codec_opts = NULL;
485 format_opts = NULL;
486#if CONFIG_SWSCALE
487 sws_opts = NULL;
488#endif
489 init_opts();
490
491 memset(&octx->cur_group, 0, sizeof(octx->cur_group));
492}
493
494/*
495 * Add an option instance to currently parsed group.
496 */
497static void add_opt(OptionParseContext *octx, const OptionDef *opt,
498 const char *key, const char *val)
499{
500 int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
501 OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
502
503 GROW_ARRAY(g->opts, g->nb_opts);
504 g->opts[g->nb_opts - 1].opt = opt;
505 g->opts[g->nb_opts - 1].key = key;
506 g->opts[g->nb_opts - 1].val = val;
507}
508
509static void init_parse_context(OptionParseContext *octx,
c661cb66 510 const OptionGroupDef *groups, int nb_groups)
8c9af5b2
AK
511{
512 static const OptionGroupDef global_group = { "global" };
8c9af5b2
AK
513 int i;
514
515 memset(octx, 0, sizeof(*octx));
516
c661cb66 517 octx->nb_groups = nb_groups;
8c9af5b2
AK
518 octx->groups = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
519 if (!octx->groups)
520 exit(1);
521
522 for (i = 0; i < octx->nb_groups; i++)
523 octx->groups[i].group_def = &groups[i];
524
525 octx->global_opts.group_def = &global_group;
526 octx->global_opts.arg = "";
527
528 init_opts();
529}
530
531void uninit_parse_context(OptionParseContext *octx)
532{
533 int i, j;
534
535 for (i = 0; i < octx->nb_groups; i++) {
536 OptionGroupList *l = &octx->groups[i];
537
538 for (j = 0; j < l->nb_groups; j++) {
539 av_freep(&l->groups[j].opts);
540 av_dict_free(&l->groups[j].codec_opts);
541 av_dict_free(&l->groups[j].format_opts);
542#if CONFIG_SWSCALE
543 sws_freeContext(l->groups[j].sws_opts);
544#endif
545 }
546 av_freep(&l->groups);
547 }
548 av_freep(&octx->groups);
549
550 av_freep(&octx->cur_group.opts);
551 av_freep(&octx->global_opts.opts);
552
553 uninit_opts();
554}
555
556int split_commandline(OptionParseContext *octx, int argc, char *argv[],
557 const OptionDef *options,
c661cb66 558 const OptionGroupDef *groups, int nb_groups)
8c9af5b2
AK
559{
560 int optindex = 1;
561
562 /* perform system-dependent conversions for arguments list */
563 prepare_app_arguments(&argc, &argv);
564
c661cb66 565 init_parse_context(octx, groups, nb_groups);
8c9af5b2
AK
566 av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
567
568 while (optindex < argc) {
569 const char *opt = argv[optindex++], *arg;
570 const OptionDef *po;
571 int ret;
572
573 av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
574
575 /* unnamed group separators, e.g. output filename */
576 if (opt[0] != '-' || !opt[1]) {
577 finish_group(octx, 0, opt);
578 av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
579 continue;
580 }
581 opt++;
582
583#define GET_ARG(arg) \
584do { \
585 arg = argv[optindex++]; \
586 if (!arg) { \
587 av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
588 return AVERROR(EINVAL); \
589 } \
590} while (0)
591
592 /* named group separators, e.g. -i */
c661cb66 593 if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
8c9af5b2
AK
594 GET_ARG(arg);
595 finish_group(octx, ret, arg);
596 av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
597 groups[ret].name, arg);
598 continue;
599 }
600
601 /* normal options */
602 po = find_option(options, opt);
603 if (po->name) {
604 if (po->flags & OPT_EXIT) {
605 /* optional argument, e.g. -h */
606 arg = argv[optindex++];
607 } else if (po->flags & HAS_ARG) {
608 GET_ARG(arg);
609 } else {
610 arg = "1";
611 }
612
613 add_opt(octx, po, opt, arg);
614 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
615 "argument '%s'.\n", po->name, po->help, arg);
616 continue;
617 }
618
619 /* AVOptions */
620 if (argv[optindex]) {
621 ret = opt_default(NULL, opt, argv[optindex]);
622 if (ret >= 0) {
623 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
624 "argument '%s'.\n", opt, argv[optindex]);
625 optindex++;
626 continue;
627 } else if (ret != AVERROR_OPTION_NOT_FOUND) {
628 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
629 "with argument '%s'.\n", opt, argv[optindex]);
630 return ret;
631 }
632 }
633
634 /* boolean -nofoo options */
635 if (opt[0] == 'n' && opt[1] == 'o' &&
636 (po = find_option(options, opt + 2)) &&
637 po->name && po->flags & OPT_BOOL) {
638 add_opt(octx, po, opt, "0");
639 av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
640 "argument 0.\n", po->name, po->help);
641 continue;
642 }
643
644 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
645 return AVERROR_OPTION_NOT_FOUND;
646 }
647
648 if (octx->cur_group.nb_opts || codec_opts || format_opts)
649 av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
650 "commandline.\n");
651
652 av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
653
654 return 0;
655}
656
11d957fb 657int opt_loglevel(void *optctx, const char *opt, const char *arg)
4c97a6fa 658{
da4c2dab 659 const struct { const char *name; int level; } log_levels[] = {
4c97a6fa
SS
660 { "quiet" , AV_LOG_QUIET },
661 { "panic" , AV_LOG_PANIC },
662 { "fatal" , AV_LOG_FATAL },
663 { "error" , AV_LOG_ERROR },
664 { "warning", AV_LOG_WARNING },
665 { "info" , AV_LOG_INFO },
666 { "verbose", AV_LOG_VERBOSE },
667 { "debug" , AV_LOG_DEBUG },
668 };
669 char *tail;
670 int level;
671 int i;
672
673 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
674 if (!strcmp(log_levels[i].name, arg)) {
675 av_log_set_level(log_levels[i].level);
676 return 0;
677 }
678 }
679
680 level = strtol(arg, &tail, 10);
681 if (*tail) {
1c5e9551
AK
682 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
683 "Possible levels are numbers or:\n", arg);
4c97a6fa 684 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
1c5e9551 685 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
5e3f9979 686 exit(1);
4c97a6fa
SS
687 }
688 av_log_set_level(level);
689 return 0;
690}
691
11d957fb 692int opt_timelimit(void *optctx, const char *opt, const char *arg)
ffcc6e24 693{
0104b608 694#if HAVE_SETRLIMIT
ffcc6e24
MR
695 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
696 struct rlimit rl = { lim, lim + 1 };
697 if (setrlimit(RLIMIT_CPU, &rl))
698 perror("setrlimit");
699#else
1c5e9551 700 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
ffcc6e24
MR
701#endif
702 return 0;
703}
704
01310af2
FB
705void print_error(const char *filename, int err)
706{
7a5bdd79 707 char errbuf[128];
735ef67b 708 const char *errbuf_ptr = errbuf;
7a5bdd79 709
9e94bd3e
SS
710 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
711 errbuf_ptr = strerror(AVUNERROR(err));
1c5e9551 712 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
01310af2 713}
f35917b2 714
d101e731
SS
715static int warned_cfg = 0;
716
208749a0
SS
717#define INDENT 1
718#define SHOW_VERSION 2
d101e731 719#define SHOW_CONFIG 4
208749a0 720
1c5e9551 721#define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
5116571d 722 if (CONFIG_##LIBNAME) { \
65dd2ded 723 const char *indent = flags & INDENT? " " : ""; \
208749a0 724 if (flags & SHOW_VERSION) { \
b6525b4b 725 unsigned int version = libname##_version(); \
bcb82fe1
JR
726 av_log(NULL, level, \
727 "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
1c5e9551
AK
728 indent, #libname, \
729 LIB##LIBNAME##_VERSION_MAJOR, \
730 LIB##LIBNAME##_VERSION_MINOR, \
731 LIB##LIBNAME##_VERSION_MICRO, \
732 version >> 16, version >> 8 & 0xff, version & 0xff); \
208749a0 733 } \
d101e731
SS
734 if (flags & SHOW_CONFIG) { \
735 const char *cfg = libname##_configuration(); \
29ba0911 736 if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
d101e731 737 if (!warned_cfg) { \
1c5e9551 738 av_log(NULL, level, \
d101e731 739 "%sWARNING: library configuration mismatch\n", \
65dd2ded 740 indent); \
d101e731
SS
741 warned_cfg = 1; \
742 } \
1c5e9551 743 av_log(NULL, level, "%s%-11s configuration: %s\n", \
65dd2ded 744 indent, #libname, cfg); \
d101e731
SS
745 } \
746 } \
208749a0 747 } \
9a109272 748
1c5e9551 749static void print_all_libs_info(int flags, int level)
9a109272 750{
1c5e9551
AK
751 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
752 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
753 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
754 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
755 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
bcb82fe1 756 PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
1c5e9551 757 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
9a109272
SS
758}
759
ea9c581f 760void show_banner(void)
86074ed1 761{
cbaef7d1
AD
762 av_log(NULL, AV_LOG_INFO,
763 "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
1c5e9551 764 program_name, program_birth_year, this_year);
45870f8b
MR
765 av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
766 __DATE__, __TIME__, CC_IDENT);
1c5e9551
AK
767 av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
768 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
769 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
86074ed1
SS
770}
771
11d957fb 772int show_version(void *optctx, const char *opt, const char *arg)
f617135b 773{
1c5e9551 774 av_log_set_callback(log_callback_help);
a03be6e1 775 printf("%s " LIBAV_VERSION "\n", program_name);
1c5e9551 776 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
f617135b
AK
777
778 return 0;
86074ed1
SS
779}
780
11d957fb 781int show_license(void *optctx, const char *opt, const char *arg)
f35917b2 782{
7ead693b 783 printf(
3bf28f9d 784#if CONFIG_NONFREE
304ba23a
SS
785 "This version of %s has nonfree parts compiled in.\n"
786 "Therefore it is not legally redistributable.\n",
787 program_name
9cad0e4e
DB
788#elif CONFIG_GPLV3
789 "%s is free software; you can redistribute it and/or modify\n"
790 "it under the terms of the GNU General Public License as published by\n"
791 "the Free Software Foundation; either version 3 of the License, or\n"
792 "(at your option) any later version.\n"
793 "\n"
794 "%s is distributed in the hope that it will be useful,\n"
795 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
796 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
797 "GNU General Public License for more details.\n"
798 "\n"
799 "You should have received a copy of the GNU General Public License\n"
800 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
801 program_name, program_name, program_name
7ead693b 802#elif CONFIG_GPL
304ba23a 803 "%s is free software; you can redistribute it and/or modify\n"
f35917b2
SS
804 "it under the terms of the GNU General Public License as published by\n"
805 "the Free Software Foundation; either version 2 of the License, or\n"
806 "(at your option) any later version.\n"
807 "\n"
304ba23a 808 "%s is distributed in the hope that it will be useful,\n"
f35917b2
SS
809 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
810 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
811 "GNU General Public License for more details.\n"
812 "\n"
813 "You should have received a copy of the GNU General Public License\n"
304ba23a
SS
814 "along with %s; if not, write to the Free Software\n"
815 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
816 program_name, program_name, program_name
9cad0e4e
DB
817#elif CONFIG_LGPLV3
818 "%s is free software; you can redistribute it and/or modify\n"
819 "it under the terms of the GNU Lesser General Public License as published by\n"
820 "the Free Software Foundation; either version 3 of the License, or\n"
821 "(at your option) any later version.\n"
822 "\n"
823 "%s is distributed in the hope that it will be useful,\n"
824 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
825 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
826 "GNU Lesser General Public License for more details.\n"
827 "\n"
828 "You should have received a copy of the GNU Lesser General Public License\n"
829 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
830 program_name, program_name, program_name
f35917b2 831#else
304ba23a 832 "%s is free software; you can redistribute it and/or\n"
f35917b2
SS
833 "modify it under the terms of the GNU Lesser General Public\n"
834 "License as published by the Free Software Foundation; either\n"
835 "version 2.1 of the License, or (at your option) any later version.\n"
836 "\n"
304ba23a 837 "%s is distributed in the hope that it will be useful,\n"
f35917b2
SS
838 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
839 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
840 "Lesser General Public License for more details.\n"
841 "\n"
842 "You should have received a copy of the GNU Lesser General Public\n"
304ba23a
SS
843 "License along with %s; if not, write to the Free Software\n"
844 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
845 program_name, program_name, program_name
f35917b2 846#endif
3bf28f9d 847 );
f617135b
AK
848
849 return 0;
f35917b2 850}
ba9880c1 851
11d957fb 852int show_formats(void *optctx, const char *opt, const char *arg)
ba9880c1 853{
cbaef7d1
AD
854 AVInputFormat *ifmt = NULL;
855 AVOutputFormat *ofmt = NULL;
ba9880c1
SS
856 const char *last_name;
857
cbaef7d1
AD
858 printf("File formats:\n"
859 " D. = Demuxing supported\n"
860 " .E = Muxing supported\n"
861 " --\n");
862 last_name = "000";
863 for (;;) {
864 int decode = 0;
865 int encode = 0;
866 const char *name = NULL;
867 const char *long_name = NULL;
868
869 while ((ofmt = av_oformat_next(ofmt))) {
870 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
871 strcmp(ofmt->name, last_name) > 0) {
872 name = ofmt->name;
873 long_name = ofmt->long_name;
874 encode = 1;
ba9880c1
SS
875 }
876 }
cbaef7d1
AD
877 while ((ifmt = av_iformat_next(ifmt))) {
878 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
879 strcmp(ifmt->name, last_name) > 0) {
880 name = ifmt->name;
881 long_name = ifmt->long_name;
882 encode = 0;
ba9880c1 883 }
cbaef7d1
AD
884 if (name && strcmp(ifmt->name, name) == 0)
885 decode = 1;
ba9880c1 886 }
cbaef7d1 887 if (name == NULL)
ba9880c1 888 break;
cbaef7d1 889 last_name = name;
ba9880c1 890
cbaef7d1
AD
891 printf(" %s%s %-15s %s\n",
892 decode ? "D" : " ",
893 encode ? "E" : " ",
894 name,
ba9880c1
SS
895 long_name ? long_name:" ");
896 }
f617135b 897 return 0;
8447f0bd 898}
ba9880c1 899
a3ad68d3
AK
900#define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
901 if (codec->field) { \
902 const type *p = c->field; \
903 \
904 printf(" Supported " list_name ":"); \
905 while (*p != term) { \
906 get_name(*p); \
907 printf(" %s", name); \
908 p++; \
909 } \
910 printf("\n"); \
911 } \
912
913static void print_codec(const AVCodec *c)
914{
915 int encoder = av_codec_is_encoder(c);
916
917 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
918 c->long_name ? c->long_name : "");
919
920 if (c->type == AVMEDIA_TYPE_VIDEO) {
921 printf(" Threading capabilities: ");
922 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
923 CODEC_CAP_SLICE_THREADS)) {
924 case CODEC_CAP_FRAME_THREADS |
925 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
926 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
927 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
928 default: printf("no"); break;
929 }
930 printf("\n");
931 }
932
933 if (c->supported_framerates) {
934 const AVRational *fps = c->supported_framerates;
935
936 printf(" Supported framerates:");
937 while (fps->num) {
938 printf(" %d/%d", fps->num, fps->den);
939 fps++;
940 }
941 printf("\n");
942 }
716d413c
AK
943 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
944 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
a3ad68d3
AK
945 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
946 GET_SAMPLE_RATE_NAME);
947 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
948 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
949 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
950 0, GET_CH_LAYOUT_DESC);
951
952 if (c->priv_class) {
953 show_help_children(c->priv_class,
954 AV_OPT_FLAG_ENCODING_PARAM |
955 AV_OPT_FLAG_DECODING_PARAM);
956 }
957}
958
7c101949
AK
959static char get_media_type_char(enum AVMediaType type)
960{
961 switch (type) {
962 case AVMEDIA_TYPE_VIDEO: return 'V';
963 case AVMEDIA_TYPE_AUDIO: return 'A';
964 case AVMEDIA_TYPE_SUBTITLE: return 'S';
965 default: return '?';
966 }
967}
968
969static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
970 int encoder)
971{
972 while ((prev = av_codec_next(prev))) {
973 if (prev->id == id &&
974 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
975 return prev;
976 }
977 return NULL;
978}
979
980static void print_codecs_for_id(enum AVCodecID id, int encoder)
981{
982 const AVCodec *codec = NULL;
983
984 printf(" (%s: ", encoder ? "encoders" : "decoders");
985
986 while ((codec = next_codec_for_id(id, codec, encoder)))
987 printf("%s ", codec->name);
988
989 printf(")");
990}
991
11d957fb 992int show_codecs(void *optctx, const char *opt, const char *arg)
8447f0bd 993{
7c101949
AK
994 const AVCodecDescriptor *desc = NULL;
995
cbaef7d1 996 printf("Codecs:\n"
e2785fa7
AK
997 " D..... = Decoding supported\n"
998 " .E.... = Encoding supported\n"
999 " ..V... = Video codec\n"
1000 " ..A... = Audio codec\n"
1001 " ..S... = Subtitle codec\n"
1002 " ...I.. = Intra frame-only codec\n"
1003 " ....L. = Lossy compression\n"
1004 " .....S = Lossless compression\n"
1005 " -------\n");
7c101949
AK
1006 while ((desc = avcodec_descriptor_next(desc))) {
1007 const AVCodec *codec = NULL;
1008
1009 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1010 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1011
1012 printf("%c", get_media_type_char(desc->type));
1013 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
e2785fa7
AK
1014 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
1015 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
7c101949
AK
1016
1017 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1018
1019 /* print decoders/encoders when there's more than one or their
1020 * names are different from codec name */
1021 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1022 if (strcmp(codec->name, desc->name)) {
1023 print_codecs_for_id(desc->id, 0);
1024 break;
ba9880c1 1025 }
7c101949
AK
1026 }
1027 codec = NULL;
1028 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1029 if (strcmp(codec->name, desc->name)) {
1030 print_codecs_for_id(desc->id, 1);
1031 break;
ba9880c1
SS
1032 }
1033 }
ba9880c1 1034
ba9880c1
SS
1035 printf("\n");
1036 }
f617135b 1037 return 0;
7c101949
AK
1038}
1039
1040static void print_codecs(int encoder)
1041{
1042 const AVCodecDescriptor *desc = NULL;
1043
1044 printf("%s:\n"
1045 " V... = Video\n"
1046 " A... = Audio\n"
1047 " S... = Subtitle\n"
1048 " .F.. = Frame-level multithreading\n"
1049 " ..S. = Slice-level multithreading\n"
1050 " ...X = Codec is experimental\n"
1051 " ---\n",
1052 encoder ? "Encoders" : "Decoders");
1053 while ((desc = avcodec_descriptor_next(desc))) {
1054 const AVCodec *codec = NULL;
1055
1056 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1057 printf("%c", get_media_type_char(desc->type));
1058 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1059 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1060 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
1061
1062 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1063 if (strcmp(codec->name, desc->name))
1064 printf(" (codec %s)", desc->name);
1065
1066 printf("\n");
1067 }
1068 }
1069}
1070
11d957fb 1071int show_decoders(void *optctx, const char *opt, const char *arg)
7c101949
AK
1072{
1073 print_codecs(0);
1074 return 0;
1075}
1076
11d957fb 1077int show_encoders(void *optctx, const char *opt, const char *arg)
7c101949
AK
1078{
1079 print_codecs(1);
1080 return 0;
8447f0bd
MN
1081}
1082
11d957fb 1083int show_bsfs(void *optctx, const char *opt, const char *arg)
8447f0bd 1084{
cbaef7d1 1085 AVBitStreamFilter *bsf = NULL;
ba9880c1
SS
1086
1087 printf("Bitstream filters:\n");
cbaef7d1 1088 while ((bsf = av_bitstream_filter_next(bsf)))
2091b27b 1089 printf("%s\n", bsf->name);
ba9880c1 1090 printf("\n");
f617135b 1091 return 0;
8447f0bd
MN
1092}
1093
11d957fb 1094int show_protocols(void *optctx, const char *opt, const char *arg)
8447f0bd 1095{
cdc6a87f
AK
1096 void *opaque = NULL;
1097 const char *name;
ba9880c1 1098
2ee5c789 1099 printf("Supported file protocols:\n"
cdc6a87f
AK
1100 "Input:\n");
1101 while ((name = avio_enum_protocols(&opaque, 0)))
1102 printf("%s\n", name);
1103 printf("Output:\n");
1104 while ((name = avio_enum_protocols(&opaque, 1)))
1105 printf("%s\n", name);
f617135b 1106 return 0;
ba9880c1 1107}
090b61b2 1108
11d957fb 1109int show_filters(void *optctx, const char *opt, const char *arg)
62d75662 1110{
78638628 1111 AVFilter av_unused(**filter) = NULL;
62d75662
SS
1112
1113 printf("Filters:\n");
663c2edf 1114#if CONFIG_AVFILTER
62d75662
SS
1115 while ((filter = av_filter_next(filter)) && *filter)
1116 printf("%-16s %s\n", (*filter)->name, (*filter)->description);
663c2edf 1117#endif
f617135b 1118 return 0;
62d75662
SS
1119}
1120
11d957fb 1121int show_pix_fmts(void *optctx, const char *opt, const char *arg)
3f7bb426 1122{
b7f1010c 1123 const AVPixFmtDescriptor *pix_desc = NULL;
9cb5c760 1124
cbaef7d1
AD
1125 printf("Pixel formats:\n"
1126 "I.... = Supported Input format for conversion\n"
1127 ".O... = Supported Output format for conversion\n"
1128 "..H.. = Hardware accelerated format\n"
1129 "...P. = Paletted format\n"
1130 "....B = Bitstream format\n"
1131 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
1132 "-----\n");
9cb5c760 1133
e24db3e3
MR
1134#if !CONFIG_SWSCALE
1135# define sws_isSupportedInput(x) 0
1136# define sws_isSupportedOutput(x) 0
1137#endif
1138
b7f1010c
AK
1139 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1140 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
9cb5c760
SS
1141 printf("%c%c%c%c%c %-16s %d %2d\n",
1142 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
1143 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
1144 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
1145 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
1146 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1147 pix_desc->name,
1148 pix_desc->nb_components,
1149 av_get_bits_per_pixel(pix_desc));
1150 }
f617135b 1151 return 0;
3f7bb426
SS
1152}
1153
11d957fb 1154int show_sample_fmts(void *optctx, const char *opt, const char *arg)
05bffc12
AK
1155{
1156 int i;
1157 char fmt_str[128];
1158 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1159 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1160 return 0;
1161}
1162
a3ad68d3
AK
1163static void show_help_codec(const char *name, int encoder)
1164{
1165 const AVCodecDescriptor *desc;
1166 const AVCodec *codec;
1167
1168 if (!name) {
1169 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1170 return;
1171 }
1172
1173 codec = encoder ? avcodec_find_encoder_by_name(name) :
1174 avcodec_find_decoder_by_name(name);
1175
1176 if (codec)
1177 print_codec(codec);
1178 else if ((desc = avcodec_descriptor_get_by_name(name))) {
1179 int printed = 0;
1180
1181 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1182 printed = 1;
1183 print_codec(codec);
1184 }
1185
1186 if (!printed) {
1187 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
1188 "but no %s for it are available. Libav might need to be "
1189 "recompiled with additional external libraries.\n",
1190 name, encoder ? "encoders" : "decoders");
1191 }
1192 } else {
1193 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
1194 name);
1195 }
1196}
1197
1136bd36
AK
1198static void show_help_demuxer(const char *name)
1199{
1200 const AVInputFormat *fmt = av_find_input_format(name);
1201
1202 if (!fmt) {
1203 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1204 return;
1205 }
1206
1207 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1208
1209 if (fmt->extensions)
1210 printf(" Common extensions: %s.\n", fmt->extensions);
1211
1212 if (fmt->priv_class)
1213 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1214}
1215
1216static void show_help_muxer(const char *name)
1217{
1218 const AVCodecDescriptor *desc;
1219 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1220
1221 if (!fmt) {
1222 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1223 return;
1224 }
1225
1226 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1227
1228 if (fmt->extensions)
1229 printf(" Common extensions: %s.\n", fmt->extensions);
1230 if (fmt->mime_type)
1231 printf(" Mime type: %s.\n", fmt->mime_type);
1232 if (fmt->video_codec != AV_CODEC_ID_NONE &&
1233 (desc = avcodec_descriptor_get(fmt->video_codec))) {
1234 printf(" Default video codec: %s.\n", desc->name);
1235 }
1236 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1237 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1238 printf(" Default audio codec: %s.\n", desc->name);
1239 }
1240 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1241 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1242 printf(" Default subtitle codec: %s.\n", desc->name);
1243 }
1244
1245 if (fmt->priv_class)
1246 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1247}
1248
11d957fb 1249int show_help(void *optctx, const char *opt, const char *arg)
a3ad68d3
AK
1250{
1251 char *topic, *par;
1252 av_log_set_callback(log_callback_help);
1253
1254 topic = av_strdup(arg ? arg : "");
1255 par = strchr(topic, '=');
1256 if (par)
1257 *par++ = 0;
1258
1259 if (!*topic) {
1260 show_help_default(topic, par);
1261 } else if (!strcmp(topic, "decoder")) {
1262 show_help_codec(par, 0);
1263 } else if (!strcmp(topic, "encoder")) {
1264 show_help_codec(par, 1);
1136bd36
AK
1265 } else if (!strcmp(topic, "demuxer")) {
1266 show_help_demuxer(par);
1267 } else if (!strcmp(topic, "muxer")) {
1268 show_help_muxer(par);
a3ad68d3
AK
1269 } else {
1270 show_help_default(topic, par);
1271 }
1272
1273 av_freep(&topic);
1274 return 0;
1275}
1276
090b61b2
SS
1277int read_yesno(void)
1278{
1279 int c = getchar();
1280 int yesno = (toupper(c) == 'Y');
1281
1282 while (c != '\n' && c != EOF)
1283 c = getchar();
1284
1285 return yesno;
1286}
458b062d 1287
02170990 1288int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
458b062d 1289{
d94c577d 1290 int ret;
c56e9e05 1291 FILE *f = fopen(filename, "rb");
458b062d
SS
1292
1293 if (!f) {
cbaef7d1
AD
1294 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1295 strerror(errno));
458b062d
SS
1296 return AVERROR(errno);
1297 }
1298 fseek(f, 0, SEEK_END);
1299 *size = ftell(f);
1300 fseek(f, 0, SEEK_SET);
1301 *bufptr = av_malloc(*size + 1);
1302 if (!*bufptr) {
1c5e9551 1303 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
458b062d
SS
1304 fclose(f);
1305 return AVERROR(ENOMEM);
1306 }
d94c577d
JG
1307 ret = fread(*bufptr, 1, *size, f);
1308 if (ret < *size) {
1309 av_free(*bufptr);
1310 if (ferror(f)) {
1311 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1312 filename, strerror(errno));
1313 ret = AVERROR(errno);
1314 } else
1315 ret = AVERROR_EOF;
1316 } else {
1317 ret = 0;
b94e4acb 1318 (*bufptr)[(*size)++] = '\0';
d94c577d 1319 }
458b062d
SS
1320
1321 fclose(f);
d94c577d 1322 return ret;
458b062d 1323}
7a8bfa5d
AS
1324
1325void init_pts_correction(PtsCorrectionContext *ctx)
1326{
1327 ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1328 ctx->last_pts = ctx->last_dts = INT64_MIN;
1329}
1330
cbaef7d1
AD
1331int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1332 int64_t dts)
7a8bfa5d
AS
1333{
1334 int64_t pts = AV_NOPTS_VALUE;
1335
1336 if (dts != AV_NOPTS_VALUE) {
1337 ctx->num_faulty_dts += dts <= ctx->last_dts;
1338 ctx->last_dts = dts;
1339 }
1340 if (reordered_pts != AV_NOPTS_VALUE) {
1341 ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1342 ctx->last_pts = reordered_pts;
1343 }
01d46198 1344 if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
cbaef7d1 1345 && reordered_pts != AV_NOPTS_VALUE)
7a8bfa5d
AS
1346 pts = reordered_pts;
1347 else
1348 pts = dts;
1349
1350 return pts;
1351}
f7ead94c 1352
6e872935 1353FILE *get_preset_file(char *filename, size_t filename_size,
cbaef7d1
AD
1354 const char *preset_name, int is_path,
1355 const char *codec_name)
6e872935
SS
1356{
1357 FILE *f = NULL;
1358 int i;
cbaef7d1
AD
1359 const char *base[3] = { getenv("AVCONV_DATADIR"),
1360 getenv("HOME"),
1361 AVCONV_DATADIR, };
6e872935
SS
1362
1363 if (is_path) {
1364 av_strlcpy(filename, preset_name, filename_size);
1365 f = fopen(filename, "r");
1366 } else {
1367 for (i = 0; i < 3 && !f; i++) {
1368 if (!base[i])
1369 continue;
050dc127 1370 snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
cbaef7d1 1371 i != 1 ? "" : "/.avconv", preset_name);
6e872935
SS
1372 f = fopen(filename, "r");
1373 if (!f && codec_name) {
1374 snprintf(filename, filename_size,
050dc127 1375 "%s%s/%s-%s.avpreset",
cbaef7d1
AD
1376 base[i], i != 1 ? "" : "/.avconv", codec_name,
1377 preset_name);
6e872935
SS
1378 f = fopen(filename, "r");
1379 }
1380 }
1381 }
1382
1383 return f;
1384}
1385
d4863fc1
AK
1386int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1387{
cbaef7d1 1388 if (*spec <= '9' && *spec >= '0') /* opt:index */
d4863fc1 1389 return strtol(spec, NULL, 0) == st->index;
cbaef7d1
AD
1390 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1391 *spec == 't') { /* opt:[vasdt] */
d4863fc1
AK
1392 enum AVMediaType type;
1393
1394 switch (*spec++) {
cbaef7d1
AD
1395 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
1396 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
1397 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1398 case 'd': type = AVMEDIA_TYPE_DATA; break;
3ccd1580 1399 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
7cf78b34 1400 default: av_assert0(0);
d4863fc1
AK
1401 }
1402 if (type != st->codec->codec_type)
1403 return 0;
cbaef7d1 1404 if (*spec++ == ':') { /* possibly followed by :index */
d4863fc1
AK
1405 int i, index = strtol(spec, NULL, 0);
1406 for (i = 0; i < s->nb_streams; i++)
1407 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1408 return i == st->index;
1409 return 0;
1410 }
1411 return 1;
2c474ddb
AK
1412 } else if (*spec == 'p' && *(spec + 1) == ':') {
1413 int prog_id, i, j;
1414 char *endptr;
1415 spec += 2;
1416 prog_id = strtol(spec, &endptr, 0);
1417 for (i = 0; i < s->nb_programs; i++) {
1418 if (s->programs[i]->id != prog_id)
1419 continue;
1420
1421 if (*endptr++ == ':') {
1422 int stream_idx = strtol(endptr, NULL, 0);
d4b63054
DB
1423 return stream_idx >= 0 &&
1424 stream_idx < s->programs[i]->nb_stream_indexes &&
1425 st->index == s->programs[i]->stream_index[stream_idx];
2c474ddb
AK
1426 }
1427
1428 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1429 if (st->index == s->programs[i]->stream_index[j])
1430 return 1;
1431 }
1432 return 0;
d4863fc1
AK
1433 } else if (!*spec) /* empty specifier, matches everything */
1434 return 1;
1435
1436 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1437 return AVERROR(EINVAL);
1438}
1439
36ef5369 1440AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
d3ed1c95 1441 AVFormatContext *s, AVStream *st, AVCodec *codec)
8c8eab8b
AK
1442{
1443 AVDictionary *ret = NULL;
1444 AVDictionaryEntry *t = NULL;
cbaef7d1
AD
1445 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1446 : AV_OPT_FLAG_DECODING_PARAM;
8c8eab8b 1447 char prefix = 0;
20c21f8b 1448 const AVClass *cc = avcodec_get_class();
8c8eab8b
AK
1449
1450 if (!codec)
d3ed1c95
MS
1451 codec = s->oformat ? avcodec_find_encoder(codec_id)
1452 : avcodec_find_decoder(codec_id);
1453 if (!codec)
8c8eab8b
AK
1454 return NULL;
1455
1456 switch (codec->type) {
cbaef7d1
AD
1457 case AVMEDIA_TYPE_VIDEO:
1458 prefix = 'v';
1459 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1460 break;
1461 case AVMEDIA_TYPE_AUDIO:
1462 prefix = 'a';
1463 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1464 break;
1465 case AVMEDIA_TYPE_SUBTITLE:
1466 prefix = 's';
1467 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1468 break;
8c8eab8b
AK
1469 }
1470
1471 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
d4863fc1
AK
1472 char *p = strchr(t->key, ':');
1473
1474 /* check stream specification in opt name */
1475 if (p)
1476 switch (check_stream_specifier(s, st, p + 1)) {
1477 case 1: *p = 0; break;
1478 case 0: continue;
1479 default: return NULL;
1480 }
1481
20c21f8b 1482 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
cbaef7d1
AD
1483 (codec && codec->priv_class &&
1484 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1485 AV_OPT_SEARCH_FAKE_OBJ)))
8c8eab8b 1486 av_dict_set(&ret, t->key, t->value, 0);
cbaef7d1
AD
1487 else if (t->key[0] == prefix &&
1488 av_opt_find(&cc, t->key + 1, NULL, flags,
1489 AV_OPT_SEARCH_FAKE_OBJ))
1490 av_dict_set(&ret, t->key + 1, t->value, 0);
d4863fc1
AK
1491
1492 if (p)
1493 *p = ':';
8c8eab8b
AK
1494 }
1495 return ret;
1496}
1497
cbaef7d1
AD
1498AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1499 AVDictionary *codec_opts)
3009f521
AK
1500{
1501 int i;
1502 AVDictionary **opts;
1503
1504 if (!s->nb_streams)
1505 return NULL;
1506 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1507 if (!opts) {
cbaef7d1
AD
1508 av_log(NULL, AV_LOG_ERROR,
1509 "Could not alloc memory for stream options.\n");
3009f521
AK
1510 return NULL;
1511 }
1512 for (i = 0; i < s->nb_streams; i++)
cbaef7d1 1513 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
d3ed1c95 1514 s, s->streams[i], NULL);
3009f521
AK
1515 return opts;
1516}
1517
cac651c8
AK
1518void *grow_array(void *array, int elem_size, int *size, int new_size)
1519{
1520 if (new_size >= INT_MAX / elem_size) {
1521 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
5e3f9979 1522 exit(1);
cac651c8
AK
1523 }
1524 if (*size < new_size) {
1525 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1526 if (!tmp) {
1527 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
5e3f9979 1528 exit(1);
cac651c8
AK
1529 }
1530 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1531 *size = new_size;
1532 return tmp;
1533 }
1534 return array;
1535}
d55c2e05
AK
1536
1537static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1538{
b7f1010c
AK
1539 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1540 FrameBuffer *buf;
d55c2e05 1541 int i, ret;
b7f1010c 1542 int pixel_size;
d55c2e05
AK
1543 int h_chroma_shift, v_chroma_shift;
1544 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1545 int w = s->width, h = s->height;
1546
b7f1010c
AK
1547 if (!desc)
1548 return AVERROR(EINVAL);
1549 pixel_size = desc->comp[0].step_minus1 + 1;
1550
1551 buf = av_mallocz(sizeof(*buf));
d55c2e05
AK
1552 if (!buf)
1553 return AVERROR(ENOMEM);
1554
1555 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1556 w += 2*edge;
1557 h += 2*edge;
1558 }
1559
1560 avcodec_align_dimensions(s, &w, &h);
1561 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1562 s->pix_fmt, 32)) < 0) {
1563 av_freep(&buf);
1564 return ret;
1565 }
1566 /* XXX this shouldn't be needed, but some tests break without this line
1567 * those decoders are buggy and need to be fixed.
1568 * the following tests fail:
1569 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1570 */
1571 memset(buf->base[0], 128, ret);
1572
c1a02e88
LB
1573 av_pix_fmt_get_chroma_sub_sample(s->pix_fmt,
1574 &h_chroma_shift, &v_chroma_shift);
1575
d55c2e05
AK
1576 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1577 const int h_shift = i==0 ? 0 : h_chroma_shift;
1578 const int v_shift = i==0 ? 0 : v_chroma_shift;
1579 if (s->flags & CODEC_FLAG_EMU_EDGE)
1580 buf->data[i] = buf->base[i];
990450c5 1581 else if (buf->base[i])
d55c2e05
AK
1582 buf->data[i] = buf->base[i] +
1583 FFALIGN((buf->linesize[i]*edge >> v_shift) +
1584 (pixel_size*edge >> h_shift), 32);
1585 }
1586 buf->w = s->width;
1587 buf->h = s->height;
1588 buf->pix_fmt = s->pix_fmt;
1589 buf->pool = pool;
1590
1591 *pbuf = buf;
1592 return 0;
1593}
1594
1595int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1596{
1597 FrameBuffer **pool = s->opaque;
1598 FrameBuffer *buf;
1599 int ret, i;
1600
1601 if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1602 return ret;
1603
1604 buf = *pool;
1605 *pool = buf->next;
1606 buf->next = NULL;
1607 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1608 av_freep(&buf->base[0]);
1609 av_free(buf);
1610 if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1611 return ret;
1612 }
1613 buf->refcount++;
1614
1615 frame->opaque = buf;
1616 frame->type = FF_BUFFER_TYPE_USER;
1617 frame->extended_data = frame->data;
d55c2e05
AK
1618
1619 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1620 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
1621 frame->data[i] = buf->data[i];
1622 frame->linesize[i] = buf->linesize[i];
1623 }
1624
1625 return 0;
1626}
1627
1628static void unref_buffer(FrameBuffer *buf)
1629{
1630 FrameBuffer **pool = buf->pool;
1631
1632 av_assert0(buf->refcount);
1633 buf->refcount--;
1634 if (!buf->refcount) {
1635 buf->next = *pool;
1636 *pool = buf;
1637 }
1638}
1639
1640void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1641{
1642 FrameBuffer *buf = frame->opaque;
1643 int i;
1644
1645 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1646 frame->data[i] = NULL;
1647
1648 unref_buffer(buf);
1649}
1650
1651void filter_release_buffer(AVFilterBuffer *fb)
1652{
1653 FrameBuffer *buf = fb->priv;
1654 av_free(fb);
1655 unref_buffer(buf);
1656}
1657
1658void free_buffer_pool(FrameBuffer **pool)
1659{
1660 FrameBuffer *buf = *pool;
1661 while (buf) {
1662 *pool = buf->next;
1663 av_freep(&buf->base[0]);
1664 av_free(buf);
1665 buf = *pool;
1666 }
1667}