2 * Copyright (c) 2010 Stefano Sabatini
3 * Copyright (c) 2010 Baptiste Coudurier
4 * Copyright (c) 2007 Bobby Bingham
6 * This file is part of FFmpeg.
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.
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.
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
25 * overlay one video on top of another
29 #include "libavutil/eval.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/pixdesc.h"
33 #include "libavutil/imgutils.h"
34 #include "libavutil/mathematics.h"
36 #include "drawutils.h"
38 static const char *var_names[] = {
39 "main_w", "W", ///< width of the main video
40 "main_h", "H", ///< height of the main video
41 "overlay_w", "w", ///< width of the overlay video
42 "overlay_h", "h", ///< height of the overlay video
49 VAR_OVERLAY_W, VAR_OW,
50 VAR_OVERLAY_H, VAR_OH,
68 int x, y; ///< position of overlayed picture
71 uint8_t main_is_packed_rgb;
72 uint8_t main_rgba_map[4];
73 uint8_t main_has_alpha;
74 uint8_t overlay_is_packed_rgb;
75 uint8_t overlay_rgba_map[4];
76 uint8_t overlay_has_alpha;
78 AVFilterBufferRef *overpicref;
80 int main_pix_step[4]; ///< steps per pixel for each plane of the main output
81 int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
82 int hsub, vsub; ///< chroma subsampling values
84 char *x_expr, *y_expr;
87 #define OFFSET(x) offsetof(OverlayContext, x)
89 static const AVOption overlay_options[] = {
90 { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
91 { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
92 {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
96 static const char *overlay_get_name(void *ctx)
101 static const AVClass overlay_class = {
107 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
109 OverlayContext *over = ctx->priv;
110 char *args1 = av_strdup(args);
111 char *expr, *bufptr = NULL;
114 over->class = &overlay_class;
115 av_opt_set_defaults(over);
117 if (expr = av_strtok(args1, ":", &bufptr)) {
118 if (!(over->x_expr = av_strdup(expr))) {
119 ret = AVERROR(ENOMEM);
123 if (expr = av_strtok(NULL, ":", &bufptr)) {
124 if (!(over->y_expr = av_strdup(expr))) {
125 ret = AVERROR(ENOMEM);
130 if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
138 static av_cold void uninit(AVFilterContext *ctx)
140 OverlayContext *over = ctx->priv;
142 av_freep(&over->x_expr);
143 av_freep(&over->y_expr);
145 if (over->overpicref)
146 avfilter_unref_buffer(over->overpicref);
149 static int query_formats(AVFilterContext *ctx)
151 OverlayContext *over = ctx->priv;
153 /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
154 const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
155 const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
156 const enum PixelFormat main_pix_fmts_rgb[] = {
157 PIX_FMT_ARGB, PIX_FMT_RGBA,
158 PIX_FMT_ABGR, PIX_FMT_BGRA,
159 PIX_FMT_RGB24, PIX_FMT_BGR24,
162 const enum PixelFormat overlay_pix_fmts_rgb[] = {
163 PIX_FMT_ARGB, PIX_FMT_RGBA,
164 PIX_FMT_ABGR, PIX_FMT_BGRA,
168 AVFilterFormats *main_formats;
169 AVFilterFormats *overlay_formats;
171 if (over->allow_packed_rgb) {
172 main_formats = avfilter_make_format_list(main_pix_fmts_rgb);
173 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_rgb);
175 main_formats = avfilter_make_format_list(main_pix_fmts_yuv);
176 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_yuv);
179 avfilter_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
180 avfilter_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
181 avfilter_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
186 static enum PixelFormat alpha_pix_fmts[] = {
187 PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
188 PIX_FMT_BGRA, PIX_FMT_NONE
191 static int config_input_main(AVFilterLink *inlink)
193 OverlayContext *over = inlink->dst->priv;
194 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
196 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
198 over->hsub = pix_desc->log2_chroma_w;
199 over->vsub = pix_desc->log2_chroma_h;
201 over->main_is_packed_rgb =
202 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
203 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
207 static int config_input_overlay(AVFilterLink *inlink)
209 AVFilterContext *ctx = inlink->dst;
210 OverlayContext *over = inlink->dst->priv;
212 double var_values[VAR_VARS_NB], res;
214 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
216 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
218 /* Finish the configuration by evaluating the expressions
219 now when both inputs are configured. */
220 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
221 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
222 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
223 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
225 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
226 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
229 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
230 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
233 /* x may depend on y */
234 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
235 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
239 over->overlay_is_packed_rgb =
240 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
241 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
243 av_log(ctx, AV_LOG_INFO,
244 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
245 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
246 av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
248 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
249 av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
251 if (over->x < 0 || over->y < 0 ||
252 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
253 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
254 av_log(ctx, AV_LOG_ERROR,
255 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
257 (int)(over->x + var_values[VAR_OVERLAY_W]),
258 (int)(over->y + var_values[VAR_OVERLAY_H]),
259 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
260 return AVERROR(EINVAL);
265 av_log(NULL, AV_LOG_ERROR,
266 "Error when evaluating the expression '%s'\n", expr);
270 static int config_output(AVFilterLink *outlink)
272 AVFilterContext *ctx = outlink->src;
274 // common timebase computation:
275 AVRational tb1 = ctx->inputs[MAIN ]->time_base;
276 AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
277 AVRational *tb = &ctx->outputs[0]->time_base;
278 exact = av_reduce(&tb->num, &tb->den,
279 av_gcd((int64_t)tb1.num * tb2.den,
280 (int64_t)tb2.num * tb1.den),
281 (int64_t)tb1.den * tb2.den, INT_MAX);
282 av_log(ctx, AV_LOG_INFO,
283 "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
284 tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
286 av_log(ctx, AV_LOG_WARNING,
287 "Timestamp conversion inexact, timestamp information loss may occurr\n");
289 outlink->w = ctx->inputs[MAIN]->w;
290 outlink->h = ctx->inputs[MAIN]->h;
295 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
297 return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
300 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
302 AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
303 AVFilterContext *ctx = inlink->dst;
304 OverlayContext *over = ctx->priv;
306 inlink->dst->outputs[0]->out_buf = outpicref;
307 outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
308 ctx->outputs[0]->time_base);
310 if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
311 AVFilterBufferRef *old = over->overpicref;
312 over->overpicref = NULL;
313 avfilter_request_frame(ctx->inputs[OVERLAY]);
314 if (over->overpicref) {
316 avfilter_unref_buffer(old);
318 over->overpicref = old;
321 avfilter_start_frame(inlink->dst->outputs[0], outpicref);
324 static void start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
326 AVFilterContext *ctx = inlink->dst;
327 OverlayContext *over = ctx->priv;
329 over->overpicref = inpicref;
330 over->overpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
331 ctx->outputs[0]->time_base);
334 // divide by 255 and round to nearest
335 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
336 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
338 static void blend_slice(AVFilterContext *ctx,
339 AVFilterBufferRef *dst, AVFilterBufferRef *src,
340 int x, int y, int w, int h,
341 int slice_y, int slice_w, int slice_h)
343 OverlayContext *over = ctx->priv;
346 int overlay_end_y = y+h;
347 int slice_end_y = slice_y+slice_h;
350 width = FFMIN(slice_w - x, w);
351 end_y = FFMIN(slice_end_y, overlay_end_y);
352 start_y = FFMAX(y, slice_y);
353 height = end_y - start_y;
355 if (over->main_is_packed_rgb) {
356 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
357 start_y * dst->linesize[0];
358 uint8_t *sp = src->data[0];
359 uint8_t alpha; ///< the amount of overlay to blend on to main
360 const int dr = over->main_rgba_map[R];
361 const int dg = over->main_rgba_map[G];
362 const int db = over->main_rgba_map[B];
363 const int da = over->main_rgba_map[A];
364 const int dstep = over->main_pix_step[0];
365 const int sr = over->overlay_rgba_map[R];
366 const int sg = over->overlay_rgba_map[G];
367 const int sb = over->overlay_rgba_map[B];
368 const int sa = over->overlay_rgba_map[A];
369 const int sstep = over->overlay_pix_step[0];
370 const int main_has_alpha = over->main_has_alpha;
372 sp += (slice_y - y) * src->linesize[0];
373 for (i = 0; i < height; i++) {
374 uint8_t *d = dp, *s = sp;
375 for (j = 0; j < width; j++) {
378 // if the main channel has an alpha channel, alpha has to be calculated
379 // to create an un-premultiplied (straight) alpha value
380 if (main_has_alpha && alpha != 0 && alpha != 255) {
381 // apply the general equation:
382 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
384 // the next line is a faster version of: 255 * 255 * alpha
385 ( (alpha << 16) - (alpha << 9) + alpha )
387 // the next line is a faster version of: 255 * (alpha + d[da])
388 ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
401 // main_value = main_value * (1 - alpha) + overlay_value * alpha
402 // since alpha is in the range 0-255, the result must divided by 255
403 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
404 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
405 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
407 if (main_has_alpha) {
415 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
416 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
422 dp += dst->linesize[0];
423 sp += src->linesize[0];
426 for (i = 0; i < 3; i++) {
427 int hsub = i ? over->hsub : 0;
428 int vsub = i ? over->vsub : 0;
429 uint8_t *dp = dst->data[i] + (x >> hsub) +
430 (start_y >> vsub) * dst->linesize[i];
431 uint8_t *sp = src->data[i];
432 uint8_t *ap = src->data[3];
433 int wp = FFALIGN(width, 1<<hsub) >> hsub;
434 int hp = FFALIGN(height, 1<<vsub) >> vsub;
436 sp += ((slice_y - y) >> vsub) * src->linesize[i];
437 ap += (slice_y - y) * src->linesize[3];
439 for (j = 0; j < hp; j++) {
440 uint8_t *d = dp, *s = sp, *a = ap;
441 for (k = 0; k < wp; k++) {
442 // average alpha for color components, improve quality
443 int alpha_v, alpha_h, alpha;
444 if (hsub && vsub && j+1 < hp && k+1 < wp) {
445 alpha = (a[0] + a[src->linesize[3]] +
446 a[1] + a[src->linesize[3]+1]) >> 2;
447 } else if (hsub || vsub) {
448 alpha_h = hsub && k+1 < wp ?
449 (a[0] + a[1]) >> 1 : a[0];
450 alpha_v = vsub && j+1 < hp ?
451 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
452 alpha = (alpha_v + alpha_h) >> 1;
455 *d = (*d * (0xff - alpha) + *s++ * alpha + 128) >> 8;
459 dp += dst->linesize[i];
460 sp += src->linesize[i];
461 ap += (1 << vsub) * src->linesize[3];
467 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
469 AVFilterContext *ctx = inlink->dst;
470 AVFilterLink *outlink = ctx->outputs[0];
471 AVFilterBufferRef *outpicref = outlink->out_buf;
472 OverlayContext *over = ctx->priv;
474 if (over->overpicref &&
475 !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
476 y+h < over->y || y >= over->y + over->overpicref->video->h)) {
477 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
478 over->overpicref->video->w, over->overpicref->video->h,
479 y, outpicref->video->w, h);
481 avfilter_draw_slice(outlink, y, h, slice_dir);
484 static void end_frame(AVFilterLink *inlink)
486 avfilter_end_frame(inlink->dst->outputs[0]);
487 avfilter_unref_buffer(inlink->cur_buf);
490 static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
492 static void null_end_frame(AVFilterLink *inlink) { }
494 AVFilter avfilter_vf_overlay = {
496 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
501 .priv_size = sizeof(OverlayContext),
503 .query_formats = query_formats,
505 .inputs = (AVFilterPad[]) {{ .name = "main",
506 .type = AVMEDIA_TYPE_VIDEO,
507 .start_frame = start_frame,
508 .get_video_buffer= get_video_buffer,
509 .config_props = config_input_main,
510 .draw_slice = draw_slice,
511 .end_frame = end_frame,
512 .min_perms = AV_PERM_READ,
513 .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
515 .type = AVMEDIA_TYPE_VIDEO,
516 .start_frame = start_frame_overlay,
517 .config_props = config_input_overlay,
518 .draw_slice = null_draw_slice,
519 .end_frame = null_end_frame,
520 .min_perms = AV_PERM_READ,
521 .rej_perms = AV_PERM_REUSE2, },
523 .outputs = (AVFilterPad[]) {{ .name = "default",
524 .type = AVMEDIA_TYPE_VIDEO,
525 .config_props = config_output, },