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