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