cmdutils: split parse_option().
[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
4138cd29
AK
343int locate_option(int argc, char **argv, const OptionDef *options,
344 const char *optname)
182cbe43
AK
345{
346 const OptionDef *po;
347 int i;
348
349 for (i = 1; i < argc; i++) {
350 const char *cur_opt = argv[i];
351
352 if (*cur_opt++ != '-')
353 continue;
354
355 po = find_option(options, cur_opt);
356 if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
357 po = find_option(options, cur_opt + 2);
358
359 if ((!po->name && !strcmp(cur_opt, optname)) ||
360 (po->name && !strcmp(optname, po->name)))
361 return i;
362
363 if (!po || po->flags & HAS_ARG)
364 i++;
365 }
366 return 0;
367}
368
369void parse_loglevel(int argc, char **argv, const OptionDef *options)
370{
371 int idx = locate_option(argc, argv, options, "loglevel");
8124d8ad
MR
372 if (!idx)
373 idx = locate_option(argc, argv, options, "v");
182cbe43 374 if (idx && argv[idx + 1])
11d957fb 375 opt_loglevel(NULL, "loglevel", argv[idx + 1]);
182cbe43
AK
376}
377
145f741e 378#define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
11d957fb 379int opt_default(void *optctx, const char *opt, const char *arg)
9ba38229
AK
380{
381 const AVOption *o;
d4863fc1
AK
382 char opt_stripped[128];
383 const char *p;
ab799664
DB
384 const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
385#if CONFIG_SWSCALE
386 const AVClass *sc = sws_get_class();
387#endif
d4863fc1
AK
388
389 if (!(p = strchr(opt, ':')))
390 p = opt + strlen(opt);
391 av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
392
cbaef7d1
AD
393 if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
394 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
395 ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
396 (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
8c8eab8b 397 av_dict_set(&codec_opts, opt, arg, FLAGS);
cbaef7d1
AD
398 else if ((o = av_opt_find(&fc, opt, NULL, 0,
399 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
9ba38229 400 av_dict_set(&format_opts, opt, arg, FLAGS);
ab799664 401#if CONFIG_SWSCALE
cbaef7d1
AD
402 else if ((o = av_opt_find(&sc, opt, NULL, 0,
403 AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
9ba38229 404 // XXX we only support sws_flags, not arbitrary sws options
3b3ea346 405 int ret = av_opt_set(sws_opts, opt, arg, 0);
9ba38229
AK
406 if (ret < 0) {
407 av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
408 return ret;
409 }
410 }
ab799664 411#endif
9ba38229 412
9ba38229
AK
413 if (o)
414 return 0;
1c5e9551 415 av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
9ba38229
AK
416 return AVERROR_OPTION_NOT_FOUND;
417}
418
11d957fb 419int opt_loglevel(void *optctx, const char *opt, const char *arg)
4c97a6fa 420{
da4c2dab 421 const struct { const char *name; int level; } log_levels[] = {
4c97a6fa
SS
422 { "quiet" , AV_LOG_QUIET },
423 { "panic" , AV_LOG_PANIC },
424 { "fatal" , AV_LOG_FATAL },
425 { "error" , AV_LOG_ERROR },
426 { "warning", AV_LOG_WARNING },
427 { "info" , AV_LOG_INFO },
428 { "verbose", AV_LOG_VERBOSE },
429 { "debug" , AV_LOG_DEBUG },
430 };
431 char *tail;
432 int level;
433 int i;
434
435 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
436 if (!strcmp(log_levels[i].name, arg)) {
437 av_log_set_level(log_levels[i].level);
438 return 0;
439 }
440 }
441
442 level = strtol(arg, &tail, 10);
443 if (*tail) {
1c5e9551
AK
444 av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
445 "Possible levels are numbers or:\n", arg);
4c97a6fa 446 for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
1c5e9551 447 av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
5e3f9979 448 exit(1);
4c97a6fa
SS
449 }
450 av_log_set_level(level);
451 return 0;
452}
453
11d957fb 454int opt_timelimit(void *optctx, const char *opt, const char *arg)
ffcc6e24 455{
0104b608 456#if HAVE_SETRLIMIT
ffcc6e24
MR
457 int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
458 struct rlimit rl = { lim, lim + 1 };
459 if (setrlimit(RLIMIT_CPU, &rl))
460 perror("setrlimit");
461#else
1c5e9551 462 av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
ffcc6e24
MR
463#endif
464 return 0;
465}
466
01310af2
FB
467void print_error(const char *filename, int err)
468{
7a5bdd79 469 char errbuf[128];
735ef67b 470 const char *errbuf_ptr = errbuf;
7a5bdd79 471
9e94bd3e
SS
472 if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
473 errbuf_ptr = strerror(AVUNERROR(err));
1c5e9551 474 av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
01310af2 475}
f35917b2 476
d101e731
SS
477static int warned_cfg = 0;
478
208749a0
SS
479#define INDENT 1
480#define SHOW_VERSION 2
d101e731 481#define SHOW_CONFIG 4
208749a0 482
1c5e9551 483#define PRINT_LIB_INFO(libname, LIBNAME, flags, level) \
5116571d 484 if (CONFIG_##LIBNAME) { \
65dd2ded 485 const char *indent = flags & INDENT? " " : ""; \
208749a0 486 if (flags & SHOW_VERSION) { \
b6525b4b 487 unsigned int version = libname##_version(); \
bcb82fe1
JR
488 av_log(NULL, level, \
489 "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n", \
1c5e9551
AK
490 indent, #libname, \
491 LIB##LIBNAME##_VERSION_MAJOR, \
492 LIB##LIBNAME##_VERSION_MINOR, \
493 LIB##LIBNAME##_VERSION_MICRO, \
494 version >> 16, version >> 8 & 0xff, version & 0xff); \
208749a0 495 } \
d101e731
SS
496 if (flags & SHOW_CONFIG) { \
497 const char *cfg = libname##_configuration(); \
29ba0911 498 if (strcmp(LIBAV_CONFIGURATION, cfg)) { \
d101e731 499 if (!warned_cfg) { \
1c5e9551 500 av_log(NULL, level, \
d101e731 501 "%sWARNING: library configuration mismatch\n", \
65dd2ded 502 indent); \
d101e731
SS
503 warned_cfg = 1; \
504 } \
1c5e9551 505 av_log(NULL, level, "%s%-11s configuration: %s\n", \
65dd2ded 506 indent, #libname, cfg); \
d101e731
SS
507 } \
508 } \
208749a0 509 } \
9a109272 510
1c5e9551 511static void print_all_libs_info(int flags, int level)
9a109272 512{
1c5e9551
AK
513 PRINT_LIB_INFO(avutil, AVUTIL, flags, level);
514 PRINT_LIB_INFO(avcodec, AVCODEC, flags, level);
515 PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
516 PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
517 PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
bcb82fe1 518 PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
1c5e9551 519 PRINT_LIB_INFO(swscale, SWSCALE, flags, level);
9a109272
SS
520}
521
ea9c581f 522void show_banner(void)
86074ed1 523{
cbaef7d1
AD
524 av_log(NULL, AV_LOG_INFO,
525 "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
1c5e9551 526 program_name, program_birth_year, this_year);
45870f8b
MR
527 av_log(NULL, AV_LOG_INFO, " built on %s %s with %s\n",
528 __DATE__, __TIME__, CC_IDENT);
1c5e9551
AK
529 av_log(NULL, AV_LOG_VERBOSE, " configuration: " LIBAV_CONFIGURATION "\n");
530 print_all_libs_info(INDENT|SHOW_CONFIG, AV_LOG_VERBOSE);
531 print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
86074ed1
SS
532}
533
11d957fb 534int show_version(void *optctx, const char *opt, const char *arg)
f617135b 535{
1c5e9551 536 av_log_set_callback(log_callback_help);
a03be6e1 537 printf("%s " LIBAV_VERSION "\n", program_name);
1c5e9551 538 print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
f617135b
AK
539
540 return 0;
86074ed1
SS
541}
542
11d957fb 543int show_license(void *optctx, const char *opt, const char *arg)
f35917b2 544{
7ead693b 545 printf(
3bf28f9d 546#if CONFIG_NONFREE
304ba23a
SS
547 "This version of %s has nonfree parts compiled in.\n"
548 "Therefore it is not legally redistributable.\n",
549 program_name
9cad0e4e
DB
550#elif CONFIG_GPLV3
551 "%s is free software; you can redistribute it and/or modify\n"
552 "it under the terms of the GNU General Public License as published by\n"
553 "the Free Software Foundation; either version 3 of the License, or\n"
554 "(at your option) any later version.\n"
555 "\n"
556 "%s is distributed in the hope that it will be useful,\n"
557 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
558 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
559 "GNU General Public License for more details.\n"
560 "\n"
561 "You should have received a copy of the GNU General Public License\n"
562 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
563 program_name, program_name, program_name
7ead693b 564#elif CONFIG_GPL
304ba23a 565 "%s is free software; you can redistribute it and/or modify\n"
f35917b2
SS
566 "it under the terms of the GNU General Public License as published by\n"
567 "the Free Software Foundation; either version 2 of the License, or\n"
568 "(at your option) any later version.\n"
569 "\n"
304ba23a 570 "%s is distributed in the hope that it will be useful,\n"
f35917b2
SS
571 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
572 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
573 "GNU General Public License for more details.\n"
574 "\n"
575 "You should have received a copy of the GNU General Public License\n"
304ba23a
SS
576 "along with %s; if not, write to the Free Software\n"
577 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
578 program_name, program_name, program_name
9cad0e4e
DB
579#elif CONFIG_LGPLV3
580 "%s is free software; you can redistribute it and/or modify\n"
581 "it under the terms of the GNU Lesser General Public License as published by\n"
582 "the Free Software Foundation; either version 3 of the License, or\n"
583 "(at your option) any later version.\n"
584 "\n"
585 "%s is distributed in the hope that it will be useful,\n"
586 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
587 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
588 "GNU Lesser General Public License for more details.\n"
589 "\n"
590 "You should have received a copy of the GNU Lesser General Public License\n"
591 "along with %s. If not, see <http://www.gnu.org/licenses/>.\n",
592 program_name, program_name, program_name
f35917b2 593#else
304ba23a 594 "%s is free software; you can redistribute it and/or\n"
f35917b2
SS
595 "modify it under the terms of the GNU Lesser General Public\n"
596 "License as published by the Free Software Foundation; either\n"
597 "version 2.1 of the License, or (at your option) any later version.\n"
598 "\n"
304ba23a 599 "%s is distributed in the hope that it will be useful,\n"
f35917b2
SS
600 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
601 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
602 "Lesser General Public License for more details.\n"
603 "\n"
604 "You should have received a copy of the GNU Lesser General Public\n"
304ba23a
SS
605 "License along with %s; if not, write to the Free Software\n"
606 "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
607 program_name, program_name, program_name
f35917b2 608#endif
3bf28f9d 609 );
f617135b
AK
610
611 return 0;
f35917b2 612}
ba9880c1 613
11d957fb 614int show_formats(void *optctx, const char *opt, const char *arg)
ba9880c1 615{
cbaef7d1
AD
616 AVInputFormat *ifmt = NULL;
617 AVOutputFormat *ofmt = NULL;
ba9880c1
SS
618 const char *last_name;
619
cbaef7d1
AD
620 printf("File formats:\n"
621 " D. = Demuxing supported\n"
622 " .E = Muxing supported\n"
623 " --\n");
624 last_name = "000";
625 for (;;) {
626 int decode = 0;
627 int encode = 0;
628 const char *name = NULL;
629 const char *long_name = NULL;
630
631 while ((ofmt = av_oformat_next(ofmt))) {
632 if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
633 strcmp(ofmt->name, last_name) > 0) {
634 name = ofmt->name;
635 long_name = ofmt->long_name;
636 encode = 1;
ba9880c1
SS
637 }
638 }
cbaef7d1
AD
639 while ((ifmt = av_iformat_next(ifmt))) {
640 if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
641 strcmp(ifmt->name, last_name) > 0) {
642 name = ifmt->name;
643 long_name = ifmt->long_name;
644 encode = 0;
ba9880c1 645 }
cbaef7d1
AD
646 if (name && strcmp(ifmt->name, name) == 0)
647 decode = 1;
ba9880c1 648 }
cbaef7d1 649 if (name == NULL)
ba9880c1 650 break;
cbaef7d1 651 last_name = name;
ba9880c1 652
cbaef7d1
AD
653 printf(" %s%s %-15s %s\n",
654 decode ? "D" : " ",
655 encode ? "E" : " ",
656 name,
ba9880c1
SS
657 long_name ? long_name:" ");
658 }
f617135b 659 return 0;
8447f0bd 660}
ba9880c1 661
a3ad68d3
AK
662#define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
663 if (codec->field) { \
664 const type *p = c->field; \
665 \
666 printf(" Supported " list_name ":"); \
667 while (*p != term) { \
668 get_name(*p); \
669 printf(" %s", name); \
670 p++; \
671 } \
672 printf("\n"); \
673 } \
674
675static void print_codec(const AVCodec *c)
676{
677 int encoder = av_codec_is_encoder(c);
678
679 printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
680 c->long_name ? c->long_name : "");
681
682 if (c->type == AVMEDIA_TYPE_VIDEO) {
683 printf(" Threading capabilities: ");
684 switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
685 CODEC_CAP_SLICE_THREADS)) {
686 case CODEC_CAP_FRAME_THREADS |
687 CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
688 case CODEC_CAP_FRAME_THREADS: printf("frame"); break;
689 case CODEC_CAP_SLICE_THREADS: printf("slice"); break;
690 default: printf("no"); break;
691 }
692 printf("\n");
693 }
694
695 if (c->supported_framerates) {
696 const AVRational *fps = c->supported_framerates;
697
698 printf(" Supported framerates:");
699 while (fps->num) {
700 printf(" %d/%d", fps->num, fps->den);
701 fps++;
702 }
703 printf("\n");
704 }
716d413c
AK
705 PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
706 AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
a3ad68d3
AK
707 PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
708 GET_SAMPLE_RATE_NAME);
709 PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
710 AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
711 PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
712 0, GET_CH_LAYOUT_DESC);
713
714 if (c->priv_class) {
715 show_help_children(c->priv_class,
716 AV_OPT_FLAG_ENCODING_PARAM |
717 AV_OPT_FLAG_DECODING_PARAM);
718 }
719}
720
7c101949
AK
721static char get_media_type_char(enum AVMediaType type)
722{
723 switch (type) {
724 case AVMEDIA_TYPE_VIDEO: return 'V';
725 case AVMEDIA_TYPE_AUDIO: return 'A';
726 case AVMEDIA_TYPE_SUBTITLE: return 'S';
727 default: return '?';
728 }
729}
730
731static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
732 int encoder)
733{
734 while ((prev = av_codec_next(prev))) {
735 if (prev->id == id &&
736 (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
737 return prev;
738 }
739 return NULL;
740}
741
742static void print_codecs_for_id(enum AVCodecID id, int encoder)
743{
744 const AVCodec *codec = NULL;
745
746 printf(" (%s: ", encoder ? "encoders" : "decoders");
747
748 while ((codec = next_codec_for_id(id, codec, encoder)))
749 printf("%s ", codec->name);
750
751 printf(")");
752}
753
11d957fb 754int show_codecs(void *optctx, const char *opt, const char *arg)
8447f0bd 755{
7c101949
AK
756 const AVCodecDescriptor *desc = NULL;
757
cbaef7d1 758 printf("Codecs:\n"
e2785fa7
AK
759 " D..... = Decoding supported\n"
760 " .E.... = Encoding supported\n"
761 " ..V... = Video codec\n"
762 " ..A... = Audio codec\n"
763 " ..S... = Subtitle codec\n"
764 " ...I.. = Intra frame-only codec\n"
765 " ....L. = Lossy compression\n"
766 " .....S = Lossless compression\n"
767 " -------\n");
7c101949
AK
768 while ((desc = avcodec_descriptor_next(desc))) {
769 const AVCodec *codec = NULL;
770
771 printf(avcodec_find_decoder(desc->id) ? "D" : ".");
772 printf(avcodec_find_encoder(desc->id) ? "E" : ".");
773
774 printf("%c", get_media_type_char(desc->type));
775 printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
e2785fa7
AK
776 printf((desc->props & AV_CODEC_PROP_LOSSY) ? "L" : ".");
777 printf((desc->props & AV_CODEC_PROP_LOSSLESS) ? "S" : ".");
7c101949
AK
778
779 printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
780
781 /* print decoders/encoders when there's more than one or their
782 * names are different from codec name */
783 while ((codec = next_codec_for_id(desc->id, codec, 0))) {
784 if (strcmp(codec->name, desc->name)) {
785 print_codecs_for_id(desc->id, 0);
786 break;
ba9880c1 787 }
7c101949
AK
788 }
789 codec = NULL;
790 while ((codec = next_codec_for_id(desc->id, codec, 1))) {
791 if (strcmp(codec->name, desc->name)) {
792 print_codecs_for_id(desc->id, 1);
793 break;
ba9880c1
SS
794 }
795 }
ba9880c1 796
ba9880c1
SS
797 printf("\n");
798 }
f617135b 799 return 0;
7c101949
AK
800}
801
802static void print_codecs(int encoder)
803{
804 const AVCodecDescriptor *desc = NULL;
805
806 printf("%s:\n"
807 " V... = Video\n"
808 " A... = Audio\n"
809 " S... = Subtitle\n"
810 " .F.. = Frame-level multithreading\n"
811 " ..S. = Slice-level multithreading\n"
812 " ...X = Codec is experimental\n"
813 " ---\n",
814 encoder ? "Encoders" : "Decoders");
815 while ((desc = avcodec_descriptor_next(desc))) {
816 const AVCodec *codec = NULL;
817
818 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
819 printf("%c", get_media_type_char(desc->type));
820 printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
821 printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
822 printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL) ? "X" : ".");
823
824 printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
825 if (strcmp(codec->name, desc->name))
826 printf(" (codec %s)", desc->name);
827
828 printf("\n");
829 }
830 }
831}
832
11d957fb 833int show_decoders(void *optctx, const char *opt, const char *arg)
7c101949
AK
834{
835 print_codecs(0);
836 return 0;
837}
838
11d957fb 839int show_encoders(void *optctx, const char *opt, const char *arg)
7c101949
AK
840{
841 print_codecs(1);
842 return 0;
8447f0bd
MN
843}
844
11d957fb 845int show_bsfs(void *optctx, const char *opt, const char *arg)
8447f0bd 846{
cbaef7d1 847 AVBitStreamFilter *bsf = NULL;
ba9880c1
SS
848
849 printf("Bitstream filters:\n");
cbaef7d1 850 while ((bsf = av_bitstream_filter_next(bsf)))
2091b27b 851 printf("%s\n", bsf->name);
ba9880c1 852 printf("\n");
f617135b 853 return 0;
8447f0bd
MN
854}
855
11d957fb 856int show_protocols(void *optctx, const char *opt, const char *arg)
8447f0bd 857{
cdc6a87f
AK
858 void *opaque = NULL;
859 const char *name;
ba9880c1 860
2ee5c789 861 printf("Supported file protocols:\n"
cdc6a87f
AK
862 "Input:\n");
863 while ((name = avio_enum_protocols(&opaque, 0)))
864 printf("%s\n", name);
865 printf("Output:\n");
866 while ((name = avio_enum_protocols(&opaque, 1)))
867 printf("%s\n", name);
f617135b 868 return 0;
ba9880c1 869}
090b61b2 870
11d957fb 871int show_filters(void *optctx, const char *opt, const char *arg)
62d75662 872{
78638628 873 AVFilter av_unused(**filter) = NULL;
62d75662
SS
874
875 printf("Filters:\n");
663c2edf 876#if CONFIG_AVFILTER
62d75662
SS
877 while ((filter = av_filter_next(filter)) && *filter)
878 printf("%-16s %s\n", (*filter)->name, (*filter)->description);
663c2edf 879#endif
f617135b 880 return 0;
62d75662
SS
881}
882
11d957fb 883int show_pix_fmts(void *optctx, const char *opt, const char *arg)
3f7bb426 884{
b7f1010c 885 const AVPixFmtDescriptor *pix_desc = NULL;
9cb5c760 886
cbaef7d1
AD
887 printf("Pixel formats:\n"
888 "I.... = Supported Input format for conversion\n"
889 ".O... = Supported Output format for conversion\n"
890 "..H.. = Hardware accelerated format\n"
891 "...P. = Paletted format\n"
892 "....B = Bitstream format\n"
893 "FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL\n"
894 "-----\n");
9cb5c760 895
e24db3e3
MR
896#if !CONFIG_SWSCALE
897# define sws_isSupportedInput(x) 0
898# define sws_isSupportedOutput(x) 0
899#endif
900
b7f1010c
AK
901 while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
902 enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
9cb5c760
SS
903 printf("%c%c%c%c%c %-16s %d %2d\n",
904 sws_isSupportedInput (pix_fmt) ? 'I' : '.',
905 sws_isSupportedOutput(pix_fmt) ? 'O' : '.',
906 pix_desc->flags & PIX_FMT_HWACCEL ? 'H' : '.',
907 pix_desc->flags & PIX_FMT_PAL ? 'P' : '.',
908 pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
909 pix_desc->name,
910 pix_desc->nb_components,
911 av_get_bits_per_pixel(pix_desc));
912 }
f617135b 913 return 0;
3f7bb426
SS
914}
915
11d957fb 916int show_sample_fmts(void *optctx, const char *opt, const char *arg)
05bffc12
AK
917{
918 int i;
919 char fmt_str[128];
920 for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
921 printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
922 return 0;
923}
924
a3ad68d3
AK
925static void show_help_codec(const char *name, int encoder)
926{
927 const AVCodecDescriptor *desc;
928 const AVCodec *codec;
929
930 if (!name) {
931 av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
932 return;
933 }
934
935 codec = encoder ? avcodec_find_encoder_by_name(name) :
936 avcodec_find_decoder_by_name(name);
937
938 if (codec)
939 print_codec(codec);
940 else if ((desc = avcodec_descriptor_get_by_name(name))) {
941 int printed = 0;
942
943 while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
944 printed = 1;
945 print_codec(codec);
946 }
947
948 if (!printed) {
949 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
950 "but no %s for it are available. Libav might need to be "
951 "recompiled with additional external libraries.\n",
952 name, encoder ? "encoders" : "decoders");
953 }
954 } else {
955 av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
956 name);
957 }
958}
959
1136bd36
AK
960static void show_help_demuxer(const char *name)
961{
962 const AVInputFormat *fmt = av_find_input_format(name);
963
964 if (!fmt) {
965 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
966 return;
967 }
968
969 printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
970
971 if (fmt->extensions)
972 printf(" Common extensions: %s.\n", fmt->extensions);
973
974 if (fmt->priv_class)
975 show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
976}
977
978static void show_help_muxer(const char *name)
979{
980 const AVCodecDescriptor *desc;
981 const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
982
983 if (!fmt) {
984 av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
985 return;
986 }
987
988 printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
989
990 if (fmt->extensions)
991 printf(" Common extensions: %s.\n", fmt->extensions);
992 if (fmt->mime_type)
993 printf(" Mime type: %s.\n", fmt->mime_type);
994 if (fmt->video_codec != AV_CODEC_ID_NONE &&
995 (desc = avcodec_descriptor_get(fmt->video_codec))) {
996 printf(" Default video codec: %s.\n", desc->name);
997 }
998 if (fmt->audio_codec != AV_CODEC_ID_NONE &&
999 (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1000 printf(" Default audio codec: %s.\n", desc->name);
1001 }
1002 if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1003 (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1004 printf(" Default subtitle codec: %s.\n", desc->name);
1005 }
1006
1007 if (fmt->priv_class)
1008 show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1009}
1010
11d957fb 1011int show_help(void *optctx, const char *opt, const char *arg)
a3ad68d3
AK
1012{
1013 char *topic, *par;
1014 av_log_set_callback(log_callback_help);
1015
1016 topic = av_strdup(arg ? arg : "");
1017 par = strchr(topic, '=');
1018 if (par)
1019 *par++ = 0;
1020
1021 if (!*topic) {
1022 show_help_default(topic, par);
1023 } else if (!strcmp(topic, "decoder")) {
1024 show_help_codec(par, 0);
1025 } else if (!strcmp(topic, "encoder")) {
1026 show_help_codec(par, 1);
1136bd36
AK
1027 } else if (!strcmp(topic, "demuxer")) {
1028 show_help_demuxer(par);
1029 } else if (!strcmp(topic, "muxer")) {
1030 show_help_muxer(par);
a3ad68d3
AK
1031 } else {
1032 show_help_default(topic, par);
1033 }
1034
1035 av_freep(&topic);
1036 return 0;
1037}
1038
090b61b2
SS
1039int read_yesno(void)
1040{
1041 int c = getchar();
1042 int yesno = (toupper(c) == 'Y');
1043
1044 while (c != '\n' && c != EOF)
1045 c = getchar();
1046
1047 return yesno;
1048}
458b062d 1049
02170990 1050int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
458b062d 1051{
d94c577d 1052 int ret;
c56e9e05 1053 FILE *f = fopen(filename, "rb");
458b062d
SS
1054
1055 if (!f) {
cbaef7d1
AD
1056 av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1057 strerror(errno));
458b062d
SS
1058 return AVERROR(errno);
1059 }
1060 fseek(f, 0, SEEK_END);
1061 *size = ftell(f);
1062 fseek(f, 0, SEEK_SET);
1063 *bufptr = av_malloc(*size + 1);
1064 if (!*bufptr) {
1c5e9551 1065 av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
458b062d
SS
1066 fclose(f);
1067 return AVERROR(ENOMEM);
1068 }
d94c577d
JG
1069 ret = fread(*bufptr, 1, *size, f);
1070 if (ret < *size) {
1071 av_free(*bufptr);
1072 if (ferror(f)) {
1073 av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1074 filename, strerror(errno));
1075 ret = AVERROR(errno);
1076 } else
1077 ret = AVERROR_EOF;
1078 } else {
1079 ret = 0;
b94e4acb 1080 (*bufptr)[(*size)++] = '\0';
d94c577d 1081 }
458b062d
SS
1082
1083 fclose(f);
d94c577d 1084 return ret;
458b062d 1085}
7a8bfa5d
AS
1086
1087void init_pts_correction(PtsCorrectionContext *ctx)
1088{
1089 ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1090 ctx->last_pts = ctx->last_dts = INT64_MIN;
1091}
1092
cbaef7d1
AD
1093int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1094 int64_t dts)
7a8bfa5d
AS
1095{
1096 int64_t pts = AV_NOPTS_VALUE;
1097
1098 if (dts != AV_NOPTS_VALUE) {
1099 ctx->num_faulty_dts += dts <= ctx->last_dts;
1100 ctx->last_dts = dts;
1101 }
1102 if (reordered_pts != AV_NOPTS_VALUE) {
1103 ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1104 ctx->last_pts = reordered_pts;
1105 }
01d46198 1106 if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
cbaef7d1 1107 && reordered_pts != AV_NOPTS_VALUE)
7a8bfa5d
AS
1108 pts = reordered_pts;
1109 else
1110 pts = dts;
1111
1112 return pts;
1113}
f7ead94c 1114
6e872935 1115FILE *get_preset_file(char *filename, size_t filename_size,
cbaef7d1
AD
1116 const char *preset_name, int is_path,
1117 const char *codec_name)
6e872935
SS
1118{
1119 FILE *f = NULL;
1120 int i;
cbaef7d1
AD
1121 const char *base[3] = { getenv("AVCONV_DATADIR"),
1122 getenv("HOME"),
1123 AVCONV_DATADIR, };
6e872935
SS
1124
1125 if (is_path) {
1126 av_strlcpy(filename, preset_name, filename_size);
1127 f = fopen(filename, "r");
1128 } else {
1129 for (i = 0; i < 3 && !f; i++) {
1130 if (!base[i])
1131 continue;
050dc127 1132 snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
cbaef7d1 1133 i != 1 ? "" : "/.avconv", preset_name);
6e872935
SS
1134 f = fopen(filename, "r");
1135 if (!f && codec_name) {
1136 snprintf(filename, filename_size,
050dc127 1137 "%s%s/%s-%s.avpreset",
cbaef7d1
AD
1138 base[i], i != 1 ? "" : "/.avconv", codec_name,
1139 preset_name);
6e872935
SS
1140 f = fopen(filename, "r");
1141 }
1142 }
1143 }
1144
1145 return f;
1146}
1147
d4863fc1
AK
1148int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1149{
cbaef7d1 1150 if (*spec <= '9' && *spec >= '0') /* opt:index */
d4863fc1 1151 return strtol(spec, NULL, 0) == st->index;
cbaef7d1
AD
1152 else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1153 *spec == 't') { /* opt:[vasdt] */
d4863fc1
AK
1154 enum AVMediaType type;
1155
1156 switch (*spec++) {
cbaef7d1
AD
1157 case 'v': type = AVMEDIA_TYPE_VIDEO; break;
1158 case 'a': type = AVMEDIA_TYPE_AUDIO; break;
1159 case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1160 case 'd': type = AVMEDIA_TYPE_DATA; break;
3ccd1580 1161 case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
7cf78b34 1162 default: av_assert0(0);
d4863fc1
AK
1163 }
1164 if (type != st->codec->codec_type)
1165 return 0;
cbaef7d1 1166 if (*spec++ == ':') { /* possibly followed by :index */
d4863fc1
AK
1167 int i, index = strtol(spec, NULL, 0);
1168 for (i = 0; i < s->nb_streams; i++)
1169 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1170 return i == st->index;
1171 return 0;
1172 }
1173 return 1;
2c474ddb
AK
1174 } else if (*spec == 'p' && *(spec + 1) == ':') {
1175 int prog_id, i, j;
1176 char *endptr;
1177 spec += 2;
1178 prog_id = strtol(spec, &endptr, 0);
1179 for (i = 0; i < s->nb_programs; i++) {
1180 if (s->programs[i]->id != prog_id)
1181 continue;
1182
1183 if (*endptr++ == ':') {
1184 int stream_idx = strtol(endptr, NULL, 0);
d4b63054
DB
1185 return stream_idx >= 0 &&
1186 stream_idx < s->programs[i]->nb_stream_indexes &&
1187 st->index == s->programs[i]->stream_index[stream_idx];
2c474ddb
AK
1188 }
1189
1190 for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1191 if (st->index == s->programs[i]->stream_index[j])
1192 return 1;
1193 }
1194 return 0;
d4863fc1
AK
1195 } else if (!*spec) /* empty specifier, matches everything */
1196 return 1;
1197
1198 av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1199 return AVERROR(EINVAL);
1200}
1201
36ef5369 1202AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
d3ed1c95 1203 AVFormatContext *s, AVStream *st, AVCodec *codec)
8c8eab8b
AK
1204{
1205 AVDictionary *ret = NULL;
1206 AVDictionaryEntry *t = NULL;
cbaef7d1
AD
1207 int flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1208 : AV_OPT_FLAG_DECODING_PARAM;
8c8eab8b 1209 char prefix = 0;
20c21f8b 1210 const AVClass *cc = avcodec_get_class();
8c8eab8b
AK
1211
1212 if (!codec)
d3ed1c95
MS
1213 codec = s->oformat ? avcodec_find_encoder(codec_id)
1214 : avcodec_find_decoder(codec_id);
1215 if (!codec)
8c8eab8b
AK
1216 return NULL;
1217
1218 switch (codec->type) {
cbaef7d1
AD
1219 case AVMEDIA_TYPE_VIDEO:
1220 prefix = 'v';
1221 flags |= AV_OPT_FLAG_VIDEO_PARAM;
1222 break;
1223 case AVMEDIA_TYPE_AUDIO:
1224 prefix = 'a';
1225 flags |= AV_OPT_FLAG_AUDIO_PARAM;
1226 break;
1227 case AVMEDIA_TYPE_SUBTITLE:
1228 prefix = 's';
1229 flags |= AV_OPT_FLAG_SUBTITLE_PARAM;
1230 break;
8c8eab8b
AK
1231 }
1232
1233 while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
d4863fc1
AK
1234 char *p = strchr(t->key, ':');
1235
1236 /* check stream specification in opt name */
1237 if (p)
1238 switch (check_stream_specifier(s, st, p + 1)) {
1239 case 1: *p = 0; break;
1240 case 0: continue;
1241 default: return NULL;
1242 }
1243
20c21f8b 1244 if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
cbaef7d1
AD
1245 (codec && codec->priv_class &&
1246 av_opt_find(&codec->priv_class, t->key, NULL, flags,
1247 AV_OPT_SEARCH_FAKE_OBJ)))
8c8eab8b 1248 av_dict_set(&ret, t->key, t->value, 0);
cbaef7d1
AD
1249 else if (t->key[0] == prefix &&
1250 av_opt_find(&cc, t->key + 1, NULL, flags,
1251 AV_OPT_SEARCH_FAKE_OBJ))
1252 av_dict_set(&ret, t->key + 1, t->value, 0);
d4863fc1
AK
1253
1254 if (p)
1255 *p = ':';
8c8eab8b
AK
1256 }
1257 return ret;
1258}
1259
cbaef7d1
AD
1260AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1261 AVDictionary *codec_opts)
3009f521
AK
1262{
1263 int i;
1264 AVDictionary **opts;
1265
1266 if (!s->nb_streams)
1267 return NULL;
1268 opts = av_mallocz(s->nb_streams * sizeof(*opts));
1269 if (!opts) {
cbaef7d1
AD
1270 av_log(NULL, AV_LOG_ERROR,
1271 "Could not alloc memory for stream options.\n");
3009f521
AK
1272 return NULL;
1273 }
1274 for (i = 0; i < s->nb_streams; i++)
cbaef7d1 1275 opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
d3ed1c95 1276 s, s->streams[i], NULL);
3009f521
AK
1277 return opts;
1278}
1279
cac651c8
AK
1280void *grow_array(void *array, int elem_size, int *size, int new_size)
1281{
1282 if (new_size >= INT_MAX / elem_size) {
1283 av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
5e3f9979 1284 exit(1);
cac651c8
AK
1285 }
1286 if (*size < new_size) {
1287 uint8_t *tmp = av_realloc(array, new_size*elem_size);
1288 if (!tmp) {
1289 av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
5e3f9979 1290 exit(1);
cac651c8
AK
1291 }
1292 memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1293 *size = new_size;
1294 return tmp;
1295 }
1296 return array;
1297}
d55c2e05
AK
1298
1299static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1300{
b7f1010c
AK
1301 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1302 FrameBuffer *buf;
d55c2e05 1303 int i, ret;
b7f1010c 1304 int pixel_size;
d55c2e05
AK
1305 int h_chroma_shift, v_chroma_shift;
1306 int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1307 int w = s->width, h = s->height;
1308
b7f1010c
AK
1309 if (!desc)
1310 return AVERROR(EINVAL);
1311 pixel_size = desc->comp[0].step_minus1 + 1;
1312
1313 buf = av_mallocz(sizeof(*buf));
d55c2e05
AK
1314 if (!buf)
1315 return AVERROR(ENOMEM);
1316
1317 if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1318 w += 2*edge;
1319 h += 2*edge;
1320 }
1321
1322 avcodec_align_dimensions(s, &w, &h);
1323 if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1324 s->pix_fmt, 32)) < 0) {
1325 av_freep(&buf);
1326 return ret;
1327 }
1328 /* XXX this shouldn't be needed, but some tests break without this line
1329 * those decoders are buggy and need to be fixed.
1330 * the following tests fail:
1331 * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1332 */
1333 memset(buf->base[0], 128, ret);
1334
c1a02e88
LB
1335 av_pix_fmt_get_chroma_sub_sample(s->pix_fmt,
1336 &h_chroma_shift, &v_chroma_shift);
1337
d55c2e05
AK
1338 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1339 const int h_shift = i==0 ? 0 : h_chroma_shift;
1340 const int v_shift = i==0 ? 0 : v_chroma_shift;
1341 if (s->flags & CODEC_FLAG_EMU_EDGE)
1342 buf->data[i] = buf->base[i];
990450c5 1343 else if (buf->base[i])
d55c2e05
AK
1344 buf->data[i] = buf->base[i] +
1345 FFALIGN((buf->linesize[i]*edge >> v_shift) +
1346 (pixel_size*edge >> h_shift), 32);
1347 }
1348 buf->w = s->width;
1349 buf->h = s->height;
1350 buf->pix_fmt = s->pix_fmt;
1351 buf->pool = pool;
1352
1353 *pbuf = buf;
1354 return 0;
1355}
1356
1357int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1358{
1359 FrameBuffer **pool = s->opaque;
1360 FrameBuffer *buf;
1361 int ret, i;
1362
1363 if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1364 return ret;
1365
1366 buf = *pool;
1367 *pool = buf->next;
1368 buf->next = NULL;
1369 if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1370 av_freep(&buf->base[0]);
1371 av_free(buf);
1372 if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1373 return ret;
1374 }
1375 buf->refcount++;
1376
1377 frame->opaque = buf;
1378 frame->type = FF_BUFFER_TYPE_USER;
1379 frame->extended_data = frame->data;
d55c2e05
AK
1380
1381 for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1382 frame->base[i] = buf->base[i]; // XXX h264.c uses base though it shouldn't
1383 frame->data[i] = buf->data[i];
1384 frame->linesize[i] = buf->linesize[i];
1385 }
1386
1387 return 0;
1388}
1389
1390static void unref_buffer(FrameBuffer *buf)
1391{
1392 FrameBuffer **pool = buf->pool;
1393
1394 av_assert0(buf->refcount);
1395 buf->refcount--;
1396 if (!buf->refcount) {
1397 buf->next = *pool;
1398 *pool = buf;
1399 }
1400}
1401
1402void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1403{
1404 FrameBuffer *buf = frame->opaque;
1405 int i;
1406
1407 for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1408 frame->data[i] = NULL;
1409
1410 unref_buffer(buf);
1411}
1412
1413void filter_release_buffer(AVFilterBuffer *fb)
1414{
1415 FrameBuffer *buf = fb->priv;
1416 av_free(fb);
1417 unref_buffer(buf);
1418}
1419
1420void free_buffer_pool(FrameBuffer **pool)
1421{
1422 FrameBuffer *buf = *pool;
1423 while (buf) {
1424 *pool = buf->next;
1425 av_freep(&buf->base[0]);
1426 av_free(buf);
1427 buf = *pool;
1428 }
1429}