OSDN Git Service

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