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
32 #include "libavutil/common.h"
33 #include "libavutil/eval.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/timestamp.h"
41 #include "bufferqueue.h"
42 #include "drawutils.h"
45 static const char *const var_names[] = {
46 "main_w", "W", ///< width of the main video
47 "main_h", "H", ///< height of the main video
48 "overlay_w", "w", ///< width of the overlay video
49 "overlay_h", "h", ///< height of the overlay video
56 VAR_OVERLAY_W, VAR_OW,
57 VAR_OVERLAY_H, VAR_OH,
75 int x, y; ///< position of overlayed picture
78 uint8_t frame_requested;
80 uint8_t main_is_packed_rgb;
81 uint8_t main_rgba_map[4];
82 uint8_t main_has_alpha;
83 uint8_t overlay_is_packed_rgb;
84 uint8_t overlay_rgba_map[4];
85 uint8_t overlay_has_alpha;
87 AVFilterBufferRef *overpicref;
88 struct FFBufQueue queue_main;
89 struct FFBufQueue queue_over;
91 int main_pix_step[4]; ///< steps per pixel for each plane of the main output
92 int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
93 int hsub, vsub; ///< chroma subsampling values
95 char *x_expr, *y_expr;
98 #define OFFSET(x) offsetof(OverlayContext, x)
99 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
101 static const AVOption overlay_options[] = {
102 { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
103 { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
104 {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
108 AVFILTER_DEFINE_CLASS(overlay);
110 static av_cold int init(AVFilterContext *ctx, const char *args)
112 OverlayContext *over = ctx->priv;
113 static const char *shorthand[] = { "x", "y", NULL };
115 over->class = &overlay_class;
116 av_opt_set_defaults(over);
118 return av_opt_set_from_string(over, args, shorthand, "=", ":");
121 static av_cold void uninit(AVFilterContext *ctx)
123 OverlayContext *over = ctx->priv;
127 avfilter_unref_bufferp(&over->overpicref);
128 ff_bufqueue_discard_all(&over->queue_main);
129 ff_bufqueue_discard_all(&over->queue_over);
132 static int query_formats(AVFilterContext *ctx)
134 OverlayContext *over = ctx->priv;
136 /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
137 static const enum AVPixelFormat main_pix_fmts_yuv[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
138 static const enum AVPixelFormat overlay_pix_fmts_yuv[] = { AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
139 static const enum AVPixelFormat main_pix_fmts_rgb[] = {
140 AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
141 AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
142 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
145 static const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
146 AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
147 AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
151 AVFilterFormats *main_formats;
152 AVFilterFormats *overlay_formats;
154 if (over->allow_packed_rgb) {
155 main_formats = ff_make_format_list(main_pix_fmts_rgb);
156 overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
158 main_formats = ff_make_format_list(main_pix_fmts_yuv);
159 overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv);
162 ff_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
163 ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
164 ff_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
169 static const enum AVPixelFormat alpha_pix_fmts[] = {
170 AV_PIX_FMT_YUVA420P, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
171 AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
174 static int config_input_main(AVFilterLink *inlink)
176 OverlayContext *over = inlink->dst->priv;
177 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
179 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
181 over->hsub = pix_desc->log2_chroma_w;
182 over->vsub = pix_desc->log2_chroma_h;
184 over->main_is_packed_rgb =
185 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
186 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
190 static int config_input_overlay(AVFilterLink *inlink)
192 AVFilterContext *ctx = inlink->dst;
193 OverlayContext *over = inlink->dst->priv;
195 double var_values[VAR_VARS_NB], res;
197 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
199 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
201 /* Finish the configuration by evaluating the expressions
202 now when both inputs are configured. */
203 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
204 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
205 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
206 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
208 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
209 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
212 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
213 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
216 /* x may depend on y */
217 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
218 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
222 over->overlay_is_packed_rgb =
223 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
224 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
226 av_log(ctx, AV_LOG_VERBOSE,
227 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
228 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
229 av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
231 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
232 av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
234 if (over->x < 0 || over->y < 0 ||
235 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
236 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
237 av_log(ctx, AV_LOG_ERROR,
238 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
240 (int)(over->x + var_values[VAR_OVERLAY_W]),
241 (int)(over->y + var_values[VAR_OVERLAY_H]),
242 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
243 return AVERROR(EINVAL);
248 av_log(NULL, AV_LOG_ERROR,
249 "Error when evaluating the expression '%s'\n", expr);
253 static int config_output(AVFilterLink *outlink)
255 AVFilterContext *ctx = outlink->src;
257 outlink->w = ctx->inputs[MAIN]->w;
258 outlink->h = ctx->inputs[MAIN]->h;
259 outlink->time_base = ctx->inputs[MAIN]->time_base;
264 // divide by 255 and round to nearest
265 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
266 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
268 // calculate the unpremultiplied alpha, applying the general equation:
269 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
270 // (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
271 // ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
272 #define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
275 * Blend image in src to destination buffer dst at position (x, y).
277 * It is assumed that the src image at position (x, y) is contained in
280 static void blend_image(AVFilterContext *ctx,
281 AVFilterBufferRef *dst, AVFilterBufferRef *src,
284 OverlayContext *over = ctx->priv;
286 int width = src->video->w;
287 int height = src->video->h;
289 if (over->main_is_packed_rgb) {
290 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
291 y * dst->linesize[0];
292 uint8_t *sp = src->data[0];
293 uint8_t alpha; ///< the amount of overlay to blend on to main
294 const int dr = over->main_rgba_map[R];
295 const int dg = over->main_rgba_map[G];
296 const int db = over->main_rgba_map[B];
297 const int da = over->main_rgba_map[A];
298 const int dstep = over->main_pix_step[0];
299 const int sr = over->overlay_rgba_map[R];
300 const int sg = over->overlay_rgba_map[G];
301 const int sb = over->overlay_rgba_map[B];
302 const int sa = over->overlay_rgba_map[A];
303 const int sstep = over->overlay_pix_step[0];
304 const int main_has_alpha = over->main_has_alpha;
305 for (i = 0; i < height; i++) {
306 uint8_t *d = dp, *s = sp;
307 for (j = 0; j < width; j++) {
310 // if the main channel has an alpha channel, alpha has to be calculated
311 // to create an un-premultiplied (straight) alpha value
312 if (main_has_alpha && alpha != 0 && alpha != 255) {
313 uint8_t alpha_d = d[da];
314 alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
326 // main_value = main_value * (1 - alpha) + overlay_value * alpha
327 // since alpha is in the range 0-255, the result must divided by 255
328 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
329 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
330 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
332 if (main_has_alpha) {
340 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
341 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
347 dp += dst->linesize[0];
348 sp += src->linesize[0];
351 const int main_has_alpha = over->main_has_alpha;
352 if (main_has_alpha) {
353 uint8_t *da = dst->data[3] + x * over->main_pix_step[3] +
354 y * dst->linesize[3];
355 uint8_t *sa = src->data[3];
356 uint8_t alpha; ///< the amount of overlay to blend on to main
357 for (i = 0; i < height; i++) {
358 uint8_t *d = da, *s = sa;
359 for (j = 0; j < width; j++) {
361 if (alpha != 0 && alpha != 255) {
362 uint8_t alpha_d = *d;
363 alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
372 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
373 *d += FAST_DIV255((255 - *d) * *s);
378 da += dst->linesize[3];
379 sa += src->linesize[3];
382 for (i = 0; i < 3; i++) {
383 int hsub = i ? over->hsub : 0;
384 int vsub = i ? over->vsub : 0;
385 uint8_t *dp = dst->data[i] + (x >> hsub) +
386 (y >> vsub) * dst->linesize[i];
387 uint8_t *sp = src->data[i];
388 uint8_t *ap = src->data[3];
389 int wp = FFALIGN(width, 1<<hsub) >> hsub;
390 int hp = FFALIGN(height, 1<<vsub) >> vsub;
391 for (j = 0; j < hp; j++) {
392 uint8_t *d = dp, *s = sp, *a = ap;
393 for (k = 0; k < wp; k++) {
394 // average alpha for color components, improve quality
395 int alpha_v, alpha_h, alpha;
396 if (hsub && vsub && j+1 < hp && k+1 < wp) {
397 alpha = (a[0] + a[src->linesize[3]] +
398 a[1] + a[src->linesize[3]+1]) >> 2;
399 } else if (hsub || vsub) {
400 alpha_h = hsub && k+1 < wp ?
401 (a[0] + a[1]) >> 1 : a[0];
402 alpha_v = vsub && j+1 < hp ?
403 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
404 alpha = (alpha_v + alpha_h) >> 1;
407 // if the main channel has an alpha channel, alpha has to be calculated
408 // to create an un-premultiplied (straight) alpha value
409 if (main_has_alpha && alpha != 0 && alpha != 255) {
410 // average alpha for color components, improve quality
412 if (hsub && vsub && j+1 < hp && k+1 < wp) {
413 alpha_d = (d[0] + d[src->linesize[3]] +
414 d[1] + d[src->linesize[3]+1]) >> 2;
415 } else if (hsub || vsub) {
416 alpha_h = hsub && k+1 < wp ?
417 (d[0] + d[1]) >> 1 : d[0];
418 alpha_v = vsub && j+1 < hp ?
419 (d[0] + d[src->linesize[3]]) >> 1 : d[0];
420 alpha_d = (alpha_v + alpha_h) >> 1;
423 alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
425 *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
430 dp += dst->linesize[i];
431 sp += src->linesize[i];
432 ap += (1 << vsub) * src->linesize[3];
438 static int try_filter_frame(AVFilterContext *ctx, AVFilterBufferRef *mainpic)
440 OverlayContext *over = ctx->priv;
441 AVFilterLink *outlink = ctx->outputs[0];
442 AVFilterBufferRef *next_overpic;
445 /* Discard obsolete overlay frames: if there is a next overlay frame with pts
446 * before the main frame, we can drop the current overlay. */
448 next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
449 if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
450 mainpic->pts , ctx->inputs[MAIN]->time_base) > 0)
452 ff_bufqueue_get(&over->queue_over);
453 avfilter_unref_buffer(over->overpicref);
454 over->overpicref = next_overpic;
457 /* If there is no next frame and no EOF and the overlay frame is before
458 * the main frame, we can not know yet if it will be superseded. */
459 if (!over->queue_over.available && !over->overlay_eof &&
460 (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
461 mainpic->pts , ctx->inputs[MAIN]->time_base) < 0))
462 return AVERROR(EAGAIN);
464 /* At this point, we know that the current overlay frame extends to the
465 * time of the main frame. */
466 av_dlog(ctx, "main_pts:%s main_pts_time:%s",
467 av_ts2str(mainpic->pts), av_ts2timestr(mainpic->pts, &outlink->time_base));
468 if (over->overpicref)
469 av_dlog(ctx, " over_pts:%s over_pts_time:%s",
470 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
473 if (over->overpicref)
474 blend_image(ctx, mainpic, over->overpicref, over->x, over->y);
475 ret = ff_filter_frame(ctx->outputs[0], mainpic);
476 av_assert1(ret != AVERROR(EAGAIN));
477 over->frame_requested = 0;
481 static int try_filter_next_frame(AVFilterContext *ctx)
483 OverlayContext *over = ctx->priv;
484 AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
488 return AVERROR(EAGAIN);
489 if ((ret = try_filter_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
491 ff_bufqueue_get(&over->queue_main);
495 static int flush_frames(AVFilterContext *ctx)
499 while (!(ret = try_filter_next_frame(ctx)));
500 return ret == AVERROR(EAGAIN) ? 0 : ret;
503 static int filter_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
505 AVFilterContext *ctx = inlink->dst;
506 OverlayContext *over = ctx->priv;
509 if ((ret = flush_frames(ctx)) < 0)
511 if ((ret = try_filter_frame(ctx, inpicref)) < 0) {
512 if (ret != AVERROR(EAGAIN))
514 ff_bufqueue_add(ctx, &over->queue_main, inpicref);
517 if (!over->overpicref)
524 static int filter_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
526 AVFilterContext *ctx = inlink->dst;
527 OverlayContext *over = ctx->priv;
530 if ((ret = flush_frames(ctx)) < 0)
532 ff_bufqueue_add(ctx, &over->queue_over, inpicref);
533 ret = try_filter_next_frame(ctx);
534 return ret == AVERROR(EAGAIN) ? 0 : ret;
537 static int request_frame(AVFilterLink *outlink)
539 AVFilterContext *ctx = outlink->src;
540 OverlayContext *over = ctx->priv;
543 if (!try_filter_next_frame(ctx))
545 over->frame_requested = 1;
546 while (over->frame_requested) {
547 /* TODO if we had a frame duration, we could guess more accurately */
548 input = !over->overlay_eof && (over->queue_main.available ||
549 over->queue_over.available < 2) ?
551 ret = ff_request_frame(ctx->inputs[input]);
552 /* EOF on main is reported immediately */
553 if (ret == AVERROR_EOF && input == OVERLAY) {
554 over->overlay_eof = 1;
555 if ((ret = try_filter_next_frame(ctx)) != AVERROR(EAGAIN))
557 ret = 0; /* continue requesting frames on main */
565 static const AVFilterPad avfilter_vf_overlay_inputs[] = {
568 .type = AVMEDIA_TYPE_VIDEO,
569 .get_video_buffer = ff_null_get_video_buffer,
570 .config_props = config_input_main,
571 .filter_frame = filter_frame_main,
572 .min_perms = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE,
576 .type = AVMEDIA_TYPE_VIDEO,
577 .config_props = config_input_overlay,
578 .filter_frame = filter_frame_over,
579 .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
584 static const AVFilterPad avfilter_vf_overlay_outputs[] = {
587 .type = AVMEDIA_TYPE_VIDEO,
588 .rej_perms = AV_PERM_WRITE,
589 .config_props = config_output,
590 .request_frame = request_frame,
595 AVFilter avfilter_vf_overlay = {
597 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
602 .priv_size = sizeof(OverlayContext),
604 .query_formats = query_formats,
606 .inputs = avfilter_vf_overlay_inputs,
607 .outputs = avfilter_vf_overlay_outputs,
608 .priv_class = &overlay_class,