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