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/eval.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/pixdesc.h"
36 #include "libavutil/imgutils.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/timestamp.h"
40 #include "bufferqueue.h"
41 #include "drawutils.h"
44 static const char *const var_names[] = {
45 "main_w", "W", ///< width of the main video
46 "main_h", "H", ///< height of the main video
47 "overlay_w", "w", ///< width of the overlay video
48 "overlay_h", "h", ///< height of the overlay video
55 VAR_OVERLAY_W, VAR_OW,
56 VAR_OVERLAY_H, VAR_OH,
74 int x, y; ///< position of overlayed picture
77 uint8_t frame_requested;
79 uint8_t main_is_packed_rgb;
80 uint8_t main_rgba_map[4];
81 uint8_t main_has_alpha;
82 uint8_t overlay_is_packed_rgb;
83 uint8_t overlay_rgba_map[4];
84 uint8_t overlay_has_alpha;
86 AVFilterBufferRef *overpicref;
87 struct FFBufQueue queue_main;
88 struct FFBufQueue queue_over;
90 int main_pix_step[4]; ///< steps per pixel for each plane of the main output
91 int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
92 int hsub, vsub; ///< chroma subsampling values
94 char *x_expr, *y_expr;
97 #define OFFSET(x) offsetof(OverlayContext, x)
99 static const AVOption overlay_options[] = {
100 { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
101 { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
102 {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
106 static const AVClass overlay_class = {
108 av_default_item_name,
112 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
114 OverlayContext *over = ctx->priv;
115 char *args1 = av_strdup(args);
116 char *expr, *bufptr = NULL;
119 over->class = &overlay_class;
120 av_opt_set_defaults(over);
122 if (expr = av_strtok(args1, ":", &bufptr)) {
123 av_free(over->x_expr);
124 if (!(over->x_expr = av_strdup(expr))) {
125 ret = AVERROR(ENOMEM);
129 if (expr = av_strtok(NULL, ":", &bufptr)) {
130 av_free(over->y_expr);
131 if (!(over->y_expr = av_strdup(expr))) {
132 ret = AVERROR(ENOMEM);
137 if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
145 static av_cold void uninit(AVFilterContext *ctx)
147 OverlayContext *over = ctx->priv;
149 av_freep(&over->x_expr);
150 av_freep(&over->y_expr);
152 if (over->overpicref)
153 avfilter_unref_buffer(over->overpicref);
154 ff_bufqueue_discard_all(&over->queue_main);
155 ff_bufqueue_discard_all(&over->queue_over);
158 static int query_formats(AVFilterContext *ctx)
160 OverlayContext *over = ctx->priv;
162 /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
163 const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
164 const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
165 const enum PixelFormat main_pix_fmts_rgb[] = {
166 PIX_FMT_ARGB, PIX_FMT_RGBA,
167 PIX_FMT_ABGR, PIX_FMT_BGRA,
168 PIX_FMT_RGB24, PIX_FMT_BGR24,
171 const enum PixelFormat overlay_pix_fmts_rgb[] = {
172 PIX_FMT_ARGB, PIX_FMT_RGBA,
173 PIX_FMT_ABGR, PIX_FMT_BGRA,
177 AVFilterFormats *main_formats;
178 AVFilterFormats *overlay_formats;
180 if (over->allow_packed_rgb) {
181 main_formats = ff_make_format_list(main_pix_fmts_rgb);
182 overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
184 main_formats = ff_make_format_list(main_pix_fmts_yuv);
185 overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv);
188 ff_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
189 ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
190 ff_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
195 static const enum PixelFormat alpha_pix_fmts[] = {
196 PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
197 PIX_FMT_BGRA, PIX_FMT_NONE
200 static int config_input_main(AVFilterLink *inlink)
202 OverlayContext *over = inlink->dst->priv;
203 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
205 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
207 over->hsub = pix_desc->log2_chroma_w;
208 over->vsub = pix_desc->log2_chroma_h;
210 over->main_is_packed_rgb =
211 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
212 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
216 static int config_input_overlay(AVFilterLink *inlink)
218 AVFilterContext *ctx = inlink->dst;
219 OverlayContext *over = inlink->dst->priv;
221 double var_values[VAR_VARS_NB], res;
223 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
225 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
227 /* Finish the configuration by evaluating the expressions
228 now when both inputs are configured. */
229 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
230 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
231 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
232 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
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)
238 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
239 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
242 /* x may depend on y */
243 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
244 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
248 over->overlay_is_packed_rgb =
249 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
250 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
252 av_log(ctx, AV_LOG_INFO,
253 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
254 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
255 av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
257 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
258 av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
260 if (over->x < 0 || over->y < 0 ||
261 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
262 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
263 av_log(ctx, AV_LOG_ERROR,
264 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
266 (int)(over->x + var_values[VAR_OVERLAY_W]),
267 (int)(over->y + var_values[VAR_OVERLAY_H]),
268 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
269 return AVERROR(EINVAL);
274 av_log(NULL, AV_LOG_ERROR,
275 "Error when evaluating the expression '%s'\n", expr);
279 static int config_output(AVFilterLink *outlink)
281 AVFilterContext *ctx = outlink->src;
283 // common timebase computation:
284 AVRational tb1 = ctx->inputs[MAIN ]->time_base;
285 AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
286 AVRational *tb = &ctx->outputs[0]->time_base;
287 exact = av_reduce(&tb->num, &tb->den,
288 av_gcd((int64_t)tb1.num * tb2.den,
289 (int64_t)tb2.num * tb1.den),
290 (int64_t)tb1.den * tb2.den, INT_MAX);
291 av_log(ctx, AV_LOG_INFO,
292 "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
293 tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
295 av_log(ctx, AV_LOG_WARNING,
296 "Timestamp conversion inexact, timestamp information loss may occurr\n");
298 outlink->w = ctx->inputs[MAIN]->w;
299 outlink->h = ctx->inputs[MAIN]->h;
304 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
306 return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
309 // divide by 255 and round to nearest
310 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
311 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
313 static void blend_slice(AVFilterContext *ctx,
314 AVFilterBufferRef *dst, AVFilterBufferRef *src,
315 int x, int y, int w, int h,
316 int slice_y, int slice_w, int slice_h)
318 OverlayContext *over = ctx->priv;
321 int overlay_end_y = y+h;
322 int slice_end_y = slice_y+slice_h;
325 width = FFMIN(slice_w - x, w);
326 end_y = FFMIN(slice_end_y, overlay_end_y);
327 start_y = FFMAX(y, slice_y);
328 height = end_y - start_y;
330 if (over->main_is_packed_rgb) {
331 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
332 start_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;
347 sp += (slice_y - y) * src->linesize[0];
348 for (i = 0; i < height; i++) {
349 uint8_t *d = dp, *s = sp;
350 for (j = 0; j < width; j++) {
353 // if the main channel has an alpha channel, alpha has to be calculated
354 // to create an un-premultiplied (straight) alpha value
355 if (main_has_alpha && alpha != 0 && alpha != 255) {
356 // apply the general equation:
357 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
359 // the next line is a faster version of: 255 * 255 * alpha
360 ( (alpha << 16) - (alpha << 9) + alpha )
362 // the next line is a faster version of: 255 * (alpha + d[da])
363 ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
376 // main_value = main_value * (1 - alpha) + overlay_value * alpha
377 // since alpha is in the range 0-255, the result must divided by 255
378 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
379 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
380 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
382 if (main_has_alpha) {
390 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
391 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
397 dp += dst->linesize[0];
398 sp += src->linesize[0];
401 for (i = 0; i < 3; i++) {
402 int hsub = i ? over->hsub : 0;
403 int vsub = i ? over->vsub : 0;
404 uint8_t *dp = dst->data[i] + (x >> hsub) +
405 (start_y >> vsub) * dst->linesize[i];
406 uint8_t *sp = src->data[i];
407 uint8_t *ap = src->data[3];
408 int wp = FFALIGN(width, 1<<hsub) >> hsub;
409 int hp = FFALIGN(height, 1<<vsub) >> vsub;
411 sp += ((slice_y - y) >> vsub) * src->linesize[i];
412 ap += (slice_y - y) * src->linesize[3];
414 for (j = 0; j < hp; j++) {
415 uint8_t *d = dp, *s = sp, *a = ap;
416 for (k = 0; k < wp; k++) {
417 // average alpha for color components, improve quality
418 int alpha_v, alpha_h, alpha;
419 if (hsub && vsub && j+1 < hp && k+1 < wp) {
420 alpha = (a[0] + a[src->linesize[3]] +
421 a[1] + a[src->linesize[3]+1]) >> 2;
422 } else if (hsub || vsub) {
423 alpha_h = hsub && k+1 < wp ?
424 (a[0] + a[1]) >> 1 : a[0];
425 alpha_v = vsub && j+1 < hp ?
426 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
427 alpha = (alpha_v + alpha_h) >> 1;
430 *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
435 dp += dst->linesize[i];
436 sp += src->linesize[i];
437 ap += (1 << vsub) * src->linesize[3];
443 static int try_start_frame(AVFilterContext *ctx, AVFilterBufferRef *mainpic)
445 OverlayContext *over = ctx->priv;
446 AVFilterLink *outlink = ctx->outputs[0];
447 AVFilterBufferRef *next_overpic, *outpicref;
449 /* Discard obsolete overlay frames: if there is a next frame with pts is
450 * before the main frame, we can drop the current overlay. */
452 next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
453 if (!next_overpic || next_overpic->pts > mainpic->pts)
455 ff_bufqueue_get(&over->queue_over);
456 avfilter_unref_buffer(over->overpicref);
457 over->overpicref = next_overpic;
459 /* If there is no next frame and no EOF and the overlay frame is before
460 * the main frame, we can not know yet if it will be superseded. */
461 if (!over->queue_over.available && !over->overlay_eof &&
462 (!over->overpicref || over->overpicref->pts < mainpic->pts))
463 return AVERROR(EAGAIN);
464 /* At this point, we know that the current overlay frame extends to the
465 * time of the main frame. */
466 outlink->out_buf = outpicref = avfilter_ref_buffer(mainpic, ~0);
468 av_dlog(ctx, "main_pts:%s main_pts_time:%s",
469 av_ts2str(outpicref->pts), av_ts2timestr(outpicref->pts, &outlink->time_base));
470 if (over->overpicref)
471 av_dlog(ctx, " over_pts:%s over_pts_time:%s",
472 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
475 ff_start_frame(ctx->outputs[0], avfilter_ref_buffer(outpicref, ~0));
476 over->frame_requested = 0;
480 static int try_start_next_frame(AVFilterContext *ctx)
482 OverlayContext *over = ctx->priv;
483 AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
484 if (!next_mainpic || try_start_frame(ctx, next_mainpic) < 0)
485 return AVERROR(EAGAIN);
486 avfilter_unref_buffer(ff_bufqueue_get(&over->queue_main));
490 static int try_push_frame(AVFilterContext *ctx)
492 OverlayContext *over = ctx->priv;
493 AVFilterLink *outlink = ctx->outputs[0];
494 AVFilterBufferRef *outpicref = outlink->out_buf;
496 if (try_start_next_frame(ctx) < 0)
497 return AVERROR(EAGAIN);
498 outpicref = outlink->out_buf;
499 if (over->overpicref)
500 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
501 over->overpicref->video->w, over->overpicref->video->h,
502 0, outpicref->video->w, outpicref->video->h);
503 ff_draw_slice(outlink, 0, outpicref->video->h, +1);
504 avfilter_unref_bufferp(&outlink->out_buf);
505 ff_end_frame(outlink);
509 static void flush_frames(AVFilterContext *ctx)
511 while (!try_push_frame(ctx));
514 static void start_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
516 AVFilterContext *ctx = inlink->dst;
517 OverlayContext *over = ctx->priv;
520 inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[MAIN]->time_base,
521 ctx->outputs[0]->time_base);
522 if (try_start_frame(ctx, inpicref) < 0)
523 ff_bufqueue_add(ctx, &over->queue_main, inpicref);
526 static void draw_slice_main(AVFilterLink *inlink, int y, int h, int slice_dir)
528 AVFilterContext *ctx = inlink->dst;
529 OverlayContext *over = ctx->priv;
530 AVFilterLink *outlink = ctx->outputs[0];
531 AVFilterBufferRef *outpicref = outlink->out_buf;
535 if (over->overpicref &&
536 y + h > over->y && y < over->y + over->overpicref->video->h) {
537 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
538 over->overpicref->video->w, over->overpicref->video->h,
539 y, outpicref->video->w, h);
541 ff_draw_slice(outlink, y, h, slice_dir);
544 static void end_frame_main(AVFilterLink *inlink)
546 AVFilterContext *ctx = inlink->dst;
547 AVFilterLink *outlink = ctx->outputs[0];
548 AVFilterBufferRef *outpicref = outlink->out_buf;
553 avfilter_unref_bufferp(&inlink->cur_buf);
554 avfilter_unref_bufferp(&outlink->out_buf);
555 ff_end_frame(ctx->outputs[0]);
558 static void start_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
562 static void end_frame_over(AVFilterLink *inlink)
564 AVFilterContext *ctx = inlink->dst;
565 OverlayContext *over = ctx->priv;
566 AVFilterBufferRef *inpicref = inlink->cur_buf;
569 inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
570 ctx->outputs[0]->time_base);
571 ff_bufqueue_add(ctx, &over->queue_over, inpicref);
575 static int request_frame(AVFilterLink *outlink)
577 AVFilterContext *ctx = outlink->src;
578 OverlayContext *over = ctx->priv;
581 if (!try_push_frame(ctx))
583 over->frame_requested = 1;
584 while (over->frame_requested) {
585 /* TODO if we had a frame duration, we could guess more accurately */
586 input = !over->overlay_eof && (over->queue_main.available ||
587 over->queue_over.available < 2) ?
589 ret = ff_request_frame(ctx->inputs[input]);
590 /* EOF on main is reported immediately */
591 if (ret == AVERROR_EOF && input == OVERLAY) {
592 over->overlay_eof = 1;
593 if (!try_start_next_frame(ctx))
595 ret = 0; /* continue requesting frames on main */
603 static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
605 AVFilter avfilter_vf_overlay = {
607 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
612 .priv_size = sizeof(OverlayContext),
614 .query_formats = query_formats,
616 .inputs = (const AVFilterPad[]) {{ .name = "main",
617 .type = AVMEDIA_TYPE_VIDEO,
618 .get_video_buffer= get_video_buffer,
619 .config_props = config_input_main,
620 .start_frame = start_frame_main,
621 .draw_slice = draw_slice_main,
622 .end_frame = end_frame_main,
623 .min_perms = AV_PERM_READ,
624 .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
626 .type = AVMEDIA_TYPE_VIDEO,
627 .config_props = config_input_overlay,
628 .start_frame = start_frame_over,
629 .draw_slice = null_draw_slice,
630 .end_frame = end_frame_over,
631 .min_perms = AV_PERM_READ,
632 .rej_perms = AV_PERM_REUSE2, },
634 .outputs = (const AVFilterPad[]) {{ .name = "default",
635 .type = AVMEDIA_TYPE_VIDEO,
636 .config_props = config_output,
637 .request_frame = request_frame, },