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