cmdutils.c 36 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1 2 3 4
/*
 * Various utilities for command line tools
 * Copyright (c) 2000-2003 Fabrice Bellard
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * Libav is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
21

22 23 24
#include <string.h>
#include <stdlib.h>
#include <errno.h>
25
#include <math.h>
26

27 28 29 30
/* Include only the enabled headers since some compilers (namely, Sun
   Studio) will not omit unused inline functions and create undefined
   references to libraries that are not being built. */

31
#include "config.h"
32 33 34
#include "libavformat/avformat.h"
#include "libavfilter/avfilter.h"
#include "libavdevice/avdevice.h"
35
#include "libswscale/swscale.h"
36
#if CONFIG_POSTPROC
37
#include "libpostproc/postprocess.h"
38
#endif
39
#include "libavutil/avstring.h"
40
#include "libavutil/mathematics.h"
41
#include "libavutil/parseutils.h"
42
#include "libavutil/pixdesc.h"
43
#include "libavutil/eval.h"
Anton Khirnov's avatar
Anton Khirnov committed
44
#include "libavutil/dict.h"
45
#include "libavutil/opt.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
46
#include "cmdutils.h"
47
#include "version.h"
Ramiro Polla's avatar
Ramiro Polla committed
48
#if CONFIG_NETWORK
49
#include "libavformat/network.h"
Ramiro Polla's avatar
Ramiro Polla committed
50
#endif
Måns Rullgård's avatar
Måns Rullgård committed
51 52 53
#if HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
Fabrice Bellard's avatar
Fabrice Bellard committed
54

55
struct SwsContext *sws_opts;
56
AVDictionary *format_opts, *codec_opts;
Michael Niedermayer's avatar
Michael Niedermayer committed
57

58
static const int this_year = 2012;
59

60 61
void init_opts(void)
{
62
#if CONFIG_SWSCALE
63 64
    sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
                              NULL, NULL, NULL);
65
#endif
66 67 68 69
}

void uninit_opts(void)
{
70
#if CONFIG_SWSCALE
71 72
    sws_freeContext(sws_opts);
    sws_opts = NULL;
73
#endif
Anton Khirnov's avatar
Anton Khirnov committed
74
    av_dict_free(&format_opts);
75
    av_dict_free(&codec_opts);
76 77
}

78
void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
79 80 81 82
{
    vfprintf(stdout, fmt, vl);
}

83 84
double parse_number_or_die(const char *context, const char *numstr, int type,
                           double min, double max)
Michael Niedermayer's avatar
Michael Niedermayer committed
85 86 87
{
    char *tail;
    const char *error;
88
    double d = av_strtod(numstr, &tail);
Michael Niedermayer's avatar
Michael Niedermayer committed
89
    if (*tail)
90
        error = "Expected number for %s but found: %s\n";
Michael Niedermayer's avatar
Michael Niedermayer committed
91
    else if (d < min || d > max)
92 93 94
        error = "The value for %s was %s which is not within %f - %f\n";
    else if (type == OPT_INT64 && (int64_t)d != d)
        error = "Expected int64 for %s but found %s\n";
95
    else if (type == OPT_INT && (int)d != d)
96
        error = "Expected int for %s but found %s\n";
Michael Niedermayer's avatar
Michael Niedermayer committed
97 98
    else
        return d;
99
    av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
100 101
    exit_program(1);
    return 0;
Michael Niedermayer's avatar
Michael Niedermayer committed
102 103
}

104 105
int64_t parse_time_or_die(const char *context, const char *timestr,
                          int is_duration)
106
{
107 108
    int64_t us;
    if (av_parse_time(&us, timestr, is_duration) < 0) {
109 110
        av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
               is_duration ? "duration" : "date", context, timestr);
111
        exit_program(1);
112 113 114 115
    }
    return us;
}

116 117
void show_help_options(const OptionDef *options, const char *msg, int mask,
                       int value)
Fabrice Bellard's avatar
Fabrice Bellard committed
118 119
{
    const OptionDef *po;
120
    int first;
Fabrice Bellard's avatar
Fabrice Bellard committed
121

122
    first = 1;
123
    for (po = options; po->name != NULL; po++) {
124 125 126 127 128 129
        char buf[64];
        if ((po->flags & mask) == value) {
            if (first) {
                printf("%s", msg);
                first = 0;
            }
130
            av_strlcpy(buf, po->name, sizeof(buf));
131
            if (po->flags & HAS_ARG) {
132 133
                av_strlcat(buf, " ", sizeof(buf));
                av_strlcat(buf, po->argname, sizeof(buf));
Fabrice Bellard's avatar
Fabrice Bellard committed
134
            }
135
            printf("-%-17s  %s\n", buf, po->help);
Fabrice Bellard's avatar
Fabrice Bellard committed
136 137 138 139
        }
    }
}

140 141 142 143 144 145 146 147 148 149
void show_help_children(const AVClass *class, int flags)
{
    const AVClass *child = NULL;
    av_opt_show2(&class, NULL, flags, 0);
    printf("\n");

    while (child = av_opt_child_class_next(class, child))
        show_help_children(child, flags);
}

150 151
static const OptionDef *find_option(const OptionDef *po, const char *name)
{
152 153 154
    const char *p = strchr(name, ':');
    int len = p ? p - name : strlen(name);

Michael Niedermayer's avatar
Michael Niedermayer committed
155
    while (po->name != NULL) {
156
        if (!strncmp(name, po->name, len) && strlen(po->name) == len)
Michael Niedermayer's avatar
Michael Niedermayer committed
157 158 159 160 161 162
            break;
        po++;
    }
    return po;
}

163
#if defined(_WIN32) && !defined(__MINGW32CE__)
164
#include <windows.h>
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/* Will be leaked on exit */
static char** win32_argv_utf8 = NULL;
static int win32_argc = 0;

/**
 * Prepare command line arguments for executable.
 * For Windows - perform wide-char to UTF-8 conversion.
 * Input arguments should be main() function arguments.
 * @param argc_ptr Arguments number (including executable)
 * @param argv_ptr Arguments list.
 */
static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
{
    char *argstr_flat;
    wchar_t **argv_w;
    int i, buffsize = 0, offset = 0;

    if (win32_argv_utf8) {
        *argc_ptr = win32_argc;
        *argv_ptr = win32_argv_utf8;
        return;
    }

    win32_argc = 0;
    argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);
    if (win32_argc <= 0 || !argv_w)
        return;

    /* determine the UTF-8 buffer size (including NULL-termination symbols) */
    for (i = 0; i < win32_argc; i++)
        buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
                                        NULL, 0, NULL, NULL);

198 199
    win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
    argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    if (win32_argv_utf8 == NULL) {
        LocalFree(argv_w);
        return;
    }

    for (i = 0; i < win32_argc; i++) {
        win32_argv_utf8[i] = &argstr_flat[offset];
        offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,
                                      &argstr_flat[offset],
                                      buffsize - offset, NULL, NULL);
    }
    win32_argv_utf8[i] = NULL;
    LocalFree(argv_w);

    *argc_ptr = win32_argc;
    *argv_ptr = win32_argv_utf8;
}
#else
static inline void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)
{
    /* nothing to do */
}
#endif /* WIN32 && !__MINGW32CE__ */

224 225
int parse_option(void *optctx, const char *opt, const char *arg,
                 const OptionDef *options)
226 227 228
{
    const OptionDef *po;
    int bool_val = 1;
229
    int *dstcount;
230 231 232 233 234 235
    void *dst;

    po = find_option(options, opt);
    if (!po->name && opt[0] == 'n' && opt[1] == 'o') {
        /* handle 'no' bool option */
        po = find_option(options, opt + 2);
236 237
        if ((po->name && (po->flags & OPT_BOOL)))
            bool_val = 0;
238 239 240 241 242 243 244 245 246 247 248 249 250 251
    }
    if (!po->name)
        po = find_option(options, "default");
    if (!po->name) {
        av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
        return AVERROR(EINVAL);
    }
    if (po->flags & HAS_ARG && !arg) {
        av_log(NULL, AV_LOG_ERROR, "Missing argument for option '%s'\n", opt);
        return AVERROR(EINVAL);
    }

    /* new-style options contain an offset into optctx, old-style address of
     * a global var*/
252 253
    dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
                                              : po->u.dst_ptr;
254 255 256 257 258

    if (po->flags & OPT_SPEC) {
        SpecifierOpt **so = dst;
        char *p = strchr(opt, ':');

259
        dstcount = (int *)(so + 1);
260 261 262 263
        *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
        (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
        dst = &(*so)[*dstcount - 1].u;
    }
264 265 266 267

    if (po->flags & OPT_STRING) {
        char *str;
        str = av_strdup(arg);
268
        *(char **)dst = str;
269
    } else if (po->flags & OPT_BOOL) {
270
        *(int *)dst = bool_val;
271
    } else if (po->flags & OPT_INT) {
272
        *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
273
    } else if (po->flags & OPT_INT64) {
274
        *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
275
    } else if (po->flags & OPT_TIME) {
276
        *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
277
    } else if (po->flags & OPT_FLOAT) {
278
        *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
279
    } else if (po->flags & OPT_DOUBLE) {
280
        *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
281
    } else if (po->u.func_arg) {
282 283
        int ret = po->flags & OPT_FUNC2 ? po->u.func2_arg(optctx, opt, arg)
                                        : po->u.func_arg(opt, arg);
284
        if (ret < 0) {
285 286
            av_log(NULL, AV_LOG_ERROR,
                   "Failed to set value '%s' for option '%s'\n", arg, opt);
287 288 289 290 291 292 293 294
            return ret;
        }
    }
    if (po->flags & OPT_EXIT)
        exit_program(0);
    return !!(po->flags & HAS_ARG);
}

295
void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
296
                   void (*parse_arg_function)(void *, const char*))
Fabrice Bellard's avatar
Fabrice Bellard committed
297
{
298 299
    const char *opt;
    int optindex, handleoptions = 1, ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
300

301 302 303
    /* perform system-dependent conversions for arguments list */
    prepare_app_arguments(&argc, &argv);

Fabrice Bellard's avatar
Fabrice Bellard committed
304 305 306 307
    /* parse options */
    optindex = 1;
    while (optindex < argc) {
        opt = argv[optindex++];
308

309
        if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
Stefano Sabatini's avatar
Stefano Sabatini committed
310 311 312 313
            if (opt[1] == '-' && opt[2] == '\0') {
                handleoptions = 0;
                continue;
            }
314
            opt++;
315 316

            if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
317
                exit_program(1);
318
            optindex += ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
319
        } else {
320
            if (parse_arg_function)
321
                parse_arg_function(optctx, opt);
Fabrice Bellard's avatar
Fabrice Bellard committed
322 323 324 325
        }
    }
}

326 327 328
/*
 * Return index of option opt in argv or 0 if not found.
 */
329 330
static int locate_option(int argc, char **argv, const OptionDef *options,
                         const char *optname)
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
{
    const OptionDef *po;
    int i;

    for (i = 1; i < argc; i++) {
        const char *cur_opt = argv[i];

        if (*cur_opt++ != '-')
            continue;

        po = find_option(options, cur_opt);
        if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')
            po = find_option(options, cur_opt + 2);

        if ((!po->name && !strcmp(cur_opt, optname)) ||
             (po->name && !strcmp(optname, po->name)))
            return i;

        if (!po || po->flags & HAS_ARG)
            i++;
    }
    return 0;
}

void parse_loglevel(int argc, char **argv, const OptionDef *options)
{
    int idx = locate_option(argc, argv, options, "loglevel");
358 359
    if (!idx)
        idx = locate_option(argc, argv, options, "v");
360 361 362 363
    if (idx && argv[idx + 1])
        opt_loglevel("loglevel", argv[idx + 1]);
}

364
#define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
365
int opt_default(const char *opt, const char *arg)
Anton Khirnov's avatar
Anton Khirnov committed
366 367
{
    const AVOption *o;
368 369
    char opt_stripped[128];
    const char *p;
370
    const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc = sws_get_class();
371 372 373 374 375

    if (!(p = strchr(opt, ':')))
        p = opt + strlen(opt);
    av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));

376 377 378 379
    if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
        ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
         (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))
380
        av_dict_set(&codec_opts, opt, arg, FLAGS);
381 382
    else if ((o = av_opt_find(&fc, opt, NULL, 0,
                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))
Anton Khirnov's avatar
Anton Khirnov committed
383
        av_dict_set(&format_opts, opt, arg, FLAGS);
384 385
    else if ((o = av_opt_find(&sc, opt, NULL, 0,
                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
Anton Khirnov's avatar
Anton Khirnov committed
386
        // XXX we only support sws_flags, not arbitrary sws options
387
        int ret = av_opt_set(sws_opts, opt, arg, 0);
Anton Khirnov's avatar
Anton Khirnov committed
388 389 390 391 392 393 394 395
        if (ret < 0) {
            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
            return ret;
        }
    }

    if (o)
        return 0;
396
    av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
Anton Khirnov's avatar
Anton Khirnov committed
397 398 399
    return AVERROR_OPTION_NOT_FOUND;
}

400 401
int opt_loglevel(const char *opt, const char *arg)
{
Carl Eugen Hoyos's avatar
Carl Eugen Hoyos committed
402
    const struct { const char *name; int level; } log_levels[] = {
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
        { "quiet"  , AV_LOG_QUIET   },
        { "panic"  , AV_LOG_PANIC   },
        { "fatal"  , AV_LOG_FATAL   },
        { "error"  , AV_LOG_ERROR   },
        { "warning", AV_LOG_WARNING },
        { "info"   , AV_LOG_INFO    },
        { "verbose", AV_LOG_VERBOSE },
        { "debug"  , AV_LOG_DEBUG   },
    };
    char *tail;
    int level;
    int i;

    for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++) {
        if (!strcmp(log_levels[i].name, arg)) {
            av_log_set_level(log_levels[i].level);
            return 0;
        }
    }

    level = strtol(arg, &tail, 10);
    if (*tail) {
425 426
        av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
               "Possible levels are numbers or:\n", arg);
427
        for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
428
            av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
429
        exit_program(1);
430 431 432 433 434
    }
    av_log_set_level(level);
    return 0;
}

Måns Rullgård's avatar
Måns Rullgård committed
435 436
int opt_timelimit(const char *opt, const char *arg)
{
Måns Rullgård's avatar
Måns Rullgård committed
437
#if HAVE_SETRLIMIT
Måns Rullgård's avatar
Måns Rullgård committed
438 439 440 441 442
    int lim = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
    struct rlimit rl = { lim, lim + 1 };
    if (setrlimit(RLIMIT_CPU, &rl))
        perror("setrlimit");
#else
443
    av_log(NULL, AV_LOG_WARNING, "-%s not implemented on this OS\n", opt);
Måns Rullgård's avatar
Måns Rullgård committed
444 445 446 447
#endif
    return 0;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
448 449
void print_error(const char *filename, int err)
{
450
    char errbuf[128];
451
    const char *errbuf_ptr = errbuf;
452

453 454
    if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
        errbuf_ptr = strerror(AVUNERROR(err));
455
    av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
Fabrice Bellard's avatar
Fabrice Bellard committed
456
}
457

458 459
static int warned_cfg = 0;

460 461
#define INDENT        1
#define SHOW_VERSION  2
462
#define SHOW_CONFIG   4
463

464
#define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
465
    if (CONFIG_##LIBNAME) {                                             \
466
        const char *indent = flags & INDENT? "  " : "";                 \
467
        if (flags & SHOW_VERSION) {                                     \
Stefano Sabatini's avatar
Stefano Sabatini committed
468
            unsigned int version = libname##_version();                 \
469 470 471 472 473 474
            av_log(NULL, level, "%slib%-9s %2d.%3d.%2d / %2d.%3d.%2d\n",\
                   indent, #libname,                                    \
                   LIB##LIBNAME##_VERSION_MAJOR,                        \
                   LIB##LIBNAME##_VERSION_MINOR,                        \
                   LIB##LIBNAME##_VERSION_MICRO,                        \
                   version >> 16, version >> 8 & 0xff, version & 0xff); \
475
        }                                                               \
476 477
        if (flags & SHOW_CONFIG) {                                      \
            const char *cfg = libname##_configuration();                \
478
            if (strcmp(LIBAV_CONFIGURATION, cfg)) {                     \
479
                if (!warned_cfg) {                                      \
480
                    av_log(NULL, level,                                 \
481
                            "%sWARNING: library configuration mismatch\n", \
482
                            indent);                                    \
483 484
                    warned_cfg = 1;                                     \
                }                                                       \
485
                av_log(NULL, level, "%s%-11s configuration: %s\n",      \
486
                        indent, #libname, cfg);                         \
487 488
            }                                                           \
        }                                                               \
489
    }                                                                   \
490

491
static void print_all_libs_info(int flags, int level)
492
{
493 494 495 496 497 498
    PRINT_LIB_INFO(avutil,   AVUTIL,   flags, level);
    PRINT_LIB_INFO(avcodec,  AVCODEC,  flags, level);
    PRINT_LIB_INFO(avformat, AVFORMAT, flags, level);
    PRINT_LIB_INFO(avdevice, AVDEVICE, flags, level);
    PRINT_LIB_INFO(avfilter, AVFILTER, flags, level);
    PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
499
#if CONFIG_POSTPROC
500
    PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
501
#endif
502 503
}

504
void show_banner(void)
505
{
506 507
    av_log(NULL, AV_LOG_INFO,
           "%s version " LIBAV_VERSION ", Copyright (c) %d-%d the Libav developers\n",
508 509 510 511 512 513
           program_name, program_birth_year, this_year);
    av_log(NULL, AV_LOG_INFO, "  built on %s %s with %s %s\n",
           __DATE__, __TIME__, CC_TYPE, CC_VERSION);
    av_log(NULL, AV_LOG_VERBOSE, "  configuration: " LIBAV_CONFIGURATION "\n");
    print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_VERBOSE);
    print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_VERBOSE);
514 515
}

516
void show_version(void) {
517
    av_log_set_callback(log_callback_help);
518
    printf("%s " LIBAV_VERSION "\n", program_name);
519
    print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
520 521
}

522 523
void show_license(void)
{
524
    printf(
525
#if CONFIG_NONFREE
526 527 528
    "This version of %s has nonfree parts compiled in.\n"
    "Therefore it is not legally redistributable.\n",
    program_name
529 530 531 532 533 534 535 536 537 538 539 540 541 542
#elif CONFIG_GPLV3
    "%s is free software; you can redistribute it and/or modify\n"
    "it under the terms of the GNU General Public License as published by\n"
    "the Free Software Foundation; either version 3 of the License, or\n"
    "(at your option) any later version.\n"
    "\n"
    "%s is distributed in the hope that it will be useful,\n"
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
    "GNU General Public License for more details.\n"
    "\n"
    "You should have received a copy of the GNU General Public License\n"
    "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
    program_name, program_name, program_name
543
#elif CONFIG_GPL
544
    "%s is free software; you can redistribute it and/or modify\n"
545 546 547 548
    "it under the terms of the GNU General Public License as published by\n"
    "the Free Software Foundation; either version 2 of the License, or\n"
    "(at your option) any later version.\n"
    "\n"
549
    "%s is distributed in the hope that it will be useful,\n"
550 551 552 553 554
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
    "GNU General Public License for more details.\n"
    "\n"
    "You should have received a copy of the GNU General Public License\n"
555 556 557
    "along with %s; if not, write to the Free Software\n"
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
    program_name, program_name, program_name
558 559 560 561 562 563 564 565 566 567 568 569 570 571
#elif CONFIG_LGPLV3
    "%s is free software; you can redistribute it and/or modify\n"
    "it under the terms of the GNU Lesser General Public License as published by\n"
    "the Free Software Foundation; either version 3 of the License, or\n"
    "(at your option) any later version.\n"
    "\n"
    "%s is distributed in the hope that it will be useful,\n"
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
    "GNU Lesser General Public License for more details.\n"
    "\n"
    "You should have received a copy of the GNU Lesser General Public License\n"
    "along with %s.  If not, see <http://www.gnu.org/licenses/>.\n",
    program_name, program_name, program_name
572
#else
573
    "%s is free software; you can redistribute it and/or\n"
574 575 576 577
    "modify it under the terms of the GNU Lesser General Public\n"
    "License as published by the Free Software Foundation; either\n"
    "version 2.1 of the License, or (at your option) any later version.\n"
    "\n"
578
    "%s is distributed in the hope that it will be useful,\n"
579 580 581 582 583
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
    "Lesser General Public License for more details.\n"
    "\n"
    "You should have received a copy of the GNU Lesser General Public\n"
584 585 586
    "License along with %s; if not, write to the Free Software\n"
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
    program_name, program_name, program_name
587
#endif
588
    );
589
}
590 591 592

void show_formats(void)
{
593 594
    AVInputFormat *ifmt  = NULL;
    AVOutputFormat *ofmt = NULL;
595 596
    const char *last_name;

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    printf("File formats:\n"
           " D. = Demuxing supported\n"
           " .E = Muxing supported\n"
           " --\n");
    last_name = "000";
    for (;;) {
        int decode = 0;
        int encode = 0;
        const char *name      = NULL;
        const char *long_name = NULL;

        while ((ofmt = av_oformat_next(ofmt))) {
            if ((name == NULL || strcmp(ofmt->name, name) < 0) &&
                strcmp(ofmt->name, last_name) > 0) {
                name      = ofmt->name;
                long_name = ofmt->long_name;
                encode    = 1;
614 615
            }
        }
616 617 618 619 620 621
        while ((ifmt = av_iformat_next(ifmt))) {
            if ((name == NULL || strcmp(ifmt->name, name) < 0) &&
                strcmp(ifmt->name, last_name) > 0) {
                name      = ifmt->name;
                long_name = ifmt->long_name;
                encode    = 0;
622
            }
623 624
            if (name && strcmp(ifmt->name, name) == 0)
                decode = 1;
625
        }
626
        if (name == NULL)
627
            break;
628
        last_name = name;
629

630 631 632 633
        printf(" %s%s %-15s %s\n",
               decode ? "D" : " ",
               encode ? "E" : " ",
               name,
634 635
            long_name ? long_name:" ");
    }
Michael Niedermayer's avatar
Michael Niedermayer committed
636
}
637

Michael Niedermayer's avatar
Michael Niedermayer committed
638 639
void show_codecs(void)
{
640
    AVCodec *p = NULL, *p2;
Michael Niedermayer's avatar
Michael Niedermayer committed
641
    const char *last_name;
642 643 644 645 646 647 648 649 650 651
    printf("Codecs:\n"
           " D..... = Decoding supported\n"
           " .E.... = Encoding supported\n"
           " ..V... = Video codec\n"
           " ..A... = Audio codec\n"
           " ..S... = Subtitle codec\n"
           " ...S.. = Supports draw_horiz_band\n"
           " ....D. = Supports direct rendering method 1\n"
           " .....T = Supports weird frame truncation\n"
           " ------\n");
652
    last_name= "000";
653 654 655 656
    for (;;) {
        int decode = 0;
        int encode = 0;
        int cap    = 0;
657 658
        const char *type_str;

659 660 661 662 663 664
        p2 = NULL;
        while ((p = av_codec_next(p))) {
            if ((p2 == NULL || strcmp(p->name, p2->name) < 0) &&
                strcmp(p->name, last_name) > 0) {
                p2 = p;
                decode = encode = cap = 0;
665
            }
666 667 668 669 670
            if (p2 && strcmp(p->name, p2->name) == 0) {
                if (p->decode)
                    decode = 1;
                if (p->encode)
                    encode = 1;
671 672 673
                cap |= p->capabilities;
            }
        }
674
        if (p2 == NULL)
675
            break;
676
        last_name = p2->name;
677

678
        switch (p2->type) {
679
        case AVMEDIA_TYPE_VIDEO:
680 681
            type_str = "V";
            break;
682
        case AVMEDIA_TYPE_AUDIO:
683 684
            type_str = "A";
            break;
685
        case AVMEDIA_TYPE_SUBTITLE:
686 687 688 689 690 691
            type_str = "S";
            break;
        default:
            type_str = "?";
            break;
        }
692 693 694 695 696 697 698 699 700 701 702 703 704
        printf(" %s%s%s%s%s%s %-15s %s",
               decode ? "D" : (/* p2->decoder ? "d" : */ " "),
               encode ? "E" : " ",
               type_str,
               cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S" : " ",
               cap & CODEC_CAP_DR1 ? "D" : " ",
               cap & CODEC_CAP_TRUNCATED ? "T" : " ",
               p2->name,
               p2->long_name ? p2->long_name : "");
#if 0
            if (p2->decoder && decode == 0)
                printf(" use %s for decoding", p2->decoder->name);
#endif
705 706 707
        printf("\n");
    }
    printf("\n");
708 709 710 711 712
    printf("Note, the names of encoders and decoders do not always match, so there are\n"
           "several cases where the above table shows encoder only or decoder only entries\n"
           "even though both encoding and decoding are supported. For example, the h263\n"
           "decoder corresponds to the h263 and h263p encoders, for file formats it is even\n"
           "worse.\n");
Michael Niedermayer's avatar
Michael Niedermayer committed
713 714 715 716
}

void show_bsfs(void)
{
717
    AVBitStreamFilter *bsf = NULL;
718 719

    printf("Bitstream filters:\n");
720
    while ((bsf = av_bitstream_filter_next(bsf)))
721
        printf("%s\n", bsf->name);
722
    printf("\n");
Michael Niedermayer's avatar
Michael Niedermayer committed
723 724 725 726
}

void show_protocols(void)
{
727 728
    void *opaque = NULL;
    const char *name;
729

730
    printf("Supported file protocols:\n"
731 732 733 734 735 736
           "Input:\n");
    while ((name = avio_enum_protocols(&opaque, 0)))
        printf("%s\n", name);
    printf("Output:\n");
    while ((name = avio_enum_protocols(&opaque, 1)))
        printf("%s\n", name);
737
}
Stefano Sabatini's avatar
Stefano Sabatini committed
738

739 740
void show_filters(void)
{
741
    AVFilter av_unused(**filter) = NULL;
742 743

    printf("Filters:\n");
744
#if CONFIG_AVFILTER
745 746
    while ((filter = av_filter_next(filter)) && *filter)
        printf("%-16s %s\n", (*filter)->name, (*filter)->description);
747
#endif
748 749
}

750 751
void show_pix_fmts(void)
{
752 753
    enum PixelFormat pix_fmt;

754 755 756 757 758 759 760 761
    printf("Pixel formats:\n"
           "I.... = Supported Input  format for conversion\n"
           ".O... = Supported Output format for conversion\n"
           "..H.. = Hardware accelerated format\n"
           "...P. = Paletted format\n"
           "....B = Bitstream format\n"
           "FLAGS NAME            NB_COMPONENTS BITS_PER_PIXEL\n"
           "-----\n");
762

763 764 765 766 767
#if !CONFIG_SWSCALE
#   define sws_isSupportedInput(x)  0
#   define sws_isSupportedOutput(x) 0
#endif

768 769 770 771 772 773 774 775 776 777 778 779
    for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++) {
        const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[pix_fmt];
        printf("%c%c%c%c%c %-16s       %d            %2d\n",
               sws_isSupportedInput (pix_fmt)      ? 'I' : '.',
               sws_isSupportedOutput(pix_fmt)      ? 'O' : '.',
               pix_desc->flags & PIX_FMT_HWACCEL   ? 'H' : '.',
               pix_desc->flags & PIX_FMT_PAL       ? 'P' : '.',
               pix_desc->flags & PIX_FMT_BITSTREAM ? 'B' : '.',
               pix_desc->name,
               pix_desc->nb_components,
               av_get_bits_per_pixel(pix_desc));
    }
780 781
}

782 783 784 785 786 787 788 789 790
int show_sample_fmts(const char *opt, const char *arg)
{
    int i;
    char fmt_str[128];
    for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
        printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
    return 0;
}

Stefano Sabatini's avatar
Stefano Sabatini committed
791 792 793 794 795 796 797 798 799 800
int read_yesno(void)
{
    int c = getchar();
    int yesno = (toupper(c) == 'Y');

    while (c != '\n' && c != EOF)
        c = getchar();

    return yesno;
}
801

802
int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
803
{
804
    int ret;
805
    FILE *f = fopen(filename, "rb");
806 807

    if (!f) {
808 809
        av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
               strerror(errno));
810 811 812 813 814 815 816
        return AVERROR(errno);
    }
    fseek(f, 0, SEEK_END);
    *size = ftell(f);
    fseek(f, 0, SEEK_SET);
    *bufptr = av_malloc(*size + 1);
    if (!*bufptr) {
817
        av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
818 819 820
        fclose(f);
        return AVERROR(ENOMEM);
    }
821 822 823 824 825 826 827 828 829 830 831 832 833
    ret = fread(*bufptr, 1, *size, f);
    if (ret < *size) {
        av_free(*bufptr);
        if (ferror(f)) {
            av_log(NULL, AV_LOG_ERROR, "Error while reading file '%s': %s\n",
                   filename, strerror(errno));
            ret = AVERROR(errno);
        } else
            ret = AVERROR_EOF;
    } else {
        ret = 0;
        (*bufptr)[*size++] = '\0';
    }
834 835

    fclose(f);
836
    return ret;
837
}
838 839 840 841 842 843 844

void init_pts_correction(PtsCorrectionContext *ctx)
{
    ctx->num_faulty_pts = ctx->num_faulty_dts = 0;
    ctx->last_pts = ctx->last_dts = INT64_MIN;
}

845 846
int64_t guess_correct_pts(PtsCorrectionContext *ctx, int64_t reordered_pts,
                          int64_t dts)
847 848 849 850 851 852 853 854 855 856 857
{
    int64_t pts = AV_NOPTS_VALUE;

    if (dts != AV_NOPTS_VALUE) {
        ctx->num_faulty_dts += dts <= ctx->last_dts;
        ctx->last_dts = dts;
    }
    if (reordered_pts != AV_NOPTS_VALUE) {
        ctx->num_faulty_pts += reordered_pts <= ctx->last_pts;
        ctx->last_pts = reordered_pts;
    }
858
    if ((ctx->num_faulty_pts<=ctx->num_faulty_dts || dts == AV_NOPTS_VALUE)
859
        && reordered_pts != AV_NOPTS_VALUE)
860 861 862 863 864 865
        pts = reordered_pts;
    else
        pts = dts;

    return pts;
}
866

867
FILE *get_preset_file(char *filename, size_t filename_size,
868 869
                      const char *preset_name, int is_path,
                      const char *codec_name)
870 871 872
{
    FILE *f = NULL;
    int i;
873 874 875
    const char *base[3] = { getenv("AVCONV_DATADIR"),
                            getenv("HOME"),
                            AVCONV_DATADIR, };
876 877 878 879 880 881 882 883

    if (is_path) {
        av_strlcpy(filename, preset_name, filename_size);
        f = fopen(filename, "r");
    } else {
        for (i = 0; i < 3 && !f; i++) {
            if (!base[i])
                continue;
884 885
            snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
                     i != 1 ? "" : "/.avconv", preset_name);
886 887 888
            f = fopen(filename, "r");
            if (!f && codec_name) {
                snprintf(filename, filename_size,
889 890 891
                         "%s%s/%s-%s.ffpreset",
                         base[i], i != 1 ? "" : "/.avconv", codec_name,
                         preset_name);
892 893 894 895 896 897 898 899
                f = fopen(filename, "r");
            }
        }
    }

    return f;
}

900 901
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
{
902
    if (*spec <= '9' && *spec >= '0') /* opt:index */
903
        return strtol(spec, NULL, 0) == st->index;
904 905
    else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
             *spec == 't') { /* opt:[vasdt] */
906 907 908
        enum AVMediaType type;

        switch (*spec++) {
909 910 911 912
        case 'v': type = AVMEDIA_TYPE_VIDEO;      break;
        case 'a': type = AVMEDIA_TYPE_AUDIO;      break;
        case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;
        case 'd': type = AVMEDIA_TYPE_DATA;       break;
913
        case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
914 915 916
        }
        if (type != st->codec->codec_type)
            return 0;
917
        if (*spec++ == ':') { /* possibly followed by :index */
918 919 920 921 922 923 924
            int i, index = strtol(spec, NULL, 0);
            for (i = 0; i < s->nb_streams; i++)
                if (s->streams[i]->codec->codec_type == type && index-- == 0)
                   return i == st->index;
            return 0;
        }
        return 1;
925 926 927 928 929 930 931 932 933 934 935
    } else if (*spec == 'p' && *(spec + 1) == ':') {
        int prog_id, i, j;
        char *endptr;
        spec += 2;
        prog_id = strtol(spec, &endptr, 0);
        for (i = 0; i < s->nb_programs; i++) {
            if (s->programs[i]->id != prog_id)
                continue;

            if (*endptr++ == ':') {
                int stream_idx = strtol(endptr, NULL, 0);
936 937 938
                return stream_idx >= 0 &&
                    stream_idx < s->programs[i]->nb_stream_indexes &&
                    st->index == s->programs[i]->stream_index[stream_idx];
939 940 941 942 943 944 945
            }

            for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)
                if (st->index == s->programs[i]->stream_index[j])
                    return 1;
        }
        return 0;
946 947 948 949 950 951 952
    } else if (!*spec) /* empty specifier, matches everything */
        return 1;

    av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
    return AVERROR(EINVAL);
}

953 954
AVDictionary *filter_codec_opts(AVDictionary *opts, enum CodecID codec_id,
                                AVFormatContext *s, AVStream *st)
955 956 957
{
    AVDictionary    *ret = NULL;
    AVDictionaryEntry *t = NULL;