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 "bufferqueue.h"
40 #include "drawutils.h"
42 static const char *const var_names[] = {
43 "main_w", "W", ///< width of the main video
44 "main_h", "H", ///< height of the main video
45 "overlay_w", "w", ///< width of the overlay video
46 "overlay_h", "h", ///< height of the overlay video
53 VAR_OVERLAY_W, VAR_OW,
54 VAR_OVERLAY_H, VAR_OH,
72 int x, y; ///< position of overlayed picture
75 uint8_t frame_requested;
77 uint8_t main_is_packed_rgb;
78 uint8_t main_rgba_map[4];
79 uint8_t main_has_alpha;
80 uint8_t overlay_is_packed_rgb;
81 uint8_t overlay_rgba_map[4];
82 uint8_t overlay_has_alpha;
84 AVFilterBufferRef *overpicref;
85 struct FFBufQueue queue_main;
86 struct FFBufQueue queue_over;
88 int main_pix_step[4]; ///< steps per pixel for each plane of the main output
89 int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
90 int hsub, vsub; ///< chroma subsampling values
92 char *x_expr, *y_expr;
95 #define OFFSET(x) offsetof(OverlayContext, x)
97 static const AVOption overlay_options[] = {
98 { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
99 { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
100 {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
104 static const char *overlay_get_name(void *ctx)
109 static const AVClass overlay_class = {
115 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
117 OverlayContext *over = ctx->priv;
118 char *args1 = av_strdup(args);
119 char *expr, *bufptr = NULL;
122 over->class = &overlay_class;
123 av_opt_set_defaults(over);
125 if (expr = av_strtok(args1, ":", &bufptr)) {
126 av_free(over->x_expr);
127 if (!(over->x_expr = av_strdup(expr))) {
128 ret = AVERROR(ENOMEM);
132 if (expr = av_strtok(NULL, ":", &bufptr)) {
133 av_free(over->y_expr);
134 if (!(over->y_expr = av_strdup(expr))) {
135 ret = AVERROR(ENOMEM);
140 if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
148 static av_cold void uninit(AVFilterContext *ctx)
150 OverlayContext *over = ctx->priv;
152 av_freep(&over->x_expr);
153 av_freep(&over->y_expr);
155 if (over->overpicref)
156 avfilter_unref_buffer(over->overpicref);
157 ff_bufqueue_discard_all(&over->queue_main);
158 ff_bufqueue_discard_all(&over->queue_over);
161 static int query_formats(AVFilterContext *ctx)
163 OverlayContext *over = ctx->priv;
165 /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
166 const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
167 const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
168 const enum PixelFormat main_pix_fmts_rgb[] = {
169 PIX_FMT_ARGB, PIX_FMT_RGBA,
170 PIX_FMT_ABGR, PIX_FMT_BGRA,
171 PIX_FMT_RGB24, PIX_FMT_BGR24,
174 const enum PixelFormat overlay_pix_fmts_rgb[] = {
175 PIX_FMT_ARGB, PIX_FMT_RGBA,
176 PIX_FMT_ABGR, PIX_FMT_BGRA,
180 AVFilterFormats *main_formats;
181 AVFilterFormats *overlay_formats;
183 if (over->allow_packed_rgb) {
184 main_formats = avfilter_make_format_list(main_pix_fmts_rgb);
185 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_rgb);
187 main_formats = avfilter_make_format_list(main_pix_fmts_yuv);
188 overlay_formats = avfilter_make_format_list(overlay_pix_fmts_yuv);
191 avfilter_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
192 avfilter_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
193 avfilter_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
198 static const enum PixelFormat alpha_pix_fmts[] = {
199 PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
200 PIX_FMT_BGRA, PIX_FMT_NONE
203 static int config_input_main(AVFilterLink *inlink)
205 OverlayContext *over = inlink->dst->priv;
206 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
208 av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
210 over->hsub = pix_desc->log2_chroma_w;
211 over->vsub = pix_desc->log2_chroma_h;
213 over->main_is_packed_rgb =
214 ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
215 over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
219 static int config_input_overlay(AVFilterLink *inlink)
221 AVFilterContext *ctx = inlink->dst;
222 OverlayContext *over = inlink->dst->priv;
224 double var_values[VAR_VARS_NB], res;
226 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
228 av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
230 /* Finish the configuration by evaluating the expressions
231 now when both inputs are configured. */
232 var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
233 var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
234 var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
235 var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
237 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
238 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
241 if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
242 NULL, NULL, NULL, NULL, NULL, 0, ctx)))
245 /* x may depend on y */
246 if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
247 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
251 over->overlay_is_packed_rgb =
252 ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
253 over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
255 av_log(ctx, AV_LOG_INFO,
256 "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
257 ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
258 av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
260 ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
261 av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
263 if (over->x < 0 || over->y < 0 ||
264 over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
265 over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
266 av_log(ctx, AV_LOG_ERROR,
267 "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
269 (int)(over->x + var_values[VAR_OVERLAY_W]),
270 (int)(over->y + var_values[VAR_OVERLAY_H]),
271 (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
272 return AVERROR(EINVAL);
277 av_log(NULL, AV_LOG_ERROR,
278 "Error when evaluating the expression '%s'\n", expr);
282 static int config_output(AVFilterLink *outlink)
284 AVFilterContext *ctx = outlink->src;
286 // common timebase computation:
287 AVRational tb1 = ctx->inputs[MAIN ]->time_base;
288 AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
289 AVRational *tb = &ctx->outputs[0]->time_base;
290 exact = av_reduce(&tb->num, &tb->den,
291 av_gcd((int64_t)tb1.num * tb2.den,
292 (int64_t)tb2.num * tb1.den),
293 (int64_t)tb1.den * tb2.den, INT_MAX);
294 av_log(ctx, AV_LOG_INFO,
295 "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
296 tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
298 av_log(ctx, AV_LOG_WARNING,
299 "Timestamp conversion inexact, timestamp information loss may occurr\n");
301 outlink->w = ctx->inputs[MAIN]->w;
302 outlink->h = ctx->inputs[MAIN]->h;
307 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
309 return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
312 // divide by 255 and round to nearest
313 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
314 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
316 static void blend_slice(AVFilterContext *ctx,
317 AVFilterBufferRef *dst, AVFilterBufferRef *src,
318 int x, int y, int w, int h,
319 int slice_y, int slice_w, int slice_h)
321 OverlayContext *over = ctx->priv;
324 int overlay_end_y = y+h;
325 int slice_end_y = slice_y+slice_h;
328 width = FFMIN(slice_w - x, w);
329 end_y = FFMIN(slice_end_y, overlay_end_y);
330 start_y = FFMAX(y, slice_y);
331 height = end_y - start_y;
333 if (over->main_is_packed_rgb) {
334 uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
335 start_y * dst->linesize[0];
336 uint8_t *sp = src->data[0];
337 uint8_t alpha; ///< the amount of overlay to blend on to main
338 const int dr = over->main_rgba_map[R];
339 const int dg = over->main_rgba_map[G];
340 const int db = over->main_rgba_map[B];
341 const int da = over->main_rgba_map[A];
342 const int dstep = over->main_pix_step[0];
343 const int sr = over->overlay_rgba_map[R];
344 const int sg = over->overlay_rgba_map[G];
345 const int sb = over->overlay_rgba_map[B];
346 const int sa = over->overlay_rgba_map[A];
347 const int sstep = over->overlay_pix_step[0];
348 const int main_has_alpha = over->main_has_alpha;
350 sp += (slice_y - y) * src->linesize[0];
351 for (i = 0; i < height; i++) {
352 uint8_t *d = dp, *s = sp;
353 for (j = 0; j < width; j++) {
356 // if the main channel has an alpha channel, alpha has to be calculated
357 // to create an un-premultiplied (straight) alpha value
358 if (main_has_alpha && alpha != 0 && alpha != 255) {
359 // apply the general equation:
360 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
362 // the next line is a faster version of: 255 * 255 * alpha
363 ( (alpha << 16) - (alpha << 9) + alpha )
365 // the next line is a faster version of: 255 * (alpha + d[da])
366 ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
379 // main_value = main_value * (1 - alpha) + overlay_value * alpha
380 // since alpha is in the range 0-255, the result must divided by 255
381 d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
382 d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
383 d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
385 if (main_has_alpha) {
393 // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
394 d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
400 dp += dst->linesize[0];
401 sp += src->linesize[0];
404 for (i = 0; i < 3; i++) {
405 int hsub = i ? over->hsub : 0;
406 int vsub = i ? over->vsub : 0;
407 uint8_t *dp = dst->data[i] + (x >> hsub) +
408 (start_y >> vsub) * dst->linesize[i];
409 uint8_t *sp = src->data[i];
410 uint8_t *ap = src->data[3];
411 int wp = FFALIGN(width, 1<<hsub) >> hsub;
412 int hp = FFALIGN(height, 1<<vsub) >> vsub;
414 sp += ((slice_y - y) >> vsub) * src->linesize[i];
415 ap += (slice_y - y) * src->linesize[3];
417 for (j = 0; j < hp; j++) {
418 uint8_t *d = dp, *s = sp, *a = ap;
419 for (k = 0; k < wp; k++) {
420 // average alpha for color components, improve quality
421 int alpha_v, alpha_h, alpha;
422 if (hsub && vsub && j+1 < hp && k+1 < wp) {
423 alpha = (a[0] + a[src->linesize[3]] +
424 a[1] + a[src->linesize[3]+1]) >> 2;
425 } else if (hsub || vsub) {
426 alpha_h = hsub && k+1 < wp ?
427 (a[0] + a[1]) >> 1 : a[0];
428 alpha_v = vsub && j+1 < hp ?
429 (a[0] + a[src->linesize[3]]) >> 1 : a[0];
430 alpha = (alpha_v + alpha_h) >> 1;
433 *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
438 dp += dst->linesize[i];
439 sp += src->linesize[i];
440 ap += (1 << vsub) * src->linesize[3];
446 static int try_start_frame(AVFilterContext *ctx, AVFilterBufferRef *mainpic)
448 OverlayContext *over = ctx->priv;
449 AVFilterLink *outlink = ctx->outputs[0];
450 AVFilterBufferRef *next_overpic, *outpicref;
452 /* Discard obsolete overlay frames: if there is a next frame with pts is
453 * before the main frame, we can drop the current overlay. */
455 next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
456 if (!next_overpic || next_overpic->pts > mainpic->pts)
458 ff_bufqueue_get(&over->queue_over);
459 avfilter_unref_buffer(over->overpicref);
460 over->overpicref = next_overpic;
462 /* If there is no next frame and no EOF and the overlay frame is before
463 * the main frame, we can not know yet if it will be superseded. */
464 if (!over->queue_over.available && !over->overlay_eof &&
465 (!over->overpicref || over->overpicref->pts < mainpic->pts))
466 return AVERROR(EAGAIN);
467 /* At this point, we know that the current overlay frame extends to the
468 * time of the main frame. */
469 outlink->out_buf = outpicref = avfilter_ref_buffer(mainpic, ~0);
471 av_dlog(ctx, "main_pts:%s main_pts_time:%s",
472 av_ts2str(outpicref->pts), av_ts2timestr(outpicref->pts, &outlink->time_base));
473 if (over->overpicref)
474 av_dlog(ctx, " over_pts:%s over_pts_time:%s",
475 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
478 avfilter_start_frame(ctx->outputs[0], avfilter_ref_buffer(outpicref, ~0));
479 over->frame_requested = 0;
483 static int try_start_next_frame(AVFilterContext *ctx)
485 OverlayContext *over = ctx->priv;
486 AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
487 if (!next_mainpic || try_start_frame(ctx, next_mainpic) < 0)
488 return AVERROR(EAGAIN);
489 avfilter_unref_buffer(ff_bufqueue_get(&over->queue_main));
493 static int try_push_frame(AVFilterContext *ctx)
495 OverlayContext *over = ctx->priv;
496 AVFilterLink *outlink = ctx->outputs[0];
497 AVFilterBufferRef *outpicref = outlink->out_buf;
499 if (try_start_next_frame(ctx) < 0)
500 return AVERROR(EAGAIN);
501 outpicref = outlink->out_buf;
502 if (over->overpicref)
503 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
504 over->overpicref->video->w, over->overpicref->video->h,
505 0, outpicref->video->w, outpicref->video->h);
506 avfilter_draw_slice(outlink, 0, outpicref->video->h, +1);
507 avfilter_unref_bufferp(&outlink->out_buf);
508 avfilter_end_frame(outlink);
512 static void flush_frames(AVFilterContext *ctx)
514 while (!try_push_frame(ctx));
517 static void start_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
519 AVFilterContext *ctx = inlink->dst;
520 OverlayContext *over = ctx->priv;
523 inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[MAIN]->time_base,
524 ctx->outputs[0]->time_base);
525 if (try_start_frame(ctx, inpicref) < 0)
526 ff_bufqueue_add(ctx, &over->queue_main, inpicref);
529 static void draw_slice_main(AVFilterLink *inlink, int y, int h, int slice_dir)
531 AVFilterContext *ctx = inlink->dst;
532 OverlayContext *over = ctx->priv;
533 AVFilterLink *outlink = ctx->outputs[0];
534 AVFilterBufferRef *outpicref = outlink->out_buf;
538 if (over->overpicref &&
539 y + h > over->y && y < over->y + over->overpicref->video->h) {
540 blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
541 over->overpicref->video->w, over->overpicref->video->h,
542 y, outpicref->video->w, h);
544 avfilter_draw_slice(outlink, y, h, slice_dir);
547 static void end_frame_main(AVFilterLink *inlink)
549 AVFilterContext *ctx = inlink->dst;
550 AVFilterLink *outlink = ctx->outputs[0];
551 AVFilterBufferRef *outpicref = outlink->out_buf;
556 avfilter_unref_bufferp(&inlink->cur_buf);
557 avfilter_unref_bufferp(&outlink->out_buf);
558 avfilter_end_frame(ctx->outputs[0]);
561 static void start_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
565 static void end_frame_over(AVFilterLink *inlink)
567 AVFilterContext *ctx = inlink->dst;
568 OverlayContext *over = ctx->priv;
569 AVFilterBufferRef *inpicref = inlink->cur_buf;
572 inpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
573 ctx->outputs[0]->time_base);
574 ff_bufqueue_add(ctx, &over->queue_over, inpicref);
578 static int request_frame(AVFilterLink *outlink)
580 AVFilterContext *ctx = outlink->src;
581 OverlayContext *over = ctx->priv;
584 if (!try_push_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 = avfilter_request_frame(ctx->inputs[input]);
593 /* EOF on main is reported immediately */
594 if (ret == AVERROR_EOF && input == OVERLAY) {
595 over->overlay_eof = 1;
596 if (!try_start_next_frame(ctx))
598 ret = 0; /* continue requesting frames on main */
606 static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
608 AVFilter avfilter_vf_overlay = {
610 .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
615 .priv_size = sizeof(OverlayContext),
617 .query_formats = query_formats,
619 .inputs = (const AVFilterPad[]) {{ .name = "main",
620 .type = AVMEDIA_TYPE_VIDEO,
621 .get_video_buffer= get_video_buffer,
622 .config_props = config_input_main,
623 .start_frame = start_frame_main,
624 .draw_slice = draw_slice_main,
625 .end_frame = end_frame_main,
626 .min_perms = AV_PERM_READ,
627 .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
629 .type = AVMEDIA_TYPE_VIDEO,
630 .config_props = config_input_overlay,
631 .start_frame = start_frame_over,
632 .draw_slice = null_draw_slice,
633 .end_frame = end_frame_over,
634 .min_perms = AV_PERM_READ,
635 .rej_perms = AV_PERM_REUSE2, },
637 .outputs = (const AVFilterPad[]) {{ .name = "default",
638 .type = AVMEDIA_TYPE_VIDEO,
639 .config_props = config_output,
640 .request_frame = request_frame, },