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