OSDN Git Service

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