]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
Merge commit '4521645b1aee9e9ad8f5cea7b2392cd5f6ffcd26'
[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(), *sc, *swr_class;
444
445     if (!(p = strchr(opt, ':')))
446         p = opt + strlen(opt);
447     av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
448
449     if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
450                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
451         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
452          (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
453         av_dict_set(&codec_opts, opt, arg, FLAGS);
454         consumed = 1;
455     }
456     if ((o = av_opt_find(&fc, opt, NULL, 0,
457                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
458         av_dict_set(&format_opts, opt, arg, FLAGS);
459         if(consumed)
460             av_log(NULL, AV_LOG_VERBOSE, "Routing %s to codec and muxer layer\n", opt);
461         consumed = 1;
462     }
463 #if CONFIG_SWSCALE
464     sc = sws_get_class();
465     if (!consumed && av_opt_find(&sc, opt, NULL, 0,
466                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
467         // XXX we only support sws_flags, not arbitrary sws options
468         int ret = av_opt_set(sws_opts, opt, arg, 0);
469         if (ret < 0) {
470             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
471             return ret;
472         }
473         consumed = 1;
474     }
475 #endif
476 #if CONFIG_SWRESAMPLE
477     swr_class = swr_get_class();
478     if (!consumed && av_opt_find(&swr_class, opt, NULL, 0,
479                                AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
480         int ret = av_opt_set(swr_opts, opt, arg, 0);
481         if (ret < 0) {
482             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
483             return ret;
484         }
485         consumed = 1;
486     }
487 #endif
488
489     if (consumed)
490         return 0;
491     av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
492     return AVERROR_OPTION_NOT_FOUND;
493 }
494
495 int opt_loglevel(void *optctx, const char *opt, const char *arg)
496 {
497     const struct { const char *name; int level; } log_levels[] = {
498         { "quiet"  , AV_LOG_QUIET   },
499         { "panic"  , AV_LOG_PANIC   },
500         { "fatal"  , AV_LOG_FATAL   },
501         { "error"  , AV_LOG_ERROR   },
502         { "warning", AV_LOG_WARNING },
503         { "info"   , AV_LOG_INFO    },
504         { "verbose", AV_LOG_VERBOSE },
505         { "debug"  , AV_LOG_DEBUG   },
506     };
507     char *tail;
508     int level;
509     int i;
510
511     for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
512         if (!strcmp(log_levels[i].name, arg)) {
513             av_log_set_level(log_levels[i].level);
514             return 0;
515         }
516     }
517
518     level = strtol(arg, &tail, 10);
519     if (*tail) {
520         av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
521                "Possible levels are numbers or:\n", arg);
522         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
523             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
524         exit(1);
525     }
526     av_log_set_level(level);
527     return 0;
528 }
529
530 int opt_report(const char *opt)
531 {
532     char filename[64];
533     time_t now;
534     struct tm *tm;
535
536     if (report_file) /* already opened */
537         return 0;
538     time(&now);
539     tm = localtime(&now);
540     snprintf(filename, sizeof(filename), "%s-%04d%02d%02d-%02d%02d%02d.log",
541              program_name,
542              tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
543              tm->tm_hour, tm->tm_min, tm->tm_sec);
544     report_file = fopen(filename, "w");
545     if (!report_file) {
546         av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
547                filename, strerror(errno));
548         return AVERROR(errno);
549     }
550     av_log_set_callback(log_callback_report);
551     av_log(NULL, AV_LOG_INFO,
552            "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
553            "Report written to \"%s\"\n",
554            program_name,
555            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
556            tm->tm_hour, tm->tm_min, tm->tm_sec,
557            filename);
558     av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
559     return 0;
560 }
561
562 int opt_max_alloc(void *optctx, const char *opt, const char *arg)
563 {
564     char *tail;
565     size_t max;
566
567     max = strtol(arg, &tail, 10);
568     if (*tail) {
569         av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
570         exit(1);
571     }
572     av_max_alloc(max);
573     return 0;
574 }
575
576 int opt_cpuflags(void *optctx, const char *opt, const char *arg)
577 {
578     int ret;
579     unsigned flags = av_get_cpu_flags();
580
581     if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
582         return ret;
583
584     av_force_cpu_flags(flags);
585     return 0;
586 }
587
588 int opt_codec_debug(void *optctx, const char *opt, const char *arg)
589 {
590     av_log_set_level(AV_LOG_DEBUG);
591     return opt_default(NULL, opt, arg);
592 }
593
594 int opt_timelimit(void *optctx, const char *opt, const char *arg)
595 {
596 #if HAVE_SETRLIMIT
597     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
598     struct rlimit rl = { lim, lim + 1 };
599     if (setrlimit(RLIMIT_CPU, &rl))
600         perror("setrlimit");
601 #else
602     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
603 #endif
604     return 0;
605 }
606
607 void print_error(const char *filename, int err)
608 {
609     char errbuf[128];
610     const char *errbuf_ptr = errbuf;
611
612     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
613         errbuf_ptr = strerror(AVUNERROR(err));
614     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
615 }
616
617 static int warned_cfg = 0;
618
619 #define INDENT        1
620 #define SHOW_VERSION  2
621 #define SHOW_CONFIG   4
622 #define SHOW_COPYRIGHT 8
623
624 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
625     if (CONFIG_##LIBNAME) {                                             \
626         const char *indent = flags & INDENT? "  " : "";                 \
627         if (flags & SHOW_VERSION) {                                     \
628             unsigned int version = libname##_version();                 \
629             av_log(NULL, level,                                         \
630                    "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n",            \
631                    indent, #libname,                                    \
632                    LIB##LIBNAME##_VERSION_MAJOR,                        \
633                    LIB##LIBNAME##_VERSION_MINOR,                        \
634                    LIB##LIBNAME##_VERSION_MICRO,                        \
635                    version >> 16, version >> 8 & 0xff, version & 0xff); \
636         }                                                               \
637         if (flags & SHOW_CONFIG) {                                      \
638             const char *cfg = libname##_configuration();                \
639             if (strcmp(FFMPEG_CONFIGURATION, cfg)) {                    \
640                 if (!warned_cfg) {                                      \
641                     av_log(NULL, level,                                 \
642                             "%sWARNING: library configuration mismatch\n", \
643                             indent);                                    \
644                     warned_cfg = 1;                                     \
645                 }                                                       \
646                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
647                         indent, #libname, cfg);                         \
648             }                                                           \
649         }                                                               \
650     }                                                                   \
651
652 static void print_all_libs_info(int flags, int level)
653 {
654     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
655     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
656     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
657     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
658     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
659 //    PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
660     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
661     PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);
662 #if CONFIG_POSTPROC
663     PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
664 #endif
665 }
666
667 static void print_program_info(int flags, int level)
668 {
669     const char *indent = flags & INDENT? "  " : "";
670
671     av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
672     if (flags & SHOW_COPYRIGHT)
673         av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
674                program_birth_year, this_year);
675     av_log(NULL, level, "\n");
676     av_log(NULL, level, "%sbuilt on %s %s with %s\n",
677            indent, __DATE__, __TIME__, CC_IDENT);
678
679     av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
680 }
681
682 void show_banner(int argc, char **argv, const OptionDef *options)
683 {
684     int idx = locate_option(argc, argv, options, "version");
685     if (idx)
686         return;
687
688     print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
689     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_INFO);
690     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
691 }
692
693 int show_version(void *optctx, const char *opt, const char *arg)
694 {
695     av_log_set_callback(log_callback_help);
696     print_program_info (0           , AV_LOG_INFO);
697     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
698
699     return 0;
700 }
701
702 int show_license(void *optctx, const char *opt, const char *arg)
703 {
704     printf(
705 #if CONFIG_NONFREE
706     "This version of %s has nonfree parts compiled in.\n"
707     "Therefore it is not legally redistributable.\n",
708     program_name
709 #elif CONFIG_GPLV3
710     "%s is free software; you can redistribute it and/or modify\n"
711     "it under the terms of the GNU General Public License as published by\n"
712     "the Free Software Foundation; either version 3 of the License, or\n"
713     "(at your option) any later version.\n"
714     "\n"
715     "%s is distributed in the hope that it will be useful,\n"
716     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
717     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
718     "GNU General Public License for more details.\n"
719     "\n"
720     "You should have received a copy of the GNU General Public License\n"
721     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
722     program_name, program_name, program_name
723 #elif CONFIG_GPL
724     "%s is free software; you can redistribute it and/or modify\n"
725     "it under the terms of the GNU General Public License as published by\n"
726     "the Free Software Foundation; either version 2 of the License, or\n"
727     "(at your option) any later version.\n"
728     "\n"
729     "%s is distributed in the hope that it will be useful,\n"
730     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
731     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
732     "GNU General Public License for more details.\n"
733     "\n"
734     "You should have received a copy of the GNU General Public License\n"
735     "along with %s; if not, write to the Free Software\n"
736     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
737     program_name, program_name, program_name
738 #elif CONFIG_LGPLV3
739     "%s is free software; you can redistribute it and/or modify\n"
740     "it under the terms of the GNU Lesser General Public License as published by\n"
741     "the Free Software Foundation; either version 3 of the License, or\n"
742     "(at your option) any later version.\n"
743     "\n"
744     "%s is distributed in the hope that it will be useful,\n"
745     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
746     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
747     "GNU Lesser General Public License for more details.\n"
748     "\n"
749     "You should have received a copy of the GNU Lesser General Public License\n"
750     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
751     program_name, program_name, program_name
752 #else
753     "%s is free software; you can redistribute it and/or\n"
754     "modify it under the terms of the GNU Lesser General Public\n"
755     "License as published by the Free Software Foundation; either\n"
756     "version 2.1 of the License, or (at your option) any later version.\n"
757     "\n"
758     "%s is distributed in the hope that it will be useful,\n"
759     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
760     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
761     "Lesser General Public License for more details.\n"
762     "\n"
763     "You should have received a copy of the GNU Lesser General Public\n"
764     "License along with %s; if not, write to the Free Software\n"
765     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
766     program_name, program_name, program_name
767 #endif
768     );
769
770     return 0;
771 }
772
773 int show_formats(void *optctx, const char *opt, const char *arg)
774 {
775     AVInputFormat *ifmt  = NULL;
776     AVOutputFormat *ofmt = NULL;
777     const char *last_name;
778
779     printf("File formats:\n"
780            " D. = Demuxing supported\n"
781            " .E = Muxing supported\n"
782            " --\n");
783     last_name = "000";
784     for (;;) {
785         int decode = 0;
786         int encode = 0;
787         const char *name      = NULL;
788         const char *long_name = NULL;
789
790         while ((ofmt = av_oformat_next(ofmt))) {
791             if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
792                 strcmp(ofmt->name, last_name) > 0) {
793                 name      = ofmt->name;
794                 long_name = ofmt->long_name;
795                 encode    = 1;
796             }
797         }
798         while ((ifmt = av_iformat_next(ifmt))) {
799             if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
800                 strcmp(ifmt->name, last_name) > 0) {
801                 name      = ifmt->name;
802                 long_name = ifmt->long_name;
803                 encode    = 0;
804             }
805             if (name && strcmp(ifmt->name, name) == 0)
806                 decode = 1;
807         }
808         if (name == NULL)
809             break;
810         last_name = name;
811
812         printf(" %s%s %-15s %s\n",
813                decode ? "D" : " ",
814                encode ? "E" : " ",
815                name,
816             long_name ? long_name:" ");
817     }
818     return 0;
819 }
820
821 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
822     if (codec->field) {                                                      \
823         const type *p = c->field;                                            \
824                                                                              \
825         printf("    Supported " list_name ":");                              \
826         while (*p != term) {                                                 \
827             get_name(*p);                                                    \
828             printf(" %s", name);                                             \
829             p++;                                                             \
830         }                                                                    \
831         printf("\n");                                                        \
832     }                                                                        \
833
834 static void print_codec(const AVCodec *c)
835 {
836     int encoder = av_codec_is_encoder(c);
837
838     printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
839            c->long_name ? c->long_name : "");
840
841     if (c->type == AVMEDIA_TYPE_VIDEO) {
842         printf("    Threading capabilities: ");
843         switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
844                                    CODEC_CAP_SLICE_THREADS)) {
845         case CODEC_CAP_FRAME_THREADS |
846              CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
847         case CODEC_CAP_FRAME_THREADS: printf("frame");           break;
848         case CODEC_CAP_SLICE_THREADS: printf("slice");           break;
849         default:                      printf("no");              break;
850         }
851         printf("\n");
852     }
853
854     if (c->supported_framerates) {
855         const AVRational *fps = c->supported_framerates;
856
857         printf("    Supported framerates:");
858         while (fps->num) {
859             printf(" %d/%d", fps->num, fps->den);
860             fps++;
861         }
862         printf("\n");
863     }
864     PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
865                           AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
866     PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
867                           GET_SAMPLE_RATE_NAME);
868     PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
869                           AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
870     PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
871                           0, GET_CH_LAYOUT_DESC);
872
873     if (c->priv_class) {
874         show_help_children(c->priv_class,
875                            AV_OPT_FLAG_ENCODING_PARAM |
876                            AV_OPT_FLAG_DECODING_PARAM);
877     }
878 }
879
880 static char get_media_type_char(enum AVMediaType type)
881 {
882     switch (type) {
883         case AVMEDIA_TYPE_VIDEO:    return 'V';
884         case AVMEDIA_TYPE_AUDIO:    return 'A';
885         case AVMEDIA_TYPE_DATA:     return 'D';
886         case AVMEDIA_TYPE_SUBTITLE: return 'S';
887         case AVMEDIA_TYPE_ATTACHMENT:return 'T';
888         default:                    return '?';
889     }
890 }
891
892 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
893                                         int encoder)
894 {
895     while ((prev = av_codec_next(prev))) {
896         if (prev->id == id &&
897             (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
898             return prev;
899     }
900     return NULL;
901 }
902
903 static int compare_codec_desc(const void *a, const void *b)
904 {
905     const AVCodecDescriptor * const *da = a;
906     const AVCodecDescriptor * const *db = b;
907
908     return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
909            strcmp((*da)->name, (*db)->name);
910 }
911
912 static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
913 {
914     const AVCodecDescriptor *desc = NULL;
915     const AVCodecDescriptor **codecs;
916     unsigned nb_codecs = 0, i = 0;
917
918     while ((desc = avcodec_descriptor_next(desc)))
919         nb_codecs++;
920     if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
921         av_log(0, AV_LOG_ERROR, "Out of memory\n");
922         exit(1);
923     }
924     desc = NULL;
925     while ((desc = avcodec_descriptor_next(desc)))
926         codecs[i++] = desc;
927     av_assert0(i == nb_codecs);
928     qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
929     *rcodecs = codecs;
930     return nb_codecs;
931 }
932
933 static void print_codecs_for_id(enum AVCodecID id, int encoder)
934 {
935     const AVCodec *codec = NULL;
936
937     printf(" (%s: ", encoder ? "encoders" : "decoders");
938
939     while ((codec = next_codec_for_id(id, codec, encoder)))
940         printf("%s ", codec->name);
941
942     printf(")");
943 }
944
945 int show_codecs(void *optctx, const char *opt, const char *arg)
946 {
947     const AVCodecDescriptor **codecs;
948     unsigned i, nb_codecs = get_codecs_sorted(&codecs);
949
950     printf("Codecs:\n"
951            " D..... = Decoding supported\n"
952            " .E.... = Encoding supported\n"
953            " ..V... = Video codec\n"
954            " ..A... = Audio codec\n"
955            " ..S... = Subtitle codec\n"
956            " ...I.. = Intra frame-only codec\n"
957            " ....L. = Lossy compression\n"
958            " .....S = Lossless compression\n"
959            " -------\n");
960     for (i = 0; i < nb_codecs; i++) {
961         const AVCodecDescriptor *desc = codecs[i];
962         const AVCodec *codec = NULL;
963
964         printf(" ");
965         printf(avcodec_find_decoder(desc->id) ? "D" : ".");
966         printf(avcodec_find_encoder(desc->id) ? "E" : ".");
967
968         printf("%c", get_media_type_char(desc->type));
969         printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
970         printf((desc->props & AV_CODEC_PROP_LOSSY)      ? "L" : ".");
971         printf((desc->props & AV_CODEC_PROP_LOSSLESS)   ? "S" : ".");
972
973         printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
974
975         /* print decoders/encoders when there's more than one or their
976          * names are different from codec name */
977         while ((codec = next_codec_for_id(desc->id, codec, 0))) {
978             if (strcmp(codec->name, desc->name)) {
979                 print_codecs_for_id(desc->id, 0);
980                 break;
981             }
982         }
983         codec = NULL;
984         while ((codec = next_codec_for_id(desc->id, codec, 1))) {
985             if (strcmp(codec->name, desc->name)) {
986                 print_codecs_for_id(desc->id, 1);
987                 break;
988             }
989         }
990
991         printf("\n");
992     }
993     av_free(codecs);
994     return 0;
995 }
996
997 static void print_codecs(int encoder)
998 {
999     const AVCodecDescriptor **codecs;
1000     unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1001
1002     printf("%s:\n"
1003            " V..... = Video\n"
1004            " A..... = Audio\n"
1005            " S..... = Subtitle\n"
1006            " .F.... = Frame-level multithreading\n"
1007            " ..S... = Slice-level multithreading\n"
1008            " ...X.. = Codec is experimental\n"
1009            " ....B. = Supports draw_horiz_band\n"
1010            " .....D = Supports direct rendering method 1\n"
1011            " ------\n",
1012            encoder ? "Encoders" : "Decoders");
1013     for (i = 0; i < nb_codecs; i++) {
1014         const AVCodecDescriptor *desc = codecs[i];
1015         const AVCodec *codec = NULL;
1016
1017         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1018             printf(" %c", get_media_type_char(desc->type));
1019             printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1020             printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1021             printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL)  ? "X" : ".");
1022             printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
1023             printf((codec->capabilities & CODEC_CAP_DR1)           ? "D" : ".");
1024
1025             printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1026             if (strcmp(codec->name, desc->name))
1027                 printf(" (codec %s)", desc->name);
1028
1029             printf("\n");
1030         }
1031     }
1032     av_free(codecs);
1033 }
1034
1035 int show_decoders(void *optctx, const char *opt, const char *arg)
1036 {
1037     print_codecs(0);
1038     return 0;
1039 }
1040
1041 int show_encoders(void *optctx, const char *opt, const char *arg)
1042 {
1043     print_codecs(1);
1044     return 0;
1045 }
1046
1047 int show_bsfs(void *optctx, const char *opt, const char *arg)
1048 {
1049     AVBitStreamFilter *bsf = NULL;
1050
1051     printf("Bitstream filters:\n");
1052     while ((bsf = av_bitstream_filter_next(bsf)))
1053         printf("%s\n", bsf->name);
1054     printf("\n");
1055     return 0;
1056 }
1057
1058 int show_protocols(void *optctx, const char *opt, const char *arg)
1059 {
1060     void *opaque = NULL;
1061     const char *name;
1062
1063     printf("Supported file protocols:\n"
1064            "Input:\n");
1065     while ((name = avio_enum_protocols(&opaque, 0)))
1066         printf("%s\n", name);
1067     printf("Output:\n");
1068     while ((name = avio_enum_protocols(&opaque, 1)))
1069         printf("%s\n", name);
1070     return 0;
1071 }
1072
1073 int show_filters(void *optctx, const char *opt, const char *arg)
1074 {
1075     AVFilter av_unused(**filter) = NULL;
1076     char descr[64], *descr_cur;
1077     int i, j;
1078     const AVFilterPad *pad;
1079
1080     printf("Filters:\n");
1081 #if CONFIG_AVFILTER
1082     while ((filter = av_filter_next(filter)) && *filter) {
1083         descr_cur = descr;
1084         for (i = 0; i < 2; i++) {
1085             if (i) {
1086                 *(descr_cur++) = '-';
1087                 *(descr_cur++) = '>';
1088             }
1089             pad = i ? (*filter)->outputs : (*filter)->inputs;
1090             for (j = 0; pad && pad[j].name; j++) {
1091                 if (descr_cur >= descr + sizeof(descr) - 4)
1092                     break;
1093                 *(descr_cur++) = get_media_type_char(pad[j].type);
1094             }
1095             if (!j)
1096                 *(descr_cur++) = '|';
1097         }
1098         *descr_cur = 0;
1099         printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
1100     }
1101 #endif
1102     return 0;
1103 }
1104
1105 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1106 {
1107     const AVPixFmtDescriptor *pix_desc = NULL;
1108
1109     printf("Pixel formats:\n"
1110            "I.... = Supported Input  format for conversion\n"
1111            ".O... = Supported Output format for conversion\n"
1112            "..H.. = Hardware accelerated format\n"
1113            "...P. = Paletted format\n"
1114            "....B = Bitstream format\n"
1115            "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
1116            "-----\n");
1117
1118 #if !CONFIG_SWSCALE
1119 #   define sws_isSupportedInput(x)  0
1120 #   define sws_isSupportedOutput(x) 0
1121 #endif
1122
1123     while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1124         enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1125         if(!pix_desc->name)
1126             continue;
1127         printf("%c%c%c%c%c %-16s       %d            %2d\n",
1128                sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
1129                sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
1130                pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
1131                pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
1132                pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1133                pix_desc->name,
1134                pix_desc->nb_components,
1135                av_get_bits_per_pixel(pix_desc));
1136     }
1137     return 0;
1138 }
1139
1140 int show_layouts(void *optctx, const char *opt, const char *arg)
1141 {
1142     int i = 0;
1143     uint64_t layout, j;
1144     const char *name, *descr;
1145
1146     printf("Individual channels:\n"
1147            "NAME        DESCRIPTION\n");
1148     for (i = 0; i < 63; i++) {
1149         name = av_get_channel_name((uint64_t)1 << i);
1150         if (!name)
1151             continue;
1152         descr = av_get_channel_description((uint64_t)1 << i);
1153         printf("%-12s%s\n", name, descr);
1154     }
1155     printf("\nStandard channel layouts:\n"
1156            "NAME        DECOMPOSITION\n");
1157     for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
1158         if (name) {
1159             printf("%-12s", name);
1160             for (j = 1; j; j <<= 1)
1161                 if ((layout & j))
1162                     printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
1163             printf("\n");
1164         }
1165     }
1166     return 0;
1167 }
1168
1169 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1170 {
1171     int i;
1172     char fmt_str[128];
1173     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1174         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1175     return 0;
1176 }
1177
1178 static void show_help_codec(const char *name, int encoder)
1179 {
1180     const AVCodecDescriptor *desc;
1181     const AVCodec *codec;
1182
1183     if (!name) {
1184         av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1185         return;
1186     }
1187
1188     codec = encoder ? avcodec_find_encoder_by_name(name) :
1189                       avcodec_find_decoder_by_name(name);
1190
1191     if (codec)
1192         print_codec(codec);
1193     else if ((desc = avcodec_descriptor_get_by_name(name))) {
1194         int printed = 0;
1195
1196         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1197             printed = 1;
1198             print_codec(codec);
1199         }
1200
1201         if (!printed) {
1202             av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
1203                    "but no %s for it are available. FFmpeg might need to be "
1204                    "recompiled with additional external libraries.\n",
1205                    name, encoder ? "encoders" : "decoders");
1206         }
1207     } else {
1208         av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
1209                name);
1210     }
1211 }
1212
1213 static void show_help_demuxer(const char *name)
1214 {
1215     const AVInputFormat *fmt = av_find_input_format(name);
1216
1217     if (!fmt) {
1218         av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1219         return;
1220     }
1221
1222     printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1223
1224     if (fmt->extensions)
1225         printf("    Common extensions: %s.\n", fmt->extensions);
1226
1227     if (fmt->priv_class)
1228         show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1229 }
1230
1231 static void show_help_muxer(const char *name)
1232 {
1233     const AVCodecDescriptor *desc;
1234     const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1235
1236     if (!fmt) {
1237         av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1238         return;
1239     }
1240
1241     printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1242
1243     if (fmt->extensions)
1244         printf("    Common extensions: %s.\n", fmt->extensions);
1245     if (fmt->mime_type)
1246         printf("    Mime type: %s.\n", fmt->mime_type);
1247     if (fmt->video_codec != AV_CODEC_ID_NONE &&
1248         (desc = avcodec_descriptor_get(fmt->video_codec))) {
1249         printf("    Default video codec: %s.\n", desc->name);
1250     }
1251     if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1252         (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1253         printf("    Default audio codec: %s.\n", desc->name);
1254     }
1255     if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1256         (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1257         printf("    Default subtitle codec: %s.\n", desc->name);
1258     }
1259
1260     if (fmt->priv_class)
1261         show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1262 }
1263
1264 int show_help(void *optctx, const char *opt, const char *arg)
1265 {
1266     char *topic, *par;
1267     av_log_set_callback(log_callback_help);
1268
1269     topic = av_strdup(arg ? arg : "");
1270     par = strchr(topic, '=');
1271     if (par)
1272         *par++ = 0;
1273
1274     if (!*topic) {
1275         show_help_default(topic, par);
1276     } else if (!strcmp(topic, "decoder")) {
1277         show_help_codec(par, 0);
1278     } else if (!strcmp(topic, "encoder")) {
1279         show_help_codec(par, 1);
1280     } else if (!strcmp(topic, "demuxer")) {
1281         show_help_demuxer(par);
1282     } else if (!strcmp(topic, "muxer")) {
1283         show_help_muxer(par);
1284     } else {
1285         show_help_default(topic, par);
1286     }
1287
1288     av_freep(&topic);
1289     return 0;
1290 }
1291
1292 int read_yesno(void)
1293 {
1294     int c = getchar();
1295     int yesno = (toupper(c) == 'Y');
1296
1297     while (c != '\n' && c != EOF)
1298         c = getchar();
1299
1300     return yesno;
1301 }
1302
1303 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1304 {
1305     int ret;
1306     FILE *f = fopen(filename, "rb");
1307
1308     if (!f) {
1309         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1310                strerror(errno));
1311         return AVERROR(errno);
1312     }
1313     fseek(f, 0, SEEK_END);
1314     *size = ftell(f);
1315     fseek(f, 0, SEEK_SET);
1316     if (*size == (size_t)-1) {
1317         av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
1318         fclose(f);
1319         return AVERROR(errno);
1320     }
1321     *bufptr = av_malloc(*size + 1);
1322     if (!*bufptr) {
1323         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1324         fclose(f);
1325         return AVERROR(ENOMEM);
1326     }
1327     ret = fread(*bufptr, 1, *size, f);
1328     if (ret < *size) {
1329         av_free(*bufptr);
1330         if (ferror(f)) {
1331             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1332                    filename, strerror(errno));
1333             ret = AVERROR(errno);
1334         } else
1335             ret = AVERROR_EOF;
1336     } else {
1337         ret = 0;
1338         (*bufptr)[(*size)++] = '\0';
1339     }
1340
1341     fclose(f);
1342     return ret;
1343 }
1344
1345 FILE *get_preset_file(char *filename, size_t filename_size,
1346                       const char *preset_name, int is_path,
1347                       const char *codec_name)
1348 {
1349     FILE *f = NULL;
1350     int i;
1351     const char *base[3] = { getenv("FFMPEG_DATADIR"),
1352                             getenv("HOME"),
1353                             FFMPEG_DATADIR, };
1354
1355     if (is_path) {
1356         av_strlcpy(filename, preset_name, filename_size);
1357         f = fopen(filename, "r");
1358     } else {
1359 #ifdef _WIN32
1360         char datadir[MAX_PATH], *ls;
1361         base[2] = NULL;
1362
1363         if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
1364         {
1365             for (ls = datadir; ls < datadir + strlen(datadir); ls++)
1366                 if (*ls == '\\') *ls = '/';
1367
1368             if (ls = strrchr(datadir, '/'))
1369             {
1370                 *ls = 0;
1371                 strncat(datadir, "/ffpresets",  sizeof(datadir) - 1 - strlen(datadir));
1372                 base[2] = datadir;
1373             }
1374         }
1375 #endif
1376         for (i = 0; i < 3 && !f; i++) {
1377             if (!base[i])
1378                 continue;
1379             snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1380                      i != 1 ? "" : "/.ffmpeg", preset_name);
1381             f = fopen(filename, "r");
1382             if (!f && codec_name) {
1383                 snprintf(filename, filename_size,
1384                          "%s%s/%s-%s.ffpreset",
1385                          base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1386                          preset_name);
1387                 f = fopen(filename, "r");
1388             }
1389         }
1390     }
1391
1392     return f;
1393 }
1394
1395 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1396 {
1397     int ret = avformat_match_stream_specifier(s, st, spec);
1398     if (ret < 0)
1399         av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1400     return ret;
1401 }
1402
1403 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1404                                 AVFormatContext *s, AVStream *st, AVCodec *codec)
1405 {
1406     AVDictionary    *ret = NULL;
1407     AVDictionaryEntry *t = NULL;
1408     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1409                                       : AV_OPT_FLAG_DECODING_PARAM;
1410     char          prefix = 0;
1411     const AVClass    *cc = avcodec_get_class();
1412
1413     if (!codec)
1414         codec            = s->oformat ? avcodec_find_encoder(codec_id)
1415                                       : avcodec_find_decoder(codec_id);
1416     if (!codec)
1417         return NULL;
1418
1419     switch (codec->type) {
1420     case AVMEDIA_TYPE_VIDEO:
1421         prefix  = 'v';
1422         flags  |= AV_OPT_FLAG_VIDEO_PARAM;
1423         break;
1424     case AVMEDIA_TYPE_AUDIO:
1425         prefix  = 'a';
1426         flags  |= AV_OPT_FLAG_AUDIO_PARAM;
1427         break;
1428     case AVMEDIA_TYPE_SUBTITLE:
1429         prefix  = 's';
1430         flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
1431         break;
1432     }
1433
1434     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1435         char *p = strchr(t->key, ':');
1436
1437         /* check stream specification in opt name */
1438         if (p)
1439             switch (check_stream_specifier(s, st, p + 1)) {
1440             case  1: *p = 0; break;
1441             case  0:         continue;
1442             default:         return NULL;
1443             }
1444
1445         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1446             (codec && codec->priv_class &&
1447              av_opt_find(&codec->priv_class, t->key, NULL, flags,
1448                          AV_OPT_SEARCH_FAKE_OBJ)))
1449             av_dict_set(&ret, t->key, t->value, 0);
1450         else if (t->key[0] == prefix &&
1451                  av_opt_find(&cc, t->key + 1, NULL, flags,
1452                              AV_OPT_SEARCH_FAKE_OBJ))
1453             av_dict_set(&ret, t->key + 1, t->value, 0);
1454
1455         if (p)
1456             *p = ':';
1457     }
1458     return ret;
1459 }
1460
1461 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1462                                            AVDictionary *codec_opts)
1463 {
1464     int i;
1465     AVDictionary **opts;
1466
1467     if (!s->nb_streams)
1468         return NULL;
1469     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1470     if (!opts) {
1471         av_log(NULL, AV_LOG_ERROR,
1472                "Could not alloc memory for stream options.\n");
1473         return NULL;
1474     }
1475     for (i = 0; i < s->nb_streams; i++)
1476         opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1477                                     s, s->streams[i], NULL);
1478     return opts;
1479 }
1480
1481 void *grow_array(void *array, int elem_size, int *size, int new_size)
1482 {
1483     if (new_size >= INT_MAX / elem_size) {
1484         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1485         exit(1);
1486     }
1487     if (*size < new_size) {
1488         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1489         if (!tmp) {
1490             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1491             exit(1);
1492         }
1493         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1494         *size = new_size;
1495         return tmp;
1496     }
1497     return array;
1498 }
1499
1500 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1501 {
1502     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1503     FrameBuffer *buf;
1504     int i, ret;
1505     int pixel_size;
1506     int h_chroma_shift, v_chroma_shift;
1507     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1508     int w = s->width, h = s->height;
1509
1510     if (!desc)
1511         return AVERROR(EINVAL);
1512     pixel_size = desc->comp[0].step_minus1 + 1;
1513
1514     buf = av_mallocz(sizeof(*buf));
1515     if (!buf)
1516         return AVERROR(ENOMEM);
1517
1518     avcodec_align_dimensions(s, &w, &h);
1519
1520     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1521         w += 2*edge;
1522         h += 2*edge;
1523     }
1524
1525     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1526                               s->pix_fmt, 32)) < 0) {
1527         av_freep(&buf);
1528         av_log(s, AV_LOG_ERROR, "alloc_buffer: av_image_alloc() failed\n");
1529         return ret;
1530     }
1531     /* XXX this shouldn't be needed, but some tests break without this line
1532      * those decoders are buggy and need to be fixed.
1533      * the following tests fail:
1534      * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1535      */
1536     memset(buf->base[0], 128, ret);
1537
1538     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1539     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1540         const int h_shift = i==0 ? 0 : h_chroma_shift;
1541         const int v_shift = i==0 ? 0 : v_chroma_shift;
1542         if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[i] || !buf->base[i])
1543             buf->data[i] = buf->base[i];
1544         else
1545             buf->data[i] = buf->base[i] +
1546                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
1547                                    (pixel_size*edge >> h_shift), 32);
1548     }
1549     buf->w       = s->width;
1550     buf->h       = s->height;
1551     buf->pix_fmt = s->pix_fmt;
1552     buf->pool    = pool;
1553
1554     *pbuf = buf;
1555     return 0;
1556 }
1557
1558 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1559 {
1560     FrameBuffer **pool = s->opaque;
1561     FrameBuffer *buf;
1562     int ret, i;
1563
1564     if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0) {
1565         av_log(s, AV_LOG_ERROR, "codec_get_buffer: image parameters invalid\n");
1566         return -1;
1567     }
1568
1569     if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1570         return ret;
1571
1572     buf              = *pool;
1573     *pool            = buf->next;
1574     buf->next        = NULL;
1575     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1576         av_freep(&buf->base[0]);
1577         av_free(buf);
1578         if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1579             return ret;
1580     }
1581     av_assert0(!buf->refcount);
1582     buf->refcount++;
1583
1584     frame->opaque        = buf;
1585     frame->type          = FF_BUFFER_TYPE_USER;
1586     frame->extended_data = frame->data;
1587     frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
1588     frame->width         = buf->w;
1589     frame->height        = buf->h;
1590     frame->format        = buf->pix_fmt;
1591     frame->sample_aspect_ratio = s->sample_aspect_ratio;
1592
1593     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1594         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
1595         frame->data[i]     = buf->data[i];
1596         frame->linesize[i] = buf->linesize[i];
1597     }
1598
1599     return 0;
1600 }
1601
1602 static void unref_buffer(FrameBuffer *buf)
1603 {
1604     FrameBuffer **pool = buf->pool;
1605
1606     av_assert0(buf->refcount > 0);
1607     buf->refcount--;
1608     if (!buf->refcount) {
1609         FrameBuffer *tmp;
1610         for(tmp= *pool; tmp; tmp= tmp->next)
1611             av_assert1(tmp != buf);
1612
1613         buf->next = *pool;
1614         *pool = buf;
1615     }
1616 }
1617
1618 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1619 {
1620     FrameBuffer *buf = frame->opaque;
1621     int i;
1622
1623     if(frame->type!=FF_BUFFER_TYPE_USER) {
1624         avcodec_default_release_buffer(s, frame);
1625         return;
1626     }
1627
1628     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1629         frame->data[i] = NULL;
1630
1631     unref_buffer(buf);
1632 }
1633
1634 void filter_release_buffer(AVFilterBuffer *fb)
1635 {
1636     FrameBuffer *buf = fb->priv;
1637     av_free(fb);
1638     unref_buffer(buf);
1639 }
1640
1641 void free_buffer_pool(FrameBuffer **pool)
1642 {
1643     FrameBuffer *buf = *pool;
1644     while (buf) {
1645         *pool = buf->next;
1646         av_freep(&buf->base[0]);
1647         av_free(buf);
1648         buf = *pool;
1649     }
1650 }