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.

777 lines
28KB

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