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