cmdutils.c 53.5 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 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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
#include "compat/va_copy.h"
33 34 35
#include "libavformat/avformat.h"
#include "libavfilter/avfilter.h"
#include "libavdevice/avdevice.h"
36
#include "libavresample/avresample.h"
37
#include "libswscale/swscale.h"
38
#include "libswresample/swresample.h"
39
#if CONFIG_POSTPROC
40
#include "libpostproc/postprocess.h"
41
#endif
42
#include "libavutil/avassert.h"
43
#include "libavutil/avstring.h"
44
#include "libavutil/bprint.h"
45
#include "libavutil/mathematics.h"
46
#include "libavutil/imgutils.h"
47
#include "libavutil/parseutils.h"
48
#include "libavutil/pixdesc.h"
49
#include "libavutil/eval.h"
50
#include "libavutil/dict.h"
51
#include "libavutil/opt.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
52
#include "cmdutils.h"
53
#include "version.h"
Ramiro Polla's avatar
Ramiro Polla committed
54
#if CONFIG_NETWORK
55
#include "libavformat/network.h"
Ramiro Polla's avatar
Ramiro Polla committed
56
#endif
Måns Rullgård's avatar
Måns Rullgård committed
57
#if HAVE_SYS_RESOURCE_H
58
#include <sys/time.h>
Måns Rullgård's avatar
Måns Rullgård committed
59 60
#include <sys/resource.h>
#endif
Fabrice Bellard's avatar
Fabrice Bellard committed
61

62 63
static int init_report(const char *env);

64
struct SwsContext *sws_opts;
65
SwrContext *swr_opts;
66
AVDictionary *format_opts, *codec_opts;
67

68
const int this_year = 2012;
69

70 71
static FILE *report_file;

72 73
void init_opts(void)
{
74 75 76

    if(CONFIG_SWSCALE)
        sws_opts = sws_getContext(16, 16, 0, 16, 16, 0, SWS_BICUBIC,
77
                              NULL, NULL, NULL);
78 79 80

    if(CONFIG_SWRESAMPLE)
        swr_opts = swr_alloc();
81 82 83 84
}

void uninit_opts(void)
{
85
#if CONFIG_SWSCALE
86 87
    sws_freeContext(sws_opts);
    sws_opts = NULL;
88
#endif
89 90 91 92

    if(CONFIG_SWRESAMPLE)
        swr_free(&swr_opts);

93
    av_dict_free(&format_opts);
94
    av_dict_free(&codec_opts);
95 96
}

97
void log_callback_help(void *ptr, int level, const char *fmt, va_list vl)
98 99 100 101
{
    vfprintf(stdout, fmt, vl);
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115
static void log_callback_report(void *ptr, int level, const char *fmt, va_list vl)
{
    va_list vl2;
    char line[1024];
    static int print_prefix = 1;

    va_copy(vl2, vl);
    av_log_default_callback(ptr, level, fmt, vl);
    av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
    va_end(vl2);
    fputs(line, report_file);
    fflush(report_file);
}

116 117
double parse_number_or_die(const char *context, const char *numstr, int type,
                           double min, double max)
118 119 120
{
    char *tail;
    const char *error;
121
    double d = av_strtod(numstr, &tail);
122
    if (*tail)
123
        error = "Expected number for %s but found: %s\n";
124
    else if (d < min || d > max)
125 126 127
        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";
128
    else if (type == OPT_INT && (int)d != d)
129
        error = "Expected int for %s but found %s\n";
130 131
    else
        return d;
132
    av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);
133
    exit(1);
134
    return 0;
135 136
}

137 138
int64_t parse_time_or_die(const char *context, const char *timestr,
                          int is_duration)
139
{
140 141
    int64_t us;
    if (av_parse_time(&us, timestr, is_duration) < 0) {
142 143
        av_log(NULL, AV_LOG_FATAL, "Invalid %s specification for %s: %s\n",
               is_duration ? "duration" : "date", context, timestr);
144
        exit(1);
145 146 147 148
    }
    return us;
}

149
void show_help_options(const OptionDef *options, const char *msg, int req_flags,
150
                       int rej_flags, int alt_flags)
Fabrice Bellard's avatar
Fabrice Bellard committed
151 152
{
    const OptionDef *po;
153
    int first;
Fabrice Bellard's avatar
Fabrice Bellard committed
154

155
    first = 1;
156
    for (po = options; po->name != NULL; po++) {
157
        char buf[64];
158 159

        if (((po->flags & req_flags) != req_flags) ||
160
            (alt_flags && !(po->flags & alt_flags)) ||
161 162 163 164 165 166 167 168
            (po->flags & rej_flags))
            continue;

        if (first) {
            printf("%s\n", msg);
            first = 0;
        }
        av_strlcpy(buf, po->name, sizeof(buf));
169
        if (po->argname) {
170 171
            av_strlcat(buf, " ", sizeof(buf));
            av_strlcat(buf, po->argname, sizeof(buf));
Fabrice Bellard's avatar
Fabrice Bellard committed
172
        }
173
        printf("-%-17s  %s\n", buf, po->help);
Fabrice Bellard's avatar
Fabrice Bellard committed
174
    }
175
    printf("\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
176 177
}

178 179 180
void show_help_children(const AVClass *class, int flags)
{
    const AVClass *child = NULL;
181 182 183 184
    if (class->option) {
        av_opt_show2(&class, NULL, flags, 0);
        printf("\n");
    }
185 186 187 188 189

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

190 191
static const OptionDef *find_option(const OptionDef *po, const char *name)
{
192 193 194
    const char *p = strchr(name, ':');
    int len = p ? p - name : strlen(name);

195
    while (po->name != NULL) {
196
        if (!strncmp(name, po->name, len) && strlen(po->name) == len)
197 198 199 200 201 202
            break;
        po++;
    }
    return po;
}

203
#if HAVE_COMMANDLINETOARGVW
204
#include <windows.h>
205
#include <shellapi.h>
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
/* 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);

239 240
    win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);
    argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    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 */
}
263
#endif /* HAVE_COMMANDLINETOARGVW */
264

265 266
int parse_option(void *optctx, const char *opt, const char *arg,
                 const OptionDef *options)
Fabrice Bellard's avatar
Fabrice Bellard committed
267 268
{
    const OptionDef *po;
269
    int bool_val = 1;
270
    int *dstcount;
271 272 273 274 275 276
    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);
277 278
        if ((po->name && (po->flags & OPT_BOOL)))
            bool_val = 0;
279 280 281 282 283 284 285 286 287 288 289 290 291 292
    }
    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*/
293 294
    dst = po->flags & (OPT_OFFSET | OPT_SPEC) ? (uint8_t *)optctx + po->u.off
                                              : po->u.dst_ptr;
295 296 297 298 299

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

300
        dstcount = (int *)(so + 1);
301 302 303 304
        *so = grow_array(*so, sizeof(**so), dstcount, *dstcount + 1);
        (*so)[*dstcount - 1].specifier = av_strdup(p ? p + 1 : "");
        dst = &(*so)[*dstcount - 1].u;
    }
305 306 307 308

    if (po->flags & OPT_STRING) {
        char *str;
        str = av_strdup(arg);
309
//         av_freep(dst);
310
        *(char **)dst = str;
311
    } else if (po->flags & OPT_BOOL) {
312
        *(int *)dst = bool_val;
313
    } else if (po->flags & OPT_INT) {
314
        *(int *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
315
    } else if (po->flags & OPT_INT64) {
316
        *(int64_t *)dst = parse_number_or_die(opt, arg, OPT_INT64, INT64_MIN, INT64_MAX);
317
    } else if (po->flags & OPT_TIME) {
318
        *(int64_t *)dst = parse_time_or_die(opt, arg, 1);
319
    } else if (po->flags & OPT_FLOAT) {
320
        *(float *)dst = parse_number_or_die(opt, arg, OPT_FLOAT, -INFINITY, INFINITY);
321
    } else if (po->flags & OPT_DOUBLE) {
322
        *(double *)dst = parse_number_or_die(opt, arg, OPT_DOUBLE, -INFINITY, INFINITY);
323
    } else if (po->u.func_arg) {
324
        int ret = po->u.func_arg(optctx, opt, arg);
325
        if (ret < 0) {
326 327
            av_log(NULL, AV_LOG_ERROR,
                   "Failed to set value '%s' for option '%s'\n", arg, opt);
328 329 330 331
            return ret;
        }
    }
    if (po->flags & OPT_EXIT)
332
        exit(0);
333 334 335
    return !!(po->flags & HAS_ARG);
}

336
void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,
337
                   void (*parse_arg_function)(void *, const char*))
Fabrice Bellard's avatar
Fabrice Bellard committed
338
{
339 340
    const char *opt;
    int optindex, handleoptions = 1, ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
341

342 343 344
    /* perform system-dependent conversions for arguments list */
    prepare_app_arguments(&argc, &argv);

Fabrice Bellard's avatar
Fabrice Bellard committed
345 346 347 348
    /* parse options */
    optindex = 1;
    while (optindex < argc) {
        opt = argv[optindex++];
349

350
        if (handleoptions && opt[0] == '-' && opt[1] != '\0') {
Stefano Sabatini's avatar
Stefano Sabatini committed
351 352 353 354
            if (opt[1] == '-' && opt[2] == '\0') {
                handleoptions = 0;
                continue;
            }
355
            opt++;
356 357

            if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)
358
                exit(1);
359
            optindex += ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
360
        } else {
361
            if (parse_arg_function)
362
                parse_arg_function(optctx, opt);
Fabrice Bellard's avatar
Fabrice Bellard committed
363 364 365 366
        }
    }
}

367 368
int locate_option(int argc, char **argv, const OptionDef *options,
                  const char *optname)
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
{
    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;

387
        if (po->flags & HAS_ARG)
388 389 390 391 392
            i++;
    }
    return 0;
}

393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
static void dump_argument(const char *a)
{
    const unsigned char *p;

    for (p = a; *p; p++)
        if (!((*p >= '+' && *p <= ':') || (*p >= '@' && *p <= 'Z') ||
              *p == '_' || (*p >= 'a' && *p <= 'z')))
            break;
    if (!*p) {
        fputs(a, report_file);
        return;
    }
    fputc('"', report_file);
    for (p = a; *p; p++) {
        if (*p == '\\' || *p == '"' || *p == '$' || *p == '`')
            fprintf(report_file, "\\%c", *p);
        else if (*p < ' ' || *p > '~')
            fprintf(report_file, "\\x%02x", *p);
        else
            fputc(*p, report_file);
    }
    fputc('"', report_file);
}

417 418 419
void parse_loglevel(int argc, char **argv, const OptionDef *options)
{
    int idx = locate_option(argc, argv, options, "loglevel");
420
    const char *env;
421 422
    if (!idx)
        idx = locate_option(argc, argv, options, "v");
423
    if (idx && argv[idx + 1])
424
        opt_loglevel(NULL, "loglevel", argv[idx + 1]);
425
    idx = locate_option(argc, argv, options, "report");
426 427
    if ((env = getenv("FFREPORT")) || idx) {
        init_report(env);
428 429 430 431 432 433 434 435 436 437
        if (report_file) {
            int i;
            fprintf(report_file, "Command line:\n");
            for (i = 0; i < argc; i++) {
                dump_argument(argv[i]);
                fputc(i < argc - 1 ? ' ' : '\n', report_file);
            }
            fflush(report_file);
        }
    }
438 439
}

440
#define FLAGS (o->type == AV_OPT_TYPE_FLAGS) ? AV_DICT_APPEND : 0
441
int opt_default(void *optctx, const char *opt, const char *arg)
442
{
443
    const AVOption *o;
444
    int consumed = 0;
445 446
    char opt_stripped[128];
    const char *p;
447
    const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();
448
    const AVClass *sc, *swr_class;
449 450 451 452 453

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

454
    if ((o = av_opt_find(&cc, opt_stripped, NULL, 0,
455 456
                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||
        ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&
457
         (o = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {
458
        av_dict_set(&codec_opts, opt, arg, FLAGS);
459 460 461 462
        consumed = 1;
    }
    if ((o = av_opt_find(&fc, opt, NULL, 0,
                              AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {
463
        av_dict_set(&format_opts, opt, arg, FLAGS);
464 465 466 467
        if(consumed)
            av_log(NULL, AV_LOG_VERBOSE, "Routing %s to codec and muxer layer\n", opt);
        consumed = 1;
    }
468
#if CONFIG_SWSCALE
469
    sc = sws_get_class();
470 471
    if (!consumed && av_opt_find(&sc, opt, NULL, 0,
                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
472
        // XXX we only support sws_flags, not arbitrary sws options
473
        int ret = av_opt_set(sws_opts, opt, arg, 0);
474 475 476 477
        if (ret < 0) {
            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
            return ret;
        }
478
        consumed = 1;
479
    }
480
#endif
481
#if CONFIG_SWRESAMPLE
482
    swr_class = swr_get_class();
483 484
    if (!consumed && av_opt_find(&swr_class, opt, NULL, 0,
                               AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) {
485 486 487 488 489
        int ret = av_opt_set(swr_opts, opt, arg, 0);
        if (ret < 0) {
            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);
            return ret;
        }
490
        consumed = 1;
491
    }
492
#endif
493

494
    if (consumed)
495
        return 0;
496
    av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);
497 498
    return AVERROR_OPTION_NOT_FOUND;
}
499

500
int opt_loglevel(void *optctx, const char *opt, const char *arg)
501
{
502
    const struct { const char *name; int level; } log_levels[] = {
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        { "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) {
525 526
        av_log(NULL, AV_LOG_FATAL, "Invalid loglevel \"%s\". "
               "Possible levels are numbers or:\n", arg);
527
        for (i = 0; i < FF_ARRAY_ELEMS(log_levels); i++)
528
            av_log(NULL, AV_LOG_FATAL, "\"%s\"\n", log_levels[i].name);
529
        exit(1);
530 531 532 533 534
    }
    av_log_set_level(level);
    return 0;
}

535 536
static void expand_filename_template(AVBPrint *bp, const char *template,
                                     struct tm *tm)
537
{
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    int c;

    while ((c = *(template++))) {
        if (c == '%') {
            if (!(c = *(template++)))
                break;
            switch (c) {
            case 'p':
                av_bprintf(bp, "%s", program_name);
                break;
            case 't':
                av_bprintf(bp, "%04d%02d%02d-%02d%02d%02d",
                           tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
                           tm->tm_hour, tm->tm_min, tm->tm_sec);
                break;
            case '%':
                av_bprint_chars(bp, c, 1);
                break;
            }
        } else {
            av_bprint_chars(bp, c, 1);
        }
    }
}

static int init_report(const char *env)
{
565
    char *filename_template = NULL;
566 567
    char *key, *val;
    int ret, count = 0;
568 569
    time_t now;
    struct tm *tm;
570
    AVBPrint filename;
571 572 573 574 575

    if (report_file) /* already opened */
        return 0;
    time(&now);
    tm = localtime(&now);
576 577 578 579 580 581 582 583 584

    while (env && *env) {
        if ((ret = av_opt_get_key_value(&env, "=", ":", 0, &key, &val)) < 0) {
            if (count)
                av_log(NULL, AV_LOG_ERROR,
                       "Failed to parse FFREPORT environment variable: %s\n",
                       av_err2str(ret));
            break;
        }
585 586
        if (*env)
            env++;
587 588
        count++;
        if (!strcmp(key, "file")) {
589
            av_free(filename_template);
590 591 592 593 594 595 596 597 598 599
            filename_template = val;
            val = NULL;
        } else {
            av_log(NULL, AV_LOG_ERROR, "Unknown key '%s' in FFREPORT\n", key);
        }
        av_free(val);
        av_free(key);
    }

    av_bprint_init(&filename, 0, 1);
600 601 602
    expand_filename_template(&filename,
                             av_x_if_null(filename_template, "%p-%t.log"), tm);
    av_free(filename_template);
603 604 605 606 607 608
    if (!av_bprint_is_complete(&filename)) {
        av_log(NULL, AV_LOG_ERROR, "Out of memory building report file name\n");
        return AVERROR(ENOMEM);
    }

    report_file = fopen(filename.str, "w");
609 610
    if (!report_file) {
        av_log(NULL, AV_LOG_ERROR, "Failed to open report \"%s\": %s\n",
611
               filename.str, strerror(errno));
612 613 614 615 616 617 618 619 620
        return AVERROR(errno);
    }
    av_log_set_callback(log_callback_report);
    av_log(NULL, AV_LOG_INFO,
           "%s started on %04d-%02d-%02d at %02d:%02d:%02d\n"
           "Report written to \"%s\"\n",
           program_name,
           tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
           tm->tm_hour, tm->tm_min, tm->tm_sec,
621
           filename.str);
622
    av_log_set_level(FFMAX(av_log_get_level(), AV_LOG_VERBOSE));
623
    av_bprint_finalize(&filename, NULL);
624 625 626
    return 0;
}

627 628 629 630 631
int opt_report(const char *opt)
{
    return init_report(NULL);
}

632
int opt_max_alloc(void *optctx, const char *opt, const char *arg)
633 634 635 636 637 638 639
{
    char *tail;
    size_t max;

    max = strtol(arg, &tail, 10);
    if (*tail) {
        av_log(NULL, AV_LOG_FATAL, "Invalid max_alloc \"%s\".\n", arg);
640
        exit(1);
641 642 643 644 645
    }
    av_max_alloc(max);
    return 0;
}

646
int opt_cpuflags(void *optctx, const char *opt, const char *arg)
647
{
648
    int ret;
649
    unsigned flags = av_get_cpu_flags();
650

651
    if ((ret = av_parse_cpu_caps(&flags, arg)) < 0)
652
        return ret;
653 654 655 656 657

    av_force_cpu_flags(flags);
    return 0;
}

658
int opt_codec_debug(void *optctx, const char *opt, const char *arg)
659 660
{
    av_log_set_level(AV_LOG_DEBUG);
661
    return opt_default(NULL, opt, arg);
662 663
}

664
int opt_timelimit(void *optctx, const char *opt, const char *arg)
Måns Rullgård's avatar
Måns Rullgård committed
665
{
Måns Rullgård's avatar
Måns Rullgård committed
666
#if HAVE_SETRLIMIT
Måns Rullgård's avatar
Måns Rullgård committed
667 668 669 670 671
    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
672
    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
673 674 675 676
#endif
    return 0;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
677 678
void print_error(const char *filename, int err)
{
679
    char errbuf[128];
680
    const char *errbuf_ptr = errbuf;
681

682 683
    if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
        errbuf_ptr = strerror(AVUNERROR(err));
684
    av_log(NULL, AV_LOG_ERROR, "%s: %s\n", filename, errbuf_ptr);
Fabrice Bellard's avatar
Fabrice Bellard committed
685
}
686

687 688
static int warned_cfg = 0;

689 690
#define INDENT        1
#define SHOW_VERSION  2
691
#define SHOW_CONFIG   4
692
#define SHOW_COPYRIGHT 8
693

694
#define PRINT_LIB_INFO(libname, LIBNAME, flags, level)                  \
695
    if (CONFIG_##LIBNAME) {                                             \
696
        const char *indent = flags & INDENT? "  " : "";                 \
697
        if (flags & SHOW_VERSION) {                                     \
Stefano Sabatini's avatar
Stefano Sabatini committed
698
            unsigned int version = libname##_version();                 \
699
            av_log(NULL, level,                                         \
700
                   "%slib%-11s %2d.%3d.%3d / %2d.%3d.%3d\n",            \
701 702 703 704 705
                   indent, #libname,                                    \
                   LIB##LIBNAME##_VERSION_MAJOR,                        \
                   LIB##LIBNAME##_VERSION_MINOR,                        \
                   LIB##LIBNAME##_VERSION_MICRO,                        \
                   version >> 16, version >> 8 & 0xff, version & 0xff); \
706
        }                                                               \
707 708
        if (flags & SHOW_CONFIG) {                                      \
            const char *cfg = libname##_configuration();                \
709
            if (strcmp(FFMPEG_CONFIGURATION, cfg)) {                    \
710
                if (!warned_cfg) {                                      \
711
                    av_log(NULL, level,                                 \
712
                            "%sWARNING: library configuration mismatch\n", \
713
                            indent);                                    \
714 715
                    warned_cfg = 1;                                     \
                }                                                       \
716
                av_log(NULL, level, "%s%-11s configuration: %s\n",      \
717
                        indent, #libname, cfg);                         \
718 719
            }                                                           \
        }                                                               \
720
    }                                                                   \
721

722
static void print_all_libs_info(int flags, int level)
723
{
724 725 726 727 728
    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);
729
//    PRINT_LIB_INFO(avresample, AVRESAMPLE, flags, level);
730
    PRINT_LIB_INFO(swscale,  SWSCALE,  flags, level);
731
    PRINT_LIB_INFO(swresample,SWRESAMPLE,  flags, level);
732
#if CONFIG_POSTPROC
733
    PRINT_LIB_INFO(postproc, POSTPROC, flags, level);
734
#endif
735 736
}

737 738 739 740 741 742 743 744 745
static void print_program_info(int flags, int level)
{
    const char *indent = flags & INDENT? "  " : "";

    av_log(NULL, level, "%s version " FFMPEG_VERSION, program_name);
    if (flags & SHOW_COPYRIGHT)
        av_log(NULL, level, " Copyright (c) %d-%d the FFmpeg developers",
               program_birth_year, this_year);
    av_log(NULL, level, "\n");
746 747 748
    av_log(NULL, level, "%sbuilt on %s %s with %s\n",
           indent, __DATE__, __TIME__, CC_IDENT);

749 750 751
    av_log(NULL, level, "%sconfiguration: " FFMPEG_CONFIGURATION "\n", indent);
}

752
void show_banner(int argc, char **argv, const OptionDef *options)
753
{
754 755 756 757
    int idx = locate_option(argc, argv, options, "version");
    if (idx)
        return;

758
    print_program_info (INDENT|SHOW_COPYRIGHT, AV_LOG_INFO);
759 760
    print_all_libs_info(INDENT|SHOW_CONFIG,  AV_LOG_INFO);
    print_all_libs_info(INDENT|SHOW_VERSION, AV_LOG_INFO);
761 762
}

763
int show_version(void *optctx, const char *opt, const char *arg)
764
{
765
    av_log_set_callback(log_callback_help);
766
    print_program_info (0           , AV_LOG_INFO);
767
    print_all_libs_info(SHOW_VERSION, AV_LOG_INFO);
768

769
    return 0;
770 771
}

772
int show_license(void *optctx, const char *opt, const char *arg)
773
{
774
#if CONFIG_NONFREE
775
    printf(
776 777
    "This version of %s has nonfree parts compiled in.\n"
    "Therefore it is not legally redistributable.\n",
778
    program_name );
779
#elif CONFIG_GPLV3
780
    printf(
781 782 783 784 785 786 787 788 789 790 791 792
    "%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",
793
    program_name, program_name, program_name );
794
#elif CONFIG_GPL
795
    printf(
796
    "%s is free software; you can redistribute it and/or modify\n"
797 798 799 800
    "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"
801
    "%s is distributed in the hope that it will be useful,\n"
802 803 804 805 806
    "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"
807 808
    "along with %s; if not, write to the Free Software\n"
    "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n",
809
    program_name, program_name, program_name );
810
#elif CONFIG_LGPLV3
811
    printf(
812 813 814 815 816 817 818 819 820 821 822 823
    "%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",
824
    program_name, program_name, program_name );
825
#else
826
    printf(
827
    "%s is free software; you can redistribute it and/or\n"
828 829 830 831
    "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"
832
    "%s is distributed in the hope that it will be useful,\n"
833 834 835 836 837
    "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"
838 839
    "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",
840
    program_name, program_name, program_name );
841
#endif
842

843
    return 0;
844
}
845

846
int show_formats(void *optctx, const char *opt, const char *arg)
847
{
848 849
    AVInputFormat *ifmt  = NULL;
    AVOutputFormat *ofmt = NULL;
850 851
    const char *last_name;

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
    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;
869 870
            }
        }
871 872 873 874 875 876
        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;
877
            }
878 879
            if (name && strcmp(ifmt->name, name) == 0)
                decode = 1;
880
        }
881
        if (name == NULL)
882
            break;
883
        last_name = name;
884

885 886 887 888
        printf(" %s%s %-15s %s\n",
               decode ? "D" : " ",
               encode ? "E" : " ",
               name,
889 890
            long_name ? long_name:" ");
    }
891
    return 0;
892
}
893

894 895
#define PRINT_CODEC_SUPPORTED(codec, field, type, list_name, term, get_name) \
    if (codec->field) {                                                      \
896
        const type *p = codec->field;                                        \
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
                                                                             \
        printf("    Supported " list_name ":");                              \
        while (*p != term) {                                                 \
            get_name(*p);                                                    \
            printf(" %s", name);                                             \
            p++;                                                             \
        }                                                                    \
        printf("\n");                                                        \
    }                                                                        \

static void print_codec(const AVCodec *c)
{
    int encoder = av_codec_is_encoder(c);

    printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,
           c->long_name ? c->long_name : "");

    if (c->type == AVMEDIA_TYPE_VIDEO) {
        printf("    Threading capabilities: ");
        switch (c->capabilities & (CODEC_CAP_FRAME_THREADS |
                                   CODEC_CAP_SLICE_THREADS)) {
        case CODEC_CAP_FRAME_THREADS |
             CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;
        case CODEC_CAP_FRAME_THREADS: printf("frame");           break;
        case CODEC_CAP_SLICE_THREADS: printf("slice");           break;
        default:                      printf("no");              break;
        }
        printf("\n");
    }

    if (c->supported_framerates) {
        const AVRational *fps = c->supported_framerates;

        printf("    Supported framerates:");
        while (fps->num) {
            printf(" %d/%d", fps->num, fps->den);
            fps++;
        }
        printf("\n");
    }
937 938
    PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",
                          AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);
939 940 941 942 943 944 945 946 947 948 949 950 951 952
    PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,
                          GET_SAMPLE_RATE_NAME);
    PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",
                          AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);
    PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",
                          0, GET_CH_LAYOUT_DESC);

    if (c->priv_class) {
        show_help_children(c->priv_class,
                           AV_OPT_FLAG_ENCODING_PARAM |
                           AV_OPT_FLAG_DECODING_PARAM);
    }
}

953 954
static char get_media_type_char(enum AVMediaType type)
{
955 956 957
    switch (type) {
        case AVMEDIA_TYPE_VIDEO:    return 'V';
        case AVMEDIA_TYPE_AUDIO:    return 'A';
958
        case AVMEDIA_TYPE_DATA:     return 'D';
959
        case AVMEDIA_TYPE_SUBTITLE: return 'S';
960
        case AVMEDIA_TYPE_ATTACHMENT:return 'T';
961 962
        default:                    return '?';
    }
963 964
}

965 966
static const AVCodec *next_codec_for_id(enum AVCodecID id, const AVCodec *prev,
                                        int encoder)
967
{
968 969 970 971 972 973 974 975
    while ((prev = av_codec_next(prev))) {
        if (prev->id == id &&
            (encoder ? av_codec_is_encoder(prev) : av_codec_is_decoder(prev)))
            return prev;
    }
    return NULL;
}

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
static int compare_codec_desc(const void *a, const void *b)
{
    const AVCodecDescriptor * const *da = a;
    const AVCodecDescriptor * const *db = b;

    return (*da)->type != (*db)->type ? (*da)->type - (*db)->type :
           strcmp((*da)->name, (*db)->name);
}

static unsigned get_codecs_sorted(const AVCodecDescriptor ***rcodecs)
{
    const AVCodecDescriptor *desc = NULL;
    const AVCodecDescriptor **codecs;
    unsigned nb_codecs = 0, i = 0;

    while ((desc = avcodec_descriptor_next(desc)))
        nb_codecs++;
    if (!(codecs = av_calloc(nb_codecs, sizeof(*codecs)))) {
994
        av_log(NULL, AV_LOG_ERROR, "Out of memory\n");
995
        exit(1);
996 997 998 999 1000 1001 1002 1003 1004 1005
    }
    desc = NULL;
    while ((desc = avcodec_descriptor_next(desc)))
        codecs[i++] = desc;
    av_assert0(i == nb_codecs);
    qsort(codecs, nb_codecs, sizeof(*codecs), compare_codec_desc);
    *rcodecs = codecs;
    return nb_codecs;
}

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
static void print_codecs_for_id(enum AVCodecID id, int encoder)
{
    const AVCodec *codec = NULL;

    printf(" (%s: ", encoder ? "encoders" : "decoders");

    while ((codec = next_codec_for_id(id, codec, encoder)))
        printf("%s ", codec->name);

    printf(")");
}

1018
int show_codecs(void *optctx, const char *opt, const char *arg)
1019
{
1020 1021
    const AVCodecDescriptor **codecs;
    unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1022

1023
    printf("Codecs:\n"
1024 1025 1026 1027 1028 1029 1030 1031 1032
           " D..... = Decoding supported\n"
           " .E.... = Encoding supported\n"
           " ..V... = Video codec\n"
           " ..A... = Audio codec\n"
           " ..S... = Subtitle codec\n"
           " ...I.. = Intra frame-only codec\n"
           " ....L. = Lossy compression\n"
           " .....S = Lossless compression\n"
           " -------\n");
1033 1034
    for (i = 0; i < nb_codecs; i++) {
        const AVCodecDescriptor *desc = codecs[i];
1035 1036
        const AVCodec *codec = NULL;

1037
        printf(" ");
1038 1039 1040 1041 1042
        printf(avcodec_find_decoder(desc->id) ? "D" : ".");
        printf(avcodec_find_encoder(desc->id) ? "E" : ".");

        printf("%c", get_media_type_char(desc->type));
        printf((desc->props & AV_CODEC_PROP_INTRA_ONLY) ? "I" : ".");
1043 1044
        printf((desc->props & AV_CODEC_PROP_LOSSY)      ? "L" : ".");
        printf((desc->props & AV_CODEC_PROP_LOSSLESS)   ? "S" : ".");
1045 1046 1047 1048 1049 1050 1051 1052 1053

        printf(" %-20s %s", desc->name, desc->long_name ? desc->long_name : "");

        /* print decoders/encoders when there's more than one or their
         * names are different from codec name */
        while ((codec = next_codec_for_id(desc->id, codec, 0))) {
            if (strcmp(codec->name, desc->name)) {
                print_codecs_for_id(desc->id, 0);
                break;
1054
            }
1055 1056 1057 1058 1059 1060
        }
        codec = NULL;
        while ((codec = next_codec_for_id(desc->id, codec, 1))) {
            if (strcmp(codec->name, desc->name)) {
                print_codecs_for_id(desc->id, 1);
                break;
1061 1062 1063 1064 1065
            }
        }

        printf("\n");
    }
1066
    av_free(codecs);
1067
    return 0;
1068 1069 1070 1071
}

static void print_codecs(int encoder)
{
1072 1073
    const AVCodecDescriptor **codecs;
    unsigned i, nb_codecs = get_codecs_sorted(&codecs);
1074 1075

    printf("%s:\n"
1076 1077 1078 1079 1080 1081 1082 1083 1084
           " V..... = Video\n"
           " A..... = Audio\n"
           " S..... = Subtitle\n"
           " .F.... = Frame-level multithreading\n"
           " ..S... = Slice-level multithreading\n"
           " ...X.. = Codec is experimental\n"
           " ....B. = Supports draw_horiz_band\n"
           " .....D = Supports direct rendering method 1\n"
           " ------\n",
1085
           encoder ? "Encoders" : "Decoders");
1086 1087
    for (i = 0; i < nb_codecs; i++) {
        const AVCodecDescriptor *desc = codecs[i];
1088 1089 1090
        const AVCodec *codec = NULL;

        while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
1091
            printf(" %c", get_media_type_char(desc->type));
1092 1093 1094
            printf((codec->capabilities & CODEC_CAP_FRAME_THREADS) ? "F" : ".");
            printf((codec->capabilities & CODEC_CAP_SLICE_THREADS) ? "S" : ".");
            printf((codec->capabilities & CODEC_CAP_EXPERIMENTAL)  ? "X" : ".");
1095 1096
            printf((codec->capabilities & CODEC_CAP_DRAW_HORIZ_BAND)?"B" : ".");
            printf((codec->capabilities & CODEC_CAP_DR1)           ? "D" : ".");
1097 1098 1099 1100 1101 1102 1103 1104

            printf(" %-20s %s", codec->name, codec->long_name ? codec->long_name : "");
            if (strcmp(codec->name, desc->name))
                printf(" (codec %s)", desc->name);

            printf("\n");
        }
    }
1105
    av_free(codecs);
1106 1107
}

1108
int show_decoders(void *optctx, const char *opt, const char *arg)
1109 1110 1111 1112 1113
{
    print_codecs(0);
    return 0;
}

1114
int show_encoders(void *optctx, const char *opt, const char *arg)
1115 1116
{
    print_codecs(1);
1117
    return 0;
1118 1119
}

1120
int show_bsfs(void *optctx, const char *opt, const char *arg)
1121
{
1122
    AVBitStreamFilter *bsf = NULL;
1123 1124

    printf("Bitstream filters:\n");
1125
    while ((bsf = av_bitstream_filter_next(bsf)))
1126
        printf("%s\n", bsf->name);
1127
    printf("\n");
1128
    return 0;
1129 1130
}

1131
int show_protocols(void *optctx, const char *opt, const char *arg)
1132
{
1133 1134
    void *opaque = NULL;
    const char *name;
1135

1136
    printf("Supported file protocols:\n"
1137 1138 1139 1140 1141 1142
           "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);
1143
    return 0;
1144
}
1145

1146
int show_filters(void *optctx, const char *opt, const char *arg)
1147
{
1148
    AVFilter av_unused(**filter) = NULL;
1149 1150 1151
    char descr[64], *descr_cur;
    int i, j;
    const AVFilterPad *pad;
1152 1153

    printf("Filters:\n");
1154
#if CONFIG_AVFILTER
1155 1156 1157 1158 1159 1160 1161 1162
    while ((filter = av_filter_next(filter)) && *filter) {
        descr_cur = descr;
        for (i = 0; i < 2; i++) {
            if (i) {
                *(descr_cur++) = '-';
                *(descr_cur++) = '>';
            }
            pad = i ? (*filter)->outputs : (*filter)->inputs;
1163
            for (j = 0; pad && pad[j].name; j++) {
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
                if (descr_cur >= descr + sizeof(descr) - 4)
                    break;
                *(descr_cur++) = get_media_type_char(pad[j].type);
            }
            if (!j)
                *(descr_cur++) = '|';
        }
        *descr_cur = 0;
        printf("%-16s %-10s %s\n", (*filter)->name, descr, (*filter)->description);
    }
1174
#endif
1175
    return 0;
1176 1177
}

1178
int show_pix_fmts(void *optctx, const char *opt, const char *arg)
1179
{
1180
    const AVPixFmtDescriptor *pix_desc = NULL;
1181

1182 1183 1184 1185 1186 1187 1188 1189
    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");
1190

1191 1192 1193 1194 1195
#if !CONFIG_SWSCALE
#   define sws_isSupportedInput(x)  0
#   define sws_isSupportedOutput(x) 0
#endif

1196 1197
    while ((pix_desc = av_pix_fmt_desc_next(pix_desc))) {
        enum AVPixelFormat pix_fmt = av_pix_fmt_desc_get_id(pix_desc);
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        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));
    }
1208
    return 0;
1209 1210
}

1211
int show_layouts(void *optctx, const char *opt, const char *arg)
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
{
    int i = 0;
    uint64_t layout, j;
    const char *name, *descr;

    printf("Individual channels:\n"
           "NAME        DESCRIPTION\n");
    for (i = 0; i < 63; i++) {
        name = av_get_channel_name((uint64_t)1 << i);
        if (!name)
            continue;
        descr = av_get_channel_description((uint64_t)1 << i);
        printf("%-12s%s\n", name, descr);
    }
    printf("\nStandard channel layouts:\n"
           "NAME        DECOMPOSITION\n");
    for (i = 0; !av_get_standard_channel_layout(i, &layout, &name); i++) {
        if (name) {
            printf("%-12s", name);
            for (j = 1; j; j <<= 1)
                if ((layout & j))
                    printf("%s%s", (layout & (j - 1)) ? "+" : "", av_get_channel_name(j));
            printf("\n");
        }
    }
    return 0;
}

1240
int show_sample_fmts(void *optctx, const char *opt, const char *arg)
1241 1242 1243 1244 1245 1246 1247 1248
{
    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;
}

1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
static void show_help_codec(const char *name, int encoder)
{
    const AVCodecDescriptor *desc;
    const AVCodec *codec;

    if (!name) {
        av_log(NULL, AV_LOG_ERROR, "No codec name specified.\n");
        return;
    }

    codec = encoder ? avcodec_find_encoder_by_name(name) :
                      avcodec_find_decoder_by_name(name);

    if (codec)
        print_codec(codec);
    else if ((desc = avcodec_descriptor_get_by_name(name))) {
        int printed = 0;

        while ((codec = next_codec_for_id(desc->id, codec, encoder))) {
            printed = 1;
            print_codec(codec);
        }

        if (!printed) {
1273 1274
            av_log(NULL, AV_LOG_ERROR, "Codec '%s' is known to FFmpeg, "
                   "but no %s for it are available. FFmpeg might need to be "
1275 1276 1277 1278
                   "recompiled with additional external libraries.\n",
                   name, encoder ? "encoders" : "decoders");
        }
    } else {
1279
        av_log(NULL, AV_LOG_ERROR, "Codec '%s' is not recognized by FFmpeg.\n",
1280 1281 1282 1283
               name);
    }
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
static void show_help_demuxer(const char *name)
{
    const AVInputFormat *fmt = av_find_input_format(name);

    if (!fmt) {
        av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
        return;
    }

    printf("Demuxer %s [%s]:\n", fmt->name, fmt->long_name);

    if (fmt->extensions)
        printf("    Common extensions: %s.\n", fmt->extensions);

    if (fmt->priv_class)
        show_help_children(fmt->priv_class, AV_OPT_FLAG_DECODING_PARAM);
}

static void show_help_muxer(const char *name)
{
    const AVCodecDescriptor *desc;
    const AVOutputFormat *fmt = av_guess_format(name, NULL, NULL);

    if (!fmt) {
        av_log(NULL, AV_LOG_ERROR, "Unknown format '%s'.\n", name);
        return;
    }

    printf("Muxer %s [%s]:\n", fmt->name, fmt->long_name);

    if (fmt->extensions)
        printf("    Common extensions: %s.\n", fmt->extensions);
    if (fmt->mime_type)
        printf("    Mime type: %s.\n", fmt->mime_type);
    if (fmt->video_codec != AV_CODEC_ID_NONE &&
        (desc = avcodec_descriptor_get(fmt->video_codec))) {
        printf("    Default video codec: %s.\n", desc->name);
    }
    if (fmt->audio_codec != AV_CODEC_ID_NONE &&
        (desc = avcodec_descriptor_get(fmt->audio_codec))) {
        printf("    Default audio codec: %s.\n", desc->name);
    }
    if (fmt->subtitle_codec != AV_CODEC_ID_NONE &&
        (desc = avcodec_descriptor_get(fmt->subtitle_codec))) {
        printf("    Default subtitle codec: %s.\n", desc->name);
    }

    if (fmt->priv_class)
        show_help_children(fmt->priv_class, AV_OPT_FLAG_ENCODING_PARAM);
}

1335
int show_help(void *optctx, const char *opt, const char *arg)
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
{
    char *topic, *par;
    av_log_set_callback(log_callback_help);

    topic = av_strdup(arg ? arg : "");
    par = strchr(topic, '=');
    if (par)
        *par++ = 0;

    if (!*topic) {
        show_help_default(topic, par);
    } else if (!strcmp(topic, "decoder")) {
        show_help_codec(par, 0);
    } else if (!strcmp(topic, "encoder")) {
        show_help_codec(par, 1);
1351 1352 1353 1354
    } else if (!strcmp(topic, "demuxer")) {
        show_help_demuxer(par);
    } else if (!strcmp(topic, "muxer")) {
        show_help_muxer(par);
1355 1356 1357 1358 1359 1360 1361 1362
    } else {
        show_help_default(topic, par);
    }

    av_freep(&topic);
    return 0;
}

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
int read_yesno(void)
{
    int c = getchar();
    int yesno = (toupper(c) == 'Y');

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

    return yesno;
}
1373

1374
int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
1375
{
1376
    int ret;
1377
    FILE *f = fopen(filename, "rb");
1378 1379

    if (!f) {
1380 1381
        av_log(NULL, AV_LOG_ERROR, "Cannot read file '%s': %s\n", filename,
               strerror(errno));
1382 1383 1384 1385 1386
        return AVERROR(errno);
    }
    fseek(f, 0, SEEK_END);
    *size = ftell(f);
    fseek(f, 0, SEEK_SET);
1387 1388
    if (*size == (size_t)-1) {
        av_log(NULL, AV_LOG_ERROR, "IO error: %s\n", strerror(errno));
1389
        fclose(f);
1390 1391
        return AVERROR(errno);
    }
1392 1393
    *bufptr = av_malloc(*size + 1);
    if (!*bufptr) {
1394
        av_log(NULL, AV_LOG_ERROR, "Could not allocate file buffer\n");
1395 1396 1397
        fclose(f);
        return AVERROR(ENOMEM);
    }
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
    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;
1409
        (*bufptr)[(*size)++] = '\0';
1410
    }
1411 1412

    fclose(f);
1413
    return ret;
1414
}
1415

1416
FILE *get_preset_file(char *filename, size_t filename_size,
1417 1418
                      const char *preset_name, int is_path,
                      const char *codec_name)
1419 1420 1421
{
    FILE *f = NULL;
    int i;
1422
    const char *base[3] = { getenv("FFMPEG_DATADIR"),
1423
                            getenv("HOME"),
1424
                            FFMPEG_DATADIR, };
1425 1426 1427 1428 1429

    if (is_path) {
        av_strlcpy(filename, preset_name, filename_size);
        f = fopen(filename, "r");
    } else {
Gianluigi Tiesi's avatar
Gianluigi Tiesi committed
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
#ifdef _WIN32
        char datadir[MAX_PATH], *ls;
        base[2] = NULL;

        if (GetModuleFileNameA(GetModuleHandleA(NULL), datadir, sizeof(datadir) - 1))
        {
            for (ls = datadir; ls < datadir + strlen(datadir); ls++)
                if (*ls == '\\') *ls = '/';

            if (ls = strrchr(datadir, '/'))
            {
                *ls = 0;
                strncat(datadir, "/ffpresets",  sizeof(datadir) - 1 - strlen(datadir));
                base[2] = datadir;
            }
        }
#endif
1447 1448 1449
        for (i = 0; i < 3 && !f; i++) {
            if (!base[i])
                continue;
1450
            snprintf(filename, filename_size, "%s%s/%s.ffpreset", base[i],
1451
                     i != 1 ? "" : "/.ffmpeg", preset_name);
1452 1453 1454
            f = fopen(filename, "r");
            if (!f && codec_name) {
                snprintf(filename, filename_size,
1455
                         "%s%s/%s-%s.ffpreset",
1456
                         base[i], i != 1 ? "" : "/.ffmpeg", codec_name,
1457
                         preset_name);
1458 1459 1460 1461 1462 1463 1464 1465
                f = fopen(filename, "r");
            }
        }
    }

    return f;
}

1466 1467
int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)
{
1468 1469 1470 1471
    int ret = avformat_match_stream_specifier(s, st, spec);
    if (ret < 0)
        av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
    return ret;
1472 1473
}

1474
AVDictionary *filter_codec_opts(AVDictionary *opts, enum AVCodecID codec_id,
1475
                                AVFormatContext *s, AVStream *st, AVCodec *codec)
1476 1477 1478
{
    AVDictionary    *ret = NULL;
    AVDictionaryEntry *t = NULL;
1479 1480
    int            flags = s->oformat ? AV_OPT_FLAG_ENCODING_PARAM
                                      : AV_OPT_FLAG_DECODING_PARAM;
1481
    char          prefix = 0;
1482
    const AVClass    *cc = avcodec_get_class();
1483

1484 1485 1486
    if (!codec)
        codec            = s->oformat ? avcodec_find_encoder(codec_id)
                                      : avcodec_find_decoder(codec_id);
1487 1488 1489 1490
    if (!codec)
        return NULL;

    switch (codec->type) {
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    case AVMEDIA_TYPE_VIDEO:
        prefix  = 'v';
        flags  |= AV_OPT_FLAG_VIDEO_PARAM;
        break;
    case AVMEDIA_TYPE_AUDIO:
        prefix  = 'a';
        flags  |= AV_OPT_FLAG_AUDIO_PARAM;
        break;
    case AVMEDIA_TYPE_SUBTITLE:
        prefix  = 's';
        flags  |= AV_OPT_FLAG_SUBTITLE_PARAM;
        break;
1503 1504 1505
    }

    while (t = av_dict_get(opts, "", t, AV_DICT_IGNORE_SUFFIX)) {
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        char *p = strchr(t->key, ':');

        /* check stream specification in opt name */
        if (p)
            switch (check_stream_specifier(s, st, p + 1)) {
            case  1: *p = 0; break;
            case  0:         continue;
            default:         return NULL;
            }

1516
        if (av_opt_find(&cc, t->key, NULL, flags, AV_OPT_SEARCH_FAKE_OBJ) ||
1517 1518 1519
            (codec && codec->priv_class &&
             av_opt_find(&codec->priv_class, t->key, NULL, flags,
                         AV_OPT_SEARCH_FAKE_OBJ)))
1520
            av_dict_set(&ret, t->key, t->value, 0);
1521 1522 1523 1524
        else if (t->key[0] == prefix &&
                 av_opt_find(&cc, t->key + 1, NULL, flags,
                             AV_OPT_SEARCH_FAKE_OBJ))
            av_dict_set(&ret, t->key + 1, t->value, 0);
1525 1526 1527

        if (p)
            *p = ':';
1528 1529 1530 1531
    }
    return ret;
}

1532 1533
AVDictionary **setup_find_stream_info_opts(AVFormatContext *s,
                                           AVDictionary *codec_opts)
1534 1535 1536 1537 1538 1539 1540 1541
{
    int i;
    AVDictionary **opts;

    if (!s->nb_streams)
        return NULL;
    opts = av_mallocz(s->nb_streams * sizeof(*opts));
    if (!opts) {
1542 1543
        av_log(NULL, AV_LOG_ERROR,
               "Could not alloc memory for stream options.\n");
1544 1545 1546
        return NULL;
    }
    for (i = 0; i < s->nb_streams; i++)
1547
        opts[i] = filter_codec_opts(codec_opts, s->streams[i]->codec->codec_id,
1548
                                    s, s->streams[i], NULL);
1549 1550 1551
    return opts;
}

1552 1553 1554 1555
void *grow_array(void *array, int elem_size, int *size, int new_size)
{
    if (new_size >= INT_MAX / elem_size) {
        av_log(NULL, AV_LOG_ERROR, "Array too big.\n");
1556
        exit(1);
1557 1558 1559 1560 1561
    }
    if (*size < new_size) {
        uint8_t *tmp = av_realloc(array, new_size*elem_size);
        if (!tmp) {
            av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");
1562
            exit(1);
1563 1564 1565 1566 1567 1568 1569
        }
        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
        *size = new_size;
        return tmp;
    }
    return array;
}
1570 1571 1572

static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)
{
1573 1574
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);
    FrameBuffer *buf;
1575
    int i, ret;
1576
    int pixel_size;
1577 1578 1579 1580
    int h_chroma_shift, v_chroma_shift;
    int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
    int w = s->width, h = s->height;

1581 1582 1583 1584 1585
    if (!desc)
        return AVERROR(EINVAL);
    pixel_size = desc->comp[0].step_minus1 + 1;

    buf = av_mallocz(sizeof(*buf));
1586 1587 1588
    if (!buf)
        return AVERROR(ENOMEM);

1589 1590
    avcodec_align_dimensions(s, &w, &h);

1591 1592 1593 1594 1595 1596 1597 1598
    if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
        w += 2*edge;
        h += 2*edge;
    }

    if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
                              s->pix_fmt, 32)) < 0) {
        av_freep(&buf);
1599
        av_log(s, AV_LOG_ERROR, "alloc_buffer: av_image_alloc() failed\n");
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
        return ret;
    }
    /* XXX this shouldn't be needed, but some tests break without this line
     * those decoders are buggy and need to be fixed.
     * the following tests fail:
     * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
     */
    memset(buf->base[0], 128, ret);

    avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
        const int h_shift = i==0 ? 0 : h_chroma_shift;
        const int v_shift = i==0 ? 0 : v_chroma_shift;
1613
        if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[i] || !buf->base[i])
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
            buf->data[i] = buf->base[i];
        else
            buf->data[i] = buf->base[i] +
                           FFALIGN((buf->linesize[i]*edge >> v_shift) +
                                   (pixel_size*edge >> h_shift), 32);
    }
    buf->w       = s->width;
    buf->h       = s->height;
    buf->pix_fmt = s->pix_fmt;
    buf->pool    = pool;

    *pbuf = buf;
    return 0;
}

int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
{
    FrameBuffer **pool = s->opaque;
    FrameBuffer *buf;
    int ret, i;

1635 1636
    if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0) {
        av_log(s, AV_LOG_ERROR, "codec_get_buffer: image parameters invalid\n");
1637
        return -1;
1638
    }
1639

1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
    if (!*pool && (ret = alloc_buffer(pool, s, pool)) < 0)
        return ret;

    buf              = *pool;
    *pool            = buf->next;
    buf->next        = NULL;
    if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
        av_freep(&buf->base[0]);
        av_free(buf);
        if ((ret = alloc_buffer(pool, s, &buf)) < 0)
            return ret;
    }
1652
    av_assert0(!buf->refcount);
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    buf->refcount++;

    frame->opaque        = buf;
    frame->type          = FF_BUFFER_TYPE_USER;
    frame->extended_data = frame->data;

    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
        frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
        frame->data[i]     = buf->data[i];
        frame->linesize[i] = buf->linesize[i];
    }

    return 0;
}

static void unref_buffer(FrameBuffer *buf)
{
    FrameBuffer **pool = buf->pool;

1672
    av_assert0(buf->refcount > 0);
1673 1674
    buf->refcount--;
    if (!buf->refcount) {
1675 1676 1677 1678
        FrameBuffer *tmp;
        for(tmp= *pool; tmp; tmp= tmp->next)
            av_assert1(tmp != buf);

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
        buf->next = *pool;
        *pool = buf;
    }
}

void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
{
    FrameBuffer *buf = frame->opaque;
    int i;

1689
    if(frame->type!=FF_BUFFER_TYPE_USER) {
1690
        avcodec_default_release_buffer(s, frame);
1691 1692
        return;
    }
1693

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
    for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
        frame->data[i] = NULL;

    unref_buffer(buf);
}

void filter_release_buffer(AVFilterBuffer *fb)
{
    FrameBuffer *buf = fb->priv;
    av_free(fb);
    unref_buffer(buf);
}

void free_buffer_pool(FrameBuffer **pool)
{
    FrameBuffer *buf = *pool;
    while (buf) {
        *pool = buf->next;
        av_freep(&buf->base[0]);
        av_free(buf);
        buf = *pool;
    }
}