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