OSDN Git Service

Merge remote branch 'official/master'
[coroid/ffmpeg_saccubus.git] / 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/pixdesc.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/mathematics.h"
34 #include "internal.h"
35
36 static const char *var_names[] = {
37     "E",
38     "PHI",
39     "PI",
40     "main_w",    "W", ///< width  of the main    video
41     "main_h",    "H", ///< height of the main    video
42     "overlay_w", "w", ///< width  of the overlay video
43     "overlay_h", "h", ///< height of the overlay video
44     NULL
45 };
46
47 enum var_name {
48     VAR_E,
49     VAR_PHI,
50     VAR_PI,
51     VAR_MAIN_W,    VAR_MW,
52     VAR_MAIN_H,    VAR_MH,
53     VAR_OVERLAY_W, VAR_OW,
54     VAR_OVERLAY_H, VAR_OH,
55     VAR_VARS_NB
56 };
57
58 #define MAIN    0
59 #define OVERLAY 1
60
61 typedef struct {
62     int x, y;                   ///< position of overlayed picture
63
64     AVFilterBufferRef *overpicref;
65
66     int max_plane_step[4];      ///< steps per pixel for each plane
67     int hsub, vsub;             ///< chroma subsampling values
68
69     char x_expr[256], y_expr[256];
70 } OverlayContext;
71
72 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
73 {
74     OverlayContext *over = ctx->priv;
75
76     av_strlcpy(over->x_expr, "0", sizeof(over->x_expr));
77     av_strlcpy(over->y_expr, "0", sizeof(over->y_expr));
78
79     if (args)
80         sscanf(args, "%255[^:]:%255[^:]", over->x_expr, over->y_expr);
81
82     return 0;
83 }
84
85 static av_cold void uninit(AVFilterContext *ctx)
86 {
87     OverlayContext *over = ctx->priv;
88
89     if (over->overpicref)
90         avfilter_unref_buffer(over->overpicref);
91 }
92
93 static int query_formats(AVFilterContext *ctx)
94 {
95     const enum PixelFormat inout_pix_fmts[] = { PIX_FMT_YUV420P,  PIX_FMT_NONE };
96     const enum PixelFormat blend_pix_fmts[] = { PIX_FMT_YUVA420P, PIX_FMT_NONE };
97     AVFilterFormats *inout_formats = avfilter_make_format_list(inout_pix_fmts);
98     AVFilterFormats *blend_formats = avfilter_make_format_list(blend_pix_fmts);
99
100     avfilter_formats_ref(inout_formats, &ctx->inputs [MAIN   ]->out_formats);
101     avfilter_formats_ref(blend_formats, &ctx->inputs [OVERLAY]->out_formats);
102     avfilter_formats_ref(inout_formats, &ctx->outputs[MAIN   ]->in_formats );
103
104     return 0;
105 }
106
107 static int config_input_main(AVFilterLink *inlink)
108 {
109     OverlayContext *over = inlink->dst->priv;
110     const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
111
112     av_image_fill_max_pixsteps(over->max_plane_step, NULL, pix_desc);
113     over->hsub = pix_desc->log2_chroma_w;
114     over->vsub = pix_desc->log2_chroma_h;
115
116     return 0;
117 }
118
119 static int config_input_overlay(AVFilterLink *inlink)
120 {
121     AVFilterContext *ctx  = inlink->dst;
122     OverlayContext  *over = inlink->dst->priv;
123     char *expr;
124     double var_values[VAR_VARS_NB], res;
125     int ret;
126
127     /* Finish the configuration by evaluating the expressions
128        now when both inputs are configured. */
129     var_values[VAR_E  ] = M_E;
130     var_values[VAR_PHI] = M_PHI;
131     var_values[VAR_PI ] = M_PI;
132
133     var_values[VAR_MAIN_W   ] = var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
134     var_values[VAR_MAIN_H   ] = var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
135     var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
136     var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
137
138     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
139                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
140         goto fail;
141     over->x = res;
142     if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
143                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)))
144         goto fail;
145     over->y = res;
146     /* x may depend on y */
147     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
148                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
149         goto fail;
150     over->x = res;
151
152     av_log(ctx, AV_LOG_INFO,
153            "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
154            ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
155            av_pix_fmt_descriptors[ctx->inputs[MAIN]->format].name,
156            over->x, over->y,
157            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
158            av_pix_fmt_descriptors[ctx->inputs[OVERLAY]->format].name);
159
160     if (over->x < 0 || over->y < 0 ||
161         over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
162         over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
163         av_log(ctx, AV_LOG_ERROR,
164                "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
165                over->x, over->y,
166                (int)(over->x + var_values[VAR_OVERLAY_W]),
167                (int)(over->y + var_values[VAR_OVERLAY_H]),
168                (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
169         return AVERROR(EINVAL);
170     }
171     return 0;
172
173 fail:
174     av_log(NULL, AV_LOG_ERROR,
175            "Error when evaluating the expression '%s'\n", expr);
176     return ret;
177 }
178
179 static int config_output(AVFilterLink *outlink)
180 {
181     AVFilterContext *ctx = outlink->src;
182     int exact;
183     // common timebase computation:
184     AVRational tb1 = ctx->inputs[MAIN   ]->time_base;
185     AVRational tb2 = ctx->inputs[OVERLAY]->time_base;
186     AVRational *tb = &ctx->outputs[0]->time_base;
187     exact = av_reduce(&tb->num, &tb->den,
188                       av_gcd((int64_t)tb1.num * tb2.den,
189                              (int64_t)tb2.num * tb1.den),
190                       (int64_t)tb1.den * tb2.den, INT_MAX);
191     av_log(ctx, AV_LOG_INFO,
192            "main_tb:%d/%d overlay_tb:%d/%d -> tb:%d/%d exact:%d\n",
193            tb1.num, tb1.den, tb2.num, tb2.den, tb->num, tb->den, exact);
194     if (!exact)
195         av_log(ctx, AV_LOG_WARNING,
196                "Timestamp conversion inexact, timestamp information loss may occurr\n");
197
198     outlink->w = ctx->inputs[MAIN]->w;
199     outlink->h = ctx->inputs[MAIN]->h;
200
201     return 0;
202 }
203
204 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
205 {
206     return avfilter_get_video_buffer(link->dst->outputs[0], perms, w, h);
207 }
208
209 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
210 {
211     AVFilterBufferRef *outpicref = avfilter_ref_buffer(inpicref, ~0);
212     AVFilterContext *ctx = inlink->dst;
213     OverlayContext *over = ctx->priv;
214
215     inlink->dst->outputs[0]->out_buf = outpicref;
216     outpicref->pts = av_rescale_q(outpicref->pts, ctx->inputs[MAIN]->time_base,
217                                   ctx->outputs[0]->time_base);
218
219     if (!over->overpicref || over->overpicref->pts < outpicref->pts) {
220         AVFilterBufferRef *old = over->overpicref;
221         over->overpicref = NULL;
222         avfilter_request_frame(ctx->inputs[OVERLAY]);
223         if (over->overpicref) {
224             if (old)
225                 avfilter_unref_buffer(old);
226         } else
227             over->overpicref = old;
228     }
229
230     avfilter_start_frame(inlink->dst->outputs[0], outpicref);
231 }
232
233 static void start_frame_overlay(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
234 {
235     AVFilterContext *ctx = inlink->dst;
236     OverlayContext *over = ctx->priv;
237
238     over->overpicref = inpicref;
239     over->overpicref->pts = av_rescale_q(inpicref->pts, ctx->inputs[OVERLAY]->time_base,
240                                          ctx->outputs[0]->time_base);
241 }
242
243 static void blend_slice(AVFilterContext *ctx,
244                         AVFilterBufferRef *dst, AVFilterBufferRef *src,
245                         int x, int y, int w, int h,
246                         int slice_y, int slice_w, int slice_h)
247 {
248     OverlayContext *over = ctx->priv;
249     int i, j, k;
250     int width, height;
251     int overlay_end_y = y+h;
252     int slice_end_y = slice_y+slice_h;
253     int end_y, start_y;
254
255     width = FFMIN(slice_w - x, w);
256     end_y = FFMIN(slice_end_y, overlay_end_y);
257     start_y = FFMAX(y, slice_y);
258     height = end_y - start_y;
259
260     if (dst->format == PIX_FMT_BGR24 || dst->format == PIX_FMT_RGB24) {
261         uint8_t *dp = dst->data[0] + x * 3 + start_y * dst->linesize[0];
262         uint8_t *sp = src->data[0];
263         int b = dst->format == PIX_FMT_BGR24 ? 2 : 0;
264         int r = dst->format == PIX_FMT_BGR24 ? 0 : 2;
265         if (slice_y > y)
266             sp += (slice_y - y) * src->linesize[0];
267         for (i = 0; i < height; i++) {
268             uint8_t *d = dp, *s = sp;
269             for (j = 0; j < width; j++) {
270                 d[r] = (d[r] * (0xff - s[3]) + s[0] * s[3] + 128) >> 8;
271                 d[1] = (d[1] * (0xff - s[3]) + s[1] * s[3] + 128) >> 8;
272                 d[b] = (d[b] * (0xff - s[3]) + s[2] * s[3] + 128) >> 8;
273                 d += 3;
274                 s += 4;
275             }
276             dp += dst->linesize[0];
277             sp += src->linesize[0];
278         }
279     } else {
280         for (i = 0; i < 3; i++) {
281             int hsub = i ? over->hsub : 0;
282             int vsub = i ? over->vsub : 0;
283             uint8_t *dp = dst->data[i] + (x >> hsub) +
284                 (start_y >> vsub) * dst->linesize[i];
285             uint8_t *sp = src->data[i];
286             uint8_t *ap = src->data[3];
287             int wp = FFALIGN(width, 1<<hsub) >> hsub;
288             int hp = FFALIGN(height, 1<<vsub) >> vsub;
289             if (slice_y > y) {
290                 sp += ((slice_y - y) >> vsub) * src->linesize[i];
291                 ap += (slice_y - y) * src->linesize[3];
292             }
293             for (j = 0; j < hp; j++) {
294                 uint8_t *d = dp, *s = sp, *a = ap;
295                 for (k = 0; k < wp; k++) {
296                     // average alpha for color components, improve quality
297                     int alpha_v, alpha_h, alpha;
298                     if (hsub && vsub && j+1 < hp && k+1 < wp) {
299                         alpha = (a[0] + a[src->linesize[3]] +
300                                  a[1] + a[src->linesize[3]+1]) >> 2;
301                     } else if (hsub || vsub) {
302                         alpha_h = hsub && k+1 < wp ?
303                             (a[0] + a[1]) >> 1 : a[0];
304                         alpha_v = vsub && j+1 < hp ?
305                             (a[0] + a[src->linesize[3]]) >> 1 : a[0];
306                         alpha = (alpha_v + alpha_h) >> 1;
307                     } else
308                         alpha = a[0];
309                     *d = (*d * (0xff - alpha) + *s++ * alpha + 128) >> 8;
310                     d++;
311                     a += 1 << hsub;
312                 }
313                 dp += dst->linesize[i];
314                 sp += src->linesize[i];
315                 ap += (1 << vsub) * src->linesize[3];
316             }
317         }
318     }
319 }
320
321 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
322 {
323     AVFilterContext *ctx = inlink->dst;
324     AVFilterLink *outlink = ctx->outputs[0];
325     AVFilterBufferRef *outpicref = outlink->out_buf;
326     OverlayContext *over = ctx->priv;
327
328     if (over->overpicref &&
329         !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||
330           y+h < over->y || y >= over->y + over->overpicref->video->h)) {
331         blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
332                     over->overpicref->video->w, over->overpicref->video->h,
333                     y, outpicref->video->w, h);
334     }
335     avfilter_draw_slice(outlink, y, h, slice_dir);
336 }
337
338 static void end_frame(AVFilterLink *inlink)
339 {
340     avfilter_end_frame(inlink->dst->outputs[0]);
341     avfilter_unref_buffer(inlink->cur_buf);
342 }
343
344 static void null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir) { }
345
346 static void null_end_frame(AVFilterLink *inlink) { }
347
348 AVFilter avfilter_vf_overlay = {
349     .name      = "overlay",
350     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
351
352     .init      = init,
353     .uninit    = uninit,
354
355     .priv_size = sizeof(OverlayContext),
356
357     .query_formats = query_formats,
358
359     .inputs    = (AVFilterPad[]) {{ .name            = "main",
360                                     .type            = AVMEDIA_TYPE_VIDEO,
361                                     .start_frame     = start_frame,
362                                     .get_video_buffer= get_video_buffer,
363                                     .config_props    = config_input_main,
364                                     .draw_slice      = draw_slice,
365                                     .end_frame       = end_frame,
366                                     .min_perms       = AV_PERM_READ,
367                                     .rej_perms       = AV_PERM_REUSE2|AV_PERM_PRESERVE, },
368                                   { .name            = "overlay",
369                                     .type            = AVMEDIA_TYPE_VIDEO,
370                                     .start_frame     = start_frame_overlay,
371                                     .config_props    = config_input_overlay,
372                                     .draw_slice      = null_draw_slice,
373                                     .end_frame       = null_end_frame,
374                                     .min_perms       = AV_PERM_READ,
375                                     .rej_perms       = AV_PERM_REUSE2, },
376                                   { .name = NULL}},
377     .outputs   = (AVFilterPad[]) {{ .name            = "default",
378                                     .type            = AVMEDIA_TYPE_VIDEO,
379                                     .config_props    = config_output, },
380                                   { .name = NULL}},
381 };