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