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