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