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