compositor: Add scaling policy to support PAR-aware scaling
[platform/upstream/gstreamer.git] / gst / compositor / compositor.c
1 /* Video compositor plugin
2  * Copyright (C) 2004, 2008 Wim Taymans <wim@fluendo.com>
3  * Copyright (C) 2010 Sebastian Dröge <sebastian.droege@collabora.co.uk>
4  * Copyright (C) 2014 Mathieu Duponchelle <mathieu.duponchelle@opencreed.com>
5  * Copyright (C) 2014 Thibault Saunier <tsaunier@gnome.org>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:element-compositor
25  * @title: compositor
26  *
27  * Compositor can accept AYUV, VUYA, ARGB and BGRA video streams. For each of the requested
28  * sink pads it will compare the incoming geometry and framerate to define the
29  * output parameters. Indeed output video frames will have the geometry of the
30  * biggest incoming video stream and the framerate of the fastest incoming one.
31  *
32  * Compositor will do colorspace conversion.
33  *
34  * Individual parameters for each input stream can be configured on the
35  * #GstCompositorPad:
36  *
37  * * "xpos": The x-coordinate position of the top-left corner of the picture (#gint)
38  * * "ypos": The y-coordinate position of the top-left corner of the picture (#gint)
39  * * "width": The width of the picture; the input will be scaled if necessary (#gint)
40  * * "height": The height of the picture; the input will be scaled if necessary (#gint)
41  * * "alpha": The transparency of the picture; between 0.0 and 1.0. The blending
42  *   is a simple copy when fully-transparent (0.0) and fully-opaque (1.0). (#gdouble)
43  * * "zorder": The z-order position of the picture in the composition (#guint)
44  *
45  * ## Sample pipelines
46  * |[
47  * gst-launch-1.0 \
48  *   videotestsrc pattern=1 ! \
49  *   video/x-raw,format=AYUV,framerate=\(fraction\)10/1,width=100,height=100 ! \
50  *   videobox border-alpha=0 top=-70 bottom=-70 right=-220 ! \
51  *   compositor name=comp sink_0::alpha=0.7 sink_1::alpha=0.5 ! \
52  *   videoconvert ! xvimagesink \
53  *   videotestsrc ! \
54  *   video/x-raw,format=AYUV,framerate=\(fraction\)5/1,width=320,height=240 ! comp.
55  * ]| A pipeline to demonstrate compositor used together with videobox.
56  * This should show a 320x240 pixels video test source with some transparency
57  * showing the background checker pattern. Another video test source with just
58  * the snow pattern of 100x100 pixels is overlaid on top of the first one on
59  * the left vertically centered with a small transparency showing the first
60  * video test source behind and the checker pattern under it. Note that the
61  * framerate of the output video is 10 frames per second.
62  * |[
63  * gst-launch-1.0 videotestsrc pattern=1 ! \
64  *   video/x-raw, framerate=\(fraction\)10/1, width=100, height=100 ! \
65  *   compositor name=comp ! videoconvert ! ximagesink \
66  *   videotestsrc !  \
67  *   video/x-raw, framerate=\(fraction\)5/1, width=320, height=240 ! comp.
68  * ]| A pipeline to demonstrate bgra comping. (This does not demonstrate alpha blending).
69  * |[
70  * gst-launch-1.0 videotestsrc pattern=1 ! \
71  *   video/x-raw,format =I420, framerate=\(fraction\)10/1, width=100, height=100 ! \
72  *   compositor name=comp ! videoconvert ! ximagesink \
73  *   videotestsrc ! \
74  *   video/x-raw,format=I420, framerate=\(fraction\)5/1, width=320, height=240 ! comp.
75  * ]| A pipeline to test I420
76  * |[
77  * gst-launch-1.0 compositor name=comp sink_1::alpha=0.5 sink_1::xpos=50 sink_1::ypos=50 ! \
78  *   videoconvert ! ximagesink \
79  *   videotestsrc pattern=snow timestamp-offset=3000000000 ! \
80  *   "video/x-raw,format=AYUV,width=640,height=480,framerate=(fraction)30/1" ! \
81  *   timeoverlay ! queue2 ! comp. \
82  *   videotestsrc pattern=smpte ! \
83  *   "video/x-raw,format=AYUV,width=800,height=600,framerate=(fraction)10/1" ! \
84  *   timeoverlay ! queue2 ! comp.
85  * ]| A pipeline to demonstrate synchronized compositing (the second stream starts after 3 seconds)
86  *
87  */
88
89 #ifdef HAVE_CONFIG_H
90 #include "config.h"
91 #endif
92
93 #include <string.h>
94
95 #include "compositor.h"
96
97 #ifdef DISABLE_ORC
98 #define orc_memset memset
99 #else
100 #include <orc/orcfunctions.h>
101 #endif
102
103 GST_DEBUG_CATEGORY_STATIC (gst_compositor_debug);
104 #define GST_CAT_DEFAULT gst_compositor_debug
105
106 #define FORMATS " { AYUV, VUYA, BGRA, ARGB, RGBA, ABGR, Y444, Y42B, YUY2, UYVY, "\
107                 "   YVYU, I420, YV12, NV12, NV21, Y41B, RGB, BGR, xRGB, xBGR, "\
108                 "   RGBx, BGRx } "
109
110 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
111     GST_PAD_SRC,
112     GST_PAD_ALWAYS,
113     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (FORMATS))
114     );
115
116 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink_%u",
117     GST_PAD_SINK,
118     GST_PAD_REQUEST,
119     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE (GST_VIDEO_FORMATS_ALL))
120     );
121
122 static void gst_compositor_child_proxy_init (gpointer g_iface,
123     gpointer iface_data);
124
125 #define GST_TYPE_COMPOSITOR_OPERATOR (gst_compositor_operator_get_type())
126 static GType
127 gst_compositor_operator_get_type (void)
128 {
129   static GType compositor_operator_type = 0;
130
131   static const GEnumValue compositor_operator[] = {
132     {COMPOSITOR_OPERATOR_SOURCE, "Source", "source"},
133     {COMPOSITOR_OPERATOR_OVER, "Over", "over"},
134     {COMPOSITOR_OPERATOR_ADD, "Add", "add"},
135     {0, NULL, NULL},
136   };
137
138   if (!compositor_operator_type) {
139     compositor_operator_type =
140         g_enum_register_static ("GstCompositorOperator", compositor_operator);
141   }
142   return compositor_operator_type;
143 }
144
145 #define GST_TYPE_COMPOSITOR_BACKGROUND (gst_compositor_background_get_type())
146 static GType
147 gst_compositor_background_get_type (void)
148 {
149   static GType compositor_background_type = 0;
150
151   static const GEnumValue compositor_background[] = {
152     {COMPOSITOR_BACKGROUND_CHECKER, "Checker pattern", "checker"},
153     {COMPOSITOR_BACKGROUND_BLACK, "Black", "black"},
154     {COMPOSITOR_BACKGROUND_WHITE, "White", "white"},
155     {COMPOSITOR_BACKGROUND_TRANSPARENT,
156         "Transparent Background to enable further compositing", "transparent"},
157     {0, NULL, NULL},
158   };
159
160   if (!compositor_background_type) {
161     compositor_background_type =
162         g_enum_register_static ("GstCompositorBackground",
163         compositor_background);
164   }
165   return compositor_background_type;
166 }
167
168 #define GST_TYPE_COMPOSITOR_SIZING_POLICY (gst_compositor_sizing_policy_get_type())
169 static GType
170 gst_compositor_sizing_policy_get_type (void)
171 {
172   static GType sizing_policy_type = 0;
173
174   static const GEnumValue sizing_polices[] = {
175     {COMPOSITOR_SIZING_POLICY_NONE,
176         "None: Image is scaled to fill configured destination rectangle without "
177           "padding or keeping the aspect ratio", "none"},
178     {COMPOSITOR_SIZING_POLICY_KEEP_ASPECT_RATIO,
179           "Keep Aspect Ratio: Image is scaled to fit destination rectangle "
180           "specified by GstCompositorPad:{xpos, ypos, width, height} "
181           "with preserved aspect ratio. Resulting image will be centered in "
182           "the destination rectangle with padding if necessary",
183         "keep-aspect-ratio"},
184     {0, NULL, NULL},
185   };
186
187   if (!sizing_policy_type) {
188     sizing_policy_type =
189         g_enum_register_static ("GstCompositorSizingPolicy", sizing_polices);
190   }
191   return sizing_policy_type;
192 }
193
194 #define DEFAULT_PAD_XPOS   0
195 #define DEFAULT_PAD_YPOS   0
196 #define DEFAULT_PAD_WIDTH  -1
197 #define DEFAULT_PAD_HEIGHT -1
198 #define DEFAULT_PAD_ALPHA  1.0
199 #define DEFAULT_PAD_OPERATOR COMPOSITOR_OPERATOR_OVER
200 #define DEFAULT_PAD_SIZING_POLICY COMPOSITOR_SIZING_POLICY_NONE
201
202 enum
203 {
204   PROP_PAD_0,
205   PROP_PAD_XPOS,
206   PROP_PAD_YPOS,
207   PROP_PAD_WIDTH,
208   PROP_PAD_HEIGHT,
209   PROP_PAD_ALPHA,
210   PROP_PAD_OPERATOR,
211   PROP_PAD_SIZING_POLICY,
212 };
213
214 G_DEFINE_TYPE (GstCompositorPad, gst_compositor_pad,
215     GST_TYPE_VIDEO_AGGREGATOR_PARALLEL_CONVERT_PAD);
216
217 static void
218 gst_compositor_pad_get_property (GObject * object, guint prop_id,
219     GValue * value, GParamSpec * pspec)
220 {
221   GstCompositorPad *pad = GST_COMPOSITOR_PAD (object);
222
223   switch (prop_id) {
224     case PROP_PAD_XPOS:
225       g_value_set_int (value, pad->xpos);
226       break;
227     case PROP_PAD_YPOS:
228       g_value_set_int (value, pad->ypos);
229       break;
230     case PROP_PAD_WIDTH:
231       g_value_set_int (value, pad->width);
232       break;
233     case PROP_PAD_HEIGHT:
234       g_value_set_int (value, pad->height);
235       break;
236     case PROP_PAD_ALPHA:
237       g_value_set_double (value, pad->alpha);
238       break;
239     case PROP_PAD_OPERATOR:
240       g_value_set_enum (value, pad->op);
241       break;
242     case PROP_PAD_SIZING_POLICY:
243       g_value_set_enum (value, pad->sizing_policy);
244       break;
245     default:
246       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
247       break;
248   }
249 }
250
251 static void
252 gst_compositor_pad_set_property (GObject * object, guint prop_id,
253     const GValue * value, GParamSpec * pspec)
254 {
255   GstCompositorPad *pad = GST_COMPOSITOR_PAD (object);
256
257   switch (prop_id) {
258     case PROP_PAD_XPOS:
259       pad->xpos = g_value_get_int (value);
260       break;
261     case PROP_PAD_YPOS:
262       pad->ypos = g_value_get_int (value);
263       break;
264     case PROP_PAD_WIDTH:
265       pad->width = g_value_get_int (value);
266       gst_video_aggregator_convert_pad_update_conversion_info
267           (GST_VIDEO_AGGREGATOR_CONVERT_PAD (pad));
268       break;
269     case PROP_PAD_HEIGHT:
270       pad->height = g_value_get_int (value);
271       gst_video_aggregator_convert_pad_update_conversion_info
272           (GST_VIDEO_AGGREGATOR_CONVERT_PAD (pad));
273       break;
274     case PROP_PAD_ALPHA:
275       pad->alpha = g_value_get_double (value);
276       break;
277     case PROP_PAD_OPERATOR:
278       pad->op = g_value_get_enum (value);
279       gst_video_aggregator_pad_set_needs_alpha (GST_VIDEO_AGGREGATOR_PAD (pad),
280           pad->op == COMPOSITOR_OPERATOR_ADD);
281       break;
282     case PROP_PAD_SIZING_POLICY:
283       pad->sizing_policy = g_value_get_enum (value);
284       gst_video_aggregator_convert_pad_update_conversion_info
285           (GST_VIDEO_AGGREGATOR_CONVERT_PAD (pad));
286       break;
287     default:
288       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
289       break;
290   }
291 }
292
293 static void
294 _mixer_pad_get_output_size (GstCompositor * comp, GstCompositorPad * comp_pad,
295     gint out_par_n, gint out_par_d, gint * width, gint * height,
296     gint * x_offset, gint * y_offset)
297 {
298   GstVideoAggregatorPad *vagg_pad = GST_VIDEO_AGGREGATOR_PAD (comp_pad);
299   gint pad_width, pad_height;
300   guint dar_n, dar_d;
301
302   *x_offset = 0;
303   *y_offset = 0;
304   *width = 0;
305   *height = 0;
306
307   /* FIXME: Anything better we can do here? */
308   if (!vagg_pad->info.finfo
309       || vagg_pad->info.finfo->format == GST_VIDEO_FORMAT_UNKNOWN) {
310     GST_DEBUG_OBJECT (comp_pad, "Have no caps yet");
311     return;
312   }
313
314   if (comp->zero_size_is_unscaled) {
315     pad_width =
316         comp_pad->width <=
317         0 ? GST_VIDEO_INFO_WIDTH (&vagg_pad->info) : comp_pad->width;
318     pad_height =
319         comp_pad->height <=
320         0 ? GST_VIDEO_INFO_HEIGHT (&vagg_pad->info) : comp_pad->height;
321   } else {
322     pad_width =
323         comp_pad->width <
324         0 ? GST_VIDEO_INFO_WIDTH (&vagg_pad->info) : comp_pad->width;
325     pad_height =
326         comp_pad->height <
327         0 ? GST_VIDEO_INFO_HEIGHT (&vagg_pad->info) : comp_pad->height;
328   }
329
330   if (pad_width == 0 || pad_height == 0)
331     return;
332
333   if (!gst_video_calculate_display_ratio (&dar_n, &dar_d, pad_width, pad_height,
334           GST_VIDEO_INFO_PAR_N (&vagg_pad->info),
335           GST_VIDEO_INFO_PAR_D (&vagg_pad->info), out_par_n, out_par_d)) {
336     GST_WARNING_OBJECT (comp_pad, "Cannot calculate display aspect ratio");
337     return;
338   }
339
340   GST_LOG_OBJECT (comp_pad, "scaling %ux%u by %u/%u (%u/%u / %u/%u)", pad_width,
341       pad_height, dar_n, dar_d, GST_VIDEO_INFO_PAR_N (&vagg_pad->info),
342       GST_VIDEO_INFO_PAR_D (&vagg_pad->info), out_par_n, out_par_d);
343
344   switch (comp_pad->sizing_policy) {
345     case COMPOSITOR_SIZING_POLICY_NONE:
346       /* Pick either height or width, whichever is an integer multiple of the
347        * display aspect ratio. However, prefer preserving the height to account
348        * for interlaced video. */
349       if (pad_height % dar_n == 0) {
350         pad_width = gst_util_uint64_scale_int (pad_height, dar_n, dar_d);
351       } else if (pad_width % dar_d == 0) {
352         pad_height = gst_util_uint64_scale_int (pad_width, dar_d, dar_n);
353       } else {
354         pad_width = gst_util_uint64_scale_int (pad_height, dar_n, dar_d);
355       }
356       break;
357     case COMPOSITOR_SIZING_POLICY_KEEP_ASPECT_RATIO:
358     {
359       gint from_dar_n, from_dar_d, to_dar_n, to_dar_d, num, den;
360
361       /* Calculate DAR again with actual video size */
362       if (!gst_util_fraction_multiply (GST_VIDEO_INFO_WIDTH (&vagg_pad->info),
363               GST_VIDEO_INFO_HEIGHT (&vagg_pad->info),
364               GST_VIDEO_INFO_PAR_N (&vagg_pad->info),
365               GST_VIDEO_INFO_PAR_D (&vagg_pad->info), &from_dar_n,
366               &from_dar_d)) {
367         from_dar_n = from_dar_d = -1;
368       }
369
370       if (!gst_util_fraction_multiply (pad_width, pad_height,
371               out_par_n, out_par_d, &to_dar_n, &to_dar_d)) {
372         to_dar_n = to_dar_d = -1;
373       }
374
375       if (from_dar_n != to_dar_n || from_dar_d != to_dar_d) {
376         /* Calculate new output resolution */
377         if (from_dar_n != -1 && from_dar_d != -1
378             && gst_util_fraction_multiply (from_dar_n, from_dar_d,
379                 out_par_d, out_par_n, &num, &den)) {
380           GstVideoRectangle src_rect, dst_rect, rst_rect;
381
382           src_rect.h = gst_util_uint64_scale_int (pad_width, den, num);
383           if (src_rect.h == 0) {
384             pad_width = 0;
385             pad_height = 0;
386             break;
387           }
388
389           src_rect.x = src_rect.y = 0;
390           src_rect.w = pad_width;
391
392           dst_rect.x = dst_rect.y = 0;
393           dst_rect.w = pad_width;
394           dst_rect.h = pad_height;
395
396           /* Scale rect to be centered in destination rect */
397           gst_video_center_rect (&src_rect, &dst_rect, &rst_rect, TRUE);
398
399           GST_LOG_OBJECT (comp_pad,
400               "Re-calculated size %dx%d -> %dx%d (x-offset %d, y-offset %d)",
401               pad_width, pad_height, rst_rect.w, rst_rect.h, rst_rect.x,
402               rst_rect.h);
403
404           *x_offset = rst_rect.x;
405           *y_offset = rst_rect.y;
406           pad_width = rst_rect.w;
407           pad_height = rst_rect.h;
408         } else {
409           GST_WARNING_OBJECT (comp_pad, "Failed to calculate output size");
410
411           *x_offset = 0;
412           *y_offset = 0;
413           pad_width = 0;
414           pad_height = 0;
415         }
416       }
417       break;
418     }
419   }
420
421   *width = pad_width;
422   *height = pad_height;
423 }
424
425 /* Test whether rectangle2 contains rectangle 1 (geometrically) */
426 static gboolean
427 is_rectangle_contained (const GstVideoRectangle rect1,
428     const GstVideoRectangle rect2)
429 {
430   if ((rect2.x <= rect1.x) && (rect2.y <= rect1.y) &&
431       ((rect2.x + rect2.w) >= (rect1.x + rect1.w)) &&
432       ((rect2.y + rect2.h) >= (rect1.y + rect1.h)))
433     return TRUE;
434   return FALSE;
435 }
436
437 static GstVideoRectangle
438 clamp_rectangle (gint x, gint y, gint w, gint h, gint outer_width,
439     gint outer_height)
440 {
441   gint x2 = x + w;
442   gint y2 = y + h;
443   GstVideoRectangle clamped;
444
445   /* Clamp the x/y coordinates of this frame to the output boundaries to cover
446    * the case where (say, with negative xpos/ypos or w/h greater than the output
447    * size) the non-obscured portion of the frame could be outside the bounds of
448    * the video itself and hence not visible at all */
449   clamped.x = CLAMP (x, 0, outer_width);
450   clamped.y = CLAMP (y, 0, outer_height);
451   clamped.w = CLAMP (x2, 0, outer_width) - clamped.x;
452   clamped.h = CLAMP (y2, 0, outer_height) - clamped.y;
453
454   return clamped;
455 }
456
457 /* Call this with the lock taken */
458 static gboolean
459 _pad_obscures_rectangle (GstVideoAggregator * vagg, GstVideoAggregatorPad * pad,
460     const GstVideoRectangle rect)
461 {
462   GstVideoRectangle pad_rect;
463   GstCompositorPad *cpad = GST_COMPOSITOR_PAD (pad);
464   GstStructure *converter_config = NULL;
465   gboolean fill_border = TRUE;
466   guint32 border_argb = 0xff000000;
467   gint x_offset, y_offset;
468
469   /* No buffer to obscure the rectangle with */
470   if (!gst_video_aggregator_pad_has_current_buffer (pad))
471     return FALSE;
472
473   /* Can't obscure if we introduce alpha or if the format has an alpha
474    * component as we'd have to inspect every pixel to know if the frame is
475    * opaque, so assume it doesn't obscure
476    */
477   if (cpad->alpha != 1.0 || GST_VIDEO_INFO_HAS_ALPHA (&pad->info))
478     return FALSE;
479
480   /* If a converter-config is set and it is either configured to not fill any
481    * borders, or configured to use a non-opaque color, then we have to handle
482    * the pad as potentially containing transparency */
483   g_object_get (pad, "converter-config", &converter_config, NULL);
484   if (converter_config) {
485     gst_structure_get (converter_config, GST_VIDEO_CONVERTER_OPT_BORDER_ARGB,
486         G_TYPE_UINT, &border_argb, NULL);
487     gst_structure_get (converter_config, GST_VIDEO_CONVERTER_OPT_FILL_BORDER,
488         G_TYPE_BOOLEAN, &fill_border, NULL);
489   }
490   gst_clear_structure (&converter_config);
491   if (!fill_border || (border_argb & 0xff000000) != 0xff000000)
492     return FALSE;
493
494   pad_rect.x = cpad->xpos;
495   pad_rect.y = cpad->ypos;
496   /* Handle pixel and display aspect ratios to find the actual size */
497   _mixer_pad_get_output_size (GST_COMPOSITOR (vagg), cpad,
498       GST_VIDEO_INFO_PAR_N (&vagg->info), GST_VIDEO_INFO_PAR_D (&vagg->info),
499       &(pad_rect.w), &(pad_rect.h), &x_offset, &y_offset);
500   pad_rect.x += x_offset;
501   pad_rect.y += y_offset;
502
503   if (!is_rectangle_contained (rect, pad_rect))
504     return FALSE;
505
506   GST_DEBUG_OBJECT (pad, "Pad %s %ix%i@(%i,%i) obscures rect %ix%i@(%i,%i)",
507       GST_PAD_NAME (pad), pad_rect.w, pad_rect.h, pad_rect.x, pad_rect.y,
508       rect.w, rect.h, rect.x, rect.y);
509
510   return TRUE;
511 }
512
513 static void
514 gst_compositor_pad_prepare_frame_start (GstVideoAggregatorPad * pad,
515     GstVideoAggregator * vagg, GstBuffer * buffer,
516     GstVideoFrame * prepared_frame)
517 {
518   GstCompositorPad *cpad = GST_COMPOSITOR_PAD (pad);
519   gint width, height;
520   gboolean frame_obscured = FALSE;
521   GList *l;
522   /* The rectangle representing this frame, clamped to the video's boundaries.
523    * Due to the clamping, this is different from the frame width/height above. */
524   GstVideoRectangle frame_rect;
525
526   /* There's three types of width/height here:
527    * 1. GST_VIDEO_FRAME_WIDTH/HEIGHT:
528    *     The frame width/height (same as pad->info.height/width;
529    *     see gst_video_frame_map())
530    * 2. cpad->width/height:
531    *     The optional pad property for scaling the frame (if zero, the video is
532    *     left unscaled)
533    * 3. conversion_info.width/height:
534    *     Equal to cpad->width/height if it's set, otherwise it's the pad
535    *     width/height. See ->set_info()
536    * */
537
538   _mixer_pad_get_output_size (GST_COMPOSITOR (vagg), cpad,
539       GST_VIDEO_INFO_PAR_N (&vagg->info), GST_VIDEO_INFO_PAR_D (&vagg->info),
540       &width, &height, &cpad->x_offset, &cpad->y_offset);
541
542   if (cpad->alpha == 0.0) {
543     GST_DEBUG_OBJECT (pad, "Pad has alpha 0.0, not converting frame");
544     return;
545   }
546
547   frame_rect = clamp_rectangle (cpad->xpos + cpad->x_offset,
548       cpad->ypos + cpad->y_offset, width, height,
549       GST_VIDEO_INFO_WIDTH (&vagg->info), GST_VIDEO_INFO_HEIGHT (&vagg->info));
550
551   if (frame_rect.w == 0 || frame_rect.h == 0) {
552     GST_DEBUG_OBJECT (pad, "Resulting frame is zero-width or zero-height "
553         "(w: %i, h: %i), skipping", frame_rect.w, frame_rect.h);
554     return;
555   }
556
557   GST_OBJECT_LOCK (vagg);
558   /* Check if this frame is obscured by a higher-zorder frame
559    * TODO: Also skip a frame if it's obscured by a combination of
560    * higher-zorder frames */
561   l = g_list_find (GST_ELEMENT (vagg)->sinkpads, pad);
562   /* The pad might've just been removed */
563   if (l)
564     l = l->next;
565   for (; l; l = l->next) {
566     if (_pad_obscures_rectangle (vagg, l->data, frame_rect)) {
567       frame_obscured = TRUE;
568       break;
569     }
570   }
571   GST_OBJECT_UNLOCK (vagg);
572
573   if (frame_obscured)
574     return;
575
576   GST_VIDEO_AGGREGATOR_PAD_CLASS
577       (gst_compositor_pad_parent_class)->prepare_frame_start (pad, vagg, buffer,
578       prepared_frame);
579 }
580
581 static void
582 gst_compositor_pad_create_conversion_info (GstVideoAggregatorConvertPad * pad,
583     GstVideoAggregator * vagg, GstVideoInfo * conversion_info)
584 {
585   GstCompositorPad *cpad = GST_COMPOSITOR_PAD (pad);
586   gint width, height;
587   gint x_offset, y_offset;
588
589   GST_VIDEO_AGGREGATOR_CONVERT_PAD_CLASS
590       (gst_compositor_pad_parent_class)->create_conversion_info (pad, vagg,
591       conversion_info);
592   if (!conversion_info->finfo)
593     return;
594
595   _mixer_pad_get_output_size (GST_COMPOSITOR (vagg), cpad,
596       GST_VIDEO_INFO_PAR_N (&vagg->info), GST_VIDEO_INFO_PAR_D (&vagg->info),
597       &width, &height, &x_offset, &y_offset);
598
599   /* The only thing that can change here is the width
600    * and height, otherwise set_info would've been called */
601   if (GST_VIDEO_INFO_WIDTH (conversion_info) != width ||
602       GST_VIDEO_INFO_HEIGHT (conversion_info) != height) {
603     GstVideoInfo tmp_info;
604
605     /* Initialize with the wanted video format and our original width and
606      * height as we don't want to rescale. Then copy over the wanted
607      * colorimetry, and chroma-site and our current pixel-aspect-ratio
608      * and other relevant fields.
609      */
610     gst_video_info_set_format (&tmp_info,
611         GST_VIDEO_INFO_FORMAT (conversion_info), width, height);
612     tmp_info.chroma_site = conversion_info->chroma_site;
613     tmp_info.colorimetry = conversion_info->colorimetry;
614     tmp_info.par_n = conversion_info->par_n;
615     tmp_info.par_d = conversion_info->par_d;
616     tmp_info.fps_n = conversion_info->fps_n;
617     tmp_info.fps_d = conversion_info->fps_d;
618     tmp_info.flags = conversion_info->flags;
619     tmp_info.interlace_mode = conversion_info->interlace_mode;
620
621     *conversion_info = tmp_info;
622   }
623 }
624
625 static void
626 gst_compositor_pad_class_init (GstCompositorPadClass * klass)
627 {
628   GObjectClass *gobject_class = (GObjectClass *) klass;
629   GstVideoAggregatorPadClass *vaggpadclass =
630       (GstVideoAggregatorPadClass *) klass;
631   GstVideoAggregatorConvertPadClass *vaggcpadclass =
632       (GstVideoAggregatorConvertPadClass *) klass;
633
634   gobject_class->set_property = gst_compositor_pad_set_property;
635   gobject_class->get_property = gst_compositor_pad_get_property;
636
637   g_object_class_install_property (gobject_class, PROP_PAD_XPOS,
638       g_param_spec_int ("xpos", "X Position", "X Position of the picture",
639           G_MININT, G_MAXINT, DEFAULT_PAD_XPOS,
640           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
641   g_object_class_install_property (gobject_class, PROP_PAD_YPOS,
642       g_param_spec_int ("ypos", "Y Position", "Y Position of the picture",
643           G_MININT, G_MAXINT, DEFAULT_PAD_YPOS,
644           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
645   g_object_class_install_property (gobject_class, PROP_PAD_WIDTH,
646       g_param_spec_int ("width", "Width", "Width of the picture",
647           G_MININT, G_MAXINT, DEFAULT_PAD_WIDTH,
648           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
649   g_object_class_install_property (gobject_class, PROP_PAD_HEIGHT,
650       g_param_spec_int ("height", "Height", "Height of the picture",
651           G_MININT, G_MAXINT, DEFAULT_PAD_HEIGHT,
652           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
653   g_object_class_install_property (gobject_class, PROP_PAD_ALPHA,
654       g_param_spec_double ("alpha", "Alpha", "Alpha of the picture", 0.0, 1.0,
655           DEFAULT_PAD_ALPHA,
656           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
657   g_object_class_install_property (gobject_class, PROP_PAD_OPERATOR,
658       g_param_spec_enum ("operator", "Operator",
659           "Blending operator to use for blending this pad over the previous ones",
660           GST_TYPE_COMPOSITOR_OPERATOR, DEFAULT_PAD_OPERATOR,
661           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
662
663   /**
664    * GstCompositorPad:sizing-policy:
665    *
666    * Specifies sizing policy to use. Depending on selected sizing policy,
667    * scaled image might not fully cover the configured target rectangle area
668    * (e.g., "keep-aspect-ratio"). In that case, any uncovered area will be
669    * filled with background unless the uncovered area is drawn by other image.
670    *
671    * Since: 1.20
672    */
673   g_object_class_install_property (gobject_class, PROP_PAD_SIZING_POLICY,
674       g_param_spec_enum ("sizing-policy", "Sizing policy",
675           "Sizing policy to use for image scaling",
676           GST_TYPE_COMPOSITOR_SIZING_POLICY, DEFAULT_PAD_SIZING_POLICY,
677           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
678
679   vaggpadclass->prepare_frame_start =
680       GST_DEBUG_FUNCPTR (gst_compositor_pad_prepare_frame_start);
681
682   vaggcpadclass->create_conversion_info =
683       GST_DEBUG_FUNCPTR (gst_compositor_pad_create_conversion_info);
684
685   gst_type_mark_as_plugin_api (GST_TYPE_COMPOSITOR_SIZING_POLICY, 0);
686 }
687
688 static void
689 gst_compositor_pad_init (GstCompositorPad * compo_pad)
690 {
691   compo_pad->xpos = DEFAULT_PAD_XPOS;
692   compo_pad->ypos = DEFAULT_PAD_YPOS;
693   compo_pad->alpha = DEFAULT_PAD_ALPHA;
694   compo_pad->op = DEFAULT_PAD_OPERATOR;
695   compo_pad->width = DEFAULT_PAD_WIDTH;
696   compo_pad->height = DEFAULT_PAD_HEIGHT;
697   compo_pad->sizing_policy = DEFAULT_PAD_SIZING_POLICY;
698 }
699
700
701 /* GstCompositor */
702 #define DEFAULT_BACKGROUND COMPOSITOR_BACKGROUND_CHECKER
703 #define DEFAULT_ZERO_SIZE_IS_UNSCALED TRUE
704 enum
705 {
706   PROP_0,
707   PROP_BACKGROUND,
708   PROP_ZERO_SIZE_IS_UNSCALED,
709 };
710
711 static void
712 gst_compositor_get_property (GObject * object,
713     guint prop_id, GValue * value, GParamSpec * pspec)
714 {
715   GstCompositor *self = GST_COMPOSITOR (object);
716
717   switch (prop_id) {
718     case PROP_BACKGROUND:
719       g_value_set_enum (value, self->background);
720       break;
721     case PROP_ZERO_SIZE_IS_UNSCALED:
722       g_value_set_boolean (value, self->zero_size_is_unscaled);
723       break;
724     default:
725       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
726       break;
727   }
728 }
729
730 static void
731 gst_compositor_set_property (GObject * object,
732     guint prop_id, const GValue * value, GParamSpec * pspec)
733 {
734   GstCompositor *self = GST_COMPOSITOR (object);
735
736   switch (prop_id) {
737     case PROP_BACKGROUND:
738       self->background = g_value_get_enum (value);
739       break;
740     case PROP_ZERO_SIZE_IS_UNSCALED:
741       self->zero_size_is_unscaled = g_value_get_boolean (value);
742       break;
743     default:
744       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
745       break;
746   }
747 }
748
749 #define gst_compositor_parent_class parent_class
750 G_DEFINE_TYPE_WITH_CODE (GstCompositor, gst_compositor,
751     GST_TYPE_VIDEO_AGGREGATOR, G_IMPLEMENT_INTERFACE (GST_TYPE_CHILD_PROXY,
752         gst_compositor_child_proxy_init));
753 GST_ELEMENT_REGISTER_DEFINE (compositor, "compositor", GST_RANK_PRIMARY + 1,
754     GST_TYPE_COMPOSITOR);
755
756 static gboolean
757 set_functions (GstCompositor * self, const GstVideoInfo * info)
758 {
759   gboolean ret = FALSE;
760
761   self->blend = NULL;
762   self->overlay = NULL;
763   self->fill_checker = NULL;
764   self->fill_color = NULL;
765
766   switch (GST_VIDEO_INFO_FORMAT (info)) {
767     case GST_VIDEO_FORMAT_AYUV:
768       self->blend = gst_compositor_blend_ayuv;
769       self->overlay = gst_compositor_overlay_ayuv;
770       self->fill_checker = gst_compositor_fill_checker_ayuv;
771       self->fill_color = gst_compositor_fill_color_ayuv;
772       ret = TRUE;
773       break;
774     case GST_VIDEO_FORMAT_VUYA:
775       self->blend = gst_compositor_blend_vuya;
776       self->overlay = gst_compositor_overlay_vuya;
777       self->fill_checker = gst_compositor_fill_checker_vuya;
778       self->fill_color = gst_compositor_fill_color_vuya;
779       ret = TRUE;
780       break;
781     case GST_VIDEO_FORMAT_ARGB:
782       self->blend = gst_compositor_blend_argb;
783       self->overlay = gst_compositor_overlay_argb;
784       self->fill_checker = gst_compositor_fill_checker_argb;
785       self->fill_color = gst_compositor_fill_color_argb;
786       ret = TRUE;
787       break;
788     case GST_VIDEO_FORMAT_BGRA:
789       self->blend = gst_compositor_blend_bgra;
790       self->overlay = gst_compositor_overlay_bgra;
791       self->fill_checker = gst_compositor_fill_checker_bgra;
792       self->fill_color = gst_compositor_fill_color_bgra;
793       ret = TRUE;
794       break;
795     case GST_VIDEO_FORMAT_ABGR:
796       self->blend = gst_compositor_blend_abgr;
797       self->overlay = gst_compositor_overlay_abgr;
798       self->fill_checker = gst_compositor_fill_checker_abgr;
799       self->fill_color = gst_compositor_fill_color_abgr;
800       ret = TRUE;
801       break;
802     case GST_VIDEO_FORMAT_RGBA:
803       self->blend = gst_compositor_blend_rgba;
804       self->overlay = gst_compositor_overlay_rgba;
805       self->fill_checker = gst_compositor_fill_checker_rgba;
806       self->fill_color = gst_compositor_fill_color_rgba;
807       ret = TRUE;
808       break;
809     case GST_VIDEO_FORMAT_Y444:
810       self->blend = gst_compositor_blend_y444;
811       self->overlay = self->blend;
812       self->fill_checker = gst_compositor_fill_checker_y444;
813       self->fill_color = gst_compositor_fill_color_y444;
814       ret = TRUE;
815       break;
816     case GST_VIDEO_FORMAT_Y42B:
817       self->blend = gst_compositor_blend_y42b;
818       self->overlay = self->blend;
819       self->fill_checker = gst_compositor_fill_checker_y42b;
820       self->fill_color = gst_compositor_fill_color_y42b;
821       ret = TRUE;
822       break;
823     case GST_VIDEO_FORMAT_YUY2:
824       self->blend = gst_compositor_blend_yuy2;
825       self->overlay = self->blend;
826       self->fill_checker = gst_compositor_fill_checker_yuy2;
827       self->fill_color = gst_compositor_fill_color_yuy2;
828       ret = TRUE;
829       break;
830     case GST_VIDEO_FORMAT_UYVY:
831       self->blend = gst_compositor_blend_uyvy;
832       self->overlay = self->blend;
833       self->fill_checker = gst_compositor_fill_checker_uyvy;
834       self->fill_color = gst_compositor_fill_color_uyvy;
835       ret = TRUE;
836       break;
837     case GST_VIDEO_FORMAT_YVYU:
838       self->blend = gst_compositor_blend_yvyu;
839       self->overlay = self->blend;
840       self->fill_checker = gst_compositor_fill_checker_yvyu;
841       self->fill_color = gst_compositor_fill_color_yvyu;
842       ret = TRUE;
843       break;
844     case GST_VIDEO_FORMAT_I420:
845       self->blend = gst_compositor_blend_i420;
846       self->overlay = self->blend;
847       self->fill_checker = gst_compositor_fill_checker_i420;
848       self->fill_color = gst_compositor_fill_color_i420;
849       ret = TRUE;
850       break;
851     case GST_VIDEO_FORMAT_YV12:
852       self->blend = gst_compositor_blend_yv12;
853       self->overlay = self->blend;
854       self->fill_checker = gst_compositor_fill_checker_yv12;
855       self->fill_color = gst_compositor_fill_color_yv12;
856       ret = TRUE;
857       break;
858     case GST_VIDEO_FORMAT_NV12:
859       self->blend = gst_compositor_blend_nv12;
860       self->overlay = self->blend;
861       self->fill_checker = gst_compositor_fill_checker_nv12;
862       self->fill_color = gst_compositor_fill_color_nv12;
863       ret = TRUE;
864       break;
865     case GST_VIDEO_FORMAT_NV21:
866       self->blend = gst_compositor_blend_nv21;
867       self->overlay = self->blend;
868       self->fill_checker = gst_compositor_fill_checker_nv21;
869       self->fill_color = gst_compositor_fill_color_nv21;
870       ret = TRUE;
871       break;
872     case GST_VIDEO_FORMAT_Y41B:
873       self->blend = gst_compositor_blend_y41b;
874       self->overlay = self->blend;
875       self->fill_checker = gst_compositor_fill_checker_y41b;
876       self->fill_color = gst_compositor_fill_color_y41b;
877       ret = TRUE;
878       break;
879     case GST_VIDEO_FORMAT_RGB:
880       self->blend = gst_compositor_blend_rgb;
881       self->overlay = self->blend;
882       self->fill_checker = gst_compositor_fill_checker_rgb;
883       self->fill_color = gst_compositor_fill_color_rgb;
884       ret = TRUE;
885       break;
886     case GST_VIDEO_FORMAT_BGR:
887       self->blend = gst_compositor_blend_bgr;
888       self->overlay = self->blend;
889       self->fill_checker = gst_compositor_fill_checker_bgr;
890       self->fill_color = gst_compositor_fill_color_bgr;
891       ret = TRUE;
892       break;
893     case GST_VIDEO_FORMAT_xRGB:
894       self->blend = gst_compositor_blend_xrgb;
895       self->overlay = self->blend;
896       self->fill_checker = gst_compositor_fill_checker_xrgb;
897       self->fill_color = gst_compositor_fill_color_xrgb;
898       ret = TRUE;
899       break;
900     case GST_VIDEO_FORMAT_xBGR:
901       self->blend = gst_compositor_blend_xbgr;
902       self->overlay = self->blend;
903       self->fill_checker = gst_compositor_fill_checker_xbgr;
904       self->fill_color = gst_compositor_fill_color_xbgr;
905       ret = TRUE;
906       break;
907     case GST_VIDEO_FORMAT_RGBx:
908       self->blend = gst_compositor_blend_rgbx;
909       self->overlay = self->blend;
910       self->fill_checker = gst_compositor_fill_checker_rgbx;
911       self->fill_color = gst_compositor_fill_color_rgbx;
912       ret = TRUE;
913       break;
914     case GST_VIDEO_FORMAT_BGRx:
915       self->blend = gst_compositor_blend_bgrx;
916       self->overlay = self->blend;
917       self->fill_checker = gst_compositor_fill_checker_bgrx;
918       self->fill_color = gst_compositor_fill_color_bgrx;
919       ret = TRUE;
920       break;
921     default:
922       break;
923   }
924
925   return ret;
926 }
927
928 static GstCaps *
929 _fixate_caps (GstAggregator * agg, GstCaps * caps)
930 {
931   GstVideoAggregator *vagg = GST_VIDEO_AGGREGATOR (agg);
932   GList *l;
933   gint best_width = -1, best_height = -1;
934   gint best_fps_n = -1, best_fps_d = -1;
935   gint par_n, par_d;
936   gdouble best_fps = 0.;
937   GstCaps *ret = NULL;
938   GstStructure *s;
939
940   ret = gst_caps_make_writable (caps);
941
942   /* we need this to calculate how large to make the output frame */
943   s = gst_caps_get_structure (ret, 0);
944   if (gst_structure_has_field (s, "pixel-aspect-ratio")) {
945     gst_structure_fixate_field_nearest_fraction (s, "pixel-aspect-ratio", 1, 1);
946     gst_structure_get_fraction (s, "pixel-aspect-ratio", &par_n, &par_d);
947   } else {
948     par_n = par_d = 1;
949   }
950
951   GST_OBJECT_LOCK (vagg);
952   for (l = GST_ELEMENT (vagg)->sinkpads; l; l = l->next) {
953     GstVideoAggregatorPad *vaggpad = l->data;
954     GstCompositorPad *compositor_pad = GST_COMPOSITOR_PAD (vaggpad);
955     gint this_width, this_height;
956     gint width, height;
957     gint fps_n, fps_d;
958     gdouble cur_fps;
959     gint x_offset;
960     gint y_offset;
961
962     fps_n = GST_VIDEO_INFO_FPS_N (&vaggpad->info);
963     fps_d = GST_VIDEO_INFO_FPS_D (&vaggpad->info);
964     _mixer_pad_get_output_size (GST_COMPOSITOR (vagg), compositor_pad, par_n,
965         par_d, &width, &height, &x_offset, &y_offset);
966
967     if (width == 0 || height == 0)
968       continue;
969
970     /* {x,y}_offset represent padding size of each top and left area.
971      * To calculate total resolution, count bottom and right padding area
972      * as well here */
973     this_width = width + MAX (compositor_pad->xpos + 2 * x_offset, 0);
974     this_height = height + MAX (compositor_pad->ypos + 2 * y_offset, 0);
975
976     if (best_width < this_width)
977       best_width = this_width;
978     if (best_height < this_height)
979       best_height = this_height;
980
981     if (fps_d == 0)
982       cur_fps = 0.0;
983     else
984       gst_util_fraction_to_double (fps_n, fps_d, &cur_fps);
985
986     if (best_fps < cur_fps) {
987       best_fps = cur_fps;
988       best_fps_n = fps_n;
989       best_fps_d = fps_d;
990     }
991   }
992   GST_OBJECT_UNLOCK (vagg);
993
994   if (best_fps_n <= 0 || best_fps_d <= 0 || best_fps == 0.0) {
995     best_fps_n = 25;
996     best_fps_d = 1;
997     best_fps = 25.0;
998   }
999
1000   gst_structure_fixate_field_nearest_int (s, "width", best_width);
1001   gst_structure_fixate_field_nearest_int (s, "height", best_height);
1002   gst_structure_fixate_field_nearest_fraction (s, "framerate", best_fps_n,
1003       best_fps_d);
1004   ret = gst_caps_fixate (ret);
1005
1006   return ret;
1007 }
1008
1009 static void
1010 gst_parallelized_task_thread_func (gpointer data)
1011 {
1012   GstParallelizedTaskRunner *runner = data;
1013   gint idx;
1014
1015   g_mutex_lock (&runner->lock);
1016   idx = runner->n_todo--;
1017   g_assert (runner->n_todo >= -1);
1018   g_mutex_unlock (&runner->lock);
1019
1020   g_assert (runner->func != NULL);
1021
1022   runner->func (runner->task_data[idx]);
1023 }
1024
1025 static void
1026 gst_parallelized_task_runner_join (GstParallelizedTaskRunner * self)
1027 {
1028   gboolean joined = FALSE;
1029
1030   while (!joined) {
1031     g_mutex_lock (&self->lock);
1032     if (!(joined = gst_queue_array_is_empty (self->tasks))) {
1033       gpointer task = gst_queue_array_pop_head (self->tasks);
1034       g_mutex_unlock (&self->lock);
1035       gst_task_pool_join (self->pool, task);
1036     } else {
1037       g_mutex_unlock (&self->lock);
1038     }
1039   }
1040 }
1041
1042 static void
1043 gst_parallelized_task_runner_free (GstParallelizedTaskRunner * self)
1044 {
1045   gst_parallelized_task_runner_join (self);
1046
1047   gst_queue_array_free (self->tasks);
1048   if (self->own_pool)
1049     gst_task_pool_cleanup (self->pool);
1050   gst_object_unref (self->pool);
1051   g_mutex_clear (&self->lock);
1052   g_free (self);
1053 }
1054
1055 static GstParallelizedTaskRunner *
1056 gst_parallelized_task_runner_new (guint n_threads, GstTaskPool * pool,
1057     gboolean async_tasks)
1058 {
1059   GstParallelizedTaskRunner *self;
1060
1061   if (n_threads == 0)
1062     n_threads = g_get_num_processors ();
1063
1064   self = g_new0 (GstParallelizedTaskRunner, 1);
1065
1066   if (pool) {
1067     self->pool = g_object_ref (pool);
1068     self->own_pool = FALSE;
1069
1070     /* No reason to split up the work between more threads than the
1071      * pool can spawn */
1072     if (GST_IS_SHARED_TASK_POOL (pool))
1073       n_threads =
1074           MIN (n_threads,
1075           gst_shared_task_pool_get_max_threads (GST_SHARED_TASK_POOL (pool)));
1076   } else {
1077     self->pool = gst_shared_task_pool_new ();
1078     self->own_pool = TRUE;
1079     gst_shared_task_pool_set_max_threads (GST_SHARED_TASK_POOL (self->pool),
1080         n_threads);
1081     gst_task_pool_prepare (self->pool, NULL);
1082   }
1083
1084   self->tasks = gst_queue_array_new (n_threads);
1085
1086   self->n_threads = n_threads;
1087
1088   self->n_todo = -1;
1089   g_mutex_init (&self->lock);
1090
1091   /* Set when scheduling a job */
1092   self->func = NULL;
1093   self->task_data = NULL;
1094   self->async_tasks = async_tasks;
1095
1096   return self;
1097 }
1098
1099 static void
1100 gst_parallelized_task_runner_finish (GstParallelizedTaskRunner * self)
1101 {
1102   g_return_if_fail (self->func != NULL);
1103
1104   gst_parallelized_task_runner_join (self);
1105
1106   self->func = NULL;
1107   self->task_data = NULL;
1108 }
1109
1110 static void
1111 gst_parallelized_task_runner_run (GstParallelizedTaskRunner * self,
1112     GstParallelizedTaskFunc func, gpointer * task_data)
1113 {
1114   guint n_threads = self->n_threads;
1115
1116   self->func = func;
1117   self->task_data = task_data;
1118
1119   if (n_threads > 1 || self->async_tasks) {
1120     guint i = 0;
1121     g_mutex_lock (&self->lock);
1122     self->n_todo = self->n_threads - 1;
1123     if (!self->async_tasks) {
1124       /* if not async, perform one of the functions in the current thread */
1125       self->n_todo--;
1126       i = 1;
1127     }
1128     for (; i < n_threads; i++) {
1129       gpointer task =
1130           gst_task_pool_push (self->pool, gst_parallelized_task_thread_func,
1131           self, NULL);
1132
1133       /* The return value of push() is nullable but NULL is only returned
1134        * with the shared task pool when gst_task_pool_prepare() has not been
1135        * called and would thus be a programming error that we should hard-fail
1136        * on.
1137        */
1138       g_assert (task != NULL);
1139       gst_queue_array_push_tail (self->tasks, task);
1140     }
1141     g_mutex_unlock (&self->lock);
1142   }
1143
1144   if (!self->async_tasks) {
1145     self->func (self->task_data[self->n_threads - 1]);
1146
1147     gst_parallelized_task_runner_finish (self);
1148   }
1149 }
1150
1151 static gboolean
1152 _negotiated_caps (GstAggregator * agg, GstCaps * caps)
1153 {
1154   GstCompositor *compositor = GST_COMPOSITOR (agg);
1155   GstVideoAggregator *vagg = GST_VIDEO_AGGREGATOR (agg);
1156   GstVideoInfo v_info;
1157   guint n_threads;
1158
1159   GST_DEBUG_OBJECT (agg, "Negotiated caps %" GST_PTR_FORMAT, caps);
1160
1161   if (!gst_video_info_from_caps (&v_info, caps))
1162     return FALSE;
1163
1164   if (!set_functions (compositor, &v_info)) {
1165     GST_ERROR_OBJECT (agg, "Failed to setup vfuncs");
1166     return FALSE;
1167   }
1168
1169   n_threads = g_get_num_processors ();
1170   /* Magic number of 200 lines */
1171   if (GST_VIDEO_INFO_HEIGHT (&v_info) / n_threads < 200)
1172     n_threads = (GST_VIDEO_INFO_HEIGHT (&v_info) + 199) / 200;
1173   if (n_threads < 1)
1174     n_threads = 1;
1175
1176   /* XXX: implement better thread count change */
1177   if (compositor->blend_runner
1178       && compositor->blend_runner->n_threads != n_threads) {
1179     gst_parallelized_task_runner_free (compositor->blend_runner);
1180     compositor->blend_runner = NULL;
1181   }
1182   if (!compositor->blend_runner) {
1183     GstTaskPool *pool = gst_video_aggregator_get_execution_task_pool (vagg);
1184     compositor->blend_runner =
1185         gst_parallelized_task_runner_new (n_threads, pool, FALSE);
1186     gst_clear_object (&pool);
1187   }
1188
1189   return GST_AGGREGATOR_CLASS (parent_class)->negotiated_src_caps (agg, caps);
1190 }
1191
1192 static gboolean
1193 _should_draw_background (GstVideoAggregator * vagg)
1194 {
1195   GstVideoRectangle bg_rect;
1196   gboolean draw = TRUE;
1197   GList *l;
1198
1199   bg_rect.x = bg_rect.y = 0;
1200
1201   GST_OBJECT_LOCK (vagg);
1202   bg_rect.w = GST_VIDEO_INFO_WIDTH (&vagg->info);
1203   bg_rect.h = GST_VIDEO_INFO_HEIGHT (&vagg->info);
1204   /* Check if the background is completely obscured by a pad
1205    * TODO: Also skip if it's obscured by a combination of pads */
1206   for (l = GST_ELEMENT (vagg)->sinkpads; l; l = l->next) {
1207     if (_pad_obscures_rectangle (vagg, l->data, bg_rect)) {
1208       draw = FALSE;
1209       break;
1210     }
1211   }
1212   GST_OBJECT_UNLOCK (vagg);
1213   return draw;
1214 }
1215
1216 static gboolean
1217 frames_can_copy (const GstVideoFrame * frame1, const GstVideoFrame * frame2)
1218 {
1219   if (GST_VIDEO_FRAME_FORMAT (frame1) != GST_VIDEO_FRAME_FORMAT (frame2))
1220     return FALSE;
1221   if (GST_VIDEO_FRAME_HEIGHT (frame1) != GST_VIDEO_FRAME_HEIGHT (frame2))
1222     return FALSE;
1223   if (GST_VIDEO_FRAME_WIDTH (frame1) != GST_VIDEO_FRAME_WIDTH (frame2))
1224     return FALSE;
1225   return TRUE;
1226 }
1227
1228 struct CompositePadInfo
1229 {
1230   GstVideoFrame *prepared_frame;
1231   GstCompositorPad *pad;
1232   GstCompositorBlendMode blend_mode;
1233 };
1234
1235 struct CompositeTask
1236 {
1237   GstCompositor *compositor;
1238   GstVideoFrame *out_frame;
1239   guint dst_line_start;
1240   guint dst_line_end;
1241   gboolean draw_background;
1242   guint n_pads;
1243   struct CompositePadInfo *pads_info;
1244 };
1245
1246 static void
1247 _draw_background (GstCompositor * comp, GstVideoFrame * outframe,
1248     guint y_start, guint y_end, BlendFunction * composite)
1249 {
1250   *composite = comp->blend;
1251
1252   switch (comp->background) {
1253     case COMPOSITOR_BACKGROUND_CHECKER:
1254       comp->fill_checker (outframe, y_start, y_end);
1255       break;
1256     case COMPOSITOR_BACKGROUND_BLACK:
1257       comp->fill_color (outframe, y_start, y_end, 16, 128, 128);
1258       break;
1259     case COMPOSITOR_BACKGROUND_WHITE:
1260       comp->fill_color (outframe, y_start, y_end, 240, 128, 128);
1261       break;
1262     case COMPOSITOR_BACKGROUND_TRANSPARENT:
1263     {
1264       guint i, plane, num_planes, height;
1265
1266       num_planes = GST_VIDEO_FRAME_N_PLANES (outframe);
1267       for (plane = 0; plane < num_planes; ++plane) {
1268         const GstVideoFormatInfo *info;
1269         gint comp[GST_VIDEO_MAX_COMPONENTS];
1270         guint8 *pdata;
1271         gsize rowsize, plane_stride;
1272         gint yoffset;
1273
1274         info = outframe->info.finfo;
1275         pdata = GST_VIDEO_FRAME_PLANE_DATA (outframe, plane);
1276         plane_stride = GST_VIDEO_FRAME_PLANE_STRIDE (outframe, plane);
1277
1278         gst_video_format_info_component (info, plane, comp);
1279         rowsize = GST_VIDEO_FRAME_COMP_WIDTH (outframe, comp[0])
1280             * GST_VIDEO_FRAME_COMP_PSTRIDE (outframe, comp[0]);
1281         height = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (info, comp[0],
1282             (y_end - y_start));
1283
1284         yoffset = GST_VIDEO_FORMAT_INFO_SCALE_HEIGHT (info, comp[0], y_start);
1285
1286         pdata += yoffset * plane_stride;
1287         for (i = 0; i < height; ++i) {
1288           memset (pdata, 0, rowsize);
1289           pdata += plane_stride;
1290         }
1291       }
1292       /* use overlay to keep background transparent */
1293       *composite = comp->overlay;
1294       break;
1295     }
1296   }
1297 }
1298
1299 static void
1300 blend_pads (struct CompositeTask *comp)
1301 {
1302   BlendFunction composite;
1303   guint i;
1304
1305   composite = comp->compositor->blend;
1306
1307   if (comp->draw_background) {
1308     _draw_background (comp->compositor, comp->out_frame, comp->dst_line_start,
1309         comp->dst_line_end, &composite);
1310   }
1311
1312   for (i = 0; i < comp->n_pads; i++) {
1313     composite (comp->pads_info[i].prepared_frame,
1314         comp->pads_info[i].pad->xpos + comp->pads_info[i].pad->x_offset,
1315         comp->pads_info[i].pad->ypos + comp->pads_info[i].pad->y_offset,
1316         comp->pads_info[i].pad->alpha, comp->out_frame, comp->dst_line_start,
1317         comp->dst_line_end, comp->pads_info[i].blend_mode);
1318   }
1319 }
1320
1321 static GstFlowReturn
1322 gst_compositor_aggregate_frames (GstVideoAggregator * vagg, GstBuffer * outbuf)
1323 {
1324   GstCompositor *compositor = GST_COMPOSITOR (vagg);
1325   GList *l;
1326   GstVideoFrame out_frame, *outframe;
1327   gboolean draw_background;
1328   guint drawn_a_pad = FALSE;
1329   struct CompositePadInfo *pads_info;
1330   guint i, n_pads = 0;
1331
1332   if (!gst_video_frame_map (&out_frame, &vagg->info, outbuf, GST_MAP_WRITE)) {
1333     GST_WARNING_OBJECT (vagg, "Could not map output buffer");
1334     return GST_FLOW_ERROR;
1335   }
1336
1337   outframe = &out_frame;
1338
1339   /* If one of the frames to be composited completely obscures the background,
1340    * don't bother drawing the background at all. We can also always use the
1341    * 'blend' BlendFunction in that case because it only changes if we have to
1342    * overlay on top of a transparent background. */
1343   draw_background = _should_draw_background (vagg);
1344
1345   GST_OBJECT_LOCK (vagg);
1346   for (l = GST_ELEMENT (vagg)->sinkpads; l; l = l->next) {
1347     GstVideoAggregatorPad *pad = l->data;
1348     GstVideoFrame *prepared_frame =
1349         gst_video_aggregator_pad_get_prepared_frame (pad);
1350
1351     if (prepared_frame)
1352       n_pads++;
1353   }
1354
1355   pads_info = g_newa (struct CompositePadInfo, n_pads);
1356   n_pads = 0;
1357
1358   for (l = GST_ELEMENT (vagg)->sinkpads; l; l = l->next) {
1359     GstVideoAggregatorPad *pad = l->data;
1360     GstCompositorPad *compo_pad = GST_COMPOSITOR_PAD (pad);
1361     GstVideoFrame *prepared_frame =
1362         gst_video_aggregator_pad_get_prepared_frame (pad);
1363     GstCompositorBlendMode blend_mode = COMPOSITOR_BLEND_MODE_OVER;
1364
1365     switch (compo_pad->op) {
1366       case COMPOSITOR_OPERATOR_SOURCE:
1367         blend_mode = COMPOSITOR_BLEND_MODE_SOURCE;
1368         break;
1369       case COMPOSITOR_OPERATOR_OVER:
1370         blend_mode = COMPOSITOR_BLEND_MODE_OVER;
1371         break;
1372       case COMPOSITOR_OPERATOR_ADD:
1373         blend_mode = COMPOSITOR_BLEND_MODE_ADD;
1374         break;
1375       default:
1376         g_assert_not_reached ();
1377         break;
1378     }
1379
1380     if (prepared_frame != NULL) {
1381       /* If this is the first pad we're drawing, and we didn't draw the
1382        * background, and @prepared_frame has the same format, height, and width
1383        * as @outframe, then we can just copy it as-is. Subsequent pads (if any)
1384        * will be composited on top of it. */
1385       if (!drawn_a_pad && !draw_background &&
1386           frames_can_copy (prepared_frame, outframe)) {
1387         gst_video_frame_copy (outframe, prepared_frame);
1388       } else {
1389         pads_info[n_pads].pad = compo_pad;
1390         pads_info[n_pads].prepared_frame = prepared_frame;
1391         pads_info[n_pads].blend_mode = blend_mode;
1392         n_pads++;
1393       }
1394       drawn_a_pad = TRUE;
1395     }
1396   }
1397
1398   {
1399     guint n_threads, lines_per_thread;
1400     guint out_height;
1401     struct CompositeTask *tasks;
1402     struct CompositeTask **tasks_p;
1403
1404     n_threads = compositor->blend_runner->n_threads;
1405
1406     tasks = g_newa (struct CompositeTask, n_threads);
1407     tasks_p = g_newa (struct CompositeTask *, n_threads);
1408
1409     out_height = GST_VIDEO_FRAME_HEIGHT (outframe);
1410     lines_per_thread = (out_height + n_threads - 1) / n_threads;
1411
1412     for (i = 0; i < n_threads; i++) {
1413       tasks[i].compositor = compositor;
1414       tasks[i].n_pads = n_pads;
1415       tasks[i].pads_info = pads_info;
1416       tasks[i].out_frame = outframe;
1417       tasks[i].draw_background = draw_background;
1418       /* This is a dumb split of the work by number of output lines.
1419        * If there is a section of the output that reads from a lot of source
1420        * pads, then that thread will consume more time. Maybe tracking and
1421        * splitting on the source fill rate would produce better results. */
1422       tasks[i].dst_line_start = i * lines_per_thread;
1423       tasks[i].dst_line_end = MIN ((i + 1) * lines_per_thread, out_height);
1424
1425       tasks_p[i] = &tasks[i];
1426     }
1427
1428     gst_parallelized_task_runner_run (compositor->blend_runner,
1429         (GstParallelizedTaskFunc) blend_pads, (gpointer *) tasks_p);
1430   }
1431
1432   GST_OBJECT_UNLOCK (vagg);
1433
1434   gst_video_frame_unmap (outframe);
1435
1436   return GST_FLOW_OK;
1437 }
1438
1439 static GstPad *
1440 gst_compositor_request_new_pad (GstElement * element, GstPadTemplate * templ,
1441     const gchar * req_name, const GstCaps * caps)
1442 {
1443   GstPad *newpad;
1444
1445   newpad = (GstPad *)
1446       GST_ELEMENT_CLASS (parent_class)->request_new_pad (element,
1447       templ, req_name, caps);
1448
1449   if (newpad == NULL)
1450     goto could_not_create;
1451
1452   gst_child_proxy_child_added (GST_CHILD_PROXY (element), G_OBJECT (newpad),
1453       GST_OBJECT_NAME (newpad));
1454
1455   return newpad;
1456
1457 could_not_create:
1458   {
1459     GST_DEBUG_OBJECT (element, "could not create/add pad");
1460     return NULL;
1461   }
1462 }
1463
1464 static void
1465 gst_compositor_release_pad (GstElement * element, GstPad * pad)
1466 {
1467   GstCompositor *compositor;
1468
1469   compositor = GST_COMPOSITOR (element);
1470
1471   GST_DEBUG_OBJECT (compositor, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1472
1473   gst_child_proxy_child_removed (GST_CHILD_PROXY (compositor), G_OBJECT (pad),
1474       GST_OBJECT_NAME (pad));
1475
1476   GST_ELEMENT_CLASS (parent_class)->release_pad (element, pad);
1477 }
1478
1479 static gboolean
1480 _sink_query (GstAggregator * agg, GstAggregatorPad * bpad, GstQuery * query)
1481 {
1482   switch (GST_QUERY_TYPE (query)) {
1483     case GST_QUERY_ALLOCATION:{
1484       GstCaps *caps;
1485       GstVideoInfo info;
1486       GstBufferPool *pool;
1487       guint size;
1488       GstStructure *structure;
1489
1490       gst_query_parse_allocation (query, &caps, NULL);
1491
1492       if (caps == NULL)
1493         return FALSE;
1494
1495       if (!gst_video_info_from_caps (&info, caps))
1496         return FALSE;
1497
1498       size = GST_VIDEO_INFO_SIZE (&info);
1499
1500       pool = gst_video_buffer_pool_new ();
1501
1502       structure = gst_buffer_pool_get_config (pool);
1503       gst_buffer_pool_config_set_params (structure, caps, size, 0, 0);
1504
1505       if (!gst_buffer_pool_set_config (pool, structure)) {
1506         gst_object_unref (pool);
1507         return FALSE;
1508       }
1509
1510       gst_query_add_allocation_pool (query, pool, size, 0, 0);
1511       gst_object_unref (pool);
1512       gst_query_add_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
1513
1514       return TRUE;
1515     }
1516     default:
1517       return GST_AGGREGATOR_CLASS (parent_class)->sink_query (agg, bpad, query);
1518   }
1519 }
1520
1521 static void
1522 gst_compositor_finalize (GObject * object)
1523 {
1524   GstCompositor *compositor = GST_COMPOSITOR (object);
1525
1526   if (compositor->blend_runner)
1527     gst_parallelized_task_runner_free (compositor->blend_runner);
1528   compositor->blend_runner = NULL;
1529
1530   G_OBJECT_CLASS (parent_class)->finalize (object);
1531 }
1532
1533 /* GObject boilerplate */
1534 static void
1535 gst_compositor_class_init (GstCompositorClass * klass)
1536 {
1537   GObjectClass *gobject_class = (GObjectClass *) klass;
1538   GstElementClass *gstelement_class = (GstElementClass *) klass;
1539   GstVideoAggregatorClass *videoaggregator_class =
1540       (GstVideoAggregatorClass *) klass;
1541   GstAggregatorClass *agg_class = (GstAggregatorClass *) klass;
1542
1543   gobject_class->get_property = gst_compositor_get_property;
1544   gobject_class->set_property = gst_compositor_set_property;
1545   gobject_class->finalize = gst_compositor_finalize;
1546
1547   gstelement_class->request_new_pad =
1548       GST_DEBUG_FUNCPTR (gst_compositor_request_new_pad);
1549   gstelement_class->release_pad =
1550       GST_DEBUG_FUNCPTR (gst_compositor_release_pad);
1551   agg_class->sink_query = _sink_query;
1552   agg_class->fixate_src_caps = _fixate_caps;
1553   agg_class->negotiated_src_caps = _negotiated_caps;
1554   videoaggregator_class->aggregate_frames = gst_compositor_aggregate_frames;
1555
1556   g_object_class_install_property (gobject_class, PROP_BACKGROUND,
1557       g_param_spec_enum ("background", "Background", "Background type",
1558           GST_TYPE_COMPOSITOR_BACKGROUND,
1559           DEFAULT_BACKGROUND, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1560
1561   /**
1562    * compositor:zero-size-is-unscaled:
1563    *
1564    * Whether a pad with height or width 0 should be left unscaled
1565    * in that dimension, or simply not composited in. Setting it to
1566    * %FALSE might be useful when animating those properties.
1567    *
1568    * Since: 1.20
1569    */
1570   g_object_class_install_property (gobject_class, PROP_ZERO_SIZE_IS_UNSCALED,
1571       g_param_spec_boolean ("zero-size-is-unscaled", "Zero size is unscaled",
1572           "If TRUE, then input video is unscaled in that dimension "
1573           "if width or height is 0 (for backwards compatibility)",
1574           DEFAULT_ZERO_SIZE_IS_UNSCALED,
1575           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1576
1577   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
1578       &src_factory, GST_TYPE_AGGREGATOR_PAD);
1579   gst_element_class_add_static_pad_template_with_gtype (gstelement_class,
1580       &sink_factory, GST_TYPE_COMPOSITOR_PAD);
1581
1582   gst_element_class_set_static_metadata (gstelement_class, "Compositor",
1583       "Filter/Editor/Video/Compositor",
1584       "Composite multiple video streams", "Wim Taymans <wim@fluendo.com>, "
1585       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
1586
1587   gst_type_mark_as_plugin_api (GST_TYPE_COMPOSITOR_PAD, 0);
1588   gst_type_mark_as_plugin_api (GST_TYPE_COMPOSITOR_OPERATOR, 0);
1589   gst_type_mark_as_plugin_api (GST_TYPE_COMPOSITOR_BACKGROUND, 0);
1590 }
1591
1592 static void
1593 gst_compositor_init (GstCompositor * self)
1594 {
1595   /* initialize variables */
1596   self->background = DEFAULT_BACKGROUND;
1597   self->zero_size_is_unscaled = DEFAULT_ZERO_SIZE_IS_UNSCALED;
1598 }
1599
1600 /* GstChildProxy implementation */
1601 static GObject *
1602 gst_compositor_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
1603     guint index)
1604 {
1605   GstCompositor *compositor = GST_COMPOSITOR (child_proxy);
1606   GObject *obj = NULL;
1607
1608   GST_OBJECT_LOCK (compositor);
1609   obj = g_list_nth_data (GST_ELEMENT_CAST (compositor)->sinkpads, index);
1610   if (obj)
1611     gst_object_ref (obj);
1612   GST_OBJECT_UNLOCK (compositor);
1613
1614   return obj;
1615 }
1616
1617 static guint
1618 gst_compositor_child_proxy_get_children_count (GstChildProxy * child_proxy)
1619 {
1620   guint count = 0;
1621   GstCompositor *compositor = GST_COMPOSITOR (child_proxy);
1622
1623   GST_OBJECT_LOCK (compositor);
1624   count = GST_ELEMENT_CAST (compositor)->numsinkpads;
1625   GST_OBJECT_UNLOCK (compositor);
1626   GST_INFO_OBJECT (compositor, "Children Count: %d", count);
1627
1628   return count;
1629 }
1630
1631 static void
1632 gst_compositor_child_proxy_init (gpointer g_iface, gpointer iface_data)
1633 {
1634   GstChildProxyInterface *iface = g_iface;
1635
1636   iface->get_child_by_index = gst_compositor_child_proxy_get_child_by_index;
1637   iface->get_children_count = gst_compositor_child_proxy_get_children_count;
1638 }
1639
1640 /* Element registration */
1641 static gboolean
1642 plugin_init (GstPlugin * plugin)
1643 {
1644   GST_DEBUG_CATEGORY_INIT (gst_compositor_debug, "compositor", 0, "compositor");
1645
1646   gst_compositor_init_blend ();
1647
1648   return GST_ELEMENT_REGISTER (compositor, plugin);
1649 }
1650
1651 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1652     GST_VERSION_MINOR,
1653     compositor,
1654     "Compositor", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME,
1655     GST_PACKAGE_ORIGIN)