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