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