]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
ff*: add -max_alloc command line option
[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_max_alloc(const char *opt, const char *arg)
514 {
515     char *tail;
516     size_t max;
517
518     max = strtol(arg, &tail, 10);
519     if (*tail) {
520         av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
521         exit_program(1);
522     }
523     av_max_alloc(max);
524     return 0;
525 }
526
527 int opt_codec_debug(const char *opt, const char *arg)
528 {
529     av_log_set_level(AV_LOG_DEBUG);
530     return opt_default(opt, arg);
531 }
532
533 int opt_timelimit(const char *opt, const char *arg)
534 {
535 #if HAVE_SETRLIMIT
536     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
537     struct rlimit rl = { lim, lim + 1 };
538     if (setrlimit(RLIMIT_CPU, &rl))
539         perror("setrlimit");
540 #else
541     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
542 #endif
543     return 0;
544 }
545
546 void print_error(const char *filename, int err)
547 {
548     char errbuf[128];
549     const char *errbuf_ptr = errbuf;
550
551     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
552         errbuf_ptr = strerror(AVUNERROR(err));
553     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
554 }
555
556 static int warned_cfg = 0;
557
558 #define INDENT        1
559 #define SHOW_VERSION  2
560 #define SHOW_CONFIG   4
561
562 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
563     if (CONFIG_##LIBNAME) {                                             \
564         const char *indent = flags & INDENT? "  " : "";                 \
565         if (flags & SHOW_VERSION) {                                     \
566             unsigned int version = libname##_version();                 \
567             av_log(NULL, level, "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n",\
568                    indent, #libname,                                    \
569                    LIB##LIBNAME##_VERSION_MAJOR,                        \
570                    LIB##LIBNAME##_VERSION_MINOR,                        \
571                    LIB##LIBNAME##_VERSION_MICRO,                        \
572                    version >> 16, version >> 8 & 0xff, version & 0xff); \
573         }                                                               \
574         if (flags & SHOW_CONFIG) {                                      \
575             const char *cfg = libname##_configuration();                \
576             if (strcmp(FFMPEG_CONFIGURATION, cfg)) {                    \
577                 if (!warned_cfg) {                                      \
578                     av_log(NULL, level,                                 \
579                             "%sWARNING: library configuration mismatch\n", \
580                             indent);                                    \
581                     warned_cfg = 1;                                     \
582                 }                                                       \
583                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
584                         indent, #libname, cfg);                         \
585             }                                                           \
586         }                                                               \
587     }                                                                   \
588
589 static void print_all_libs_info(int flags, int level)
590 {
591     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
592     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
593     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
594     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
595     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
596     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
597     PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);
598     PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
599 }
600
601 void show_banner(int argc, char **argv, const OptionDef *options)
602 {
603     int idx = locate_option(argc, argv, options, "version");
604     if (idx)
605         return;
606
607     av_log(NULL, AV_LOG_INFO, "%s version " FFMPEG_VERSION ", Copyright (c) %d-%d the FFmpeg developers\n",
608            program_name, program_birth_year, this_year);
609     av_log(NULL, AV_LOG_INFO, "  built on %s %s with %s %s\n",
610            __DATE__, __TIME__, CC_TYPE, CC_VERSION);
611     av_log(NULL, AV_LOG_INFO, "  configuration: " FFMPEG_CONFIGURATION "\n");
612     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_INFO);
613     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
614 }
615
616 int opt_version(const char *opt, const char *arg) {
617     av_log_set_callback(log_callback_help);
618     printf("%s " FFMPEG_VERSION "\n", program_name);
619     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
620     return 0;
621 }
622
623 int opt_license(const char *opt, const char *arg)
624 {
625     printf(
626 #if CONFIG_NONFREE
627     "This version of %s has nonfree parts compiled in.\n"
628     "Therefore it is not legally redistributable.\n",
629     program_name
630 #elif CONFIG_GPLV3
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 3 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, see <http://www.gnu.org/licenses/>.\n",
643     program_name, program_name, program_name
644 #elif CONFIG_GPL
645     "%s is free software; you can redistribute it and/or modify\n"
646     "it under the terms of the GNU General Public License as published by\n"
647     "the Free Software Foundation; either version 2 of the License, or\n"
648     "(at your option) any later version.\n"
649     "\n"
650     "%s is distributed in the hope that it will be useful,\n"
651     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
652     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
653     "GNU General Public License for more details.\n"
654     "\n"
655     "You should have received a copy of the GNU General Public License\n"
656     "along with %s; if not, write to the Free Software\n"
657     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
658     program_name, program_name, program_name
659 #elif CONFIG_LGPLV3
660     "%s is free software; you can redistribute it and/or modify\n"
661     "it under the terms of the GNU Lesser General Public License as published by\n"
662     "the Free Software Foundation; either version 3 of the License, or\n"
663     "(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\n"
668     "GNU Lesser General Public License for more details.\n"
669     "\n"
670     "You should have received a copy of the GNU Lesser General Public License\n"
671     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
672     program_name, program_name, program_name
673 #else
674     "%s is free software; you can redistribute it and/or\n"
675     "modify it under the terms of the GNU Lesser General Public\n"
676     "License as published by the Free Software Foundation; either\n"
677     "version 2.1 of the License, or (at your option) any later version.\n"
678     "\n"
679     "%s is distributed in the hope that it will be useful,\n"
680     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
681     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
682     "Lesser General Public License for more details.\n"
683     "\n"
684     "You should have received a copy of the GNU Lesser General Public\n"
685     "License along with %s; if not, write to the Free Software\n"
686     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
687     program_name, program_name, program_name
688 #endif
689     );
690     return 0;
691 }
692
693 int opt_formats(const char *opt, const char *arg)
694 {
695     AVInputFormat *ifmt=NULL;
696     AVOutputFormat *ofmt=NULL;
697     const char *last_name;
698
699     printf(
700         "File formats:\n"
701         " D. = Demuxing supported\n"
702         " .E = Muxing supported\n"
703         " --\n");
704     last_name= "000";
705     for(;;){
706         int decode=0;
707         int encode=0;
708         const char *name=NULL;
709         const char *long_name=NULL;
710
711         while((ofmt= av_oformat_next(ofmt))) {
712             if((name == NULL || strcmp(ofmt->name, name)<0) &&
713                 strcmp(ofmt->name, last_name)>0){
714                 name= ofmt->name;
715                 long_name= ofmt->long_name;
716                 encode=1;
717             }
718         }
719         while((ifmt= av_iformat_next(ifmt))) {
720             if((name == NULL || strcmp(ifmt->name, name)<0) &&
721                 strcmp(ifmt->name, last_name)>0){
722                 name= ifmt->name;
723                 long_name= ifmt->long_name;
724                 encode=0;
725             }
726             if(name && strcmp(ifmt->name, name)==0)
727                 decode=1;
728         }
729         if(name==NULL)
730             break;
731         last_name= name;
732
733         printf(
734             " %s%s %-15s %s\n",
735             decode ? "D":" ",
736             encode ? "E":" ",
737             name,
738             long_name ? long_name:" ");
739     }
740     return 0;
741 }
742
743 int opt_codecs(const char *opt, const char *arg)
744 {
745     AVCodec *p=NULL, *p2;
746     const char *last_name;
747     printf(
748         "Codecs:\n"
749         " D..... = Decoding supported\n"
750         " .E.... = Encoding supported\n"
751         " ..V... = Video codec\n"
752         " ..A... = Audio codec\n"
753         " ..S... = Subtitle codec\n"
754         " ...S.. = Supports draw_horiz_band\n"
755         " ....D. = Supports direct rendering method 1\n"
756         " .....T = Supports weird frame truncation\n"
757         " ------\n");
758     last_name= "000";
759     for(;;){
760         int decode=0;
761         int encode=0;
762         int cap=0;
763         const char *type_str;
764
765         p2=NULL;
766         while((p= av_codec_next(p))) {
767             if((p2==NULL || strcmp(p->name, p2->name)<0) &&
768                 strcmp(p->name, last_name)>0){
769                 p2= p;
770                 decode= encode= cap=0;
771             }
772             if(p2 && strcmp(p->name, p2->name)==0){
773                 if(p->decode) decode=1;
774                 if(p->encode) encode=1;
775                 cap |= p->capabilities;
776             }
777         }
778         if(p2==NULL)
779             break;
780         last_name= p2->name;
781
782         switch(p2->type) {
783         case AVMEDIA_TYPE_VIDEO:
784             type_str = "V";
785             break;
786         case AVMEDIA_TYPE_AUDIO:
787             type_str = "A";
788             break;
789         case AVMEDIA_TYPE_SUBTITLE:
790             type_str = "S";
791             break;
792         default:
793             type_str = "?";
794             break;
795         }
796         printf(
797             " %s%s%s%s%s%s %-15s %s",
798             decode ? "D": (/*p2->decoder ? "d":*/" "),
799             encode ? "E":" ",
800             type_str,
801             cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
802             cap & CODEC_CAP_DR1 ? "D":" ",
803             cap & CODEC_CAP_TRUNCATED ? "T":" ",
804             p2->name,
805             p2->long_name ? p2->long_name : "");
806        /* if(p2->decoder && decode==0)
807             printf(" use %s for decoding", p2->decoder->name);*/
808         printf("\n");
809     }
810     printf("\n");
811     printf(
812 "Note, the names of encoders and decoders do not always match, so there are\n"
813 "several cases where the above table shows encoder only or decoder only entries\n"
814 "even though both encoding and decoding are supported. For example, the h263\n"
815 "decoder corresponds to the h263 and h263p encoders, for file formats it is even\n"
816 "worse.\n");
817     return 0;
818 }
819
820 int opt_bsfs(const char *opt, const char *arg)
821 {
822     AVBitStreamFilter *bsf=NULL;
823
824     printf("Bitstream filters:\n");
825     while((bsf = av_bitstream_filter_next(bsf)))
826         printf("%s\n", bsf->name);
827     printf("\n");
828     return 0;
829 }
830
831 int opt_protocols(const char *opt, const char *arg)
832 {
833     URLProtocol *up=NULL;
834
835     printf("Supported file protocols:\n"
836            "I.. = Input  supported\n"
837            ".O. = Output supported\n"
838            "..S = Seek   supported\n"
839            "FLAGS NAME\n"
840            "----- \n");
841     while((up = av_protocol_next(up)))
842         printf("%c%c%c   %s\n",
843                up->url_read  ? 'I' : '.',
844                up->url_write ? 'O' : '.',
845                up->url_seek  ? 'S' : '.',
846                up->name);
847     return 0;
848 }
849
850 int opt_filters(const char *opt, const char *arg)
851 {
852     AVFilter av_unused(**filter) = NULL;
853
854     printf("Filters:\n");
855 #if CONFIG_AVFILTER
856     while ((filter = av_filter_next(filter)) && *filter)
857         printf("%-16s %s\n", (*filter)->name, (*filter)->description);
858 #endif
859     return 0;
860 }
861
862 int opt_pix_fmts(const char *opt, const char *arg)
863 {
864     enum PixelFormat pix_fmt;
865
866     printf(
867         "Pixel formats:\n"
868         "I.... = Supported Input  format for conversion\n"
869         ".O... = Supported Output format for conversion\n"
870         "..H.. = Hardware accelerated format\n"
871         "...P. = Paletted format\n"
872         "....B = Bitstream format\n"
873         "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
874         "-----\n");
875
876 #if !CONFIG_SWSCALE
877 #   define sws_isSupportedInput(x)  0
878 #   define sws_isSupportedOutput(x) 0
879 #endif
880
881     for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
882         const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
883         if(!pix_desc->name)
884             continue;
885         printf("%c%c%c%c%c %-16s       %d            %2d\n",
886                sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
887                sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
888                pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
889                pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
890                pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
891                pix_desc->name,
892                pix_desc->nb_components,
893                av_get_bits_per_pixel(pix_desc));
894     }
895     return 0;
896 }
897
898 int show_sample_fmts(const char *opt, const char *arg)
899 {
900     int i;
901     char fmt_str[128];
902     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
903         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
904     return 0;
905 }
906
907 int read_yesno(void)
908 {
909     int c = getchar();
910     int yesno = (toupper(c) == 'Y');
911
912     while (c != '\n' && c != EOF)
913         c = getchar();
914
915     return yesno;
916 }
917
918 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
919 {
920     int ret;
921     FILE *f = fopen(filename, "rb");
922
923     if (!f) {
924         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename, strerror(errno));
925         return AVERROR(errno);
926     }
927     fseek(f, 0, SEEK_END);
928     *size = ftell(f);
929     fseek(f, 0, SEEK_SET);
930     *bufptr = av_malloc(*size + 1);
931     if (!*bufptr) {
932         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
933         fclose(f);
934         return AVERROR(ENOMEM);
935     }
936     ret = fread(*bufptr, 1, *size, f);
937     if (ret < *size) {
938         av_free(*bufptr);
939         if (ferror(f)) {
940             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
941                    filename, strerror(errno));
942             ret = AVERROR(errno);
943         } else
944             ret = AVERROR_EOF;
945     } else {
946         ret = 0;
947         (*bufptr)[*size++] = '\0';
948     }
949
950     fclose(f);
951     return ret;
952 }
953
954 FILE *get_preset_file(char *filename, size_t filename_size,
955                       const char *preset_name, int is_path, const char *codec_name)
956 {
957     FILE *f = NULL;
958     int i;
959     const char *base[3]= { getenv("FFMPEG_DATADIR"),
960                            getenv("HOME"),
961                            FFMPEG_DATADIR,
962                          };
963
964     if (is_path) {
965         av_strlcpy(filename, preset_name, filename_size);
966         f = fopen(filename, "r");
967     } else {
968 #ifdef _WIN32
969         char datadir[MAX_PATH], *ls;
970         base[2] = NULL;
971
972         if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
973         {
974             for (ls = datadir; ls < datadir + strlen(datadir); ls++)
975                 if (*ls == '\\') *ls = '/';
976
977             if (ls = strrchr(datadir, '/'))
978             {
979                 *ls = 0;
980                 strncat(datadir, "/ffpresets",  sizeof(datadir) - 1 - strlen(datadir));
981                 base[2] = datadir;
982             }
983         }
984 #endif
985         for (i = 0; i < 3 && !f; i++) {
986             if (!base[i])
987                 continue;
988             snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i], i != 1 ? "" : "/.ffmpeg", preset_name);
989             f = fopen(filename, "r");
990             if (!f && codec_name) {
991                 snprintf(filename, filename_size,
992                          "%s%s/%s-%s.ffpreset", base[i],  i != 1 ? "" : "/.ffmpeg", codec_name, preset_name);
993                 f = fopen(filename, "r");
994             }
995         }
996     }
997
998     return f;
999 }
1000
1001 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1002 {
1003     if (*spec <= '9' && *spec >= '0')                                        /* opt:index */
1004         return strtol(spec, NULL, 0) == st->index;
1005     else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' || *spec == 't') { /* opt:[vasdt] */
1006         enum AVMediaType type;
1007
1008         switch (*spec++) {
1009         case 'v': type = AVMEDIA_TYPE_VIDEO;    break;
1010         case 'a': type = AVMEDIA_TYPE_AUDIO;    break;
1011         case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
1012         case 'd': type = AVMEDIA_TYPE_DATA;     break;
1013         case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1014         default: abort(); // never reached, silence warning
1015         }
1016         if (type != st->codec->codec_type)
1017             return 0;
1018         if (*spec++ == ':') {                                   /* possibly followed by :index */
1019             int i, index = strtol(spec, NULL, 0);
1020             for (i = 0; i < s->nb_streams; i++)
1021                 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1022                    return i == st->index;
1023             return 0;
1024         }
1025         return 1;
1026     } else if (*spec == 'p' && *(spec + 1) == ':') {
1027         int prog_id, i, j;
1028         char *endptr;
1029         spec += 2;
1030         prog_id = strtol(spec, &endptr, 0);
1031         for (i = 0; i < s->nb_programs; i++) {
1032             if (s->programs[i]->id != prog_id)
1033                 continue;
1034
1035             if (*endptr++ == ':') {
1036                 int stream_idx = strtol(endptr, NULL, 0);
1037                 return (stream_idx >= 0 && stream_idx < s->programs[i]->nb_stream_indexes &&
1038                         st->index == s->programs[i]->stream_index[stream_idx]);
1039             }
1040
1041             for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1042                 if (st->index == s->programs[i]->stream_index[j])
1043                     return 1;
1044         }
1045         return 0;
1046     } else if (!*spec) /* empty specifier, matches everything */
1047         return 1;
1048
1049     av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1050     return AVERROR(EINVAL);
1051 }
1052
1053 AVDictionary *filter_codec_opts(AVDictionary *opts, AVCodec *codec, AVFormatContext *s, AVStream *st)
1054 {
1055     AVDictionary    *ret = NULL;
1056     AVDictionaryEntry *t = NULL;
1057     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM : AV_OPT_FLAG_DECODING_PARAM;
1058     char          prefix = 0;
1059     const AVClass    *cc = avcodec_get_class();
1060
1061     if (!codec)
1062         return NULL;
1063
1064     switch (codec->type) {
1065     case AVMEDIA_TYPE_VIDEO:    prefix = 'v'; flags |= AV_OPT_FLAG_VIDEO_PARAM;    break;
1066     case AVMEDIA_TYPE_AUDIO:    prefix = 'a'; flags |= AV_OPT_FLAG_AUDIO_PARAM;    break;
1067     case AVMEDIA_TYPE_SUBTITLE: prefix = 's'; flags |= AV_OPT_FLAG_SUBTITLE_PARAM; break;
1068     }
1069
1070     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1071         char *p = strchr(t->key, ':');
1072
1073         /* check stream specification in opt name */
1074         if (p)
1075             switch (check_stream_specifier(s, st, p + 1)) {
1076             case  1: *p = 0; break;
1077             case  0:         continue;
1078             default:         return NULL;
1079             }
1080
1081         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1082             (codec && codec->priv_class && av_opt_find(&codec->priv_class, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ)))
1083             av_dict_set(&ret, t->key, t->value, 0);
1084         else if (t->key[0] == prefix && av_opt_find(&cc, t->key+1, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ))
1085             av_dict_set(&ret, t->key+1, t->value, 0);
1086
1087         if (p)
1088             *p = ':';
1089     }
1090     return ret;
1091 }
1092
1093 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s, AVDictionary *codec_opts)
1094 {
1095     int i;
1096     AVDictionary **opts;
1097
1098     if (!s->nb_streams)
1099         return NULL;
1100     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1101     if (!opts) {
1102         av_log(NULL, AV_LOG_ERROR, "Could not alloc memory for stream options.\n");
1103         return NULL;
1104     }
1105     for (i = 0; i < s->nb_streams; i++)
1106         opts[i] = filter_codec_opts(codec_opts, avcodec_find_decoder(s->streams[i]->codec->codec_id), s, s->streams[i]);
1107     return opts;
1108 }
1109
1110 void *grow_array(void *array, int elem_size, int *size, int new_size)
1111 {
1112     if (new_size >= INT_MAX / elem_size) {
1113         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1114         exit_program(1);
1115     }
1116     if (*size < new_size) {
1117         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1118         if (!tmp) {
1119             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1120             exit_program(1);
1121         }
1122         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1123         *size = new_size;
1124         return tmp;
1125     }
1126     return array;
1127 }