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;
86 enum OverlayFormat { OVERLAY_FORMAT_YUV420, OVERLAY_FORMAT_YUV444, OVERLAY_FORMAT_RGB, OVERLAY_FORMAT_NB} format;
88 AVFilterBufferRef *overpicref;
89 struct FFBufQueue queue_main;
90 struct FFBufQueue queue_over;
92 int main_pix_step[4]; ///< steps per pixel for each plane of the main output
93 int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
94 int hsub, vsub; ///< chroma subsampling values
95 int shortest; ///< terminate stream when the shortest input terminates
97 char *x_expr, *y_expr;
100 #define OFFSET(x) offsetof(OverlayContext, x)
101 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
103 static const AVOption overlay_options[] = {
104 { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
105 { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
106 { "rgb", "force packed RGB in input and output (deprecated)", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
107 { "shortest", "force termination when the shortest input terminates", OFFSET(shortest), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
109 { "format", "set output format", OFFSET(format), AV_OPT_TYPE_INT, {.i64=OVERLAY_FORMAT_YUV420}, 0, OVERLAY_FORMAT_NB-1, FLAGS, "format" },
110 { "yuv420", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV420}, .flags = FLAGS, .unit = "format" },
111 { "yuv444", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV444}, .flags = FLAGS, .unit = "format" },
112 { "rgb", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_RGB}, .flags = FLAGS, .unit = "format" },
117 AVFILTER_DEFINE_CLASS(overlay);
119 static av_cold int init(AVFilterContext *ctx, const char *args)
121 OverlayContext *over = ctx->priv;
122 static const char *shorthand[] = { "x", "y", NULL };
125 over->class = &overlay_class;
126 av_opt_set_defaults(over);
128 ret = av_opt_set_from_string(over, args, shorthand, "=", ":");
132 if (over->allow_packed_rgb) {
133 av_log(ctx, AV_LOG_WARNING,
134 "The rgb option is deprecated and is overriding the format option, use format instead\n");
135 over->format = OVERLAY_FORMAT_RGB;
140 static av_cold void uninit(AVFilterContext *ctx)
142 OverlayContext *over = ctx->priv;
146 avfilter_unref_bufferp(&over->overpicref);
147 ff_bufqueue_discard_all(&over->queue_main);
148 ff_bufqueue_discard_all(&over->queue_over);
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 static const enum AVPixelFormat main_pix_fmts_yuv420[] = {
157 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
159 static const enum AVPixelFormat overlay_pix_fmts_yuv420[] = {
160 AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
163 static const enum AVPixelFormat main_pix_fmts_yuv444[] = {
164 AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
166 static const enum AVPixelFormat overlay_pix_fmts_yuv444[] = {
167 AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
170 static const enum AVPixelFormat main_pix_fmts_rgb[] = {
171 AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
172 AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
173 AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
176 static const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
177 AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
178 AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
182 AVFilterFormats *main_formats;
183 AVFilterFormats *overlay_formats;
185 switch (over->format) {
186 case OVERLAY_FORMAT_YUV420:
187 main_formats = ff_make_format_list(main_pix_fmts_yuv420);
188 overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv420);
190 case OVERLAY_FORMAT_YUV444:
191 main_formats = ff_make_format_list(main_pix_fmts_yuv444);
192 overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv444);
194 case OVERLAY_FORMAT_RGB:
195 main_formats = ff_make_format_list(main_pix_fmts_rgb);
196 overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
202 ff_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
203 ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
204 ff_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
209 static const enum AVPixelFormat alpha_pix_fmts[] = {
210 AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA444P,
211 AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
212 AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
215 static int config_input_main(AVFilterLink *inlink)
217 OverlayContext *over = inlink->dst->priv;
218 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
220 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
222 over->hsub = pix_desc->log2_chroma_w;
223 over->vsub = pix_desc->log2_chroma_h;
225 over->main_is_packed_rgb =
226 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
227 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
231 static int config_input_overlay(AVFilterLink *inlink)
233 AVFilterContext *ctx = inlink->dst;
234 OverlayContext *over = inlink->dst->priv;
236 double var_values[VAR_VARS_NB], res;
238 const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
240 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
242 /* Finish the configuration by evaluating the expressions
243 now when both inputs are configured. */
244 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
245 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
246 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
247 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
249 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
250 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
253 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
254 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
257 /* x may depend on y */
258 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
259 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
263 over->overlay_is_packed_rgb =
264 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
265 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
267 av_log(ctx, AV_LOG_VERBOSE,
268 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
269 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
270 av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
272 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
273 av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
275 if (over->x < 0 || over->y < 0 ||
276 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
277 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
278 av_log(ctx, AV_LOG_ERROR,
279 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
281 (int)(over->x + var_values[VAR_OVERLAY_W]),
282 (int)(over->y + var_values[VAR_OVERLAY_H]),
283 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
284 return AVERROR(EINVAL);
289 av_log(NULL, AV_LOG_ERROR,
290 "Error when evaluating the expression '%s'\n", expr);
294 static int config_output(AVFilterLink *outlink)
296 AVFilterContext *ctx = outlink->src;
298 outlink->w = ctx->inputs[MAIN]->w;
299 outlink->h = ctx->inputs[MAIN]->h;
300 outlink->time_base = ctx->inputs[MAIN]->time_base;
305 // divide by 255 and round to nearest
306 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
307 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
309 // calculate the unpremultiplied alpha, applying the general equation:
310 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
311 // (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
312 // ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
313 #define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
316 * Blend image in src to destination buffer dst at position (x, y).
318 * It is assumed that the src image at position (x, y) is contained in
321 static void blend_image(AVFilterContext *ctx,
322 AVFilterBufferRef *dst, AVFilterBufferRef *src,
325 OverlayContext *over = ctx->priv;
327 int width = src->video->w;
328 int height = src->video->h;
330 if (over->main_is_packed_rgb) {
331 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
332 y * dst->linesize[0];
333 uint8_t *sp = src->data[0];
334 uint8_t alpha; ///< the amount of overlay to blend on to main
335 const int dr = over->main_rgba_map[R];
336 const int dg = over->main_rgba_map[G];
337 const int db = over->main_rgba_map[B];
338 const int da = over->main_rgba_map[A];
339 const int dstep = over->main_pix_step[0];
340 const int sr = over->overlay_rgba_map[R];
341 const int sg = over->overlay_rgba_map[G];
342 const int sb = over->overlay_rgba_map[B];
343 const int sa = over->overlay_rgba_map[A];
344 const int sstep = over->overlay_pix_step[0];
345 const int main_has_alpha = over->main_has_alpha;
346 for (i = 0; i < height; i++) {
347 uint8_t *d = dp, *s = sp;
348 for (j = 0; j < width; j++) {
351 // if the main channel has an alpha channel, alpha has to be calculated
352 // to create an un-premultiplied (straight) alpha value
353 if (main_has_alpha && alpha != 0 && alpha != 255) {
354 uint8_t alpha_d = d[da];
355 alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
367 // main_value = main_value * (1 - alpha) + overlay_value * alpha
368 // since alpha is in the range 0-255, the result must divided by 255
369 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
370 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
371 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
373 if (main_has_alpha) {
381 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
382 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
388 dp += dst->linesize[0];
389 sp += src->linesize[0];
392 const int main_has_alpha = over->main_has_alpha;
393 if (main_has_alpha) {
394 uint8_t *da = dst->data[3] + x * over->main_pix_step[3] +
395 y * dst->linesize[3];
396 uint8_t *sa = src->data[3];
397 uint8_t alpha; ///< the amount of overlay to blend on to main
398 for (i = 0; i < height; i++) {
399 uint8_t *d = da, *s = sa;
400 for (j = 0; j < width; j++) {
402 if (alpha != 0 && alpha != 255) {
403 uint8_t alpha_d = *d;
404 alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
413 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
414 *d += FAST_DIV255((255 - *d) * *s);
419 da += dst->linesize[3];
420 sa += src->linesize[3];
423 for (i = 0; i < 3; i++) {
424 int hsub = i ? over->hsub : 0;
425 int vsub = i ? over->vsub : 0;
426 uint8_t *dp = dst->data[i] + (x >> hsub) +
427 (y >> vsub) * dst->linesize[i];
428 uint8_t *sp = src->data[i];
429 uint8_t *ap = src->data[3];
430 int wp = FFALIGN(width, 1<<hsub) >> hsub;
431 int hp = FFALIGN(height, 1<<vsub) >> vsub;
432 for (j = 0; j < hp; j++) {
433 uint8_t *d = dp, *s = sp, *a = ap;
434 for (k = 0; k < wp; k++) {
435 // average alpha for color components, improve quality
436 int alpha_v, alpha_h, alpha;
437 if (hsub && vsub && j+1 < hp && k+1 < wp) {
438 alpha = (a[0] + a[src->linesize[3]] +
439 a[1] + a[src->linesize[3]+1]) >> 2;
440 } else if (hsub || vsub) {
441 alpha_h = hsub && k+1 < wp ?
442 (a[0] + a[1]) >> 1 : a[0];
443 alpha_v = vsub && j+1 < hp ?
444 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
445 alpha = (alpha_v + alpha_h) >> 1;
448 // if the main channel has an alpha channel, alpha has to be calculated
449 // to create an un-premultiplied (straight) alpha value
450 if (main_has_alpha && alpha != 0 && alpha != 255) {
451 // average alpha for color components, improve quality
453 if (hsub && vsub && j+1 < hp && k+1 < wp) {
454 alpha_d = (d[0] + d[src->linesize[3]] +
455 d[1] + d[src->linesize[3]+1]) >> 2;
456 } else if (hsub || vsub) {
457 alpha_h = hsub && k+1 < wp ?
458 (d[0] + d[1]) >> 1 : d[0];
459 alpha_v = vsub && j+1 < hp ?
460 (d[0] + d[src->linesize[3]]) >> 1 : d[0];
461 alpha_d = (alpha_v + alpha_h) >> 1;
464 alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
466 *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
471 dp += dst->linesize[i];
472 sp += src->linesize[i];
473 ap += (1 << vsub) * src->linesize[3];
479 static int try_filter_frame(AVFilterContext *ctx, AVFilterBufferRef *mainpic)
481 OverlayContext *over = ctx->priv;
482 AVFilterLink *outlink = ctx->outputs[0];
483 AVFilterBufferRef *next_overpic;
486 /* Discard obsolete overlay frames: if there is a next overlay frame with pts
487 * before the main frame, we can drop the current overlay. */
489 next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
490 if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
491 mainpic->pts , ctx->inputs[MAIN]->time_base) > 0)
493 ff_bufqueue_get(&over->queue_over);
494 avfilter_unref_buffer(over->overpicref);
495 over->overpicref = next_overpic;
498 /* If there is no next frame and no EOF and the overlay frame is before
499 * the main frame, we can not know yet if it will be superseded. */
500 if (!over->queue_over.available && !over->overlay_eof &&
501 (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
502 mainpic->pts , ctx->inputs[MAIN]->time_base) < 0))
503 return AVERROR(EAGAIN);
505 /* At this point, we know that the current overlay frame extends to the
506 * time of the main frame. */
507 av_dlog(ctx, "main_pts:%s main_pts_time:%s",
508 av_ts2str(mainpic->pts), av_ts2timestr(mainpic->pts, &outlink->time_base));
509 if (over->overpicref)
510 av_dlog(ctx, " over_pts:%s over_pts_time:%s",
511 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
514 if (over->overpicref)
515 blend_image(ctx, mainpic, over->overpicref, over->x, over->y);
516 ret = ff_filter_frame(ctx->outputs[0], mainpic);
517 av_assert1(ret != AVERROR(EAGAIN));
518 over->frame_requested = 0;
522 static int try_filter_next_frame(AVFilterContext *ctx)
524 OverlayContext *over = ctx->priv;
525 AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
529 return AVERROR(EAGAIN);
530 if ((ret = try_filter_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
532 ff_bufqueue_get(&over->queue_main);
536 static int flush_frames(AVFilterContext *ctx)
540 while (!(ret = try_filter_next_frame(ctx)));
541 return ret == AVERROR(EAGAIN) ? 0 : ret;
544 static int filter_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
546 AVFilterContext *ctx = inlink->dst;
547 OverlayContext *over = ctx->priv;
550 if ((ret = flush_frames(ctx)) < 0)
552 if ((ret = try_filter_frame(ctx, inpicref)) < 0) {
553 if (ret != AVERROR(EAGAIN))
555 ff_bufqueue_add(ctx, &over->queue_main, inpicref);
558 if (!over->overpicref)
565 static int filter_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
567 AVFilterContext *ctx = inlink->dst;
568 OverlayContext *over = ctx->priv;
571 if ((ret = flush_frames(ctx)) < 0)
573 ff_bufqueue_add(ctx, &over->queue_over, inpicref);
574 ret = try_filter_next_frame(ctx);
575 return ret == AVERROR(EAGAIN) ? 0 : ret;
578 static int request_frame(AVFilterLink *outlink)
580 AVFilterContext *ctx = outlink->src;
581 OverlayContext *over = ctx->priv;
584 if (!try_filter_next_frame(ctx))
586 over->frame_requested = 1;
587 while (over->frame_requested) {
588 /* TODO if we had a frame duration, we could guess more accurately */
589 input = !over->overlay_eof && (over->queue_main.available ||
590 over->queue_over.available < 2) ?
592 ret = ff_request_frame(ctx->inputs[input]);
593 /* EOF on main is reported immediately */
594 if (ret == AVERROR_EOF && input == OVERLAY) {
595 over->overlay_eof = 1;
598 if ((ret = try_filter_next_frame(ctx)) != AVERROR(EAGAIN))
600 ret = 0; /* continue requesting frames on main */
608 static const AVFilterPad avfilter_vf_overlay_inputs[] = {
611 .type = AVMEDIA_TYPE_VIDEO,
612 .get_video_buffer = ff_null_get_video_buffer,
613 .config_props = config_input_main,
614 .filter_frame = filter_frame_main,
615 .min_perms = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE,
619 .type = AVMEDIA_TYPE_VIDEO,
620 .config_props = config_input_overlay,
621 .filter_frame = filter_frame_over,
622 .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
627 static const AVFilterPad avfilter_vf_overlay_outputs[] = {
630 .type = AVMEDIA_TYPE_VIDEO,
631 .rej_perms = AV_PERM_WRITE,
632 .config_props = config_output,
633 .request_frame = request_frame,
638 AVFilter avfilter_vf_overlay = {
640 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
645 .priv_size = sizeof(OverlayContext),
647 .query_formats = query_formats,
649 .inputs = avfilter_vf_overlay_inputs,
650 .outputs = avfilter_vf_overlay_outputs,
651 .priv_class = &overlay_class,