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