]> git.sesse.net Git - ffmpeg/blob - cmdutils.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / cmdutils.c
1 /*
2  * Various utilities for command line tools
3  * Copyright (c) 2000-2003 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <string.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <math.h>
26
27 /* Include only the enabled headers since some compilers (namely, Sun
28    Studio) will not omit unused inline functions and create undefined
29    references to libraries that are not being built. */
30
31 #include "config.h"
32 #include "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 = 2012;
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, const char *opt)
541 {
542     const OptionGroupDef *p = groups;
543
544     while (p->name) {
545         if (p->sep && !strcmp(p->sep, opt))
546             return p - groups;
547         p++;
548     }
549
550     return -1;
551 }
552
553 /*
554  * Finish parsing an option group.
555  *
556  * @param group_idx which group definition should this group belong to
557  * @param arg argument of the group delimiting option
558  */
559 static void finish_group(OptionParseContext *octx, int group_idx,
560                          const char *arg)
561 {
562     OptionGroupList *l = &octx->groups[group_idx];
563     OptionGroup *g;
564
565     GROW_ARRAY(l->groups, l->nb_groups);
566     g = &l->groups[l->nb_groups - 1];
567
568     *g             = octx->cur_group;
569     g->arg         = arg;
570     g->group_def   = l->group_def;
571 #if CONFIG_SWSCALE
572     g->sws_opts    = sws_opts;
573 #endif
574     g->swr_opts    = swr_opts;
575     g->codec_opts  = codec_opts;
576     g->format_opts = format_opts;
577
578     codec_opts  = NULL;
579     format_opts = NULL;
580 #if CONFIG_SWSCALE
581     sws_opts    = NULL;
582 #endif
583     swr_opts    = NULL;
584     init_opts();
585
586     memset(&octx->cur_group, 0, sizeof(octx->cur_group));
587 }
588
589 /*
590  * Add an option instance to currently parsed group.
591  */
592 static void add_opt(OptionParseContext *octx, const OptionDef *opt,
593                     const char *key, const char *val)
594 {
595     int global = !(opt->flags & (OPT_PERFILE | OPT_SPEC | OPT_OFFSET));
596     OptionGroup *g = global ? &octx->global_opts : &octx->cur_group;
597
598     GROW_ARRAY(g->opts, g->nb_opts);
599     g->opts[g->nb_opts - 1].opt = opt;
600     g->opts[g->nb_opts - 1].key = key;
601     g->opts[g->nb_opts - 1].val = val;
602 }
603
604 static void init_parse_context(OptionParseContext *octx,
605                                const OptionGroupDef *groups)
606 {
607     static const OptionGroupDef global_group = { "global" };
608     const OptionGroupDef *g = groups;
609     int i;
610
611     memset(octx, 0, sizeof(*octx));
612
613     while (g->name)
614         g++;
615     octx->nb_groups = g - groups;
616     octx->groups    = av_mallocz(sizeof(*octx->groups) * octx->nb_groups);
617     if (!octx->groups)
618         exit(1);
619
620     for (i = 0; i < octx->nb_groups; i++)
621         octx->groups[i].group_def = &groups[i];
622
623     octx->global_opts.group_def = &global_group;
624     octx->global_opts.arg       = "";
625
626     init_opts();
627 }
628
629 void uninit_parse_context(OptionParseContext *octx)
630 {
631     int i, j;
632
633     for (i = 0; i < octx->nb_groups; i++) {
634         OptionGroupList *l = &octx->groups[i];
635
636         for (j = 0; j < l->nb_groups; j++) {
637             av_freep(&l->groups[j].opts);
638             av_dict_free(&l->groups[j].codec_opts);
639             av_dict_free(&l->groups[j].format_opts);
640 #if CONFIG_SWSCALE
641             sws_freeContext(l->groups[j].sws_opts);
642 #endif
643             if(CONFIG_SWRESAMPLE)
644                 swr_free(&l->groups[j].swr_opts);
645         }
646         av_freep(&l->groups);
647     }
648     av_freep(&octx->groups);
649
650     av_freep(&octx->cur_group.opts);
651     av_freep(&octx->global_opts.opts);
652
653     uninit_opts();
654 }
655
656 int split_commandline(OptionParseContext *octx, int argc, char *argv[],
657                       const OptionDef *options,
658                       const OptionGroupDef *groups)
659 {
660     int optindex = 1;
661
662     /* perform system-dependent conversions for arguments list */
663     prepare_app_arguments(&argc, &argv);
664
665     init_parse_context(octx, groups);
666     av_log(NULL, AV_LOG_DEBUG, "Splitting the commandline.\n");
667
668     while (optindex < argc) {
669         const char *opt = argv[optindex++], *arg;
670         const OptionDef *po;
671         int ret;
672
673         av_log(NULL, AV_LOG_DEBUG, "Reading option '%s' ...", opt);
674
675         /* unnamed group separators, e.g. output filename */
676         if (opt[0] != '-' || !opt[1]) {
677             finish_group(octx, 0, opt);
678             av_log(NULL, AV_LOG_DEBUG, " matched as %s.\n", groups[0].name);
679             continue;
680         }
681         opt++;
682
683 #define GET_ARG(arg)                                                           \
684 do {                                                                           \
685     arg = argv[optindex++];                                                    \
686     if (!arg) {                                                                \
687         av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'.\n", opt);\
688         return AVERROR(EINVAL);                                                \
689     }                                                                          \
690 } while (0)
691
692         /* named group separators, e.g. -i */
693         if ((ret = match_group_separator(groups, opt)) >= 0) {
694             GET_ARG(arg);
695             finish_group(octx, ret, arg);
696             av_log(NULL, AV_LOG_DEBUG, " matched as %s with argument '%s'.\n",
697                    groups[ret].name, arg);
698             continue;
699         }
700
701         /* normal options */
702         po = find_option(options, opt);
703         if (po->name) {
704             if (po->flags & OPT_EXIT) {
705                 /* optional argument, e.g. -h */
706                 arg = argv[optindex++];
707             } else if (po->flags & HAS_ARG) {
708                 GET_ARG(arg);
709             } else {
710                 arg = "1";
711             }
712
713             add_opt(octx, po, opt, arg);
714             av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
715                    "argument '%s'.\n", po->name, po->help, arg);
716             continue;
717         }
718
719         /* AVOptions */
720         if (argv[optindex]) {
721             ret = opt_default(NULL, opt, argv[optindex]);
722             if (ret >= 0) {
723                 av_log(NULL, AV_LOG_DEBUG, " matched as AVOption '%s' with "
724                        "argument '%s'.\n", opt, argv[optindex]);
725                 optindex++;
726                 continue;
727             } else if (ret != AVERROR_OPTION_NOT_FOUND) {
728                 av_log(NULL, AV_LOG_ERROR, "Error parsing option '%s' "
729                        "with argument '%s'.\n", opt, argv[optindex]);
730                 return ret;
731             }
732         }
733
734         /* boolean -nofoo options */
735         if (opt[0] == 'n' && opt[1] == 'o' &&
736             (po = find_option(options, opt + 2)) &&
737             po->name && po->flags & OPT_BOOL) {
738             add_opt(octx, po, opt, "0");
739             av_log(NULL, AV_LOG_DEBUG, " matched as option '%s' (%s) with "
740                    "argument 0.\n", po->name, po->help);
741             continue;
742         }
743
744         av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'.\n", opt);
745         return AVERROR_OPTION_NOT_FOUND;
746     }
747
748     if (octx->cur_group.nb_opts || codec_opts || format_opts)
749         av_log(NULL, AV_LOG_WARNING, "Trailing options were found on the "
750                "commandline.\n");
751
752     av_log(NULL, AV_LOG_DEBUG, "Finished splitting the commandline.\n");
753
754     return 0;
755 }
756
757 int opt_loglevel(void *optctx, const char *opt, const char *arg)
758 {
759     const struct { const char *name; int level; } log_levels[] = {
760         { "quiet"  , AV_LOG_QUIET   },
761         { "panic"  , AV_LOG_PANIC   },
762         { "fatal"  , AV_LOG_FATAL   },
763         { "error"  , AV_LOG_ERROR   },
764         { "warning", AV_LOG_WARNING },
765         { "info"   , AV_LOG_INFO    },
766         { "verbose", AV_LOG_VERBOSE },
767         { "debug"  , AV_LOG_DEBUG   },
768     };
769     char *tail;
770     int level;
771     int i;
772
773     for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
774         if (!strcmp(log_levels[i].name, arg)) {
775             av_log_set_level(log_levels[i].level);
776             return 0;
777         }
778     }
779
780     level = strtol(arg, &tail, 10);
781     if (*tail) {
782         av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
783                "Possible levels are numbers or:\n", arg);
784         for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
785             av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
786         exit(1);
787     }
788     av_log_set_level(level);
789     return 0;
790 }
791
792 static void expand_filename_template(AVBPrint *bp, const char *template,
793                                      struct tm *tm)
794 {
795     int c;
796
797     while ((c = *(template++))) {
798         if (c == '%') {
799             if (!(c = *(template++)))
800                 break;
801             switch (c) {
802             case 'p':
803                 av_bprintf(bp, "%s", program_name);
804                 break;
805             case 't':
806                 av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
807                            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
808                            tm->tm_hour, tm->tm_min, tm->tm_sec);
809                 break;
810             case '%':
811                 av_bprint_chars(bp, c, 1);
812                 break;
813             }
814         } else {
815             av_bprint_chars(bp, c, 1);
816         }
817     }
818 }
819
820 static int init_report(const char *env)
821 {
822     char *filename_template = NULL;
823     char *key, *val;
824     int ret, count = 0;
825     time_t now;
826     struct tm *tm;
827     AVBPrint filename;
828
829     if (report_file) /* already opened */
830         return 0;
831     time(&now);
832     tm = localtime(&now);
833
834     while (env && *env) {
835         if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
836             if (count)
837                 av_log(NULL, AV_LOG_ERROR,
838                        "Failed to parse FFREPORT environment variable: %s\n",
839                        av_err2str(ret));
840             break;
841         }
842         if (*env)
843             env++;
844         count++;
845         if (!strcmp(key, "file")) {
846             av_free(filename_template);
847             filename_template = val;
848             val = NULL;
849         } else {
850             av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
851         }
852         av_free(val);
853         av_free(key);
854     }
855
856     av_bprint_init(&filename, 0, 1);
857     expand_filename_template(&filename,
858                              av_x_if_null(filename_template, "%p-%t.log"), tm);
859     av_free(filename_template);
860     if (!av_bprint_is_complete(&filename)) {
861         av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
862         return AVERROR(ENOMEM);
863     }
864
865     report_file = fopen(filename.str, "w");
866     if (!report_file) {
867         av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
868                filename.str, strerror(errno));
869         return AVERROR(errno);
870     }
871     av_log_set_callback(log_callback_report);
872     av_log(NULL, AV_LOG_INFO,
873            "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
874            "Report written to \"%s\"\n",
875            program_name,
876            tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
877            tm->tm_hour, tm->tm_min, tm->tm_sec,
878            filename.str);
879     av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
880     av_bprint_finalize(&filename, NULL);
881     return 0;
882 }
883
884 int opt_report(const char *opt)
885 {
886     return init_report(NULL);
887 }
888
889 int opt_max_alloc(void *optctx, const char *opt, const char *arg)
890 {
891     char *tail;
892     size_t max;
893
894     max = strtol(arg, &tail, 10);
895     if (*tail) {
896         av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
897         exit(1);
898     }
899     av_max_alloc(max);
900     return 0;
901 }
902
903 int opt_cpuflags(void *optctx, const char *opt, const char *arg)
904 {
905     int ret;
906     unsigned flags = av_get_cpu_flags();
907
908     if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
909         return ret;
910
911     av_force_cpu_flags(flags);
912     return 0;
913 }
914
915 int opt_timelimit(void *optctx, const char *opt, const char *arg)
916 {
917 #if HAVE_SETRLIMIT
918     int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
919     struct rlimit rl = { lim, lim + 1 };
920     if (setrlimit(RLIMIT_CPU, &rl))
921         perror("setrlimit");
922 #else
923     av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
924 #endif
925     return 0;
926 }
927
928 void print_error(const char *filename, int err)
929 {
930     char errbuf[128];
931     const char *errbuf_ptr = errbuf;
932
933     if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
934         errbuf_ptr = strerror(AVUNERROR(err));
935     av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
936 }
937
938 static int warned_cfg = 0;
939
940 #define INDENT        1
941 #define SHOW_VERSION  2
942 #define SHOW_CONFIG   4
943 #define SHOW_COPYRIGHT 8
944
945 #define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
946     if (CONFIG_##LIBNAME) {                                             \
947         const char *indent = flags & INDENT? "  " : "";                 \
948         if (flags & SHOW_VERSION) {                                     \
949             unsigned int version = libname##_version();                 \
950             av_log(NULL, level,                                         \
951                    "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n",            \
952                    indent, #libname,                                    \
953                    LIB##LIBNAME##_VERSION_MAJOR,                        \
954                    LIB##LIBNAME##_VERSION_MINOR,                        \
955                    LIB##LIBNAME##_VERSION_MICRO,                        \
956                    version >> 16, version >> 8 & 0xff, version & 0xff); \
957         }                                                               \
958         if (flags & SHOW_CONFIG) {                                      \
959             const char *cfg = libname##_configuration();                \
960             if (strcmp(FFMPEG_CONFIGURATION, cfg)) {                    \
961                 if (!warned_cfg) {                                      \
962                     av_log(NULL, level,                                 \
963                             "%sWARNING: library configuration mismatch\n", \
964                             indent);                                    \
965                     warned_cfg = 1;                                     \
966                 }                                                       \
967                 av_log(NULL, level, "%s%-11s configuration: %s\n",      \
968                         indent, #libname, cfg);                         \
969             }                                                           \
970         }                                                               \
971     }                                                                   \
972
973 static void print_all_libs_info(int flags, int level)
974 {
975     PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
976     PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
977     PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
978     PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
979     PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
980 //    PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
981     PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
982     PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);
983 #if CONFIG_POSTPROC
984     PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
985 #endif
986 }
987
988 static void print_program_info(int flags, int level)
989 {
990     const char *indent = flags & INDENT? "  " : "";
991
992     av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
993     if (flags & SHOW_COPYRIGHT)
994         av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
995                program_birth_year, this_year);
996     av_log(NULL, level, "\n");
997     av_log(NULL, level, "%sbuilt on %s %s with %s\n",
998            indent, __DATE__, __TIME__, CC_IDENT);
999
1000     av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
1001 }
1002
1003 void show_banner(int argc, char **argv, const OptionDef *options)
1004 {
1005     int idx = locate_option(argc, argv, options, "version");
1006     if (idx)
1007         return;
1008
1009     print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
1010     print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_INFO);
1011     print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
1012 }
1013
1014 int show_version(void *optctx, const char *opt, const char *arg)
1015 {
1016     av_log_set_callback(log_callback_help);
1017     print_program_info (0           , AV_LOG_INFO);
1018     print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
1019
1020     return 0;
1021 }
1022
1023 int show_license(void *optctx, const char *opt, const char *arg)
1024 {
1025 #if CONFIG_NONFREE
1026     printf(
1027     "This version of %s has nonfree parts compiled in.\n"
1028     "Therefore it is not legally redistributable.\n",
1029     program_name );
1030 #elif CONFIG_GPLV3
1031     printf(
1032     "%s is free software; you can redistribute it and/or modify\n"
1033     "it under the terms of the GNU General Public License as published by\n"
1034     "the Free Software Foundation; either version 3 of the License, or\n"
1035     "(at your option) any later version.\n"
1036     "\n"
1037     "%s is distributed in the hope that it will be useful,\n"
1038     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1039     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1040     "GNU General Public License for more details.\n"
1041     "\n"
1042     "You should have received a copy of the GNU General Public License\n"
1043     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
1044     program_name, program_name, program_name );
1045 #elif CONFIG_GPL
1046     printf(
1047     "%s is free software; you can redistribute it and/or modify\n"
1048     "it under the terms of the GNU General Public License as published by\n"
1049     "the Free Software Foundation; either version 2 of the License, or\n"
1050     "(at your option) any later version.\n"
1051     "\n"
1052     "%s is distributed in the hope that it will be useful,\n"
1053     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1054     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1055     "GNU General Public License for more details.\n"
1056     "\n"
1057     "You should have received a copy of the GNU General Public License\n"
1058     "along with %s; if not, write to the Free Software\n"
1059     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1060     program_name, program_name, program_name );
1061 #elif CONFIG_LGPLV3
1062     printf(
1063     "%s is free software; you can redistribute it and/or modify\n"
1064     "it under the terms of the GNU Lesser General Public License as published by\n"
1065     "the Free Software Foundation; either version 3 of the License, or\n"
1066     "(at your option) any later version.\n"
1067     "\n"
1068     "%s is distributed in the hope that it will be useful,\n"
1069     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1070     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1071     "GNU Lesser General Public License for more details.\n"
1072     "\n"
1073     "You should have received a copy of the GNU Lesser General Public License\n"
1074     "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
1075     program_name, program_name, program_name );
1076 #else
1077     printf(
1078     "%s is free software; you can redistribute it and/or\n"
1079     "modify it under the terms of the GNU Lesser General Public\n"
1080     "License as published by the Free Software Foundation; either\n"
1081     "version 2.1 of the License, or (at your option) any later version.\n"
1082     "\n"
1083     "%s is distributed in the hope that it will be useful,\n"
1084     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1085     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
1086     "Lesser General Public License for more details.\n"
1087     "\n"
1088     "You should have received a copy of the GNU Lesser General Public\n"
1089     "License along with %s; if not, write to the Free Software\n"
1090     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
1091     program_name, program_name, program_name );
1092 #endif
1093
1094     return 0;
1095 }
1096
1097 int show_formats(void *optctx, const char *opt, const char *arg)
1098 {
1099     AVInputFormat *ifmt  = NULL;
1100     AVOutputFormat *ofmt = NULL;
1101     const char *last_name;
1102
1103     printf("File formats:\n"
1104            " D. = Demuxing supported\n"
1105            " .E = Muxing supported\n"
1106            " --\n");
1107     last_name = "000";
1108     for (;;) {
1109         int decode = 0;
1110         int encode = 0;
1111         const char *name      = NULL;
1112         const char *long_name = NULL;
1113
1114         while ((ofmt = av_oformat_next(ofmt))) {
1115             if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
1116                 strcmp(ofmt->name, last_name) > 0) {
1117                 name      = ofmt->name;
1118                 long_name = ofmt->long_name;
1119                 encode    = 1;
1120             }
1121         }
1122         while ((ifmt = av_iformat_next(ifmt))) {
1123             if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
1124                 strcmp(ifmt->name, last_name) > 0) {
1125                 name      = ifmt->name;
1126                 long_name = ifmt->long_name;
1127                 encode    = 0;
1128             }
1129             if (name && strcmp(ifmt->name, name) == 0)
1130                 decode = 1;
1131         }
1132         if (name == NULL)
1133             break;
1134         last_name = name;
1135
1136         printf(" %s%s %-15s %s\n",
1137                decode ? "D" : " ",
1138                encode ? "E" : " ",
1139                name,
1140             long_name ? long_name:" ");
1141     }
1142     return 0;
1143 }
1144
1145 #define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
1146     if (codec->field) {                                                      \
1147         const type *p = codec->field;                                        \
1148                                                                              \
1149         printf("    Supported " list_name ":");                              \
1150         while (*p != term) {                                                 \
1151             get_name(*p);                                                    \
1152             printf(" %s", name);                                             \
1153             p++;                                                             \
1154         }                                                                    \
1155         printf("\n");                                                        \
1156     }                                                                        \
1157
1158 static void print_codec(const AVCodec *c)
1159 {
1160     int encoder = av_codec_is_encoder(c);
1161
1162     printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
1163            c->long_name ? c->long_name : "");
1164
1165     if (c->type == AVMEDIA_TYPE_VIDEO) {
1166         printf("    Threading capabilities: ");
1167         switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
1168                                    CODEC_CAP_SLICE_THREADS)) {
1169         case CODEC_CAP_FRAME_THREADS |
1170              CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
1171         case CODEC_CAP_FRAME_THREADS: printf("frame");           break;
1172         case CODEC_CAP_SLICE_THREADS: printf("slice");           break;
1173         default:                      printf("no");              break;
1174         }
1175         printf("\n");
1176     }
1177
1178     if (c->supported_framerates) {
1179         const AVRational *fps = c->supported_framerates;
1180
1181         printf("    Supported framerates:");
1182         while (fps->num) {
1183             printf(" %d/%d", fps->num, fps->den);
1184             fps++;
1185         }
1186         printf("\n");
1187     }
1188     PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
1189                           AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
1190     PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
1191                           GET_SAMPLE_RATE_NAME);
1192     PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
1193                           AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
1194     PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
1195                           0, GET_CH_LAYOUT_DESC);
1196
1197     if (c->priv_class) {
1198         show_help_children(c->priv_class,
1199                            AV_OPT_FLAG_ENCODING_PARAM |
1200                            AV_OPT_FLAG_DECODING_PARAM);
1201     }
1202 }
1203
1204 static char get_media_type_char(enum AVMediaType type)
1205 {
1206     switch (type) {
1207         case AVMEDIA_TYPE_VIDEO:    return 'V';
1208         case AVMEDIA_TYPE_AUDIO:    return 'A';
1209         case AVMEDIA_TYPE_DATA:     return 'D';
1210         case AVMEDIA_TYPE_SUBTITLE: return 'S';
1211         case AVMEDIA_TYPE_ATTACHMENT:return 'T';
1212         default:                    return '?';
1213     }
1214 }
1215
1216 static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
1217                                         int encoder)
1218 {
1219     while ((prev = av_codec_next(prev))) {
1220         if (prev->id == id &&
1221             (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
1222             return prev;
1223     }
1224     return NULL;
1225 }
1226
1227 static int compare_codec_desc(const void *a, const void *b)
1228 {
1229     const AVCodecDescriptor * const *da = a;
1230     const AVCodecDescriptor * const *db = b;
1231
1232     return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
1233            strcmp((*da)->name, (*db)->name);
1234 }
1235
1236 static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
1237 {
1238     const AVCodecDescriptor *desc = NULL;
1239     const AVCodecDescriptor **codecs;
1240     unsigned nb_codecs = 0, i = 0;
1241
1242     while ((desc = avcodec_descriptor_next(desc)))
1243         nb_codecs++;
1244     if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
1245         av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
1246         exit(1);
1247     }
1248     desc = NULL;
1249     while ((desc = avcodec_descriptor_next(desc)))
1250         codecs[i++] = desc;
1251     av_assert0(i == nb_codecs);
1252     qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
1253     *rcodecs = codecs;
1254     return nb_codecs;
1255 }
1256
1257 static void print_codecs_for_id(enum AVCodecID id, int encoder)
1258 {
1259     const AVCodec *codec = NULL;
1260
1261     printf(" (%s: ", encoder ? "encoders" : "decoders");
1262
1263     while ((codec = next_codec_for_id(id, codec, encoder)))
1264         printf("%s ", codec->name);
1265
1266     printf(")");
1267 }
1268
1269 int show_codecs(void *optctx, const char *opt, const char *arg)
1270 {
1271     const AVCodecDescriptor **codecs;
1272     unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1273
1274     printf("Codecs:\n"
1275            " D..... = Decoding supported\n"
1276            " .E.... = Encoding supported\n"
1277            " ..V... = Video codec\n"
1278            " ..A... = Audio codec\n"
1279            " ..S... = Subtitle codec\n"
1280            " ...I.. = Intra frame-only codec\n"
1281            " ....L. = Lossy compression\n"
1282            " .....S = Lossless compression\n"
1283            " -------\n");
1284     for (i = 0; i < nb_codecs; i++) {
1285         const AVCodecDescriptor *desc = codecs[i];
1286         const AVCodec *codec = NULL;
1287
1288         printf(" ");
1289         printf(avcodec_find_decoder(desc->id) ? "D" : ".");
1290         printf(avcodec_find_encoder(desc->id) ? "E" : ".");
1291
1292         printf("%c", get_media_type_char(desc->type));
1293         printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1294         printf((desc->props & AV_CODEC_PROP_LOSSY)      ? "L" : ".");
1295         printf((desc->props & AV_CODEC_PROP_LOSSLESS)   ? "S" : ".");
1296
1297         printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");
1298
1299         /* print decoders/encoders when there's more than one or their
1300          * names are different from codec name */
1301         while ((codec = next_codec_for_id(desc->id, codec, 0))) {
1302             if (strcmp(codec->name, desc->name)) {
1303                 print_codecs_for_id(desc->id, 0);
1304                 break;
1305             }
1306         }
1307         codec = NULL;
1308         while ((codec = next_codec_for_id(desc->id, codec, 1))) {
1309             if (strcmp(codec->name, desc->name)) {
1310                 print_codecs_for_id(desc->id, 1);
1311                 break;
1312             }
1313         }
1314
1315         printf("\n");
1316     }
1317     av_free(codecs);
1318     return 0;
1319 }
1320
1321 static void print_codecs(int encoder)
1322 {
1323     const AVCodecDescriptor **codecs;
1324     unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1325
1326     printf("%s:\n"
1327            " V..... = Video\n"
1328            " A..... = Audio\n"
1329            " S..... = Subtitle\n"
1330            " .F.... = Frame-level multithreading\n"
1331            " ..S... = Slice-level multithreading\n"
1332            " ...X.. = Codec is experimental\n"
1333            " ....B. = Supports draw_horiz_band\n"
1334            " .....D = Supports direct rendering method 1\n"
1335            " ------\n",
1336            encoder ? "Encoders" : "Decoders");
1337     for (i = 0; i < nb_codecs; i++) {
1338         const AVCodecDescriptor *desc = codecs[i];
1339         const AVCodec *codec = NULL;
1340
1341         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1342             printf(" %c", get_media_type_char(desc->type));
1343             printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
1344             printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
1345             printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL)  ? "X" : ".");
1346             printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
1347             printf((codec->capabilities & CODEC_CAP_DR1)           ? "D" : ".");
1348
1349             printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
1350             if (strcmp(codec->name, desc->name))
1351                 printf(" (codec %s)", desc->name);
1352
1353             printf("\n");
1354         }
1355     }
1356     av_free(codecs);
1357 }
1358
1359 int show_decoders(void *optctx, const char *opt, const char *arg)
1360 {
1361     print_codecs(0);
1362     return 0;
1363 }
1364
1365 int show_encoders(void *optctx, const char *opt, const char *arg)
1366 {
1367     print_codecs(1);
1368     return 0;
1369 }
1370
1371 int show_bsfs(void *optctx, const char *opt, const char *arg)
1372 {
1373     AVBitStreamFilter *bsf = NULL;
1374
1375     printf("Bitstream filters:\n");
1376     while ((bsf = av_bitstream_filter_next(bsf)))
1377         printf("%s\n", bsf->name);
1378     printf("\n");
1379     return 0;
1380 }
1381
1382 int show_protocols(void *optctx, const char *opt, const char *arg)
1383 {
1384     void *opaque = NULL;
1385     const char *name;
1386
1387     printf("Supported file protocols:\n"
1388            "Input:\n");
1389     while ((name = avio_enum_protocols(&opaque, 0)))
1390         printf("%s\n", name);
1391     printf("Output:\n");
1392     while ((name = avio_enum_protocols(&opaque, 1)))
1393         printf("%s\n", name);
1394     return 0;
1395 }
1396
1397 int show_filters(void *optctx, const char *opt, const char *arg)
1398 {
1399     AVFilter av_unused(**filter) = NULL;
1400     char descr[64], *descr_cur;
1401     int i, j;
1402     const AVFilterPad *pad;
1403
1404     printf("Filters:\n");
1405 #if CONFIG_AVFILTER
1406     while ((filter = av_filter_next(filter)) && *filter) {
1407         descr_cur = descr;
1408         for (i = 0; i < 2; i++) {
1409             if (i) {
1410                 *(descr_cur++) = '-';
1411                 *(descr_cur++) = '>';
1412             }
1413             pad = i ? (*filter)->outputs : (*filter)->inputs;
1414             for (j = 0; pad && pad[j].name; j++) {
1415                 if (descr_cur >= descr + sizeof(descr) - 4)
1416                     break;
1417                 *(descr_cur++) = get_media_type_char(pad[j].type);
1418             }
1419             if (!j)
1420                 *(descr_cur++) = '|';
1421         }
1422         *descr_cur = 0;
1423         printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
1424     }
1425 #endif
1426     return 0;
1427 }
1428
1429 int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1430 {
1431     const AVPixFmtDescriptor *pix_desc = NULL;
1432
1433     printf("Pixel formats:\n"
1434            "I.... = Supported Input  format for conversion\n"
1435            ".O... = Supported Output format for conversion\n"
1436            "..H.. = Hardware accelerated format\n"
1437            "...P. = Paletted format\n"
1438            "....B = Bitstream format\n"
1439            "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
1440            "-----\n");
1441
1442 #if !CONFIG_SWSCALE
1443 #   define sws_isSupportedInput(x)  0
1444 #   define sws_isSupportedOutput(x) 0
1445 #endif
1446
1447     while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
1448         enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1449         printf("%c%c%c%c%c %-16s       %d            %2d\n",
1450                sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
1451                sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
1452                pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
1453                pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
1454                pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
1455                pix_desc->name,
1456                pix_desc->nb_components,
1457                av_get_bits_per_pixel(pix_desc));
1458     }
1459     return 0;
1460 }
1461
1462 int show_layouts(void *optctx, const char *opt, const char *arg)
1463 {
1464     int i = 0;
1465     uint64_t layout, j;
1466     const char *name, *descr;
1467
1468     printf("Individual channels:\n"
1469            "NAME        DESCRIPTION\n");
1470     for (i = 0; i < 63; i++) {
1471         name = av_get_channel_name((uint64_t)1 << i);
1472         if (!name)
1473             continue;
1474         descr = av_get_channel_description((uint64_t)1 << i);
1475         printf("%-12s%s\n", name, descr);
1476     }
1477     printf("\nStandard channel layouts:\n"
1478            "NAME        DECOMPOSITION\n");
1479     for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
1480         if (name) {
1481             printf("%-12s", name);
1482             for (j = 1; j; j <<= 1)
1483                 if ((layout & j))
1484                     printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
1485             printf("\n");
1486         }
1487     }
1488     return 0;
1489 }
1490
1491 int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1492 {
1493     int i;
1494     char fmt_str[128];
1495     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
1496         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
1497     return 0;
1498 }
1499
1500 static void show_help_codec(const char *name, int encoder)
1501 {
1502     const AVCodecDescriptor *desc;
1503     const AVCodec *codec;
1504
1505     if (!name) {
1506         av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
1507         return;
1508     }
1509
1510     codec = encoder ? avcodec_find_encoder_by_name(name) :
1511                       avcodec_find_decoder_by_name(name);
1512
1513     if (codec)
1514         print_codec(codec);
1515     else if ((desc = avcodec_descriptor_get_by_name(name))) {
1516         int printed = 0;
1517
1518         while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1519             printed = 1;
1520             print_codec(codec);
1521         }
1522
1523         if (!printed) {
1524             av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
1525                    "but no %s for it are available. FFmpeg might need to be "
1526                    "recompiled with additional external libraries.\n",
1527                    name, encoder ? "encoders" : "decoders");
1528         }
1529     } else {
1530         av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
1531                name);
1532     }
1533 }
1534
1535 static void show_help_demuxer(const char *name)
1536 {
1537     const AVInputFormat *fmt = av_find_input_format(name);
1538
1539     if (!fmt) {
1540         av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1541         return;
1542     }
1543
1544     printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);
1545
1546     if (fmt->extensions)
1547         printf("    Common extensions: %s.\n", fmt->extensions);
1548
1549     if (fmt->priv_class)
1550         show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
1551 }
1552
1553 static void show_help_muxer(const char *name)
1554 {
1555     const AVCodecDescriptor *desc;
1556     const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);
1557
1558     if (!fmt) {
1559         av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
1560         return;
1561     }
1562
1563     printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);
1564
1565     if (fmt->extensions)
1566         printf("    Common extensions: %s.\n", fmt->extensions);
1567     if (fmt->mime_type)
1568         printf("    Mime type: %s.\n", fmt->mime_type);
1569     if (fmt->video_codec != AV_CODEC_ID_NONE &&
1570         (desc = avcodec_descriptor_get(fmt->video_codec))) {
1571         printf("    Default video codec: %s.\n", desc->name);
1572     }
1573     if (fmt->audio_codec != AV_CODEC_ID_NONE &&
1574         (desc = avcodec_descriptor_get(fmt->audio_codec))) {
1575         printf("    Default audio codec: %s.\n", desc->name);
1576     }
1577     if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
1578         (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
1579         printf("    Default subtitle codec: %s.\n", desc->name);
1580     }
1581
1582     if (fmt->priv_class)
1583         show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
1584 }
1585
1586 int show_help(void *optctx, const char *opt, const char *arg)
1587 {
1588     char *topic, *par;
1589     av_log_set_callback(log_callback_help);
1590
1591     topic = av_strdup(arg ? arg : "");
1592     par = strchr(topic, '=');
1593     if (par)
1594         *par++ = 0;
1595
1596     if (!*topic) {
1597         show_help_default(topic, par);
1598     } else if (!strcmp(topic, "decoder")) {
1599         show_help_codec(par, 0);
1600     } else if (!strcmp(topic, "encoder")) {
1601         show_help_codec(par, 1);
1602     } else if (!strcmp(topic, "demuxer")) {
1603         show_help_demuxer(par);
1604     } else if (!strcmp(topic, "muxer")) {
1605         show_help_muxer(par);
1606     } else {
1607         show_help_default(topic, par);
1608     }
1609
1610     av_freep(&topic);
1611     return 0;
1612 }
1613
1614 int read_yesno(void)
1615 {
1616     int c = getchar();
1617     int yesno = (toupper(c) == 'Y');
1618
1619     while (c != '\n' && c != EOF)
1620         c = getchar();
1621
1622     return yesno;
1623 }
1624
1625 int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1626 {
1627     int ret;
1628     FILE *f = fopen(filename, "rb");
1629
1630     if (!f) {
1631         av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
1632                strerror(errno));
1633         return AVERROR(errno);
1634     }
1635     fseek(f, 0, SEEK_END);
1636     *size = ftell(f);
1637     fseek(f, 0, SEEK_SET);
1638     if (*size == (size_t)-1) {
1639         av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
1640         fclose(f);
1641         return AVERROR(errno);
1642     }
1643     *bufptr = av_malloc(*size + 1);
1644     if (!*bufptr) {
1645         av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1646         fclose(f);
1647         return AVERROR(ENOMEM);
1648     }
1649     ret = fread(*bufptr, 1, *size, f);
1650     if (ret < *size) {
1651         av_free(*bufptr);
1652         if (ferror(f)) {
1653             av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
1654                    filename, strerror(errno));
1655             ret = AVERROR(errno);
1656         } else
1657             ret = AVERROR_EOF;
1658     } else {
1659         ret = 0;
1660         (*bufptr)[(*size)++] = '\0';
1661     }
1662
1663     fclose(f);
1664     return ret;
1665 }
1666
1667 FILE *get_preset_file(char *filename, size_t filename_size,
1668                       const char *preset_name, int is_path,
1669                       const char *codec_name)
1670 {
1671     FILE *f = NULL;
1672     int i;
1673     const char *base[3] = { getenv("FFMPEG_DATADIR"),
1674                             getenv("HOME"),
1675                             FFMPEG_DATADIR, };
1676
1677     if (is_path) {
1678         av_strlcpy(filename, preset_name, filename_size);
1679         f = fopen(filename, "r");
1680     } else {
1681 #ifdef _WIN32
1682         char datadir[MAX_PATH], *ls;
1683         base[2] = NULL;
1684
1685         if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
1686         {
1687             for (ls = datadir; ls < datadir + strlen(datadir); ls++)
1688                 if (*ls == '\\') *ls = '/';
1689
1690             if (ls = strrchr(datadir, '/'))
1691             {
1692                 *ls = 0;
1693                 strncat(datadir, "/ffpresets",  sizeof(datadir) - 1 - strlen(datadir));
1694                 base[2] = datadir;
1695             }
1696         }
1697 #endif
1698         for (i = 0; i < 3 && !f; i++) {
1699             if (!base[i])
1700                 continue;
1701             snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1702                      i != 1 ? "" : "/.ffmpeg", preset_name);
1703             f = fopen(filename, "r");
1704             if (!f && codec_name) {
1705                 snprintf(filename, filename_size,
1706                          "%s%s/%s-%s.ffpreset",
1707                          base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1708                          preset_name);
1709                 f = fopen(filename, "r");
1710             }
1711         }
1712     }
1713
1714     return f;
1715 }
1716
1717 int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
1718 {
1719     int ret = avformat_match_stream_specifier(s, st, spec);
1720     if (ret < 0)
1721         av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
1722     return ret;
1723 }
1724
1725 AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1726                                 AVFormatContext *s, AVStream *st, AVCodec *codec)
1727 {
1728     AVDictionary    *ret = NULL;
1729     AVDictionaryEntry *t = NULL;
1730     int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
1731                                       : AV_OPT_FLAG_DECODING_PARAM;
1732     char          prefix = 0;
1733     const AVClass    *cc = avcodec_get_class();
1734
1735     if (!codec)
1736         codec            = s->oformat ? avcodec_find_encoder(codec_id)
1737                                       : avcodec_find_decoder(codec_id);
1738     if (!codec)
1739         return NULL;
1740
1741     switch (codec->type) {
1742     case AVMEDIA_TYPE_VIDEO:
1743         prefix  = 'v';
1744         flags  |= AV_OPT_FLAG_VIDEO_PARAM;
1745         break;
1746     case AVMEDIA_TYPE_AUDIO:
1747         prefix  = 'a';
1748         flags  |= AV_OPT_FLAG_AUDIO_PARAM;
1749         break;
1750     case AVMEDIA_TYPE_SUBTITLE:
1751         prefix  = 's';
1752         flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
1753         break;
1754     }
1755
1756     while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1757         char *p = strchr(t->key, ':');
1758
1759         /* check stream specification in opt name */
1760         if (p)
1761             switch (check_stream_specifier(s, st, p + 1)) {
1762             case  1: *p = 0; break;
1763             case  0:         continue;
1764             default:         return NULL;
1765             }
1766
1767         if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1768             (codec && codec->priv_class &&
1769              av_opt_find(&codec->priv_class, t->key, NULL, flags,
1770                          AV_OPT_SEARCH_FAKE_OBJ)))
1771             av_dict_set(&ret, t->key, t->value, 0);
1772         else if (t->key[0] == prefix &&
1773                  av_opt_find(&cc, t->key + 1, NULL, flags,
1774                              AV_OPT_SEARCH_FAKE_OBJ))
1775             av_dict_set(&ret, t->key + 1, t->value, 0);
1776
1777         if (p)
1778             *p = ':';
1779     }
1780     return ret;
1781 }
1782
1783 AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
1784                                            AVDictionary *codec_opts)
1785 {
1786     int i;
1787     AVDictionary **opts;
1788
1789     if (!s->nb_streams)
1790         return NULL;
1791     opts = av_mallocz(s->nb_streams * sizeof(*opts));
1792     if (!opts) {
1793         av_log(NULL, AV_LOG_ERROR,
1794                "Could not alloc memory for stream options.\n");
1795         return NULL;
1796     }
1797     for (i = 0; i < s->nb_streams; i++)
1798         opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1799                                     s, s->streams[i], NULL);
1800     return opts;
1801 }
1802
1803 void *grow_array(void *array, int elem_size, int *size, int new_size)
1804 {
1805     if (new_size >= INT_MAX / elem_size) {
1806         av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1807         exit(1);
1808     }
1809     if (*size < new_size) {
1810         uint8_t *tmp = av_realloc(array, new_size*elem_size);
1811         if (!tmp) {
1812             av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1813             exit(1);
1814         }
1815         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
1816         *size = new_size;
1817         return tmp;
1818     }
1819     return array;
1820 }
1821
1822 static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
1823 {
1824     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
1825     FrameBuffer *buf;
1826     int i, ret;
1827     int pixel_size;
1828     int h_chroma_shift, v_chroma_shift;
1829     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
1830     int w = s->width, h = s->height;
1831
1832     if (!desc)
1833         return AVERROR(EINVAL);
1834     pixel_size = desc->comp[0].step_minus1 + 1;
1835
1836     buf = av_mallocz(sizeof(*buf));
1837     if (!buf)
1838         return AVERROR(ENOMEM);
1839
1840     avcodec_align_dimensions(s, &w, &h);
1841
1842     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
1843         w += 2*edge;
1844         h += 2*edge;
1845     }
1846
1847     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
1848                               s->pix_fmt, 32)) < 0) {
1849         av_freep(&buf);
1850         av_log(s, AV_LOG_ERROR, "alloc_buffer: av_image_alloc() failed\n");
1851         return ret;
1852     }
1853     /* XXX this shouldn't be needed, but some tests break without this line
1854      * those decoders are buggy and need to be fixed.
1855      * the following tests fail:
1856      * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
1857      */
1858     memset(buf->base[0], 128, ret);
1859
1860     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
1861     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1862         const int h_shift = i==0 ? 0 : h_chroma_shift;
1863         const int v_shift = i==0 ? 0 : v_chroma_shift;
1864         if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[i] || !buf->base[i])
1865             buf->data[i] = buf->base[i];
1866         else
1867             buf->data[i] = buf->base[i] +
1868                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
1869                                    (pixel_size*edge >> h_shift), 32);
1870     }
1871     buf->w       = s->width;
1872     buf->h       = s->height;
1873     buf->pix_fmt = s->pix_fmt;
1874     buf->pool    = pool;
1875
1876     *pbuf = buf;
1877     return 0;
1878 }
1879
1880 int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
1881 {
1882     FrameBuffer **pool = s->opaque;
1883     FrameBuffer *buf;
1884     int ret, i;
1885
1886     if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0) {
1887         av_log(s, AV_LOG_ERROR, "codec_get_buffer: image parameters invalid\n");
1888         return -1;
1889     }
1890
1891     if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
1892         return ret;
1893
1894     buf              = *pool;
1895     *pool            = buf->next;
1896     buf->next        = NULL;
1897     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
1898         av_freep(&buf->base[0]);
1899         av_free(buf);
1900         if ((ret = alloc_buffer(pool, s, &buf)) < 0)
1901             return ret;
1902     }
1903     av_assert0(!buf->refcount);
1904     buf->refcount++;
1905
1906     frame->opaque        = buf;
1907     frame->type          = FF_BUFFER_TYPE_USER;
1908     frame->extended_data = frame->data;
1909
1910     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
1911         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
1912         frame->data[i]     = buf->data[i];
1913         frame->linesize[i] = buf->linesize[i];
1914     }
1915
1916     return 0;
1917 }
1918
1919 static void unref_buffer(FrameBuffer *buf)
1920 {
1921     FrameBuffer **pool = buf->pool;
1922
1923     av_assert0(buf->refcount > 0);
1924     buf->refcount--;
1925     if (!buf->refcount) {
1926         FrameBuffer *tmp;
1927         for(tmp= *pool; tmp; tmp= tmp->next)
1928             av_assert1(tmp != buf);
1929
1930         buf->next = *pool;
1931         *pool = buf;
1932     }
1933 }
1934
1935 void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
1936 {
1937     FrameBuffer *buf = frame->opaque;
1938     int i;
1939
1940     if(frame->type!=FF_BUFFER_TYPE_USER) {
1941         avcodec_default_release_buffer(s, frame);
1942         return;
1943     }
1944
1945     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
1946         frame->data[i] = NULL;
1947
1948     unref_buffer(buf);
1949 }
1950
1951 void filter_release_buffer(AVFilterBuffer *fb)
1952 {
1953     FrameBuffer *buf = fb->priv;
1954     av_free(fb);
1955     unref_buffer(buf);
1956 }
1957
1958 void free_buffer_pool(FrameBuffer **pool)
1959 {
1960     FrameBuffer *buf = *pool;
1961     while (buf) {
1962         *pool = buf->next;
1963         av_freep(&buf->base[0]);
1964         av_free(buf);
1965         buf = *pool;
1966     }
1967 }