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.

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