vf_overlay.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. #include "avfilter.h"
  27. #include "libavutil/eval.h"
  28. #include "libavutil/avstring.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/pixdesc.h"
  31. #include "libavutil/imgutils.h"
  32. #include "libavutil/mathematics.h"
  33. #include "internal.h"
  34. #include "drawutils.h"
  35. static const char * const var_names[] = {
  36. "main_w", "W", ///< width of the main video
  37. "main_h", "H", ///< height of the main video
  38. "overlay_w", "w", ///< width of the overlay video
  39. "overlay_h", "h", ///< height of the overlay video
  40. NULL
  41. };
  42. enum var_name {
  43. VAR_MAIN_W, VAR_MW,
  44. VAR_MAIN_H, VAR_MH,
  45. VAR_OVERLAY_W, VAR_OW,
  46. VAR_OVERLAY_H, VAR_OH,
  47. VAR_VARS_NB
  48. };
  49. #define MAIN 0
  50. #define OVERLAY 1
  51. #define R 0
  52. #define G 1
  53. #define B 2
  54. #define A 3
  55. #define Y 0
  56. #define U 1
  57. #define V 2
  58. typedef struct {
  59. const AVClass *class;
  60. int x, y; ///< position of overlayed picture
  61. int allow_packed_rgb;
  62. uint8_t main_is_packed_rgb;
  63. uint8_t main_rgba_map[4];
  64. uint8_t main_has_alpha;
  65. uint8_t overlay_is_packed_rgb;
  66. uint8_t overlay_rgba_map[4];
  67. uint8_t overlay_has_alpha;
  68. AVFilterBufferRef *overpicref;
  69. int main_pix_step[4]; ///< steps per pixel for each plane of the main output
  70. int overlay_pix_step[4]; ///< steps per pixel for each plane of the overlay
  71. int hsub, vsub; ///< chroma subsampling values
  72. char *x_expr, *y_expr;
  73. } OverlayContext;
  74. #define OFFSET(x) offsetof(OverlayContext, x)
  75. static const AVOption overlay_options[] = {
  76. { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
  77. { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX },
  78. {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  79. {NULL},
  80. };
  81. static const char *overlay_get_name(void *ctx)
  82. {
  83. return "overlay";
  84. }
  85. static const AVClass overlay_class = {
  86. "OverlayContext",
  87. overlay_get_name,
  88. overlay_options
  89. };
  90. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  91. {
  92. OverlayContext *over = ctx->priv;
  93. char *args1 = av_strdup(args);
  94. char *expr, *bufptr = NULL;
  95. int ret = 0;
  96. over->class = &overlay_class;
  97. av_opt_set_defaults(over);
  98. if (expr = av_strtok(args1, ":", &bufptr)) {
  99. av_free(over->x_expr);
  100. if (!(over->x_expr = av_strdup(expr))) {
  101. ret = AVERROR(ENOMEM);
  102. goto end;
  103. }
  104. }
  105. if (expr = av_strtok(NULL, ":", &bufptr)) {
  106. av_free(over->y_expr);
  107. if (!(over->y_expr = av_strdup(expr))) {
  108. ret = AVERROR(ENOMEM);
  109. goto end;
  110. }
  111. }
  112. if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
  113. goto end;
  114. end:
  115. av_free(args1);
  116. return ret;
  117. }
  118. static av_cold void uninit(AVFilterContext *ctx)
  119. {
  120. OverlayContext *over = ctx->priv;
  121. av_freep(&over->x_expr);
  122. av_freep(&over->y_expr);
  123. if (over->overpicref)
  124. avfilter_unref_buffer(over->overpicref);
  125. }
  126. static int query_formats(AVFilterContext *ctx)
  127. {
  128. OverlayContext *over = ctx->priv;
  129. /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
  130. const enum PixelFormat main_pix_fmts_yuv[] = { PIX_FMT_YUV420P, PIX_FMT_NONE };
  131. const enum PixelFormat overlay_pix_fmts_yuv[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
  132. const enum PixelFormat main_pix_fmts_rgb[] = {
  133. PIX_FMT_ARGB, PIX_FMT_RGBA,
  134. PIX_FMT_ABGR, PIX_FMT_BGRA,
  135. PIX_FMT_RGB24, PIX_FMT_BGR24,
  136. PIX_FMT_NONE
  137. };
  138. const enum PixelFormat overlay_pix_fmts_rgb[] = {
  139. PIX_FMT_ARGB, PIX_FMT_RGBA,
  140. PIX_FMT_ABGR, PIX_FMT_BGRA,
  141. PIX_FMT_NONE
  142. };
  143. AVFilterFormats *main_formats;
  144. AVFilterFormats *overlay_formats;
  145. if (over->allow_packed_rgb) {
  146. main_formats = avfilter_make_format_list(main_pix_fmts_rgb);
  147. overlay_formats = avfilter_make_format_list(overlay_pix_fmts_rgb);
  148. } else {
  149. main_formats = avfilter_make_format_list(main_pix_fmts_yuv);
  150. overlay_formats = avfilter_make_format_list(overlay_pix_fmts_yuv);
  151. }
  152. avfilter_formats_ref(main_formats, &ctx->inputs [MAIN ]->out_formats);
  153. avfilter_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
  154. avfilter_formats_ref(main_formats, &ctx->outputs[MAIN ]->in_formats );
  155. return 0;
  156. }
  157. static const enum PixelFormat alpha_pix_fmts[] = {
  158. PIX_FMT_YUVA420P, PIX_FMT_ARGB, PIX_FMT_ABGR, PIX_FMT_RGBA,
  159. PIX_FMT_BGRA, PIX_FMT_NONE
  160. };
  161. static int config_input_main(AVFilterLink *inlink)
  162. {
  163. OverlayContext *over = inlink->dst->priv;
  164. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
  165. av_image_fill_max_pixsteps(over->main_pix_step, NULL, pix_desc);
  166. over->hsub = pix_desc->log2_chroma_w;
  167. over->vsub = pix_desc->log2_chroma_h;
  168. over->main_is_packed_rgb =
  169. ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
  170. over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
  171. return 0;
  172. }
  173. static int config_input_overlay(AVFilterLink *inlink)
  174. {
  175. AVFilterContext *ctx = inlink->dst;
  176. OverlayContext *over = inlink->dst->priv;
  177. char *expr;
  178. double var_values[VAR_VARS_NB], res;
  179. int ret;
  180. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
  181. av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
  182. /* Finish the configuration by evaluating the expressions
  183. now when both inputs are configured. */
  184. var_values[VAR_MAIN_W ] = var_values[VAR_MW] = ctx->inputs[MAIN ]->w;
  185. var_values[VAR_MAIN_H ] = var_values[VAR_MH] = ctx->inputs[MAIN ]->h;
  186. var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
  187. var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
  188. if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
  189. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  190. goto fail;
  191. over->x = res;
  192. if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
  193. NULL, NULL, NULL, NULL, NULL, 0, ctx)))
  194. goto fail;
  195. over->y = res;
  196. /* x may depend on y */
  197. if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
  198. NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  199. goto fail;
  200. over->x = res;
  201. over->overlay_is_packed_rgb =
  202. ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
  203. over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
  204. av_log(ctx, AV_LOG_INFO,
  205. "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
  206. ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
  207. av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
  208. over->x, over->y,
  209. ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
  210. av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
  211. if (over->x < 0 || over->y < 0 ||
  212. over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
  213. over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
  214. av_log(ctx, AV_LOG_ERROR,
  215. "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
  216. over->x, over->y,
  217. (int)(over->x + var_values[VAR_OVERLAY_W]),
  218. (int)(over->y + var_values[VAR_OVERLAY_H]),
  219. (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
  220. return AVERROR(EINVAL);
  221. }
  222. return 0;
  223. fail:
  224. av_log(NULL, AV_LOG_ERROR,
  225. "Error when evaluating the expression '%s'\n", expr);
  226. return ret;
  227. }
  228. static int config_output(AVFilterLink *outlink)
  229. {
  230. AVFilterContext *ctx = outlink->src;
  231. int exact;
  232. // common timebase computation:
  233. AVRational tb1 = ctx->inputs[MAIN ]->time_base;
  234. AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
  235. AVRational *tb = &ctx->outputs[0]->time_base;
  236. exact = av_reduce(&tb->num, &tb->den,
  237. av_gcd((int64_t)tb1.num * tb2.den,
  238. (int64_t)tb2.num * tb1.den),
  239. (int64_t)tb1.den * tb2.den, INT_MAX);
  240. av_log(ctx, AV_LOG_INFO,
  241. "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
  242. tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
  243. if (!exact)
  244. av_log(ctx, AV_LOG_WARNING,
  245. "Timestamp conversion inexact, timestamp information loss may occurr\n");
  246. outlink->w = ctx->inputs[MAIN]->w;
  247. outlink->h = ctx->inputs[MAIN]->h;
  248. return 0;
  249. }
  250. static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
  251. {
  252. return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
  253. }
  254. static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
  255. {
  256. AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
  257. AVFilterContext *ctx = inlink->dst;
  258. OverlayContext *over = ctx->priv;
  259. inlink->dst->outputs[0]->out_buf = outpicref;
  260. outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
  261. ctx->outputs[0]->time_base);
  262. if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
  263. AVFilterBufferRef *old = over->overpicref;
  264. over->overpicref = NULL;
  265. avfilter_request_frame(ctx->inputs[OVERLAY]);
  266. if (over->overpicref) {
  267. if (old)
  268. avfilter_unref_buffer(old);
  269. } else
  270. over->overpicref = old;
  271. }
  272. avfilter_start_frame(inlink->dst->outputs[0], outpicref);
  273. }
  274. static void start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
  275. {
  276. AVFilterContext *ctx = inlink->dst;
  277. OverlayContext *over = ctx->priv;
  278. over->overpicref = inpicref;
  279. over->overpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
  280. ctx->outputs[0]->time_base);
  281. }
  282. // divide by 255 and round to nearest
  283. // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
  284. #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
  285. static void blend_slice(AVFilterContext *ctx,
  286. AVFilterBufferRef *dst, AVFilterBufferRef *src,
  287. int x, int y, int w, int h,
  288. int slice_y, int slice_w, int slice_h)
  289. {
  290. OverlayContext *over = ctx->priv;
  291. int i, j, k;
  292. int width, height;
  293. int overlay_end_y = y+h;
  294. int slice_end_y = slice_y+slice_h;
  295. int end_y, start_y;
  296. width = FFMIN(slice_w - x, w);
  297. end_y = FFMIN(slice_end_y, overlay_end_y);
  298. start_y = FFMAX(y, slice_y);
  299. height = end_y - start_y;
  300. if (over->main_is_packed_rgb) {
  301. uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
  302. start_y * dst->linesize[0];
  303. uint8_t *sp = src->data[0];
  304. uint8_t alpha; ///< the amount of overlay to blend on to main
  305. const int dr = over->main_rgba_map[R];
  306. const int dg = over->main_rgba_map[G];
  307. const int db = over->main_rgba_map[B];
  308. const int da = over->main_rgba_map[A];
  309. const int dstep = over->main_pix_step[0];
  310. const int sr = over->overlay_rgba_map[R];
  311. const int sg = over->overlay_rgba_map[G];
  312. const int sb = over->overlay_rgba_map[B];
  313. const int sa = over->overlay_rgba_map[A];
  314. const int sstep = over->overlay_pix_step[0];
  315. const int main_has_alpha = over->main_has_alpha;
  316. if (slice_y > y)
  317. sp += (slice_y - y) * src->linesize[0];
  318. for (i = 0; i < height; i++) {
  319. uint8_t *d = dp, *s = sp;
  320. for (j = 0; j < width; j++) {
  321. alpha = s[sa];
  322. // if the main channel has an alpha channel, alpha has to be calculated
  323. // to create an un-premultiplied (straight) alpha value
  324. if (main_has_alpha && alpha != 0 && alpha != 255) {
  325. // apply the general equation:
  326. // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
  327. alpha =
  328. // the next line is a faster version of: 255 * 255 * alpha
  329. ( (alpha << 16) - (alpha << 9) + alpha )
  330. /
  331. // the next line is a faster version of: 255 * (alpha + d[da])
  332. ( ((alpha + d[da]) << 8 ) - (alpha + d[da])
  333. - d[da] * alpha );
  334. }
  335. switch (alpha) {
  336. case 0:
  337. break;
  338. case 255:
  339. d[dr] = s[sr];
  340. d[dg] = s[sg];
  341. d[db] = s[sb];
  342. break;
  343. default:
  344. // main_value = main_value * (1 - alpha) + overlay_value * alpha
  345. // since alpha is in the range 0-255, the result must divided by 255
  346. d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
  347. d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
  348. d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
  349. }
  350. if (main_has_alpha) {
  351. switch (alpha) {
  352. case 0:
  353. break;
  354. case 255:
  355. d[da] = s[sa];
  356. break;
  357. default:
  358. // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
  359. d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
  360. }
  361. }
  362. d += dstep;
  363. s += sstep;
  364. }
  365. dp += dst->linesize[0];
  366. sp += src->linesize[0];
  367. }
  368. } else {
  369. for (i = 0; i < 3; i++) {
  370. int hsub = i ? over->hsub : 0;
  371. int vsub = i ? over->vsub : 0;
  372. uint8_t *dp = dst->data[i] + (x >> hsub) +
  373. (start_y >> vsub) * dst->linesize[i];
  374. uint8_t *sp = src->data[i];
  375. uint8_t *ap = src->data[3];
  376. int wp = FFALIGN(width, 1<<hsub) >> hsub;
  377. int hp = FFALIGN(height, 1<<vsub) >> vsub;
  378. if (slice_y > y) {
  379. sp += ((slice_y - y) >> vsub) * src->linesize[i];
  380. ap += (slice_y - y) * src->linesize[3];
  381. }
  382. for (j = 0; j < hp; j++) {
  383. uint8_t *d = dp, *s = sp, *a = ap;
  384. for (k = 0; k < wp; k++) {
  385. // average alpha for color components, improve quality
  386. int alpha_v, alpha_h, alpha;
  387. if (hsub && vsub && j+1 < hp && k+1 < wp) {
  388. alpha = (a[0] + a[src->linesize[3]] +
  389. a[1] + a[src->linesize[3]+1]) >> 2;
  390. } else if (hsub || vsub) {
  391. alpha_h = hsub && k+1 < wp ?
  392. (a[0] + a[1]) >> 1 : a[0];
  393. alpha_v = vsub && j+1 < hp ?
  394. (a[0] + a[src->linesize[3]]) >> 1 : a[0];
  395. alpha = (alpha_v + alpha_h) >> 1;
  396. } else
  397. alpha = a[0];
  398. *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
  399. s++;
  400. d++;
  401. a += 1 << hsub;
  402. }
  403. dp += dst->linesize[i];
  404. sp += src->linesize[i];
  405. ap += (1 << vsub) * src->linesize[3];
  406. }
  407. }
  408. }
  409. }
  410. static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
  411. {
  412. AVFilterContext *ctx = inlink->dst;
  413. AVFilterLink *outlink = ctx->outputs[0];
  414. AVFilterBufferRef *outpicref = outlink->out_buf;
  415. OverlayContext *over = ctx->priv;
  416. if (over->overpicref &&
  417. !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
  418. y+h < over->y || y >= over->y + over->overpicref->video->h)) {
  419. blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
  420. over->overpicref->video->w, over->overpicref->video->h,
  421. y, outpicref->video->w, h);
  422. }
  423. avfilter_draw_slice(outlink, y, h, slice_dir);
  424. }
  425. static void end_frame(AVFilterLink *inlink)
  426. {
  427. avfilter_end_frame(inlink->dst->outputs[0]);
  428. avfilter_unref_buffer(inlink->cur_buf);
  429. }
  430. static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
  431. static void null_end_frame(AVFilterLink *inlink) { }
  432. AVFilter avfilter_vf_overlay = {
  433. .name = "overlay",
  434. .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
  435. .init = init,
  436. .uninit = uninit,
  437. .priv_size = sizeof(OverlayContext),
  438. .query_formats = query_formats,
  439. .inputs = (const AVFilterPad[]) {{ .name = "main",
  440. .type = AVMEDIA_TYPE_VIDEO,
  441. .start_frame = start_frame,
  442. .get_video_buffer= get_video_buffer,
  443. .config_props = config_input_main,
  444. .draw_slice = draw_slice,
  445. .end_frame = end_frame,
  446. .min_perms = AV_PERM_READ,
  447. .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
  448. { .name = "overlay",
  449. .type = AVMEDIA_TYPE_VIDEO,
  450. .start_frame = start_frame_overlay,
  451. .config_props = config_input_overlay,
  452. .draw_slice = null_draw_slice,
  453. .end_frame = null_end_frame,
  454. .min_perms = AV_PERM_READ,
  455. .rej_perms = AV_PERM_REUSE2, },
  456. { .name = NULL}},
  457. .outputs = (const AVFilterPad[]) {{ .name = "default",
  458. .type = AVMEDIA_TYPE_VIDEO,
  459. .config_props = config_output, },
  460. { .name = NULL}},
  461. };