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