]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
arm: Add VFP-accelerated version of int32_to_float_fmul_array8
[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/time.h>
53 #include <sys/resource.h>
54 #endif
55
56 struct SwsContext *sws_opts;
57 AVDictionary *format_opts, *codec_opts, *resample_opts;
58
59 static const int this_year = 2013;
60
61 void init_opts(void)
62 {
63 #if CONFIG_SWSCALE
64     sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
65                               NULL, NULL, NULL);
66 #endif
67 }
68
69 void uninit_opts(void)
70 {
71 #if CONFIG_SWSCALE
72     sws_freeContext(sws_opts);
73     sws_opts = NULL;
74 #endif
75     av_dict_free(&format_opts);
76     av_dict_free(&codec_opts);
77     av_dict_free(&resample_opts);
78 }
79
80 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
81 {
82     vfprintf(stdout, fmt, vl);
83 }
84
85 static void (*program_exit)(int ret);
86
87 void register_exit(void (*cb)(int ret))
88 {
89     program_exit = cb;
90 }
91
92 void exit_program(int ret)
93 {
94     if (program_exit)
95         program_exit(ret);
96
97     exit(ret);
98 }
99
100 double parse_number_or_die(const char *context, const char *numstr, int type,
101                            double min, double max)
102 {
103     char *tail;
104     const char *error;
105     double d = av_strtod(numstr, &tail);
106     if (*tail)
107         error = "Expected number for %s but found: %s\n";
108     else if (d < min || d > max)
109         error = "The value for %s was %s which is not within %f - %f\n";
110     else if (type == OPT_INT64 && (int64_t)d != d)
111         error = "Expected int64 for %s but found %s\n";
112     else if (type == OPT_INT && (int)d != d)
113         error = "Expected int for %s but found %s\n";
114     else
115         return d;
116     av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
117     exit_program(1);
118     return 0;
119 }
120
121 int64_t parse_time_or_die(const char *context, const char *timestr,
122                           int is_duration)
123 {
124     int64_t us;
125     if (av_parse_time(&us, timestr, is_duration) < 0) {
126         av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
127                is_duration ? "duration" : "date", context, timestr);
128         exit_program(1);
129     }
130     return us;
131 }
132
133 void show_help_options(const OptionDef *options, const char *msg, int req_flags,
134                        int rej_flags, int alt_flags)
135 {
136     const OptionDef *po;
137     int first;
138
139     first = 1;
140     for (po = options; po->name != NULL; po++) {
141         char buf[64];
142
143         if (((po->flags & req_flags) != req_flags) ||
144             (alt_flags && !(po->flags & alt_flags)) ||
145             (po->flags & rej_flags))
146             continue;
147
148         if (first) {
149             printf("%s\n", msg);
150             first = 0;
151         }
152         av_strlcpy(buf, po->name, sizeof(buf));
153         if (po->argname) {
154             av_strlcat(buf, " ", sizeof(buf));
155             av_strlcat(buf, po->argname, sizeof(buf));
156         }
157         printf("-%-17s  %s\n", buf, po->help);
158     }
159     printf("\n");
160 }
161
162 void show_help_children(const AVClass *class, int flags)
163 {
164     const AVClass *child = NULL;
165     av_opt_show2(&class, NULL, flags, 0);
166     printf("\n");
167
168     while (child = av_opt_child_class_next(class, child))
169         show_help_children(child, flags);
170 }
171
172 static const OptionDef *find_option(const OptionDef *po, const char *name)
173 {
174     const char *p = strchr(name, ':');
175     int len = p ? p - name : strlen(name);
176
177     while (po->name != NULL) {
178         if (!strncmp(name, po->name, len) && strlen(po->name) == len)
179             break;
180         po++;
181     }
182     return po;
183 }
184
185 #if HAVE_COMMANDLINETOARGVW
186 #include <windows.h>
187 #include <shellapi.h>
188 /* Will be leaked on exit */
189 static char** win32_argv_utf8 = NULL;
190 static int win32_argc = 0;
191
192 /**
193  * Prepare command line arguments for executable.
194  * For Windows - perform wide-char to UTF-8 conversion.
195  * Input arguments should be main() function arguments.
196  * @param argc_ptr Arguments number (including executable)
197  * @param argv_ptr Arguments list.
198  */
199 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
200 {
201     char *argstr_flat;
202     wchar_t **argv_w;
203     int i, buffsize = 0, offset = 0;
204
205     if (win32_argv_utf8) {
206         *argc_ptr = win32_argc;
207         *argv_ptr = win32_argv_utf8;
208         return;
209     }
210
211     win32_argc = 0;
212     argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
213     if (win32_argc <= 0 || !argv_w)
214         return;
215
216     /* determine the UTF-8 buffer size (including NULL-termination symbols) */
217     for (i = 0; i < win32_argc; i++)
218         buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
219                                         NULL, 0, NULL, NULL);
220
221     win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
222     argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
223     if (win32_argv_utf8 == NULL) {
224         LocalFree(argv_w);
225         return;
226     }
227
228     for (i = 0; i < win32_argc; i++) {
229         win32_argv_utf8[i] = &argstr_flat[offset];
230         offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
231                                       &argstr_flat[offset],
232                                       buffsize - offset, NULL, NULL);
233     }
234     win32_argv_utf8[i] = NULL;
235     LocalFree(argv_w);
236
237     *argc_ptr = win32_argc;
238     *argv_ptr = win32_argv_utf8;
239 }
240 #else
241 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
242 {
243     /* nothing to do */
244 }
245 #endif /* HAVE_COMMANDLINETOARGVW */
246
247 static int write_option(void *optctx, const OptionDef *po, const char *opt,
248                         const char *arg)
249 {
250     /* new-style options contain an offset into optctx, old-style address of
251      * a global var*/
252     void *dst = po->flags & (OPT_OFFSET | OPT_SPEC) ?
253                 (uint8_t *)optctx + po->u.off : po->u.dst_ptr;
254     int *dstcount;
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         av_freep(dst);
270         *(char **)dst = str;
271     } else if (po->flags & OPT_BOOL || po->flags & OPT_INT) {
272         *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
273     } else if (po->flags & OPT_INT64) {
274         *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
275     } else if (po->flags & OPT_TIME) {
276         *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
277     } else if (po->flags & OPT_FLOAT) {
278         *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
279     } else if (po->flags & OPT_DOUBLE) {
280         *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
281     } else if (po->u.func_arg) {
282         int ret = po->u.func_arg(optctx, opt, arg);
283         if (ret < 0) {
284             av_log(NULL, AV_LOG_ERROR,
285                    "Failed to set value '%s' for option '%s'\n", arg, opt);
286             return ret;
287         }
288     }
289     if (po->flags & OPT_EXIT)
290         exit_program(0);
291
292     return 0;
293 }
294
295 int parse_option(void *optctx, const char *opt, const char *arg,
296                  const OptionDef *options)
297 {
298     const OptionDef *po;
299     int ret;
300
301     po = find_option(options, opt);
302     if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
303         /* handle 'no' bool option */
304         po = find_option(options, opt + 2);
305         if ((po->name && (po->flags & OPT_BOOL)))
306             arg = "0";
307     } else if (po->flags & OPT_BOOL)
308         arg = "1";
309
310     if (!po->name)
311         po = find_option(options, "default");
312     if (!po->name) {
313         av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
314         return AVERROR(EINVAL);
315     }
316     if (po->flags & HAS_ARG && !arg) {
317         av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
318         return AVERROR(EINVAL);
319     }
320
321     ret = write_option(optctx, po, opt, arg);
322     if (ret < 0)
323         return ret;
324
325     return !!(po->flags & HAS_ARG);
326 }
327
328 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
329                    void (*parse_arg_function)(void *, const char*))
330 {
331     const char *opt;
332     int optindex, handleoptions = 1, ret;
333
334     /* perform system-dependent conversions for arguments list */
335     prepare_app_arguments(&argc, &argv);
336
337     /* parse options */
338     optindex = 1;
339     while (optindex < argc) {
340         opt = argv[optindex++];
341
342         if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
343             if (opt[1] == '-' && opt[2] == '\0') {
344                 handleoptions = 0;
345                 continue;
346             }
347             opt++;
348
349             if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
350                 exit_program(1);
351             optindex += ret;
352         } else {
353             if (parse_arg_function)
354                 parse_arg_function(optctx, opt);
355         }
356     }
357 }
358
359 int parse_optgroup(void *optctx, OptionGroup *g)
360 {
361     int i, ret;
362
363     av_log(NULL, AV_LOG_DEBUG, "Parsing a group of options: %s %s.\n",
364            g->group_def->name, g->arg);
365
366     for (i = 0; i < g->nb_opts; i++) {
367         Option *o = &g->opts[i];
368
369         if (g->group_def->flags &&
370             !(g->group_def->flags & o->opt->flags)) {
371             av_log(NULL, AV_LOG_ERROR, "Option %s (%s) cannot be applied to "
372                    "%s %s -- you are trying to apply an input option to an "
373                    "output file or vice versa. Move this option before the "
374                    "file it belongs to.\n", o->key, o->opt->help,
375                    g->group_def->name, g->arg);
376             return AVERROR(EINVAL);
377         }
378
379         av_log(NULL, AV_LOG_DEBUG, "Applying option %s (%s) with argument %s.\n",
380                o->key, o->opt->help, o->val);
381
382         ret = write_option(optctx, o->opt, o->key, o->val);
383         if (ret < 0)
384             return ret;
385     }
386
387     av_log(NULL, AV_LOG_DEBUG, "Successfully parsed a group of options.\n");
388
389     return 0;
390 }
391
392 int locate_option(int argc, char **argv, const OptionDef *options,
393                   const char *optname)
394 {
395     const OptionDef *po;
396     int i;
397
398     for (i = 1; i < argc; i++) {
399         const char *cur_opt = argv[i];
400
401         if (*cur_opt++ != '-')
402             continue;
403
404         po = find_option(options, cur_opt);
405         if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
406             po = find_option(options, cur_opt + 2);
407
408         if ((!po->name && !strcmp(cur_opt, optname)) ||
409              (po->name && !strcmp(optname, po->name)))
410             return i;
411
412         if (!po || po->flags & HAS_ARG)
413             i++;
414     }
415     return 0;
416 }
417
418 void parse_loglevel(int argc, char **argv, const OptionDef *options)
419 {
420     int idx = locate_option(argc, argv, options, "loglevel");
421     if (!idx)
422         idx = locate_option(argc, argv, options, "v");
423     if (idx && argv[idx + 1])
424         opt_loglevel(NULL, "loglevel", argv[idx + 1]);
425 }
426
427 #define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
428 int opt_default(void *optctx, const char *opt, const char *arg)
429 {
430     const AVOption *o;
431     char opt_stripped[128];
432     const char *p;
433     const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
434 #if CONFIG_AVRESAMPLE
435     const AVClass *rc = avresample_get_class();
436 #endif
437 #if CONFIG_SWSCALE
438     const AVClass *sc = sws_get_class();
439 #endif
440
441     if (!(p = strchr(opt, ':')))
442         p = opt + strlen(opt);
443     av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
444
445     if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
446                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
447         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
448          (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
449         av_dict_set(&codec_opts, opt, arg, FLAGS);
450     else if ((o = av_opt_find(&fc, opt, NULL, 0,
451                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
452         av_dict_set(&format_opts, opt, arg, FLAGS);
453 #if CONFIG_AVRESAMPLE
454     else if ((o = av_opt_find(&rc, opt, NULL, 0,
455                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
456         av_dict_set(&resample_opts, opt, arg, FLAGS);
457 #endif
458 #if CONFIG_SWSCALE
459     else if ((o = av_opt_find(&sc, opt, NULL, 0,
460                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
461         // XXX we only support sws_flags, not arbitrary sws options
462         int ret = av_opt_set(sws_opts, opt, arg, 0);
463         if (ret < 0) {
464             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
465             return ret;
466         }
467     }
468 #endif
469
470     if (o)
471         return 0;
472     return AVERROR_OPTION_NOT_FOUND;
473 }
474
475 /*
476  * Check whether given option is a group separator.
477  *
478  * @return index of the group definition that matched or -1 if none
479  */
480 static int match_group_separator(const OptionGroupDef *groups, int nb_groups,
481                                  const char *opt)
482 {
483     int i;
484
485     for (i = 0; i < nb_groups; i++) {
486         const OptionGroupDef *p = &groups[i];
487         if (p->sep && !strcmp(p->sep, opt))
488             return i;
489     }
490
491     return -1;
492 }
493
494 /*
495  * Finish parsing an option group.
496  *
497  * @param group_idx which group definition should this group belong to
498  * @param arg argument of the group delimiting option
499  */
500 static void finish_group(OptionParseContext *octx, int group_idx,
501                          const char *arg)
502 {
503     OptionGroupList *l = &octx->groups[group_idx];
504     OptionGroup *g;
505
506     GROW_ARRAY(l->groups, l->nb_groups);
507     g = &l->groups[l->nb_groups - 1];
508
509     *g             = octx->cur_group;
510     g->arg         = arg;
511     g->group_def   = l->group_def;
512 #if CONFIG_SWSCALE
513     g->sws_opts    = sws_opts;
514 #endif
515     g->codec_opts  = codec_opts;
516     g->format_opts = format_opts;
517     g->resample_opts = resample_opts;
518
519     codec_opts  = NULL;
520     format_opts = NULL;
521     resample_opts = NULL;
522 #if CONFIG_SWSCALE
523     sws_opts    = NULL;
524 #endif
525     init_opts();
526
527     memset(&octx->cur_group, 0, sizeof(octx->cur_group));
528 }
529
530 /*
531  * Add an option instance to currently parsed group.
532  */
533 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
534                     const char *key, const char *val)
535 {
536     int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
537     OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
538
539     GROW_ARRAY(g->opts, g->nb_opts);
540     g->opts[g->nb_opts - 1].opt = opt;
541     g->opts[g->nb_opts - 1].key = key;
542     g->opts[g->nb_opts - 1].val = val;
543 }
544
545 static void init_parse_context(OptionParseContext *octx,
546                                const OptionGroupDef *groups, int nb_groups)
547 {
548     static const OptionGroupDef global_group = { "global" };
549     int i;
550
551     memset(octx, 0, sizeof(*octx));
552
553     octx->nb_groups = nb_groups;
554     octx->groups    = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
555     if (!octx->groups)
556         exit_program(1);
557
558     for (i = 0; i < octx->nb_groups; i++)
559         octx->groups[i].group_def = &groups[i];
560
561     octx->global_opts.group_def = &global_group;
562     octx->global_opts.arg       = "";
563
564     init_opts();
565 }
566
567 void uninit_parse_context(OptionParseContext *octx)
568 {
569     int i, j;
570
571     for (i = 0; i < octx->nb_groups; i++) {
572         OptionGroupList *l = &octx->groups[i];
573
574         for (j = 0; j < l->nb_groups; j++) {
575             av_freep(&l->groups[j].opts);
576             av_dict_free(&l->groups[j].codec_opts);
577             av_dict_free(&l->groups[j].format_opts);
578             av_dict_free(&l->groups[j].resample_opts);
579 #if CONFIG_SWSCALE
580             sws_freeContext(l->groups[j].sws_opts);
581 #endif
582         }
583         av_freep(&l->groups);
584     }
585     av_freep(&octx->groups);
586
587     av_freep(&octx->cur_group.opts);
588     av_freep(&octx->global_opts.opts);
589
590     uninit_opts();
591 }
592
593 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
594                       const OptionDef *options,
595                       const OptionGroupDef *groups, int nb_groups)
596 {
597     int optindex = 1;
598
599     /* perform system-dependent conversions for arguments list */
600     prepare_app_arguments(&argc, &argv);
601
602     init_parse_context(octx, groups, nb_groups);
603     av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
604
605     while (optindex < argc) {
606         const char *opt = argv[optindex++], *arg;
607         const OptionDef *po;
608         int ret;
609
610         av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
611
612         /* unnamed group separators, e.g. output filename */
613         if (opt[0] != '-' || !opt[1]) {
614             finish_group(octx, 0, opt);
615             av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
616             continue;
617         }
618         opt++;
619
620 #define GET_ARG(arg)                                                           \
621 do {                                                                           \
622     arg = argv[optindex++];                                                    \
623     if (!arg) {                                                                \
624         av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
625         return AVERROR(EINVAL);                                                \
626     }                                                                          \
627 } while (0)
628
629         /* named group separators, e.g. -i */
630         if ((ret = match_group_separator(groups, nb_groups, opt)) >= 0) {
631             GET_ARG(arg);
632             finish_group(octx, ret, arg);
633             av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
634                    groups[ret].name, arg);
635             continue;
636         }
637
638         /* normal options */
639         po = find_option(options, opt);
640         if (po->name) {
641             if (po->flags & OPT_EXIT) {
642                 /* optional argument, e.g. -h */
643                 arg = argv[optindex++];
644             } else if (po->flags & HAS_ARG) {
645                 GET_ARG(arg);
646             } else {
647                 arg = "1";
648             }
649
650             add_opt(octx, po, opt, arg);
651             av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
652                    "argument '%s'.\n", po->name, po->help, arg);
653             continue;
654         }
655
656         /* AVOptions */
657         if (argv[optindex]) {
658             ret = opt_default(NULL, opt, argv[optindex]);
659             if (ret >= 0) {
660                 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
661                        "argument '%s'.\n", opt, argv[optindex]);
662                 optindex++;
663                 continue;
664             } else if (ret != AVERROR_OPTION_NOT_FOUND) {
665                 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
666                        "with argument '%s'.\n", opt, argv[optindex]);
667                 return ret;
668             }
669         }
670
671         /* boolean -nofoo options */
672         if (opt[0] == 'n' && opt[1] == 'o' &&
673             (po = find_option(options, opt + 2)) &&
674             po->name && po->flags & OPT_BOOL) {
675             add_opt(octx, po, opt, "0");
676             av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
677                    "argument 0.\n", po->name, po->help);
678             continue;
679         }
680
681         av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
682         return AVERROR_OPTION_NOT_FOUND;
683     }
684
685     if (octx->cur_group.nb_opts || codec_opts || format_opts || resample_opts)
686         av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
687                "commandline.\n");
688
689     av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
690
691     return 0;
692 }
693
694 int opt_loglevel(void *optctx, const char *opt, const char *arg)
695 {
696     const struct { const char *name; int level; } log_levels[] = {
697         { "quiet"  , AV_LOG_QUIET   },
698         { "panic"  , AV_LOG_PANIC   },
699         { "fatal"  , AV_LOG_FATAL   },
700         { "error"  , AV_LOG_ERROR   },
701         { "warning", AV_LOG_WARNING },
702         { "info"   , AV_LOG_INFO    },
703         { "verbose", AV_LOG_VERBOSE },
704         { "debug"  , AV_LOG_DEBUG   },
705     };
706     char *tail;
707     int level;
708     int i;
709
710     for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
711         if (!strcmp(log_levels[i].name, arg)) {
712             av_log_set_level(log_levels[i].level);
713             return 0;
714         }
715     }
716
717     level = strtol(arg, &tail, 10);
718     if (*tail) {
719         av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
720                "Possible levels are numbers or:\n", arg);
721         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
722             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
723         exit_program(1);
724     }
725     av_log_set_level(level);
726     return 0;
727 }
728
729 int opt_timelimit(void *optctx, const char *opt, const char *arg)
730 {
731 #if HAVE_SETRLIMIT
732     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
733     struct rlimit rl = { lim, lim + 1 };
734     if (setrlimit(RLIMIT_CPU, &rl))
735         perror("setrlimit");
736 #else
737     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
738 #endif
739     return 0;
740 }
741
742 void print_error(const char *filename, int err)
743 {
744     char errbuf[128];
745     const char *errbuf_ptr = errbuf;
746
747     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
748         errbuf_ptr = strerror(AVUNERROR(err));
749     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
750 }
751
752 static int warned_cfg = 0;
753
754 #define INDENT        1
755 #define SHOW_VERSION  2
756 #define SHOW_CONFIG   4
757
758 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
759     if (CONFIG_##LIBNAME) {                                             \
760         const char *indent = flags & INDENT? "  " : "";                 \
761         if (flags & SHOW_VERSION) {                                     \
762             unsigned int version = libname##_version();                 \
763             av_log(NULL, level,                                         \
764                    "%slib%-10s %2d.%3d.%2d / %2d.%3d.%2d\n",            \
765                    indent, #libname,                                    \
766                    LIB##LIBNAME##_VERSION_MAJOR,                        \
767                    LIB##LIBNAME##_VERSION_MINOR,                        \
768                    LIB##LIBNAME##_VERSION_MICRO,                        \
769                    version >> 16, version >> 8 & 0xff, version & 0xff); \
770         }                                                               \
771         if (flags & SHOW_CONFIG) {                                      \
772             const char *cfg = libname##_configuration();                \
773             if (strcmp(LIBAV_CONFIGURATION, cfg)) {                     \
774                 if (!warned_cfg) {                                      \
775                     av_log(NULL, level,                                 \
776                             "%sWARNING: library configuration mismatch\n", \
777                             indent);                                    \
778                     warned_cfg = 1;                                     \
779                 }                                                       \
780                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
781                         indent, #libname, cfg);                         \
782             }                                                           \
783         }                                                               \
784     }                                                                   \
785
786 static void print_all_libs_info(int flags, int level)
787 {
788     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
789     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
790     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
791     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
792     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
793     PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
794     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
795 }
796
797 void show_banner(void)
798 {
799     av_log(NULL, AV_LOG_INFO,
800            "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
801            program_name, program_birth_year, this_year);
802     av_log(NULL, AV_LOG_INFO, "  built on %s %s with %s\n",
803            __DATE__, __TIME__, CC_IDENT);
804     av_log(NULL, AV_LOG_VERBOSE, "  configuration: " LIBAV_CONFIGURATION "\n");
805     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_VERBOSE);
806     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
807 }
808
809 int show_version(void *optctx, const char *opt, const char *arg)
810 {
811     av_log_set_callback(log_callback_help);
812     printf("%s " LIBAV_VERSION "\n", program_name);
813     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
814
815     return 0;
816 }
817
818 int show_license(void *optctx, const char *opt, const char *arg)
819 {
820     printf(
821 #if CONFIG_NONFREE
822     "This version of %s has nonfree parts compiled in.\n"
823     "Therefore it is not legally redistributable.\n",
824     program_name
825 #elif CONFIG_GPLV3
826     "%s is free software; you can redistribute it and/or modify\n"
827     "it under the terms of the GNU General Public License as published by\n"
828     "the Free Software Foundation; either version 3 of the License, or\n"
829     "(at your option) any later version.\n"
830     "\n"
831     "%s is distributed in the hope that it will be useful,\n"
832     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
833     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
834     "GNU General Public License for more details.\n"
835     "\n"
836     "You should have received a copy of the GNU General Public License\n"
837     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
838     program_name, program_name, program_name
839 #elif CONFIG_GPL
840     "%s is free software; you can redistribute it and/or modify\n"
841     "it under the terms of the GNU General Public License as published by\n"
842     "the Free Software Foundation; either version 2 of the License, or\n"
843     "(at your option) any later version.\n"
844     "\n"
845     "%s is distributed in the hope that it will be useful,\n"
846     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
847     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
848     "GNU General Public License for more details.\n"
849     "\n"
850     "You should have received a copy of the GNU General Public License\n"
851     "along with %s; if not, write to the Free Software\n"
852     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
853     program_name, program_name, program_name
854 #elif CONFIG_LGPLV3
855     "%s is free software; you can redistribute it and/or modify\n"
856     "it under the terms of the GNU Lesser General Public License as published by\n"
857     "the Free Software Foundation; either version 3 of the License, or\n"
858     "(at your option) any later version.\n"
859     "\n"
860     "%s is distributed in the hope that it will be useful,\n"
861     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
862     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
863     "GNU Lesser General Public License for more details.\n"
864     "\n"
865     "You should have received a copy of the GNU Lesser General Public License\n"
866     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
867     program_name, program_name, program_name
868 #else
869     "%s is free software; you can redistribute it and/or\n"
870     "modify it under the terms of the GNU Lesser General Public\n"
871     "License as published by the Free Software Foundation; either\n"
872     "version 2.1 of the License, or (at your option) any later version.\n"
873     "\n"
874     "%s is distributed in the hope that it will be useful,\n"
875     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
876     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
877     "Lesser General Public License for more details.\n"
878     "\n"
879     "You should have received a copy of the GNU Lesser General Public\n"
880     "License along with %s; if not, write to the Free Software\n"
881     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
882     program_name, program_name, program_name
883 #endif
884     );
885
886     return 0;
887 }
888
889 int show_formats(void *optctx, const char *opt, const char *arg)
890 {
891     AVInputFormat *ifmt  = NULL;
892     AVOutputFormat *ofmt = NULL;
893     const char *last_name;
894
895     printf("File formats:\n"
896            " D. = Demuxing supported\n"
897            " .E = Muxing supported\n"
898            " --\n");
899     last_name = "000";
900     for (;;) {
901         int decode = 0;
902         int encode = 0;
903         const char *name      = NULL;
904         const char *long_name = NULL;
905
906         while ((ofmt = av_oformat_next(ofmt))) {
907             if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
908                 strcmp(ofmt->name, last_name) > 0) {
909                 name      = ofmt->name;
910                 long_name = ofmt->long_name;
911                 encode    = 1;
912             }
913         }
914         while ((ifmt = av_iformat_next(ifmt))) {
915             if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
916                 strcmp(ifmt->name, last_name) > 0) {
917                 name      = ifmt->name;
918                 long_name = ifmt->long_name;
919                 encode    = 0;
920             }
921             if (name && strcmp(ifmt->name, name) == 0)
922                 decode = 1;
923         }
924         if (name == NULL)
925             break;
926         last_name = name;
927
928         printf(" %s%s %-15s %s\n",
929                decode ? "D" : " ",
930                encode ? "E" : " ",
931                name,
932             long_name ? long_name:" ");
933     }
934     return 0;
935 }
936
937 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
938     if (codec->field) {                                                      \
939         const type *p = c->field;                                            \
940                                                                              \
941         printf("    Supported " list_name ":");                              \
942         while (*p != term) {                                                 \
943             get_name(*p);                                                    \
944             printf(" %s", name);                                             \
945             p++;                                                             \
946         }                                                                    \
947         printf("\n");                                                        \
948     }                                                                        \
949
950 static void print_codec(const AVCodec *c)
951 {
952     int encoder = av_codec_is_encoder(c);
953
954     printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
955            c->long_name ? c->long_name : "");
956
957     if (c->type == AVMEDIA_TYPE_VIDEO) {
958         printf("    Threading capabilities: ");
959         switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
960                                    CODEC_CAP_SLICE_THREADS)) {
961         case CODEC_CAP_FRAME_THREADS |
962              CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
963         case CODEC_CAP_FRAME_THREADS: printf("frame");           break;
964         case CODEC_CAP_SLICE_THREADS: printf("slice");           break;
965         default:                      printf("no");              break;
966         }
967         printf("\n");
968     }
969
970     if (c->supported_framerates) {
971         const AVRational *fps = c->supported_framerates;
972
973         printf("    Supported framerates:");
974         while (fps->num) {
975             printf(" %d/%d", fps->num, fps->den);
976             fps++;
977         }
978         printf("\n");
979     }
980     PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
981                           AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
982     PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
983                           GET_SAMPLE_RATE_NAME);
984     PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
985                           AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
986     PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
987                           0, GET_CH_LAYOUT_DESC);
988
989     if (c->priv_class) {
990         show_help_children(c->priv_class,
991                            AV_OPT_FLAG_ENCODING_PARAM |
992                            AV_OPT_FLAG_DECODING_PARAM);
993     }
994 }
995
996 static char get_media_type_char(enum AVMediaType type)
997 {
998     switch (type) {
999         case AVMEDIA_TYPE_VIDEO:    return 'V';
1000         case AVMEDIA_TYPE_AUDIO:    return 'A';
1001         case AVMEDIA_TYPE_SUBTITLE: return 'S';
1002         default:                    return '?';
1003     }
1004 }
1005
1006 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
1007                                         int encoder)
1008 {
1009     while ((prev = av_codec_next(prev))) {
1010         if (prev->id == id &&
1011             (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
1012             return prev;
1013     }
1014     return NULL;
1015 }
1016
1017 static void print_codecs_for_id(enum AVCodecID id, int encoder)
1018 {
1019     const AVCodec *codec = NULL;
1020
1021     printf(" (%s: ", encoder ? "encoders" : "decoders");
1022
1023     while ((codec = next_codec_for_id(id, codec, encoder)))
1024         printf("%s ", codec->name);
1025
1026     printf(")");
1027 }
1028
1029 int show_codecs(void *optctx, const char *opt, const char *arg)
1030 {
1031     const AVCodecDescriptor *desc = NULL;
1032
1033     printf("Codecs:\n"
1034            " D..... = Decoding supported\n"
1035            " .E.... = Encoding supported\n"
1036            " ..V... = Video codec\n"
1037            " ..A... = Audio codec\n"
1038            " ..S... = Subtitle codec\n"
1039            " ...I.. = Intra frame-only codec\n"
1040            " ....L. = Lossy compression\n"
1041            " .....S = Lossless compression\n"
1042            " -------\n");
1043     while ((desc = avcodec_descriptor_next(desc))) {
1044         const AVCodec *codec = NULL;
1045
1046         printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1047         printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1048
1049         printf("%c", get_media_type_char(desc->type));
1050         printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1051         printf((desc->props & AV_CODEC_PROP_LOSSY)      ? "L" : ".");
1052         printf((desc->props & AV_CODEC_PROP_LOSSLESS)   ? "S" : ".");
1053
1054         printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1055
1056         /* print decoders/encoders when there's more than one or their
1057          * names are different from codec name */
1058         while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1059             if (strcmp(codec->name, desc->name)) {
1060                 print_codecs_for_id(desc->id, 0);
1061                 break;
1062             }
1063         }
1064         codec = NULL;
1065         while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1066             if (strcmp(codec->name, desc->name)) {
1067                 print_codecs_for_id(desc->id, 1);
1068                 break;
1069             }
1070         }
1071
1072         printf("\n");
1073     }
1074     return 0;
1075 }
1076
1077 static void print_codecs(int encoder)
1078 {
1079     const AVCodecDescriptor *desc = NULL;
1080
1081     printf("%s:\n"
1082            " V... = Video\n"
1083            " A... = Audio\n"
1084            " S... = Subtitle\n"
1085            " .F.. = Frame-level multithreading\n"
1086            " ..S. = Slice-level multithreading\n"
1087            " ...X = Codec is experimental\n"
1088            " ---\n",
1089            encoder ? "Encoders" : "Decoders");
1090     while ((desc = avcodec_descriptor_next(desc))) {
1091         const AVCodec *codec = NULL;
1092
1093         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1094             printf("%c", get_media_type_char(desc->type));
1095             printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1096             printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1097             printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL)  ? "X" : ".");
1098
1099             printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1100             if (strcmp(codec->name, desc->name))
1101                 printf(" (codec %s)", desc->name);
1102
1103             printf("\n");
1104         }
1105     }
1106 }
1107
1108 int show_decoders(void *optctx, const char *opt, const char *arg)
1109 {
1110     print_codecs(0);
1111     return 0;
1112 }
1113
1114 int show_encoders(void *optctx, const char *opt, const char *arg)
1115 {
1116     print_codecs(1);
1117     return 0;
1118 }
1119
1120 int show_bsfs(void *optctx, const char *opt, const char *arg)
1121 {
1122     AVBitStreamFilter *bsf = NULL;
1123
1124     printf("Bitstream filters:\n");
1125     while ((bsf = av_bitstream_filter_next(bsf)))
1126         printf("%s\n", bsf->name);
1127     printf("\n");
1128     return 0;
1129 }
1130
1131 int show_protocols(void *optctx, const char *opt, const char *arg)
1132 {
1133     void *opaque = NULL;
1134     const char *name;
1135
1136     printf("Supported file protocols:\n"
1137            "Input:\n");
1138     while ((name = avio_enum_protocols(&opaque, 0)))
1139         printf("%s\n", name);
1140     printf("Output:\n");
1141     while ((name = avio_enum_protocols(&opaque, 1)))
1142         printf("%s\n", name);
1143     return 0;
1144 }
1145
1146 int show_filters(void *optctx, const char *opt, const char *arg)
1147 {
1148     const AVFilter av_unused(*filter) = NULL;
1149
1150     printf("Filters:\n");
1151 #if CONFIG_AVFILTER
1152     while ((filter = avfilter_next(filter)))
1153         printf("%-16s %s\n", filter->name, filter->description);
1154 #endif
1155     return 0;
1156 }
1157
1158 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1159 {
1160     const AVPixFmtDescriptor *pix_desc = NULL;
1161
1162     printf("Pixel formats:\n"
1163            "I.... = Supported Input  format for conversion\n"
1164            ".O... = Supported Output format for conversion\n"
1165            "..H.. = Hardware accelerated format\n"
1166            "...P. = Paletted format\n"
1167            "....B = Bitstream format\n"
1168            "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
1169            "-----\n");
1170
1171 #if !CONFIG_SWSCALE
1172 #   define sws_isSupportedInput(x)  0
1173 #   define sws_isSupportedOutput(x) 0
1174 #endif
1175
1176     while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1177         enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1178         printf("%c%c%c%c%c %-16s       %d            %2d\n",
1179                sws_isSupportedInput (pix_fmt)              ? 'I' : '.',
1180                sws_isSupportedOutput(pix_fmt)              ? 'O' : '.',
1181                pix_desc->flags & AV_PIX_FMT_FLAG_HWACCEL   ? 'H' : '.',
1182                pix_desc->flags & AV_PIX_FMT_FLAG_PAL       ? 'P' : '.',
1183                pix_desc->flags & AV_PIX_FMT_FLAG_BITSTREAM ? 'B' : '.',
1184                pix_desc->name,
1185                pix_desc->nb_components,
1186                av_get_bits_per_pixel(pix_desc));
1187     }
1188     return 0;
1189 }
1190
1191 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1192 {
1193     int i;
1194     char fmt_str[128];
1195     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1196         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1197     return 0;
1198 }
1199
1200 static void show_help_codec(const char *name, int encoder)
1201 {
1202     const AVCodecDescriptor *desc;
1203     const AVCodec *codec;
1204
1205     if (!name) {
1206         av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1207         return;
1208     }
1209
1210     codec = encoder ? avcodec_find_encoder_by_name(name) :
1211                       avcodec_find_decoder_by_name(name);
1212
1213     if (codec)
1214         print_codec(codec);
1215     else if ((desc = avcodec_descriptor_get_by_name(name))) {
1216         int printed = 0;
1217
1218         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1219             printed = 1;
1220             print_codec(codec);
1221         }
1222
1223         if (!printed) {
1224             av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to Libav, "
1225                    "but no %s for it are available. Libav might need to be "
1226                    "recompiled with additional external libraries.\n",
1227                    name, encoder ? "encoders" : "decoders");
1228         }
1229     } else {
1230         av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by Libav.\n",
1231                name);
1232     }
1233 }
1234
1235 static void show_help_demuxer(const char *name)
1236 {
1237     const AVInputFormat *fmt = av_find_input_format(name);
1238
1239     if (!fmt) {
1240         av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1241         return;
1242     }
1243
1244     printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1245
1246     if (fmt->extensions)
1247         printf("    Common extensions: %s.\n", fmt->extensions);
1248
1249     if (fmt->priv_class)
1250         show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1251 }
1252
1253 static void show_help_muxer(const char *name)
1254 {
1255     const AVCodecDescriptor *desc;
1256     const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1257
1258     if (!fmt) {
1259         av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1260         return;
1261     }
1262
1263     printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1264
1265     if (fmt->extensions)
1266         printf("    Common extensions: %s.\n", fmt->extensions);
1267     if (fmt->mime_type)
1268         printf("    Mime type: %s.\n", fmt->mime_type);
1269     if (fmt->video_codec != AV_CODEC_ID_NONE &&
1270         (desc = avcodec_descriptor_get(fmt->video_codec))) {
1271         printf("    Default video codec: %s.\n", desc->name);
1272     }
1273     if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1274         (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1275         printf("    Default audio codec: %s.\n", desc->name);
1276     }
1277     if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1278         (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1279         printf("    Default subtitle codec: %s.\n", desc->name);
1280     }
1281
1282     if (fmt->priv_class)
1283         show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1284 }
1285
1286 #if CONFIG_AVFILTER
1287 static void show_help_filter(const char *name)
1288 {
1289     const AVFilter *f = avfilter_get_by_name(name);
1290     int i, count;
1291
1292     if (!name) {
1293         av_log(NULL, AV_LOG_ERROR, "No filter name specified.\n");
1294         return;
1295     } else if (!f) {
1296         av_log(NULL, AV_LOG_ERROR, "Unknown filter '%s'.\n", name);
1297         return;
1298     }
1299
1300     printf("Filter %s [%s]:\n", f->name, f->description);
1301
1302     if (f->flags & AVFILTER_FLAG_SLICE_THREADS)
1303         printf("    slice threading supported\n");
1304
1305     printf("    Inputs:\n");
1306     count = avfilter_pad_count(f->inputs);
1307     for (i = 0; i < count; i++) {
1308         printf("        %d %s (%s)\n", i, avfilter_pad_get_name(f->inputs, i),
1309                media_type_string(avfilter_pad_get_type(f->inputs, i)));
1310     }
1311     if (f->flags & AVFILTER_FLAG_DYNAMIC_INPUTS)
1312         printf("        dynamic (depending on the options)\n");
1313
1314     printf("    Outputs:\n");
1315     count = avfilter_pad_count(f->outputs);
1316     for (i = 0; i < count; i++) {
1317         printf("        %d %s (%s)\n", i, avfilter_pad_get_name(f->outputs, i),
1318                media_type_string(avfilter_pad_get_type(f->outputs, i)));
1319     }
1320     if (f->flags & AVFILTER_FLAG_DYNAMIC_OUTPUTS)
1321         printf("        dynamic (depending on the options)\n");
1322
1323     if (f->priv_class)
1324         show_help_children(f->priv_class, AV_OPT_FLAG_VIDEO_PARAM |
1325                                           AV_OPT_FLAG_AUDIO_PARAM);
1326 }
1327 #endif
1328
1329 int show_help(void *optctx, const char *opt, const char *arg)
1330 {
1331     char *topic, *par;
1332     av_log_set_callback(log_callback_help);
1333
1334     topic = av_strdup(arg ? arg : "");
1335     par = strchr(topic, '=');
1336     if (par)
1337         *par++ = 0;
1338
1339     if (!*topic) {
1340         show_help_default(topic, par);
1341     } else if (!strcmp(topic, "decoder")) {
1342         show_help_codec(par, 0);
1343     } else if (!strcmp(topic, "encoder")) {
1344         show_help_codec(par, 1);
1345     } else if (!strcmp(topic, "demuxer")) {
1346         show_help_demuxer(par);
1347     } else if (!strcmp(topic, "muxer")) {
1348         show_help_muxer(par);
1349 #if CONFIG_AVFILTER
1350     } else if (!strcmp(topic, "filter")) {
1351         show_help_filter(par);
1352 #endif
1353     } else {
1354         show_help_default(topic, par);
1355     }
1356
1357     av_freep(&topic);
1358     return 0;
1359 }
1360
1361 int read_yesno(void)
1362 {
1363     int c = getchar();
1364     int yesno = (av_toupper(c) == 'Y');
1365
1366     while (c != '\n' && c != EOF)
1367         c = getchar();
1368
1369     return yesno;
1370 }
1371
1372 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1373 {
1374     int ret;
1375     FILE *f = fopen(filename, "rb");
1376
1377     if (!f) {
1378         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1379                strerror(errno));
1380         return AVERROR(errno);
1381     }
1382     fseek(f, 0, SEEK_END);
1383     *size = ftell(f);
1384     fseek(f, 0, SEEK_SET);
1385     *bufptr = av_malloc(*size + 1);
1386     if (!*bufptr) {
1387         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1388         fclose(f);
1389         return AVERROR(ENOMEM);
1390     }
1391     ret = fread(*bufptr, 1, *size, f);
1392     if (ret < *size) {
1393         av_free(*bufptr);
1394         if (ferror(f)) {
1395             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1396                    filename, strerror(errno));
1397             ret = AVERROR(errno);
1398         } else
1399             ret = AVERROR_EOF;
1400     } else {
1401         ret = 0;
1402         (*bufptr)[(*size)++] = '\0';
1403     }
1404
1405     fclose(f);
1406     return ret;
1407 }
1408
1409 void init_pts_correction(PtsCorrectionContext *ctx)
1410 {
1411     ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
1412     ctx->last_pts = ctx->last_dts = INT64_MIN;
1413 }
1414
1415 int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
1416                           int64_t dts)
1417 {
1418     int64_t pts = AV_NOPTS_VALUE;
1419
1420     if (dts != AV_NOPTS_VALUE) {
1421         ctx->num_faulty_dts += dts <= ctx->last_dts;
1422         ctx->last_dts = dts;
1423     }
1424     if (reordered_pts != AV_NOPTS_VALUE) {
1425         ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
1426         ctx->last_pts = reordered_pts;
1427     }
1428     if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
1429         && reordered_pts != AV_NOPTS_VALUE)
1430         pts = reordered_pts;
1431     else
1432         pts = dts;
1433
1434     return pts;
1435 }
1436
1437 FILE *get_preset_file(char *filename, size_t filename_size,
1438                       const char *preset_name, int is_path,
1439                       const char *codec_name)
1440 {
1441     FILE *f = NULL;
1442     int i;
1443     const char *base[3] = { getenv("AVCONV_DATADIR"),
1444                             getenv("HOME"),
1445                             AVCONV_DATADIR, };
1446
1447     if (is_path) {
1448         av_strlcpy(filename, preset_name, filename_size);
1449         f = fopen(filename, "r");
1450     } else {
1451         for (i = 0; i < 3 && !f; i++) {
1452             if (!base[i])
1453                 continue;
1454             snprintf(filename, filename_size, "%s%s/%s.avpreset", base[i],
1455                      i != 1 ? "" : "/.avconv", preset_name);
1456             f = fopen(filename, "r");
1457             if (!f && codec_name) {
1458                 snprintf(filename, filename_size,
1459                          "%s%s/%s-%s.avpreset",
1460                          base[i], i != 1 ? "" : "/.avconv", codec_name,
1461                          preset_name);
1462                 f = fopen(filename, "r");
1463             }
1464         }
1465     }
1466
1467     return f;
1468 }
1469
1470 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1471 {
1472     if (*spec <= '9' && *spec >= '0') /* opt:index */
1473         return strtol(spec, NULL, 0) == st->index;
1474     else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1475              *spec == 't') { /* opt:[vasdt] */
1476         enum AVMediaType type;
1477
1478         switch (*spec++) {
1479         case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
1480         case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
1481         case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
1482         case 'd': type = AVMEDIA_TYPE_DATA;       break;
1483         case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1484         default:  av_assert0(0);
1485         }
1486         if (type != st->codec->codec_type)
1487             return 0;
1488         if (*spec++ == ':') { /* possibly followed by :index */
1489             int i, index = strtol(spec, NULL, 0);
1490             for (i = 0; i < s->nb_streams; i++)
1491                 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1492                    return i == st->index;
1493             return 0;
1494         }
1495         return 1;
1496     } else if (*spec == 'p' && *(spec + 1) == ':') {
1497         int prog_id, i, j;
1498         char *endptr;
1499         spec += 2;
1500         prog_id = strtol(spec, &endptr, 0);
1501         for (i = 0; i < s->nb_programs; i++) {
1502             if (s->programs[i]->id != prog_id)
1503                 continue;
1504
1505             if (*endptr++ == ':') {
1506                 int stream_idx = strtol(endptr, NULL, 0);
1507                 return stream_idx >= 0 &&
1508                     stream_idx < s->programs[i]->nb_stream_indexes &&
1509                     st->index == s->programs[i]->stream_index[stream_idx];
1510             }
1511
1512             for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1513                 if (st->index == s->programs[i]->stream_index[j])
1514                     return 1;
1515         }
1516         return 0;
1517     } else if (!*spec) /* empty specifier, matches everything */
1518         return 1;
1519
1520     av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1521     return AVERROR(EINVAL);
1522 }
1523
1524 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1525                                 AVFormatContext *s, AVStream *st, AVCodec *codec)
1526 {
1527     AVDictionary    *ret = NULL;
1528     AVDictionaryEntry *t = NULL;
1529     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1530                                       : AV_OPT_FLAG_DECODING_PARAM;
1531     char          prefix = 0;
1532     const AVClass    *cc = avcodec_get_class();
1533
1534     if (!codec)
1535         codec            = s->oformat ? avcodec_find_encoder(codec_id)
1536                                       : avcodec_find_decoder(codec_id);
1537
1538     switch (st->codec->codec_type) {
1539     case AVMEDIA_TYPE_VIDEO:
1540         prefix  = 'v';
1541         flags  |= AV_OPT_FLAG_VIDEO_PARAM;
1542         break;
1543     case AVMEDIA_TYPE_AUDIO:
1544         prefix  = 'a';
1545         flags  |= AV_OPT_FLAG_AUDIO_PARAM;
1546         break;
1547     case AVMEDIA_TYPE_SUBTITLE:
1548         prefix  = 's';
1549         flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
1550         break;
1551     }
1552
1553     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1554         char *p = strchr(t->key, ':');
1555
1556         /* check stream specification in opt name */
1557         if (p)
1558             switch (check_stream_specifier(s, st, p + 1)) {
1559             case  1: *p = 0; break;
1560             case  0:         continue;
1561             default:         return NULL;
1562             }
1563
1564         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1565             (codec && codec->priv_class &&
1566              av_opt_find(&codec->priv_class, t->key, NULL, flags,
1567                          AV_OPT_SEARCH_FAKE_OBJ)))
1568             av_dict_set(&ret, t->key, t->value, 0);
1569         else if (t->key[0] == prefix &&
1570                  av_opt_find(&cc, t->key + 1, NULL, flags,
1571                              AV_OPT_SEARCH_FAKE_OBJ))
1572             av_dict_set(&ret, t->key + 1, t->value, 0);
1573
1574         if (p)
1575             *p = ':';
1576     }
1577     return ret;
1578 }
1579
1580 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1581                                            AVDictionary *codec_opts)
1582 {
1583     int i;
1584     AVDictionary **opts;
1585
1586     if (!s->nb_streams)
1587         return NULL;
1588     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1589     if (!opts) {
1590         av_log(NULL, AV_LOG_ERROR,
1591                "Could not alloc memory for stream options.\n");
1592         return NULL;
1593     }
1594     for (i = 0; i < s->nb_streams; i++)
1595         opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1596                                     s, s->streams[i], NULL);
1597     return opts;
1598 }
1599
1600 void *grow_array(void *array, int elem_size, int *size, int new_size)
1601 {
1602     if (new_size >= INT_MAX / elem_size) {
1603         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1604         exit_program(1);
1605     }
1606     if (*size < new_size) {
1607         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1608         if (!tmp) {
1609             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1610             exit_program(1);
1611         }
1612         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1613         *size = new_size;
1614         return tmp;
1615     }
1616     return array;
1617 }
1618
1619 const char *media_type_string(enum AVMediaType media_type)
1620 {
1621     switch (media_type) {
1622     case AVMEDIA_TYPE_VIDEO:      return "video";
1623     case AVMEDIA_TYPE_AUDIO:      return "audio";
1624     case AVMEDIA_TYPE_DATA:       return "data";
1625     case AVMEDIA_TYPE_SUBTITLE:   return "subtitle";
1626     case AVMEDIA_TYPE_ATTACHMENT: return "attachment";
1627     default:                      return "unknown";
1628     }
1629 }