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