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