]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_overlay.c
lavfi/overlay: reindent fix.
[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/opt.h"
40 #include "libavutil/timestamp.h"
41 #include "internal.h"
42 #include "bufferqueue.h"
43 #include "drawutils.h"
44 #include "video.h"
45
46 static const char *const var_names[] = {
47     "main_w",    "W", ///< width  of the main    video
48     "main_h",    "H", ///< height of the main    video
49     "overlay_w", "w", ///< width  of the overlay video
50     "overlay_h", "h", ///< height of the overlay video
51     "hsub",
52     "vsub",
53     "x",
54     "y",
55     "n",            ///< number of frame
56     "pos",          ///< position in the file
57     "t",            ///< timestamp expressed in seconds
58     NULL
59 };
60
61 enum var_name {
62     VAR_MAIN_W,    VAR_MW,
63     VAR_MAIN_H,    VAR_MH,
64     VAR_OVERLAY_W, VAR_OW,
65     VAR_OVERLAY_H, VAR_OH,
66     VAR_HSUB,
67     VAR_VSUB,
68     VAR_X,
69     VAR_Y,
70     VAR_N,
71     VAR_POS,
72     VAR_T,
73     VAR_VARS_NB
74 };
75
76 #define MAIN    0
77 #define OVERLAY 1
78
79 #define R 0
80 #define G 1
81 #define B 2
82 #define A 3
83
84 #define Y 0
85 #define U 1
86 #define V 2
87
88 typedef struct {
89     const AVClass *class;
90     int x, y;                   ///< position of overlayed picture
91     int enable;                 ///< tells if blending is enabled
92
93     int allow_packed_rgb;
94     uint8_t frame_requested;
95     uint8_t overlay_eof;
96     uint8_t main_is_packed_rgb;
97     uint8_t main_rgba_map[4];
98     uint8_t main_has_alpha;
99     uint8_t overlay_is_packed_rgb;
100     uint8_t overlay_rgba_map[4];
101     uint8_t overlay_has_alpha;
102     enum OverlayFormat { OVERLAY_FORMAT_YUV420, OVERLAY_FORMAT_YUV444, OVERLAY_FORMAT_RGB, OVERLAY_FORMAT_NB} format;
103     enum EvalMode { EVAL_MODE_INIT, EVAL_MODE_FRAME, EVAL_MODE_NB } eval_mode;
104
105     AVFrame *overpicref;
106     struct FFBufQueue queue_main;
107     struct FFBufQueue queue_over;
108
109     int main_pix_step[4];       ///< steps per pixel for each plane of the main output
110     int overlay_pix_step[4];    ///< steps per pixel for each plane of the overlay
111     int hsub, vsub;             ///< chroma subsampling values
112     int shortest;               ///< terminate stream when the shortest input terminates
113     int repeatlast;             ///< repeat last overlay frame
114
115     double var_values[VAR_VARS_NB];
116     char *x_expr, *y_expr;
117     AVExpr *x_pexpr, *y_pexpr;
118 } OverlayContext;
119
120 static av_cold int init(AVFilterContext *ctx)
121 {
122     OverlayContext *over = ctx->priv;
123
124     if (over->allow_packed_rgb) {
125         av_log(ctx, AV_LOG_WARNING,
126                "The rgb option is deprecated and is overriding the format option, use format instead\n");
127         over->format = OVERLAY_FORMAT_RGB;
128     }
129     return 0;
130 }
131
132 static av_cold void uninit(AVFilterContext *ctx)
133 {
134     OverlayContext *over = ctx->priv;
135
136     av_frame_free(&over->overpicref);
137     ff_bufqueue_discard_all(&over->queue_main);
138     ff_bufqueue_discard_all(&over->queue_over);
139     av_expr_free(over->x_pexpr); over->x_pexpr = NULL;
140     av_expr_free(over->y_pexpr); over->y_pexpr = NULL;
141 }
142
143 static inline int normalize_xy(double d, int chroma_sub)
144 {
145     if (isnan(d))
146         return INT_MAX;
147     return (int)d & ~((1 << chroma_sub) - 1);
148 }
149
150 static void eval_expr(AVFilterContext *ctx)
151 {
152     OverlayContext  *over = ctx->priv;
153
154     over->var_values[VAR_X] = av_expr_eval(over->x_pexpr, over->var_values, NULL);
155     over->var_values[VAR_Y] = av_expr_eval(over->y_pexpr, over->var_values, NULL);
156     over->var_values[VAR_X] = av_expr_eval(over->x_pexpr, over->var_values, NULL);
157     over->x = normalize_xy(over->var_values[VAR_X], over->hsub);
158     over->y = normalize_xy(over->var_values[VAR_Y], over->vsub);
159 }
160
161 static int set_expr(AVExpr **pexpr, const char *expr, const char *option, void *log_ctx)
162 {
163     int ret;
164     AVExpr *old = NULL;
165
166     if (*pexpr)
167         old = *pexpr;
168     ret = av_expr_parse(pexpr, expr, var_names,
169                         NULL, NULL, NULL, NULL, 0, log_ctx);
170     if (ret < 0) {
171         av_log(log_ctx, AV_LOG_ERROR,
172                "Error when evaluating the expression '%s' for %s\n",
173                expr, option);
174         *pexpr = old;
175         return ret;
176     }
177
178     av_expr_free(old);
179     return 0;
180 }
181
182 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
183                            char *res, int res_len, int flags)
184 {
185     OverlayContext *over = ctx->priv;
186     int ret;
187
188     if      (!strcmp(cmd, "x"))
189         ret = set_expr(&over->x_pexpr, args, cmd, ctx);
190     else if (!strcmp(cmd, "y"))
191         ret = set_expr(&over->y_pexpr, args, cmd, ctx);
192     else
193         ret = AVERROR(ENOSYS);
194
195     if (ret < 0)
196         return ret;
197
198     if (over->eval_mode == EVAL_MODE_INIT) {
199         eval_expr(ctx);
200         av_log(ctx, AV_LOG_VERBOSE, "x:%f xi:%d y:%f yi:%d\n",
201                over->var_values[VAR_X], over->x,
202                over->var_values[VAR_Y], over->y);
203     }
204     return ret;
205 }
206
207 static int query_formats(AVFilterContext *ctx)
208 {
209     OverlayContext *over = ctx->priv;
210
211     /* overlay formats contains alpha, for avoiding conversion with alpha information loss */
212     static const enum AVPixelFormat main_pix_fmts_yuv420[] = {
213         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
214     };
215     static const enum AVPixelFormat overlay_pix_fmts_yuv420[] = {
216         AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE
217     };
218
219     static const enum AVPixelFormat main_pix_fmts_yuv444[] = {
220         AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
221     };
222     static const enum AVPixelFormat overlay_pix_fmts_yuv444[] = {
223         AV_PIX_FMT_YUVA444P, AV_PIX_FMT_NONE
224     };
225
226     static const enum AVPixelFormat main_pix_fmts_rgb[] = {
227         AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
228         AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
229         AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
230         AV_PIX_FMT_NONE
231     };
232     static const enum AVPixelFormat overlay_pix_fmts_rgb[] = {
233         AV_PIX_FMT_ARGB,  AV_PIX_FMT_RGBA,
234         AV_PIX_FMT_ABGR,  AV_PIX_FMT_BGRA,
235         AV_PIX_FMT_NONE
236     };
237
238     AVFilterFormats *main_formats;
239     AVFilterFormats *overlay_formats;
240
241     switch (over->format) {
242     case OVERLAY_FORMAT_YUV420:
243         main_formats    = ff_make_format_list(main_pix_fmts_yuv420);
244         overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv420);
245         break;
246     case OVERLAY_FORMAT_YUV444:
247         main_formats    = ff_make_format_list(main_pix_fmts_yuv444);
248         overlay_formats = ff_make_format_list(overlay_pix_fmts_yuv444);
249         break;
250     case OVERLAY_FORMAT_RGB:
251         main_formats    = ff_make_format_list(main_pix_fmts_rgb);
252         overlay_formats = ff_make_format_list(overlay_pix_fmts_rgb);
253         break;
254     default:
255         av_assert0(0);
256     }
257
258     ff_formats_ref(main_formats,    &ctx->inputs [MAIN   ]->out_formats);
259     ff_formats_ref(overlay_formats, &ctx->inputs [OVERLAY]->out_formats);
260     ff_formats_ref(main_formats,    &ctx->outputs[MAIN   ]->in_formats );
261
262     return 0;
263 }
264
265 static const enum AVPixelFormat alpha_pix_fmts[] = {
266     AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA444P,
267     AV_PIX_FMT_ARGB, AV_PIX_FMT_ABGR, AV_PIX_FMT_RGBA,
268     AV_PIX_FMT_BGRA, AV_PIX_FMT_NONE
269 };
270
271 static int config_input_main(AVFilterLink *inlink)
272 {
273     OverlayContext *over = inlink->dst->priv;
274     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
275
276     av_image_fill_max_pixsteps(over->main_pix_step,    NULL, pix_desc);
277
278     over->hsub = pix_desc->log2_chroma_w;
279     over->vsub = pix_desc->log2_chroma_h;
280
281     over->main_is_packed_rgb =
282         ff_fill_rgba_map(over->main_rgba_map, inlink->format) >= 0;
283     over->main_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
284     return 0;
285 }
286
287 static int config_input_overlay(AVFilterLink *inlink)
288 {
289     AVFilterContext *ctx  = inlink->dst;
290     OverlayContext  *over = inlink->dst->priv;
291     int ret;
292     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
293
294     av_image_fill_max_pixsteps(over->overlay_pix_step, NULL, pix_desc);
295
296     /* Finish the configuration by evaluating the expressions
297        now when both inputs are configured. */
298     over->var_values[VAR_MAIN_W   ] = over->var_values[VAR_MW] = ctx->inputs[MAIN   ]->w;
299     over->var_values[VAR_MAIN_H   ] = over->var_values[VAR_MH] = ctx->inputs[MAIN   ]->h;
300     over->var_values[VAR_OVERLAY_W] = over->var_values[VAR_OW] = ctx->inputs[OVERLAY]->w;
301     over->var_values[VAR_OVERLAY_H] = over->var_values[VAR_OH] = ctx->inputs[OVERLAY]->h;
302     over->var_values[VAR_HSUB]  = 1<<pix_desc->log2_chroma_w;
303     over->var_values[VAR_VSUB]  = 1<<pix_desc->log2_chroma_h;
304     over->var_values[VAR_X]     = NAN;
305     over->var_values[VAR_Y]     = NAN;
306     over->var_values[VAR_N]     = 0;
307     over->var_values[VAR_T]     = NAN;
308     over->var_values[VAR_POS]   = NAN;
309
310     if ((ret = set_expr(&over->x_pexpr,      over->x_expr,      "x",      ctx)) < 0 ||
311         (ret = set_expr(&over->y_pexpr,      over->y_expr,      "y",      ctx)) < 0)
312         return ret;
313
314     over->overlay_is_packed_rgb =
315         ff_fill_rgba_map(over->overlay_rgba_map, inlink->format) >= 0;
316     over->overlay_has_alpha = ff_fmt_is_in(inlink->format, alpha_pix_fmts);
317
318     if (over->eval_mode == EVAL_MODE_INIT) {
319         eval_expr(ctx);
320         av_log(ctx, AV_LOG_VERBOSE, "x:%f xi:%d y:%f yi:%d\n",
321                over->var_values[VAR_X], over->x,
322                over->var_values[VAR_Y], over->y);
323     }
324
325     av_log(ctx, AV_LOG_VERBOSE,
326            "main w:%d h:%d fmt:%s overlay w:%d h:%d fmt:%s\n",
327            ctx->inputs[MAIN]->w, ctx->inputs[MAIN]->h,
328            av_get_pix_fmt_name(ctx->inputs[MAIN]->format),
329            ctx->inputs[OVERLAY]->w, ctx->inputs[OVERLAY]->h,
330            av_get_pix_fmt_name(ctx->inputs[OVERLAY]->format));
331     return 0;
332 }
333
334 static int config_output(AVFilterLink *outlink)
335 {
336     AVFilterContext *ctx = outlink->src;
337
338     outlink->w = ctx->inputs[MAIN]->w;
339     outlink->h = ctx->inputs[MAIN]->h;
340     outlink->time_base = ctx->inputs[MAIN]->time_base;
341
342     return 0;
343 }
344
345 // divide by 255 and round to nearest
346 // apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
347 #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16)
348
349 // calculate the unpremultiplied alpha, applying the general equation:
350 // alpha = alpha_overlay / ( (alpha_main + alpha_overlay) - (alpha_main * alpha_overlay) )
351 // (((x) << 16) - ((x) << 9) + (x)) is a faster version of: 255 * 255 * x
352 // ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)) is a faster version of: 255 * (x + y)
353 #define UNPREMULTIPLY_ALPHA(x, y) ((((x) << 16) - ((x) << 9) + (x)) / ((((x) + (y)) << 8) - ((x) + (y)) - (y) * (x)))
354
355 /**
356  * Blend image in src to destination buffer dst at position (x, y).
357  */
358 static void blend_image(AVFilterContext *ctx,
359                         AVFrame *dst, AVFrame *src,
360                         int x, int y)
361 {
362     OverlayContext *over = ctx->priv;
363     int i, imax, j, jmax, k, kmax;
364     const int src_w = src->width;
365     const int src_h = src->height;
366     const int dst_w = dst->width;
367     const int dst_h = dst->height;
368
369     if (x >= dst_w || x+dst_w  < 0 ||
370         y >= dst_h || y+dst_h < 0)
371         return; /* no intersection */
372
373     if (over->main_is_packed_rgb) {
374         uint8_t alpha;          ///< the amount of overlay to blend on to main
375         const int dr = over->main_rgba_map[R];
376         const int dg = over->main_rgba_map[G];
377         const int db = over->main_rgba_map[B];
378         const int da = over->main_rgba_map[A];
379         const int dstep = over->main_pix_step[0];
380         const int sr = over->overlay_rgba_map[R];
381         const int sg = over->overlay_rgba_map[G];
382         const int sb = over->overlay_rgba_map[B];
383         const int sa = over->overlay_rgba_map[A];
384         const int sstep = over->overlay_pix_step[0];
385         const int main_has_alpha = over->main_has_alpha;
386         uint8_t *s, *sp, *d, *dp;
387
388         i = FFMAX(-y, 0);
389         sp = src->data[0] + i     * src->linesize[0];
390         dp = dst->data[0] + (y+i) * dst->linesize[0];
391
392         for (imax = FFMIN(-y + dst_h, src_h); i < imax; i++) {
393             j = FFMAX(-x, 0);
394             s = sp + j     * sstep;
395             d = dp + (x+j) * dstep;
396
397             for (jmax = FFMIN(-x + dst_w, src_w); j < jmax; j++) {
398                 alpha = s[sa];
399
400                 // if the main channel has an alpha channel, alpha has to be calculated
401                 // to create an un-premultiplied (straight) alpha value
402                 if (main_has_alpha && alpha != 0 && alpha != 255) {
403                     uint8_t alpha_d = d[da];
404                     alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
405                 }
406
407                 switch (alpha) {
408                 case 0:
409                     break;
410                 case 255:
411                     d[dr] = s[sr];
412                     d[dg] = s[sg];
413                     d[db] = s[sb];
414                     break;
415                 default:
416                     // main_value = main_value * (1 - alpha) + overlay_value * alpha
417                     // since alpha is in the range 0-255, the result must divided by 255
418                     d[dr] = FAST_DIV255(d[dr] * (255 - alpha) + s[sr] * alpha);
419                     d[dg] = FAST_DIV255(d[dg] * (255 - alpha) + s[sg] * alpha);
420                     d[db] = FAST_DIV255(d[db] * (255 - alpha) + s[sb] * alpha);
421                 }
422                 if (main_has_alpha) {
423                     switch (alpha) {
424                     case 0:
425                         break;
426                     case 255:
427                         d[da] = s[sa];
428                         break;
429                     default:
430                         // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
431                         d[da] += FAST_DIV255((255 - d[da]) * s[sa]);
432                     }
433                 }
434                 d += dstep;
435                 s += sstep;
436             }
437             dp += dst->linesize[0];
438             sp += src->linesize[0];
439         }
440     } else {
441         const int main_has_alpha = over->main_has_alpha;
442         if (main_has_alpha) {
443             uint8_t alpha;          ///< the amount of overlay to blend on to main
444             uint8_t *s, *sa, *d, *da;
445
446             i = FFMAX(-y, 0);
447             sa = src->data[3] + i     * src->linesize[3];
448             da = dst->data[3] + (y+i) * dst->linesize[3];
449
450             for (imax = FFMIN(-y + dst_h, src_h); i < imax; i++) {
451                 j = FFMAX(-x, 0);
452                 s = sa + j;
453                 d = da + x+j;
454
455                 for (jmax = FFMIN(-x + dst_w, src_w); j < jmax; j++) {
456                     alpha = *s;
457                     if (alpha != 0 && alpha != 255) {
458                         uint8_t alpha_d = *d;
459                         alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
460                     }
461                     switch (alpha) {
462                     case 0:
463                         break;
464                     case 255:
465                         *d = *s;
466                         break;
467                     default:
468                         // apply alpha compositing: main_alpha += (1-main_alpha) * overlay_alpha
469                         *d += FAST_DIV255((255 - *d) * *s);
470                     }
471                     d += 1;
472                     s += 1;
473                 }
474                 da += dst->linesize[3];
475                 sa += src->linesize[3];
476             }
477         }
478         for (i = 0; i < 3; i++) {
479             int hsub = i ? over->hsub : 0;
480             int vsub = i ? over->vsub : 0;
481             int src_wp = FFALIGN(src_w, 1<<hsub) >> hsub;
482             int src_hp = FFALIGN(src_h, 1<<vsub) >> vsub;
483             int dst_wp = FFALIGN(dst_w, 1<<hsub) >> hsub;
484             int dst_hp = FFALIGN(dst_h, 1<<vsub) >> vsub;
485             int yp = y>>vsub;
486             int xp = x>>hsub;
487             uint8_t *s, *sp, *d, *dp, *a, *ap;
488
489             j = FFMAX(-yp, 0);
490             sp = src->data[i] + j         * src->linesize[i];
491             dp = dst->data[i] + (yp+j)    * dst->linesize[i];
492             ap = src->data[3] + (j<<vsub) * src->linesize[3];
493
494             for (jmax = FFMIN(-yp + dst_hp, src_hp); j < jmax; j++) {
495                 k = FFMAX(-xp, 0);
496                 d = dp + xp+k;
497                 s = sp + k;
498                 a = ap + (k<<hsub);
499
500                 for (kmax = FFMIN(-xp + dst_wp, src_wp); k < kmax; k++) {
501                     int alpha_v, alpha_h, alpha;
502
503                     // average alpha for color components, improve quality
504                     if (hsub && vsub && j+1 < src_hp && k+1 < src_wp) {
505                         alpha = (a[0] + a[src->linesize[3]] +
506                                  a[1] + a[src->linesize[3]+1]) >> 2;
507                     } else if (hsub || vsub) {
508                         alpha_h = hsub && k+1 < src_wp ?
509                             (a[0] + a[1]) >> 1 : a[0];
510                         alpha_v = vsub && j+1 < src_hp ?
511                             (a[0] + a[src->linesize[3]]) >> 1 : a[0];
512                         alpha = (alpha_v + alpha_h) >> 1;
513                     } else
514                         alpha = a[0];
515                     // if the main channel has an alpha channel, alpha has to be calculated
516                     // to create an un-premultiplied (straight) alpha value
517                     if (main_has_alpha && alpha != 0 && alpha != 255) {
518                         // average alpha for color components, improve quality
519                         uint8_t alpha_d;
520                         if (hsub && vsub && j+1 < src_hp && k+1 < src_wp) {
521                             alpha_d = (d[0] + d[src->linesize[3]] +
522                                        d[1] + d[src->linesize[3]+1]) >> 2;
523                         } else if (hsub || vsub) {
524                             alpha_h = hsub && k+1 < src_wp ?
525                                 (d[0] + d[1]) >> 1 : d[0];
526                             alpha_v = vsub && j+1 < src_hp ?
527                                 (d[0] + d[src->linesize[3]]) >> 1 : d[0];
528                             alpha_d = (alpha_v + alpha_h) >> 1;
529                         } else
530                             alpha_d = d[0];
531                         alpha = UNPREMULTIPLY_ALPHA(alpha, alpha_d);
532                     }
533                     *d = FAST_DIV255(*d * (255 - alpha) + *s * alpha);
534                     s++;
535                     d++;
536                     a += 1 << hsub;
537                 }
538                 dp += dst->linesize[i];
539                 sp += src->linesize[i];
540                 ap += (1 << vsub) * src->linesize[3];
541             }
542         }
543     }
544 }
545
546 static int try_filter_frame(AVFilterContext *ctx, AVFrame *mainpic)
547 {
548     OverlayContext *over = ctx->priv;
549     AVFilterLink *inlink = ctx->inputs[0];
550     AVFrame *next_overpic;
551     int ret;
552
553     /* Discard obsolete overlay frames: if there is a next overlay frame with pts
554      * before the main frame, we can drop the current overlay. */
555     while (1) {
556         next_overpic = ff_bufqueue_peek(&over->queue_over, 0);
557         if (!next_overpic && over->overlay_eof && !over->repeatlast) {
558             av_frame_free(&over->overpicref);
559             break;
560         }
561         if (!next_overpic || av_compare_ts(next_overpic->pts, ctx->inputs[OVERLAY]->time_base,
562                                            mainpic->pts     , ctx->inputs[MAIN]->time_base) > 0)
563             break;
564         ff_bufqueue_get(&over->queue_over);
565         av_frame_free(&over->overpicref);
566         over->overpicref = next_overpic;
567     }
568
569     /* If there is no next frame and no EOF and the overlay frame is before
570      * the main frame, we can not know yet if it will be superseded. */
571     if (!over->queue_over.available && !over->overlay_eof &&
572         (!over->overpicref || av_compare_ts(over->overpicref->pts, ctx->inputs[OVERLAY]->time_base,
573                                             mainpic->pts         , ctx->inputs[MAIN]->time_base) < 0))
574         return AVERROR(EAGAIN);
575
576     /* At this point, we know that the current overlay frame extends to the
577      * time of the main frame. */
578     av_dlog(ctx, "main_pts:%s main_pts_time:%s",
579             av_ts2str(mainpic->pts), av_ts2timestr(mainpic->pts, &ctx->inputs[MAIN]->time_base));
580     if (over->overpicref)
581         av_dlog(ctx, " over_pts:%s over_pts_time:%s",
582                 av_ts2str(over->overpicref->pts), av_ts2timestr(over->overpicref->pts, &ctx->inputs[OVERLAY]->time_base));
583     av_dlog(ctx, "\n");
584
585     if (over->overpicref) {
586         if (over->eval_mode == EVAL_MODE_FRAME) {
587             int64_t pos = av_frame_get_pkt_pos(mainpic);
588
589             over->var_values[VAR_N] = inlink->frame_count;
590             over->var_values[VAR_T] = mainpic->pts == AV_NOPTS_VALUE ?
591                 NAN : mainpic->pts * av_q2d(inlink->time_base);
592             over->var_values[VAR_POS] = pos == -1 ? NAN : pos;
593
594             eval_expr(ctx);
595             av_log(ctx, AV_LOG_DEBUG, "n:%f t:%f pos:%f x:%f xi:%d y:%f yi:%d\n",
596                    over->var_values[VAR_N], over->var_values[VAR_T], over->var_values[VAR_POS],
597                    over->var_values[VAR_X], over->x,
598                    over->var_values[VAR_Y], over->y);
599         }
600         if (over->enable)
601             blend_image(ctx, mainpic, over->overpicref, over->x, over->y);
602
603     }
604     ret = ff_filter_frame(ctx->outputs[0], mainpic);
605     av_assert1(ret != AVERROR(EAGAIN));
606     over->frame_requested = 0;
607     return ret;
608 }
609
610 static int try_filter_next_frame(AVFilterContext *ctx)
611 {
612     OverlayContext *over = ctx->priv;
613     AVFrame *next_mainpic = ff_bufqueue_peek(&over->queue_main, 0);
614     int ret;
615
616     if (!next_mainpic)
617         return AVERROR(EAGAIN);
618     if ((ret = try_filter_frame(ctx, next_mainpic)) == AVERROR(EAGAIN))
619         return ret;
620     ff_bufqueue_get(&over->queue_main);
621     return ret;
622 }
623
624 static int flush_frames(AVFilterContext *ctx)
625 {
626     int ret;
627
628     while (!(ret = try_filter_next_frame(ctx)));
629     return ret == AVERROR(EAGAIN) ? 0 : ret;
630 }
631
632 static int filter_frame_main(AVFilterLink *inlink, AVFrame *inpicref)
633 {
634     AVFilterContext *ctx = inlink->dst;
635     OverlayContext *over = ctx->priv;
636     int ret;
637
638     if ((ret = flush_frames(ctx)) < 0)
639         return ret;
640     if ((ret = try_filter_frame(ctx, inpicref)) < 0) {
641         if (ret != AVERROR(EAGAIN))
642             return ret;
643         ff_bufqueue_add(ctx, &over->queue_main, inpicref);
644     }
645
646     if (!over->overpicref)
647         return 0;
648     flush_frames(ctx);
649
650     return 0;
651 }
652
653 static int filter_frame_over(AVFilterLink *inlink, AVFrame *inpicref)
654 {
655     AVFilterContext *ctx = inlink->dst;
656     OverlayContext *over = ctx->priv;
657     int ret;
658
659     if ((ret = flush_frames(ctx)) < 0)
660         return ret;
661     ff_bufqueue_add(ctx, &over->queue_over, inpicref);
662     ret = try_filter_next_frame(ctx);
663     return ret == AVERROR(EAGAIN) ? 0 : ret;
664 }
665
666 #define DEF_FILTER_FRAME(name, mode, enable_value)                              \
667 static int filter_frame_##name##_##mode(AVFilterLink *inlink, AVFrame *frame)   \
668 {                                                                               \
669     AVFilterContext *ctx = inlink->dst;                                         \
670     OverlayContext *over = ctx->priv;                                           \
671     over->enable = enable_value;                                                \
672     return filter_frame_##name(inlink, frame);                                  \
673 }
674
675 DEF_FILTER_FRAME(main, enabled,  1);
676 DEF_FILTER_FRAME(main, disabled, 0);
677 DEF_FILTER_FRAME(over, enabled,  1);
678 DEF_FILTER_FRAME(over, disabled, 0);
679
680 static int request_frame(AVFilterLink *outlink)
681 {
682     AVFilterContext *ctx = outlink->src;
683     OverlayContext *over = ctx->priv;
684     int input, ret;
685
686     if (!try_filter_next_frame(ctx))
687         return 0;
688     over->frame_requested = 1;
689     while (over->frame_requested) {
690         /* TODO if we had a frame duration, we could guess more accurately */
691         input = !over->overlay_eof && (over->queue_main.available ||
692                                        over->queue_over.available < 2) ?
693                 OVERLAY : MAIN;
694         ret = ff_request_frame(ctx->inputs[input]);
695         /* EOF on main is reported immediately */
696         if (ret == AVERROR_EOF && input == OVERLAY) {
697             over->overlay_eof = 1;
698             if (over->shortest)
699                 return ret;
700             if ((ret = try_filter_next_frame(ctx)) != AVERROR(EAGAIN))
701                 return ret;
702             ret = 0; /* continue requesting frames on main */
703         }
704         if (ret < 0)
705             return ret;
706     }
707     return 0;
708 }
709
710 #define OFFSET(x) offsetof(OverlayContext, x)
711 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
712
713 static const AVOption overlay_options[] = {
714     { "x", "set the x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
715     { "y", "set the y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str = "0"}, CHAR_MIN, CHAR_MAX, FLAGS },
716     { "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_FRAME}, 0, EVAL_MODE_NB-1, FLAGS, "eval" },
717          { "init",  "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT},  .flags = FLAGS, .unit = "eval" },
718          { "frame", "eval expressions per-frame",                  0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" },
719     { "rgb", "force packed RGB in input and output (deprecated)", OFFSET(allow_packed_rgb), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
720     { "shortest", "force termination when the shortest input terminates", OFFSET(shortest), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
721     { "format", "set output format", OFFSET(format), AV_OPT_TYPE_INT, {.i64=OVERLAY_FORMAT_YUV420}, 0, OVERLAY_FORMAT_NB-1, FLAGS, "format" },
722         { "yuv420", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV420}, .flags = FLAGS, .unit = "format" },
723         { "yuv444", "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_YUV444}, .flags = FLAGS, .unit = "format" },
724         { "rgb",    "", 0, AV_OPT_TYPE_CONST, {.i64=OVERLAY_FORMAT_RGB},    .flags = FLAGS, .unit = "format" },
725     { "repeatlast", "repeat overlay of the last overlay frame", OFFSET(repeatlast), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS },
726     { NULL }
727 };
728
729 AVFILTER_DEFINE_CLASS(overlay);
730
731 static const AVFilterPad avfilter_vf_overlay_inputs[] = {
732     {
733         .name         = "main",
734         .type         = AVMEDIA_TYPE_VIDEO,
735         .get_video_buffer = ff_null_get_video_buffer,
736         .config_props = config_input_main,
737         .filter_frame             = filter_frame_main_enabled,
738         .passthrough_filter_frame = filter_frame_main_disabled,
739         .needs_writable = 1,
740     },
741     {
742         .name         = "overlay",
743         .type         = AVMEDIA_TYPE_VIDEO,
744         .config_props = config_input_overlay,
745         .filter_frame             = filter_frame_over_enabled,
746         .passthrough_filter_frame = filter_frame_over_disabled,
747     },
748     { NULL }
749 };
750
751 static const AVFilterPad avfilter_vf_overlay_outputs[] = {
752     {
753         .name          = "default",
754         .type          = AVMEDIA_TYPE_VIDEO,
755         .config_props  = config_output,
756         .request_frame = request_frame,
757     },
758     { NULL }
759 };
760
761 AVFilter avfilter_vf_overlay = {
762     .name      = "overlay",
763     .description = NULL_IF_CONFIG_SMALL("Overlay a video source on top of the input."),
764
765     .init      = init,
766     .uninit    = uninit,
767
768     .priv_size = sizeof(OverlayContext),
769     .priv_class = &overlay_class,
770
771     .query_formats = query_formats,
772     .process_command = process_command,
773
774     .inputs    = avfilter_vf_overlay_inputs,
775     .outputs   = avfilter_vf_overlay_outputs,
776     .flags     = AVFILTER_FLAG_SUPPORT_TIMELINE,
777 };