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