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.

499 lines
18KB

  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 *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 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 dstep = over->main_pix_step[0];
  307. const int sr = over->overlay_rgba_map[R];
  308. const int sg = over->overlay_rgba_map[G];
  309. const int sb = over->overlay_rgba_map[B];
  310. const int sa = over->overlay_rgba_map[A];
  311. const int sstep = over->overlay_pix_step[0];
  312. if (slice_y > y)
  313. sp += (slice_y - y) * src->linesize[0];
  314. for (i = 0; i < height; i++) {
  315. uint8_t *d = dp, *s = sp;
  316. for (j = 0; j < width; j++) {
  317. alpha = s[sa];
  318. switch (alpha) {
  319. case 0:
  320. break;
  321. case 255:
  322. d[dr] = s[sr];
  323. d[dg] = s[sg];
  324. d[db] = s[sb];
  325. break;
  326. default:
  327. // main_value = main_value * (1 - alpha) + overlay_value * alpha
  328. // since alpha is in the range 0-255, the result must divided by 255
  329. d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
  330. d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
  331. d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
  332. }
  333. d += dstep;
  334. s += sstep;
  335. }
  336. dp += dst->linesize[0];
  337. sp += src->linesize[0];
  338. }
  339. } else {
  340. for (i = 0; i < 3; i++) {
  341. int hsub = i ? over->hsub : 0;
  342. int vsub = i ? over->vsub : 0;
  343. uint8_t *dp = dst->data[i] + (x >> hsub) +
  344. (start_y >> vsub) * dst->linesize[i];
  345. uint8_t *sp = src->data[i];
  346. uint8_t *ap = src->data[3];
  347. int wp = FFALIGN(width, 1<<hsub) >> hsub;
  348. int hp = FFALIGN(height, 1<<vsub) >> vsub;
  349. if (slice_y > y) {
  350. sp += ((slice_y - y) >> vsub) * src->linesize[i];
  351. ap += (slice_y - y) * src->linesize[3];
  352. }
  353. for (j = 0; j < hp; j++) {
  354. uint8_t *d = dp, *s = sp, *a = ap;
  355. for (k = 0; k < wp; k++) {
  356. // average alpha for color components, improve quality
  357. int alpha_v, alpha_h, alpha;
  358. if (hsub && vsub && j+1 < hp && k+1 < wp) {
  359. alpha = (a[0] + a[src->linesize[3]] +
  360. a[1] + a[src->linesize[3]+1]) >> 2;
  361. } else if (hsub || vsub) {
  362. alpha_h = hsub && k+1 < wp ?
  363. (a[0] + a[1]) >> 1 : a[0];
  364. alpha_v = vsub && j+1 < hp ?
  365. (a[0] + a[src->linesize[3]]) >> 1 : a[0];
  366. alpha = (alpha_v + alpha_h) >> 1;
  367. } else
  368. alpha = a[0];
  369. *d = (*d * (0xff - alpha) + *s++ * alpha + 128) >> 8;
  370. d++;
  371. a += 1 << hsub;
  372. }
  373. dp += dst->linesize[i];
  374. sp += src->linesize[i];
  375. ap += (1 << vsub) * src->linesize[3];
  376. }
  377. }
  378. }
  379. }
  380. static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
  381. {
  382. AVFilterContext *ctx = inlink->dst;
  383. AVFilterLink *outlink = ctx->outputs[0];
  384. AVFilterBufferRef *outpicref = outlink->out_buf;
  385. OverlayContext *over = ctx->priv;
  386. if (over->overpicref &&
  387. !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
  388. y+h < over->y || y >= over->y + over->overpicref->video->h)) {
  389. blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
  390. over->overpicref->video->w, over->overpicref->video->h,
  391. y, outpicref->video->w, h);
  392. }
  393. avfilter_draw_slice(outlink, y, h, slice_dir);
  394. }
  395. static void end_frame(AVFilterLink *inlink)
  396. {
  397. avfilter_end_frame(inlink->dst->outputs[0]);
  398. avfilter_unref_buffer(inlink->cur_buf);
  399. }
  400. static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
  401. static void null_end_frame(AVFilterLink *inlink) { }
  402. AVFilter avfilter_vf_overlay = {
  403. .name = "overlay",
  404. .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
  405. .init = init,
  406. .uninit = uninit,
  407. .priv_size = sizeof(OverlayContext),
  408. .query_formats = query_formats,
  409. .inputs = (AVFilterPad[]) {{ .name = "main",
  410. .type = AVMEDIA_TYPE_VIDEO,
  411. .start_frame = start_frame,
  412. .get_video_buffer= get_video_buffer,
  413. .config_props = config_input_main,
  414. .draw_slice = draw_slice,
  415. .end_frame = end_frame,
  416. .min_perms = AV_PERM_READ,
  417. .rej_perms = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
  418. { .name = "overlay",
  419. .type = AVMEDIA_TYPE_VIDEO,
  420. .start_frame = start_frame_overlay,
  421. .config_props = config_input_overlay,
  422. .draw_slice = null_draw_slice,
  423. .end_frame = null_end_frame,
  424. .min_perms = AV_PERM_READ,
  425. .rej_perms = AV_PERM_REUSE2, },
  426. { .name = NULL}},
  427. .outputs = (AVFilterPad[]) {{ .name = "default",
  428. .type = AVMEDIA_TYPE_VIDEO,
  429. .config_props = config_output, },
  430. { .name = NULL}},
  431. };