You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

770 lines
27KB

  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. * @file
  24. * overlay one video on top of another
  25. */
  26. /* #define DEBUG */
  27. #include "avfilter.h"
  28. #include "formats.h"
  29. #include "libavutil/common.h"
  30. #include "libavutil/eval.h"
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/imgutils.h"
  35. #include "libavutil/mathematics.h"
  36. #include "libavutil/timestamp.h"
  37. #include "internal.h"
  38. #include "bufferqueue.h"
  39. #include "drawutils.h"
  40. #include "video.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
  46. "hsub",
  47. "vsub",
  48. "x",
  49. "y",
  50. "n", ///< number of frame
  51. "pos", ///< position in the file
  52. "t", ///< timestamp expressed in seconds
  53. NULL
  54. };
  55. enum var_name {
  56. VAR_MAIN_W, VAR_MW,
  57. VAR_MAIN_H, VAR_MH,
  58. VAR_OVERLAY_W, VAR_OW,
  59. VAR_OVERLAY_H, VAR_OH,
  60. VAR_HSUB,
  61. VAR_VSUB,
  62. VAR_X,
  63. VAR_Y,
  64. VAR_N,
  65. VAR_POS,
  66. VAR_T,
  67. VAR_VARS_NB
  68. };
  69. #define MAIN 0
  70. #define OVERLAY 1
  71. #define R 0
  72. #define G 1
  73. #define B 2
  74. #define A 3
  75. #define Y 0
  76. #define U 1
  77. #define V 2
  78. typedef struct {
  79. const AVClass *class;
  80. int x, y; ///< position of overlayed picture
  81. double enable; ///< tells if blending is enabled
  82. int allow_packed_rgb;
  83. uint8_t frame_requested;
  84. uint8_t overlay_eof;
  85. uint8_t main_is_packed_rgb;
  86. uint8_t main_rgba_map[4];
  87. uint8_t main_has_alpha;
  88. uint8_t overlay_is_packed_rgb;
  89. uint8_t overlay_rgba_map[4];
  90. uint8_t overlay_has_alpha;
  91. enum OverlayFormat { OVERLAY_FORMAT_YUV420, OVERLAY_FORMAT_YUV444, OVERLAY_FORMAT_RGB, OVERLAY_FORMAT_NB} format;
  92. enum EvalMode { EVAL_MODE_INIT, EVAL_MODE_FRAME, EVAL_MODE_NB } eval_mode;
  93. AVFrame *overpicref;
  94. struct FFBufQueue queue_main;
  95. struct FFBufQueue queue_over;
  96. int main_pix_step[4]; ///< steps per pixel for each plane of the main output
  97. int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
  98. int hsub, vsub; ///< chroma subsampling values
  99. int shortest; ///< terminate stream when the shortest input terminates
  100. double var_values[VAR_VARS_NB];
  101. char *x_expr, *y_expr, *enable_expr;
  102. AVExpr *x_pexpr, *y_pexpr, *enable_pexpr;
  103. } OverlayContext;
  104. #define OFFSET(x) offsetof(OverlayContext, x)
  105. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
  106. static const AVOption overlay_options[] = {
  107. { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
  108. { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
  109. { "enable", "set expression which enables overlay", OFFSET(enable_expr), AV_OPT_TYPE_STRING, {.str = "1"}, .flags = FLAGS },
  110. { "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_FRAME}, 0, EVAL_MODE_NB-1, FLAGS, "eval" },
  111. { "init", "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT}, .flags = FLAGS, .unit = "eval" },
  112. { "frame", "eval expressions per-frame", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" },
  113. { "rgb", "force packed RGB in input and output (deprecated)", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
  114. { "shortest", "force termination when the shortest input terminates", OFFSET(shortest), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
  115. { "format", "set output format", OFFSET(format), AV_OPT_TYPE_INT, {.i64=OVERLAY_FORMAT_YUV420}, 0, OVERLAY_FORMAT_NB-1, FLAGS, "format" },
  116. { "yuv420", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV420}, .flags = FLAGS, .unit = "format" },
  117. { "yuv444", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV444}, .flags = FLAGS, .unit = "format" },
  118. { "rgb", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_RGB}, .flags = FLAGS, .unit = "format" },
  119. { NULL }
  120. };
  121. AVFILTER_DEFINE_CLASS(overlay);
  122. static av_cold int init(AVFilterContext *ctx, const char *args)
  123. {
  124. OverlayContext *over = ctx->priv;
  125. if (over->allow_packed_rgb) {
  126. av_log(ctx, AV_LOG_WARNING,
  127. "The rgb option is deprecated and is overriding the format option, use format instead\n");
  128. over->format = OVERLAY_FORMAT_RGB;
  129. }
  130. return 0;
  131. }
  132. static av_cold void uninit(AVFilterContext *ctx)
  133. {
  134. OverlayContext *over = ctx->priv;
  135. av_frame_free(&over->overpicref);
  136. ff_bufqueue_discard_all(&over->queue_main);
  137. ff_bufqueue_discard_all(&over->queue_over);
  138. av_expr_free(over->x_pexpr); over->x_pexpr = NULL;
  139. av_expr_free(over->y_pexpr); over->y_pexpr = NULL;
  140. av_expr_free(over->enable_pexpr); over->enable_pexpr = NULL;
  141. }
  142. static inline int normalize_xy(double d, int chroma_sub)
  143. {
  144. if (isnan(d))
  145. return INT_MAX;
  146. return (int)d & ~((1 << chroma_sub) - 1);
  147. }
  148. enum EvalTarget { EVAL_XY, EVAL_ENABLE, EVAL_ALL };
  149. static void eval_expr(AVFilterContext *ctx, enum EvalTarget eval_tgt)
  150. {
  151. OverlayContext *over = ctx->priv;
  152. if (eval_tgt == EVAL_XY || eval_tgt == EVAL_ALL) {
  153. over->var_values[VAR_X] = av_expr_eval(over->x_pexpr, over->var_values, NULL);
  154. over->var_values[VAR_Y] = av_expr_eval(over->y_pexpr, over->var_values, NULL);
  155. over->var_values[VAR_X] = av_expr_eval(over->x_pexpr, over->var_values, NULL);
  156. over->x = normalize_xy(over->var_values[VAR_X], over->hsub);
  157. over->y = normalize_xy(over->var_values[VAR_Y], over->vsub);
  158. }
  159. if (eval_tgt == EVAL_ENABLE || eval_tgt == EVAL_ALL) {
  160. over->enable = av_expr_eval(over->enable_pexpr, over->var_values, NULL);
  161. }
  162. }
  163. static int set_expr(AVExpr **pexpr, const char *expr, void *log_ctx)
  164. {
  165. int ret;
  166. if (*pexpr)
  167. av_expr_free(*pexpr);
  168. *pexpr = NULL;
  169. ret = av_expr_parse(pexpr, expr, var_names,
  170. NULL, NULL, NULL, NULL, 0, log_ctx);
  171. if (ret < 0)
  172. av_log(log_ctx, AV_LOG_ERROR,
  173. "Error when evaluating the expression '%s'\n", expr);
  174. return ret;
  175. }
  176. static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
  177. char *res, int res_len, int flags)
  178. {
  179. OverlayContext *over = ctx->priv;
  180. int ret;
  181. if (!strcmp(cmd, "x"))
  182. ret = set_expr(&over->x_pexpr, args, ctx);
  183. else if (!strcmp(cmd, "y"))
  184. ret = set_expr(&over->y_pexpr, args, ctx);
  185. else if (!strcmp(cmd, "enable"))
  186. ret = set_expr(&over->enable_pexpr, args, ctx);
  187. else
  188. ret = AVERROR(ENOSYS);
  189. if (ret < 0)
  190. return ret;
  191. if (over->eval_mode == EVAL_MODE_INIT) {
  192. eval_expr(ctx, EVAL_ALL);
  193. av_log(ctx, AV_LOG_VERBOSE, "x:%f xi:%d y:%f yi:%d enable:%f\n",
  194. over->var_values[VAR_X], over->x,
  195. over->var_values[VAR_Y], over->y,
  196. over->enable);
  197. }
  198. return ret;
  199. }
  200. static int query_formats(AVFilterContext *ctx)
  201. {
  202. OverlayContext *over = ctx->priv;
  203. /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
  204. static const enum AVPixelFormat main_pix_fmts_yuv420[] = {
  205. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
  206. };
  207. static const enum AVPixelFormat overlay_pix_fmts_yuv420[] = {
  208. AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
  209. };
  210. static const enum AVPixelFormat main_pix_fmts_yuv444[] = {
  211. AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
  212. };
  213. static const enum AVPixelFormat overlay_pix_fmts_yuv444[] = {
  214. AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
  215. };
  216. static const enum AVPixelFormat main_pix_fmts_rgb[] = {
  217. AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
  218. AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
  219. AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
  220. AV_PIX_FMT_NONE
  221. };
  222. static const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
  223. AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
  224. AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
  225. AV_PIX_FMT_NONE
  226. };
  227. AVFilterFormats *main_formats;
  228. AVFilterFormats *overlay_formats;
  229. switch (over->format) {
  230. case OVERLAY_FORMAT_YUV420:
  231. main_formats = ff_make_format_list(main_pix_fmts_yuv420);
  232. overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv420);
  233. break;
  234. case OVERLAY_FORMAT_YUV444:
  235. main_formats = ff_make_format_list(main_pix_fmts_yuv444);
  236. overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv444);
  237. break;
  238. case OVERLAY_FORMAT_RGB:
  239. main_formats = ff_make_format_list(main_pix_fmts_rgb);
  240. overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
  241. break;
  242. default:
  243. av_assert0(0);
  244. }
  245. ff_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
  246. ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
  247. ff_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
  248. return 0;
  249. }
  250. static const enum AVPixelFormat alpha_pix_fmts[] = {
  251. AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA444P,
  252. AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
  253. AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
  254. };
  255. static int config_input_main(AVFilterLink *inlink)
  256. {
  257. OverlayContext *over = inlink->dst->priv;
  258. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
  259. av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
  260. over->hsub = pix_desc->log2_chroma_w;
  261. over->vsub = pix_desc->log2_chroma_h;
  262. over->main_is_packed_rgb =
  263. ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
  264. over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
  265. return 0;
  266. }
  267. static int config_input_overlay(AVFilterLink *inlink)
  268. {
  269. AVFilterContext *ctx = inlink->dst;
  270. OverlayContext *over = inlink->dst->priv;
  271. int ret;
  272. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
  273. av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
  274. /* Finish the configuration by evaluating the expressions
  275. now when both inputs are configured. */
  276. over->var_values[VAR_MAIN_W ] = over->var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
  277. over->var_values[VAR_MAIN_H ] = over->var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
  278. over->var_values[VAR_OVERLAY_W] = over->var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
  279. over->var_values[VAR_OVERLAY_H] = over->var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
  280. over->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
  281. over->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
  282. over->var_values[VAR_X] = NAN;
  283. over->var_values[VAR_Y] = NAN;
  284. over->var_values[VAR_N] = 0;
  285. over->var_values[VAR_T] = NAN;
  286. over->var_values[VAR_POS] = NAN;
  287. if ((ret = set_expr(&over->x_pexpr, over->x_expr, ctx)) < 0 ||
  288. (ret = set_expr(&over->y_pexpr, over->y_expr, ctx)) < 0 ||
  289. (ret = set_expr(&over->enable_pexpr, over->enable_expr, ctx)) < 0)
  290. return ret;
  291. over->overlay_is_packed_rgb =
  292. ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
  293. over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
  294. if (over->eval_mode == EVAL_MODE_INIT) {
  295. eval_expr(ctx, EVAL_ALL);
  296. av_log(ctx, AV_LOG_VERBOSE, "x:%f xi:%d y:%f yi:%d enable:%f\n",
  297. over->var_values[VAR_X], over->x,
  298. over->var_values[VAR_Y], over->y,
  299. over->enable);
  300. }
  301. av_log(ctx, AV_LOG_VERBOSE,
  302. "main w:%d h:%d fmt:%s overlay w:%d h:%d fmt:%s\n",
  303. ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
  304. av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
  305. ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
  306. av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
  307. return 0;
  308. }
  309. static int config_output(AVFilterLink *outlink)
  310. {
  311. AVFilterContext *ctx = outlink->src;
  312. outlink->w = ctx->inputs[MAIN]->w;
  313. outlink->h = ctx->inputs[MAIN]->h;
  314. outlink->time_base = ctx->inputs[MAIN]->time_base;
  315. return 0;
  316. }
  317. // divide by 255 and round to nearest
  318. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  319. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  320. // calculate the unpremultiplied alpha, applying the general equation:
  321. // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
  322. // (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
  323. // ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
  324. #define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
  325. /**
  326. * Blend image in src to destination buffer dst at position (x, y).
  327. */
  328. static void blend_image(AVFilterContext *ctx,
  329. AVFrame *dst, AVFrame *src,
  330. int x, int y)
  331. {
  332. OverlayContext *over = ctx->priv;
  333. int i, imax, j, jmax, k, kmax;
  334. const int src_w = src->width;
  335. const int src_h = src->height;
  336. const int dst_w = dst->width;
  337. const int dst_h = dst->height;
  338. if (x >= dst_w || x+dst_w < 0 ||
  339. y >= dst_h || y+dst_h < 0)
  340. return; /* no intersection */
  341. if (over->main_is_packed_rgb) {
  342. uint8_t alpha; ///< the amount of overlay to blend on to main
  343. const int dr = over->main_rgba_map[R];
  344. const int dg = over->main_rgba_map[G];
  345. const int db = over->main_rgba_map[B];
  346. const int da = over->main_rgba_map[A];
  347. const int dstep = over->main_pix_step[0];
  348. const int sr = over->overlay_rgba_map[R];
  349. const int sg = over->overlay_rgba_map[G];
  350. const int sb = over->overlay_rgba_map[B];
  351. const int sa = over->overlay_rgba_map[A];
  352. const int sstep = over->overlay_pix_step[0];
  353. const int main_has_alpha = over->main_has_alpha;
  354. uint8_t *s, *sp, *d, *dp;
  355. i = FFMAX(-y, 0);
  356. sp = src->data[0] + i * src->linesize[0];
  357. dp = dst->data[0] + (y+i) * dst->linesize[0];
  358. for (imax = FFMIN(-y + dst_h, src_h); i < imax; i++) {
  359. j = FFMAX(-x, 0);
  360. s = sp + j * sstep;
  361. d = dp + (x+j) * dstep;
  362. for (jmax = FFMIN(-x + dst_w, src_w); j < jmax; j++) {
  363. alpha = s[sa];
  364. // if the main channel has an alpha channel, alpha has to be calculated
  365. // to create an un-premultiplied (straight) alpha value
  366. if (main_has_alpha && alpha != 0 && alpha != 255) {
  367. uint8_t alpha_d = d[da];
  368. alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
  369. }
  370. switch (alpha) {
  371. case 0:
  372. break;
  373. case 255:
  374. d[dr] = s[sr];
  375. d[dg] = s[sg];
  376. d[db] = s[sb];
  377. break;
  378. default:
  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);
  384. }
  385. if (main_has_alpha) {
  386. switch (alpha) {
  387. case 0:
  388. break;
  389. case 255:
  390. d[da] = s[sa];
  391. break;
  392. default:
  393. // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
  394. d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
  395. }
  396. }
  397. d += dstep;
  398. s += sstep;
  399. }
  400. dp += dst->linesize[0];
  401. sp += src->linesize[0];
  402. }
  403. } else {
  404. const int main_has_alpha = over->main_has_alpha;
  405. if (main_has_alpha) {
  406. uint8_t alpha; ///< the amount of overlay to blend on to main
  407. uint8_t *s, *sa, *d, *da;
  408. i = FFMAX(-y, 0);
  409. sa = src->data[3] + i * src->linesize[3];
  410. da = dst->data[3] + (y+i) * dst->linesize[3];
  411. for (imax = FFMIN(-y + dst_h, src_h); i < imax; i++) {
  412. j = FFMAX(-x, 0);
  413. s = sa + j;
  414. d = da + x+j;
  415. for (jmax = FFMIN(-x + dst_w, src_w); j < jmax; j++) {
  416. alpha = *s;
  417. if (alpha != 0 && alpha != 255) {
  418. uint8_t alpha_d = *d;
  419. alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
  420. }
  421. switch (alpha) {
  422. case 0:
  423. break;
  424. case 255:
  425. *d = *s;
  426. break;
  427. default:
  428. // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
  429. *d += FAST_DIV255((255 - *d) * *s);
  430. }
  431. d += 1;
  432. s += 1;
  433. }
  434. da += dst->linesize[3];
  435. sa += src->linesize[3];
  436. }
  437. }
  438. for (i = 0; i < 3; i++) {
  439. int hsub = i ? over->hsub : 0;
  440. int vsub = i ? over->vsub : 0;
  441. int src_wp = FFALIGN(src_w, 1<<hsub) >> hsub;
  442. int src_hp = FFALIGN(src_h, 1<<vsub) >> vsub;
  443. int dst_wp = FFALIGN(dst_w, 1<<hsub) >> hsub;
  444. int dst_hp = FFALIGN(dst_h, 1<<vsub) >> vsub;
  445. int yp = y>>vsub;
  446. int xp = x>>hsub;
  447. uint8_t *s, *sp, *d, *dp, *a, *ap;
  448. j = FFMAX(-yp, 0);
  449. sp = src->data[i] + j * src->linesize[i];
  450. dp = dst->data[i] + (yp+j) * dst->linesize[i];
  451. ap = src->data[3] + (j<<vsub) * src->linesize[3];
  452. for (jmax = FFMIN(-yp + dst_hp, src_hp); j < jmax; j++) {
  453. k = FFMAX(-xp, 0);
  454. d = dp + xp+k;
  455. s = sp + k;
  456. a = ap + (k<<hsub);
  457. for (kmax = FFMIN(-xp + dst_wp, src_wp); k < kmax; k++) {
  458. int alpha_v, alpha_h, alpha;
  459. // average alpha for color components, improve quality
  460. if (hsub && vsub && j+1 < src_hp && k+1 < src_wp) {
  461. alpha = (a[0] + a[src->linesize[3]] +
  462. a[1] + a[src->linesize[3]+1]) >> 2;
  463. } else if (hsub || vsub) {
  464. alpha_h = hsub && k+1 < src_wp ?
  465. (a[0] + a[1]) >> 1 : a[0];
  466. alpha_v = vsub && j+1 < src_hp ?
  467. (a[0] + a[src->linesize[3]]) >> 1 : a[0];
  468. alpha = (alpha_v + alpha_h) >> 1;
  469. } else
  470. alpha = a[0];
  471. // if the main channel has an alpha channel, alpha has to be calculated
  472. // to create an un-premultiplied (straight) alpha value
  473. if (main_has_alpha && alpha != 0 && alpha != 255) {
  474. // average alpha for color components, improve quality
  475. uint8_t alpha_d;
  476. if (hsub && vsub && j+1 < src_hp && k+1 < src_wp) {
  477. alpha_d = (d[0] + d[src->linesize[3]] +
  478. d[1] + d[src->linesize[3]+1]) >> 2;
  479. } else if (hsub || vsub) {
  480. alpha_h = hsub && k+1 < src_wp ?
  481. (d[0] + d[1]) >> 1 : d[0];
  482. alpha_v = vsub && j+1 < src_hp ?
  483. (d[0] + d[src->linesize[3]]) >> 1 : d[0];
  484. alpha_d = (alpha_v + alpha_h) >> 1;
  485. } else
  486. alpha_d = d[0];
  487. alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
  488. }
  489. *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
  490. s++;
  491. d++;
  492. a += 1 << hsub;
  493. }
  494. dp += dst->linesize[i];
  495. sp += src->linesize[i];
  496. ap += (1 << vsub) * src->linesize[3];
  497. }
  498. }
  499. }
  500. }
  501. static int try_filter_frame(AVFilterContext *ctx, AVFrame *mainpic)
  502. {
  503. OverlayContext *over = ctx->priv;
  504. AVFilterLink *inlink = ctx->inputs[0];
  505. AVFrame *next_overpic;
  506. int ret;
  507. /* Discard obsolete overlay frames: if there is a next overlay frame with pts
  508. * before the main frame, we can drop the current overlay. */
  509. while (1) {
  510. next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
  511. if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
  512. mainpic->pts , ctx->inputs[MAIN]->time_base) > 0)
  513. break;
  514. ff_bufqueue_get(&over->queue_over);
  515. av_frame_free(&over->overpicref);
  516. over->overpicref = next_overpic;
  517. }
  518. /* If there is no next frame and no EOF and the overlay frame is before
  519. * the main frame, we can not know yet if it will be superseded. */
  520. if (!over->queue_over.available && !over->overlay_eof &&
  521. (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
  522. mainpic->pts , ctx->inputs[MAIN]->time_base) < 0))
  523. return AVERROR(EAGAIN);
  524. /* At this point, we know that the current overlay frame extends to the
  525. * time of the main frame. */
  526. av_dlog(ctx, "main_pts:%s main_pts_time:%s",
  527. av_ts2str(mainpic->pts), av_ts2timestr(mainpic->pts, &ctx->inputs[MAIN]->time_base));
  528. if (over->overpicref)
  529. av_dlog(ctx, " over_pts:%s over_pts_time:%s",
  530. av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &ctx->inputs[OVERLAY]->time_base));
  531. av_dlog(ctx, "\n");
  532. if (over->overpicref) {
  533. if (over->eval_mode == EVAL_MODE_FRAME) {
  534. int64_t pos = av_frame_get_pkt_pos(mainpic);
  535. over->var_values[VAR_T] = mainpic->pts == AV_NOPTS_VALUE ?
  536. NAN : mainpic->pts * av_q2d(inlink->time_base);
  537. over->var_values[VAR_POS] = pos == -1 ? NAN : pos;
  538. eval_expr(ctx, EVAL_ALL);
  539. av_log(ctx, AV_LOG_DEBUG, "n:%f t:%f pos:%f x:%f xi:%d y:%f yi:%d enable:%f\n",
  540. over->var_values[VAR_N], over->var_values[VAR_T], over->var_values[VAR_POS],
  541. over->var_values[VAR_X], over->x,
  542. over->var_values[VAR_Y], over->y,
  543. over->enable);
  544. }
  545. if (over->enable)
  546. blend_image(ctx, mainpic, over->overpicref, over->x, over->y);
  547. over->var_values[VAR_N] += 1.0;
  548. }
  549. ret = ff_filter_frame(ctx->outputs[0], mainpic);
  550. av_assert1(ret != AVERROR(EAGAIN));
  551. over->frame_requested = 0;
  552. return ret;
  553. }
  554. static int try_filter_next_frame(AVFilterContext *ctx)
  555. {
  556. OverlayContext *over = ctx->priv;
  557. AVFrame *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
  558. int ret;
  559. if (!next_mainpic)
  560. return AVERROR(EAGAIN);
  561. if ((ret = try_filter_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
  562. return ret;
  563. ff_bufqueue_get(&over->queue_main);
  564. return ret;
  565. }
  566. static int flush_frames(AVFilterContext *ctx)
  567. {
  568. int ret;
  569. while (!(ret = try_filter_next_frame(ctx)));
  570. return ret == AVERROR(EAGAIN) ? 0 : ret;
  571. }
  572. static int filter_frame_main(AVFilterLink *inlink, AVFrame *inpicref)
  573. {
  574. AVFilterContext *ctx = inlink->dst;
  575. OverlayContext *over = ctx->priv;
  576. int ret;
  577. if ((ret = flush_frames(ctx)) < 0)
  578. return ret;
  579. if ((ret = try_filter_frame(ctx, inpicref)) < 0) {
  580. if (ret != AVERROR(EAGAIN))
  581. return ret;
  582. ff_bufqueue_add(ctx, &over->queue_main, inpicref);
  583. }
  584. if (!over->overpicref)
  585. return 0;
  586. flush_frames(ctx);
  587. return 0;
  588. }
  589. static int filter_frame_over(AVFilterLink *inlink, AVFrame *inpicref)
  590. {
  591. AVFilterContext *ctx = inlink->dst;
  592. OverlayContext *over = ctx->priv;
  593. int ret;
  594. if ((ret = flush_frames(ctx)) < 0)
  595. return ret;
  596. ff_bufqueue_add(ctx, &over->queue_over, inpicref);
  597. ret = try_filter_next_frame(ctx);
  598. return ret == AVERROR(EAGAIN) ? 0 : ret;
  599. }
  600. static int request_frame(AVFilterLink *outlink)
  601. {
  602. AVFilterContext *ctx = outlink->src;
  603. OverlayContext *over = ctx->priv;
  604. int input, ret;
  605. if (!try_filter_next_frame(ctx))
  606. return 0;
  607. over->frame_requested = 1;
  608. while (over->frame_requested) {
  609. /* TODO if we had a frame duration, we could guess more accurately */
  610. input = !over->overlay_eof && (over->queue_main.available ||
  611. over->queue_over.available < 2) ?
  612. OVERLAY : MAIN;
  613. ret = ff_request_frame(ctx->inputs[input]);
  614. /* EOF on main is reported immediately */
  615. if (ret == AVERROR_EOF && input == OVERLAY) {
  616. over->overlay_eof = 1;
  617. if (over->shortest)
  618. return ret;
  619. if ((ret = try_filter_next_frame(ctx)) != AVERROR(EAGAIN))
  620. return ret;
  621. ret = 0; /* continue requesting frames on main */
  622. }
  623. if (ret < 0)
  624. return ret;
  625. }
  626. return 0;
  627. }
  628. static const AVFilterPad avfilter_vf_overlay_inputs[] = {
  629. {
  630. .name = "main",
  631. .type = AVMEDIA_TYPE_VIDEO,
  632. .get_video_buffer = ff_null_get_video_buffer,
  633. .config_props = config_input_main,
  634. .filter_frame = filter_frame_main,
  635. .needs_writable = 1,
  636. },
  637. {
  638. .name = "overlay",
  639. .type = AVMEDIA_TYPE_VIDEO,
  640. .config_props = config_input_overlay,
  641. .filter_frame = filter_frame_over,
  642. },
  643. { NULL }
  644. };
  645. static const AVFilterPad avfilter_vf_overlay_outputs[] = {
  646. {
  647. .name = "default",
  648. .type = AVMEDIA_TYPE_VIDEO,
  649. .config_props = config_output,
  650. .request_frame = request_frame,
  651. },
  652. { NULL }
  653. };
  654. static const char *const shorthand[] = { "x", "y", NULL };
  655. AVFilter avfilter_vf_overlay = {
  656. .name = "overlay",
  657. .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
  658. .init = init,
  659. .uninit = uninit,
  660. .priv_size = sizeof(OverlayContext),
  661. .query_formats = query_formats,
  662. .process_command = process_command,
  663. .inputs = avfilter_vf_overlay_inputs,
  664. .outputs = avfilter_vf_overlay_outputs,
  665. .priv_class = &overlay_class,
  666. .shorthand = shorthand,
  667. };