videomixer[2]: Use orc_memset() instead of memset()
[platform/upstream/gst-plugins-good.git] / gst / videomixer / videomixer2.c
1 /* Generic video mixer plugin
2  * Copyright (C) 2004, 2008 Wim Taymans <wim@fluendo.com>
3  * Copyright (C) 2010 Sebastian Dröge <sebastian.droege@collabora.co.uk>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-videomixer2
23  *
24  * Videomixer2 can accept AYUV, ARGB and BGRA video streams. For each of the requested
25  * sink pads it will compare the incoming geometry and framerate to define the
26  * output parameters. Indeed output video frames will have the geometry of the
27  * biggest incoming video stream and the framerate of the fastest incoming one.
28  *
29  * All sink pads must be either AYUV, ARGB or BGRA, but a mixture of them is not 
30  * supported. The src pad will have the same colorspace as the sinks. 
31  * No colorspace conversion is done. 
32  * 
33  * Individual parameters for each input stream can be configured on the
34  * #GstVideoMixer2Pad.
35  *
36  * At this stage, videomixer2 is considered UNSTABLE. The API provided in the
37  * properties may yet change in the near future. When videomixer2 is stable,
38  * it will replace #videomixer
39  *
40  * <refsect2>
41  * <title>Sample pipelines</title>
42  * |[
43  * gst-launch-0.10 \
44  *   videotestsrc pattern=1 ! \
45  *   video/x-raw-yuv,format=\(fourcc\)AYUV,framerate=\(fraction\)10/1,width=100,height=100 ! \
46  *   videobox border-alpha=0 top=-70 bottom=-70 right=-220 ! \
47  *   videomixer2 name=mix sink_0::alpha=0.7 sink_1::alpha=0.5 ! \
48  *   ffmpegcolorspace ! xvimagesink \
49  *   videotestsrc ! \
50  *   video/x-raw-yuv,format=\(fourcc\)AYUV,framerate=\(fraction\)5/1,width=320,height=240 ! mix.
51  * ]| A pipeline to demonstrate videomixer used together with videobox.
52  * This should show a 320x240 pixels video test source with some transparency
53  * showing the background checker pattern. Another video test source with just
54  * the snow pattern of 100x100 pixels is overlayed on top of the first one on
55  * the left vertically centered with a small transparency showing the first
56  * video test source behind and the checker pattern under it. Note that the
57  * framerate of the output video is 10 frames per second.
58  * |[
59  * gst-launch videotestsrc pattern=1 ! \
60  *   video/x-raw-rgb, framerate=\(fraction\)10/1, width=100, height=100 ! \
61  *   videomixer2 name=mix ! ffmpegcolorspace ! ximagesink \
62  *   videotestsrc !  \
63  *   video/x-raw-rgb, framerate=\(fraction\)5/1, width=320, height=240 ! mix.
64  * ]| A pipeline to demostrate bgra mixing. (This does not demonstrate alpha blending). 
65  * |[
66  * gst-launch videotestsrc pattern=1 ! \
67  *   video/x-raw-yuv,format =\(fourcc\)I420, framerate=\(fraction\)10/1, width=100, height=100 ! \
68  *   videomixer2 name=mix ! ffmpegcolorspace ! ximagesink \
69  *   videotestsrc ! \
70  *   video/x-raw-yuv,format=\(fourcc\)I420, framerate=\(fraction\)5/1, width=320, height=240 ! mix.
71  * ]| A pipeline to test I420
72  * |[
73  * gst-launch videomixer2 name=mixer sink_1::alpha=0.5 sink_1::xpos=50 sink_1::ypos=50 ! \
74  *   ffmpegcolorspace ! ximagesink \
75  *   videotestsrc pattern=snow timestamp-offset=3000000000 ! \
76  *   "video/x-raw-yuv,format=(fourcc)AYUV,width=640,height=480,framerate=(fraction)30/1" ! \
77  *   timeoverlay ! queue2 ! mixer. \
78  *   videotestsrc pattern=smpte ! \
79  *   "video/x-raw-yuv,format=(fourcc)AYUV,width=800,height=600,framerate=(fraction)10/1" ! \
80  *   timeoverlay ! queue2 ! mixer.
81  * ]| A pipeline to demonstrate synchronized mixing (the second stream starts after 3 seconds)
82  * </refsect2>
83  */
84
85 #ifdef HAVE_CONFIG_H
86 #include "config.h"
87 #endif
88
89 #include <string.h>
90
91 #include "videomixer2.h"
92 #include "videomixer2pad.h"
93
94 #include <gst/controller/gstcontroller.h>
95
96 #ifdef DISABLE_ORC
97 #define orc_memset memset
98 #else
99 #include <orc/orcfunctions.h>
100 #endif
101
102 GST_DEBUG_CATEGORY_STATIC (gst_videomixer2_debug);
103 #define GST_CAT_DEFAULT gst_videomixer2_debug
104
105 #define GST_VIDEO_MIXER2_GET_LOCK(mix) \
106   (GST_VIDEO_MIXER2(mix)->lock)
107 #define GST_VIDEO_MIXER2_LOCK(mix) \
108   (g_mutex_lock(GST_VIDEO_MIXER2_GET_LOCK (mix)))
109 #define GST_VIDEO_MIXER2_UNLOCK(mix) \
110   (g_mutex_unlock(GST_VIDEO_MIXER2_GET_LOCK (mix)))
111
112 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
113     GST_PAD_SRC,
114     GST_PAD_ALWAYS,
115     GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_BGRA ";"
116         GST_VIDEO_CAPS_ARGB ";" GST_VIDEO_CAPS_RGBA ";" GST_VIDEO_CAPS_ABGR ";"
117         GST_VIDEO_CAPS_YUV ("Y444") ";" GST_VIDEO_CAPS_YUV ("Y42B") ";"
118         GST_VIDEO_CAPS_YUV ("YUY2") ";" GST_VIDEO_CAPS_YUV ("UYVY") ";"
119         GST_VIDEO_CAPS_YUV ("YVYU") ";"
120         GST_VIDEO_CAPS_YUV ("I420") ";" GST_VIDEO_CAPS_YUV ("YV12") ";"
121         GST_VIDEO_CAPS_YUV ("Y41B") ";" GST_VIDEO_CAPS_RGB ";"
122         GST_VIDEO_CAPS_BGR ";" GST_VIDEO_CAPS_xRGB ";" GST_VIDEO_CAPS_xBGR ";"
123         GST_VIDEO_CAPS_RGBx ";" GST_VIDEO_CAPS_BGRx)
124     );
125
126 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink_%d",
127     GST_PAD_SINK,
128     GST_PAD_REQUEST,
129     GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_BGRA ";"
130         GST_VIDEO_CAPS_ARGB ";" GST_VIDEO_CAPS_RGBA ";" GST_VIDEO_CAPS_ABGR ";"
131         GST_VIDEO_CAPS_YUV ("Y444") ";" GST_VIDEO_CAPS_YUV ("Y42B") ";"
132         GST_VIDEO_CAPS_YUV ("YUY2") ";" GST_VIDEO_CAPS_YUV ("UYVY") ";"
133         GST_VIDEO_CAPS_YUV ("YVYU") ";"
134         GST_VIDEO_CAPS_YUV ("I420") ";" GST_VIDEO_CAPS_YUV ("YV12") ";"
135         GST_VIDEO_CAPS_YUV ("Y41B") ";" GST_VIDEO_CAPS_RGB ";"
136         GST_VIDEO_CAPS_BGR ";" GST_VIDEO_CAPS_xRGB ";" GST_VIDEO_CAPS_xBGR ";"
137         GST_VIDEO_CAPS_RGBx ";" GST_VIDEO_CAPS_BGRx)
138     );
139
140 static void gst_videomixer2_child_proxy_init (gpointer g_iface,
141     gpointer iface_data);
142 static gboolean gst_videomixer2_push_sink_event (GstVideoMixer2 * mix,
143     GstEvent * event);
144 static void gst_videomixer2_release_pad (GstElement * element, GstPad * pad);
145 static void gst_videomixer2_reset_qos (GstVideoMixer2 * mix);
146
147 static void
148 _do_init (GType object_type)
149 {
150   static const GInterfaceInfo child_proxy_info = {
151     (GInterfaceInitFunc) gst_videomixer2_child_proxy_init,
152     NULL,
153     NULL
154   };
155
156   g_type_add_interface_static (object_type, GST_TYPE_CHILD_PROXY,
157       &child_proxy_info);
158 }
159
160 struct _GstVideoMixer2Collect
161 {
162   GstCollectData2 collect;      /* we extend the CollectData */
163
164   GstVideoMixer2Pad *mixpad;
165
166   GstBuffer *queued;            /* buffer for which we don't know the end time yet */
167
168   GstBuffer *buffer;            /* buffer that should be blended now */
169   GstClockTime start_time;
170   GstClockTime end_time;
171 };
172
173 #define DEFAULT_PAD_ZORDER 0
174 #define DEFAULT_PAD_XPOS   0
175 #define DEFAULT_PAD_YPOS   0
176 #define DEFAULT_PAD_ALPHA  1.0
177 enum
178 {
179   PROP_PAD_0,
180   PROP_PAD_ZORDER,
181   PROP_PAD_XPOS,
182   PROP_PAD_YPOS,
183   PROP_PAD_ALPHA
184 };
185
186 G_DEFINE_TYPE (GstVideoMixer2Pad, gst_videomixer2_pad, GST_TYPE_PAD);
187
188 static void
189 gst_videomixer2_collect_free (GstCollectData2 * data)
190 {
191   GstVideoMixer2Collect *cdata = (GstVideoMixer2Collect *) data;
192
193   gst_buffer_replace (&cdata->buffer, NULL);
194 }
195
196 static gboolean
197 gst_videomixer2_update_src_caps (GstVideoMixer2 * mix)
198 {
199   GSList *l;
200   gint best_width = -1, best_height = -1;
201   gdouble best_fps = -1, cur_fps;
202   gint best_fps_n = -1, best_fps_d = -1;
203   gboolean ret = TRUE;
204
205   GST_VIDEO_MIXER2_LOCK (mix);
206
207   for (l = mix->sinkpads; l; l = l->next) {
208     GstVideoMixer2Pad *mpad = l->data;
209     gint this_width, this_height;
210
211     if (mpad->fps_n == 0 || mpad->fps_d == 0 ||
212         mpad->width == 0 || mpad->height == 0)
213       continue;
214
215     this_width = mpad->width + MAX (mpad->xpos, 0);
216     this_height = mpad->height + MAX (mpad->ypos, 0);
217
218     if (best_width < this_width)
219       best_width = this_width;
220     if (best_height < this_height)
221       best_height = this_height;
222
223     if (mpad->fps_d == 0)
224       cur_fps = 0.0;
225     else
226       gst_util_fraction_to_double (mpad->fps_n, mpad->fps_d, &cur_fps);
227     if (best_fps < cur_fps) {
228       best_fps = cur_fps;
229       best_fps_n = mpad->fps_n;
230       best_fps_d = mpad->fps_d;
231     }
232   }
233
234   if (best_fps_n <= 0 && best_fps_d <= 0) {
235     best_fps_n = 25;
236     best_fps_d = 1;
237     best_fps = 25.0;
238   }
239
240   if (best_width > 0 && best_height > 0 && best_fps > 0) {
241     GstCaps *caps, *peercaps;
242     GstStructure *s;
243
244     if (mix->fps_n != best_fps_n || mix->fps_d != best_fps_d) {
245       if (mix->segment.last_stop != -1) {
246         mix->ts_offset = mix->segment.last_stop - mix->segment.start;
247         mix->nframes = 0;
248       }
249     }
250
251     caps = gst_video_format_new_caps (mix->format,
252         best_width, best_height, best_fps_n, best_fps_d,
253         mix->par_n, mix->par_d);
254
255     peercaps = gst_pad_peer_get_caps (mix->srcpad);
256     if (peercaps) {
257       GstCaps *tmp;
258
259       s = gst_caps_get_structure (caps, 0);
260       gst_structure_set (s, "width", GST_TYPE_INT_RANGE, 1, G_MAXINT, "height",
261           GST_TYPE_INT_RANGE, 1, G_MAXINT, "framerate", GST_TYPE_FRACTION_RANGE,
262           0, 1, G_MAXINT, 1, NULL);
263
264       tmp = gst_caps_intersect (caps, peercaps);
265       gst_caps_unref (caps);
266       gst_caps_unref (peercaps);
267       caps = tmp;
268       if (gst_caps_is_empty (caps)) {
269         ret = FALSE;
270         GST_VIDEO_MIXER2_UNLOCK (mix);
271         goto done;
272       }
273
274       gst_caps_truncate (caps);
275       s = gst_caps_get_structure (caps, 0);
276       gst_structure_fixate_field_nearest_int (s, "width", best_width);
277       gst_structure_fixate_field_nearest_int (s, "height", best_height);
278       gst_structure_fixate_field_nearest_fraction (s, "framerate", best_fps_n,
279           best_fps_d);
280
281       gst_structure_get_int (s, "width", &best_width);
282       gst_structure_get_int (s, "height", &best_height);
283       gst_structure_get_fraction (s, "fraction", &best_fps_n, &best_fps_d);
284     }
285
286     mix->fps_n = best_fps_n;
287     mix->fps_d = best_fps_d;
288     mix->width = best_width;
289     mix->height = best_height;
290
291     GST_VIDEO_MIXER2_UNLOCK (mix);
292     ret = gst_pad_set_caps (mix->srcpad, caps);
293     gst_caps_unref (caps);
294   } else {
295     GST_VIDEO_MIXER2_UNLOCK (mix);
296   }
297
298 done:
299   return ret;
300 }
301
302
303 static gboolean
304 gst_videomixer2_pad_sink_setcaps (GstPad * pad, GstCaps * caps)
305 {
306   GstVideoMixer2 *mix;
307   GstVideoMixer2Pad *mixpad;
308   GstVideoFormat fmt;
309   gint width, height;
310   gint fps_n = 0, fps_d = 0;
311   gint par_n = 1, par_d = 1;
312   gboolean ret = FALSE;
313   GstStructure *s;
314
315   GST_INFO_OBJECT (pad, "Setting caps %" GST_PTR_FORMAT, caps);
316
317   mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (pad));
318   mixpad = GST_VIDEO_MIXER2_PAD (pad);
319
320   if (!gst_video_format_parse_caps (caps, &fmt, &width, &height) ||
321       !gst_video_parse_caps_pixel_aspect_ratio (caps, &par_n, &par_d)) {
322     GST_ERROR_OBJECT (pad, "Failed to parse caps");
323     goto beach;
324   }
325
326   s = gst_caps_get_structure (caps, 0);
327   if (gst_structure_has_field (s, "framerate")
328       && !gst_video_parse_caps_framerate (caps, &fps_n, &fps_d)) {
329     GST_ERROR_OBJECT (pad, "Failed to parse caps");
330     goto beach;
331   }
332
333   GST_VIDEO_MIXER2_LOCK (mix);
334   if (mix->format != GST_VIDEO_FORMAT_UNKNOWN) {
335     if (mix->format != fmt || mix->par_n != par_n || mix->par_d != par_d) {
336       GST_ERROR_OBJECT (pad, "Caps not compatible with other pads' caps");
337       GST_VIDEO_MIXER2_UNLOCK (mix);
338       goto beach;
339     }
340   }
341
342   mix->format = fmt;
343   mix->par_n = par_n;
344   mix->par_d = par_d;
345   mixpad->fps_n = fps_n;
346   mixpad->fps_d = fps_d;
347   mixpad->width = width;
348   mixpad->height = height;
349
350   GST_VIDEO_MIXER2_UNLOCK (mix);
351
352   ret = gst_videomixer2_update_src_caps (mix);
353
354 beach:
355   gst_object_unref (mix);
356
357   return ret;
358 }
359
360 static GstCaps *
361 gst_videomixer2_pad_sink_getcaps (GstPad * pad)
362 {
363   GstVideoMixer2 *mix;
364   GstVideoMixer2Pad *mixpad;
365   GstCaps *srccaps;
366   GstStructure *s;
367   gint i, n;
368
369   mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (pad));
370   mixpad = GST_VIDEO_MIXER2_PAD (pad);
371
372   srccaps = gst_pad_get_fixed_caps_func (GST_PAD (mix->srcpad));
373   srccaps = gst_caps_make_writable (srccaps);
374
375   n = gst_caps_get_size (srccaps);
376   for (i = 0; i < n; i++) {
377     s = gst_caps_get_structure (srccaps, i);
378     gst_structure_set (s, "width", GST_TYPE_INT_RANGE, 1, G_MAXINT,
379         "height", GST_TYPE_INT_RANGE, 1, G_MAXINT,
380         "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
381     if (!gst_structure_has_field (s, "pixel-aspect-ratio"))
382       gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1,
383           NULL);
384   }
385
386   GST_DEBUG_OBJECT (pad, "Returning %" GST_PTR_FORMAT, srccaps);
387
388   return srccaps;
389 }
390
391 static gboolean
392 gst_videomixer2_pad_sink_acceptcaps (GstPad * pad, GstCaps * caps)
393 {
394   gboolean ret;
395   GstVideoMixer2 *mix;
396   GstCaps *accepted_caps;
397   gint i, n;
398   GstStructure *s;
399
400   mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (pad));
401   GST_DEBUG_OBJECT (pad, "%" GST_PTR_FORMAT, caps);
402
403   accepted_caps = gst_pad_get_fixed_caps_func (GST_PAD (mix->srcpad));
404   accepted_caps = gst_caps_make_writable (accepted_caps);
405   GST_LOG_OBJECT (pad, "src caps %" GST_PTR_FORMAT, accepted_caps);
406
407   n = gst_caps_get_size (accepted_caps);
408   for (i = 0; i < n; i++) {
409     s = gst_caps_get_structure (accepted_caps, i);
410     gst_structure_set (s, "width", GST_TYPE_INT_RANGE, 1, G_MAXINT,
411         "height", GST_TYPE_INT_RANGE, 1, G_MAXINT,
412         "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
413     if (!gst_structure_has_field (s, "pixel-aspect-ratio"))
414       gst_structure_set (s, "pixel-aspect-ratio", GST_TYPE_FRACTION, 1, 1,
415           NULL);
416   }
417
418   ret = gst_caps_can_intersect (caps, accepted_caps);
419   GST_INFO_OBJECT (pad, "%saccepted caps %" GST_PTR_FORMAT, (ret ? "" : "not "),
420       caps);
421   GST_INFO_OBJECT (pad, "acceptable caps are %" GST_PTR_FORMAT, accepted_caps);
422
423   gst_caps_unref (accepted_caps);
424
425   gst_object_unref (mix);
426   return ret;
427 }
428
429 static void
430 gst_videomixer2_pad_get_property (GObject * object, guint prop_id,
431     GValue * value, GParamSpec * pspec)
432 {
433   GstVideoMixer2Pad *pad = GST_VIDEO_MIXER2_PAD (object);
434
435   switch (prop_id) {
436     case PROP_PAD_ZORDER:
437       g_value_set_uint (value, pad->zorder);
438       break;
439     case PROP_PAD_XPOS:
440       g_value_set_int (value, pad->xpos);
441       break;
442     case PROP_PAD_YPOS:
443       g_value_set_int (value, pad->ypos);
444       break;
445     case PROP_PAD_ALPHA:
446       g_value_set_double (value, pad->alpha);
447       break;
448     default:
449       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
450       break;
451   }
452 }
453
454 static int
455 pad_zorder_compare (const GstVideoMixer2Pad * pad1,
456     const GstVideoMixer2Pad * pad2)
457 {
458   return pad1->zorder - pad2->zorder;
459 }
460
461 static void
462 gst_videomixer2_pad_set_property (GObject * object, guint prop_id,
463     const GValue * value, GParamSpec * pspec)
464 {
465   GstVideoMixer2Pad *pad = GST_VIDEO_MIXER2_PAD (object);
466   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (GST_PAD (pad)));
467
468   switch (prop_id) {
469     case PROP_PAD_ZORDER:
470       GST_VIDEO_MIXER2_LOCK (mix);
471       pad->zorder = g_value_get_uint (value);
472
473       mix->sinkpads = g_slist_sort (mix->sinkpads,
474           (GCompareFunc) pad_zorder_compare);
475       GST_VIDEO_MIXER2_UNLOCK (mix);
476       break;
477     case PROP_PAD_XPOS:
478       pad->xpos = g_value_get_int (value);
479       break;
480     case PROP_PAD_YPOS:
481       pad->ypos = g_value_get_int (value);
482       break;
483     case PROP_PAD_ALPHA:
484       pad->alpha = g_value_get_double (value);
485       break;
486     default:
487       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
488       break;
489   }
490
491   gst_object_unref (mix);
492 }
493
494 static void
495 gst_videomixer2_pad_class_init (GstVideoMixer2PadClass * klass)
496 {
497   GObjectClass *gobject_class = (GObjectClass *) klass;
498
499   gobject_class->set_property = gst_videomixer2_pad_set_property;
500   gobject_class->get_property = gst_videomixer2_pad_get_property;
501
502   g_object_class_install_property (gobject_class, PROP_PAD_ZORDER,
503       g_param_spec_uint ("zorder", "Z-Order", "Z Order of the picture",
504           0, 10000, DEFAULT_PAD_ZORDER,
505           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
506   g_object_class_install_property (gobject_class, PROP_PAD_XPOS,
507       g_param_spec_int ("xpos", "X Position", "X Position of the picture",
508           G_MININT, G_MAXINT, DEFAULT_PAD_XPOS,
509           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
510   g_object_class_install_property (gobject_class, PROP_PAD_YPOS,
511       g_param_spec_int ("ypos", "Y Position", "Y Position of the picture",
512           G_MININT, G_MAXINT, DEFAULT_PAD_YPOS,
513           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
514   g_object_class_install_property (gobject_class, PROP_PAD_ALPHA,
515       g_param_spec_double ("alpha", "Alpha", "Alpha of the picture", 0.0, 1.0,
516           DEFAULT_PAD_ALPHA,
517           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
518 }
519
520 static void
521 gst_videomixer2_pad_init (GstVideoMixer2Pad * mixerpad)
522 {
523   /* setup some pad functions */
524   gst_pad_set_setcaps_function (GST_PAD (mixerpad),
525       gst_videomixer2_pad_sink_setcaps);
526   gst_pad_set_acceptcaps_function (GST_PAD (mixerpad),
527       GST_DEBUG_FUNCPTR (gst_videomixer2_pad_sink_acceptcaps));
528   gst_pad_set_getcaps_function (GST_PAD (mixerpad),
529       gst_videomixer2_pad_sink_getcaps);
530
531   mixerpad->zorder = DEFAULT_PAD_ZORDER;
532   mixerpad->xpos = DEFAULT_PAD_XPOS;
533   mixerpad->ypos = DEFAULT_PAD_YPOS;
534   mixerpad->alpha = DEFAULT_PAD_ALPHA;
535 }
536
537 /* GstVideoMixer2 */
538 #define DEFAULT_BACKGROUND VIDEO_MIXER2_BACKGROUND_CHECKER
539 enum
540 {
541   PROP_0,
542   PROP_BACKGROUND
543 };
544
545 #define GST_TYPE_VIDEO_MIXER2_BACKGROUND (gst_videomixer2_background_get_type())
546 static GType
547 gst_videomixer2_background_get_type (void)
548 {
549   static GType video_mixer_background_type = 0;
550
551   static const GEnumValue video_mixer_background[] = {
552     {VIDEO_MIXER2_BACKGROUND_CHECKER, "Checker pattern", "checker"},
553     {VIDEO_MIXER2_BACKGROUND_BLACK, "Black", "black"},
554     {VIDEO_MIXER2_BACKGROUND_WHITE, "White", "white"},
555     {VIDEO_MIXER2_BACKGROUND_TRANSPARENT,
556         "Transparent Background to enable further mixing", "transparent"},
557     {0, NULL, NULL},
558   };
559
560   if (!video_mixer_background_type) {
561     video_mixer_background_type =
562         g_enum_register_static ("GstVideoMixer2Background",
563         video_mixer_background);
564   }
565   return video_mixer_background_type;
566 }
567
568
569 GST_BOILERPLATE_FULL (GstVideoMixer2, gst_videomixer2, GstElement,
570     GST_TYPE_ELEMENT, _do_init);
571
572 static void
573 gst_videomixer2_update_qos (GstVideoMixer2 * mix, gdouble proportion,
574     GstClockTimeDiff diff, GstClockTime timestamp)
575 {
576   GST_DEBUG_OBJECT (mix,
577       "Updating QoS: proportion %lf, diff %s%" GST_TIME_FORMAT ", timestamp %"
578       GST_TIME_FORMAT, proportion, (diff < 0) ? "-" : "",
579       GST_TIME_ARGS (ABS (diff)), GST_TIME_ARGS (timestamp));
580
581   GST_OBJECT_LOCK (mix);
582   mix->proportion = proportion;
583   if (G_LIKELY (timestamp != GST_CLOCK_TIME_NONE)) {
584     if (G_UNLIKELY (diff > 0))
585       mix->earliest_time =
586           timestamp + 2 * diff + gst_util_uint64_scale_int (GST_SECOND,
587           mix->fps_d, mix->fps_n);
588     else
589       mix->earliest_time = timestamp + diff;
590   } else {
591     mix->earliest_time = GST_CLOCK_TIME_NONE;
592   }
593   GST_OBJECT_UNLOCK (mix);
594 }
595
596 static void
597 gst_videomixer2_reset_qos (GstVideoMixer2 * mix)
598 {
599   gst_videomixer2_update_qos (mix, 0.5, 0, GST_CLOCK_TIME_NONE);
600   mix->qos_processed = mix->qos_dropped = 0;
601 }
602
603 static void
604 gst_videomixer2_read_qos (GstVideoMixer2 * mix, gdouble * proportion,
605     GstClockTime * time)
606 {
607   GST_OBJECT_LOCK (mix);
608   *proportion = mix->proportion;
609   *time = mix->earliest_time;
610   GST_OBJECT_UNLOCK (mix);
611 }
612
613 static void
614 gst_videomixer2_reset (GstVideoMixer2 * mix)
615 {
616   GSList *l;
617
618   mix->format = GST_VIDEO_FORMAT_UNKNOWN;
619   mix->width = mix->height = 0;
620   mix->fps_n = mix->fps_d = 0;
621   mix->par_n = mix->par_d = 0;
622   mix->ts_offset = 0;
623   mix->nframes = 0;
624
625   gst_segment_init (&mix->segment, GST_FORMAT_TIME);
626   mix->segment.last_stop = -1;
627
628   gst_videomixer2_reset_qos (mix);
629
630   for (l = mix->sinkpads; l; l = l->next) {
631     GstVideoMixer2Pad *p = l->data;
632     GstVideoMixer2Collect *mixcol = p->mixcol;
633
634     gst_buffer_replace (&mixcol->buffer, NULL);
635     mixcol->start_time = -1;
636     mixcol->end_time = -1;
637
638     p->fps_n = p->fps_d = 0;
639     p->width = p->height = 0;
640   }
641
642   mix->newseg_pending = TRUE;
643   mix->flush_stop_pending = FALSE;
644 }
645
646 /*  1 == OK
647  *  0 == need more data
648  * -1 == EOS
649  * -2 == error
650  */
651 static gint
652 gst_videomixer2_fill_queues (GstVideoMixer2 * mix,
653     GstClockTime output_start_time, GstClockTime output_end_time)
654 {
655   GSList *l;
656   gboolean eos = TRUE;
657   gboolean need_more_data = FALSE;
658
659   for (l = mix->sinkpads; l; l = l->next) {
660     GstVideoMixer2Pad *pad = l->data;
661     GstVideoMixer2Collect *mixcol = pad->mixcol;
662     GstSegment *segment = &pad->mixcol->collect.segment;
663     GstBuffer *buf;
664
665     buf = gst_collect_pads2_peek (mix->collect, &mixcol->collect);
666     if (buf) {
667       GstClockTime start_time, end_time;
668
669       start_time = GST_BUFFER_TIMESTAMP (buf);
670       if (start_time == -1) {
671         gst_buffer_unref (buf);
672         GST_ERROR_OBJECT (pad, "Need timestamped buffers!");
673         return -2;
674       }
675
676       /* FIXME: Make all this work with negative rates */
677
678       if ((mixcol->buffer && start_time < GST_BUFFER_TIMESTAMP (mixcol->buffer))
679           || (mixcol->queued
680               && start_time < GST_BUFFER_TIMESTAMP (mixcol->queued))) {
681         GST_WARNING_OBJECT (pad, "Buffer from the past, dropping");
682         gst_buffer_unref (buf);
683         buf = gst_collect_pads2_pop (mix->collect, &mixcol->collect);
684         gst_buffer_unref (buf);
685         need_more_data = TRUE;
686         continue;
687       }
688
689       if (mixcol->queued) {
690         end_time = start_time - GST_BUFFER_TIMESTAMP (mixcol->queued);
691         start_time = GST_BUFFER_TIMESTAMP (mixcol->queued);
692         gst_buffer_unref (buf);
693         buf = gst_buffer_ref (mixcol->queued);
694       } else {
695         end_time = GST_BUFFER_DURATION (buf);
696
697         if (end_time == -1) {
698           mixcol->queued = buf;
699           need_more_data = TRUE;
700           continue;
701         }
702       }
703
704       g_assert (start_time != -1 && end_time != -1);
705       end_time += start_time;   /* convert from duration to position */
706
707       if (mixcol->end_time != -1 && mixcol->end_time > end_time) {
708         GST_WARNING_OBJECT (pad, "Buffer from the past, dropping");
709         if (buf == mixcol->queued) {
710           gst_buffer_unref (buf);
711           gst_buffer_replace (&mixcol->queued, NULL);
712         } else {
713           gst_buffer_unref (buf);
714           buf = gst_collect_pads2_pop (mix->collect, &mixcol->collect);
715           gst_buffer_unref (buf);
716         }
717
718         need_more_data = TRUE;
719         continue;
720       }
721
722       /* Check if it's inside the segment */
723       if (start_time >= segment->stop || end_time < segment->start) {
724         GST_DEBUG_OBJECT (pad, "Buffer outside the segment");
725
726         if (buf == mixcol->queued) {
727           gst_buffer_unref (buf);
728           gst_buffer_replace (&mixcol->queued, NULL);
729         } else {
730           gst_buffer_unref (buf);
731           buf = gst_collect_pads2_pop (mix->collect, &mixcol->collect);
732           gst_buffer_unref (buf);
733         }
734
735         need_more_data = TRUE;
736         continue;
737       }
738
739       /* Clip to segment and convert to running time */
740       start_time = MAX (start_time, segment->start);
741       if (segment->stop != -1)
742         end_time = MIN (end_time, segment->stop);
743       start_time =
744           gst_segment_to_running_time (segment, GST_FORMAT_TIME, start_time);
745       end_time =
746           gst_segment_to_running_time (segment, GST_FORMAT_TIME, end_time);
747       g_assert (start_time != -1 && end_time != -1);
748
749       /* Convert to the output segment rate */
750       if (mix->segment.abs_rate != 1.0) {
751         start_time *= mix->segment.abs_rate;
752         end_time *= mix->segment.abs_rate;
753       }
754
755       if (end_time >= output_start_time && start_time < output_end_time) {
756         GST_DEBUG_OBJECT (pad,
757             "Taking new buffer with start time %" GST_TIME_FORMAT,
758             GST_TIME_ARGS (start_time));
759         gst_buffer_replace (&mixcol->buffer, buf);
760         mixcol->start_time = start_time;
761         mixcol->end_time = end_time;
762
763         if (buf == mixcol->queued) {
764           gst_buffer_unref (buf);
765           gst_buffer_replace (mixcol->queued, NULL);
766         } else {
767           gst_buffer_unref (buf);
768           buf = gst_collect_pads2_pop (mix->collect, &mixcol->collect);
769           gst_buffer_unref (buf);
770         }
771         eos = FALSE;
772       } else if (start_time >= output_end_time) {
773         GST_DEBUG_OBJECT (pad, "Keeping buffer until %" GST_TIME_FORMAT,
774             GST_TIME_ARGS (start_time));
775         eos = FALSE;
776       } else {
777         GST_DEBUG_OBJECT (pad, "Too old buffer -- dropping");
778         if (buf == mixcol->queued) {
779           gst_buffer_unref (buf);
780           gst_buffer_replace (&mixcol->queued, NULL);
781         } else {
782           gst_buffer_unref (buf);
783           buf = gst_collect_pads2_pop (mix->collect, &mixcol->collect);
784           gst_buffer_unref (buf);
785         }
786
787         need_more_data = TRUE;
788         continue;
789       }
790     } else {
791       if (mixcol->end_time != -1) {
792         if (mixcol->end_time < output_start_time) {
793           gst_buffer_replace (&mixcol->buffer, NULL);
794           mixcol->start_time = mixcol->end_time = -1;
795           if (!GST_COLLECT_PADS2_STATE_IS_SET (mixcol,
796                   GST_COLLECT_PADS2_STATE_EOS))
797             need_more_data = TRUE;
798         } else {
799           eos = FALSE;
800         }
801       }
802     }
803   }
804
805   if (need_more_data)
806     return 0;
807   if (eos)
808     return -1;
809
810   return 1;
811 }
812
813 static GstFlowReturn
814 gst_videomixer2_blend_buffers (GstVideoMixer2 * mix,
815     GstClockTime output_start_time, GstClockTime output_end_time,
816     GstBuffer ** outbuf)
817 {
818   GSList *l;
819   GstFlowReturn ret;
820   guint outsize;
821   BlendFunction composite;
822
823   outsize = gst_video_format_get_size (mix->format, mix->width, mix->height);
824   ret = gst_pad_alloc_buffer_and_set_caps (mix->srcpad, GST_BUFFER_OFFSET_NONE,
825       outsize, GST_PAD_CAPS (mix->srcpad), outbuf);
826   if (ret != GST_FLOW_OK)
827     return ret;
828
829   GST_BUFFER_TIMESTAMP (*outbuf) = output_start_time;
830   GST_BUFFER_DURATION (*outbuf) = output_end_time - output_start_time;
831
832   /* default to blending */
833   composite = mix->blend;
834   switch (mix->background) {
835     case VIDEO_MIXER2_BACKGROUND_CHECKER:
836       mix->fill_checker (GST_BUFFER_DATA (*outbuf), mix->width, mix->height);
837       break;
838     case VIDEO_MIXER2_BACKGROUND_BLACK:
839       mix->fill_color (GST_BUFFER_DATA (*outbuf), mix->width,
840           mix->height, 16, 128, 128);
841       break;
842     case VIDEO_MIXER2_BACKGROUND_WHITE:
843       mix->fill_color (GST_BUFFER_DATA (*outbuf), mix->width,
844           mix->height, 240, 128, 128);
845       break;
846     case VIDEO_MIXER2_BACKGROUND_TRANSPARENT:
847       orc_memset (GST_BUFFER_DATA (*outbuf), 0,
848           gst_video_format_get_row_stride (mix->format, 0,
849               mix->width) * mix->height);
850       /* use overlay to keep background transparent */
851       composite = mix->overlay;
852       break;
853   }
854
855   for (l = mix->sinkpads; l; l = l->next) {
856     GstVideoMixer2Pad *pad = l->data;
857     GstVideoMixer2Collect *mixcol = pad->mixcol;
858
859     if (mixcol->buffer != NULL) {
860       GstClockTime timestamp;
861       gint64 stream_time;
862       GstSegment *seg;
863
864       seg = &mixcol->collect.segment;
865
866       timestamp = GST_BUFFER_TIMESTAMP (mixcol->buffer);
867
868       stream_time =
869           gst_segment_to_stream_time (seg, GST_FORMAT_TIME, timestamp);
870
871       /* sync object properties on stream time */
872       if (GST_CLOCK_TIME_IS_VALID (stream_time))
873         gst_object_sync_values (G_OBJECT (pad), stream_time);
874
875       composite (GST_BUFFER_DATA (mixcol->buffer),
876           pad->xpos, pad->ypos, pad->width, pad->height, pad->alpha,
877           GST_BUFFER_DATA (*outbuf), mix->width, mix->height);
878     }
879   }
880
881   return GST_FLOW_OK;
882 }
883
884 /* Perform qos calculations before processing the next frame. Returns TRUE if
885  * the frame should be processed, FALSE if the frame can be dropped entirely */
886 static gint64
887 gst_videomixer2_do_qos (GstVideoMixer2 * mix, GstClockTime timestamp)
888 {
889   GstClockTime qostime, earliest_time;
890   gdouble proportion;
891   gint64 jitter;
892
893   /* no timestamp, can't do QoS => process frame */
894   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (timestamp))) {
895     GST_LOG_OBJECT (mix, "invalid timestamp, can't do QoS, process frame");
896     return -1;
897   }
898
899   /* get latest QoS observation values */
900   gst_videomixer2_read_qos (mix, &proportion, &earliest_time);
901
902   /* skip qos if we have no observation (yet) => process frame */
903   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (earliest_time))) {
904     GST_LOG_OBJECT (mix, "no observation yet, process frame");
905     return -1;
906   }
907
908   /* qos is done on running time */
909   qostime =
910       gst_segment_to_running_time (&mix->segment, GST_FORMAT_TIME, timestamp);
911
912   /* see how our next timestamp relates to the latest qos timestamp */
913   GST_LOG_OBJECT (mix, "qostime %" GST_TIME_FORMAT ", earliest %"
914       GST_TIME_FORMAT, GST_TIME_ARGS (qostime), GST_TIME_ARGS (earliest_time));
915
916   jitter = GST_CLOCK_DIFF (qostime, earliest_time);
917   if (qostime != GST_CLOCK_TIME_NONE && jitter > 0) {
918     GST_DEBUG_OBJECT (mix, "we are late, drop frame");
919     return jitter;
920   }
921
922   GST_LOG_OBJECT (mix, "process frame");
923   return jitter;
924 }
925
926 static GstFlowReturn
927 gst_videomixer2_collected (GstCollectPads2 * pads, GstVideoMixer2 * mix)
928 {
929   GstFlowReturn ret;
930   GstClockTime output_start_time, output_end_time;
931   GstBuffer *outbuf = NULL;
932   gint res;
933   gint64 jitter;
934
935   /* If we're not negotiated yet... */
936   if (mix->format == GST_VIDEO_FORMAT_UNKNOWN)
937     return GST_FLOW_NOT_NEGOTIATED;
938
939   if (g_atomic_int_compare_and_exchange (&mix->flush_stop_pending, TRUE, FALSE)) {
940     GST_DEBUG_OBJECT (mix, "pending flush stop");
941     gst_pad_push_event (mix->srcpad, gst_event_new_flush_stop ());
942   }
943
944   GST_VIDEO_MIXER2_LOCK (mix);
945
946   if (mix->newseg_pending) {
947     GST_DEBUG_OBJECT (mix, "Sending NEWSEGMENT event");
948     if (!gst_pad_push_event (mix->srcpad, gst_event_new_new_segment_full (FALSE,
949                 mix->segment.rate, mix->segment.applied_rate,
950                 mix->segment.format, mix->segment.start, mix->segment.stop,
951                 mix->segment.time))) {
952       ret = GST_FLOW_ERROR;
953       goto done;
954     }
955     mix->newseg_pending = FALSE;
956   }
957
958   if (mix->segment.last_stop == -1)
959     output_start_time = mix->segment.start;
960   else
961     output_start_time = mix->segment.last_stop;
962
963   if (output_start_time >= mix->segment.stop) {
964     GST_DEBUG_OBJECT (mix, "Segment done");
965     gst_pad_push_event (mix->srcpad, gst_event_new_eos ());
966     ret = GST_FLOW_UNEXPECTED;
967     goto done;
968   }
969
970   output_end_time =
971       mix->ts_offset + gst_util_uint64_scale (mix->nframes + 1,
972       GST_SECOND * mix->fps_d, mix->fps_n);
973   if (mix->segment.stop != -1)
974     output_end_time = MIN (output_end_time, mix->segment.stop);
975
976   res = gst_videomixer2_fill_queues (mix, output_start_time, output_end_time);
977
978   if (res == 0) {
979     GST_DEBUG_OBJECT (mix, "Need more data for decisions");
980     ret = GST_FLOW_OK;
981     goto done;
982   } else if (res == -1) {
983     GST_DEBUG_OBJECT (mix, "All sinkpads are EOS -- forwarding");
984     gst_pad_push_event (mix->srcpad, gst_event_new_eos ());
985     ret = GST_FLOW_UNEXPECTED;
986     goto done;
987   } else if (res == -2) {
988     GST_ERROR_OBJECT (mix, "Error collecting buffers");
989     ret = GST_FLOW_ERROR;
990     goto done;
991   }
992
993   jitter = gst_videomixer2_do_qos (mix, output_start_time);
994   if (jitter <= 0) {
995     ret =
996         gst_videomixer2_blend_buffers (mix, output_start_time,
997         output_end_time, &outbuf);
998     mix->qos_processed++;
999   } else {
1000     GstMessage *msg;
1001
1002     mix->qos_dropped++;
1003
1004     /* TODO: live */
1005     msg =
1006         gst_message_new_qos (GST_OBJECT_CAST (mix), FALSE,
1007         gst_segment_to_running_time (&mix->segment, GST_FORMAT_TIME,
1008             output_start_time), gst_segment_to_stream_time (&mix->segment,
1009             GST_FORMAT_TIME, output_start_time), output_start_time,
1010         output_end_time - output_start_time);
1011     gst_message_set_qos_values (msg, jitter, mix->proportion, 1000000);
1012     gst_message_set_qos_stats (msg, GST_FORMAT_BUFFERS, mix->qos_processed,
1013         mix->qos_dropped);
1014     gst_element_post_message (GST_ELEMENT_CAST (mix), msg);
1015
1016     ret = GST_FLOW_OK;
1017   }
1018
1019   gst_segment_set_last_stop (&mix->segment, GST_FORMAT_TIME, output_end_time);
1020   mix->nframes++;
1021
1022   GST_VIDEO_MIXER2_UNLOCK (mix);
1023   if (outbuf) {
1024     GST_LOG_OBJECT (mix,
1025         "Pushing buffer with ts %" GST_TIME_FORMAT " and duration %"
1026         GST_TIME_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1027         GST_TIME_ARGS (GST_BUFFER_DURATION (outbuf)));
1028     ret = gst_pad_push (mix->srcpad, outbuf);
1029   }
1030   GST_VIDEO_MIXER2_LOCK (mix);
1031
1032 done:
1033   GST_VIDEO_MIXER2_UNLOCK (mix);
1034
1035   return ret;
1036 }
1037
1038 static GstCaps *
1039 gst_videomixer2_src_getcaps (GstPad * pad)
1040 {
1041   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (pad));
1042   GstCaps *caps;
1043   GstStructure *s;
1044   gint n;
1045
1046   if (mix->format != GST_VIDEO_FORMAT_UNKNOWN) {
1047     caps = gst_caps_copy (GST_PAD_CAPS (mix->srcpad));
1048   } else {
1049     caps = gst_caps_copy (gst_pad_get_pad_template_caps (mix->srcpad));
1050   }
1051
1052   n = gst_caps_get_size (caps) - 1;
1053   for (; n >= 0; n--) {
1054     s = gst_caps_get_structure (caps, n);
1055     gst_structure_set (s, "width", GST_TYPE_INT_RANGE, 1, G_MAXINT,
1056         "height", GST_TYPE_INT_RANGE, 1, G_MAXINT, NULL);
1057     if (mix->fps_d != 0) {
1058       gst_structure_set (s,
1059           "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, G_MAXINT, 1, NULL);
1060     }
1061   }
1062
1063   gst_object_unref (mix);
1064
1065   return caps;
1066 }
1067
1068 static gboolean
1069 gst_videomixer2_query_duration (GstVideoMixer2 * mix, GstQuery * query)
1070 {
1071   gint64 max;
1072   gboolean res;
1073   GstFormat format;
1074   GstIterator *it;
1075   gboolean done;
1076
1077   /* parse format */
1078   gst_query_parse_duration (query, &format, NULL);
1079
1080   max = -1;
1081   res = TRUE;
1082   done = FALSE;
1083
1084   /* Take maximum of all durations */
1085   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mix));
1086   while (!done) {
1087     GstIteratorResult ires;
1088     gpointer item;
1089
1090     ires = gst_iterator_next (it, &item);
1091     switch (ires) {
1092       case GST_ITERATOR_DONE:
1093         done = TRUE;
1094         break;
1095       case GST_ITERATOR_OK:
1096       {
1097         GstPad *pad = GST_PAD_CAST (item);
1098         gint64 duration;
1099
1100         /* ask sink peer for duration */
1101         res &= gst_pad_query_peer_duration (pad, &format, &duration);
1102         /* take max from all valid return values */
1103         if (res) {
1104           /* valid unknown length, stop searching */
1105           if (duration == -1) {
1106             max = duration;
1107             done = TRUE;
1108           }
1109           /* else see if bigger than current max */
1110           else if (duration > max)
1111             max = duration;
1112         }
1113         gst_object_unref (pad);
1114         break;
1115       }
1116       case GST_ITERATOR_RESYNC:
1117         max = -1;
1118         res = TRUE;
1119         gst_iterator_resync (it);
1120         break;
1121       default:
1122         res = FALSE;
1123         done = TRUE;
1124         break;
1125     }
1126   }
1127   gst_iterator_free (it);
1128
1129   if (res) {
1130     /* and store the max */
1131     GST_DEBUG_OBJECT (mix, "Total duration in format %s: %"
1132         GST_TIME_FORMAT, gst_format_get_name (format), GST_TIME_ARGS (max));
1133     gst_query_set_duration (query, format, max);
1134   }
1135
1136   return res;
1137 }
1138
1139 static gboolean
1140 gst_videomixer2_query_latency (GstVideoMixer2 * mix, GstQuery * query)
1141 {
1142   GstClockTime min, max;
1143   gboolean live;
1144   gboolean res;
1145   GstIterator *it;
1146   gboolean done;
1147
1148   res = TRUE;
1149   done = FALSE;
1150   live = FALSE;
1151   min = 0;
1152   max = GST_CLOCK_TIME_NONE;
1153
1154   /* Take maximum of all latency values */
1155   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mix));
1156   while (!done) {
1157     GstIteratorResult ires;
1158     gpointer item;
1159
1160     ires = gst_iterator_next (it, &item);
1161     switch (ires) {
1162       case GST_ITERATOR_DONE:
1163         done = TRUE;
1164         break;
1165       case GST_ITERATOR_OK:
1166       {
1167         GstPad *pad = GST_PAD_CAST (item);
1168         GstQuery *peerquery;
1169         GstClockTime min_cur, max_cur;
1170         gboolean live_cur;
1171
1172         peerquery = gst_query_new_latency ();
1173
1174         /* Ask peer for latency */
1175         res &= gst_pad_peer_query (pad, peerquery);
1176
1177         /* take max from all valid return values */
1178         if (res) {
1179           gst_query_parse_latency (peerquery, &live_cur, &min_cur, &max_cur);
1180
1181           if (min_cur > min)
1182             min = min_cur;
1183
1184           if (max_cur != GST_CLOCK_TIME_NONE &&
1185               ((max != GST_CLOCK_TIME_NONE && max_cur > max) ||
1186                   (max == GST_CLOCK_TIME_NONE)))
1187             max = max_cur;
1188
1189           live = live || live_cur;
1190         }
1191
1192         gst_query_unref (peerquery);
1193         gst_object_unref (pad);
1194         break;
1195       }
1196       case GST_ITERATOR_RESYNC:
1197         live = FALSE;
1198         min = 0;
1199         max = GST_CLOCK_TIME_NONE;
1200         res = TRUE;
1201         gst_iterator_resync (it);
1202         break;
1203       default:
1204         res = FALSE;
1205         done = TRUE;
1206         break;
1207     }
1208   }
1209   gst_iterator_free (it);
1210
1211   if (res) {
1212     /* store the results */
1213     GST_DEBUG_OBJECT (mix, "Calculated total latency: live %s, min %"
1214         GST_TIME_FORMAT ", max %" GST_TIME_FORMAT,
1215         (live ? "yes" : "no"), GST_TIME_ARGS (min), GST_TIME_ARGS (max));
1216     gst_query_set_latency (query, live, min, max);
1217   }
1218
1219   return res;
1220 }
1221
1222 static gboolean
1223 gst_videomixer2_src_query (GstPad * pad, GstQuery * query)
1224 {
1225   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (pad));
1226   gboolean res = FALSE;
1227
1228   switch (GST_QUERY_TYPE (query)) {
1229     case GST_QUERY_POSITION:
1230     {
1231       GstFormat format;
1232
1233       gst_query_parse_position (query, &format, NULL);
1234
1235       switch (format) {
1236         case GST_FORMAT_TIME:
1237           gst_query_set_position (query, format,
1238               gst_segment_to_stream_time (&mix->segment, GST_FORMAT_TIME,
1239                   mix->segment.last_stop));
1240           res = TRUE;
1241           break;
1242         default:
1243           break;
1244       }
1245       break;
1246     }
1247     case GST_QUERY_DURATION:
1248       res = gst_videomixer2_query_duration (mix, query);
1249       break;
1250     case GST_QUERY_LATENCY:
1251       res = gst_videomixer2_query_latency (mix, query);
1252       break;
1253     default:
1254       /* FIXME, needs a custom query handler because we have multiple
1255        * sinkpads */
1256       res = FALSE;
1257       gst_query_unref (query);
1258       break;
1259   }
1260
1261   gst_object_unref (mix);
1262   return res;
1263 }
1264
1265 static gboolean
1266 gst_videomixer2_src_event (GstPad * pad, GstEvent * event)
1267 {
1268   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (gst_pad_get_parent (pad));
1269   gboolean result;
1270
1271   switch (GST_EVENT_TYPE (event)) {
1272     case GST_EVENT_QOS:{
1273       GstClockTimeDiff diff;
1274       GstClockTime timestamp;
1275       gdouble proportion;
1276
1277       gst_event_parse_qos (event, &proportion, &diff, &timestamp);
1278
1279       gst_videomixer2_update_qos (mix, proportion, diff, timestamp);
1280
1281       result = gst_videomixer2_push_sink_event (mix, event);
1282       break;
1283     }
1284     case GST_EVENT_SEEK:
1285     {
1286       gdouble rate;
1287       GstFormat fmt;
1288       GstSeekFlags flags;
1289       GstSeekType start_type, stop_type;
1290       gint64 start, stop;
1291       GSList *l;
1292       gdouble abs_rate;
1293
1294       /* parse the seek parameters */
1295       gst_event_parse_seek (event, &rate, &fmt, &flags, &start_type,
1296           &start, &stop_type, &stop);
1297
1298       if (rate <= 0.0) {
1299         GST_ERROR_OBJECT (mix, "Negative rates not supported yet");
1300         result = FALSE;
1301         gst_event_unref (event);
1302         break;
1303       }
1304
1305       GST_DEBUG_OBJECT (mix, "Handling SEEK event");
1306
1307       /* check if we are flushing */
1308       if (flags & GST_SEEK_FLAG_FLUSH) {
1309         /* flushing seek, start flush downstream, the flush will be done
1310          * when all pads received a FLUSH_STOP. */
1311         gst_pad_push_event (mix->srcpad, gst_event_new_flush_start ());
1312
1313         /* make sure we accept nothing anymore and return WRONG_STATE */
1314         gst_collect_pads2_set_flushing (mix->collect, TRUE);
1315       }
1316
1317       /* now wait for the collected to be finished and mark a new
1318        * segment */
1319       GST_COLLECT_PADS2_STREAM_LOCK (mix->collect);
1320
1321       abs_rate = ABS (rate);
1322
1323       GST_VIDEO_MIXER2_LOCK (mix);
1324       for (l = mix->sinkpads; l; l = l->next) {
1325         GstVideoMixer2Pad *p = l->data;
1326
1327         if (flags & GST_SEEK_FLAG_FLUSH) {
1328           gst_buffer_replace (&p->mixcol->buffer, NULL);
1329           p->mixcol->start_time = p->mixcol->end_time = -1;
1330           continue;
1331         }
1332
1333         /* Convert to the output segment rate */
1334         if (mix->segment.abs_rate != abs_rate) {
1335           if (mix->segment.abs_rate != 1.0 && p->mixcol->buffer) {
1336             p->mixcol->start_time /= mix->segment.abs_rate;
1337             p->mixcol->end_time /= mix->segment.abs_rate;
1338           }
1339           if (abs_rate != 1.0 && p->mixcol->buffer) {
1340             p->mixcol->start_time *= abs_rate;
1341             p->mixcol->end_time *= abs_rate;
1342           }
1343         }
1344       }
1345       GST_VIDEO_MIXER2_UNLOCK (mix);
1346
1347       gst_segment_set_seek (&mix->segment, rate, fmt, flags, start_type, start,
1348           stop_type, stop, NULL);
1349       mix->segment.last_stop = -1;
1350       mix->ts_offset = 0;
1351       mix->nframes = 0;
1352       mix->newseg_pending = TRUE;
1353
1354       if (flags & GST_SEEK_FLAG_FLUSH) {
1355         gst_collect_pads2_set_flushing (mix->collect, FALSE);
1356
1357         /* we can't send FLUSH_STOP here since upstream could start pushing data
1358          * after we unlock mix->collect.
1359          * We set flush_stop_pending to TRUE instead and send FLUSH_STOP after
1360          * forwarding the seek upstream or from gst_videomixer_collected,
1361          * whichever happens first.
1362          */
1363         mix->flush_stop_pending = TRUE;
1364       }
1365
1366       GST_COLLECT_PADS2_STREAM_UNLOCK (mix->collect);
1367
1368       gst_videomixer2_reset_qos (mix);
1369
1370       result = gst_videomixer2_push_sink_event (mix, event);
1371
1372       if (g_atomic_int_compare_and_exchange (&mix->flush_stop_pending, TRUE,
1373               FALSE)) {
1374         GST_DEBUG_OBJECT (mix, "pending flush stop");
1375         gst_pad_push_event (mix->srcpad, gst_event_new_flush_stop ());
1376       }
1377
1378       break;
1379     }
1380     case GST_EVENT_NAVIGATION:
1381       /* navigation is rather pointless. */
1382       result = FALSE;
1383       gst_event_unref (event);
1384       break;
1385     default:
1386       /* just forward the rest for now */
1387       result = gst_videomixer2_push_sink_event (mix, event);
1388       break;
1389   }
1390   gst_object_unref (mix);
1391
1392   return result;
1393 }
1394
1395 static gboolean
1396 gst_videomixer2_src_setcaps (GstPad * pad, GstCaps * caps)
1397 {
1398   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (gst_pad_get_parent_element (pad));
1399   gboolean ret = FALSE;
1400   GstVideoFormat fmt;
1401   gint width, height;
1402   gint fps_n, fps_d;
1403   gint par_n, par_d;
1404
1405   GST_INFO_OBJECT (pad, "set src caps: %" GST_PTR_FORMAT, caps);
1406
1407   mix->blend = NULL;
1408   mix->overlay = NULL;
1409   mix->fill_checker = NULL;
1410   mix->fill_color = NULL;
1411
1412   if (!gst_video_format_parse_caps (caps, &fmt, &width, &height) ||
1413       !gst_video_parse_caps_framerate (caps, &fps_n, &fps_d) ||
1414       !gst_video_parse_caps_pixel_aspect_ratio (caps, &par_n, &par_d))
1415     goto done;
1416
1417   GST_VIDEO_MIXER2_LOCK (mix);
1418
1419   if (mix->fps_n != fps_n || mix->fps_d != fps_d) {
1420     if (mix->segment.last_stop != -1) {
1421       mix->ts_offset = mix->segment.last_stop - mix->segment.start;
1422       mix->nframes = 0;
1423     }
1424     gst_videomixer2_reset_qos (mix);
1425   }
1426
1427   mix->format = fmt;
1428   mix->width = width;
1429   mix->height = height;
1430   mix->fps_n = fps_n;
1431   mix->fps_d = fps_d;
1432   mix->par_n = par_n;
1433   mix->par_d = par_d;
1434
1435   switch (mix->format) {
1436     case GST_VIDEO_FORMAT_AYUV:
1437       mix->blend = gst_video_mixer_blend_ayuv;
1438       mix->overlay = gst_video_mixer_overlay_ayuv;
1439       mix->fill_checker = gst_video_mixer_fill_checker_ayuv;
1440       mix->fill_color = gst_video_mixer_fill_color_ayuv;
1441       ret = TRUE;
1442       break;
1443     case GST_VIDEO_FORMAT_ARGB:
1444       mix->blend = gst_video_mixer_blend_argb;
1445       mix->overlay = gst_video_mixer_overlay_argb;
1446       mix->fill_checker = gst_video_mixer_fill_checker_argb;
1447       mix->fill_color = gst_video_mixer_fill_color_argb;
1448       ret = TRUE;
1449       break;
1450     case GST_VIDEO_FORMAT_BGRA:
1451       mix->blend = gst_video_mixer_blend_bgra;
1452       mix->overlay = gst_video_mixer_overlay_bgra;
1453       mix->fill_checker = gst_video_mixer_fill_checker_bgra;
1454       mix->fill_color = gst_video_mixer_fill_color_bgra;
1455       ret = TRUE;
1456       break;
1457     case GST_VIDEO_FORMAT_ABGR:
1458       mix->blend = gst_video_mixer_blend_abgr;
1459       mix->overlay = gst_video_mixer_overlay_abgr;
1460       mix->fill_checker = gst_video_mixer_fill_checker_abgr;
1461       mix->fill_color = gst_video_mixer_fill_color_abgr;
1462       ret = TRUE;
1463       break;
1464     case GST_VIDEO_FORMAT_RGBA:
1465       mix->blend = gst_video_mixer_blend_rgba;
1466       mix->overlay = gst_video_mixer_overlay_rgba;
1467       mix->fill_checker = gst_video_mixer_fill_checker_rgba;
1468       mix->fill_color = gst_video_mixer_fill_color_rgba;
1469       ret = TRUE;
1470       break;
1471     case GST_VIDEO_FORMAT_Y444:
1472       mix->blend = gst_video_mixer_blend_y444;
1473       mix->overlay = mix->blend;
1474       mix->fill_checker = gst_video_mixer_fill_checker_y444;
1475       mix->fill_color = gst_video_mixer_fill_color_y444;
1476       ret = TRUE;
1477       break;
1478     case GST_VIDEO_FORMAT_Y42B:
1479       mix->blend = gst_video_mixer_blend_y42b;
1480       mix->overlay = mix->blend;
1481       mix->fill_checker = gst_video_mixer_fill_checker_y42b;
1482       mix->fill_color = gst_video_mixer_fill_color_y42b;
1483       ret = TRUE;
1484       break;
1485     case GST_VIDEO_FORMAT_YUY2:
1486       mix->blend = gst_video_mixer_blend_yuy2;
1487       mix->overlay = mix->blend;
1488       mix->fill_checker = gst_video_mixer_fill_checker_yuy2;
1489       mix->fill_color = gst_video_mixer_fill_color_yuy2;
1490       ret = TRUE;
1491       break;
1492     case GST_VIDEO_FORMAT_UYVY:
1493       mix->blend = gst_video_mixer_blend_uyvy;
1494       mix->overlay = mix->blend;
1495       mix->fill_checker = gst_video_mixer_fill_checker_uyvy;
1496       mix->fill_color = gst_video_mixer_fill_color_uyvy;
1497       ret = TRUE;
1498       break;
1499     case GST_VIDEO_FORMAT_YVYU:
1500       mix->blend = gst_video_mixer_blend_yvyu;
1501       mix->overlay = mix->blend;
1502       mix->fill_checker = gst_video_mixer_fill_checker_yvyu;
1503       mix->fill_color = gst_video_mixer_fill_color_yvyu;
1504       ret = TRUE;
1505       break;
1506     case GST_VIDEO_FORMAT_I420:
1507       mix->blend = gst_video_mixer_blend_i420;
1508       mix->overlay = mix->blend;
1509       mix->fill_checker = gst_video_mixer_fill_checker_i420;
1510       mix->fill_color = gst_video_mixer_fill_color_i420;
1511       ret = TRUE;
1512       break;
1513     case GST_VIDEO_FORMAT_YV12:
1514       mix->blend = gst_video_mixer_blend_yv12;
1515       mix->overlay = mix->blend;
1516       mix->fill_checker = gst_video_mixer_fill_checker_yv12;
1517       mix->fill_color = gst_video_mixer_fill_color_yv12;
1518       ret = TRUE;
1519       break;
1520     case GST_VIDEO_FORMAT_Y41B:
1521       mix->blend = gst_video_mixer_blend_y41b;
1522       mix->overlay = mix->blend;
1523       mix->fill_checker = gst_video_mixer_fill_checker_y41b;
1524       mix->fill_color = gst_video_mixer_fill_color_y41b;
1525       ret = TRUE;
1526       break;
1527     case GST_VIDEO_FORMAT_RGB:
1528       mix->blend = gst_video_mixer_blend_rgb;
1529       mix->overlay = mix->blend;
1530       mix->fill_checker = gst_video_mixer_fill_checker_rgb;
1531       mix->fill_color = gst_video_mixer_fill_color_rgb;
1532       ret = TRUE;
1533       break;
1534     case GST_VIDEO_FORMAT_BGR:
1535       mix->blend = gst_video_mixer_blend_bgr;
1536       mix->overlay = mix->blend;
1537       mix->fill_checker = gst_video_mixer_fill_checker_bgr;
1538       mix->fill_color = gst_video_mixer_fill_color_bgr;
1539       ret = TRUE;
1540       break;
1541     case GST_VIDEO_FORMAT_xRGB:
1542       mix->blend = gst_video_mixer_blend_xrgb;
1543       mix->overlay = mix->blend;
1544       mix->fill_checker = gst_video_mixer_fill_checker_xrgb;
1545       mix->fill_color = gst_video_mixer_fill_color_xrgb;
1546       ret = TRUE;
1547       break;
1548     case GST_VIDEO_FORMAT_xBGR:
1549       mix->blend = gst_video_mixer_blend_xbgr;
1550       mix->overlay = mix->blend;
1551       mix->fill_checker = gst_video_mixer_fill_checker_xbgr;
1552       mix->fill_color = gst_video_mixer_fill_color_xbgr;
1553       ret = TRUE;
1554       break;
1555     case GST_VIDEO_FORMAT_RGBx:
1556       mix->blend = gst_video_mixer_blend_rgbx;
1557       mix->overlay = mix->blend;
1558       mix->fill_checker = gst_video_mixer_fill_checker_rgbx;
1559       mix->fill_color = gst_video_mixer_fill_color_rgbx;
1560       ret = TRUE;
1561       break;
1562     case GST_VIDEO_FORMAT_BGRx:
1563       mix->blend = gst_video_mixer_blend_bgrx;
1564       mix->overlay = mix->blend;
1565       mix->fill_checker = gst_video_mixer_fill_checker_bgrx;
1566       mix->fill_color = gst_video_mixer_fill_color_bgrx;
1567       ret = TRUE;
1568       break;
1569     default:
1570       break;
1571   }
1572   GST_VIDEO_MIXER2_UNLOCK (mix);
1573
1574 done:
1575   gst_object_unref (mix);
1576
1577   return ret;
1578 }
1579
1580 static GstFlowReturn
1581 gst_videomixer2_sink_prepare_buffer (GstCollectPads2 * pads,
1582     GstCollectData2 * data, GstBuffer * buf, GstVideoMixer2 * mix)
1583 {
1584   GstVideoMixer2Pad *pad = GST_VIDEO_MIXER2_PAD (data->pad);
1585   GstVideoMixer2Collect *mixcol = pad->mixcol;
1586   GstClockTime start_time, end_time;
1587   gint64 last_stop;
1588
1589   start_time = GST_BUFFER_TIMESTAMP (buf);
1590   if (start_time == -1) {
1591     GST_ERROR_OBJECT (pad, "Timestamped buffers required!");
1592     return GST_FLOW_ERROR;
1593   }
1594
1595   end_time = GST_BUFFER_DURATION (buf);
1596   if (end_time == -1)
1597     end_time = gst_util_uint64_scale_int (GST_SECOND, pad->fps_d, pad->fps_n);
1598   if (end_time == -1)
1599     return GST_FLOW_OK;
1600
1601   start_time = MAX (start_time, mixcol->collect.segment.start);
1602   start_time =
1603       gst_segment_to_running_time (&mixcol->collect.segment,
1604       GST_FORMAT_TIME, start_time);
1605
1606   end_time += GST_BUFFER_TIMESTAMP (buf);
1607   if (mixcol->collect.segment.stop != -1)
1608     end_time = MIN (end_time, mixcol->collect.segment.stop);
1609   end_time =
1610       gst_segment_to_running_time (&mixcol->collect.segment,
1611       GST_FORMAT_TIME, end_time);
1612
1613   /* Convert to the output segment rate */
1614   if (mix->segment.abs_rate != 1.0) {
1615     start_time *= mix->segment.abs_rate;
1616     end_time *= mix->segment.abs_rate;
1617   }
1618
1619   last_stop = mix->segment.last_stop;
1620   if (mix->segment.last_stop == -1)
1621     last_stop = mix->segment.start;
1622
1623   if (mixcol->buffer != NULL && end_time < mixcol->end_time) {
1624     return GST_COLLECT_PADS2_FLOW_DROP;
1625   }
1626
1627   return GST_FLOW_OK;
1628 }
1629
1630 static gboolean
1631 gst_videomixer2_sink_event (GstCollectPads2 * pads, GstCollectData2 * cdata,
1632     GstEvent * event, GstVideoMixer2 * mix)
1633 {
1634   GstVideoMixer2Pad *pad = GST_VIDEO_MIXER2_PAD (cdata->pad);
1635   gboolean ret = TRUE;
1636
1637   GST_DEBUG_OBJECT (pad, "Got %s event on pad %s:%s",
1638       GST_EVENT_TYPE_NAME (event), GST_DEBUG_PAD_NAME (pad));
1639
1640   /* return FALSE => event will be forwarded */
1641   switch (GST_EVENT_TYPE (event)) {
1642     case GST_EVENT_NEWSEGMENT:{
1643       GstFormat fmt;
1644       gst_event_parse_new_segment (event, NULL, NULL, &fmt, NULL, NULL, NULL);
1645
1646       g_assert (fmt == GST_FORMAT_TIME);
1647       /* eat NEWSEGMENT events, collectpads2 unrefs the event */
1648       ret = FALSE;
1649       break;
1650     }
1651     case GST_EVENT_FLUSH_STOP:
1652       mix->newseg_pending = TRUE;
1653       mix->flush_stop_pending = FALSE;
1654       gst_videomixer2_reset_qos (mix);
1655       gst_buffer_replace (&pad->mixcol->buffer, NULL);
1656       pad->mixcol->start_time = -1;
1657       pad->mixcol->end_time = -1;
1658
1659       gst_segment_init (&mix->segment, GST_FORMAT_TIME);
1660       mix->segment.last_stop = -1;
1661       mix->ts_offset = 0;
1662       mix->nframes = 0;
1663
1664       gst_pad_push_event (mix->srcpad, event);
1665       break;
1666     default:
1667       gst_pad_push_event (mix->srcpad, event);
1668       break;
1669   }
1670
1671   return ret;
1672 }
1673
1674 static gboolean
1675 forward_event_func (GstPad * pad, GValue * ret, GstEvent * event)
1676 {
1677   gst_event_ref (event);
1678   GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
1679   if (!gst_pad_push_event (pad, event)) {
1680     g_value_set_boolean (ret, FALSE);
1681     GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
1682         event, GST_EVENT_TYPE_NAME (event));
1683   } else {
1684     GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
1685         event, GST_EVENT_TYPE_NAME (event));
1686   }
1687   gst_object_unref (pad);
1688   return TRUE;
1689 }
1690
1691 static gboolean
1692 gst_videomixer2_push_sink_event (GstVideoMixer2 * mix, GstEvent * event)
1693 {
1694   GstIterator *it;
1695   GValue vret = { 0 };
1696
1697   GST_LOG_OBJECT (mix, "Forwarding event %p (%s)", event,
1698       GST_EVENT_TYPE_NAME (event));
1699
1700   g_value_init (&vret, G_TYPE_BOOLEAN);
1701   g_value_set_boolean (&vret, TRUE);
1702   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mix));
1703   gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func, &vret,
1704       event);
1705   gst_iterator_free (it);
1706   gst_event_unref (event);
1707
1708   return g_value_get_boolean (&vret);
1709 }
1710
1711 /* GstElement vmethods */
1712 static GstStateChangeReturn
1713 gst_videomixer2_change_state (GstElement * element, GstStateChange transition)
1714 {
1715   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (element);
1716   GstStateChangeReturn ret;
1717
1718   switch (transition) {
1719     case GST_STATE_CHANGE_READY_TO_PAUSED:
1720       GST_LOG_OBJECT (mix, "starting collectpads");
1721       gst_collect_pads2_start (mix->collect);
1722       break;
1723     case GST_STATE_CHANGE_PAUSED_TO_READY:
1724       GST_LOG_OBJECT (mix, "stopping collectpads");
1725       gst_collect_pads2_stop (mix->collect);
1726       break;
1727     default:
1728       break;
1729   }
1730
1731   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1732
1733   switch (transition) {
1734     case GST_STATE_CHANGE_PAUSED_TO_READY:
1735       gst_videomixer2_reset (mix);
1736       break;
1737     default:
1738       break;
1739   }
1740
1741   return ret;
1742 }
1743
1744 static GstPad *
1745 gst_videomixer2_request_new_pad (GstElement * element,
1746     GstPadTemplate * templ, const gchar * req_name)
1747 {
1748   GstVideoMixer2 *mix;
1749   GstVideoMixer2Pad *mixpad;
1750   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
1751
1752   mix = GST_VIDEO_MIXER2 (element);
1753
1754   if (templ == gst_element_class_get_pad_template (klass, "sink_%d")) {
1755     gint serial = 0;
1756     gchar *name = NULL;
1757     GstVideoMixer2Collect *mixcol = NULL;
1758
1759     GST_VIDEO_MIXER2_LOCK (mix);
1760     if (req_name == NULL || strlen (req_name) < 6
1761         || !g_str_has_prefix (req_name, "sink_")) {
1762       /* no name given when requesting the pad, use next available int */
1763       serial = mix->next_sinkpad++;
1764     } else {
1765       /* parse serial number from requested padname */
1766       serial = g_ascii_strtoull (&req_name[5], NULL, 10);
1767       if (serial >= mix->next_sinkpad)
1768         mix->next_sinkpad = serial + 1;
1769     }
1770     /* create new pad with the name */
1771     name = g_strdup_printf ("sink_%d", serial);
1772     mixpad = g_object_new (GST_TYPE_VIDEO_MIXER2_PAD, "name", name, "direction",
1773         templ->direction, "template", templ, NULL);
1774     g_free (name);
1775
1776     mixpad->zorder = mix->numpads;
1777     mixpad->xpos = DEFAULT_PAD_XPOS;
1778     mixpad->ypos = DEFAULT_PAD_YPOS;
1779     mixpad->alpha = DEFAULT_PAD_ALPHA;
1780
1781     mixcol = (GstVideoMixer2Collect *)
1782         gst_collect_pads2_add_pad_full (mix->collect, GST_PAD (mixpad),
1783         sizeof (GstVideoMixer2Collect),
1784         (GstCollectData2DestroyNotify) gst_videomixer2_collect_free, TRUE);
1785
1786     /* Keep track of each other */
1787     mixcol->mixpad = mixpad;
1788     mixpad->mixcol = mixcol;
1789
1790     mixcol->start_time = -1;
1791     mixcol->end_time = -1;
1792
1793     /* Keep an internal list of mixpads for zordering */
1794     mix->sinkpads = g_slist_append (mix->sinkpads, mixpad);
1795     mix->numpads++;
1796     GST_VIDEO_MIXER2_UNLOCK (mix);
1797   } else {
1798     return NULL;
1799   }
1800
1801   GST_DEBUG_OBJECT (element, "Adding pad %s", GST_PAD_NAME (mixpad));
1802
1803   /* add the pad to the element */
1804   gst_element_add_pad (element, GST_PAD (mixpad));
1805   gst_child_proxy_child_added (GST_OBJECT (mix), GST_OBJECT (mixpad));
1806
1807   return GST_PAD (mixpad);
1808 }
1809
1810 static void
1811 gst_videomixer2_release_pad (GstElement * element, GstPad * pad)
1812 {
1813   GstVideoMixer2 *mix = NULL;
1814   GstVideoMixer2Pad *mixpad;
1815   gboolean update_caps;
1816
1817   mix = GST_VIDEO_MIXER2 (element);
1818
1819   GST_VIDEO_MIXER2_LOCK (mix);
1820   if (G_UNLIKELY (g_slist_find (mix->sinkpads, pad) == NULL)) {
1821     g_warning ("Unknown pad %s", GST_PAD_NAME (pad));
1822     goto error;
1823   }
1824
1825   mixpad = GST_VIDEO_MIXER2_PAD (pad);
1826
1827   mix->sinkpads = g_slist_remove (mix->sinkpads, pad);
1828   gst_child_proxy_child_removed (GST_OBJECT (mix), GST_OBJECT (mixpad));
1829   mix->numpads--;
1830
1831   update_caps = mix->format != GST_VIDEO_FORMAT_UNKNOWN;
1832   GST_VIDEO_MIXER2_UNLOCK (mix);
1833
1834   gst_collect_pads2_remove_pad (mix->collect, pad);
1835
1836   if (update_caps)
1837     gst_videomixer2_update_src_caps (mix);
1838
1839   gst_element_remove_pad (element, pad);
1840   return;
1841 error:
1842   GST_VIDEO_MIXER2_UNLOCK (mix);
1843 }
1844
1845 /* GObject vmethods */
1846 static void
1847 gst_videomixer2_finalize (GObject * o)
1848 {
1849   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (o);
1850
1851   gst_object_unref (mix->collect);
1852   g_mutex_free (mix->lock);
1853
1854   G_OBJECT_CLASS (parent_class)->finalize (o);
1855 }
1856
1857 static void
1858 gst_videomixer2_get_property (GObject * object,
1859     guint prop_id, GValue * value, GParamSpec * pspec)
1860 {
1861   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (object);
1862
1863   switch (prop_id) {
1864     case PROP_BACKGROUND:
1865       g_value_set_enum (value, mix->background);
1866       break;
1867     default:
1868       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1869       break;
1870   }
1871 }
1872
1873 static void
1874 gst_videomixer2_set_property (GObject * object,
1875     guint prop_id, const GValue * value, GParamSpec * pspec)
1876 {
1877   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (object);
1878
1879   switch (prop_id) {
1880     case PROP_BACKGROUND:
1881       mix->background = g_value_get_enum (value);
1882       break;
1883     default:
1884       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1885       break;
1886   }
1887 }
1888
1889 /* GstChildProxy implementation */
1890 static GstObject *
1891 gst_videomixer2_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
1892     guint index)
1893 {
1894   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (child_proxy);
1895   GstObject *obj;
1896
1897   GST_VIDEO_MIXER2_LOCK (mix);
1898   if ((obj = g_slist_nth_data (mix->sinkpads, index)))
1899     gst_object_ref (obj);
1900   GST_VIDEO_MIXER2_UNLOCK (mix);
1901   return obj;
1902 }
1903
1904 static guint
1905 gst_videomixer2_child_proxy_get_children_count (GstChildProxy * child_proxy)
1906 {
1907   guint count = 0;
1908   GstVideoMixer2 *mix = GST_VIDEO_MIXER2 (child_proxy);
1909
1910   GST_VIDEO_MIXER2_LOCK (mix);
1911   count = mix->numpads;
1912   GST_VIDEO_MIXER2_UNLOCK (mix);
1913   GST_INFO_OBJECT (mix, "Children Count: %d", count);
1914   return count;
1915 }
1916
1917 static void
1918 gst_videomixer2_child_proxy_init (gpointer g_iface, gpointer iface_data)
1919 {
1920   GstChildProxyInterface *iface = g_iface;
1921
1922   GST_INFO ("intializing child proxy interface");
1923   iface->get_child_by_index = gst_videomixer2_child_proxy_get_child_by_index;
1924   iface->get_children_count = gst_videomixer2_child_proxy_get_children_count;
1925 }
1926
1927 /* GObject boilerplate */
1928 static void
1929 gst_videomixer2_base_init (gpointer g_class)
1930 {
1931   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
1932
1933   gst_element_class_add_pad_template (element_class,
1934       gst_static_pad_template_get (&src_factory));
1935   gst_element_class_add_pad_template (element_class,
1936       gst_static_pad_template_get (&sink_factory));
1937
1938   gst_element_class_set_details_simple (element_class, "Video mixer 2",
1939       "Filter/Editor/Video",
1940       "Mix multiple video streams", "Wim Taymans <wim@fluendo.com>, "
1941       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
1942 }
1943
1944 static void
1945 gst_videomixer2_class_init (GstVideoMixer2Class * klass)
1946 {
1947   GObjectClass *gobject_class = (GObjectClass *) klass;
1948   GstElementClass *gstelement_class = (GstElementClass *) klass;
1949
1950   gobject_class->finalize = gst_videomixer2_finalize;
1951
1952   gobject_class->get_property = gst_videomixer2_get_property;
1953   gobject_class->set_property = gst_videomixer2_set_property;
1954
1955   g_object_class_install_property (gobject_class, PROP_BACKGROUND,
1956       g_param_spec_enum ("background", "Background", "Background type",
1957           GST_TYPE_VIDEO_MIXER2_BACKGROUND,
1958           DEFAULT_BACKGROUND, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1959
1960   gstelement_class->request_new_pad =
1961       GST_DEBUG_FUNCPTR (gst_videomixer2_request_new_pad);
1962   gstelement_class->release_pad =
1963       GST_DEBUG_FUNCPTR (gst_videomixer2_release_pad);
1964   gstelement_class->change_state =
1965       GST_DEBUG_FUNCPTR (gst_videomixer2_change_state);
1966
1967   /* Register the pad class */
1968   g_type_class_ref (GST_TYPE_VIDEO_MIXER2_PAD);
1969 }
1970
1971 static void
1972 gst_videomixer2_init (GstVideoMixer2 * mix, GstVideoMixer2Class * g_class)
1973 {
1974   GstElementClass *klass = GST_ELEMENT_GET_CLASS (mix);
1975
1976   mix->srcpad =
1977       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
1978           "src"), "src");
1979   gst_pad_set_getcaps_function (GST_PAD (mix->srcpad),
1980       GST_DEBUG_FUNCPTR (gst_videomixer2_src_getcaps));
1981   gst_pad_set_setcaps_function (GST_PAD (mix->srcpad),
1982       GST_DEBUG_FUNCPTR (gst_videomixer2_src_setcaps));
1983   gst_pad_set_query_function (GST_PAD (mix->srcpad),
1984       GST_DEBUG_FUNCPTR (gst_videomixer2_src_query));
1985   gst_pad_set_event_function (GST_PAD (mix->srcpad),
1986       GST_DEBUG_FUNCPTR (gst_videomixer2_src_event));
1987   gst_element_add_pad (GST_ELEMENT (mix), mix->srcpad);
1988
1989   mix->collect = gst_collect_pads2_new ();
1990   mix->background = DEFAULT_BACKGROUND;
1991
1992   gst_collect_pads2_set_function (mix->collect,
1993       (GstCollectPads2Function) GST_DEBUG_FUNCPTR (gst_videomixer2_collected),
1994       mix);
1995   gst_collect_pads2_set_event_function (mix->collect,
1996       (GstCollectPads2EventFunction) gst_videomixer2_sink_event, mix);
1997   gst_collect_pads2_set_prepare_buffer_function (mix->collect,
1998       (GstCollectPads2BufferFunction) gst_videomixer2_sink_prepare_buffer, mix);
1999
2000   mix->lock = g_mutex_new ();
2001   /* initialize variables */
2002   gst_videomixer2_reset (mix);
2003 }
2004
2005 /* Element registration */
2006 gboolean
2007 gst_videomixer2_register (GstPlugin * plugin)
2008 {
2009   GST_DEBUG_CATEGORY_INIT (gst_videomixer2_debug, "videomixer2", 0,
2010       "video mixer 2");
2011
2012   return gst_element_register (plugin, "videomixer2", GST_RANK_SECONDARY,
2013       GST_TYPE_VIDEO_MIXER2);
2014 }