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