vf_overlay.c 19 KB

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