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