]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
cmdutils: make this_year extern, so it can be referenced from other .o files
[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 "libavformat/avformat.h"
33 #include "libavfilter/avfilter.h"
34 #include "libavdevice/avdevice.h"
35 #include "libswscale/swscale.h"
36 #include "libswresample/swresample.h"
37 #include "libpostproc/postprocess.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/pixdesc.h"
42 #include "libavutil/eval.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/opt.h"
45 #include "cmdutils.h"
46 #include "version.h"
47 #if CONFIG_NETWORK
48 #include "libavformat/network.h"
49 #endif
50 #if HAVE_SYS_RESOURCE_H
51 #include <sys/resource.h>
52 #endif
53
54 struct SwsContext *sws_opts;
55 AVDictionary *format_opts, *codec_opts;
56
57 const int this_year = 2012;
58
59 static FILE *report_file;
60
61 void init_opts(void)
62 {
63 #if CONFIG_SWSCALE
64     sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
65                               NULL, NULL, NULL);
66 #endif
67 }
68
69 void uninit_opts(void)
70 {
71 #if CONFIG_SWSCALE
72     sws_freeContext(sws_opts);
73     sws_opts = NULL;
74 #endif
75     av_dict_free(&format_opts);
76     av_dict_free(&codec_opts);
77 }
78
79 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
80 {
81     vfprintf(stdout, fmt, vl);
82 }
83
84 static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
85 {
86     va_list vl2;
87     char line[1024];
88     static int print_prefix = 1;
89
90     va_copy(vl2, vl);
91     av_log_default_callback(ptr, level, fmt, vl);
92     av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
93     va_end(vl2);
94     fputs(line, report_file);
95     fflush(report_file);
96 }
97
98 double parse_number_or_die(const char *context, const char *numstr, int type,
99                            double min, double max)
100 {
101     char *tail;
102     const char *error;
103     double d = av_strtod(numstr, &tail);
104     if (*tail)
105         error = "Expected number for %s but found: %s\n";
106     else if (d < min || d > max)
107         error = "The value for %s was %s which is not within %f - %f\n";
108     else if (type == OPT_INT64 && (int64_t)d != d)
109         error = "Expected int64 for %s but found %s\n";
110     else if (type == OPT_INT && (int)d != d)
111         error = "Expected int for %s but found %s\n";
112     else
113         return d;
114     av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
115     exit_program(1);
116     return 0;
117 }
118
119 int64_t parse_time_or_die(const char *context, const char *timestr,
120                           int is_duration)
121 {
122     int64_t us;
123     if (av_parse_time(&us, timestr, is_duration) < 0) {
124         av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
125                is_duration ? "duration" : "date", context, timestr);
126         exit_program(1);
127     }
128     return us;
129 }
130
131 void show_help_options(const OptionDef *options, const char *msg, int mask,
132                        int value)
133 {
134     const OptionDef *po;
135     int first;
136
137     first = 1;
138     for (po = options; po->name != NULL; po++) {
139         char buf[64];
140         if ((po->flags & mask) == value) {
141             if (first) {
142                 printf("%s", msg);
143                 first = 0;
144             }
145             av_strlcpy(buf, po->name, sizeof(buf));
146             if (po->flags & HAS_ARG) {
147                 av_strlcat(buf, " ", sizeof(buf));
148                 av_strlcat(buf, po->argname, sizeof(buf));
149             }
150             printf("-%-17s  %s\n", buf, po->help);
151         }
152     }
153 }
154
155 void show_help_children(const AVClass *class, int flags)
156 {
157     const AVClass *child = NULL;
158     av_opt_show2(&class, NULL, flags, 0);
159     printf("\n");
160
161     while (child = av_opt_child_class_next(class, child))
162         show_help_children(child, flags);
163 }
164
165 static const OptionDef *find_option(const OptionDef *po, const char *name)
166 {
167     const char *p = strchr(name, ':');
168     int len = p ? p - name : strlen(name);
169
170     while (po->name != NULL) {
171         if (!strncmp(name, po->name, len) && strlen(po->name) == len)
172             break;
173         po++;
174     }
175     return po;
176 }
177
178 #if defined(_WIN32) && !defined(__MINGW32CE__)
179 #include <windows.h>
180 /* Will be leaked on exit */
181 static char** win32_argv_utf8 = NULL;
182 static int win32_argc = 0;
183
184 /**
185  * Prepare command line arguments for executable.
186  * For Windows - perform wide-char to UTF-8 conversion.
187  * Input arguments should be main() function arguments.
188  * @param argc_ptr Arguments number (including executable)
189  * @param argv_ptr Arguments list.
190  */
191 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
192 {
193     char *argstr_flat;
194     wchar_t **argv_w;
195     int i, buffsize = 0, offset = 0;
196
197     if (win32_argv_utf8) {
198         *argc_ptr = win32_argc;
199         *argv_ptr = win32_argv_utf8;
200         return;
201     }
202
203     win32_argc = 0;
204     argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
205     if (win32_argc <= 0 || !argv_w)
206         return;
207
208     /* determine the UTF-8 buffer size (including NULL-termination symbols) */
209     for (i = 0; i < win32_argc; i++)
210         buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
211                                         NULL, 0, NULL, NULL);
212
213     win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
214     argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
215     if (win32_argv_utf8 == NULL) {
216         LocalFree(argv_w);
217         return;
218     }
219
220     for (i = 0; i < win32_argc; i++) {
221         win32_argv_utf8[i] = &argstr_flat[offset];
222         offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
223                                       &argstr_flat[offset],
224                                       buffsize - offset, NULL, NULL);
225     }
226     win32_argv_utf8[i] = NULL;
227     LocalFree(argv_w);
228
229     *argc_ptr = win32_argc;
230     *argv_ptr = win32_argv_utf8;
231 }
232 #else
233 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
234 {
235     /* nothing to do */
236 }
237 #endif /* WIN32 && !__MINGW32CE__ */
238
239 int parse_option(void *optctx, const char *opt, const char *arg,
240                  const OptionDef *options)
241 {
242     const OptionDef *po;
243     int bool_val = 1;
244     int *dstcount;
245     void *dst;
246
247     po = find_option(options, opt);
248     if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
249         /* handle 'no' bool option */
250         po = find_option(options, opt + 2);
251         if (!(po->name && (po->flags & OPT_BOOL)))
252             goto unknown_opt;
253         bool_val = 0;
254     }
255     if (!po->name)
256         po = find_option(options, "default");
257     if (!po->name) {
258 unknown_opt:
259         av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
260         return AVERROR(EINVAL);
261     }
262     if (po->flags & HAS_ARG && !arg) {
263         av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
264         return AVERROR(EINVAL);
265     }
266
267     /* new-style options contain an offset into optctx, old-style address of
268      * a global var*/
269     dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
270                                               : po->u.dst_ptr;
271
272     if (po->flags & OPT_SPEC) {
273         SpecifierOpt **so = dst;
274         char *p = strchr(opt, ':');
275
276         dstcount = (int *)(so + 1);
277         *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
278         (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
279         dst = &(*so)[*dstcount - 1].u;
280     }
281
282     if (po->flags & OPT_STRING) {
283         char *str;
284         str = av_strdup(arg);
285         *(char **)dst = str;
286     } else if (po->flags & OPT_BOOL) {
287         *(int *)dst = bool_val;
288     } else if (po->flags & OPT_INT) {
289         *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
290     } else if (po->flags & OPT_INT64) {
291         *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
292     } else if (po->flags & OPT_TIME) {
293         *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
294     } else if (po->flags & OPT_FLOAT) {
295         *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
296     } else if (po->flags & OPT_DOUBLE) {
297         *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
298     } else if (po->u.func_arg) {
299         int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
300                                         : po->u.func_arg(opt, arg);
301         if (ret < 0) {
302             av_log(NULL, AV_LOG_ERROR,
303                    "Failed to set value '%s' for option '%s'\n", arg, opt);
304             return ret;
305         }
306     }
307     if (po->flags & OPT_EXIT)
308         exit_program(0);
309     return !!(po->flags & HAS_ARG);
310 }
311
312 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
313                    void (*parse_arg_function)(void *, const char*))
314 {
315     const char *opt;
316     int optindex, handleoptions = 1, ret;
317
318     /* perform system-dependent conversions for arguments list */
319     prepare_app_arguments(&argc, &argv);
320
321     /* parse options */
322     optindex = 1;
323     while (optindex < argc) {
324         opt = argv[optindex++];
325
326         if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
327             if (opt[1] == '-' && opt[2] == '\0') {
328                 handleoptions = 0;
329                 continue;
330             }
331             opt++;
332
333             if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
334                 exit_program(1);
335             optindex += ret;
336         } else {
337             if (parse_arg_function)
338                 parse_arg_function(optctx, opt);
339         }
340     }
341 }
342
343 /*
344  * Return index of option opt in argv or 0 if not found.
345  */
346 static int locate_option(int argc, char **argv, const OptionDef *options,
347                          const char *optname)
348 {
349     const OptionDef *po;
350     int i;
351
352     for (i = 1; i < argc; i++) {
353         const char *cur_opt = argv[i];
354
355         if (*cur_opt++ != '-')
356             continue;
357
358         po = find_option(options, cur_opt);
359         if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
360             po = find_option(options, cur_opt + 2);
361
362         if ((!po->name && !strcmp(cur_opt, optname)) ||
363              (po->name && !strcmp(optname, po->name)))
364             return i;
365
366         if (!po || po->flags & HAS_ARG)
367             i++;
368     }
369     return 0;
370 }
371
372 static void dump_argument(const char *a)
373 {
374     const unsigned char *p;
375
376     for (p = a; *p; p++)
377         if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
378               *p == '_' || (*p >= 'a' && *p <= 'z')))
379             break;
380     if (!*p) {
381         fputs(a, report_file);
382         return;
383     }
384     fputc('"', report_file);
385     for (p = a; *p; p++) {
386         if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
387             fprintf(report_file, "\\%c", *p);
388         else if (*p < ' ' || *p > '~')
389             fprintf(report_file, "\\x%02x", *p);
390         else
391             fputc(*p, report_file);
392     }
393     fputc('"', report_file);
394 }
395
396 void parse_loglevel(int argc, char **argv, const OptionDef *options)
397 {
398     int idx = locate_option(argc, argv, options, "loglevel");
399     if (!idx)
400         idx = locate_option(argc, argv, options, "v");
401     if (idx && argv[idx + 1])
402         opt_loglevel("loglevel", argv[idx + 1]);
403     idx = locate_option(argc, argv, options, "report");
404     if (idx || getenv("FFREPORT")) {
405         opt_report("report");
406         if (report_file) {
407             int i;
408             fprintf(report_file, "Command line:\n");
409             for (i = 0; i < argc; i++) {
410                 dump_argument(argv[i]);
411                 fputc(i < argc - 1 ? ' ' : '\n', report_file);
412             }
413             fflush(report_file);
414         }
415     }
416 }
417
418 #define FLAGS(o) ((o)->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
419 int opt_default(const char *opt, const char *arg)
420 {
421     const AVOption *oc, *of, *os;
422     char opt_stripped[128];
423     const char *p;
424     const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc;
425
426     if (!(p = strchr(opt, ':')))
427         p = opt + strlen(opt);
428     av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
429
430     if ((oc = av_opt_find(&cc, opt_stripped, NULL, 0,
431                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
432         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
433          (oc = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
434         av_dict_set(&codec_opts, opt, arg, FLAGS(oc));
435     if ((of = av_opt_find(&fc, opt, NULL, 0,
436                           AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
437         av_dict_set(&format_opts, opt, arg, FLAGS(of));
438 #if CONFIG_SWSCALE
439     sc = sws_get_class();
440     if ((os = av_opt_find(&sc, opt, NULL, 0,
441                           AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
442         // XXX we only support sws_flags, not arbitrary sws options
443         int ret = av_opt_set(sws_opts, opt, arg, 0);
444         if (ret < 0) {
445             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
446             return ret;
447         }
448     }
449 #endif
450
451     if (oc || of || os)
452         return 0;
453     av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
454     return AVERROR_OPTION_NOT_FOUND;
455 }
456
457 int opt_loglevel(const char *opt, const char *arg)
458 {
459     const struct { const char *name; int level; } log_levels[] = {
460         { "quiet"  , AV_LOG_QUIET   },
461         { "panic"  , AV_LOG_PANIC   },
462         { "fatal"  , AV_LOG_FATAL   },
463         { "error"  , AV_LOG_ERROR   },
464         { "warning", AV_LOG_WARNING },
465         { "info"   , AV_LOG_INFO    },
466         { "verbose", AV_LOG_VERBOSE },
467         { "debug"  , AV_LOG_DEBUG   },
468     };
469     char *tail;
470     int level;
471     int i;
472
473     for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
474         if (!strcmp(log_levels[i].name, arg)) {
475             av_log_set_level(log_levels[i].level);
476             return 0;
477         }
478     }
479
480     level = strtol(arg, &tail, 10);
481     if (*tail) {
482         av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
483                "Possible levels are numbers or:\n", arg);
484         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
485             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
486         exit_program(1);
487     }
488     av_log_set_level(level);
489     return 0;
490 }
491
492 int opt_report(const char *opt)
493 {
494     char filename[64];
495     time_t now;
496     struct tm *tm;
497
498     if (report_file) /* already opened */
499         return 0;
500     time(&now);
501     tm = localtime(&now);
502     snprintf(filename, sizeof(filename), "%s-%04d%02d%02d-%02d%02d%02d.log",
503              program_name,
504              tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
505              tm->tm_hour, tm->tm_min, tm->tm_sec);
506     report_file = fopen(filename, "w");
507     if (!report_file) {
508         av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
509                filename, strerror(errno));
510         return AVERROR(errno);
511     }
512     av_log_set_callback(log_callback_report);
513     av_log(NULL, AV_LOG_INFO,
514            "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
515            "Report written to \"%s\"\n",
516            program_name,
517            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
518            tm->tm_hour, tm->tm_min, tm->tm_sec,
519            filename);
520     av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
521     return 0;
522 }
523
524 int opt_max_alloc(const char *opt, const char *arg)
525 {
526     char *tail;
527     size_t max;
528
529     max = strtol(arg, &tail, 10);
530     if (*tail) {
531         av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
532         exit_program(1);
533     }
534     av_max_alloc(max);
535     return 0;
536 }
537
538 int opt_codec_debug(const char *opt, const char *arg)
539 {
540     av_log_set_level(AV_LOG_DEBUG);
541     return opt_default(opt, arg);
542 }
543
544 int opt_timelimit(const char *opt, const char *arg)
545 {
546 #if HAVE_SETRLIMIT
547     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
548     struct rlimit rl = { lim, lim + 1 };
549     if (setrlimit(RLIMIT_CPU, &rl))
550         perror("setrlimit");
551 #else
552     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
553 #endif
554     return 0;
555 }
556
557 void print_error(const char *filename, int err)
558 {
559     char errbuf[128];
560     const char *errbuf_ptr = errbuf;
561
562     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
563         errbuf_ptr = strerror(AVUNERROR(err));
564     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
565 }
566
567 static int warned_cfg = 0;
568
569 #define INDENT        1
570 #define SHOW_VERSION  2
571 #define SHOW_CONFIG   4
572 #define SHOW_COPYRIGHT 8
573
574 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
575     if (CONFIG_##LIBNAME) {                                             \
576         const char *indent = flags & INDENT? "  " : "";                 \
577         if (flags & SHOW_VERSION) {                                     \
578             unsigned int version = libname##_version();                 \
579             av_log(NULL, level, "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n",\
580                    indent, #libname,                                    \
581                    LIB##LIBNAME##_VERSION_MAJOR,                        \
582                    LIB##LIBNAME##_VERSION_MINOR,                        \
583                    LIB##LIBNAME##_VERSION_MICRO,                        \
584                    version >> 16, version >> 8 & 0xff, version & 0xff); \
585         }                                                               \
586         if (flags & SHOW_CONFIG) {                                      \
587             const char *cfg = libname##_configuration();                \
588             if (strcmp(FFMPEG_CONFIGURATION, cfg)) {                    \
589                 if (!warned_cfg) {                                      \
590                     av_log(NULL, level,                                 \
591                             "%sWARNING: library configuration mismatch\n", \
592                             indent);                                    \
593                     warned_cfg = 1;                                     \
594                 }                                                       \
595                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
596                         indent, #libname, cfg);                         \
597             }                                                           \
598         }                                                               \
599     }                                                                   \
600
601 static void print_all_libs_info(int flags, int level)
602 {
603     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
604     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
605     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
606     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
607     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
608     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
609     PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);
610     PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
611 }
612
613 static void print_program_info(int flags, int level)
614 {
615     const char *indent = flags & INDENT? "  " : "";
616
617     av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
618     if (flags & SHOW_COPYRIGHT)
619         av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
620                program_birth_year, this_year);
621     av_log(NULL, level, "\n");
622     av_log(NULL, level, "%sbuilt on %s %s with %s %s\n",
623            indent, __DATE__, __TIME__, CC_TYPE, CC_VERSION);
624     av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
625 }
626
627 void show_banner(int argc, char **argv, const OptionDef *options)
628 {
629     int idx = locate_option(argc, argv, options, "version");
630     if (idx)
631         return;
632
633     print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
634     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_INFO);
635     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
636 }
637
638 int opt_version(const char *opt, const char *arg) {
639     av_log_set_callback(log_callback_help);
640     print_program_info (0           , AV_LOG_INFO);
641     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
642     return 0;
643 }
644
645 int opt_license(const char *opt, const char *arg)
646 {
647     printf(
648 #if CONFIG_NONFREE
649     "This version of %s has nonfree parts compiled in.\n"
650     "Therefore it is not legally redistributable.\n",
651     program_name
652 #elif CONFIG_GPLV3
653     "%s is free software; you can redistribute it and/or modify\n"
654     "it under the terms of the GNU General Public License as published by\n"
655     "the Free Software Foundation; either version 3 of the License, or\n"
656     "(at your option) any later version.\n"
657     "\n"
658     "%s is distributed in the hope that it will be useful,\n"
659     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
660     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
661     "GNU General Public License for more details.\n"
662     "\n"
663     "You should have received a copy of the GNU General Public License\n"
664     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
665     program_name, program_name, program_name
666 #elif CONFIG_GPL
667     "%s is free software; you can redistribute it and/or modify\n"
668     "it under the terms of the GNU General Public License as published by\n"
669     "the Free Software Foundation; either version 2 of the License, or\n"
670     "(at your option) any later version.\n"
671     "\n"
672     "%s is distributed in the hope that it will be useful,\n"
673     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
674     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
675     "GNU General Public License for more details.\n"
676     "\n"
677     "You should have received a copy of the GNU General Public License\n"
678     "along with %s; if not, write to the Free Software\n"
679     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
680     program_name, program_name, program_name
681 #elif CONFIG_LGPLV3
682     "%s is free software; you can redistribute it and/or modify\n"
683     "it under the terms of the GNU Lesser General Public License as published by\n"
684     "the Free Software Foundation; either version 3 of the License, or\n"
685     "(at your option) any later version.\n"
686     "\n"
687     "%s is distributed in the hope that it will be useful,\n"
688     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
689     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
690     "GNU Lesser General Public License for more details.\n"
691     "\n"
692     "You should have received a copy of the GNU Lesser General Public License\n"
693     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
694     program_name, program_name, program_name
695 #else
696     "%s is free software; you can redistribute it and/or\n"
697     "modify it under the terms of the GNU Lesser General Public\n"
698     "License as published by the Free Software Foundation; either\n"
699     "version 2.1 of the License, or (at your option) any later version.\n"
700     "\n"
701     "%s is distributed in the hope that it will be useful,\n"
702     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
703     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
704     "Lesser General Public License for more details.\n"
705     "\n"
706     "You should have received a copy of the GNU Lesser General Public\n"
707     "License along with %s; if not, write to the Free Software\n"
708     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
709     program_name, program_name, program_name
710 #endif
711     );
712     return 0;
713 }
714
715 int opt_formats(const char *opt, const char *arg)
716 {
717     AVInputFormat *ifmt  = NULL;
718     AVOutputFormat *ofmt = NULL;
719     const char *last_name;
720
721     printf("File formats:\n"
722            " D. = Demuxing supported\n"
723            " .E = Muxing supported\n"
724            " --\n");
725     last_name = "000";
726     for (;;) {
727         int decode = 0;
728         int encode = 0;
729         const char *name      = NULL;
730         const char *long_name = NULL;
731
732         while ((ofmt = av_oformat_next(ofmt))) {
733             if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
734                 strcmp(ofmt->name, last_name) > 0) {
735                 name      = ofmt->name;
736                 long_name = ofmt->long_name;
737                 encode    = 1;
738             }
739         }
740         while ((ifmt = av_iformat_next(ifmt))) {
741             if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
742                 strcmp(ifmt->name, last_name) > 0) {
743                 name      = ifmt->name;
744                 long_name = ifmt->long_name;
745                 encode    = 0;
746             }
747             if (name && strcmp(ifmt->name, name) == 0)
748                 decode = 1;
749         }
750         if (name == NULL)
751             break;
752         last_name = name;
753
754         printf(" %s%s %-15s %s\n",
755                decode ? "D" : " ",
756                encode ? "E" : " ",
757                name,
758             long_name ? long_name:" ");
759     }
760     return 0;
761 }
762
763 int opt_codecs(const char *opt, const char *arg)
764 {
765     AVCodec *p = NULL, *p2;
766     const char *last_name;
767     printf("Codecs:\n"
768            " D..... = Decoding supported\n"
769            " .E.... = Encoding supported\n"
770            " ..V... = Video codec\n"
771            " ..A... = Audio codec\n"
772            " ..S... = Subtitle codec\n"
773            " ...S.. = Supports draw_horiz_band\n"
774            " ....D. = Supports direct rendering method 1\n"
775            " .....T = Supports weird frame truncation\n"
776            " ------\n");
777     last_name= "000";
778     for (;;) {
779         int decode = 0;
780         int encode = 0;
781         int cap    = 0;
782         const char *type_str;
783
784         p2 = NULL;
785         while ((p = av_codec_next(p))) {
786             if ((p2 == NULL || strcmp(p->name, p2->name) < 0) &&
787                 strcmp(p->name, last_name) > 0) {
788                 p2 = p;
789                 decode = encode = cap = 0;
790             }
791             if (p2 && strcmp(p->name, p2->name) == 0) {
792                 if (p->decode)
793                     decode = 1;
794                 if (p->encode)
795                     encode = 1;
796                 cap |= p->capabilities;
797             }
798         }
799         if (p2 == NULL)
800             break;
801         last_name = p2->name;
802
803         switch (p2->type) {
804         case AVMEDIA_TYPE_VIDEO:
805             type_str = "V";
806             break;
807         case AVMEDIA_TYPE_AUDIO:
808             type_str = "A";
809             break;
810         case AVMEDIA_TYPE_SUBTITLE:
811             type_str = "S";
812             break;
813         default:
814             type_str = "?";
815             break;
816         }
817         printf(" %s%s%s%s%s%s %-15s %s",
818                decode ? "D" : (/* p2->decoder ? "d" : */ " "),
819                encode ? "E" : " ",
820                type_str,
821                cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S" : " ",
822                cap & CODEC_CAP_DR1 ? "D" : " ",
823                cap & CODEC_CAP_TRUNCATED ? "T" : " ",
824                p2->name,
825                p2->long_name ? p2->long_name : "");
826 #if 0
827             if (p2->decoder && decode == 0)
828                 printf(" use %s for decoding", p2->decoder->name);
829 #endif
830         printf("\n");
831     }
832     printf("\n");
833     printf("Note, the names of encoders and decoders do not always match, so there are\n"
834            "several cases where the above table shows encoder only or decoder only entries\n"
835            "even though both encoding and decoding are supported. For example, the h263\n"
836            "decoder corresponds to the h263 and h263p encoders, for file formats it is even\n"
837            "worse.\n");
838     return 0;
839 }
840
841 int opt_bsfs(const char *opt, const char *arg)
842 {
843     AVBitStreamFilter *bsf = NULL;
844
845     printf("Bitstream filters:\n");
846     while ((bsf = av_bitstream_filter_next(bsf)))
847         printf("%s\n", bsf->name);
848     printf("\n");
849     return 0;
850 }
851
852 int opt_protocols(const char *opt, const char *arg)
853 {
854     URLProtocol *up=NULL;
855
856     printf("Supported file protocols:\n"
857            "I.. = Input  supported\n"
858            ".O. = Output supported\n"
859            "..S = Seek   supported\n"
860            "FLAGS NAME\n"
861            "----- \n");
862     while((up = av_protocol_next(up)))
863         printf("%c%c%c   %s\n",
864                up->url_read  ? 'I' : '.',
865                up->url_write ? 'O' : '.',
866                up->url_seek  ? 'S' : '.',
867                up->name);
868     return 0;
869 }
870
871 int opt_filters(const char *opt, const char *arg)
872 {
873     AVFilter av_unused(**filter) = NULL;
874
875     printf("Filters:\n");
876 #if CONFIG_AVFILTER
877     while ((filter = av_filter_next(filter)) && *filter)
878         printf("%-16s %s\n", (*filter)->name, (*filter)->description);
879 #endif
880     return 0;
881 }
882
883 int opt_pix_fmts(const char *opt, const char *arg)
884 {
885     enum PixelFormat pix_fmt;
886
887     printf("Pixel formats:\n"
888            "I.... = Supported Input  format for conversion\n"
889            ".O... = Supported Output format for conversion\n"
890            "..H.. = Hardware accelerated format\n"
891            "...P. = Paletted format\n"
892            "....B = Bitstream format\n"
893            "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
894            "-----\n");
895
896 #if !CONFIG_SWSCALE
897 #   define sws_isSupportedInput(x)  0
898 #   define sws_isSupportedOutput(x) 0
899 #endif
900
901     for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
902         const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
903         if(!pix_desc->name)
904             continue;
905         printf("%c%c%c%c%c %-16s       %d            %2d\n",
906                sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
907                sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
908                pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
909                pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
910                pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
911                pix_desc->name,
912                pix_desc->nb_components,
913                av_get_bits_per_pixel(pix_desc));
914     }
915     return 0;
916 }
917
918 int show_sample_fmts(const char *opt, const char *arg)
919 {
920     int i;
921     char fmt_str[128];
922     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
923         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
924     return 0;
925 }
926
927 int read_yesno(void)
928 {
929     int c = getchar();
930     int yesno = (toupper(c) == 'Y');
931
932     while (c != '\n' && c != EOF)
933         c = getchar();
934
935     return yesno;
936 }
937
938 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
939 {
940     int ret;
941     FILE *f = fopen(filename, "rb");
942
943     if (!f) {
944         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
945                strerror(errno));
946         return AVERROR(errno);
947     }
948     fseek(f, 0, SEEK_END);
949     *size = ftell(f);
950     fseek(f, 0, SEEK_SET);
951     *bufptr = av_malloc(*size + 1);
952     if (!*bufptr) {
953         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
954         fclose(f);
955         return AVERROR(ENOMEM);
956     }
957     ret = fread(*bufptr, 1, *size, f);
958     if (ret < *size) {
959         av_free(*bufptr);
960         if (ferror(f)) {
961             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
962                    filename, strerror(errno));
963             ret = AVERROR(errno);
964         } else
965             ret = AVERROR_EOF;
966     } else {
967         ret = 0;
968         (*bufptr)[*size++] = '\0';
969     }
970
971     fclose(f);
972     return ret;
973 }
974
975 FILE *get_preset_file(char *filename, size_t filename_size,
976                       const char *preset_name, int is_path,
977                       const char *codec_name)
978 {
979     FILE *f = NULL;
980     int i;
981     const char *base[3] = { getenv("FFMPEG_DATADIR"),
982                             getenv("HOME"),
983                             FFMPEG_DATADIR, };
984
985     if (is_path) {
986         av_strlcpy(filename, preset_name, filename_size);
987         f = fopen(filename, "r");
988     } else {
989 #ifdef _WIN32
990         char datadir[MAX_PATH], *ls;
991         base[2] = NULL;
992
993         if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
994         {
995             for (ls = datadir; ls < datadir + strlen(datadir); ls++)
996                 if (*ls == '\\') *ls = '/';
997
998             if (ls = strrchr(datadir, '/'))
999             {
1000                 *ls = 0;
1001                 strncat(datadir, "/ffpresets",  sizeof(datadir) - 1 - strlen(datadir));
1002                 base[2] = datadir;
1003             }
1004         }
1005 #endif
1006         for (i = 0; i < 3 && !f; i++) {
1007             if (!base[i])
1008                 continue;
1009             snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1010                      i != 1 ? "" : "/.ffmpeg", preset_name);
1011             f = fopen(filename, "r");
1012             if (!f && codec_name) {
1013                 snprintf(filename, filename_size,
1014                          "%s%s/%s-%s.ffpreset",
1015                          base[i],  i != 1 ? "" : "/.ffmpeg", codec_name,
1016                          preset_name);
1017                 f = fopen(filename, "r");
1018             }
1019         }
1020     }
1021
1022     return f;
1023 }
1024
1025 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1026 {
1027     if (*spec <= '9' && *spec >= '0') /* opt:index */
1028         return strtol(spec, NULL, 0) == st->index;
1029     else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1030              *spec == 't') { /* opt:[vasdt] */
1031         enum AVMediaType type;
1032
1033         switch (*spec++) {
1034         case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
1035         case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
1036         case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
1037         case 'd': type = AVMEDIA_TYPE_DATA;       break;
1038         case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1039         default: abort(); // never reached, silence warning
1040         }
1041         if (type != st->codec->codec_type)
1042             return 0;
1043         if (*spec++ == ':') { /* possibly followed by :index */
1044             int i, index = strtol(spec, NULL, 0);
1045             for (i = 0; i < s->nb_streams; i++)
1046                 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1047                    return i == st->index;
1048             return 0;
1049         }
1050         return 1;
1051     } else if (*spec == 'p' && *(spec + 1) == ':') {
1052         int prog_id, i, j;
1053         char *endptr;
1054         spec += 2;
1055         prog_id = strtol(spec, &endptr, 0);
1056         for (i = 0; i < s->nb_programs; i++) {
1057             if (s->programs[i]->id != prog_id)
1058                 continue;
1059
1060             if (*endptr++ == ':') {
1061                 int stream_idx = strtol(endptr, NULL, 0);
1062                 return stream_idx >= 0 &&
1063                     stream_idx < s->programs[i]->nb_stream_indexes &&
1064                     st->index == s->programs[i]->stream_index[stream_idx];
1065             }
1066
1067             for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1068                 if (st->index == s->programs[i]->stream_index[j])
1069                     return 1;
1070         }
1071         return 0;
1072     } else if (!*spec) /* empty specifier, matches everything */
1073         return 1;
1074
1075     av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1076     return AVERROR(EINVAL);
1077 }
1078
1079 AVDictionary *filter_codec_opts(AVDictionary *opts, AVCodec *codec,
1080                                 AVFormatContext *s, AVStream *st)
1081 {
1082     AVDictionary    *ret = NULL;
1083     AVDictionaryEntry *t = NULL;
1084     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1085                                       : AV_OPT_FLAG_DECODING_PARAM;
1086     char          prefix = 0;
1087     const AVClass    *cc = avcodec_get_class();
1088
1089     if (!codec)
1090         return NULL;
1091
1092     switch (codec->type) {
1093     case AVMEDIA_TYPE_VIDEO:
1094         prefix  = 'v';
1095         flags  |= AV_OPT_FLAG_VIDEO_PARAM;
1096         break;
1097     case AVMEDIA_TYPE_AUDIO:
1098         prefix  = 'a';
1099         flags  |= AV_OPT_FLAG_AUDIO_PARAM;
1100         break;
1101     case AVMEDIA_TYPE_SUBTITLE:
1102         prefix  = 's';
1103         flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
1104         break;
1105     }
1106
1107     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1108         char *p = strchr(t->key, ':');
1109
1110         /* check stream specification in opt name */
1111         if (p)
1112             switch (check_stream_specifier(s, st, p + 1)) {
1113             case  1: *p = 0; break;
1114             case  0:         continue;
1115             default:         return NULL;
1116             }
1117
1118         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1119             (codec && codec->priv_class &&
1120              av_opt_find(&codec->priv_class, t->key, NULL, flags,
1121                          AV_OPT_SEARCH_FAKE_OBJ)))
1122             av_dict_set(&ret, t->key, t->value, 0);
1123         else if (t->key[0] == prefix &&
1124                  av_opt_find(&cc, t->key + 1, NULL, flags,
1125                              AV_OPT_SEARCH_FAKE_OBJ))
1126             av_dict_set(&ret, t->key + 1, t->value, 0);
1127
1128         if (p)
1129             *p = ':';
1130     }
1131     return ret;
1132 }
1133
1134 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1135                                            AVDictionary *codec_opts)
1136 {
1137     int i;
1138     AVDictionary **opts;
1139
1140     if (!s->nb_streams)
1141         return NULL;
1142     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1143     if (!opts) {
1144         av_log(NULL, AV_LOG_ERROR,
1145                "Could not alloc memory for stream options.\n");
1146         return NULL;
1147     }
1148     for (i = 0; i < s->nb_streams; i++)
1149         opts[i] = filter_codec_opts(codec_opts, avcodec_find_decoder(s->streams[i]->codec->codec_id),
1150                                     s, s->streams[i]);
1151     return opts;
1152 }
1153
1154 void *grow_array(void *array, int elem_size, int *size, int new_size)
1155 {
1156     if (new_size >= INT_MAX / elem_size) {
1157         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1158         exit_program(1);
1159     }
1160     if (*size < new_size) {
1161         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1162         if (!tmp) {
1163             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1164             exit_program(1);
1165         }
1166         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1167         *size = new_size;
1168         return tmp;
1169     }
1170     return array;
1171 }