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