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