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