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