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