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.

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