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