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