FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vf_overlay.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2010 Stefano Sabatini
3  * Copyright (c) 2010 Baptiste Coudurier
4  * Copyright (c) 2007 Bobby Bingham
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22 
23 /**
24  * @file
25  * overlay one video on top of another
26  */
27 
28 /* #define DEBUG */
29 
30 #include "avfilter.h"
31 #include "formats.h"
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"
40 #include "internal.h"
41 #include "bufferqueue.h"
42 #include "drawutils.h"
43 #include "video.h"
44 
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
50  NULL
51 };
52 
53 enum var_name {
59 };
60 
61 #define MAIN 0
62 #define OVERLAY 1
63 
64 #define R 0
65 #define G 1
66 #define B 2
67 #define A 3
68 
69 #define Y 0
70 #define U 1
71 #define V 2
72 
73 typedef struct {
74  const AVClass *class;
75  int x, y; ///< position of overlayed picture
76 
81  uint8_t main_rgba_map[4];
84  uint8_t overlay_rgba_map[4];
86 
88  struct FFBufQueue queue_main;
89  struct FFBufQueue queue_over;
90 
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
94 
95  char *x_expr, *y_expr;
97 
98 #define OFFSET(x) offsetof(OverlayContext, x)
99 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
100 
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 },
105  {NULL},
106 };
107 
108 AVFILTER_DEFINE_CLASS(overlay);
109 
110 static av_cold int init(AVFilterContext *ctx, const char *args)
111 {
112  OverlayContext *over = ctx->priv;
113  static const char *shorthand[] = { "x", "y", NULL };
114 
115  over->class = &overlay_class;
116  av_opt_set_defaults(over);
117 
118  return av_opt_set_from_string(over, args, shorthand, "=", ":");
119 }
120 
121 static av_cold void uninit(AVFilterContext *ctx)
122 {
123  OverlayContext *over = ctx->priv;
124 
125  av_opt_free(over);
126 
130 }
131 
133 {
134  OverlayContext *over = ctx->priv;
135 
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[] = {
144  };
145  static const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
149  };
150 
151  AVFilterFormats *main_formats;
152  AVFilterFormats *overlay_formats;
153 
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);
157  } else {
158  main_formats = ff_make_format_list(main_pix_fmts_yuv);
159  overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv);
160  }
161 
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 );
165 
166  return 0;
167 }
168 
169 static const enum AVPixelFormat alpha_pix_fmts[] = {
172 };
173 
174 static int config_input_main(AVFilterLink *inlink)
175 {
176  OverlayContext *over = inlink->dst->priv;
177  const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
178 
180 
181  over->hsub = pix_desc->log2_chroma_w;
182  over->vsub = pix_desc->log2_chroma_h;
183 
184  over->main_is_packed_rgb =
185  ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
187  return 0;
188 }
189 
191 {
192  AVFilterContext *ctx = inlink->dst;
193  OverlayContext *over = inlink->dst->priv;
194  char *expr;
195  double var_values[VAR_VARS_NB], res;
196  int ret;
197  const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
198 
200 
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;
207 
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)
210  goto fail;
211  over->x = res;
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)))
214  goto fail;
215  over->y = res;
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)
219  goto fail;
220  over->x = res;
221 
222  over->overlay_is_packed_rgb =
223  ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
225 
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,
230  over->x, over->y,
231  ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
233 
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",
239  over->x, over->y,
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);
244  }
245  return 0;
246 
247 fail:
249  "Error when evaluating the expression '%s'\n", expr);
250  return ret;
251 }
252 
253 static int config_output(AVFilterLink *outlink)
254 {
255  AVFilterContext *ctx = outlink->src;
256 
257  outlink->w = ctx->inputs[MAIN]->w;
258  outlink->h = ctx->inputs[MAIN]->h;
259  outlink->time_base = ctx->inputs[MAIN]->time_base;
260 
261  return 0;
262 }
263 
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)
267 
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)))
273 
274 /**
275  * Blend image in src to destination buffer dst at position (x, y).
276  *
277  * It is assumed that the src image at position (x, y) is contained in
278  * dst.
279  */
280 static void blend_image(AVFilterContext *ctx,
282  int x, int y)
283 {
284  OverlayContext *over = ctx->priv;
285  int i, j, k;
286  int width = src->video->w;
287  int height = src->video->h;
288 
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++) {
308  alpha = s[sa];
309 
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);
315  }
316 
317  switch (alpha) {
318  case 0:
319  break;
320  case 255:
321  d[dr] = s[sr];
322  d[dg] = s[sg];
323  d[db] = s[sb];
324  break;
325  default:
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);
331  }
332  if (main_has_alpha) {
333  switch (alpha) {
334  case 0:
335  break;
336  case 255:
337  d[da] = s[sa];
338  break;
339  default:
340  // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
341  d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
342  }
343  }
344  d += dstep;
345  s += sstep;
346  }
347  dp += dst->linesize[0];
348  sp += src->linesize[0];
349  }
350  } else {
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++) {
360  alpha = *s;
361  if (alpha != 0 && alpha != 255) {
362  uint8_t alpha_d = *d;
363  alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
364  }
365  switch (alpha) {
366  case 0:
367  break;
368  case 255:
369  *d = *s;
370  break;
371  default:
372  // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
373  *d += FAST_DIV255((255 - *d) * *s);
374  }
375  d += 1;
376  s += 1;
377  }
378  da += dst->linesize[3];
379  sa += src->linesize[3];
380  }
381  }
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;
405  } else
406  alpha = a[0];
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
411  uint8_t alpha_d;
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;
421  } else
422  alpha_d = d[0];
423  alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
424  }
425  *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
426  s++;
427  d++;
428  a += 1 << hsub;
429  }
430  dp += dst->linesize[i];
431  sp += src->linesize[i];
432  ap += (1 << vsub) * src->linesize[3];
433  }
434  }
435  }
436 }
437 
439 {
440  OverlayContext *over = ctx->priv;
441  AVFilterLink *outlink = ctx->outputs[0];
442  AVFilterBufferRef *next_overpic;
443  int ret;
444 
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. */
447  while (1) {
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)
451  break;
452  ff_bufqueue_get(&over->queue_over);
454  over->overpicref = next_overpic;
455  }
456 
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);
463 
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));
471  av_dlog(ctx, "\n");
472 
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  over->frame_requested = 0;
477  return ret;
478 }
479 
481 {
482  OverlayContext *over = ctx->priv;
483  AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
484  int ret;
485 
486  if (!next_mainpic)
487  return AVERROR(EAGAIN);
488  if ((ret = try_filter_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
489  return ret;
490  ff_bufqueue_get(&over->queue_main);
491  return ret;
492 }
493 
495 {
496  int ret;
497 
498  while (!(ret = try_filter_next_frame(ctx)));
499  return ret == AVERROR(EAGAIN) ? 0 : ret;
500 }
501 
502 static int filter_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
503 {
504  AVFilterContext *ctx = inlink->dst;
505  OverlayContext *over = ctx->priv;
506  int ret;
507 
508  if ((ret = flush_frames(ctx)) < 0)
509  return ret;
510  if ((ret = try_filter_frame(ctx, inpicref)) < 0) {
511  if (ret != AVERROR(EAGAIN))
512  return ret;
513  ff_bufqueue_add(ctx, &over->queue_main, inpicref);
514  }
515 
516  if (!over->overpicref)
517  return 0;
518  flush_frames(ctx);
519 
520  return 0;
521 }
522 
523 static int filter_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
524 {
525  AVFilterContext *ctx = inlink->dst;
526  OverlayContext *over = ctx->priv;
527  int ret;
528 
529  if ((ret = flush_frames(ctx)) < 0)
530  return ret;
531  ff_bufqueue_add(ctx, &over->queue_over, inpicref);
532  ret = try_filter_next_frame(ctx);
533  return ret == AVERROR(EAGAIN) ? 0 : ret;
534 }
535 
536 static int request_frame(AVFilterLink *outlink)
537 {
538  AVFilterContext *ctx = outlink->src;
539  OverlayContext *over = ctx->priv;
540  int input, ret;
541 
542  if (!try_filter_next_frame(ctx))
543  return 0;
544  over->frame_requested = 1;
545  while (over->frame_requested) {
546  /* TODO if we had a frame duration, we could guess more accurately */
547  input = !over->overlay_eof && (over->queue_main.available ||
548  over->queue_over.available < 2) ?
549  OVERLAY : MAIN;
550  ret = ff_request_frame(ctx->inputs[input]);
551  /* EOF on main is reported immediately */
552  if (ret == AVERROR_EOF && input == OVERLAY) {
553  over->overlay_eof = 1;
554  if ((ret = try_filter_next_frame(ctx)) != AVERROR(EAGAIN))
555  return ret;
556  ret = 0; /* continue requesting frames on main */
557  }
558  if (ret < 0)
559  return ret;
560  }
561  return 0;
562 }
563 
565  {
566  .name = "main",
567  .type = AVMEDIA_TYPE_VIDEO,
568  .get_video_buffer = ff_null_get_video_buffer,
569  .config_props = config_input_main,
570  .filter_frame = filter_frame_main,
572  },
573  {
574  .name = "overlay",
575  .type = AVMEDIA_TYPE_VIDEO,
576  .config_props = config_input_overlay,
577  .filter_frame = filter_frame_over,
578  .min_perms = AV_PERM_READ | AV_PERM_PRESERVE,
579  },
580  { NULL }
581 };
582 
584  {
585  .name = "default",
586  .type = AVMEDIA_TYPE_VIDEO,
587  .rej_perms = AV_PERM_WRITE,
588  .config_props = config_output,
589  .request_frame = request_frame,
590  },
591  { NULL }
592 };
593 
595  .name = "overlay",
596  .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
597 
598  .init = init,
599  .uninit = uninit,
600 
601  .priv_size = sizeof(OverlayContext),
602 
604 
605  .inputs = avfilter_vf_overlay_inputs,
606  .outputs = avfilter_vf_overlay_outputs,
607  .priv_class = &overlay_class,
608 };