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