OSDN Git Service

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