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