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