]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_overlay.c
Merge commit '9840130edf3a969ec06dd0faa61dcf8d90c5f67a'
[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     enum OverlayFormat { OVERLAY_FORMAT_YUV420, OVERLAY_FORMAT_YUV444, OVERLAY_FORMAT_RGB, OVERLAY_FORMAT_NB} format;
87
88     AVFilterBufferRef *overpicref;
89     struct FFBufQueue queue_main;
90     struct FFBufQueue queue_over;
91
92     int main_pix_step[4];       ///< steps per pixel for each plane of the main output
93     int overlay_pix_step[4];    ///< steps per pixel for each plane of the overlay
94     int hsub, vsub;             ///< chroma subsampling values
95     int shortest;               ///< terminate stream when the shortest input terminates
96
97     char *x_expr, *y_expr;
98 } OverlayContext;
99
100 #define OFFSET(x) offsetof(OverlayContext, x)
101 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
102
103 static const AVOption overlay_options[] = {
104     { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
105     { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
106     { "rgb", "force packed RGB in input and output (deprecated)", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
107     { "shortest", "force termination when the shortest input terminates", OFFSET(shortest), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
108
109     { "format", "set output format", OFFSET(format), AV_OPT_TYPE_INT, {.i64=OVERLAY_FORMAT_YUV420}, 0, OVERLAY_FORMAT_NB-1, FLAGS, "format" },
110     { "yuv420", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV420}, .flags = FLAGS, .unit = "format" },
111     { "yuv444", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV444}, .flags = FLAGS, .unit = "format" },
112     { "rgb",    "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_RGB},    .flags = FLAGS, .unit = "format" },
113
114     { NULL }
115 };
116
117 AVFILTER_DEFINE_CLASS(overlay);
118
119 static av_cold int init(AVFilterContext *ctx, const char *args)
120 {
121     OverlayContext *over = ctx->priv;
122     static const char *shorthand[] = { "x", "y", NULL };
123     int ret;
124
125     over->class = &overlay_class;
126     av_opt_set_defaults(over);
127
128     ret = av_opt_set_from_string(over, args, shorthand, "=", ":");
129     if (ret < 0)
130         return ret;
131
132     if (over->allow_packed_rgb) {
133         av_log(ctx, AV_LOG_WARNING,
134                "The rgb option is deprecated and is overriding the format option, use format instead\n");
135         over->format = OVERLAY_FORMAT_RGB;
136     }
137     return 0;
138 }
139
140 static av_cold void uninit(AVFilterContext *ctx)
141 {
142     OverlayContext *over = ctx->priv;
143
144     av_opt_free(over);
145
146     avfilter_unref_bufferp(&over->overpicref);
147     ff_bufqueue_discard_all(&over->queue_main);
148     ff_bufqueue_discard_all(&over->queue_over);
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     static const enum AVPixelFormat main_pix_fmts_yuv420[] = {
157         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
158     };
159     static const enum AVPixelFormat overlay_pix_fmts_yuv420[] = {
160         AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
161     };
162
163     static const enum AVPixelFormat main_pix_fmts_yuv444[] = {
164         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
165     };
166     static const enum AVPixelFormat overlay_pix_fmts_yuv444[] = {
167         AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
168     };
169
170     static const enum AVPixelFormat main_pix_fmts_rgb[] = {
171         AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
172         AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
173         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
174         AV_PIX_FMT_NONE
175     };
176     static const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
177         AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
178         AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
179         AV_PIX_FMT_NONE
180     };
181
182     AVFilterFormats *main_formats;
183     AVFilterFormats *overlay_formats;
184
185     switch (over->format) {
186     case OVERLAY_FORMAT_YUV420:
187         main_formats    = ff_make_format_list(main_pix_fmts_yuv420);
188         overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv420);
189         break;
190     case OVERLAY_FORMAT_YUV444:
191         main_formats    = ff_make_format_list(main_pix_fmts_yuv444);
192         overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv444);
193         break;
194     case OVERLAY_FORMAT_RGB:
195         main_formats    = ff_make_format_list(main_pix_fmts_rgb);
196         overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
197         break;
198     default:
199         av_assert0(0);
200     }
201
202     ff_formats_ref(main_formats,    &ctx->inputs [MAIN   ]->out_formats);
203     ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
204     ff_formats_ref(main_formats,    &ctx->outputs[MAIN   ]->in_formats );
205
206     return 0;
207 }
208
209 static const enum AVPixelFormat alpha_pix_fmts[] = {
210     AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA444P,
211     AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
212     AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
213 };
214
215 static int config_input_main(AVFilterLink *inlink)
216 {
217     OverlayContext *over = inlink->dst->priv;
218     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
219
220     av_image_fill_max_pixsteps(over->main_pix_step,    NULL, pix_desc);
221
222     over->hsub = pix_desc->log2_chroma_w;
223     over->vsub = pix_desc->log2_chroma_h;
224
225     over->main_is_packed_rgb =
226         ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
227     over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
228     return 0;
229 }
230
231 static int config_input_overlay(AVFilterLink *inlink)
232 {
233     AVFilterContext *ctx  = inlink->dst;
234     OverlayContext  *over = inlink->dst->priv;
235     char *expr;
236     double var_values[VAR_VARS_NB], res;
237     int ret;
238     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
239
240     av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
241
242     /* Finish the configuration by evaluating the expressions
243        now when both inputs are configured. */
244     var_values[VAR_MAIN_W   ] = var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
245     var_values[VAR_MAIN_H   ] = var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
246     var_values[VAR_OVERLAY_W] = var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
247     var_values[VAR_OVERLAY_H] = var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
248
249     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
250                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
251         goto fail;
252     over->x = res;
253     if ((ret = av_expr_parse_and_eval(&res, (expr = over->y_expr), var_names, var_values,
254                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)))
255         goto fail;
256     over->y = res;
257     /* x may depend on y */
258     if ((ret = av_expr_parse_and_eval(&res, (expr = over->x_expr), var_names, var_values,
259                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
260         goto fail;
261     over->x = res;
262
263     over->overlay_is_packed_rgb =
264         ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
265     over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
266
267     av_log(ctx, AV_LOG_VERBOSE,
268            "main w:%d h:%d fmt:%s overlay x:%d y:%d w:%d h:%d fmt:%s\n",
269            ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
270            av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
271            over->x, over->y,
272            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
273            av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
274
275     if (over->x < 0 || over->y < 0 ||
276         over->x + var_values[VAR_OVERLAY_W] > var_values[VAR_MAIN_W] ||
277         over->y + var_values[VAR_OVERLAY_H] > var_values[VAR_MAIN_H]) {
278         av_log(ctx, AV_LOG_ERROR,
279                "Overlay area (%d,%d)<->(%d,%d) not within the main area (0,0)<->(%d,%d) or zero-sized\n",
280                over->x, over->y,
281                (int)(over->x + var_values[VAR_OVERLAY_W]),
282                (int)(over->y + var_values[VAR_OVERLAY_H]),
283                (int)var_values[VAR_MAIN_W], (int)var_values[VAR_MAIN_H]);
284         return AVERROR(EINVAL);
285     }
286     return 0;
287
288 fail:
289     av_log(NULL, AV_LOG_ERROR,
290            "Error when evaluating the expression '%s'\n", expr);
291     return ret;
292 }
293
294 static int config_output(AVFilterLink *outlink)
295 {
296     AVFilterContext *ctx = outlink->src;
297
298     outlink->w = ctx->inputs[MAIN]->w;
299     outlink->h = ctx->inputs[MAIN]->h;
300     outlink->time_base = ctx->inputs[MAIN]->time_base;
301
302     return 0;
303 }
304
305 // divide by 255 and round to nearest
306 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
307 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
308
309 // calculate the unpremultiplied alpha, applying the general equation:
310 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
311 // (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
312 // ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
313 #define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
314
315 /**
316  * Blend image in src to destination buffer dst at position (x, y).
317  *
318  * It is assumed that the src image at position (x, y) is contained in
319  * dst.
320  */
321 static void blend_image(AVFilterContext *ctx,
322                         AVFilterBufferRef *dst, AVFilterBufferRef *src,
323                         int x, int y)
324 {
325     OverlayContext *over = ctx->priv;
326     int i, j, k;
327     int width   = src->video->w;
328     int height  = src->video->h;
329
330     if (over->main_is_packed_rgb) {
331         uint8_t *dp = dst->data[0] + x * over->main_pix_step[0] +
332                       y * dst->linesize[0];
333         uint8_t *sp = src->data[0];
334         uint8_t alpha;          ///< the amount of overlay to blend on to main
335         const int dr = over->main_rgba_map[R];
336         const int dg = over->main_rgba_map[G];
337         const int db = over->main_rgba_map[B];
338         const int da = over->main_rgba_map[A];
339         const int dstep = over->main_pix_step[0];
340         const int sr = over->overlay_rgba_map[R];
341         const int sg = over->overlay_rgba_map[G];
342         const int sb = over->overlay_rgba_map[B];
343         const int sa = over->overlay_rgba_map[A];
344         const int sstep = over->overlay_pix_step[0];
345         const int main_has_alpha = over->main_has_alpha;
346         for (i = 0; i < height; i++) {
347             uint8_t *d = dp, *s = sp;
348             for (j = 0; j < width; j++) {
349                 alpha = s[sa];
350
351                 // if the main channel has an alpha channel, alpha has to be calculated
352                 // to create an un-premultiplied (straight) alpha value
353                 if (main_has_alpha && alpha != 0 && alpha != 255) {
354                     uint8_t alpha_d = d[da];
355                     alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
356                 }
357
358                 switch (alpha) {
359                 case 0:
360                     break;
361                 case 255:
362                     d[dr] = s[sr];
363                     d[dg] = s[sg];
364                     d[db] = s[sb];
365                     break;
366                 default:
367                     // main_value = main_value * (1 - alpha) + overlay_value * alpha
368                     // since alpha is in the range 0-255, the result must divided by 255
369                     d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
370                     d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
371                     d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
372                 }
373                 if (main_has_alpha) {
374                     switch (alpha) {
375                     case 0:
376                         break;
377                     case 255:
378                         d[da] = s[sa];
379                         break;
380                     default:
381                         // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
382                         d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
383                     }
384                 }
385                 d += dstep;
386                 s += sstep;
387             }
388             dp += dst->linesize[0];
389             sp += src->linesize[0];
390         }
391     } else {
392         const int main_has_alpha = over->main_has_alpha;
393         if (main_has_alpha) {
394             uint8_t *da = dst->data[3] + x * over->main_pix_step[3] +
395                           y * dst->linesize[3];
396             uint8_t *sa = src->data[3];
397             uint8_t alpha;          ///< the amount of overlay to blend on to main
398             for (i = 0; i < height; i++) {
399                 uint8_t *d = da, *s = sa;
400                 for (j = 0; j < width; j++) {
401                     alpha = *s;
402                     if (alpha != 0 && alpha != 255) {
403                         uint8_t alpha_d = *d;
404                         alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
405                     }
406                     switch (alpha) {
407                     case 0:
408                         break;
409                     case 255:
410                         *d = *s;
411                         break;
412                     default:
413                         // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
414                         *d += FAST_DIV255((255 - *d) * *s);
415                     }
416                     d += 1;
417                     s += 1;
418                 }
419                 da += dst->linesize[3];
420                 sa += src->linesize[3];
421             }
422         }
423         for (i = 0; i < 3; i++) {
424             int hsub = i ? over->hsub : 0;
425             int vsub = i ? over->vsub : 0;
426             uint8_t *dp = dst->data[i] + (x >> hsub) +
427                 (y >> vsub) * dst->linesize[i];
428             uint8_t *sp = src->data[i];
429             uint8_t *ap = src->data[3];
430             int wp = FFALIGN(width, 1<<hsub) >> hsub;
431             int hp = FFALIGN(height, 1<<vsub) >> vsub;
432             for (j = 0; j < hp; j++) {
433                 uint8_t *d = dp, *s = sp, *a = ap;
434                 for (k = 0; k < wp; k++) {
435                     // average alpha for color components, improve quality
436                     int alpha_v, alpha_h, alpha;
437                     if (hsub && vsub && j+1 < hp && k+1 < wp) {
438                         alpha = (a[0] + a[src->linesize[3]] +
439                                  a[1] + a[src->linesize[3]+1]) >> 2;
440                     } else if (hsub || vsub) {
441                         alpha_h = hsub && k+1 < wp ?
442                             (a[0] + a[1]) >> 1 : a[0];
443                         alpha_v = vsub && j+1 < hp ?
444                             (a[0] + a[src->linesize[3]]) >> 1 : a[0];
445                         alpha = (alpha_v + alpha_h) >> 1;
446                     } else
447                         alpha = a[0];
448                     // if the main channel has an alpha channel, alpha has to be calculated
449                     // to create an un-premultiplied (straight) alpha value
450                     if (main_has_alpha && alpha != 0 && alpha != 255) {
451                         // average alpha for color components, improve quality
452                         uint8_t alpha_d;
453                         if (hsub && vsub && j+1 < hp && k+1 < wp) {
454                             alpha_d = (d[0] + d[src->linesize[3]] +
455                                        d[1] + d[src->linesize[3]+1]) >> 2;
456                         } else if (hsub || vsub) {
457                             alpha_h = hsub && k+1 < wp ?
458                                 (d[0] + d[1]) >> 1 : d[0];
459                             alpha_v = vsub && j+1 < hp ?
460                                 (d[0] + d[src->linesize[3]]) >> 1 : d[0];
461                             alpha_d = (alpha_v + alpha_h) >> 1;
462                         } else
463                             alpha_d = d[0];
464                         alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
465                     }
466                     *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
467                     s++;
468                     d++;
469                     a += 1 << hsub;
470                 }
471                 dp += dst->linesize[i];
472                 sp += src->linesize[i];
473                 ap += (1 << vsub) * src->linesize[3];
474             }
475         }
476     }
477 }
478
479 static int try_filter_frame(AVFilterContext *ctx, AVFilterBufferRef *mainpic)
480 {
481     OverlayContext *over = ctx->priv;
482     AVFilterLink *outlink = ctx->outputs[0];
483     AVFilterBufferRef *next_overpic;
484     int ret;
485
486     /* Discard obsolete overlay frames: if there is a next overlay frame with pts
487      * before the main frame, we can drop the current overlay. */
488     while (1) {
489         next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
490         if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
491                                            mainpic->pts     , ctx->inputs[MAIN]->time_base) > 0)
492             break;
493         ff_bufqueue_get(&over->queue_over);
494         avfilter_unref_buffer(over->overpicref);
495         over->overpicref = next_overpic;
496     }
497
498     /* If there is no next frame and no EOF and the overlay frame is before
499      * the main frame, we can not know yet if it will be superseded. */
500     if (!over->queue_over.available && !over->overlay_eof &&
501         (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
502                                             mainpic->pts         , ctx->inputs[MAIN]->time_base) < 0))
503         return AVERROR(EAGAIN);
504
505     /* At this point, we know that the current overlay frame extends to the
506      * time of the main frame. */
507     av_dlog(ctx, "main_pts:%s main_pts_time:%s",
508             av_ts2str(mainpic->pts), av_ts2timestr(mainpic->pts, &outlink->time_base));
509     if (over->overpicref)
510         av_dlog(ctx, " over_pts:%s over_pts_time:%s",
511                 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &outlink->time_base));
512     av_dlog(ctx, "\n");
513
514     if (over->overpicref)
515         blend_image(ctx, mainpic, over->overpicref, over->x, over->y);
516     ret = ff_filter_frame(ctx->outputs[0], mainpic);
517     av_assert1(ret != AVERROR(EAGAIN));
518     over->frame_requested = 0;
519     return ret;
520 }
521
522 static int try_filter_next_frame(AVFilterContext *ctx)
523 {
524     OverlayContext *over = ctx->priv;
525     AVFilterBufferRef *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
526     int ret;
527
528     if (!next_mainpic)
529         return AVERROR(EAGAIN);
530     if ((ret = try_filter_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
531         return ret;
532     ff_bufqueue_get(&over->queue_main);
533     return ret;
534 }
535
536 static int flush_frames(AVFilterContext *ctx)
537 {
538     int ret;
539
540     while (!(ret = try_filter_next_frame(ctx)));
541     return ret == AVERROR(EAGAIN) ? 0 : ret;
542 }
543
544 static int filter_frame_main(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
545 {
546     AVFilterContext *ctx = inlink->dst;
547     OverlayContext *over = ctx->priv;
548     int ret;
549
550     if ((ret = flush_frames(ctx)) < 0)
551         return ret;
552     if ((ret = try_filter_frame(ctx, inpicref)) < 0) {
553         if (ret != AVERROR(EAGAIN))
554             return ret;
555         ff_bufqueue_add(ctx, &over->queue_main, inpicref);
556     }
557
558     if (!over->overpicref)
559         return 0;
560     flush_frames(ctx);
561
562     return 0;
563 }
564
565 static int filter_frame_over(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
566 {
567     AVFilterContext *ctx = inlink->dst;
568     OverlayContext *over = ctx->priv;
569     int ret;
570
571     if ((ret = flush_frames(ctx)) < 0)
572         return ret;
573     ff_bufqueue_add(ctx, &over->queue_over, inpicref);
574     ret = try_filter_next_frame(ctx);
575     return ret == AVERROR(EAGAIN) ? 0 : ret;
576 }
577
578 static int request_frame(AVFilterLink *outlink)
579 {
580     AVFilterContext *ctx = outlink->src;
581     OverlayContext *over = ctx->priv;
582     int input, ret;
583
584     if (!try_filter_next_frame(ctx))
585         return 0;
586     over->frame_requested = 1;
587     while (over->frame_requested) {
588         /* TODO if we had a frame duration, we could guess more accurately */
589         input = !over->overlay_eof && (over->queue_main.available ||
590                                        over->queue_over.available < 2) ?
591                 OVERLAY : MAIN;
592         ret = ff_request_frame(ctx->inputs[input]);
593         /* EOF on main is reported immediately */
594         if (ret == AVERROR_EOF && input == OVERLAY) {
595             over->overlay_eof = 1;
596             if (over->shortest)
597                 return ret;
598             if ((ret = try_filter_next_frame(ctx)) != AVERROR(EAGAIN))
599                 return ret;
600             ret = 0; /* continue requesting frames on main */
601         }
602         if (ret < 0)
603             return ret;
604     }
605     return 0;
606 }
607
608 static const AVFilterPad avfilter_vf_overlay_inputs[] = {
609     {
610         .name         = "main",
611         .type         = AVMEDIA_TYPE_VIDEO,
612         .get_video_buffer = ff_null_get_video_buffer,
613         .config_props = config_input_main,
614         .filter_frame = filter_frame_main,
615         .min_perms    = AV_PERM_READ | AV_PERM_WRITE | AV_PERM_PRESERVE,
616     },
617     {
618         .name         = "overlay",
619         .type         = AVMEDIA_TYPE_VIDEO,
620         .config_props = config_input_overlay,
621         .filter_frame = filter_frame_over,
622         .min_perms    = AV_PERM_READ | AV_PERM_PRESERVE,
623     },
624     { NULL }
625 };
626
627 static const AVFilterPad avfilter_vf_overlay_outputs[] = {
628     {
629         .name          = "default",
630         .type          = AVMEDIA_TYPE_VIDEO,
631         .rej_perms     = AV_PERM_WRITE,
632         .config_props  = config_output,
633         .request_frame = request_frame,
634     },
635     { NULL }
636 };
637
638 AVFilter avfilter_vf_overlay = {
639     .name      = "overlay",
640     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
641
642     .init      = init,
643     .uninit    = uninit,
644
645     .priv_size = sizeof(OverlayContext),
646
647     .query_formats = query_formats,
648
649     .inputs    = avfilter_vf_overlay_inputs,
650     .outputs   = avfilter_vf_overlay_outputs,
651     .priv_class = &overlay_class,
652 };