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 * const 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 av_free(over->x_expr);
119 if (!(over->x_expr = av_strdup(expr))) {
120 ret = AVERROR(ENOMEM);
124 if (expr = av_strtok(NULL, ":", &bufptr)) {
125 av_free(over->y_expr);
126 if (!(over->y_expr = av_strdup(expr))) {
127 ret = AVERROR(ENOMEM);
132 if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
140 static av_cold void uninit(AVFilterContext *ctx)
142 OverlayContext *over = ctx->priv;
144 av_freep(&over->x_expr);
145 av_freep(&over->y_expr);
147 if (over->overpicref)
148 avfilter_unref_buffer(over->overpicref);
151 static int query_formats(AVFilterContext *ctx)
153 OverlayContext *over = ctx->priv;
155 /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
156 const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
157 const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
158 const enum PixelFormat main_pix_fmts_rgb[] = {
159 PIX_FMT_ARGB, PIX_FMT_RGBA,
160 PIX_FMT_ABGR, PIX_FMT_BGRA,
161 PIX_FMT_RGB24, PIX_FMT_BGR24,
164 const enum PixelFormat overlay_pix_fmts_rgb[] = {
165 PIX_FMT_ARGB, PIX_FMT_RGBA,
166 PIX_FMT_ABGR, PIX_FMT_BGRA,
170 AVFilterFormats *main_formats;
171 AVFilterFormats *overlay_formats;
173 if (over->allow_packed_rgb) {
174 main_formats = avfilter_make_format_list(main_pix_fmts_rgb);
175 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_rgb);
177 main_formats = avfilter_make_format_list(main_pix_fmts_yuv);
178 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_yuv);
181 avfilter_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
182 avfilter_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
183 avfilter_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
188 static const enum PixelFormat alpha_pix_fmts[] = {
189 PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
190 PIX_FMT_BGRA, PIX_FMT_NONE
193 static int config_input_main(AVFilterLink *inlink)
195 OverlayContext *over = inlink->dst->priv;
196 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
198 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
200 over->hsub = pix_desc->log2_chroma_w;
201 over->vsub = pix_desc->log2_chroma_h;
203 over->main_is_packed_rgb =
204 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
205 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
209 static int config_input_overlay(AVFilterLink *inlink)
211 AVFilterContext *ctx = inlink->dst;
212 OverlayContext *over = inlink->dst->priv;
214 double var_values[VAR_VARS_NB], res;
216 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
218 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
220 /* Finish the configuration by evaluating the expressions
221 now when both inputs are configured. */
222 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
223 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
224 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
225 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
227 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
228 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
231 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
232 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
235 /* x may depend on y */
236 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
237 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
241 over->overlay_is_packed_rgb =
242 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
243 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
245 av_log(ctx, AV_LOG_INFO,
246 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
247 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
248 av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
250 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
251 av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
253 if (over->x < 0 || over->y < 0 ||
254 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
255 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
256 av_log(ctx, AV_LOG_ERROR,
257 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
259 (int)(over->x + var_values[VAR_OVERLAY_W]),
260 (int)(over->y + var_values[VAR_OVERLAY_H]),
261 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
262 return AVERROR(EINVAL);
267 av_log(NULL, AV_LOG_ERROR,
268 "Error when evaluating the expression '%s'\n", expr);
272 static int config_output(AVFilterLink *outlink)
274 AVFilterContext *ctx = outlink->src;
276 // common timebase computation:
277 AVRational tb1 = ctx->inputs[MAIN ]->time_base;
278 AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
279 AVRational *tb = &ctx->outputs[0]->time_base;
280 exact = av_reduce(&tb->num, &tb->den,
281 av_gcd((int64_t)tb1.num * tb2.den,
282 (int64_t)tb2.num * tb1.den),
283 (int64_t)tb1.den * tb2.den, INT_MAX);
284 av_log(ctx, AV_LOG_INFO,
285 "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
286 tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
288 av_log(ctx, AV_LOG_WARNING,
289 "Timestamp conversion inexact, timestamp information loss may occurr\n");
291 outlink->w = ctx->inputs[MAIN]->w;
292 outlink->h = ctx->inputs[MAIN]->h;
297 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
299 return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
302 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
304 AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
305 AVFilterContext *ctx = inlink->dst;
306 OverlayContext *over = ctx->priv;
308 inlink->dst->outputs[0]->out_buf = outpicref;
309 outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
310 ctx->outputs[0]->time_base);
312 if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
313 AVFilterBufferRef *old = over->overpicref;
314 over->overpicref = NULL;
315 avfilter_request_frame(ctx->inputs[OVERLAY]);
316 if (over->overpicref) {
318 avfilter_unref_buffer(old);
320 over->overpicref = old;
323 avfilter_start_frame(inlink->dst->outputs[0], outpicref);
326 static void start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
328 AVFilterContext *ctx = inlink->dst;
329 OverlayContext *over = ctx->priv;
331 over->overpicref = inpicref;
332 over->overpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
333 ctx->outputs[0]->time_base);
336 // divide by 255 and round to nearest
337 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
338 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
340 static void blend_slice(AVFilterContext *ctx,
341 AVFilterBufferRef *dst, AVFilterBufferRef *src,
342 int x, int y, int w, int h,
343 int slice_y, int slice_w, int slice_h)
345 OverlayContext *over = ctx->priv;
348 int overlay_end_y = y+h;
349 int slice_end_y = slice_y+slice_h;
352 width = FFMIN(slice_w - x, w);
353 end_y = FFMIN(slice_end_y, overlay_end_y);
354 start_y = FFMAX(y, slice_y);
355 height = end_y - start_y;
357 if (over->main_is_packed_rgb) {
358 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
359 start_y * dst->linesize[0];
360 uint8_t *sp = src->data[0];
361 uint8_t alpha; ///< the amount of overlay to blend on to main
362 const int dr = over->main_rgba_map[R];
363 const int dg = over->main_rgba_map[G];
364 const int db = over->main_rgba_map[B];
365 const int da = over->main_rgba_map[A];
366 const int dstep = over->main_pix_step[0];
367 const int sr = over->overlay_rgba_map[R];
368 const int sg = over->overlay_rgba_map[G];
369 const int sb = over->overlay_rgba_map[B];
370 const int sa = over->overlay_rgba_map[A];
371 const int sstep = over->overlay_pix_step[0];
372 const int main_has_alpha = over->main_has_alpha;
374 sp += (slice_y - y) * src->linesize[0];
375 for (i = 0; i < height; i++) {
376 uint8_t *d = dp, *s = sp;
377 for (j = 0; j < width; j++) {
380 // if the main channel has an alpha channel, alpha has to be calculated
381 // to create an un-premultiplied (straight) alpha value
382 if (main_has_alpha && alpha != 0 && alpha != 255) {
383 // apply the general equation:
384 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
386 // the next line is a faster version of: 255 * 255 * alpha
387 ( (alpha << 16) - (alpha << 9) + alpha )
389 // the next line is a faster version of: 255 * (alpha + d[da])
390 ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
403 // main_value = main_value * (1 - alpha) + overlay_value * alpha
404 // since alpha is in the range 0-255, the result must divided by 255
405 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
406 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
407 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
409 if (main_has_alpha) {
417 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
418 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
424 dp += dst->linesize[0];
425 sp += src->linesize[0];
428 for (i = 0; i < 3; i++) {
429 int hsub = i ? over->hsub : 0;
430 int vsub = i ? over->vsub : 0;
431 uint8_t *dp = dst->data[i] + (x >> hsub) +
432 (start_y >> vsub) * dst->linesize[i];
433 uint8_t *sp = src->data[i];
434 uint8_t *ap = src->data[3];
435 int wp = FFALIGN(width, 1<<hsub) >> hsub;
436 int hp = FFALIGN(height, 1<<vsub) >> vsub;
438 sp += ((slice_y - y) >> vsub) * src->linesize[i];
439 ap += (slice_y - y) * src->linesize[3];
441 for (j = 0; j < hp; j++) {
442 uint8_t *d = dp, *s = sp, *a = ap;
443 for (k = 0; k < wp; k++) {
444 // average alpha for color components, improve quality
445 int alpha_v, alpha_h, alpha;
446 if (hsub && vsub && j+1 < hp && k+1 < wp) {
447 alpha = (a[0] + a[src->linesize[3]] +
448 a[1] + a[src->linesize[3]+1]) >> 2;
449 } else if (hsub || vsub) {
450 alpha_h = hsub && k+1 < wp ?
451 (a[0] + a[1]) >> 1 : a[0];
452 alpha_v = vsub && j+1 < hp ?
453 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
454 alpha = (alpha_v + alpha_h) >> 1;
457 *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
462 dp += dst->linesize[i];
463 sp += src->linesize[i];
464 ap += (1 << vsub) * src->linesize[3];
470 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
472 AVFilterContext *ctx = inlink->dst;
473 AVFilterLink *outlink = ctx->outputs[0];
474 AVFilterBufferRef *outpicref = outlink->out_buf;
475 OverlayContext *over = ctx->priv;
477 if (over->overpicref &&
478 !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
479 y+h < over->y || y >= over->y + over->overpicref->video->h)) {
480 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
481 over->overpicref->video->w, over->overpicref->video->h,
482 y, outpicref->video->w, h);
484 avfilter_draw_slice(outlink, y, h, slice_dir);
487 static void end_frame(AVFilterLink *inlink)
489 avfilter_end_frame(inlink->dst->outputs[0]);
490 avfilter_unref_buffer(inlink->cur_buf);
493 static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
495 static void null_end_frame(AVFilterLink *inlink) { }
497 AVFilter avfilter_vf_overlay = {
499 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
504 .priv_size = sizeof(OverlayContext),
506 .query_formats = query_formats,
508 .inputs = (const AVFilterPad[]) {{ .name = "main",
509 .type = AVMEDIA_TYPE_VIDEO,
510 .start_frame = start_frame,
511 .get_video_buffer= get_video_buffer,
512 .config_props = config_input_main,
513 .draw_slice = draw_slice,
514 .end_frame = end_frame,
515 .min_perms = AV_PERM_READ,
516 .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
518 .type = AVMEDIA_TYPE_VIDEO,
519 .start_frame = start_frame_overlay,
520 .config_props = config_input_overlay,
521 .draw_slice = null_draw_slice,
522 .end_frame = null_end_frame,
523 .min_perms = AV_PERM_READ,
524 .rej_perms = AV_PERM_REUSE2, },
526 .outputs = (const AVFilterPad[]) {{ .name = "default",
527 .type = AVMEDIA_TYPE_VIDEO,
528 .config_props = config_output, },