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
31 #include "libavutil/eval.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/imgutils.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/timestamp.h"
39 #include "drawutils.h"
41 static const char *const var_names[] = {
42 "main_w", "W", ///< width of the main video
43 "main_h", "H", ///< height of the main video
44 "overlay_w", "w", ///< width of the overlay video
45 "overlay_h", "h", ///< height of the overlay video
52 VAR_OVERLAY_W, VAR_OW,
53 VAR_OVERLAY_H, VAR_OH,
71 int x, y; ///< position of overlayed picture
74 uint8_t main_is_packed_rgb;
75 uint8_t main_rgba_map[4];
76 uint8_t main_has_alpha;
77 uint8_t overlay_is_packed_rgb;
78 uint8_t overlay_rgba_map[4];
79 uint8_t overlay_has_alpha;
81 AVFilterBufferRef *overpicref, *overpicref_next;
83 int main_pix_step[4]; ///< steps per pixel for each plane of the main output
84 int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
85 int hsub, vsub; ///< chroma subsampling values
87 char *x_expr, *y_expr;
90 #define OFFSET(x) offsetof(OverlayContext, x)
92 static const AVOption overlay_options[] = {
93 { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
94 { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
95 {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
99 static const char *overlay_get_name(void *ctx)
104 static const AVClass overlay_class = {
110 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
112 OverlayContext *over = ctx->priv;
113 char *args1 = av_strdup(args);
114 char *expr, *bufptr = NULL;
117 over->class = &overlay_class;
118 av_opt_set_defaults(over);
120 if (expr = av_strtok(args1, ":", &bufptr)) {
121 av_free(over->x_expr);
122 if (!(over->x_expr = av_strdup(expr))) {
123 ret = AVERROR(ENOMEM);
127 if (expr = av_strtok(NULL, ":", &bufptr)) {
128 av_free(over->y_expr);
129 if (!(over->y_expr = av_strdup(expr))) {
130 ret = AVERROR(ENOMEM);
135 if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
143 static av_cold void uninit(AVFilterContext *ctx)
145 OverlayContext *over = ctx->priv;
147 av_freep(&over->x_expr);
148 av_freep(&over->y_expr);
150 if (over->overpicref)
151 avfilter_unref_buffer(over->overpicref);
152 if (over->overpicref_next)
153 avfilter_unref_buffer(over->overpicref_next);
156 static int query_formats(AVFilterContext *ctx)
158 OverlayContext *over = ctx->priv;
160 /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
161 const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
162 const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
163 const enum PixelFormat main_pix_fmts_rgb[] = {
164 PIX_FMT_ARGB, PIX_FMT_RGBA,
165 PIX_FMT_ABGR, PIX_FMT_BGRA,
166 PIX_FMT_RGB24, PIX_FMT_BGR24,
169 const enum PixelFormat overlay_pix_fmts_rgb[] = {
170 PIX_FMT_ARGB, PIX_FMT_RGBA,
171 PIX_FMT_ABGR, PIX_FMT_BGRA,
175 AVFilterFormats *main_formats;
176 AVFilterFormats *overlay_formats;
178 if (over->allow_packed_rgb) {
179 main_formats = avfilter_make_format_list(main_pix_fmts_rgb);
180 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_rgb);
182 main_formats = avfilter_make_format_list(main_pix_fmts_yuv);
183 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_yuv);
186 avfilter_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
187 avfilter_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
188 avfilter_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
193 static const enum PixelFormat alpha_pix_fmts[] = {
194 PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
195 PIX_FMT_BGRA, PIX_FMT_NONE
198 static int config_input_main(AVFilterLink *inlink)
200 OverlayContext *over = inlink->dst->priv;
201 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
203 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
205 over->hsub = pix_desc->log2_chroma_w;
206 over->vsub = pix_desc->log2_chroma_h;
208 over->main_is_packed_rgb =
209 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
210 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
214 static int config_input_overlay(AVFilterLink *inlink)
216 AVFilterContext *ctx = inlink->dst;
217 OverlayContext *over = inlink->dst->priv;
219 double var_values[VAR_VARS_NB], res;
221 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
223 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
225 /* Finish the configuration by evaluating the expressions
226 now when both inputs are configured. */
227 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
228 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
229 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
230 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
232 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
233 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
236 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
237 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
240 /* x may depend on y */
241 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
242 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
246 over->overlay_is_packed_rgb =
247 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
248 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
250 av_log(ctx, AV_LOG_INFO,
251 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
252 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
253 av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
255 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
256 av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
258 if (over->x < 0 || over->y < 0 ||
259 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
260 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
261 av_log(ctx, AV_LOG_ERROR,
262 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
264 (int)(over->x + var_values[VAR_OVERLAY_W]),
265 (int)(over->y + var_values[VAR_OVERLAY_H]),
266 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
267 return AVERROR(EINVAL);
272 av_log(NULL, AV_LOG_ERROR,
273 "Error when evaluating the expression '%s'\n", expr);
277 static int config_output(AVFilterLink *outlink)
279 AVFilterContext *ctx = outlink->src;
281 // common timebase computation:
282 AVRational tb1 = ctx->inputs[MAIN ]->time_base;
283 AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
284 AVRational *tb = &ctx->outputs[0]->time_base;
285 exact = av_reduce(&tb->num, &tb->den,
286 av_gcd((int64_t)tb1.num * tb2.den,
287 (int64_t)tb2.num * tb1.den),
288 (int64_t)tb1.den * tb2.den, INT_MAX);
289 av_log(ctx, AV_LOG_INFO,
290 "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
291 tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
293 av_log(ctx, AV_LOG_WARNING,
294 "Timestamp conversion inexact, timestamp information loss may occurr\n");
296 outlink->w = ctx->inputs[MAIN]->w;
297 outlink->h = ctx->inputs[MAIN]->h;
302 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
304 return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
307 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
309 AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
310 AVFilterContext *ctx = inlink->dst;
311 OverlayContext *over = ctx->priv;
312 av_unused AVFilterLink *outlink = ctx->outputs[0];
314 inlink->dst->outputs[0]->out_buf = outpicref;
315 outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
316 ctx->outputs[0]->time_base);
318 if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
319 if (!over->overpicref_next)
320 avfilter_request_frame(ctx->inputs[OVERLAY]);
322 if (over->overpicref && over->overpicref_next &&
323 over->overpicref_next->pts <= outpicref->pts) {
324 avfilter_unref_buffer(over->overpicref);
325 over->overpicref = over->overpicref_next;
326 over->overpicref_next = NULL;
330 av_dlog(ctx, "main_pts:%s main_pts_time:%s",
331 av_ts2str(outpicref->pts), av_ts2timestr(outpicref->pts, &outlink->time_base));
332 if (over->overpicref)
333 av_dlog(ctx, " over_pts:%s over_pts_time:%s",
334 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
337 avfilter_start_frame(inlink->dst->outputs[0], outpicref);
340 static void start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
342 AVFilterContext *ctx = inlink->dst;
343 OverlayContext *over = ctx->priv;
345 inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
346 ctx->outputs[0]->time_base);
348 if (!over->overpicref) over->overpicref = inpicref;
349 else over->overpicref_next = inpicref;
352 // divide by 255 and round to nearest
353 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
354 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
356 static void blend_slice(AVFilterContext *ctx,
357 AVFilterBufferRef *dst, AVFilterBufferRef *src,
358 int x, int y, int w, int h,
359 int slice_y, int slice_w, int slice_h)
361 OverlayContext *over = ctx->priv;
364 int overlay_end_y = y+h;
365 int slice_end_y = slice_y+slice_h;
368 width = FFMIN(slice_w - x, w);
369 end_y = FFMIN(slice_end_y, overlay_end_y);
370 start_y = FFMAX(y, slice_y);
371 height = end_y - start_y;
373 if (over->main_is_packed_rgb) {
374 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
375 start_y * dst->linesize[0];
376 uint8_t *sp = src->data[0];
377 uint8_t alpha; ///< the amount of overlay to blend on to main
378 const int dr = over->main_rgba_map[R];
379 const int dg = over->main_rgba_map[G];
380 const int db = over->main_rgba_map[B];
381 const int da = over->main_rgba_map[A];
382 const int dstep = over->main_pix_step[0];
383 const int sr = over->overlay_rgba_map[R];
384 const int sg = over->overlay_rgba_map[G];
385 const int sb = over->overlay_rgba_map[B];
386 const int sa = over->overlay_rgba_map[A];
387 const int sstep = over->overlay_pix_step[0];
388 const int main_has_alpha = over->main_has_alpha;
390 sp += (slice_y - y) * src->linesize[0];
391 for (i = 0; i < height; i++) {
392 uint8_t *d = dp, *s = sp;
393 for (j = 0; j < width; j++) {
396 // if the main channel has an alpha channel, alpha has to be calculated
397 // to create an un-premultiplied (straight) alpha value
398 if (main_has_alpha && alpha != 0 && alpha != 255) {
399 // apply the general equation:
400 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
402 // the next line is a faster version of: 255 * 255 * alpha
403 ( (alpha << 16) - (alpha << 9) + alpha )
405 // the next line is a faster version of: 255 * (alpha + d[da])
406 ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
419 // main_value = main_value * (1 - alpha) + overlay_value * alpha
420 // since alpha is in the range 0-255, the result must divided by 255
421 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
422 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
423 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
425 if (main_has_alpha) {
433 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
434 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
440 dp += dst->linesize[0];
441 sp += src->linesize[0];
444 for (i = 0; i < 3; i++) {
445 int hsub = i ? over->hsub : 0;
446 int vsub = i ? over->vsub : 0;
447 uint8_t *dp = dst->data[i] + (x >> hsub) +
448 (start_y >> vsub) * dst->linesize[i];
449 uint8_t *sp = src->data[i];
450 uint8_t *ap = src->data[3];
451 int wp = FFALIGN(width, 1<<hsub) >> hsub;
452 int hp = FFALIGN(height, 1<<vsub) >> vsub;
454 sp += ((slice_y - y) >> vsub) * src->linesize[i];
455 ap += (slice_y - y) * src->linesize[3];
457 for (j = 0; j < hp; j++) {
458 uint8_t *d = dp, *s = sp, *a = ap;
459 for (k = 0; k < wp; k++) {
460 // average alpha for color components, improve quality
461 int alpha_v, alpha_h, alpha;
462 if (hsub && vsub && j+1 < hp && k+1 < wp) {
463 alpha = (a[0] + a[src->linesize[3]] +
464 a[1] + a[src->linesize[3]+1]) >> 2;
465 } else if (hsub || vsub) {
466 alpha_h = hsub && k+1 < wp ?
467 (a[0] + a[1]) >> 1 : a[0];
468 alpha_v = vsub && j+1 < hp ?
469 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
470 alpha = (alpha_v + alpha_h) >> 1;
473 *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
478 dp += dst->linesize[i];
479 sp += src->linesize[i];
480 ap += (1 << vsub) * src->linesize[3];
486 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
488 AVFilterContext *ctx = inlink->dst;
489 AVFilterLink *outlink = ctx->outputs[0];
490 AVFilterBufferRef *outpicref = outlink->out_buf;
491 OverlayContext *over = ctx->priv;
493 if (over->overpicref &&
494 !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
495 y+h < over->y || y >= over->y + over->overpicref->video->h)) {
496 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
497 over->overpicref->video->w, over->overpicref->video->h,
498 y, outpicref->video->w, h);
500 avfilter_draw_slice(outlink, y, h, slice_dir);
503 static void end_frame(AVFilterLink *inlink)
505 avfilter_end_frame(inlink->dst->outputs[0]);
506 avfilter_unref_buffer(inlink->cur_buf);
509 static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
511 static void null_end_frame(AVFilterLink *inlink) { }
513 static int poll_frame(AVFilterLink *link)
515 AVFilterContext *s = link->src;
516 OverlayContext *over = s->priv;
517 int ret = avfilter_poll_frame(s->inputs[OVERLAY]);
519 if (ret == AVERROR_EOF)
520 ret = !!over->overpicref;
522 return ret && avfilter_poll_frame(s->inputs[MAIN]);
525 AVFilter avfilter_vf_overlay = {
527 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
532 .priv_size = sizeof(OverlayContext),
534 .query_formats = query_formats,
536 .inputs = (const AVFilterPad[]) {{ .name = "main",
537 .type = AVMEDIA_TYPE_VIDEO,
538 .start_frame = start_frame,
539 .get_video_buffer= get_video_buffer,
540 .config_props = config_input_main,
541 .draw_slice = draw_slice,
542 .end_frame = end_frame,
543 .min_perms = AV_PERM_READ,
544 .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
546 .type = AVMEDIA_TYPE_VIDEO,
547 .start_frame = start_frame_overlay,
548 .config_props = config_input_overlay,
549 .draw_slice = null_draw_slice,
550 .end_frame = null_end_frame,
551 .min_perms = AV_PERM_READ,
552 .rej_perms = AV_PERM_REUSE2, },
554 .outputs = (const AVFilterPad[]) {{ .name = "default",
555 .type = AVMEDIA_TYPE_VIDEO,
556 .config_props = config_output,
557 .poll_frame = poll_frame },