]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / cmdutils.c
1 /*
2  * Various utilities for command line tools
3  * Copyright (c) 2000-2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <string.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <math.h>
26
27 /* Include only the enabled headers since some compilers (namely, Sun
28    Studio) will not omit unused inline functions and create undefined
29    references to libraries that are not being built. */
30
31 #include "config.h"
32 #include "libavformat/avformat.h"
33 #include "libavfilter/avfilter.h"
34 #include "libavdevice/avdevice.h"
35 #include "libavresample/avresample.h"
36 #include "libswscale/swscale.h"
37 #include "libswresample/swresample.h"
38 #if CONFIG_POSTPROC
39 #include "libpostproc/postprocess.h"
40 #endif
41 #include "libavutil/avstring.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/parseutils.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/eval.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/opt.h"
48 #include "cmdutils.h"
49 #include "version.h"
50 #if CONFIG_NETWORK
51 #include "libavformat/network.h"
52 #endif
53 #if HAVE_SYS_RESOURCE_H
54 #include <sys/resource.h>
55 #endif
56
57 struct SwsContext *sws_opts;
58 SwrContext *swr_opts;
59 AVDictionary *format_opts, *codec_opts;
60
61 const int this_year = 2012;
62
63 static FILE *report_file;
64
65 void init_opts(void)
66 {
67 #if CONFIG_SWSCALE
68     sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
69                               NULL, NULL, NULL);
70 #endif
71     swr_opts = swr_alloc();
72 }
73
74 void uninit_opts(void)
75 {
76 #if CONFIG_SWSCALE
77     sws_freeContext(sws_opts);
78     sws_opts = NULL;
79 #endif
80     swr_free(&swr_opts);
81     av_dict_free(&format_opts);
82     av_dict_free(&codec_opts);
83 }
84
85 void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
86 {
87     vfprintf(stdout, fmt, vl);
88 }
89
90 static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
91 {
92     va_list vl2;
93     char line[1024];
94     static int print_prefix = 1;
95
96     va_copy(vl2, vl);
97     av_log_default_callback(ptr, level, fmt, vl);
98     av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
99     va_end(vl2);
100     fputs(line, report_file);
101     fflush(report_file);
102 }
103
104 double parse_number_or_die(const char *context, const char *numstr, int type,
105                            double min, double max)
106 {
107     char *tail;
108     const char *error;
109     double d = av_strtod(numstr, &tail);
110     if (*tail)
111         error = "Expected number for %s but found: %s\n";
112     else if (d < min || d > max)
113         error = "The value for %s was %s which is not within %f - %f\n";
114     else if (type == OPT_INT64 && (int64_t)d != d)
115         error = "Expected int64 for %s but found %s\n";
116     else if (type == OPT_INT && (int)d != d)
117         error = "Expected int for %s but found %s\n";
118     else
119         return d;
120     av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
121     exit_program(1);
122     return 0;
123 }
124
125 int64_t parse_time_or_die(const char *context, const char *timestr,
126                           int is_duration)
127 {
128     int64_t us;
129     if (av_parse_time(&us, timestr, is_duration) < 0) {
130         av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
131                is_duration ? "duration" : "date", context, timestr);
132         exit_program(1);
133     }
134     return us;
135 }
136
137 void show_help_options(const OptionDef *options, const char *msg, int mask,
138                        int value)
139 {
140     const OptionDef *po;
141     int first;
142
143     first = 1;
144     for (po = options; po->name != NULL; po++) {
145         char buf[64];
146         if ((po->flags & mask) == value) {
147             if (first) {
148                 printf("%s", msg);
149                 first = 0;
150             }
151             av_strlcpy(buf, po->name, sizeof(buf));
152             if (po->flags & HAS_ARG) {
153                 av_strlcat(buf, " ", sizeof(buf));
154                 av_strlcat(buf, po->argname, sizeof(buf));
155             }
156             printf("-%-17s  %s\n", buf, po->help);
157         }
158     }
159 }
160
161 void show_help_children(const AVClass *class, int flags)
162 {
163     const AVClass *child = NULL;
164     av_opt_show2(&class, NULL, flags, 0);
165     printf("\n");
166
167     while (child = av_opt_child_class_next(class, child))
168         show_help_children(child, flags);
169 }
170
171 static const OptionDef *find_option(const OptionDef *po, const char *name)
172 {
173     const char *p = strchr(name, ':');
174     int len = p ? p - name : strlen(name);
175
176     while (po->name != NULL) {
177         if (!strncmp(name, po->name, len) && strlen(po->name) == len)
178             break;
179         po++;
180     }
181     return po;
182 }
183
184 #if defined(_WIN32) && !defined(__MINGW32CE__)
185 #include <windows.h>
186 /* Will be leaked on exit */
187 static char** win32_argv_utf8 = NULL;
188 static int win32_argc = 0;
189
190 /**
191  * Prepare command line arguments for executable.
192  * For Windows - perform wide-char to UTF-8 conversion.
193  * Input arguments should be main() function arguments.
194  * @param argc_ptr Arguments number (including executable)
195  * @param argv_ptr Arguments list.
196  */
197 static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
198 {
199     char *argstr_flat;
200     wchar_t **argv_w;
201     int i, buffsize = 0, offset = 0;
202
203     if (win32_argv_utf8) {
204         *argc_ptr = win32_argc;
205         *argv_ptr = win32_argv_utf8;
206         return;
207     }
208
209     win32_argc = 0;
210     argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
211     if (win32_argc <= 0 || !argv_w)
212         return;
213
214     /* determine the UTF-8 buffer size (including NULL-termination symbols) */
215     for (i = 0; i < win32_argc; i++)
216         buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
217                                         NULL, 0, NULL, NULL);
218
219     win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
220     argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
221     if (win32_argv_utf8 == NULL) {
222         LocalFree(argv_w);
223         return;
224     }
225
226     for (i = 0; i < win32_argc; i++) {
227         win32_argv_utf8[i] = &argstr_flat[offset];
228         offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
229                                       &argstr_flat[offset],
230                                       buffsize - offset, NULL, NULL);
231     }
232     win32_argv_utf8[i] = NULL;
233     LocalFree(argv_w);
234
235     *argc_ptr = win32_argc;
236     *argv_ptr = win32_argv_utf8;
237 }
238 #else
239 static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
240 {
241     /* nothing to do */
242 }
243 #endif /* WIN32 && !__MINGW32CE__ */
244
245 int parse_option(void *optctx, const char *opt, const char *arg,
246                  const OptionDef *options)
247 {
248     const OptionDef *po;
249     int bool_val = 1;
250     int *dstcount;
251     void *dst;
252
253     po = find_option(options, opt);
254     if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
255         /* handle 'no' bool option */
256         po = find_option(options, opt + 2);
257         if ((po->name && (po->flags & OPT_BOOL)))
258             bool_val = 0;
259     }
260     if (!po->name)
261         po = find_option(options, "default");
262     if (!po->name) {
263         av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
264         return AVERROR(EINVAL);
265     }
266     if (po->flags & HAS_ARG && !arg) {
267         av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
268         return AVERROR(EINVAL);
269     }
270
271     /* new-style options contain an offset into optctx, old-style address of
272      * a global var*/
273     dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
274                                               : po->u.dst_ptr;
275
276     if (po->flags & OPT_SPEC) {
277         SpecifierOpt **so = dst;
278         char *p = strchr(opt, ':');
279
280         dstcount = (int *)(so + 1);
281         *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
282         (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
283         dst = &(*so)[*dstcount - 1].u;
284     }
285
286     if (po->flags & OPT_STRING) {
287         char *str;
288         str = av_strdup(arg);
289         *(char **)dst = str;
290     } else if (po->flags & OPT_BOOL) {
291         *(int *)dst = bool_val;
292     } else if (po->flags & OPT_INT) {
293         *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
294     } else if (po->flags & OPT_INT64) {
295         *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
296     } else if (po->flags & OPT_TIME) {
297         *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
298     } else if (po->flags & OPT_FLOAT) {
299         *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
300     } else if (po->flags & OPT_DOUBLE) {
301         *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
302     } else if (po->u.func_arg) {
303         int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
304                                         : po->u.func_arg(opt, arg);
305         if (ret < 0) {
306             av_log(NULL, AV_LOG_ERROR,
307                    "Failed to set value '%s' for option '%s'\n", arg, opt);
308             return ret;
309         }
310     }
311     if (po->flags & OPT_EXIT)
312         exit_program(0);
313     return !!(po->flags & HAS_ARG);
314 }
315
316 void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
317                    void (*parse_arg_function)(void *, const char*))
318 {
319     const char *opt;
320     int optindex, handleoptions = 1, ret;
321
322     /* perform system-dependent conversions for arguments list */
323     prepare_app_arguments(&argc, &argv);
324
325     /* parse options */
326     optindex = 1;
327     while (optindex < argc) {
328         opt = argv[optindex++];
329
330         if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
331             if (opt[1] == '-' && opt[2] == '\0') {
332                 handleoptions = 0;
333                 continue;
334             }
335             opt++;
336
337             if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
338                 exit_program(1);
339             optindex += ret;
340         } else {
341             if (parse_arg_function)
342                 parse_arg_function(optctx, opt);
343         }
344     }
345 }
346
347 int locate_option(int argc, char **argv, const OptionDef *options,
348                   const char *optname)
349 {
350     const OptionDef *po;
351     int i;
352
353     for (i = 1; i < argc; i++) {
354         const char *cur_opt = argv[i];
355
356         if (*cur_opt++ != '-')
357             continue;
358
359         po = find_option(options, cur_opt);
360         if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
361             po = find_option(options, cur_opt + 2);
362
363         if ((!po->name && !strcmp(cur_opt, optname)) ||
364              (po->name && !strcmp(optname, po->name)))
365             return i;
366
367         if (!po || po->flags & HAS_ARG)
368             i++;
369     }
370     return 0;
371 }
372
373 static void dump_argument(const char *a)
374 {
375     const unsigned char *p;
376
377     for (p = a; *p; p++)
378         if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
379               *p == '_' || (*p >= 'a' && *p <= 'z')))
380             break;
381     if (!*p) {
382         fputs(a, report_file);
383         return;
384     }
385     fputc('"', report_file);
386     for (p = a; *p; p++) {
387         if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
388             fprintf(report_file, "\\%c", *p);
389         else if (*p < ' ' || *p > '~')
390             fprintf(report_file, "\\x%02x", *p);
391         else
392             fputc(*p, report_file);
393     }
394     fputc('"', report_file);
395 }
396
397 void parse_loglevel(int argc, char **argv, const OptionDef *options)
398 {
399     int idx = locate_option(argc, argv, options, "loglevel");
400     if (!idx)
401         idx = locate_option(argc, argv, options, "v");
402     if (idx && argv[idx + 1])
403         opt_loglevel("loglevel", argv[idx + 1]);
404     idx = locate_option(argc, argv, options, "report");
405     if (idx || getenv("FFREPORT")) {
406         opt_report("report");
407         if (report_file) {
408             int i;
409             fprintf(report_file, "Command line:\n");
410             for (i = 0; i < argc; i++) {
411                 dump_argument(argv[i]);
412                 fputc(i < argc - 1 ? ' ' : '\n', report_file);
413             }
414             fflush(report_file);
415         }
416     }
417 }
418
419 #define FLAGS(o) ((o)->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
420 int opt_default(const char *opt, const char *arg)
421 {
422     const AVOption *oc, *of, *os, *oswr = NULL;
423     char opt_stripped[128];
424     const char *p;
425     const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc, *swr_class;
426
427     if (!(p = strchr(opt, ':')))
428         p = opt + strlen(opt);
429     av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));
430
431     if ((oc = av_opt_find(&cc, opt_stripped, NULL, 0,
432                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
433         ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
434          (oc = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
435         av_dict_set(&codec_opts, opt, arg, FLAGS(oc));
436     if ((of = av_opt_find(&fc, opt, NULL, 0,
437                           AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
438         av_dict_set(&format_opts, opt, arg, FLAGS(of));
439 #if CONFIG_SWSCALE
440     sc = sws_get_class();
441     if ((os = av_opt_find(&sc, opt, NULL, 0,
442                           AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
443         // XXX we only support sws_flags, not arbitrary sws options
444         int ret = av_opt_set(sws_opts, opt, arg, 0);
445         if (ret < 0) {
446             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
447             return ret;
448         }
449     }
450 #endif
451     swr_class = swr_get_class();
452     if (!oc && !of && !os && (oswr = av_opt_find(&swr_class, opt, NULL, 0,
453                           AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
454         int ret = av_opt_set(swr_opts, opt, arg, 0);
455         if (ret < 0) {
456             av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
457             return ret;
458         }
459     }
460
461     if (oc || of || os || oswr)
462         return 0;
463     av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
464     return AVERROR_OPTION_NOT_FOUND;
465 }
466
467 int opt_loglevel(const char *opt, const char *arg)
468 {
469     const struct { const char *name; int level; } log_levels[] = {
470         { "quiet"  , AV_LOG_QUIET   },
471         { "panic"  , AV_LOG_PANIC   },
472         { "fatal"  , AV_LOG_FATAL   },
473         { "error"  , AV_LOG_ERROR   },
474         { "warning", AV_LOG_WARNING },
475         { "info"   , AV_LOG_INFO    },
476         { "verbose", AV_LOG_VERBOSE },
477         { "debug"  , AV_LOG_DEBUG   },
478     };
479     char *tail;
480     int level;
481     int i;
482
483     for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
484         if (!strcmp(log_levels[i].name, arg)) {
485             av_log_set_level(log_levels[i].level);
486             return 0;
487         }
488     }
489
490     level = strtol(arg, &tail, 10);
491     if (*tail) {
492         av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
493                "Possible levels are numbers or:\n", arg);
494         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
495             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
496         exit_program(1);
497     }
498     av_log_set_level(level);
499     return 0;
500 }
501
502 int opt_report(const char *opt)
503 {
504     char filename[64];
505     time_t now;
506     struct tm *tm;
507
508     if (report_file) /* already opened */
509         return 0;
510     time(&now);
511     tm = localtime(&now);
512     snprintf(filename, sizeof(filename), "%s-%04d%02d%02d-%02d%02d%02d.log",
513              program_name,
514              tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
515              tm->tm_hour, tm->tm_min, tm->tm_sec);
516     report_file = fopen(filename, "w");
517     if (!report_file) {
518         av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
519                filename, strerror(errno));
520         return AVERROR(errno);
521     }
522     av_log_set_callback(log_callback_report);
523     av_log(NULL, AV_LOG_INFO,
524            "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
525            "Report written to \"%s\"\n",
526            program_name,
527            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
528            tm->tm_hour, tm->tm_min, tm->tm_sec,
529            filename);
530     av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
531     return 0;
532 }
533
534 int opt_max_alloc(const char *opt, const char *arg)
535 {
536     char *tail;
537     size_t max;
538
539     max = strtol(arg, &tail, 10);
540     if (*tail) {
541         av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
542         exit_program(1);
543     }
544     av_max_alloc(max);
545     return 0;
546 }
547
548 int opt_cpuflags(const char *opt, const char *arg)
549 {
550     static const AVOption cpuflags_opts[] = {
551         { "flags"   , NULL, 0, AV_OPT_TYPE_FLAGS, { 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
552         { "altivec" , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ALTIVEC  },    .unit = "flags" },
553         { "mmx"     , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_MMX      },    .unit = "flags" },
554         { "mmx2"    , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_MMX2     },    .unit = "flags" },
555         { "sse"     , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE      },    .unit = "flags" },
556         { "sse2"    , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE2     },    .unit = "flags" },
557         { "sse2slow", NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE2SLOW },    .unit = "flags" },
558         { "sse3"    , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE3     },    .unit = "flags" },
559         { "sse3slow", NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE3SLOW },    .unit = "flags" },
560         { "ssse3"   , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSSE3    },    .unit = "flags" },
561         { "atom"    , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ATOM     },    .unit = "flags" },
562         { "sse4.1"  , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE4     },    .unit = "flags" },
563         { "sse4.2"  , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_SSE42    },    .unit = "flags" },
564         { "avx"     , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_AVX      },    .unit = "flags" },
565         { "xop"     , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_XOP      },    .unit = "flags" },
566         { "fma4"    , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_FMA4     },    .unit = "flags" },
567         { "3dnow"   , NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_3DNOW    },    .unit = "flags" },
568         { "3dnowext", NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_3DNOWEXT },    .unit = "flags" },
569
570         { "armv5te",  NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ARMV5TE  },    .unit = "flags" },
571         { "armv6",    NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ARMV6    },    .unit = "flags" },
572         { "armv6t2",  NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_ARMV6T2  },    .unit = "flags" },
573         { "vfp",      NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_VFP      },    .unit = "flags" },
574         { "vfpv3",    NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_VFPV3    },    .unit = "flags" },
575         { "neon",     NULL, 0, AV_OPT_TYPE_CONST, { AV_CPU_FLAG_NEON     },    .unit = "flags" },
576
577         { NULL },
578     };
579     static const AVClass class = {
580         .class_name = "cpuflags",
581         .item_name  = av_default_item_name,
582         .option     = cpuflags_opts,
583         .version    = LIBAVUTIL_VERSION_INT,
584     };
585     int flags = av_get_cpu_flags();
586     int ret;
587     const AVClass *pclass = &class;
588
589     if ((ret = av_opt_eval_flags(&pclass, &cpuflags_opts[0], arg, &flags)) < 0)
590         return ret;
591
592     av_force_cpu_flags(flags);
593     return 0;
594 }
595
596 int opt_codec_debug(const char *opt, const char *arg)
597 {
598     av_log_set_level(AV_LOG_DEBUG);
599     return opt_default(opt, arg);
600 }
601
602 int opt_timelimit(const char *opt, const char *arg)
603 {
604 #if HAVE_SETRLIMIT
605     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
606     struct rlimit rl = { lim, lim + 1 };
607     if (setrlimit(RLIMIT_CPU, &rl))
608         perror("setrlimit");
609 #else
610     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
611 #endif
612     return 0;
613 }
614
615 void print_error(const char *filename, int err)
616 {
617     char errbuf[128];
618     const char *errbuf_ptr = errbuf;
619
620     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
621         errbuf_ptr = strerror(AVUNERROR(err));
622     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
623 }
624
625 static int warned_cfg = 0;
626
627 #define INDENT        1
628 #define SHOW_VERSION  2
629 #define SHOW_CONFIG   4
630 #define SHOW_COPYRIGHT 8
631
632 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
633     if (CONFIG_##LIBNAME) {                                             \
634         const char *indent = flags & INDENT? "  " : "";                 \
635         if (flags & SHOW_VERSION) {                                     \
636             unsigned int version = libname##_version();                 \
637             av_log(NULL, level,                                         \
638                    "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n",            \
639                    indent, #libname,                                    \
640                    LIB##LIBNAME##_VERSION_MAJOR,                        \
641                    LIB##LIBNAME##_VERSION_MINOR,                        \
642                    LIB##LIBNAME##_VERSION_MICRO,                        \
643                    version >> 16, version >> 8 & 0xff, version & 0xff); \
644         }                                                               \
645         if (flags & SHOW_CONFIG) {                                      \
646             const char *cfg = libname##_configuration();                \
647             if (strcmp(FFMPEG_CONFIGURATION, cfg)) {                    \
648                 if (!warned_cfg) {                                      \
649                     av_log(NULL, level,                                 \
650                             "%sWARNING: library configuration mismatch\n", \
651                             indent);                                    \
652                     warned_cfg = 1;                                     \
653                 }                                                       \
654                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
655                         indent, #libname, cfg);                         \
656             }                                                           \
657         }                                                               \
658     }                                                                   \
659
660 static void print_all_libs_info(int flags, int level)
661 {
662     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
663     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
664     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
665     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
666     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
667 //    PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
668     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
669     PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);
670 #if CONFIG_POSTPROC
671     PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
672 #endif
673 }
674
675 static void print_program_info(int flags, int level)
676 {
677     const char *indent = flags & INDENT? "  " : "";
678
679     av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
680     if (flags & SHOW_COPYRIGHT)
681         av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
682                program_birth_year, this_year);
683     av_log(NULL, level, "\n");
684     av_log(NULL, level, "%sbuilt on %s %s with %s %s\n",
685            indent, __DATE__, __TIME__, CC_TYPE, CC_VERSION);
686     av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
687 }
688
689 void show_banner(int argc, char **argv, const OptionDef *options)
690 {
691     int idx = locate_option(argc, argv, options, "version");
692     if (idx)
693         return;
694
695     print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
696     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_INFO);
697     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
698 }
699
700 int opt_version(const char *opt, const char *arg) {
701     av_log_set_callback(log_callback_help);
702     print_program_info (0           , AV_LOG_INFO);
703     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
704     return 0;
705 }
706
707 int opt_license(const char *opt, const char *arg)
708 {
709     printf(
710 #if CONFIG_NONFREE
711     "This version of %s has nonfree parts compiled in.\n"
712     "Therefore it is not legally redistributable.\n",
713     program_name
714 #elif CONFIG_GPLV3
715     "%s is free software; you can redistribute it and/or modify\n"
716     "it under the terms of the GNU General Public License as published by\n"
717     "the Free Software Foundation; either version 3 of the License, or\n"
718     "(at your option) any later version.\n"
719     "\n"
720     "%s is distributed in the hope that it will be useful,\n"
721     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
722     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
723     "GNU General Public License for more details.\n"
724     "\n"
725     "You should have received a copy of the GNU General Public License\n"
726     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
727     program_name, program_name, program_name
728 #elif CONFIG_GPL
729     "%s is free software; you can redistribute it and/or modify\n"
730     "it under the terms of the GNU General Public License as published by\n"
731     "the Free Software Foundation; either version 2 of the License, or\n"
732     "(at your option) any later version.\n"
733     "\n"
734     "%s is distributed in the hope that it will be useful,\n"
735     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
736     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
737     "GNU General Public License for more details.\n"
738     "\n"
739     "You should have received a copy of the GNU General Public License\n"
740     "along with %s; if not, write to the Free Software\n"
741     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
742     program_name, program_name, program_name
743 #elif CONFIG_LGPLV3
744     "%s is free software; you can redistribute it and/or modify\n"
745     "it under the terms of the GNU Lesser General Public License as published by\n"
746     "the Free Software Foundation; either version 3 of the License, or\n"
747     "(at your option) any later version.\n"
748     "\n"
749     "%s is distributed in the hope that it will be useful,\n"
750     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
751     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
752     "GNU Lesser General Public License for more details.\n"
753     "\n"
754     "You should have received a copy of the GNU Lesser General Public License\n"
755     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
756     program_name, program_name, program_name
757 #else
758     "%s is free software; you can redistribute it and/or\n"
759     "modify it under the terms of the GNU Lesser General Public\n"
760     "License as published by the Free Software Foundation; either\n"
761     "version 2.1 of the License, or (at your option) any later version.\n"
762     "\n"
763     "%s is distributed in the hope that it will be useful,\n"
764     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
765     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
766     "Lesser General Public License for more details.\n"
767     "\n"
768     "You should have received a copy of the GNU Lesser General Public\n"
769     "License along with %s; if not, write to the Free Software\n"
770     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
771     program_name, program_name, program_name
772 #endif
773     );
774     return 0;
775 }
776
777 int opt_formats(const char *opt, const char *arg)
778 {
779     AVInputFormat *ifmt  = NULL;
780     AVOutputFormat *ofmt = NULL;
781     const char *last_name;
782
783     printf("File formats:\n"
784            " D. = Demuxing supported\n"
785            " .E = Muxing supported\n"
786            " --\n");
787     last_name = "000";
788     for (;;) {
789         int decode = 0;
790         int encode = 0;
791         const char *name      = NULL;
792         const char *long_name = NULL;
793
794         while ((ofmt = av_oformat_next(ofmt))) {
795             if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
796                 strcmp(ofmt->name, last_name) > 0) {
797                 name      = ofmt->name;
798                 long_name = ofmt->long_name;
799                 encode    = 1;
800             }
801         }
802         while ((ifmt = av_iformat_next(ifmt))) {
803             if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
804                 strcmp(ifmt->name, last_name) > 0) {
805                 name      = ifmt->name;
806                 long_name = ifmt->long_name;
807                 encode    = 0;
808             }
809             if (name && strcmp(ifmt->name, name) == 0)
810                 decode = 1;
811         }
812         if (name == NULL)
813             break;
814         last_name = name;
815
816         printf(" %s%s %-15s %s\n",
817                decode ? "D" : " ",
818                encode ? "E" : " ",
819                name,
820             long_name ? long_name:" ");
821     }
822     return 0;
823 }
824
825 static char get_media_type_char(enum AVMediaType type)
826 {
827     static const char map[AVMEDIA_TYPE_NB] = {
828         [AVMEDIA_TYPE_VIDEO]      = 'V',
829         [AVMEDIA_TYPE_AUDIO]      = 'A',
830         [AVMEDIA_TYPE_DATA]       = 'D',
831         [AVMEDIA_TYPE_SUBTITLE]   = 'S',
832         [AVMEDIA_TYPE_ATTACHMENT] = 'T',
833     };
834     return type >= 0 && type < AVMEDIA_TYPE_NB && map[type] ? map[type] : '?';
835 }
836
837 int opt_codecs(const char *opt, const char *arg)
838 {
839     AVCodec *p = NULL, *p2;
840     const char *last_name;
841     printf("Codecs:\n"
842            " D..... = Decoding supported\n"
843            " .E.... = Encoding supported\n"
844            " ..V... = Video codec\n"
845            " ..A... = Audio codec\n"
846            " ..S... = Subtitle codec\n"
847            " ...S.. = Supports draw_horiz_band\n"
848            " ....D. = Supports direct rendering method 1\n"
849            " .....T = Supports weird frame truncation\n"
850            " ------\n");
851     last_name= "000";
852     for (;;) {
853         int decode = 0;
854         int encode = 0;
855         int cap    = 0;
856
857         p2 = NULL;
858         while ((p = av_codec_next(p))) {
859             if ((p2 == NULL || strcmp(p->name, p2->name) < 0) &&
860                 strcmp(p->name, last_name) > 0) {
861                 p2 = p;
862                 decode = encode = cap = 0;
863             }
864             if (p2 && strcmp(p->name, p2->name) == 0) {
865                 if (av_codec_is_decoder(p))
866                     decode = 1;
867                 if (av_codec_is_encoder(p))
868                     encode = 1;
869                 cap |= p->capabilities;
870             }
871         }
872         if (p2 == NULL)
873             break;
874         last_name = p2->name;
875
876         printf(" %s%s%c%s%s%s %-15s %s",
877                decode ? "D" : (/* p2->decoder ? "d" : */ " "),
878                encode ? "E" : " ",
879                get_media_type_char(p2->type),
880                cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S" : " ",
881                cap & CODEC_CAP_DR1 ? "D" : " ",
882                cap & CODEC_CAP_TRUNCATED ? "T" : " ",
883                p2->name,
884                p2->long_name ? p2->long_name : "");
885 #if 0
886             if (p2->decoder && decode == 0)
887                 printf(" use %s for decoding", p2->decoder->name);
888 #endif
889         printf("\n");
890     }
891     printf("\n");
892     printf("Note, the names of encoders and decoders do not always match, so there are\n"
893            "several cases where the above table shows encoder only or decoder only entries\n"
894            "even though both encoding and decoding are supported. For example, the h263\n"
895            "decoder corresponds to the h263 and h263p encoders, for file formats it is even\n"
896            "worse.\n");
897     return 0;
898 }
899
900 int opt_bsfs(const char *opt, const char *arg)
901 {
902     AVBitStreamFilter *bsf = NULL;
903
904     printf("Bitstream filters:\n");
905     while ((bsf = av_bitstream_filter_next(bsf)))
906         printf("%s\n", bsf->name);
907     printf("\n");
908     return 0;
909 }
910
911 int opt_protocols(const char *opt, const char *arg)
912 {
913     void *opaque = NULL;
914     const char *name;
915
916     printf("Supported file protocols:\n"
917            "Input:\n");
918     while ((name = avio_enum_protocols(&opaque, 0)))
919         printf("%s\n", name);
920     printf("Output:\n");
921     while ((name = avio_enum_protocols(&opaque, 1)))
922         printf("%s\n", name);
923     return 0;
924 }
925
926 int opt_filters(const char *opt, const char *arg)
927 {
928     AVFilter av_unused(**filter) = NULL;
929     char descr[64], *descr_cur;
930     int i, j;
931     const AVFilterPad *pad;
932
933     printf("Filters:\n");
934 #if CONFIG_AVFILTER
935     while ((filter = av_filter_next(filter)) && *filter) {
936         descr_cur = descr;
937         for (i = 0; i < 2; i++) {
938             if (i) {
939                 *(descr_cur++) = '-';
940                 *(descr_cur++) = '>';
941             }
942             pad = i ? (*filter)->outputs : (*filter)->inputs;
943             for (j = 0; pad[j].name; j++) {
944                 if (descr_cur >= descr + sizeof(descr) - 4)
945                     break;
946                 *(descr_cur++) = get_media_type_char(pad[j].type);
947             }
948             if (!j)
949                 *(descr_cur++) = '|';
950         }
951         *descr_cur = 0;
952         printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
953     }
954 #endif
955     return 0;
956 }
957
958 int opt_pix_fmts(const char *opt, const char *arg)
959 {
960     enum PixelFormat pix_fmt;
961
962     printf("Pixel formats:\n"
963            "I.... = Supported Input  format for conversion\n"
964            ".O... = Supported Output format for conversion\n"
965            "..H.. = Hardware accelerated format\n"
966            "...P. = Paletted format\n"
967            "....B = Bitstream format\n"
968            "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
969            "-----\n");
970
971 #if !CONFIG_SWSCALE
972 #   define sws_isSupportedInput(x)  0
973 #   define sws_isSupportedOutput(x) 0
974 #endif
975
976     for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
977         const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
978         if(!pix_desc->name)
979             continue;
980         printf("%c%c%c%c%c %-16s       %d            %2d\n",
981                sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
982                sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
983                pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
984                pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
985                pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
986                pix_desc->name,
987                pix_desc->nb_components,
988                av_get_bits_per_pixel(pix_desc));
989     }
990     return 0;
991 }
992
993 int show_sample_fmts(const char *opt, const char *arg)
994 {
995     int i;
996     char fmt_str[128];
997     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
998         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
999     return 0;
1000 }
1001
1002 int read_yesno(void)
1003 {
1004     int c = getchar();
1005     int yesno = (toupper(c) == 'Y');
1006
1007     while (c != '\n' && c != EOF)
1008         c = getchar();
1009
1010     return yesno;
1011 }
1012
1013 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1014 {
1015     int ret;
1016     FILE *f = fopen(filename, "rb");
1017
1018     if (!f) {
1019         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1020                strerror(errno));
1021         return AVERROR(errno);
1022     }
1023     fseek(f, 0, SEEK_END);
1024     *size = ftell(f);
1025     fseek(f, 0, SEEK_SET);
1026     *bufptr = av_malloc(*size + 1);
1027     if (!*bufptr) {
1028         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1029         fclose(f);
1030         return AVERROR(ENOMEM);
1031     }
1032     ret = fread(*bufptr, 1, *size, f);
1033     if (ret < *size) {
1034         av_free(*bufptr);
1035         if (ferror(f)) {
1036             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1037                    filename, strerror(errno));
1038             ret = AVERROR(errno);
1039         } else
1040             ret = AVERROR_EOF;
1041     } else {
1042         ret = 0;
1043         (*bufptr)[*size++] = '\0';
1044     }
1045
1046     fclose(f);
1047     return ret;
1048 }
1049
1050 FILE *get_preset_file(char *filename, size_t filename_size,
1051                       const char *preset_name, int is_path,
1052                       const char *codec_name)
1053 {
1054     FILE *f = NULL;
1055     int i;
1056     const char *base[3] = { getenv("FFMPEG_DATADIR"),
1057                             getenv("HOME"),
1058                             FFMPEG_DATADIR, };
1059
1060     if (is_path) {
1061         av_strlcpy(filename, preset_name, filename_size);
1062         f = fopen(filename, "r");
1063     } else {
1064 #ifdef _WIN32
1065         char datadir[MAX_PATH], *ls;
1066         base[2] = NULL;
1067
1068         if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
1069         {
1070             for (ls = datadir; ls < datadir + strlen(datadir); ls++)
1071                 if (*ls == '\\') *ls = '/';
1072
1073             if (ls = strrchr(datadir, '/'))
1074             {
1075                 *ls = 0;
1076                 strncat(datadir, "/ffpresets",  sizeof(datadir) - 1 - strlen(datadir));
1077                 base[2] = datadir;
1078             }
1079         }
1080 #endif
1081         for (i = 0; i < 3 && !f; i++) {
1082             if (!base[i])
1083                 continue;
1084             snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1085                      i != 1 ? "" : "/.ffmpeg", preset_name);
1086             f = fopen(filename, "r");
1087             if (!f && codec_name) {
1088                 snprintf(filename, filename_size,
1089                          "%s%s/%s-%s.ffpreset",
1090                          base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1091                          preset_name);
1092                 f = fopen(filename, "r");
1093             }
1094         }
1095     }
1096
1097     return f;
1098 }
1099
1100 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1101 {
1102     if (*spec <= '9' && *spec >= '0') /* opt:index */
1103         return strtol(spec, NULL, 0) == st->index;
1104     else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
1105              *spec == 't') { /* opt:[vasdt] */
1106         enum AVMediaType type;
1107
1108         switch (*spec++) {
1109         case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
1110         case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
1111         case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
1112         case 'd': type = AVMEDIA_TYPE_DATA;       break;
1113         case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
1114         default: abort(); // never reached, silence warning
1115         }
1116         if (type != st->codec->codec_type)
1117             return 0;
1118         if (*spec++ == ':') { /* possibly followed by :index */
1119             int i, index = strtol(spec, NULL, 0);
1120             for (i = 0; i < s->nb_streams; i++)
1121                 if (s->streams[i]->codec->codec_type == type && index-- == 0)
1122                    return i == st->index;
1123             return 0;
1124         }
1125         return 1;
1126     } else if (*spec == 'p' && *(spec + 1) == ':') {
1127         int prog_id, i, j;
1128         char *endptr;
1129         spec += 2;
1130         prog_id = strtol(spec, &endptr, 0);
1131         for (i = 0; i < s->nb_programs; i++) {
1132             if (s->programs[i]->id != prog_id)
1133                 continue;
1134
1135             if (*endptr++ == ':') {
1136                 int stream_idx = strtol(endptr, NULL, 0);
1137                 return stream_idx >= 0 &&
1138                     stream_idx < s->programs[i]->nb_stream_indexes &&
1139                     st->index == s->programs[i]->stream_index[stream_idx];
1140             }
1141
1142             for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
1143                 if (st->index == s->programs[i]->stream_index[j])
1144                     return 1;
1145         }
1146         return 0;
1147     } else if (!*spec) /* empty specifier, matches everything */
1148         return 1;
1149
1150     av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1151     return AVERROR(EINVAL);
1152 }
1153
1154 AVDictionary *filter_codec_opts(AVDictionary *opts, AVCodec *codec,
1155                                 AVFormatContext *s, AVStream *st)
1156 {
1157     AVDictionary    *ret = NULL;
1158     AVDictionaryEntry *t = NULL;
1159     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1160                                       : AV_OPT_FLAG_DECODING_PARAM;
1161     char          prefix = 0;
1162     const AVClass    *cc = avcodec_get_class();
1163
1164     if (!codec)
1165         return NULL;
1166
1167     switch (codec->type) {
1168     case AVMEDIA_TYPE_VIDEO:
1169         prefix  = 'v';
1170         flags  |= AV_OPT_FLAG_VIDEO_PARAM;
1171         break;
1172     case AVMEDIA_TYPE_AUDIO:
1173         prefix  = 'a';
1174         flags  |= AV_OPT_FLAG_AUDIO_PARAM;
1175         break;
1176     case AVMEDIA_TYPE_SUBTITLE:
1177         prefix  = 's';
1178         flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
1179         break;
1180     }
1181
1182     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1183         char *p = strchr(t->key, ':');
1184
1185         /* check stream specification in opt name */
1186         if (p)
1187             switch (check_stream_specifier(s, st, p + 1)) {
1188             case  1: *p = 0; break;
1189             case  0:         continue;
1190             default:         return NULL;
1191             }
1192
1193         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1194             (codec && codec->priv_class &&
1195              av_opt_find(&codec->priv_class, t->key, NULL, flags,
1196                          AV_OPT_SEARCH_FAKE_OBJ)))
1197             av_dict_set(&ret, t->key, t->value, 0);
1198         else if (t->key[0] == prefix &&
1199                  av_opt_find(&cc, t->key + 1, NULL, flags,
1200                              AV_OPT_SEARCH_FAKE_OBJ))
1201             av_dict_set(&ret, t->key + 1, t->value, 0);
1202
1203         if (p)
1204             *p = ':';
1205     }
1206     return ret;
1207 }
1208
1209 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1210                                            AVDictionary *codec_opts)
1211 {
1212     int i;
1213     AVDictionary **opts;
1214
1215     if (!s->nb_streams)
1216         return NULL;
1217     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1218     if (!opts) {
1219         av_log(NULL, AV_LOG_ERROR,
1220                "Could not alloc memory for stream options.\n");
1221         return NULL;
1222     }
1223     for (i = 0; i < s->nb_streams; i++)
1224         opts[i] = filter_codec_opts(codec_opts, avcodec_find_decoder(s->streams[i]->codec->codec_id),
1225                                     s, s->streams[i]);
1226     return opts;
1227 }
1228
1229 void *grow_array(void *array, int elem_size, int *size, int new_size)
1230 {
1231     if (new_size >= INT_MAX / elem_size) {
1232         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1233         exit_program(1);
1234     }
1235     if (*size < new_size) {
1236         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1237         if (!tmp) {
1238             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1239             exit_program(1);
1240         }
1241         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1242         *size = new_size;
1243         return tmp;
1244     }
1245     return array;
1246 }