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