vf_pad.c 16.4 KB
Newer Older
M
Michael Niedermayer 已提交
1
/*
2 3
 * Copyright (c) 2008 vmrsss
 * Copyright (c) 2009 Stefano Sabatini
M
Michael Niedermayer 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * 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
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
23
 * @file
S
Stefano Sabatini 已提交
24
 * video padding filter
M
Michael Niedermayer 已提交
25 26
 */

27 28
#include <float.h>  /* DBL_MAX */

M
Michael Niedermayer 已提交
29
#include "avfilter.h"
30
#include "formats.h"
31
#include "internal.h"
32
#include "video.h"
33
#include "libavutil/avstring.h"
34
#include "libavutil/common.h"
35
#include "libavutil/eval.h"
M
Michael Niedermayer 已提交
36
#include "libavutil/pixdesc.h"
37
#include "libavutil/colorspace.h"
38 39
#include "libavutil/imgutils.h"
#include "libavutil/parseutils.h"
40
#include "libavutil/mathematics.h"
41 42
#include "libavutil/opt.h"

S
Stefano Sabatini 已提交
43
#include "drawutils.h"
44

45
static const char *const var_names[] = {
46 47 48 49 50 51
    "in_w",   "iw",
    "in_h",   "ih",
    "out_w",  "ow",
    "out_h",  "oh",
    "x",
    "y",
52
    "a",
53
    "sar",
54
    "dar",
55 56 57 58 59 60 61 62 63 64 65 66
    "hsub",
    "vsub",
    NULL
};

enum var_name {
    VAR_IN_W,   VAR_IW,
    VAR_IN_H,   VAR_IH,
    VAR_OUT_W,  VAR_OW,
    VAR_OUT_H,  VAR_OH,
    VAR_X,
    VAR_Y,
67
    VAR_A,
68
    VAR_SAR,
69
    VAR_DAR,
70 71 72 73 74
    VAR_HSUB,
    VAR_VSUB,
    VARS_NB
};

75 76
static int query_formats(AVFilterContext *ctx)
{
77
    return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
78 79
}

80 81 82 83 84 85
enum EvalMode {
    EVAL_MODE_INIT,
    EVAL_MODE_FRAME,
    EVAL_MODE_NB
};

V
Vittorio Giovara 已提交
86
typedef struct PadContext {
87
    const AVClass *class;
M
Michael Niedermayer 已提交
88 89 90
    int w, h;               ///< output dimensions, a value of 0 will result in the input size
    int x, y;               ///< offsets of the input area with respect to the padded area
    int in_w, in_h;         ///< width and height for the padded input video, which has to be aligned to the chroma values in order to avoid chroma issues
91
    int inlink_w, inlink_h;
92
    AVRational aspect;
M
Michael Niedermayer 已提交
93

94 95 96 97
    char *w_expr;           ///< width  expression string
    char *h_expr;           ///< height expression string
    char *x_expr;           ///< width  expression string
    char *y_expr;           ///< height expression string
98 99 100
    uint8_t rgba_color[4];  ///< color for the padding area
    FFDrawContext draw;
    FFDrawColor color;
101 102

    int eval_mode;          ///< expression evaluation mode
M
Michael Niedermayer 已提交
103 104 105 106 107
} PadContext;

static int config_input(AVFilterLink *inlink)
{
    AVFilterContext *ctx = inlink->dst;
108
    PadContext *s = ctx->priv;
109
    AVRational adjusted_aspect = s->aspect;
110
    int ret;
111 112
    double var_values[VARS_NB], res;
    char *expr;
M
Michael Niedermayer 已提交
113

114 115
    ff_draw_init(&s->draw, inlink->format, 0);
    ff_draw_color(&s->draw, &s->color, s->rgba_color);
M
Michael Niedermayer 已提交
116

117 118 119 120
    var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
    var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
    var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
    var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
121
    var_values[VAR_A]     = (double) inlink->w / inlink->h;
122
    var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
123
        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
124
    var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
125 126
    var_values[VAR_HSUB]  = 1 << s->draw.hsub_max;
    var_values[VAR_VSUB]  = 1 << s->draw.vsub_max;
127 128

    /* evaluate width and height */
129
    av_expr_parse_and_eval(&res, (expr = s->w_expr),
130 131
                           var_names, var_values,
                           NULL, NULL, NULL, NULL, NULL, 0, ctx);
132 133
    s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
    if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
134 135 136
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        goto eval_fail;
137
    s->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
138 139 140
    if (!s->h)
        var_values[VAR_OUT_H] = var_values[VAR_OH] = s->h = inlink->h;

141
    /* evaluate the width again, as it may depend on the evaluated output height */
142
    if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
143 144 145
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        goto eval_fail;
146
    s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
147 148
    if (!s->w)
        var_values[VAR_OUT_W] = var_values[VAR_OW] = s->w = inlink->w;
149

150 151 152 153 154 155 156 157 158
    if (adjusted_aspect.num && adjusted_aspect.den) {
        adjusted_aspect = av_div_q(adjusted_aspect, inlink->sample_aspect_ratio);
        if (s->h < av_rescale(s->w, adjusted_aspect.den, adjusted_aspect.num)) {
            s->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = av_rescale(s->w, adjusted_aspect.den, adjusted_aspect.num);
        } else {
            s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = av_rescale(s->h, adjusted_aspect.num, adjusted_aspect.den);
        }
    }

159
    /* evaluate x and y */
160
    av_expr_parse_and_eval(&res, (expr = s->x_expr),
161 162
                           var_names, var_values,
                           NULL, NULL, NULL, NULL, NULL, 0, ctx);
163 164
    s->x = var_values[VAR_X] = res;
    if ((ret = av_expr_parse_and_eval(&res, (expr = s->y_expr),
165 166 167
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        goto eval_fail;
168
    s->y = var_values[VAR_Y] = res;
169
    /* evaluate x again, as it may depend on the evaluated y value */
170
    if ((ret = av_expr_parse_and_eval(&res, (expr = s->x_expr),
171 172 173
                                      var_names, var_values,
                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
        goto eval_fail;
174
    s->x = var_values[VAR_X] = res;
175

176 177 178 179 180
    if (s->x < 0 || s->x + inlink->w > s->w)
        s->x = var_values[VAR_X] = (s->w - inlink->w) / 2;
    if (s->y < 0 || s->y + inlink->h > s->h)
        s->y = var_values[VAR_Y] = (s->h - inlink->h) / 2;

181 182
    s->w    = ff_draw_round_to_sub(&s->draw, 0, -1, s->w);
    s->h    = ff_draw_round_to_sub(&s->draw, 1, -1, s->h);
183
    /* sanity check params */
184 185
    if (s->w < inlink->w || s->h < inlink->h) {
        av_log(ctx, AV_LOG_ERROR, "Padded dimensions cannot be smaller than input dimensions.\n");
186 187 188
        return AVERROR(EINVAL);
    }

189 190 191 192
    s->x    = ff_draw_round_to_sub(&s->draw, 0, -1, s->x);
    s->y    = ff_draw_round_to_sub(&s->draw, 1, -1, s->y);
    s->in_w = ff_draw_round_to_sub(&s->draw, 0, -1, inlink->w);
    s->in_h = ff_draw_round_to_sub(&s->draw, 1, -1, inlink->h);
193 194
    s->inlink_w = inlink->w;
    s->inlink_h = inlink->h;
M
Michael Niedermayer 已提交
195

196
    av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d x:%d y:%d color:0x%02X%02X%02X%02X\n",
197
           inlink->w, inlink->h, s->w, s->h, s->x, s->y,
198
           s->rgba_color[0], s->rgba_color[1], s->rgba_color[2], s->rgba_color[3]);
M
Michael Niedermayer 已提交
199

200 201 202 203
    if (s->x <  0 || s->y <  0                      ||
        s->w <= 0 || s->h <= 0                      ||
        (unsigned)s->x + (unsigned)inlink->w > s->w ||
        (unsigned)s->y + (unsigned)inlink->h > s->h) {
M
Michael Niedermayer 已提交
204 205
        av_log(ctx, AV_LOG_ERROR,
               "Input area %d:%d:%d:%d not within the padded area 0:0:%d:%d or zero-sized\n",
206
               s->x, s->y, s->x + inlink->w, s->y + inlink->h, s->w, s->h);
207
        return AVERROR(EINVAL);
M
Michael Niedermayer 已提交
208 209 210
    }

    return 0;
211 212

eval_fail:
213
    av_log(ctx, AV_LOG_ERROR,
214 215 216
           "Error when evaluating the expression '%s'\n", expr);
    return ret;

M
Michael Niedermayer 已提交
217 218 219 220
}

static int config_output(AVFilterLink *outlink)
{
221
    PadContext *s = outlink->src->priv;
M
Michael Niedermayer 已提交
222

223 224
    outlink->w = s->w;
    outlink->h = s->h;
M
Michael Niedermayer 已提交
225 226 227
    return 0;
}

A
Anton Khirnov 已提交
228
static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)
M
Michael Niedermayer 已提交
229
{
230
    PadContext *s = inlink->dst->priv;
231
    AVFrame *frame;
232
    int plane;
M
Michael Niedermayer 已提交
233

234 235 236 237 238 239 240
    if (s->inlink_w <= 0)
        return NULL;

    frame = ff_get_video_buffer(inlink->dst->outputs[0],
                                w + (s->w - s->in_w),
                                h + (s->h - s->in_h) + (s->x > 0));

A
Anton Khirnov 已提交
241
    if (!frame)
242 243
        return NULL;

A
Anton Khirnov 已提交
244 245
    frame->width  = w;
    frame->height = h;
246

247
    for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) {
248 249 250 251
        int hsub = s->draw.hsub[plane];
        int vsub = s->draw.vsub[plane];
        frame->data[plane] += (s->x >> hsub) * s->draw.pixelstep[plane] +
                              (s->y >> vsub) * frame->linesize[plane];
M
Michael Niedermayer 已提交
252 253
    }

A
Anton Khirnov 已提交
254
    return frame;
M
Michael Niedermayer 已提交
255 256
}

A
Anton Khirnov 已提交
257 258
/* check whether each plane in this buffer can be padded without copying */
static int buffer_needs_copy(PadContext *s, AVFrame *frame, AVBufferRef *buf)
259
{
A
Anton Khirnov 已提交
260 261
    int planes[4] = { -1, -1, -1, -1}, *p = planes;
    int i, j;
262

A
Anton Khirnov 已提交
263 264 265 266 267
    /* get all planes in this buffer */
    for (i = 0; i < FF_ARRAY_ELEMS(planes) && frame->data[i]; i++) {
        if (av_frame_get_plane_buffer(frame, i) == buf)
            *p++ = i;
    }
268

A
Anton Khirnov 已提交
269 270 271
    /* for each plane in this buffer, check that it can be padded without
     * going over buffer bounds or other planes */
    for (i = 0; i < FF_ARRAY_ELEMS(planes) && planes[i] >= 0; i++) {
272 273
        int hsub = s->draw.hsub[planes[i]];
        int vsub = s->draw.vsub[planes[i]];
A
Anton Khirnov 已提交
274 275

        uint8_t *start = frame->data[planes[i]];
276
        uint8_t *end   = start + (frame->height >> vsub) *
A
Anton Khirnov 已提交
277 278 279 280
                                 frame->linesize[planes[i]];

        /* amount of free space needed before the start and after the end
         * of the plane */
281
        ptrdiff_t req_start = (s->x >> hsub) * s->draw.pixelstep[planes[i]] +
A
Anton Khirnov 已提交
282 283
                              (s->y >> vsub) * frame->linesize[planes[i]];
        ptrdiff_t req_end   = ((s->w - s->x - frame->width) >> hsub) *
284
                              s->draw.pixelstep[planes[i]] +
M
Michael Niedermayer 已提交
285
                              ((s->h - s->y - frame->height) >> vsub) * frame->linesize[planes[i]];
A
Anton Khirnov 已提交
286

287
        if (frame->linesize[planes[i]] < (s->w >> hsub) * s->draw.pixelstep[planes[i]])
A
Anton Khirnov 已提交
288 289 290 291 292
            return 1;
        if (start - buf->data < req_start ||
            (buf->data + buf->size) - end < req_end)
            return 1;

293
        for (j = 0; j < FF_ARRAY_ELEMS(planes) && planes[j] >= 0; j++) {
294
            int vsub1 = s->draw.vsub[planes[j]];
A
Anton Khirnov 已提交
295
            uint8_t *start1 = frame->data[planes[j]];
296
            uint8_t *end1   = start1 + (frame->height >> vsub1) *
A
Anton Khirnov 已提交
297 298 299 300
                                       frame->linesize[planes[j]];
            if (i == j)
                continue;

P
Paul B Mahol 已提交
301 302
            if (FFSIGN(start - end1) != FFSIGN(start - end1 - req_start) ||
                FFSIGN(end - start1) != FFSIGN(end - start1 + req_end))
A
Anton Khirnov 已提交
303 304 305
                return 1;
        }
    }
306

A
Anton Khirnov 已提交
307 308
    return 0;
}
309

A
Anton Khirnov 已提交
310 311 312
static int frame_needs_copy(PadContext *s, AVFrame *frame)
{
    int i;
313

A
Anton Khirnov 已提交
314
    if (!av_frame_is_writable(frame))
315
        return 1;
A
Anton Khirnov 已提交
316

317
    for (i = 0; i < 4 && frame->buf[i]; i++)
A
Anton Khirnov 已提交
318 319
        if (buffer_needs_copy(s, frame, frame->buf[i]))
            return 1;
320 321 322
    return 0;
}

A
Anton Khirnov 已提交
323
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
M
Michael Niedermayer 已提交
324
{
325
    PadContext *s = inlink->dst->priv;
326
    AVFilterLink *outlink = inlink->dst->outputs[0];
A
Anton Khirnov 已提交
327
    AVFrame *out;
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    int needs_copy;
    if(s->eval_mode == EVAL_MODE_FRAME && (
           in->width  != s->inlink_w
        || in->height != s->inlink_h
        || in->format != outlink->format
        || in->sample_aspect_ratio.den != outlink->sample_aspect_ratio.den || in->sample_aspect_ratio.num != outlink->sample_aspect_ratio.num)) {
        int ret;

        inlink->dst->inputs[0]->format = in->format;
        inlink->dst->inputs[0]->w      = in->width;
        inlink->dst->inputs[0]->h      = in->height;

        inlink->dst->inputs[0]->sample_aspect_ratio.den = in->sample_aspect_ratio.den;
        inlink->dst->inputs[0]->sample_aspect_ratio.num = in->sample_aspect_ratio.num;


        if ((ret = config_input(inlink)) < 0) {
            s->inlink_w = -1;
            return ret;
        }
        if ((ret = config_output(outlink)) < 0) {
            s->inlink_w = -1;
            return ret;
        }
    }

    needs_copy = frame_needs_copy(s, in);
355

356
    if (needs_copy) {
357
        av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
A
Anton Khirnov 已提交
358
        out = ff_get_video_buffer(inlink->dst->outputs[0],
359 360
                                  FFMAX(inlink->w, s->w),
                                  FFMAX(inlink->h, s->h));
361
        if (!out) {
A
Anton Khirnov 已提交
362
            av_frame_free(&in);
363
            return AVERROR(ENOMEM);
364
        }
365

A
Anton Khirnov 已提交
366 367 368
        av_frame_copy_props(out, in);
    } else {
        int i;
369

A
Anton Khirnov 已提交
370
        out = in;
371
        for (i = 0; i < 4 && out->data[i] && out->linesize[i]; i++) {
372 373 374
            int hsub = s->draw.hsub[i];
            int vsub = s->draw.vsub[i];
            out->data[i] -= (s->x >> hsub) * s->draw.pixelstep[i] +
375
                            (s->y >> vsub) * out->linesize[i];
A
Anton Khirnov 已提交
376 377
        }
    }
378

379
    /* top bar */
380
    if (s->y) {
381
        ff_fill_rectangle(&s->draw, &s->color,
382
                          out->data, out->linesize,
383
                          0, 0, s->w, s->y);
M
Michael Niedermayer 已提交
384 385
    }

386
    /* bottom bar */
387
    if (s->h > s->y + s->in_h) {
388
        ff_fill_rectangle(&s->draw, &s->color,
389
                          out->data, out->linesize,
390
                          0, s->y + s->in_h, s->w, s->h - s->y - s->in_h);
M
Michael Niedermayer 已提交
391 392 393
    }

    /* left border */
394 395
    ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
                      0, s->y, s->x, in->height);
396

397
    if (needs_copy) {
398
        ff_copy_rectangle2(&s->draw,
399
                          out->data, out->linesize, in->data, in->linesize,
400
                          s->x, s->y, 0, 0, in->width, in->height);
401 402
    }

M
Michael Niedermayer 已提交
403
    /* right border */
404
    ff_fill_rectangle(&s->draw, &s->color, out->data, out->linesize,
405
                      s->x + s->in_w, s->y, s->w - s->x - s->in_w,
A
Anton Khirnov 已提交
406 407
                      in->height);

408 409
    out->width  = s->w;
    out->height = s->h;
M
Michael Niedermayer 已提交
410

A
Anton Khirnov 已提交
411 412
    if (in != out)
        av_frame_free(&in);
413
    return ff_filter_frame(inlink->dst->outputs[0], out);
M
Michael Niedermayer 已提交
414 415
}

416
#define OFFSET(x) offsetof(PadContext, x)
417 418 419
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM

static const AVOption pad_options[] = {
P
Paul B Mahol 已提交
420 421 422 423 424 425
    { "width",  "set the pad area width expression",       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, FLAGS },
    { "w",      "set the pad area width expression",       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, 0, 0, FLAGS },
    { "height", "set the pad area height expression",      OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, FLAGS },
    { "h",      "set the pad area height expression",      OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, 0, 0, FLAGS },
    { "x",      "set the x offset expression for the input image position", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, FLAGS },
    { "y",      "set the y offset expression for the input image position", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, 0, 0, FLAGS },
426
    { "color",  "set the color of the padded area border", OFFSET(rgba_color), AV_OPT_TYPE_COLOR, {.str = "black"}, .flags = FLAGS },
427 428 429
    { "eval",   "specify when to evaluate expressions",    OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_INIT}, 0, EVAL_MODE_NB-1, FLAGS, "eval" },
         { "init",  "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT},  .flags = FLAGS, .unit = "eval" },
         { "frame", "eval expressions during initialization and per-frame", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" },
430
    { "aspect",  "pad to fit an aspect instead of a resolution", OFFSET(aspect), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, 0, DBL_MAX, FLAGS },
P
Paul B Mahol 已提交
431
    { NULL }
432 433
};

434
AVFILTER_DEFINE_CLASS(pad);
435

436 437 438 439 440 441
static const AVFilterPad avfilter_vf_pad_inputs[] = {
    {
        .name             = "default",
        .type             = AVMEDIA_TYPE_VIDEO,
        .config_props     = config_input,
        .get_video_buffer = get_video_buffer,
442
        .filter_frame     = filter_frame,
443 444 445 446 447 448 449 450 451 452 453 454 455
    },
    { NULL }
};

static const AVFilterPad avfilter_vf_pad_outputs[] = {
    {
        .name         = "default",
        .type         = AVMEDIA_TYPE_VIDEO,
        .config_props = config_output,
    },
    { NULL }
};

456
AVFilter ff_vf_pad = {
M
Michael Niedermayer 已提交
457
    .name          = "pad",
458
    .description   = NULL_IF_CONFIG_SMALL("Pad the input video."),
M
Michael Niedermayer 已提交
459
    .priv_size     = sizeof(PadContext),
460
    .priv_class    = &pad_class,
M
Michael Niedermayer 已提交
461
    .query_formats = query_formats,
P
Paul B Mahol 已提交
462 463
    .inputs        = avfilter_vf_pad_inputs,
    .outputs       = avfilter_vf_pad_outputs,
M
Michael Niedermayer 已提交
464
};