]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_overlay.c
vsrc_mandelbrot: switch to filter_frame
[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 /* #define DEBUG */
29
30 #include "avfilter.h"
31 #include "formats.h"
32 #include "libavutil/common.h"
33 #include "libavutil/eval.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/imgutils.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/timestamp.h"
40 #include "internal.h"
41 #include "bufferqueue.h"
42 #include "drawutils.h"
43 #include "video.h"
44
45 static const char *const var_names[] = {
46     "main_w",    "W", ///< width  of the main    video
47     "main_h",    "H", ///< height of the main    video
48     "overlay_w", "w", ///< width  of the overlay video
49     "overlay_h", "h", ///< height of the overlay video
50     NULL
51 };
52
53 enum var_name {
54     VAR_MAIN_W,    VAR_MW,
55     VAR_MAIN_H,    VAR_MH,
56     VAR_OVERLAY_W, VAR_OW,
57     VAR_OVERLAY_H, VAR_OH,
58     VAR_VARS_NB
59 };
60
61 #define MAIN    0
62 #define OVERLAY 1
63
64 #define R 0
65 #define G 1
66 #define B 2
67 #define A 3
68
69 #define Y 0
70 #define U 1
71 #define V 2
72
73 typedef struct {
74     const AVClass *class;
75     int x, y;                   ///< position of overlayed picture
76
77     int allow_packed_rgb;
78     uint8_t frame_requested;
79     uint8_t overlay_eof;
80     uint8_t main_is_packed_rgb;
81     uint8_t main_rgba_map[4];
82     uint8_t main_has_alpha;
83     uint8_t overlay_is_packed_rgb;
84     uint8_t overlay_rgba_map[4];
85     uint8_t overlay_has_alpha;
86
87     AVFilterBufferRef *overpicref;
88     struct FFBufQueue queue_main;
89     struct FFBufQueue queue_over;
90
91     int main_pix_step[4];       ///< steps per pixel for each plane of the main output
92     int overlay_pix_step[4];    ///< steps per pixel for each plane of the overlay
93     int hsub, vsub;             ///< chroma subsampling values
94
95     char *x_expr, *y_expr;
96 } OverlayContext;
97
98 #define OFFSET(x) offsetof(OverlayContext, x)
99 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
100
101 static const AVOption overlay_options[] = {
102     { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
103     { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
104     {"rgb", "force packed RGB in input and output", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
105     {NULL},
106 };
107
108 AVFILTER_DEFINE_CLASS(overlay);
109
110 static av_cold int init(AVFilterContext *ctx, const char *args)
111 {
112     OverlayContext *over = ctx->priv;
113     char *args1 = av_strdup(args);
114     char *expr, *bufptr = NULL;
115     int ret = 0;
116
117     over->class = &overlay_class;
118     av_opt_set_defaults(over);
119
120     if (expr = av_strtok(args1, ":", &bufptr)) {
121         av_free(over->x_expr);
122         if (!(over->x_expr = av_strdup(expr))) {
123             ret = AVERROR(ENOMEM);
124             goto end;
125         }
126     }
127     if (expr = av_strtok(NULL, ":", &bufptr)) {
128         av_free(over->y_expr);
129         if (!(over->y_expr = av_strdup(expr))) {
130             ret = AVERROR(ENOMEM);
131             goto end;
132         }
133     }
134
135     if (bufptr && (ret = av_set_options_string(over, bufptr, "=", ":")) < 0)
136         goto end;
137
138 end:
139     av_free(args1);
140     return ret;
141 }
142
143 static av_cold void uninit(AVFilterContext *ctx)
144 {
145     OverlayContext *over = ctx->priv;
146
147     av_freep(&over->x_expr);
148     av_freep(&over->y_expr);
149
150     avfilter_unref_bufferp(&over->overpicref);
151     ff_bufqueue_discard_all(&over->queue_main);
152     ff_bufqueue_discard_all(&over->queue_over);
153 }
154
155 static int query_formats(AVFilterContext *ctx)
156 {
157     OverlayContext *over = ctx->priv;
158
159     /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
160     const enum AVPixelFormat main_pix_fmts_yuv[] = { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
161     const enum AVPixelFormat overlay_pix_fmts_yuv[] = { AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE };
162     const enum AVPixelFormat main_pix_fmts_rgb[] = {
163         AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
164         AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
165         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
166         AV_PIX_FMT_NONE
167     };
168     const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
169         AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
170         AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
171         AV_PIX_FMT_NONE
172     };
173
174     AVFilterFormats *main_formats;
175     AVFilterFormats *overlay_formats;
176
177     if (over->allow_packed_rgb) {
178         main_formats    = ff_make_format_list(main_pix_fmts_rgb);
179         overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
180     } else {
181         main_formats    = ff_make_format_list(main_pix_fmts_yuv);
182         overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv);
183     }
184
185     ff_formats_ref(main_formats,    &ctx->inputs [MAIN   ]->out_formats);
186     ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
187     ff_formats_ref(main_formats,    &ctx->outputs[MAIN   ]->in_formats );
188
189     return 0;
190 }
191
192 static const enum AVPixelFormat alpha_pix_fmts[] = {
193     AV_PIX_FMT_YUVA420P, AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
194     AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
195 };
196
197 static int config_input_main(AVFilterLink *inlink)
198 {
199     OverlayContext *over = inlink->dst->priv;
200     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
201
202     av_image_fill_max_pixsteps(over->main_pix_step,    NULL, pix_desc);
203
204     over->hsub = pix_desc->log2_chroma_w;
205     over->vsub = pix_desc->log2_chroma_h;
206
207     over->main_is_packed_rgb =
208         ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
209     over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
210     return 0;
211 }
212
213 static int config_input_overlay(AVFilterLink *inlink)
214 {
215     AVFilterContext *ctx  = inlink->dst;
216     OverlayContext  *over = inlink->dst->priv;
217     char *expr;
218     double var_values[VAR_VARS_NB], res;
219     int ret;
220     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
221
222     av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
223
224     /* Finish the configuration by evaluating the expressions
225        now when both inputs are configured. */
226     var_values[VAR_MAIN_W   ] = var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
227     var_values[VAR_MAIN_H   ] = var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
228     var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
229     var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
230
231     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
232                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
233         goto fail;
234     over->x = res;
235     if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
236                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)))
237         goto fail;
238     over->y = res;
239     /* x may depend on y */
240     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
241                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
242         goto fail;
243     over->x = res;
244
245     over->overlay_is_packed_rgb =
246         ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
247     over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
248
249     av_log(ctx, AV_LOG_VERBOSE,
250            "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
251            ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
252            av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
253            over->x, over->y,
254            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
255            av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
256
257     if (over->x < 0 || over->y < 0 ||
258         over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
259         over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
260         av_log(ctx, AV_LOG_ERROR,
261                "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
262                over->x, over->y,
263                (int)(over->x + var_values[VAR_OVERLAY_W]),
264                (int)(over->y + var_values[VAR_OVERLAY_H]),
265                (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
266         return AVERROR(EINVAL);
267     }
268     return 0;
269
270 fail:
271     av_log(NULL, AV_LOG_ERROR,
272            "Error when evaluating the expression '%s'\n", expr);
273     return ret;
274 }
275
276 static int config_output(AVFilterLink *outlink)
277 {
278     AVFilterContext *ctx = outlink->src;
279
280     outlink->w = ctx->inputs[MAIN]->w;
281     outlink->h = ctx->inputs[MAIN]->h;
282     outlink->time_base = ctx->inputs[MAIN]->time_base;
283
284     return 0;
285 }
286
287 static AVFilterBufferRef *get_video_buffer(AVFilterLink *link, int perms, int w, int h)
288 {
289     return ff_get_video_buffer(link->dst->outputs[0], perms, w, h);
290 }
291
292 // divide by 255 and round to nearest
293 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
294 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
295
296 // calculate the unpremultiplied alpha, applying the general equation:
297 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
298 // (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
299 // ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
300 #define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
301
302 static void blend_slice(AVFilterContext *ctx,
303                         AVFilterBufferRef *dst, AVFilterBufferRef *src,
304                         int x, int y, int w, int h,
305                         int slice_y, int slice_w, int slice_h)
306 {
307     OverlayContext *over = ctx->priv;
308     int i, j, k;
309     int width, height;
310     int overlay_end_y = y+h;
311     int slice_end_y = slice_y+slice_h;
312     int end_y, start_y;
313
314     width = FFMIN(slice_w - x, w);
315     end_y = FFMIN(slice_end_y, overlay_end_y);
316     start_y = FFMAX(y, slice_y);
317     height = end_y - start_y;
318
319     if (over->main_is_packed_rgb) {
320         uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
321                       start_y * dst->linesize[0];
322         uint8_t *sp = src->data[0];
323         uint8_t alpha;          ///< the amount of overlay to blend on to main
324         const int dr = over->main_rgba_map[R];
325         const int dg = over->main_rgba_map[G];
326         const int db = over->main_rgba_map[B];
327         const int da = over->main_rgba_map[A];
328         const int dstep = over->main_pix_step[0];
329         const int sr = over->overlay_rgba_map[R];
330         const int sg = over->overlay_rgba_map[G];
331         const int sb = over->overlay_rgba_map[B];
332         const int sa = over->overlay_rgba_map[A];
333         const int sstep = over->overlay_pix_step[0];
334         const int main_has_alpha = over->main_has_alpha;
335         if (slice_y > y)
336             sp += (slice_y - y) * src->linesize[0];
337         for (i = 0; i < height; i++) {
338             uint8_t *d = dp, *s = sp;
339             for (j = 0; j < width; j++) {
340                 alpha = s[sa];
341
342                 // if the main channel has an alpha channel, alpha has to be calculated
343                 // to create an un-premultiplied (straight) alpha value
344                 if (main_has_alpha && alpha != 0 && alpha != 255) {
345                     uint8_t alpha_d = d[da];
346                     alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
347                 }
348
349                 switch (alpha) {
350                 case 0:
351                     break;
352                 case 255:
353                     d[dr] = s[sr];
354                     d[dg] = s[sg];
355                     d[db] = s[sb];
356                     break;
357                 default:
358                     // main_value = main_value * (1 - alpha) + overlay_value * alpha
359                     // since alpha is in the range 0-255, the result must divided by 255
360                     d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
361                     d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
362                     d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
363                 }
364                 if (main_has_alpha) {
365                     switch (alpha) {
366                     case 0:
367                         break;
368                     case 255:
369                         d[da] = s[sa];
370                         break;
371                     default:
372                         // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
373                         d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
374                     }
375                 }
376                 d += dstep;
377                 s += sstep;
378             }
379             dp += dst->linesize[0];
380             sp += src->linesize[0];
381         }
382     } else {
383         const int main_has_alpha = over->main_has_alpha;
384         if (main_has_alpha) {
385             uint8_t *da = dst->data[3] + x * over->main_pix_step[3] +
386                           start_y * dst->linesize[3];
387             uint8_t *sa = src->data[3];
388             uint8_t alpha;          ///< the amount of overlay to blend on to main
389             if (slice_y > y)
390                 sa += (slice_y - y) * src->linesize[3];
391             for (i = 0; i < height; i++) {
392                 uint8_t *d = da, *s = sa;
393                 for (j = 0; j < width; j++) {
394                     alpha = *s;
395                     if (alpha != 0 && alpha != 255) {
396                         uint8_t alpha_d = *d;
397                         alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
398                     }
399                     switch (alpha) {
400                     case 0:
401                         break;
402                     case 255:
403                         *d = *s;
404                         break;
405                     default:
406                         // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
407                         *d += FAST_DIV255((255 - *d) * *s);
408                     }
409                     d += 1;
410                     s += 1;
411                 }
412                 da += dst->linesize[3];
413                 sa += src->linesize[3];
414             }
415         }
416         for (i = 0; i < 3; i++) {
417             int hsub = i ? over->hsub : 0;
418             int vsub = i ? over->vsub : 0;
419             uint8_t *dp = dst->data[i] + (x >> hsub) +
420                 (start_y >> vsub) * dst->linesize[i];
421             uint8_t *sp = src->data[i];
422             uint8_t *ap = src->data[3];
423             int wp = FFALIGN(width, 1<<hsub) >> hsub;
424             int hp = FFALIGN(height, 1<<vsub) >> vsub;
425             if (slice_y > y) {
426                 sp += ((slice_y - y) >> vsub) * src->linesize[i];
427                 ap += (slice_y - y) * src->linesize[3];
428             }
429             for (j = 0; j < hp; j++) {
430                 uint8_t *d = dp, *s = sp, *a = ap;
431                 for (k = 0; k < wp; k++) {
432                     // average alpha for color components, improve quality
433                     int alpha_v, alpha_h, alpha;
434                     if (hsub && vsub && j+1 < hp && k+1 < wp) {
435                         alpha = (a[0] + a[src->linesize[3]] +
436                                  a[1] + a[src->linesize[3]+1]) >> 2;
437                     } else if (hsub || vsub) {
438                         alpha_h = hsub && k+1 < wp ?
439                             (a[0] + a[1]) >> 1 : a[0];
440                         alpha_v = vsub && j+1 < hp ?
441                             (a[0] + a[src->linesize[3]]) >> 1 : a[0];
442                         alpha = (alpha_v + alpha_h) >> 1;
443                     } else
444                         alpha = a[0];
445                     // if the main channel has an alpha channel, alpha has to be calculated
446                     // to create an un-premultiplied (straight) alpha value
447                     if (main_has_alpha && alpha != 0 && alpha != 255) {
448                         // average alpha for color components, improve quality
449                         uint8_t alpha_d;
450                         if (hsub && vsub && j+1 < hp && k+1 < wp) {
451                             alpha_d = (d[0] + d[src->linesize[3]] +
452                                        d[1] + d[src->linesize[3]+1]) >> 2;
453                         } else if (hsub || vsub) {
454                             alpha_h = hsub && k+1 < wp ?
455                                 (d[0] + d[1]) >> 1 : d[0];
456                             alpha_v = vsub && j+1 < hp ?
457                                 (d[0] + d[src->linesize[3]]) >> 1 : d[0];
458                             alpha_d = (alpha_v + alpha_h) >> 1;
459                         } else
460                             alpha_d = d[0];
461                         alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
462                     }
463                     *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
464                     s++;
465                     d++;
466                     a += 1 << hsub;
467                 }
468                 dp += dst->linesize[i];
469                 sp += src->linesize[i];
470                 ap += (1 << vsub) * src->linesize[3];
471             }
472         }
473     }
474 }
475
476 static int try_start_frame(AVFilterContext *ctx, AVFilterBufferRef *mainpic)
477 {
478     OverlayContext *over = ctx->priv;
479     AVFilterLink *outlink = ctx->outputs[0];
480     AVFilterBufferRef *next_overpic, *outpicref;
481     int ret;
482
483     /* Discard obsolete overlay frames: if there is a next frame with pts is
484      * before the main frame, we can drop the current overlay. */
485     while (1) {
486         next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
487         if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
488                                            mainpic->pts     , ctx->inputs[MAIN]->time_base) > 0)
489             break;
490         ff_bufqueue_get(&over->queue_over);
491         avfilter_unref_buffer(over->overpicref);
492         over->overpicref = next_overpic;
493     }
494     /* If there is no next frame and no EOF and the overlay frame is before
495      * the main frame, we can not know yet if it will be superseded. */
496     if (!over->queue_over.available && !over->overlay_eof &&
497         (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
498                                             mainpic->pts         , ctx->inputs[MAIN]->time_base) < 0))
499         return AVERROR(EAGAIN);
500     /* At this point, we know that the current overlay frame extends to the
501      * time of the main frame. */
502     outlink->out_buf = outpicref = avfilter_ref_buffer(mainpic, ~0);
503
504     av_dlog(ctx, "main_pts:%s main_pts_time:%s",
505             av_ts2str(outpicref->pts), av_ts2timestr(outpicref->pts, &outlink->time_base));
506     if (over->overpicref)
507         av_dlog(ctx, " over_pts:%s over_pts_time:%s",
508                 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
509     av_dlog(ctx, "\n");
510
511     ret = ff_start_frame(ctx->outputs[0], avfilter_ref_buffer(outpicref, ~0));
512     over->frame_requested = 0;
513     return ret;
514 }
515
516 static int try_start_next_frame(AVFilterContext *ctx)
517 {
518     OverlayContext *over = ctx->priv;
519     AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
520     int ret;
521
522     if (!next_mainpic)
523         return AVERROR(EAGAIN);
524     if ((ret = try_start_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
525         return ret;
526     avfilter_unref_buffer(ff_bufqueue_get(&over->queue_main));
527     return ret;
528 }
529
530 static int try_push_frame(AVFilterContext *ctx)
531 {
532     OverlayContext *over = ctx->priv;
533     AVFilterLink *outlink = ctx->outputs[0];
534     AVFilterBufferRef *outpicref;
535     int ret;
536
537     if ((ret = try_start_next_frame(ctx)) < 0)
538         return ret;
539     outpicref = outlink->out_buf;
540     if (over->overpicref)
541         blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
542                     over->overpicref->video->w, over->overpicref->video->h,
543                     0, outpicref->video->w, outpicref->video->h);
544     if ((ret = ff_draw_slice(outlink, 0, outpicref->video->h, +1)) < 0 ||
545         (ret = ff_end_frame(outlink)) < 0)
546         return ret;
547     return 0;
548 }
549
550 static int flush_frames(AVFilterContext *ctx)
551 {
552     int ret;
553
554     while (!(ret = try_push_frame(ctx)));
555     return ret == AVERROR(EAGAIN) ? 0 : ret;
556 }
557
558 static int start_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
559 {
560     AVFilterContext *ctx = inlink->dst;
561     OverlayContext *over = ctx->priv;
562     int ret;
563
564     if ((ret = flush_frames(ctx)) < 0)
565         return ret;
566     if ((ret = try_start_frame(ctx, inpicref)) < 0) {
567         if (ret != AVERROR(EAGAIN))
568             return ret;
569         ff_bufqueue_add(ctx, &over->queue_main, inpicref);
570         av_assert1(inpicref == inlink->cur_buf);
571         inlink->cur_buf = NULL;
572     }
573     return 0;
574 }
575
576 static int draw_slice_main(AVFilterLink *inlink, int y, int h, int slice_dir)
577 {
578     AVFilterContext *ctx = inlink->dst;
579     OverlayContext *over = ctx->priv;
580     AVFilterLink *outlink = ctx->outputs[0];
581     AVFilterBufferRef *outpicref = outlink->out_buf;
582
583     if (!outpicref)
584         return 0;
585     if (over->overpicref &&
586         y + h > over->y && y < over->y + over->overpicref->video->h) {
587         blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,
588                     over->overpicref->video->w, over->overpicref->video->h,
589                     y, outpicref->video->w, h);
590     }
591     return ff_draw_slice(outlink, y, h, slice_dir);
592 }
593
594 static int end_frame_main(AVFilterLink *inlink)
595 {
596     AVFilterContext *ctx = inlink->dst;
597     AVFilterLink *outlink = ctx->outputs[0];
598     AVFilterBufferRef *outpicref = outlink->out_buf;
599     flush_frames(ctx);
600
601     if (!outpicref)
602         return 0;
603     return ff_end_frame(ctx->outputs[0]);
604 }
605
606 static int start_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
607 {
608     return 0;
609 }
610
611 static int end_frame_over(AVFilterLink *inlink)
612 {
613     AVFilterContext *ctx = inlink->dst;
614     OverlayContext *over = ctx->priv;
615     AVFilterBufferRef *inpicref = inlink->cur_buf;
616     int ret;
617
618     inlink->cur_buf = NULL;
619
620     if ((ret = flush_frames(ctx)) < 0)
621         return ret;
622     ff_bufqueue_add(ctx, &over->queue_over, inpicref);
623     ret = try_push_frame(ctx);
624     return ret == AVERROR(EAGAIN) ? 0 : ret;
625 }
626
627 static int request_frame(AVFilterLink *outlink)
628 {
629     AVFilterContext *ctx = outlink->src;
630     OverlayContext *over = ctx->priv;
631     int input, ret;
632
633     if (!try_push_frame(ctx))
634         return 0;
635     over->frame_requested = 1;
636     while (over->frame_requested) {
637         /* TODO if we had a frame duration, we could guess more accurately */
638         input = !over->overlay_eof && (over->queue_main.available ||
639                                        over->queue_over.available < 2) ?
640                 OVERLAY : MAIN;
641         ret = ff_request_frame(ctx->inputs[input]);
642         /* EOF on main is reported immediately */
643         if (ret == AVERROR_EOF && input == OVERLAY) {
644             over->overlay_eof = 1;
645             if ((ret = try_start_next_frame(ctx)) != AVERROR(EAGAIN))
646                 return ret;
647             ret = 0; /* continue requesting frames on main */
648         }
649         if (ret < 0)
650             return ret;
651     }
652     return 0;
653 }
654
655 static int null_draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
656 {
657     return 0;
658 }
659
660 static const AVFilterPad avfilter_vf_overlay_inputs[] = {
661     {
662         .name         = "main",
663         .type         = AVMEDIA_TYPE_VIDEO,
664         .get_video_buffer= get_video_buffer,
665         .config_props = config_input_main,
666         .start_frame  = start_frame_main,
667         .draw_slice   = draw_slice_main,
668         .end_frame    = end_frame_main,
669         .min_perms    = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE,
670     },
671     {
672         .name         = "overlay",
673         .type         = AVMEDIA_TYPE_VIDEO,
674         .config_props = config_input_overlay,
675         .start_frame  = start_frame_over,
676         .draw_slice   = null_draw_slice,
677         .end_frame    = end_frame_over,
678         .min_perms    = AV_PERM_READ | AV_PERM_PRESERVE,
679     },
680     { NULL }
681 };
682
683 static const AVFilterPad avfilter_vf_overlay_outputs[] = {
684     {
685         .name          = "default",
686         .type          = AVMEDIA_TYPE_VIDEO,
687         .rej_perms     = AV_PERM_WRITE,
688         .config_props  = config_output,
689         .request_frame = request_frame,
690     },
691     { NULL }
692 };
693
694 AVFilter avfilter_vf_overlay = {
695     .name      = "overlay",
696     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
697
698     .init      = init,
699     .uninit    = uninit,
700
701     .priv_size = sizeof(OverlayContext),
702
703     .query_formats = query_formats,
704
705     .inputs    = avfilter_vf_overlay_inputs,
706     .outputs   = avfilter_vf_overlay_outputs,
707     .priv_class = &overlay_class,
708 };