]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_pad.c
Merge commit '8c747d46f721cffa8ea51990805ad1d3a3a4fd0a'
[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
115     if (av_parse_color(pad->rgba_color, pad->color_str, -1, ctx) < 0)
116         return AVERROR(EINVAL);
117
118     return 0;
119 }
120
121 static int config_input(AVFilterLink *inlink)
122 {
123     AVFilterContext *ctx = inlink->dst;
124     PadContext *pad = ctx->priv;
125     int ret;
126     double var_values[VARS_NB], res;
127     char *expr;
128
129     ff_draw_init(&pad->draw, inlink->format, 0);
130     ff_draw_color(&pad->draw, &pad->color, pad->rgba_color);
131
132     var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
133     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
134     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
135     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
136     var_values[VAR_A]     = (double) inlink->w / inlink->h;
137     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
138         (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
139     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
140     var_values[VAR_HSUB]  = 1 << pad->draw.hsub_max;
141     var_values[VAR_VSUB]  = 1 << pad->draw.vsub_max;
142
143     /* evaluate width and height */
144     av_expr_parse_and_eval(&res, (expr = pad->w_expr),
145                            var_names, var_values,
146                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
147     pad->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
148     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->h_expr),
149                                       var_names, var_values,
150                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
151         goto eval_fail;
152     pad->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
153     /* evaluate the width again, as it may depend on the evaluated output height */
154     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->w_expr),
155                                       var_names, var_values,
156                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
157         goto eval_fail;
158     pad->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
159
160     /* evaluate x and y */
161     av_expr_parse_and_eval(&res, (expr = pad->x_expr),
162                            var_names, var_values,
163                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
164     pad->x = var_values[VAR_X] = res;
165     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->y_expr),
166                                       var_names, var_values,
167                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
168         goto eval_fail;
169     pad->y = var_values[VAR_Y] = res;
170     /* evaluate x again, as it may depend on the evaluated y value */
171     if ((ret = av_expr_parse_and_eval(&res, (expr = pad->x_expr),
172                                       var_names, var_values,
173                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
174         goto eval_fail;
175     pad->x = var_values[VAR_X] = res;
176
177     /* sanity check params */
178     if (pad->w < 0 || pad->h < 0 || pad->x < 0 || pad->y < 0) {
179         av_log(ctx, AV_LOG_ERROR, "Negative values are not acceptable.\n");
180         return AVERROR(EINVAL);
181     }
182
183     if (!pad->w)
184         pad->w = inlink->w;
185     if (!pad->h)
186         pad->h = inlink->h;
187
188     pad->w    = ff_draw_round_to_sub(&pad->draw, 0, -1, pad->w);
189     pad->h    = ff_draw_round_to_sub(&pad->draw, 1, -1, pad->h);
190     pad->x    = ff_draw_round_to_sub(&pad->draw, 0, -1, pad->x);
191     pad->y    = ff_draw_round_to_sub(&pad->draw, 1, -1, pad->y);
192     pad->in_w = ff_draw_round_to_sub(&pad->draw, 0, -1, inlink->w);
193     pad->in_h = ff_draw_round_to_sub(&pad->draw, 1, -1, inlink->h);
194
195     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",
196            inlink->w, inlink->h, pad->w, pad->h, pad->x, pad->y,
197            pad->rgba_color[0], pad->rgba_color[1], pad->rgba_color[2], pad->rgba_color[3]);
198
199     if (pad->x <  0 || pad->y <  0                      ||
200         pad->w <= 0 || pad->h <= 0                      ||
201         (unsigned)pad->x + (unsigned)inlink->w > pad->w ||
202         (unsigned)pad->y + (unsigned)inlink->h > pad->h) {
203         av_log(ctx, AV_LOG_ERROR,
204                "Input area %d:%d:%d:%d not within the padded area 0:0:%d:%d or zero-sized\n",
205                pad->x, pad->y, pad->x + inlink->w, pad->y + inlink->h, pad->w, pad->h);
206         return AVERROR(EINVAL);
207     }
208
209     return 0;
210
211 eval_fail:
212     av_log(NULL, AV_LOG_ERROR,
213            "Error when evaluating the expression '%s'\n", expr);
214     return ret;
215
216 }
217
218 static int config_output(AVFilterLink *outlink)
219 {
220     PadContext *pad = outlink->src->priv;
221
222     outlink->w = pad->w;
223     outlink->h = pad->h;
224     return 0;
225 }
226
227 static AVFrame *get_video_buffer(AVFilterLink *inlink, int w, int h)
228 {
229     PadContext *pad = inlink->dst->priv;
230
231     AVFrame *frame = ff_get_video_buffer(inlink->dst->outputs[0],
232                                          w + (pad->w - pad->in_w),
233                                          h + (pad->h - pad->in_h));
234     int plane;
235
236     if (!frame)
237         return NULL;
238
239     frame->width  = w;
240     frame->height = h;
241
242     for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
243         int hsub = pad->draw.hsub[plane];
244         int vsub = pad->draw.vsub[plane];
245         frame->data[plane] += (pad->x >> hsub) * pad->draw.pixelstep[plane] +
246                               (pad->y >> vsub) * frame->linesize[plane];
247     }
248
249     return frame;
250 }
251
252 /* check whether each plane in this buffer can be padded without copying */
253 static int buffer_needs_copy(PadContext *s, AVFrame *frame, AVBufferRef *buf)
254 {
255     int planes[4] = { -1, -1, -1, -1}, *p = planes;
256     int i, j;
257
258     /* get all planes in this buffer */
259     for (i = 0; i < FF_ARRAY_ELEMS(planes) && frame->data[i]; i++) {
260         if (av_frame_get_plane_buffer(frame, i) == buf)
261             *p++ = i;
262     }
263
264     /* for each plane in this buffer, check that it can be padded without
265      * going over buffer bounds or other planes */
266     for (i = 0; i < FF_ARRAY_ELEMS(planes) && planes[i] >= 0; i++) {
267         int hsub = s->draw.hsub[planes[i]];
268         int vsub = s->draw.vsub[planes[i]];
269
270         uint8_t *start = frame->data[planes[i]];
271         uint8_t *end   = start + (frame->height >> vsub) *
272                                  frame->linesize[planes[i]];
273
274         /* amount of free space needed before the start and after the end
275          * of the plane */
276         ptrdiff_t req_start = (s->x >> hsub) * s->draw.pixelstep[planes[i]] +
277                               (s->y >> vsub) * frame->linesize[planes[i]];
278         ptrdiff_t req_end   = ((s->w - s->x - frame->width) >> hsub) *
279                               s->draw.pixelstep[planes[i]] +
280                               (s->y >> vsub) * frame->linesize[planes[i]];
281
282         if (frame->linesize[planes[i]] < (s->w >> hsub) * s->draw.pixelstep[planes[i]])
283             return 1;
284         if (start - buf->data < req_start ||
285             (buf->data + buf->size) - end < req_end)
286             return 1;
287
288 #define SIGN(x) ((x) > 0 ? 1 : -1)
289         for (j = 0; j < FF_ARRAY_ELEMS(planes) && planes[j] >= 0; j++) {
290             int vsub1 = s->draw.vsub[planes[j]];
291             uint8_t *start1 = frame->data[planes[j]];
292             uint8_t *end1   = start1 + (frame->height >> vsub1) *
293                                        frame->linesize[planes[j]];
294             if (i == j)
295                 continue;
296
297             if (SIGN(start - end1) != SIGN(start - end1 - req_start) ||
298                 SIGN(end - start1) != SIGN(end - start1 + req_end))
299                 return 1;
300         }
301     }
302
303     return 0;
304 }
305
306 static int frame_needs_copy(PadContext *s, AVFrame *frame)
307 {
308     int i;
309
310     if (!av_frame_is_writable(frame))
311         return 1;
312
313     for (i = 0; i < 4 && frame->buf[i]; i++)
314         if (buffer_needs_copy(s, frame, frame->buf[i]))
315             return 1;
316     return 0;
317 }
318
319 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
320 {
321     PadContext *pad = inlink->dst->priv;
322     AVFrame *out;
323     int needs_copy = frame_needs_copy(pad, in);
324
325     if (needs_copy) {
326         av_log(inlink->dst, AV_LOG_DEBUG, "Direct padding impossible allocating new frame\n");
327         out = ff_get_video_buffer(inlink->dst->outputs[0],
328                                   FFMAX(inlink->w, pad->w),
329                                   FFMAX(inlink->h, pad->h));
330         if (!out) {
331             av_frame_free(&in);
332             return AVERROR(ENOMEM);
333         }
334
335         av_frame_copy_props(out, in);
336     } else {
337         int i;
338
339         out = in;
340         for (i = 0; i < 4 && out->data[i]; i++) {
341             int hsub = pad->draw.hsub[i];
342             int vsub = pad->draw.vsub[i];
343             out->data[i] -= (pad->x >> hsub) * pad->draw.pixelstep[i] +
344                             (pad->y >> vsub) * out->linesize[i];
345         }
346     }
347
348     /* top bar */
349     if (pad->y) {
350         ff_fill_rectangle(&pad->draw, &pad->color,
351                           out->data, out->linesize,
352                           0, 0, pad->w, pad->y);
353     }
354
355     /* bottom bar */
356     if (pad->h > pad->y + pad->in_h) {
357         ff_fill_rectangle(&pad->draw, &pad->color,
358                           out->data, out->linesize,
359                           0, pad->y + pad->in_h, pad->w, pad->h - pad->y - pad->in_h);
360     }
361
362     /* left border */
363     ff_fill_rectangle(&pad->draw, &pad->color, out->data, out->linesize,
364                       0, pad->y, pad->x, in->height);
365
366     if (needs_copy) {
367         ff_copy_rectangle2(&pad->draw,
368                           out->data, out->linesize, in->data, in->linesize,
369                           pad->x, pad->y, 0, 0, in->width, in->height);
370     }
371
372     /* right border */
373     ff_fill_rectangle(&pad->draw, &pad->color, out->data, out->linesize,
374                       pad->x + pad->in_w, pad->y, pad->w - pad->x - pad->in_w,
375                       in->height);
376
377     out->width  = pad->w;
378     out->height = pad->h;
379
380     if (in != out)
381         av_frame_free(&in);
382     return ff_filter_frame(inlink->dst->outputs[0], out);
383 }
384
385 static const AVFilterPad avfilter_vf_pad_inputs[] = {
386     {
387         .name             = "default",
388         .type             = AVMEDIA_TYPE_VIDEO,
389         .config_props     = config_input,
390         .get_video_buffer = get_video_buffer,
391         .filter_frame     = filter_frame,
392     },
393     { NULL }
394 };
395
396 static const AVFilterPad avfilter_vf_pad_outputs[] = {
397     {
398         .name         = "default",
399         .type         = AVMEDIA_TYPE_VIDEO,
400         .config_props = config_output,
401     },
402     { NULL }
403 };
404
405 static const char *const shorthand[] = { "width", "height", "x", "y", "color", NULL };
406
407 AVFilter avfilter_vf_pad = {
408     .name          = "pad",
409     .description   = NULL_IF_CONFIG_SMALL("Pad input image to width:height[:x:y[:color]] (default x and y: 0, default color: black)."),
410
411     .priv_size     = sizeof(PadContext),
412     .init          = init,
413     .query_formats = query_formats,
414
415     .inputs    = avfilter_vf_pad_inputs,
416
417     .outputs   = avfilter_vf_pad_outputs,
418     .priv_class = &pad_class,
419     .shorthand = shorthand,
420 };