]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_overlay.c
Add a libwebp encoder
[ffmpeg] / libavfilter / vf_overlay.c
1 /*
2  * Copyright (c) 2010 Stefano Sabatini
3  * Copyright (c) 2010 Baptiste Coudurier
4  * Copyright (c) 2007 Bobby Bingham
5  *
6  * This file is part of Libav.
7  *
8  * Libav is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * Libav is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * overlay one video on top of another
26  */
27
28 #include "avfilter.h"
29 #include "formats.h"
30 #include "libavutil/common.h"
31 #include "libavutil/eval.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/opt.h"
38 #include "internal.h"
39 #include "video.h"
40
41 static const char *const var_names[] = {
42     "E",
43     "PHI",
44     "PI",
45     "main_w",    "W", ///< width  of the main    video
46     "main_h",    "H", ///< height of the main    video
47     "overlay_w", "w", ///< width  of the overlay video
48     "overlay_h", "h", ///< height of the overlay video
49     NULL
50 };
51
52 enum var_name {
53     VAR_E,
54     VAR_PHI,
55     VAR_PI,
56     VAR_MAIN_W,    VAR_MW,
57     VAR_MAIN_H,    VAR_MH,
58     VAR_OVERLAY_W, VAR_OW,
59     VAR_OVERLAY_H, VAR_OH,
60     VAR_VARS_NB
61 };
62
63 #define MAIN    0
64 #define OVERLAY 1
65
66 typedef struct {
67     const AVClass *class;
68     int x, y;                   ///< position of overlayed picture
69
70     int max_plane_step[4];      ///< steps per pixel for each plane
71     int hsub, vsub;             ///< chroma subsampling values
72
73     char *x_expr, *y_expr;
74
75     AVFrame *main;
76     AVFrame *over_prev, *over_next;
77 } OverlayContext;
78
79 static av_cold void uninit(AVFilterContext *ctx)
80 {
81     OverlayContext *s = ctx->priv;
82
83     av_frame_free(&s->main);
84     av_frame_free(&s->over_prev);
85     av_frame_free(&s->over_next);
86 }
87
88 static int query_formats(AVFilterContext *ctx)
89 {
90     const enum AVPixelFormat inout_pix_fmts[] = { AV_PIX_FMT_YUV420P,  AV_PIX_FMT_NONE };
91     const enum AVPixelFormat blend_pix_fmts[] = { AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
92     AVFilterFormats *inout_formats = ff_make_format_list(inout_pix_fmts);
93     AVFilterFormats *blend_formats = ff_make_format_list(blend_pix_fmts);
94
95     ff_formats_ref(inout_formats, &ctx->inputs [MAIN   ]->out_formats);
96     ff_formats_ref(blend_formats, &ctx->inputs [OVERLAY]->out_formats);
97     ff_formats_ref(inout_formats, &ctx->outputs[MAIN   ]->in_formats );
98
99     return 0;
100 }
101
102 static int config_input_main(AVFilterLink *inlink)
103 {
104     OverlayContext *s = inlink->dst->priv;
105     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
106
107     av_image_fill_max_pixsteps(s->max_plane_step, NULL, pix_desc);
108     s->hsub = pix_desc->log2_chroma_w;
109     s->vsub = pix_desc->log2_chroma_h;
110
111     return 0;
112 }
113
114 static int config_input_overlay(AVFilterLink *inlink)
115 {
116     AVFilterContext *ctx  = inlink->dst;
117     OverlayContext  *s = inlink->dst->priv;
118     char *expr;
119     double var_values[VAR_VARS_NB], res;
120     int ret;
121
122     /* Finish the configuration by evaluating the expressions
123        now when both inputs are configured. */
124     var_values[VAR_E  ] = M_E;
125     var_values[VAR_PHI] = M_PHI;
126     var_values[VAR_PI ] = M_PI;
127
128     var_values[VAR_MAIN_W   ] = var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
129     var_values[VAR_MAIN_H   ] = var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
130     var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
131     var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
132
133     if ((ret = av_expr_parse_and_eval(&res, (expr = s->x_expr), var_names, var_values,
134                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
135         goto fail;
136     s->x = res;
137     if ((ret = av_expr_parse_and_eval(&res, (expr = s->y_expr), var_names, var_values,
138                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)))
139         goto fail;
140     s->y = res;
141     /* x may depend on y */
142     if ((ret = av_expr_parse_and_eval(&res, (expr = s->x_expr), var_names, var_values,
143                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
144         goto fail;
145     s->x = res;
146
147     av_log(ctx, AV_LOG_VERBOSE,
148            "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
149            ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
150            av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
151            s->x, s->y,
152            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
153            av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
154
155     if (s->x < 0 || s->y < 0 ||
156         s->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
157         s->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
158         av_log(ctx, AV_LOG_ERROR,
159                "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
160                s->x, s->y,
161                (int)(s->x + var_values[VAR_OVERLAY_W]),
162                (int)(s->y + var_values[VAR_OVERLAY_H]),
163                (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
164         return AVERROR(EINVAL);
165     }
166     return 0;
167
168 fail:
169     av_log(NULL, AV_LOG_ERROR,
170            "Error when evaluating the expression '%s'\n", expr);
171     return ret;
172 }
173
174 static int config_output(AVFilterLink *outlink)
175 {
176     AVFilterContext *ctx = outlink->src;
177
178     outlink->w = ctx->inputs[MAIN]->w;
179     outlink->h = ctx->inputs[MAIN]->h;
180     outlink->time_base = ctx->inputs[MAIN]->time_base;
181
182     return 0;
183 }
184
185 static void blend_frame(AVFilterContext *ctx,
186                         AVFrame *dst, AVFrame *src,
187                         int x, int y)
188 {
189     OverlayContext *s = ctx->priv;
190     int i, j, k;
191     int width, height;
192     int overlay_end_y = y + src->height;
193     int end_y, start_y;
194
195     width = FFMIN(dst->width - x, src->width);
196     end_y = FFMIN(dst->height, overlay_end_y);
197     start_y = FFMAX(y, 0);
198     height = end_y - start_y;
199
200     if (dst->format == AV_PIX_FMT_BGR24 || dst->format == AV_PIX_FMT_RGB24) {
201         uint8_t *dp = dst->data[0] + x * 3 + start_y * dst->linesize[0];
202         uint8_t *sp = src->data[0];
203         int b = dst->format == AV_PIX_FMT_BGR24 ? 2 : 0;
204         int r = dst->format == AV_PIX_FMT_BGR24 ? 0 : 2;
205         if (y < 0)
206             sp += -y * src->linesize[0];
207         for (i = 0; i < height; i++) {
208             uint8_t *d = dp, *s = sp;
209             for (j = 0; j < width; j++) {
210                 d[r] = (d[r] * (0xff - s[3]) + s[0] * s[3] + 128) >> 8;
211                 d[1] = (d[1] * (0xff - s[3]) + s[1] * s[3] + 128) >> 8;
212                 d[b] = (d[b] * (0xff - s[3]) + s[2] * s[3] + 128) >> 8;
213                 d += 3;
214                 s += 4;
215             }
216             dp += dst->linesize[0];
217             sp += src->linesize[0];
218         }
219     } else {
220         for (i = 0; i < 3; i++) {
221             int hsub = i ? s->hsub : 0;
222             int vsub = i ? s->vsub : 0;
223             uint8_t *dp = dst->data[i] + (x >> hsub) +
224                 (start_y >> vsub) * dst->linesize[i];
225             uint8_t *sp = src->data[i];
226             uint8_t *ap = src->data[3];
227             int wp = FFALIGN(width, 1<<hsub) >> hsub;
228             int hp = FFALIGN(height, 1<<vsub) >> vsub;
229             if (y < 0) {
230                 sp += ((-y) >> vsub) * src->linesize[i];
231                 ap += -y * src->linesize[3];
232             }
233             for (j = 0; j < hp; j++) {
234                 uint8_t *d = dp, *s = sp, *a = ap;
235                 for (k = 0; k < wp; k++) {
236                     // average alpha for color components, improve quality
237                     int alpha_v, alpha_h, alpha;
238                     if (hsub && vsub && j+1 < hp && k+1 < wp) {
239                         alpha = (a[0] + a[src->linesize[3]] +
240                                  a[1] + a[src->linesize[3]+1]) >> 2;
241                     } else if (hsub || vsub) {
242                         alpha_h = hsub && k+1 < wp ?
243                             (a[0] + a[1]) >> 1 : a[0];
244                         alpha_v = vsub && j+1 < hp ?
245                             (a[0] + a[src->linesize[3]]) >> 1 : a[0];
246                         alpha = (alpha_v + alpha_h) >> 1;
247                     } else
248                         alpha = a[0];
249                     *d = (*d * (0xff - alpha) + *s++ * alpha + 128) >> 8;
250                     d++;
251                     a += 1 << hsub;
252                 }
253                 dp += dst->linesize[i];
254                 sp += src->linesize[i];
255                 ap += (1 << vsub) * src->linesize[3];
256             }
257         }
258     }
259 }
260
261 static int filter_frame_main(AVFilterLink *inlink, AVFrame *frame)
262 {
263     OverlayContext *s = inlink->dst->priv;
264
265     av_assert0(!s->main);
266     s->main         = frame;
267
268     return 0;
269 }
270
271 static int filter_frame_overlay(AVFilterLink *inlink, AVFrame *frame)
272 {
273     OverlayContext *s = inlink->dst->priv;
274
275     av_assert0(!s->over_next);
276     s->over_next    = frame;
277
278     return 0;
279 }
280
281 static int output_frame(AVFilterContext *ctx)
282 {
283     OverlayContext *s = ctx->priv;
284     AVFilterLink *outlink = ctx->outputs[0];
285     int ret = ff_filter_frame(outlink, s->main);
286     s->main = NULL;
287
288     return ret;
289 }
290
291 static int handle_overlay_eof(AVFilterContext *ctx)
292 {
293     OverlayContext *s = ctx->priv;
294     if (s->over_prev)
295         blend_frame(ctx, s->main, s->over_prev, s->x, s->y);
296     return output_frame(ctx);
297 }
298
299 static int request_frame(AVFilterLink *outlink)
300 {
301     AVFilterContext *ctx = outlink->src;
302     OverlayContext    *s = ctx->priv;
303     AVRational tb_main = ctx->inputs[MAIN]->time_base;
304     AVRational tb_over = ctx->inputs[OVERLAY]->time_base;
305     int ret = 0;
306
307     /* get a frame on the main input */
308     if (!s->main) {
309         ret = ff_request_frame(ctx->inputs[MAIN]);
310         if (ret < 0)
311             return ret;
312     }
313
314     /* get a new frame on the overlay input, on EOF
315      * reuse previous */
316     if (!s->over_next) {
317         ret = ff_request_frame(ctx->inputs[OVERLAY]);
318         if (ret == AVERROR_EOF)
319            return handle_overlay_eof(ctx);
320         else if (ret < 0)
321             return ret;
322     }
323
324     while (s->main->pts != AV_NOPTS_VALUE &&
325            s->over_next->pts != AV_NOPTS_VALUE &&
326            av_compare_ts(s->over_next->pts, tb_over, s->main->pts, tb_main) < 0) {
327         av_frame_free(&s->over_prev);
328         FFSWAP(AVFrame*, s->over_prev, s->over_next);
329
330         ret = ff_request_frame(ctx->inputs[OVERLAY]);
331         if (ret == AVERROR_EOF)
332             return handle_overlay_eof(ctx);
333         else if (ret < 0)
334             return ret;
335     }
336
337     if (s->main->pts == AV_NOPTS_VALUE ||
338         s->over_next->pts == AV_NOPTS_VALUE ||
339         !av_compare_ts(s->over_next->pts, tb_over, s->main->pts, tb_main)) {
340         blend_frame(ctx, s->main, s->over_next, s->x, s->y);
341         av_frame_free(&s->over_prev);
342         FFSWAP(AVFrame*, s->over_prev, s->over_next);
343     } else if (s->over_prev) {
344         blend_frame(ctx, s->main, s->over_prev, s->x, s->y);
345     }
346
347     return output_frame(ctx);
348 }
349
350 #define OFFSET(x) offsetof(OverlayContext, x)
351 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM
352 static const AVOption options[] = {
353     { "x", "Horizontal position of the left edge of the overlaid video on the "
354         "main video.",          OFFSET(x_expr), AV_OPT_TYPE_STRING, { .str = "0" }, .flags = FLAGS },
355     { "y", "Vertical position of the top edge of the overlaid video on the "
356         "main video.",          OFFSET(y_expr), AV_OPT_TYPE_STRING, { .str = "0" }, .flags = FLAGS },
357     { NULL },
358 };
359
360 static const AVClass overlay_class = {
361     .class_name = "overlay",
362     .item_name  = av_default_item_name,
363     .option     = options,
364     .version    = LIBAVUTIL_VERSION_INT,
365 };
366
367 static const AVFilterPad avfilter_vf_overlay_inputs[] = {
368     {
369         .name         = "main",
370         .type         = AVMEDIA_TYPE_VIDEO,
371         .config_props = config_input_main,
372         .filter_frame = filter_frame_main,
373         .needs_writable = 1,
374         .needs_fifo   = 1,
375     },
376     {
377         .name         = "overlay",
378         .type         = AVMEDIA_TYPE_VIDEO,
379         .config_props = config_input_overlay,
380         .filter_frame = filter_frame_overlay,
381         .needs_fifo   = 1,
382     },
383     { NULL }
384 };
385
386 static const AVFilterPad avfilter_vf_overlay_outputs[] = {
387     {
388         .name          = "default",
389         .type          = AVMEDIA_TYPE_VIDEO,
390         .config_props  = config_output,
391         .request_frame = request_frame,
392     },
393     { NULL }
394 };
395
396 AVFilter ff_vf_overlay = {
397     .name      = "overlay",
398     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
399
400     .uninit    = uninit,
401
402     .priv_size = sizeof(OverlayContext),
403     .priv_class = &overlay_class,
404
405     .query_formats = query_formats,
406
407     .inputs    = avfilter_vf_overlay_inputs,
408     .outputs   = avfilter_vf_overlay_outputs,
409 };