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