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