]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
avtools: move some newlines to show_help_options().
[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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 "libavresample/avresample.h"
36 #include "libswscale/swscale.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/mathematics.h"
40 #include "libavutil/imgutils.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/pixdesc.h"
43 #include "libavutil/eval.h"
44 #include "libavutil/dict.h"
45 #include "libavutil/opt.h"
46 #include "cmdutils.h"
47 #include "version.h"
48 #if CONFIG_NETWORK
49 #include "libavformat/network.h"
50 #endif
51 #if HAVE_SYS_RESOURCE_H
52 #include <sys/resource.h>
53 #endif
54
55 struct SwsContext *sws_opts;
56 AVDictionary *format_opts, *codec_opts;
57
58 static const int this_year = 2012;
59
60 void init_opts(void)
61 {
62 #if CONFIG_SWSCALE
63     sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
64                               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 double parse_number_or_die(const char *context, const char *numstr, int type,
84                            double min, double max)
85 {
86     char *tail;
87     const char *error;
88     double d = av_strtod(numstr, &tail);
89     if (*tail)
90         error = "Expected number for %s but found: %s\n";
91     else if (d < min || d > max)
92         error = "The value for %s was %s which is not within %f - %f\n";
93     else if (type == OPT_INT64 && (int64_t)d != d)
94         error = "Expected int64 for %s but found %s\n";
95     else if (type == OPT_INT && (int)d != d)
96         error = "Expected int for %s but found %s\n";
97     else
98         return d;
99     av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
100     exit_program(1);
101     return 0;
102 }
103
104 int64_t parse_time_or_die(const char *context, const char *timestr,
105                           int is_duration)
106 {
107     int64_t us;
108     if (av_parse_time(&us, timestr, is_duration) < 0) {
109         av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
110                is_duration ? "duration" : "date", context, timestr);
111         exit_program(1);
112     }
113     return us;
114 }
115
116 void show_help_options(const OptionDef *options, const char *msg, int mask,
117                        int value)
118 {
119     const OptionDef *po;
120     int first;
121
122     first = 1;
123     for (po = options; po->name != NULL; po++) {
124         char buf[64];
125         if ((po->flags & mask) == value) {
126             if (first) {
127                 printf("%s\n", msg);
128                 first = 0;
129             }
130             av_strlcpy(buf, po->name, sizeof(buf));
131             if (po->flags & HAS_ARG) {
132                 av_strlcat(buf, " ", sizeof(buf));
133                 av_strlcat(buf, po->argname, sizeof(buf));
134             }
135             printf("-%-17s  %s\n", buf, po->help);
136         }
137     }
138     printf("\n");
139 }
140
141 void show_help_children(const AVClass *class, int flags)
142 {
143     const AVClass *child = NULL;
144     av_opt_show2(&class, NULL, flags, 0);
145     printf("\n");
146
147     while (child = av_opt_child_class_next(class, child))
148         show_help_children(child, flags);
149 }
150
151 static const OptionDef *find_option(const OptionDef *po, const char *name)
152 {
153     const char *p = strchr(name, ':');
154     int len = p ? p - name : strlen(name);
155
156     while (po->name != NULL) {
157         if (!strncmp(name, po->name, len) && strlen(po->name) == len)
158             break;
159         po++;
160     }
161     return po;
162 }
163
164 #if defined(_WIN32) && !defined(__MINGW32CE__)
165 #include <windows.h>
166 #include <shellapi.h>
167 /* Will be leaked on exit */
168 static char** win32_argv_utf8 = NULL;
169 static int win32_argc = 0;
170
171 /**
172  * Prepare command line arguments for executable.
173  * For Windows - perform wide-char to UTF-8 conversion.
174  * Input arguments should be main() function arguments.
175  * @param argc_ptr Arguments number (including executable)
176  * @param argv_ptr Arguments list.
177  */
178 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
179 {
180     char *argstr_flat;
181     wchar_t **argv_w;
182     int i, buffsize = 0, offset = 0;
183
184     if (win32_argv_utf8) {
185         *argc_ptr = win32_argc;
186         *argv_ptr = win32_argv_utf8;
187         return;
188     }
189
190     win32_argc = 0;
191     argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
192     if (win32_argc <= 0 || !argv_w)
193         return;
194
195     /* determine the UTF-8 buffer size (including NULL-termination symbols) */
196     for (i = 0; i < win32_argc; i++)
197         buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
198                                         NULL, 0, NULL, NULL);
199
200     win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
201     argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
202     if (win32_argv_utf8 == NULL) {
203         LocalFree(argv_w);
204         return;
205     }
206
207     for (i = 0; i < win32_argc; i++) {
208         win32_argv_utf8[i] = &argstr_flat[offset];
209         offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
210                                       &argstr_flat[offset],
211                                       buffsize - offset, NULL, NULL);
212     }
213     win32_argv_utf8[i] = NULL;
214     LocalFree(argv_w);
215
216     *argc_ptr = win32_argc;
217     *argv_ptr = win32_argv_utf8;
218 }
219 #else
220 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
221 {
222     /* nothing to do */
223 }
224 #endif /* WIN32 && !__MINGW32CE__ */
225
226 int parse_option(void *optctx, const char *opt, const char *arg,
227                  const OptionDef *options)
228 {
229     const OptionDef *po;
230     int bool_val = 1;
231     int *dstcount;
232     void *dst;
233
234     po = find_option(options, opt);
235     if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
236         /* handle 'no' bool option */
237         po = find_option(options, opt + 2);
238         if ((po->name && (po->flags & OPT_BOOL)))
239             bool_val = 0;
240     }
241     if (!po->name)
242         po = find_option(options, "default");
243     if (!po->name) {
244         av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
245         return AVERROR(EINVAL);
246     }
247     if (po->flags & HAS_ARG && !arg) {
248         av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
249         return AVERROR(EINVAL);
250     }
251
252     /* new-style options contain an offset into optctx, old-style address of
253      * a global var*/
254     dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
255                                               : po->u.dst_ptr;
256
257     if (po->flags & OPT_SPEC) {
258         SpecifierOpt **so = dst;
259         char *p = strchr(opt, ':');
260
261         dstcount = (int *)(so + 1);
262         *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
263         (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
264         dst = &(*so)[*dstcount - 1].u;
265     }
266
267     if (po->flags & OPT_STRING) {
268         char *str;
269         str = av_strdup(arg);
270         *(char **)dst = str;
271     } else if (po->flags & OPT_BOOL) {
272         *(int *)dst = bool_val;
273     } else if (po->flags & OPT_INT) {
274         *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
275     } else if (po->flags & OPT_INT64) {
276         *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
277     } else if (po->flags & OPT_TIME) {
278         *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
279     } else if (po->flags & OPT_FLOAT) {
280         *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
281     } else if (po->flags & OPT_DOUBLE) {
282         *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
283     } else if (po->u.func_arg) {
284         int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
285                                         : po->u.func_arg(opt, arg);
286         if (ret < 0) {
287             av_log(NULL, AV_LOG_ERROR,
288                    "Failed to set value '%s' for option '%s'\n", arg, opt);
289             return ret;
290         }
291     }
292     if (po->flags & OPT_EXIT)
293         exit_program(0);
294     return !!(po->flags & HAS_ARG);
295 }
296
297 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
298                    void (*parse_arg_function)(void *, const char*))
299 {
300     const char *opt;
301     int optindex, handleoptions = 1, ret;
302
303     /* perform system-dependent conversions for arguments list */
304     prepare_app_arguments(&argc, &argv);
305
306     /* parse options */
307     optindex = 1;
308     while (optindex < argc) {
309         opt = argv[optindex++];
310
311         if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
312             if (opt[1] == '-' && opt[2] == '\0') {
313                 handleoptions = 0;
314                 continue;
315             }
316             opt++;
317
318             if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
319                 exit_program(1);
320             optindex += ret;
321         } else {
322             if (parse_arg_function)
323                 parse_arg_function(optctx, opt);
324         }
325     }
326 }
327
328 int locate_option(int argc, char **argv, const OptionDef *options,
329                   const char *optname)
330 {
331     const OptionDef *po;
332     int i;
333
334     for (i = 1; i < argc; i++) {
335         const char *cur_opt = argv[i];
336
337         if (*cur_opt++ != '-')
338             continue;
339
340         po = find_option(options, cur_opt);
341         if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
342             po = find_option(options, cur_opt + 2);
343
344         if ((!po->name && !strcmp(cur_opt, optname)) ||
345              (po->name && !strcmp(optname, po->name)))
346             return i;
347
348         if (!po || po->flags & HAS_ARG)
349             i++;
350     }
351     return 0;
352 }
353
354 void parse_loglevel(int argc, char **argv, const OptionDef *options)
355 {
356     int idx = locate_option(argc, argv, options, "loglevel");
357     if (!idx)
358         idx = locate_option(argc, argv, options, "v");
359     if (idx && argv[idx + 1])
360         opt_loglevel("loglevel", argv[idx + 1]);
361 }
362
363 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
364 int opt_default(const char *opt, const char *arg)
365 {
366     const AVOption *o;
367     char opt_stripped[128];
368     const char *p;
369     const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc = sws_get_class();
370
371     if (!(p = strchr(opt, ':')))
372         p = opt + strlen(opt);
373     av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
374
375     if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
376                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
377         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
378          (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
379         av_dict_set(&codec_opts, opt, arg, FLAGS);
380     else if ((o = av_opt_find(&fc, opt, NULL, 0,
381                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
382         av_dict_set(&format_opts, opt, arg, FLAGS);
383     else if ((o = av_opt_find(&sc, opt, NULL, 0,
384                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
385         // XXX we only support sws_flags, not arbitrary sws options
386         int ret = av_opt_set(sws_opts, opt, arg, 0);
387         if (ret < 0) {
388             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
389             return ret;
390         }
391     }
392
393     if (o)
394         return 0;
395     av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
396     return AVERROR_OPTION_NOT_FOUND;
397 }
398
399 int opt_loglevel(const char *opt, const char *arg)
400 {
401     const struct { const char *name; int level; } log_levels[] = {
402         { "quiet"  , AV_LOG_QUIET   },
403         { "panic"  , AV_LOG_PANIC   },
404         { "fatal"  , AV_LOG_FATAL   },
405         { "error"  , AV_LOG_ERROR   },
406         { "warning", AV_LOG_WARNING },
407         { "info"   , AV_LOG_INFO    },
408         { "verbose", AV_LOG_VERBOSE },
409         { "debug"  , AV_LOG_DEBUG   },
410     };
411     char *tail;
412     int level;
413     int i;
414
415     for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
416         if (!strcmp(log_levels[i].name, arg)) {
417             av_log_set_level(log_levels[i].level);
418             return 0;
419         }
420     }
421
422     level = strtol(arg, &tail, 10);
423     if (*tail) {
424         av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
425                "Possible levels are numbers or:\n", arg);
426         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
427             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
428         exit_program(1);
429     }
430     av_log_set_level(level);
431     return 0;
432 }
433
434 int opt_timelimit(const char *opt, const char *arg)
435 {
436 #if HAVE_SETRLIMIT
437     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
438     struct rlimit rl = { lim, lim + 1 };
439     if (setrlimit(RLIMIT_CPU, &rl))
440         perror("setrlimit");
441 #else
442     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
443 #endif
444     return 0;
445 }
446
447 void print_error(const char *filename, int err)
448 {
449     char errbuf[128];
450     const char *errbuf_ptr = errbuf;
451
452     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
453         errbuf_ptr = strerror(AVUNERROR(err));
454     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
455 }
456
457 static int warned_cfg = 0;
458
459 #define INDENT        1
460 #define SHOW_VERSION  2
461 #define SHOW_CONFIG   4
462
463 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
464     if (CONFIG_##LIBNAME) {                                             \
465         const char *indent = flags & INDENT? "  " : "";                 \
466         if (flags & SHOW_VERSION) {                                     \
467             unsigned int version = libname##_version();                 \
468             av_log(NULL, level,                                         \
469                    "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n",            \
470                    indent, #libname,                                    \
471                    LIB##LIBNAME##_VERSION_MAJOR,                        \
472                    LIB##LIBNAME##_VERSION_MINOR,                        \
473                    LIB##LIBNAME##_VERSION_MICRO,                        \
474                    version >> 16, version >> 8 & 0xff, version & 0xff); \
475         }                                                               \
476         if (flags & SHOW_CONFIG) {                                      \
477             const char *cfg = libname##_configuration();                \
478             if (strcmp(LIBAV_CONFIGURATION, cfg)) {                     \
479                 if (!warned_cfg) {                                      \
480                     av_log(NULL, level,                                 \
481                             "%sWARNING: library configuration mismatch\n", \
482                             indent);                                    \
483                     warned_cfg = 1;                                     \
484                 }                                                       \
485                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
486                         indent, #libname, cfg);                         \
487             }                                                           \
488         }                                                               \
489     }                                                                   \
490
491 static void print_all_libs_info(int flags, int level)
492 {
493     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
494     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
495     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
496     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
497     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
498     PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
499     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
500 }
501
502 void show_banner(void)
503 {
504     av_log(NULL, AV_LOG_INFO,
505            "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
506            program_name, program_birth_year, this_year);
507     av_log(NULL, AV_LOG_INFO, "  built on %s %s with %s\n",
508            __DATE__, __TIME__, CC_IDENT);
509     av_log(NULL, AV_LOG_VERBOSE, "  configuration: " LIBAV_CONFIGURATION "\n");
510     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_VERBOSE);
511     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
512 }
513
514 int show_version(const char *opt, const char *arg)
515 {
516     av_log_set_callback(log_callback_help);
517     printf("%s " LIBAV_VERSION "\n", program_name);
518     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
519
520     return 0;
521 }
522
523 int show_license(const char *opt, const char *arg)
524 {
525     printf(
526 #if CONFIG_NONFREE
527     "This version of %s has nonfree parts compiled in.\n"
528     "Therefore it is not legally redistributable.\n",
529     program_name
530 #elif CONFIG_GPLV3
531     "%s is free software; you can redistribute it and/or modify\n"
532     "it under the terms of the GNU General Public License as published by\n"
533     "the Free Software Foundation; either version 3 of the License, or\n"
534     "(at your option) any later version.\n"
535     "\n"
536     "%s is distributed in the hope that it will be useful,\n"
537     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
538     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
539     "GNU General Public License for more details.\n"
540     "\n"
541     "You should have received a copy of the GNU General Public License\n"
542     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
543     program_name, program_name, program_name
544 #elif CONFIG_GPL
545     "%s is free software; you can redistribute it and/or modify\n"
546     "it under the terms of the GNU General Public License as published by\n"
547     "the Free Software Foundation; either version 2 of the License, or\n"
548     "(at your option) any later version.\n"
549     "\n"
550     "%s is distributed in the hope that it will be useful,\n"
551     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
552     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
553     "GNU General Public License for more details.\n"
554     "\n"
555     "You should have received a copy of the GNU General Public License\n"
556     "along with %s; if not, write to the Free Software\n"
557     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
558     program_name, program_name, program_name
559 #elif CONFIG_LGPLV3
560     "%s is free software; you can redistribute it and/or modify\n"
561     "it under the terms of the GNU Lesser General Public License as published by\n"
562     "the Free Software Foundation; either version 3 of the License, or\n"
563     "(at your option) any later version.\n"
564     "\n"
565     "%s is distributed in the hope that it will be useful,\n"
566     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
567     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
568     "GNU Lesser General Public License for more details.\n"
569     "\n"
570     "You should have received a copy of the GNU Lesser General Public License\n"
571     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
572     program_name, program_name, program_name
573 #else
574     "%s is free software; you can redistribute it and/or\n"
575     "modify it under the terms of the GNU Lesser General Public\n"
576     "License as published by the Free Software Foundation; either\n"
577     "version 2.1 of the License, or (at your option) any later version.\n"
578     "\n"
579     "%s is distributed in the hope that it will be useful,\n"
580     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
581     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
582     "Lesser General Public License for more details.\n"
583     "\n"
584     "You should have received a copy of the GNU Lesser General Public\n"
585     "License along with %s; if not, write to the Free Software\n"
586     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
587     program_name, program_name, program_name
588 #endif
589     );
590
591     return 0;
592 }
593
594 int show_formats(const char *opt, const char *arg)
595 {
596     AVInputFormat *ifmt  = NULL;
597     AVOutputFormat *ofmt = NULL;
598     const char *last_name;
599
600     printf("File formats:\n"
601            " D. = Demuxing supported\n"
602            " .E = Muxing supported\n"
603            " --\n");
604     last_name = "000";
605     for (;;) {
606         int decode = 0;
607         int encode = 0;
608         const char *name      = NULL;
609         const char *long_name = NULL;
610
611         while ((ofmt = av_oformat_next(ofmt))) {
612             if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
613                 strcmp(ofmt->name, last_name) > 0) {
614                 name      = ofmt->name;
615                 long_name = ofmt->long_name;
616                 encode    = 1;
617             }
618         }
619         while ((ifmt = av_iformat_next(ifmt))) {
620             if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
621                 strcmp(ifmt->name, last_name) > 0) {
622                 name      = ifmt->name;
623                 long_name = ifmt->long_name;
624                 encode    = 0;
625             }
626             if (name && strcmp(ifmt->name, name) == 0)
627                 decode = 1;
628         }
629         if (name == NULL)
630             break;
631         last_name = name;
632
633         printf(" %s%s %-15s %s\n",
634                decode ? "D" : " ",
635                encode ? "E" : " ",
636                name,
637             long_name ? long_name:" ");
638     }
639     return 0;
640 }
641
642 static char get_media_type_char(enum AVMediaType type)
643 {
644     switch (type) {
645         case AVMEDIA_TYPE_VIDEO:    return 'V';
646         case AVMEDIA_TYPE_AUDIO:    return 'A';
647         case AVMEDIA_TYPE_SUBTITLE: return 'S';
648         default:                    return '?';
649     }
650 }
651
652 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
653                                         int encoder)
654 {
655     while ((prev = av_codec_next(prev))) {
656         if (prev->id == id &&
657             (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
658             return prev;
659     }
660     return NULL;
661 }
662
663 static void print_codecs_for_id(enum AVCodecID id, int encoder)
664 {
665     const AVCodec *codec = NULL;
666
667     printf(" (%s: ", encoder ? "encoders" : "decoders");
668
669     while ((codec = next_codec_for_id(id, codec, encoder)))
670         printf("%s ", codec->name);
671
672     printf(")");
673 }
674
675 int show_codecs(const char *opt, const char *arg)
676 {
677     const AVCodecDescriptor *desc = NULL;
678
679     printf("Codecs:\n"
680            " D... = Decoding supported\n"
681            " .E.. = Encoding supported\n"
682            " ..V. = Video codec\n"
683            " ..A. = Audio codec\n"
684            " ..S. = Subtitle codec\n"
685            " ...I = Intra frame-only codec\n"
686            " -----\n");
687     while ((desc = avcodec_descriptor_next(desc))) {
688         const AVCodec *codec = NULL;
689
690         printf(avcodec_find_decoder(desc->id) ? "D" : ".");
691         printf(avcodec_find_encoder(desc->id) ? "E" : ".");
692
693         printf("%c", get_media_type_char(desc->type));
694         printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
695
696         printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
697
698         /* print decoders/encoders when there's more than one or their
699          * names are different from codec name */
700         while ((codec = next_codec_for_id(desc->id, codec, 0))) {
701             if (strcmp(codec->name, desc->name)) {
702                 print_codecs_for_id(desc->id, 0);
703                 break;
704             }
705         }
706         codec = NULL;
707         while ((codec = next_codec_for_id(desc->id, codec, 1))) {
708             if (strcmp(codec->name, desc->name)) {
709                 print_codecs_for_id(desc->id, 1);
710                 break;
711             }
712         }
713
714         printf("\n");
715     }
716     return 0;
717 }
718
719 static void print_codecs(int encoder)
720 {
721     const AVCodecDescriptor *desc = NULL;
722
723     printf("%s:\n"
724            " V... = Video\n"
725            " A... = Audio\n"
726            " S... = Subtitle\n"
727            " .F.. = Frame-level multithreading\n"
728            " ..S. = Slice-level multithreading\n"
729            " ...X = Codec is experimental\n"
730            " ---\n",
731            encoder ? "Encoders" : "Decoders");
732     while ((desc = avcodec_descriptor_next(desc))) {
733         const AVCodec *codec = NULL;
734
735         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
736             printf("%c", get_media_type_char(desc->type));
737             printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
738             printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
739             printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL)  ? "X" : ".");
740
741             printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
742             if (strcmp(codec->name, desc->name))
743                 printf(" (codec %s)", desc->name);
744
745             printf("\n");
746         }
747     }
748 }
749
750 int show_decoders(const char *opt, const char *arg)
751 {
752     print_codecs(0);
753     return 0;
754 }
755
756 int show_encoders(const char *opt, const char *arg)
757 {
758     print_codecs(1);
759     return 0;
760 }
761
762 int show_bsfs(const char *opt, const char *arg)
763 {
764     AVBitStreamFilter *bsf = NULL;
765
766     printf("Bitstream filters:\n");
767     while ((bsf = av_bitstream_filter_next(bsf)))
768         printf("%s\n", bsf->name);
769     printf("\n");
770     return 0;
771 }
772
773 int show_protocols(const char *opt, const char *arg)
774 {
775     void *opaque = NULL;
776     const char *name;
777
778     printf("Supported file protocols:\n"
779            "Input:\n");
780     while ((name = avio_enum_protocols(&opaque, 0)))
781         printf("%s\n", name);
782     printf("Output:\n");
783     while ((name = avio_enum_protocols(&opaque, 1)))
784         printf("%s\n", name);
785     return 0;
786 }
787
788 int show_filters(const char *opt, const char *arg)
789 {
790     AVFilter av_unused(**filter) = NULL;
791
792     printf("Filters:\n");
793 #if CONFIG_AVFILTER
794     while ((filter = av_filter_next(filter)) && *filter)
795         printf("%-16s %s\n", (*filter)->name, (*filter)->description);
796 #endif
797     return 0;
798 }
799
800 int show_pix_fmts(const char *opt, const char *arg)
801 {
802     enum PixelFormat pix_fmt;
803
804     printf("Pixel formats:\n"
805            "I.... = Supported Input  format for conversion\n"
806            ".O... = Supported Output format for conversion\n"
807            "..H.. = Hardware accelerated format\n"
808            "...P. = Paletted format\n"
809            "....B = Bitstream format\n"
810            "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
811            "-----\n");
812
813 #if !CONFIG_SWSCALE
814 #   define sws_isSupportedInput(x)  0
815 #   define sws_isSupportedOutput(x) 0
816 #endif
817
818     for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
819         const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
820         printf("%c%c%c%c%c %-16s       %d            %2d\n",
821                sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
822                sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
823                pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
824                pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
825                pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
826                pix_desc->name,
827                pix_desc->nb_components,
828                av_get_bits_per_pixel(pix_desc));
829     }
830     return 0;
831 }
832
833 int show_sample_fmts(const char *opt, const char *arg)
834 {
835     int i;
836     char fmt_str[128];
837     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
838         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
839     return 0;
840 }
841
842 int read_yesno(void)
843 {
844     int c = getchar();
845     int yesno = (toupper(c) == 'Y');
846
847     while (c != '\n' && c != EOF)
848         c = getchar();
849
850     return yesno;
851 }
852
853 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
854 {
855     int ret;
856     FILE *f = fopen(filename, "rb");
857
858     if (!f) {
859         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
860                strerror(errno));
861         return AVERROR(errno);
862     }
863     fseek(f, 0, SEEK_END);
864     *size = ftell(f);
865     fseek(f, 0, SEEK_SET);
866     *bufptr = av_malloc(*size + 1);
867     if (!*bufptr) {
868         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
869         fclose(f);
870         return AVERROR(ENOMEM);
871     }
872     ret = fread(*bufptr, 1, *size, f);
873     if (ret < *size) {
874         av_free(*bufptr);
875         if (ferror(f)) {
876             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
877                    filename, strerror(errno));
878             ret = AVERROR(errno);
879         } else
880             ret = AVERROR_EOF;
881     } else {
882         ret = 0;
883         (*bufptr)[*size++] = '\0';
884     }
885
886     fclose(f);
887     return ret;
888 }
889
890 void init_pts_correction(PtsCorrectionContext *ctx)
891 {
892     ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
893     ctx->last_pts = ctx->last_dts = INT64_MIN;
894 }
895
896 int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
897                           int64_t dts)
898 {
899     int64_t pts = AV_NOPTS_VALUE;
900
901     if (dts != AV_NOPTS_VALUE) {
902         ctx->num_faulty_dts += dts <= ctx->last_dts;
903         ctx->last_dts = dts;
904     }
905     if (reordered_pts != AV_NOPTS_VALUE) {
906         ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
907         ctx->last_pts = reordered_pts;
908     }
909     if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
910         && reordered_pts != AV_NOPTS_VALUE)
911         pts = reordered_pts;
912     else
913         pts = dts;
914
915     return pts;
916 }
917
918 FILE *get_preset_file(char *filename, size_t filename_size,
919                       const char *preset_name, int is_path,
920                       const char *codec_name)
921 {
922     FILE *f = NULL;
923     int i;
924     const char *base[3] = { getenv("AVCONV_DATADIR"),
925                             getenv("HOME"),
926                             AVCONV_DATADIR, };
927
928     if (is_path) {
929         av_strlcpy(filename, preset_name, filename_size);
930         f = fopen(filename, "r");
931     } else {
932         for (i = 0; i < 3 && !f; i++) {
933             if (!base[i])
934                 continue;
935             snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
936                      i != 1 ? "" : "/.avconv", preset_name);
937             f = fopen(filename, "r");
938             if (!f && codec_name) {
939                 snprintf(filename, filename_size,
940                          "%s%s/%s-%s.avpreset",
941                          base[i], i != 1 ? "" : "/.avconv", codec_name,
942                          preset_name);
943                 f = fopen(filename, "r");
944             }
945         }
946     }
947
948     return f;
949 }
950
951 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
952 {
953     if (*spec <= '9' && *spec >= '0') /* opt:index */
954         return strtol(spec, NULL, 0) == st->index;
955     else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
956              *spec == 't') { /* opt:[vasdt] */
957         enum AVMediaType type;
958
959         switch (*spec++) {
960         case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
961         case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
962         case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
963         case 'd': type = AVMEDIA_TYPE_DATA;       break;
964         case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
965         default:  av_assert0(0);
966         }
967         if (type != st->codec->codec_type)
968             return 0;
969         if (*spec++ == ':') { /* possibly followed by :index */
970             int i, index = strtol(spec, NULL, 0);
971             for (i = 0; i < s->nb_streams; i++)
972                 if (s->streams[i]->codec->codec_type == type && index-- == 0)
973                    return i == st->index;
974             return 0;
975         }
976         return 1;
977     } else if (*spec == 'p' && *(spec + 1) == ':') {
978         int prog_id, i, j;
979         char *endptr;
980         spec += 2;
981         prog_id = strtol(spec, &endptr, 0);
982         for (i = 0; i < s->nb_programs; i++) {
983             if (s->programs[i]->id != prog_id)
984                 continue;
985
986             if (*endptr++ == ':') {
987                 int stream_idx = strtol(endptr, NULL, 0);
988                 return stream_idx >= 0 &&
989                     stream_idx < s->programs[i]->nb_stream_indexes &&
990                     st->index == s->programs[i]->stream_index[stream_idx];
991             }
992
993             for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
994                 if (st->index == s->programs[i]->stream_index[j])
995                     return 1;
996         }
997         return 0;
998     } else if (!*spec) /* empty specifier, matches everything */
999         return 1;
1000
1001     av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1002     return AVERROR(EINVAL);
1003 }
1004
1005 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1006                                 AVFormatContext *s, AVStream *st, AVCodec *codec)
1007 {
1008     AVDictionary    *ret = NULL;
1009     AVDictionaryEntry *t = NULL;
1010     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1011                                       : AV_OPT_FLAG_DECODING_PARAM;
1012     char          prefix = 0;
1013     const AVClass    *cc = avcodec_get_class();
1014
1015     if (!codec)
1016         codec            = s->oformat ? avcodec_find_encoder(codec_id)
1017                                       : avcodec_find_decoder(codec_id);
1018     if (!codec)
1019         return NULL;
1020
1021     switch (codec->type) {
1022     case AVMEDIA_TYPE_VIDEO:
1023         prefix  = 'v';
1024         flags  |= AV_OPT_FLAG_VIDEO_PARAM;
1025         break;
1026     case AVMEDIA_TYPE_AUDIO:
1027         prefix  = 'a';
1028         flags  |= AV_OPT_FLAG_AUDIO_PARAM;
1029         break;
1030     case AVMEDIA_TYPE_SUBTITLE:
1031         prefix  = 's';
1032         flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
1033         break;
1034     }
1035
1036     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1037         char *p = strchr(t->key, ':');
1038
1039         /* check stream specification in opt name */
1040         if (p)
1041             switch (check_stream_specifier(s, st, p + 1)) {
1042             case  1: *p = 0; break;
1043             case  0:         continue;
1044             default:         return NULL;
1045             }
1046
1047         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1048             (codec && codec->priv_class &&
1049              av_opt_find(&codec->priv_class, t->key, NULL, flags,
1050                          AV_OPT_SEARCH_FAKE_OBJ)))
1051             av_dict_set(&ret, t->key, t->value, 0);
1052         else if (t->key[0] == prefix &&
1053                  av_opt_find(&cc, t->key + 1, NULL, flags,
1054                              AV_OPT_SEARCH_FAKE_OBJ))
1055             av_dict_set(&ret, t->key + 1, t->value, 0);
1056
1057         if (p)
1058             *p = ':';
1059     }
1060     return ret;
1061 }
1062
1063 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1064                                            AVDictionary *codec_opts)
1065 {
1066     int i;
1067     AVDictionary **opts;
1068
1069     if (!s->nb_streams)
1070         return NULL;
1071     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1072     if (!opts) {
1073         av_log(NULL, AV_LOG_ERROR,
1074                "Could not alloc memory for stream options.\n");
1075         return NULL;
1076     }
1077     for (i = 0; i < s->nb_streams; i++)
1078         opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1079                                     s, s->streams[i], NULL);
1080     return opts;
1081 }
1082
1083 void *grow_array(void *array, int elem_size, int *size, int new_size)
1084 {
1085     if (new_size >= INT_MAX / elem_size) {
1086         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1087         exit_program(1);
1088     }
1089     if (*size < new_size) {
1090         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1091         if (!tmp) {
1092             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1093             exit_program(1);
1094         }
1095         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1096         *size = new_size;
1097         return tmp;
1098     }
1099     return array;
1100 }
1101
1102 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1103 {
1104     FrameBuffer  *buf = av_mallocz(sizeof(*buf));
1105     int i, ret;
1106     const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
1107     int h_chroma_shift, v_chroma_shift;
1108     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1109     int w = s->width, h = s->height;
1110
1111     if (!buf)
1112         return AVERROR(ENOMEM);
1113
1114     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1115         w += 2*edge;
1116         h += 2*edge;
1117     }
1118
1119     avcodec_align_dimensions(s, &w, &h);
1120     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1121                               s->pix_fmt, 32)) < 0) {
1122         av_freep(&buf);
1123         return ret;
1124     }
1125     /* XXX this shouldn't be needed, but some tests break without this line
1126      * those decoders are buggy and need to be fixed.
1127      * the following tests fail:
1128      * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1129      */
1130     memset(buf->base[0], 128, ret);
1131
1132     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1133     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1134         const int h_shift = i==0 ? 0 : h_chroma_shift;
1135         const int v_shift = i==0 ? 0 : v_chroma_shift;
1136         if (s->flags & CODEC_FLAG_EMU_EDGE)
1137             buf->data[i] = buf->base[i];
1138         else
1139             buf->data[i] = buf->base[i] +
1140                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
1141                                    (pixel_size*edge >> h_shift), 32);
1142     }
1143     buf->w       = s->width;
1144     buf->h       = s->height;
1145     buf->pix_fmt = s->pix_fmt;
1146     buf->pool    = pool;
1147
1148     *pbuf = buf;
1149     return 0;
1150 }
1151
1152 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1153 {
1154     FrameBuffer **pool = s->opaque;
1155     FrameBuffer *buf;
1156     int ret, i;
1157
1158     if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1159         return ret;
1160
1161     buf              = *pool;
1162     *pool            = buf->next;
1163     buf->next        = NULL;
1164     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1165         av_freep(&buf->base[0]);
1166         av_free(buf);
1167         if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1168             return ret;
1169     }
1170     buf->refcount++;
1171
1172     frame->opaque        = buf;
1173     frame->type          = FF_BUFFER_TYPE_USER;
1174     frame->extended_data = frame->data;
1175     frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
1176     frame->width         = buf->w;
1177     frame->height        = buf->h;
1178     frame->format        = buf->pix_fmt;
1179     frame->sample_aspect_ratio = s->sample_aspect_ratio;
1180
1181     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1182         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
1183         frame->data[i]     = buf->data[i];
1184         frame->linesize[i] = buf->linesize[i];
1185     }
1186
1187     return 0;
1188 }
1189
1190 static void unref_buffer(FrameBuffer *buf)
1191 {
1192     FrameBuffer **pool = buf->pool;
1193
1194     av_assert0(buf->refcount);
1195     buf->refcount--;
1196     if (!buf->refcount) {
1197         buf->next = *pool;
1198         *pool = buf;
1199     }
1200 }
1201
1202 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1203 {
1204     FrameBuffer *buf = frame->opaque;
1205     int i;
1206
1207     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1208         frame->data[i] = NULL;
1209
1210     unref_buffer(buf);
1211 }
1212
1213 void filter_release_buffer(AVFilterBuffer *fb)
1214 {
1215     FrameBuffer *buf = fb->priv;
1216     av_free(fb);
1217     unref_buffer(buf);
1218 }
1219
1220 void free_buffer_pool(FrameBuffer **pool)
1221 {
1222     FrameBuffer *buf = *pool;
1223     while (buf) {
1224         *pool = buf->next;
1225         av_freep(&buf->base[0]);
1226         av_free(buf);
1227         buf = *pool;
1228     }
1229 }