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