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