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