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