]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_pad.c
Merge commit '79dad2a932534d1155079f937649e099f9e5cc27'
[ffmpeg] / libavfilter / vf_pad.c
1 /*
2  * Copyright (c) 2008 vmrsss
3  * Copyright (c) 2009 Stefano Sabatini
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * video padding filter
25  */
26
27 #include "avfilter.h"
28 #include "formats.h"
29 #include "internal.h"
30 #include "video.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/common.h"
33 #include "libavutil/eval.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/colorspace.h"
36 #include "libavutil/avassert.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/mathematics.h"
41 #include "drawutils.h"
42
43 static const char *const var_names[] = {
44     "in_w",   "iw",
45     "in_h",   "ih",
46     "out_w",  "ow",
47     "out_h",  "oh",
48     "x",
49     "y",
50     "a",
51     "sar",
52     "dar",
53     "hsub",
54     "vsub",
55     NULL
56 };
57
58 enum var_name {
59     VAR_IN_W,   VAR_IW,
60     VAR_IN_H,   VAR_IH,
61     VAR_OUT_W,  VAR_OW,
62     VAR_OUT_H,  VAR_OH,
63     VAR_X,
64     VAR_Y,
65     VAR_A,
66     VAR_SAR,
67     VAR_DAR,
68     VAR_HSUB,
69     VAR_VSUB,
70     VARS_NB
71 };
72
73 static int query_formats(AVFilterContext *ctx)
74 {
75     ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
76     return 0;
77 }
78
79 typedef struct {
80     const AVClass *class;
81     int w, h;               ///< output dimensions, a value of 0 will result in the input size
82     int x, y;               ///< offsets of the input area with respect to the padded area
83     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
84
85     char *w_expr;       ///< width  expression string
86     char *h_expr;       ///< height expression string
87     char *x_expr;       ///< width  expression string
88     char *y_expr;       ///< height expression string
89     char *color_str;
90     uint8_t rgba_color[4];  ///< color for the padding area
91     FFDrawContext draw;
92     FFDrawColor color;
93 } PadContext;
94
95 #define OFFSET(x) offsetof(PadContext, x)
96 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
97
98 static const AVOption pad_options[] = {
99     { "width",  "set the pad area width expression",       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
100     { "w",      "set the pad area width expression",       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, CHAR_MIN, CHAR_MAX, FLAGS },
101     { "height", "set the pad area height expression",      OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
102     { "h",      "set the pad area height expression",      OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, CHAR_MIN, CHAR_MAX, FLAGS },
103     { "x",      "set the x offset expression for the input image position", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
104     { "y",      "set the y offset expression for the input image position", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
105     { "color",  "set the color of the padded area border", OFFSET(color_str), AV_OPT_TYPE_STRING, {.str = "black"}, .flags = FLAGS },
106     {NULL}
107 };
108
109 AVFILTER_DEFINE_CLASS(pad);
110
111 static av_cold int init(AVFilterContext *ctx, const char *args)
112 {
113     PadContext *pad = ctx->priv;
114     static const char *shorthand[] = { "width", "height", "x", "y", "color", NULL };
115     int ret;
116
117     pad->class = &pad_class;
118     av_opt_set_defaults(pad);
119
120     if ((ret = av_opt_set_from_string(pad, args, shorthand, "=", ":")) < 0)
121         return ret;
122
123     if (av_parse_color(pad->rgba_color, pad->color_str, -1, ctx) < 0)
124         return AVERROR(EINVAL);
125
126     return 0;
127 }
128
129 static av_cold void uninit(AVFilterContext *ctx)
130 {
131     PadContext *pad = ctx->priv;
132     av_opt_free(pad);
133 }
134
135 static int config_input(AVFilterLink *inlink)
136 {
137     AVFilterContext *ctx = inlink->dst;
138     PadContext *pad = ctx->priv;
139     int ret;
140     double var_values[VARS_NB], res;
141     char *expr;
142
143     ff_draw_init(&pad->draw, inlink->format, 0);
144     ff_draw_color(&pad->draw, &pad->color, pad->rgba_color);
145
146     var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
147     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
148     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
149     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
150     var_values[VAR_A]     = (double) inlink->w / inlink->h;
151     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
152         (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
153     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
154     var_values[VAR_HSUB]  = 1 << pad->draw.hsub_max;
155     var_values[VAR_VSUB]  = 1 << pad->draw.vsub_max;
156
157     /* evaluate width and height */
158     av_expr_parse_and_eval(&res, (expr = pad->w_expr),
159                            var_names, var_values,
160                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
161     pad->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
162     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->h_expr),
163                                       var_names, var_values,
164                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
165         goto eval_fail;
166     pad->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
167     /* evaluate the width again, as it may depend on the evaluated output height */
168     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->w_expr),
169                                       var_names, var_values,
170                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
171         goto eval_fail;
172     pad->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
173
174     /* evaluate x and y */
175     av_expr_parse_and_eval(&res, (expr = pad->x_expr),
176                            var_names, var_values,
177                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
178     pad->x = var_values[VAR_X] = res;
179     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->y_expr),
180                                       var_names, var_values,
181                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
182         goto eval_fail;
183     pad->y = var_values[VAR_Y] = res;
184     /* evaluate x again, as it may depend on the evaluated y value */
185     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->x_expr),
186                                       var_names, var_values,
187                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
188         goto eval_fail;
189     pad->x = var_values[VAR_X] = res;
190
191     /* sanity check params */
192     if (pad->w < 0 || pad->h < 0 || pad->x < 0 || pad->y < 0) {
193         av_log(ctx, AV_LOG_ERROR, "Negative values are not acceptable.\n");
194         return AVERROR(EINVAL);
195     }
196
197     if (!pad->w)
198         pad->w = inlink->w;
199     if (!pad->h)
200         pad->h = inlink->h;
201
202     pad->w    = ff_draw_round_to_sub(&pad->draw, 0, -1, pad->w);
203     pad->h    = ff_draw_round_to_sub(&pad->draw, 1, -1, pad->h);
204     pad->x    = ff_draw_round_to_sub(&pad->draw, 0, -1, pad->x);
205     pad->y    = ff_draw_round_to_sub(&pad->draw, 1, -1, pad->y);
206     pad->in_w = ff_draw_round_to_sub(&pad->draw, 0, -1, inlink->w);
207     pad->in_h = ff_draw_round_to_sub(&pad->draw, 1, -1, inlink->h);
208
209     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",
210            inlink->w, inlink->h, pad->w, pad->h, pad->x, pad->y,
211            pad->rgba_color[0], pad->rgba_color[1], pad->rgba_color[2], pad->rgba_color[3]);
212
213     if (pad->x <  0 || pad->y <  0                      ||
214         pad->w <= 0 || pad->h <= 0                      ||
215         (unsigned)pad->x + (unsigned)inlink->w > pad->w ||
216         (unsigned)pad->y + (unsigned)inlink->h > pad->h) {
217         av_log(ctx, AV_LOG_ERROR,
218                "Input area %d:%d:%d:%d not within the padded area 0:0:%d:%d or zero-sized\n",
219                pad->x, pad->y, pad->x + inlink->w, pad->y + inlink->h, pad->w, pad->h);
220         return AVERROR(EINVAL);
221     }
222
223     return 0;
224
225 eval_fail:
226     av_log(NULL, AV_LOG_ERROR,
227            "Error when evaluating the expression '%s'\n", expr);
228     return ret;
229
230 }
231
232 static int config_output(AVFilterLink *outlink)
233 {
234     PadContext *pad = outlink->src->priv;
235
236     outlink->w = pad->w;
237     outlink->h = pad->h;
238     return 0;
239 }
240
241 static AVFilterBufferRef *get_video_buffer(AVFilterLink *inlink, int perms, int w, int h)
242 {
243     PadContext *pad = inlink->dst->priv;
244     int align = (perms&AV_PERM_ALIGN) ? AVFILTER_ALIGN : 1;
245
246     AVFilterBufferRef *picref = ff_get_video_buffer(inlink->dst->outputs[0], perms,
247                                                     w + (pad->w - pad->in_w) + 4*align,
248                                                     h + (pad->h - pad->in_h));
249     int plane;
250
251     if (!picref)
252         return NULL;
253
254     picref->video->w = w;
255     picref->video->h = h;
256
257     for (plane = 0; plane < 4 && picref->data[plane]; plane++)
258         picref->data[plane] += FFALIGN(pad->x >> pad->draw.hsub[plane], align) * pad->draw.pixelstep[plane] +
259                                       (pad->y >> pad->draw.vsub[plane])        * picref->linesize[plane];
260
261     return picref;
262 }
263
264 static int does_clip(PadContext *pad, AVFilterBufferRef *outpicref, int plane, int hsub, int vsub, int x, int y)
265 {
266     int64_t x_in_buf, y_in_buf;
267
268     x_in_buf =  outpicref->data[plane] - outpicref->buf->data[plane]
269              +  (x >> hsub) * pad->draw.pixelstep[plane]
270              +  (y >> vsub) * outpicref->linesize[plane];
271
272     if(x_in_buf < 0 || x_in_buf % pad->draw.pixelstep[plane])
273         return 1;
274     x_in_buf /= pad->draw.pixelstep[plane];
275
276     av_assert0(outpicref->buf->linesize[plane]>0); //while reference can use negative linesize the main buffer should not
277
278     y_in_buf = x_in_buf / outpicref->buf->linesize[plane];
279     x_in_buf %= outpicref->buf->linesize[plane];
280
281     if(   y_in_buf<<vsub >= outpicref->buf->h
282        || x_in_buf<<hsub >= outpicref->buf->w)
283         return 1;
284     return 0;
285 }
286
287 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
288 {
289     PadContext *pad = inlink->dst->priv;
290     AVFilterBufferRef *out = avfilter_ref_buffer(in, ~0);
291     int plane, needs_copy;
292
293     if (!out) {
294         avfilter_unref_bufferp(&in);
295         return AVERROR(ENOMEM);
296     }
297
298     for (plane = 0; plane < 4 && out->data[plane] && pad->draw.pixelstep[plane]; plane++) {
299         int hsub = pad->draw.hsub[plane];
300         int vsub = pad->draw.vsub[plane];
301
302         av_assert0(out->buf->w > 0 && out->buf->h > 0);
303
304         if (out->format != out->buf->format) //unsupported currently
305             break;
306
307         out->data[plane] -= (pad->x  >> hsub) * pad->draw.pixelstep[plane] +
308                             (pad->y  >> vsub) * out->linesize[plane];
309
310         if (does_clip(pad, out, plane, hsub, vsub, 0,                   0) ||
311             does_clip(pad, out, plane, hsub, vsub, 0,          pad->h - 1) ||
312             does_clip(pad, out, plane, hsub, vsub, pad->w - 1,          0) ||
313             does_clip(pad, out, plane, hsub, vsub, pad->w - 1, pad->h - 1))
314             break;
315     }
316     needs_copy = plane < 4 && out->data[plane] || !(out->perms & AV_PERM_WRITE);
317     if (needs_copy) {
318         av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
319         avfilter_unref_buffer(out);
320         out = ff_get_video_buffer(inlink->dst->outputs[0], AV_PERM_WRITE | AV_PERM_NEG_LINESIZES,
321                                   FFMAX(inlink->w, pad->w),
322                                   FFMAX(inlink->h, pad->h));
323         if (!out) {
324             avfilter_unref_bufferp(&in);
325             return AVERROR(ENOMEM);
326         }
327
328         avfilter_copy_buffer_ref_props(out, in);
329     }
330
331     out->video->w = pad->w;
332     out->video->h = pad->h;
333
334     /* top bar */
335     if (pad->y) {
336         ff_fill_rectangle(&pad->draw, &pad->color,
337                           out->data, out->linesize,
338                           0, 0, pad->w, pad->y);
339     }
340
341     /* bottom bar */
342     if (pad->h > pad->y + pad->in_h) {
343         ff_fill_rectangle(&pad->draw, &pad->color,
344                           out->data, out->linesize,
345                           0, pad->y + pad->in_h, pad->w, pad->h - pad->y - pad->in_h);
346     }
347
348     /* left border */
349     ff_fill_rectangle(&pad->draw, &pad->color, out->data, out->linesize,
350                       0, pad->y, pad->x, in->video->h);
351
352     if (needs_copy) {
353         ff_copy_rectangle2(&pad->draw,
354                           out->data, out->linesize, in->data, in->linesize,
355                           pad->x, pad->y, 0, 0, in->video->w, in->video->h);
356     }
357
358     /* right border */
359     ff_fill_rectangle(&pad->draw, &pad->color, out->data, out->linesize,
360                       pad->x + pad->in_w, pad->y, pad->w - pad->x - pad->in_w,
361                       in->video->h);
362
363     avfilter_unref_bufferp(&in);
364     return ff_filter_frame(inlink->dst->outputs[0], out);
365 }
366
367 static const AVFilterPad avfilter_vf_pad_inputs[] = {
368     {
369         .name             = "default",
370         .type             = AVMEDIA_TYPE_VIDEO,
371         .config_props     = config_input,
372         .get_video_buffer = get_video_buffer,
373         .filter_frame     = filter_frame,
374     },
375     { NULL }
376 };
377
378 static const AVFilterPad avfilter_vf_pad_outputs[] = {
379     {
380         .name         = "default",
381         .type         = AVMEDIA_TYPE_VIDEO,
382         .config_props = config_output,
383     },
384     { NULL }
385 };
386
387 AVFilter avfilter_vf_pad = {
388     .name          = "pad",
389     .description   = NULL_IF_CONFIG_SMALL("Pad input image to width:height[:x:y[:color]] (default x and y: 0, default color: black)."),
390
391     .priv_size     = sizeof(PadContext),
392     .init          = init,
393     .uninit        = uninit,
394     .query_formats = query_formats,
395
396     .inputs    = avfilter_vf_pad_inputs,
397
398     .outputs   = avfilter_vf_pad_outputs,
399     .priv_class = &pad_class,
400 };