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.

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