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