]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_overlay.c
6dd9be4975e1e1a52d155182393ad3ad04ed0be4
[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/pixdesc.h"
34 #include "libavutil/imgutils.h"
35 #include "libavutil/mathematics.h"
36 #include "internal.h"
37 #include "video.h"
38
39 static const char *const var_names[] = {
40     "E",
41     "PHI",
42     "PI",
43     "main_w",    "W", ///< width  of the main    video
44     "main_h",    "H", ///< height of the main    video
45     "overlay_w", "w", ///< width  of the overlay video
46     "overlay_h", "h", ///< height of the overlay video
47     NULL
48 };
49
50 enum var_name {
51     VAR_E,
52     VAR_PHI,
53     VAR_PI,
54     VAR_MAIN_W,    VAR_MW,
55     VAR_MAIN_H,    VAR_MH,
56     VAR_OVERLAY_W, VAR_OW,
57     VAR_OVERLAY_H, VAR_OH,
58     VAR_VARS_NB
59 };
60
61 #define MAIN    0
62 #define OVERLAY 1
63
64 typedef struct {
65     int x, y;                   ///< position of overlayed picture
66
67     AVFilterBufferRef *overpicref;
68
69     int max_plane_step[4];      ///< steps per pixel for each plane
70     int hsub, vsub;             ///< chroma subsampling values
71
72     char x_expr[256], y_expr[256];
73 } OverlayContext;
74
75 static av_cold int init(AVFilterContext *ctx, const char *args)
76 {
77     OverlayContext *over = ctx->priv;
78
79     av_strlcpy(over->x_expr, "0", sizeof(over->x_expr));
80     av_strlcpy(over->y_expr, "0", sizeof(over->y_expr));
81
82     if (args)
83         sscanf(args, "%255[^:]:%255[^:]", over->x_expr, over->y_expr);
84
85     return 0;
86 }
87
88 static av_cold void uninit(AVFilterContext *ctx)
89 {
90     OverlayContext *over = ctx->priv;
91
92     avfilter_unref_bufferp(&over->overpicref);
93 }
94
95 static int query_formats(AVFilterContext *ctx)
96 {
97     const enum PixelFormat inout_pix_fmts[] = { PIX_FMT_YUV420P,  PIX_FMT_NONE };
98     const enum PixelFormat blend_pix_fmts[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
99     AVFilterFormats *inout_formats = ff_make_format_list(inout_pix_fmts);
100     AVFilterFormats *blend_formats = ff_make_format_list(blend_pix_fmts);
101
102     ff_formats_ref(inout_formats, &ctx->inputs [MAIN   ]->out_formats);
103     ff_formats_ref(blend_formats, &ctx->inputs [OVERLAY]->out_formats);
104     ff_formats_ref(inout_formats, &ctx->outputs[MAIN   ]->in_formats );
105
106     return 0;
107 }
108
109 static int config_input_main(AVFilterLink *inlink)
110 {
111     OverlayContext *over = inlink->dst->priv;
112     const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
113
114     av_image_fill_max_pixsteps(over->max_plane_step, NULL, pix_desc);
115     over->hsub = pix_desc->log2_chroma_w;
116     over->vsub = pix_desc->log2_chroma_h;
117
118     return 0;
119 }
120
121 static int config_input_overlay(AVFilterLink *inlink)
122 {
123     AVFilterContext *ctx  = inlink->dst;
124     OverlayContext  *over = inlink->dst->priv;
125     char *expr;
126     double var_values[VAR_VARS_NB], res;
127     int ret;
128
129     /* Finish the configuration by evaluating the expressions
130        now when both inputs are configured. */
131     var_values[VAR_E  ] = M_E;
132     var_values[VAR_PHI] = M_PHI;
133     var_values[VAR_PI ] = M_PI;
134
135     var_values[VAR_MAIN_W   ] = var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
136     var_values[VAR_MAIN_H   ] = var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
137     var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
138     var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
139
140     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
141                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
142         goto fail;
143     over->x = res;
144     if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
145                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)))
146         goto fail;
147     over->y = res;
148     /* x may depend on y */
149     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
150                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
151         goto fail;
152     over->x = res;
153
154     av_log(ctx, AV_LOG_VERBOSE,
155            "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
156            ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
157            av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
158            over->x, over->y,
159            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
160            av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
161
162     if (over->x < 0 || over->y < 0 ||
163         over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
164         over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
165         av_log(ctx, AV_LOG_ERROR,
166                "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
167                over->x, over->y,
168                (int)(over->x + var_values[VAR_OVERLAY_W]),
169                (int)(over->y + var_values[VAR_OVERLAY_H]),
170                (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
171         return AVERROR(EINVAL);
172     }
173     return 0;
174
175 fail:
176     av_log(NULL, AV_LOG_ERROR,
177            "Error when evaluating the expression '%s'\n", expr);
178     return ret;
179 }
180
181 static int config_output(AVFilterLink *outlink)
182 {
183     AVFilterContext *ctx = outlink->src;
184     int exact;
185     // common timebase computation:
186     AVRational tb1 = ctx->inputs[MAIN   ]->time_base;
187     AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
188     AVRational *tb = &ctx->outputs[0]->time_base;
189     exact = av_reduce(&tb->num, &tb->den,
190                       av_gcd((int64_t)tb1.num * tb2.den,
191                              (int64_t)tb2.num * tb1.den),
192                       (int64_t)tb1.den * tb2.den, INT_MAX);
193     av_log(ctx, AV_LOG_VERBOSE,
194            "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
195            tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
196     if (!exact)
197         av_log(ctx, AV_LOG_WARNING,
198                "Timestamp conversion inexact, timestamp information loss may occurr\n");
199
200     outlink->w = ctx->inputs[MAIN]->w;
201     outlink->h = ctx->inputs[MAIN]->h;
202
203     return 0;
204 }
205
206 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
207 {
208     return ff_get_video_buffer(link->dst->outputs[0], perms, w, h);
209 }
210
211 static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
212 {
213     AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
214     AVFilterContext *ctx = inlink->dst;
215     OverlayContext *over = ctx->priv;
216
217     if (!outpicref)
218         return AVERROR(ENOMEM);
219
220     outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
221                                   ctx->outputs[0]->time_base);
222
223     if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
224         AVFilterBufferRef *old = over->overpicref;
225         over->overpicref = NULL;
226         ff_request_frame(ctx->inputs[OVERLAY]);
227         if (over->overpicref) {
228             if (old)
229                 avfilter_unref_buffer(old);
230         } else
231             over->overpicref = old;
232     }
233
234     return ff_start_frame(inlink->dst->outputs[0], outpicref);
235 }
236
237 static int start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
238 {
239     AVFilterContext *ctx = inlink->dst;
240     OverlayContext *over = ctx->priv;
241
242     inlink->cur_buf  = NULL;
243     avfilter_unref_bufferp(&over->overpicref);
244     over->overpicref = inpicref;
245     over->overpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
246                                          ctx->outputs[0]->time_base);
247     return 0;
248 }
249
250 static void blend_slice(AVFilterContext *ctx,
251                         AVFilterBufferRef *dst, AVFilterBufferRef *src,
252                         int x, int y, int w, int h,
253                         int slice_y, int slice_w, int slice_h)
254 {
255     OverlayContext *over = ctx->priv;
256     int i, j, k;
257     int width, height;
258     int overlay_end_y = y+h;
259     int slice_end_y = slice_y+slice_h;
260     int end_y, start_y;
261
262     width = FFMIN(slice_w - x, w);
263     end_y = FFMIN(slice_end_y, overlay_end_y);
264     start_y = FFMAX(y, slice_y);
265     height = end_y - start_y;
266
267     if (dst->format == PIX_FMT_BGR24 || dst->format == PIX_FMT_RGB24) {
268         uint8_t *dp = dst->data[0] + x * 3 + start_y * dst->linesize[0];
269         uint8_t *sp = src->data[0];
270         int b = dst->format == PIX_FMT_BGR24 ? 2 : 0;
271         int r = dst->format == PIX_FMT_BGR24 ? 0 : 2;
272         if (slice_y > y)
273             sp += (slice_y - y) * src->linesize[0];
274         for (i = 0; i < height; i++) {
275             uint8_t *d = dp, *s = sp;
276             for (j = 0; j < width; j++) {
277                 d[r] = (d[r] * (0xff - s[3]) + s[0] * s[3] + 128) >> 8;
278                 d[1] = (d[1] * (0xff - s[3]) + s[1] * s[3] + 128) >> 8;
279                 d[b] = (d[b] * (0xff - s[3]) + s[2] * s[3] + 128) >> 8;
280                 d += 3;
281                 s += 4;
282             }
283             dp += dst->linesize[0];
284             sp += src->linesize[0];
285         }
286     } else {
287         for (i = 0; i < 3; i++) {
288             int hsub = i ? over->hsub : 0;
289             int vsub = i ? over->vsub : 0;
290             uint8_t *dp = dst->data[i] + (x >> hsub) +
291                 (start_y >> vsub) * dst->linesize[i];
292             uint8_t *sp = src->data[i];
293             uint8_t *ap = src->data[3];
294             int wp = FFALIGN(width, 1<<hsub) >> hsub;
295             int hp = FFALIGN(height, 1<<vsub) >> vsub;
296             if (slice_y > y) {
297                 sp += ((slice_y - y) >> vsub) * src->linesize[i];
298                 ap += (slice_y - y) * src->linesize[3];
299             }
300             for (j = 0; j < hp; j++) {
301                 uint8_t *d = dp, *s = sp, *a = ap;
302                 for (k = 0; k < wp; k++) {
303                     // average alpha for color components, improve quality
304                     int alpha_v, alpha_h, alpha;
305                     if (hsub && vsub && j+1 < hp && k+1 < wp) {
306                         alpha = (a[0] + a[src->linesize[3]] +
307                                  a[1] + a[src->linesize[3]+1]) >> 2;
308                     } else if (hsub || vsub) {
309                         alpha_h = hsub && k+1 < wp ?
310                             (a[0] + a[1]) >> 1 : a[0];
311                         alpha_v = vsub && j+1 < hp ?
312                             (a[0] + a[src->linesize[3]]) >> 1 : a[0];
313                         alpha = (alpha_v + alpha_h) >> 1;
314                     } else
315                         alpha = a[0];
316                     *d = (*d * (0xff - alpha) + *s++ * alpha + 128) >> 8;
317                     d++;
318                     a += 1 << hsub;
319                 }
320                 dp += dst->linesize[i];
321                 sp += src->linesize[i];
322                 ap += (1 << vsub) * src->linesize[3];
323             }
324         }
325     }
326 }
327
328 static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
329 {
330     AVFilterContext *ctx = inlink->dst;
331     AVFilterLink *outlink = ctx->outputs[0];
332     AVFilterBufferRef *outpicref = inlink->cur_buf;
333     OverlayContext *over = ctx->priv;
334
335     if (over->overpicref &&
336         !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
337           y+h < over->y || y >= over->y + over->overpicref->video->h)) {
338         blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
339                     over->overpicref->video->w, over->overpicref->video->h,
340                     y, outpicref->video->w, h);
341     }
342     return ff_draw_slice(outlink, y, h, slice_dir);
343 }
344
345 static int end_frame(AVFilterLink *inlink)
346 {
347     return ff_end_frame(inlink->dst->outputs[0]);
348 }
349
350 static int null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
351 {
352     return 0;
353 }
354
355 static int null_end_frame(AVFilterLink *inlink)
356 {
357     return 0;
358 }
359
360 static int poll_frame(AVFilterLink *link)
361 {
362     AVFilterContext   *s = link->src;
363     OverlayContext *over = s->priv;
364     int ret = ff_poll_frame(s->inputs[OVERLAY]);
365
366     if (ret == AVERROR_EOF)
367         ret = !!over->overpicref;
368
369     return ret && ff_poll_frame(s->inputs[MAIN]);
370 }
371
372 AVFilter avfilter_vf_overlay = {
373     .name      = "overlay",
374     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
375
376     .init      = init,
377     .uninit    = uninit,
378
379     .priv_size = sizeof(OverlayContext),
380
381     .query_formats = query_formats,
382
383     .inputs    = (const AVFilterPad[]) {{ .name            = "main",
384                                           .type            = AVMEDIA_TYPE_VIDEO,
385                                           .start_frame     = start_frame,
386                                           .get_video_buffer= get_video_buffer,
387                                           .config_props    = config_input_main,
388                                           .draw_slice      = draw_slice,
389                                           .end_frame       = end_frame,
390                                           .min_perms       = AV_PERM_READ,
391                                           .rej_perms       = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
392                                         { .name            = "overlay",
393                                           .type            = AVMEDIA_TYPE_VIDEO,
394                                           .start_frame     = start_frame_overlay,
395                                           .config_props    = config_input_overlay,
396                                           .draw_slice      = null_draw_slice,
397                                           .end_frame       = null_end_frame,
398                                           .min_perms       = AV_PERM_READ,
399                                           .rej_perms       = AV_PERM_REUSE2, },
400                                         { .name = NULL}},
401     .outputs   = (const AVFilterPad[]) {{ .name            = "default",
402                                           .type            = AVMEDIA_TYPE_VIDEO,
403                                           .config_props    = config_output,
404                                           .poll_frame      = poll_frame },
405                                         { .name = NULL}},
406 };