docs: Quieten a couple more docs warnings
[platform/upstream/gst-plugins-good.git] / gst / videomixer / videomixer.c
1 /* Generic video mixer plugin
2  * Copyright (C) 2004 Wim Taymans <wim@fluendo.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-videomixer
22  *
23  * Videomixer can accept AYUV and BGRA video streams. For each of the requested
24  * sink pads it will compare the incoming geometry and framerate to define the
25  * output parameters. Indeed output video frames will have the geometry of the
26  * biggest incoming video stream and the framerate of the fastest incoming one.
27  *
28  * All sink pads must be either AYUV or BGRA, but a mixture of them is not 
29  * supported. The src pad will have the same colorspace as the sinks. 
30  * No colorspace conversion is done. 
31  * 
32  *
33  * Individual parameters for each input stream can be configured on the
34  * #GstVideoMixerPad.
35  *
36  * <refsect2>
37  * <title>Sample pipelines</title>
38  * |[
39  * gst-launch videotestsrc pattern=1 ! video/x-raw-yuv, framerate=\(fraction\)10/1, width=100, height=100 ! videobox border-alpha=0 alpha=0.5 top=-70 bottom=-70 right=-220 ! videomixer name=mix ! ffmpegcolorspace ! xvimagesink videotestsrc ! video/x-raw-yuv, framerate=\(fraction\)5/1, width=320, height=240 ! alpha alpha=0.7 ! mix.
40  * ]| A pipeline to demonstrate videomixer used together with videobox.
41  * This should show a 320x240 pixels video test source with some transparency
42  * showing the background checker pattern. Another video test source with just
43  * the snow pattern of 100x100 pixels is overlayed on top of the first one on
44  * the left vertically centered with a small transparency showing the first
45  * video test source behind and the checker pattern under it. Note that the
46  * framerate of the output video is 10 frames per second.
47  * |[
48  * gst-launch videotestsrc pattern=1 ! video/x-raw-rgb, framerate=\(fraction\)10/1, width=100, height=100 ! videomixer name=mix ! ffmpegcolorspace ! ximagesink videotestsrc ! video/x-raw-rgb, framerate=\(fraction\)5/1, width=320, height=240 ! mix.
49  * ]| A pipeline to demostrate bgra mixing. (This does not demonstrate alpha blending). 
50  * |[
51  * gst-launch   videotestsrc pattern=1 ! video/x-raw-yuv,format =\(fourcc\)I420, framerate=\(fraction\)10/1, width=100, height=100 ! videomixer name=mix ! ffmpegcolorspace ! ximagesink videotestsrc ! video/x-raw-yuv,format=\(fourcc\)I420, framerate=\(fraction\)5/1, width=320, height=240 ! mix.
52  * ]| A pipeline to test I420
53  * </refsect2>
54  */
55
56 #ifdef HAVE_CONFIG_H
57 #include "config.h"
58 #endif
59
60 #include <gst/gst.h>
61 #include <gst/base/gstcollectpads.h>
62 #include <gst/controller/gstcontroller.h>
63 #include <gst/video/video.h>
64
65 #ifdef HAVE_STDLIB_H
66 #include <stdlib.h>
67 #endif
68 #ifdef HAVE_STRING_H
69 #include <string.h>
70 #endif
71
72 #include "videomixer.h"
73
74 GST_DEBUG_CATEGORY_STATIC (gst_videomixer_debug);
75 #define GST_CAT_DEFAULT gst_videomixer_debug
76
77 #define GST_VIDEO_MIXER_GET_STATE_LOCK(mix) \
78   (GST_VIDEO_MIXER(mix)->state_lock)
79 #define GST_VIDEO_MIXER_STATE_LOCK(mix) \
80   (g_mutex_lock(GST_VIDEO_MIXER_GET_STATE_LOCK (mix)))
81 #define GST_VIDEO_MIXER_STATE_UNLOCK(mix) \
82   (g_mutex_unlock(GST_VIDEO_MIXER_GET_STATE_LOCK (mix)))
83
84 static GType gst_videomixer_get_type (void);
85
86
87 static void gst_videomixer_pad_class_init (GstVideoMixerPadClass * klass);
88 static void gst_videomixer_pad_init (GstVideoMixerPad * mixerpad);
89
90 static void gst_videomixer_pad_get_property (GObject * object, guint prop_id,
91     GValue * value, GParamSpec * pspec);
92 static void gst_videomixer_pad_set_property (GObject * object, guint prop_id,
93     const GValue * value, GParamSpec * pspec);
94
95 static gboolean gst_videomixer_src_event (GstPad * pad, GstEvent * event);
96 static gboolean gst_videomixer_sink_event (GstPad * pad, GstEvent * event);
97
98 static void gst_videomixer_sort_pads (GstVideoMixer * mix);
99
100 /*AYUV function definitions see file: blend_ayuv*/
101 void gst_videomixer_blend_ayuv_ayuv (guint8 * src, gint xpos, gint ypos,
102     gint src_width, gint src_height, gdouble src_alpha,
103     guint8 * dest, gint dest_width, gint dest_height);
104 void gst_videomixer_fill_ayuv_checker (guint8 * dest, gint width, gint height);
105 void gst_videomixer_fill_ayuv_color (guint8 * dest, gint width, gint height,
106     gint colY, gint colU, gint colV);
107 size_t gst_videomixer_calculate_frame_size_ayuv (gint width, gint height);
108 /*BGRA function definitions see file: blend_ayuv*/
109 void gst_videomixer_blend_bgra_bgra (guint8 * src, gint xpos, gint ypos,
110     gint src_width, gint src_height, gdouble src_alpha,
111     guint8 * dest, gint dest_width, gint dest_height);
112 void gst_videomixer_fill_bgra_checker (guint8 * dest, gint width, gint height);
113 void gst_videomixer_fill_bgra_color (guint8 * dest, gint width, gint height,
114     gint colY, gint colU, gint colV);
115 size_t gst_videomixer_calculate_frame_size_bgra (gint width, gint height);
116 /*I420 function definitions see file: blend_i420.c*/
117 void gst_videomixer_blend_i420_i420 (guint8 * src, gint xpos, gint ypos,
118     gint src_width, gint src_height, gdouble src_alpha,
119     guint8 * dest, gint dest_width, gint dest_heighty);
120 void gst_videomixer_fill_i420_checker (guint8 * dest, gint width, gint height);
121 void gst_videomixer_fill_i420_color (guint8 * dest, gint width, gint height,
122     gint colY, gint colU, gint colV);
123 size_t gst_videomixer_calculate_frame_size_i420 (gint width, gint height);
124
125 #define DEFAULT_PAD_ZORDER 0
126 #define DEFAULT_PAD_XPOS   0
127 #define DEFAULT_PAD_YPOS   0
128 #define DEFAULT_PAD_ALPHA  1.0
129 enum
130 {
131   ARG_PAD_0,
132   ARG_PAD_ZORDER,
133   ARG_PAD_XPOS,
134   ARG_PAD_YPOS,
135   ARG_PAD_ALPHA
136 };
137
138 static GType
139 gst_videomixer_pad_get_type (void)
140 {
141   static GType videomixer_pad_type = 0;
142
143   if (!videomixer_pad_type) {
144     static const GTypeInfo videomixer_pad_info = {
145       sizeof (GstVideoMixerPadClass),
146       NULL,
147       NULL,
148       (GClassInitFunc) gst_videomixer_pad_class_init,
149       NULL,
150       NULL,
151       sizeof (GstVideoMixerPad),
152       0,
153       (GInstanceInitFunc) gst_videomixer_pad_init,
154     };
155
156     videomixer_pad_type = g_type_register_static (GST_TYPE_PAD,
157         "GstVideoMixerPad", &videomixer_pad_info, 0);
158   }
159   return videomixer_pad_type;
160 }
161
162 static void
163 gst_videomixer_pad_class_init (GstVideoMixerPadClass * klass)
164 {
165   GObjectClass *gobject_class;
166
167   gobject_class = (GObjectClass *) klass;
168
169   gobject_class->set_property =
170       GST_DEBUG_FUNCPTR (gst_videomixer_pad_set_property);
171   gobject_class->get_property =
172       GST_DEBUG_FUNCPTR (gst_videomixer_pad_get_property);
173
174   g_object_class_install_property (gobject_class, ARG_PAD_ZORDER,
175       g_param_spec_uint ("zorder", "Z-Order", "Z Order of the picture",
176           0, 10000, DEFAULT_PAD_ZORDER,
177           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
178   g_object_class_install_property (gobject_class, ARG_PAD_XPOS,
179       g_param_spec_int ("xpos", "X Position", "X Position of the picture",
180           G_MININT, G_MAXINT, DEFAULT_PAD_XPOS,
181           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
182   g_object_class_install_property (gobject_class, ARG_PAD_YPOS,
183       g_param_spec_int ("ypos", "Y Position", "Y Position of the picture",
184           G_MININT, G_MAXINT, DEFAULT_PAD_YPOS,
185           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
186   g_object_class_install_property (gobject_class, ARG_PAD_ALPHA,
187       g_param_spec_double ("alpha", "Alpha", "Alpha of the picture", 0.0, 1.0,
188           DEFAULT_PAD_ALPHA, G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE));
189 }
190
191 static void
192 gst_videomixer_pad_get_property (GObject * object, guint prop_id,
193     GValue * value, GParamSpec * pspec)
194 {
195   GstVideoMixerPad *pad = GST_VIDEO_MIXER_PAD (object);
196
197   switch (prop_id) {
198     case ARG_PAD_ZORDER:
199       g_value_set_uint (value, pad->zorder);
200       break;
201     case ARG_PAD_XPOS:
202       g_value_set_int (value, pad->xpos);
203       break;
204     case ARG_PAD_YPOS:
205       g_value_set_int (value, pad->ypos);
206       break;
207     case ARG_PAD_ALPHA:
208       g_value_set_double (value, pad->alpha);
209       break;
210     default:
211       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
212       break;
213   }
214 }
215
216 static void
217 gst_videomixer_pad_set_property (GObject * object, guint prop_id,
218     const GValue * value, GParamSpec * pspec)
219 {
220   GstVideoMixerPad *pad;
221   GstVideoMixer *mix;
222
223   pad = GST_VIDEO_MIXER_PAD (object);
224   mix = GST_VIDEO_MIXER (gst_pad_get_parent (GST_PAD (pad)));
225
226   switch (prop_id) {
227     case ARG_PAD_ZORDER:
228       GST_VIDEO_MIXER_STATE_LOCK (mix);
229       pad->zorder = g_value_get_uint (value);
230       gst_videomixer_sort_pads (mix);
231       GST_VIDEO_MIXER_STATE_UNLOCK (mix);
232       break;
233     case ARG_PAD_XPOS:
234       pad->xpos = g_value_get_int (value);
235       break;
236     case ARG_PAD_YPOS:
237       pad->ypos = g_value_get_int (value);
238       break;
239     case ARG_PAD_ALPHA:
240       pad->alpha = g_value_get_double (value);
241       break;
242     default:
243       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
244       break;
245   }
246
247   gst_object_unref (mix);
248 }
249
250 static void
251 gst_videomixer_set_master_geometry (GstVideoMixer * mix)
252 {
253   GSList *walk;
254   gint width = 0, height = 0, fps_n = 0, fps_d = 0;
255   GstVideoMixerPad *master = NULL;
256
257   walk = mix->sinkpads;
258   while (walk) {
259     GstVideoMixerPad *mixpad = GST_VIDEO_MIXER_PAD (walk->data);
260
261     walk = g_slist_next (walk);
262
263     /* Biggest input geometry will be our output geometry */
264     width = MAX (width, mixpad->in_width);
265     height = MAX (height, mixpad->in_height);
266
267     /* If mix framerate < mixpad framerate, using fractions */
268     GST_DEBUG_OBJECT (mix, "comparing framerate %d/%d to mixpad's %d/%d",
269         fps_n, fps_d, mixpad->fps_n, mixpad->fps_d);
270     if ((!fps_n && !fps_d) ||
271         ((gint64) fps_n * mixpad->fps_d < (gint64) mixpad->fps_n * fps_d)) {
272       fps_n = mixpad->fps_n;
273       fps_d = mixpad->fps_d;
274       GST_DEBUG_OBJECT (mixpad, "becomes the master pad");
275       master = mixpad;
276     }
277   }
278
279   /* set results */
280   if (mix->master != master || mix->in_width != width
281       || mix->in_height != height || mix->fps_n != fps_n
282       || mix->fps_d != fps_d) {
283     mix->setcaps = TRUE;
284     mix->sendseg = TRUE;
285     mix->master = master;
286     mix->in_width = width;
287     mix->in_height = height;
288     mix->fps_n = fps_n;
289     mix->fps_d = fps_d;
290   }
291 }
292
293 static gboolean
294 gst_videomixer_pad_sink_setcaps (GstPad * pad, GstCaps * vscaps)
295 {
296   GstVideoMixer *mix;
297   GstVideoMixerPad *mixpad;
298   GstStructure *structure;
299   gint in_width, in_height;
300   gboolean ret = FALSE;
301   const GValue *framerate;
302   GST_INFO_OBJECT (pad, "setcaps:\n%" GST_PTR_FORMAT, vscaps);
303
304   mix = GST_VIDEO_MIXER (gst_pad_get_parent (pad));
305   mixpad = GST_VIDEO_MIXER_PAD (pad);
306
307   if (!mixpad)
308     goto beach;
309
310   GST_DEBUG_OBJECT (mixpad, "setcaps triggered");
311
312   structure = gst_caps_get_structure (vscaps, 0);
313
314   if (!gst_structure_get_int (structure, "width", &in_width)
315       || !gst_structure_get_int (structure, "height", &in_height)
316       || (framerate = gst_structure_get_value (structure, "framerate")) == NULL)
317     goto beach;
318
319   GST_VIDEO_MIXER_STATE_LOCK (mix);
320   mixpad->fps_n = gst_value_get_fraction_numerator (framerate);
321   mixpad->fps_d = gst_value_get_fraction_denominator (framerate);
322
323   mixpad->in_width = in_width;
324   mixpad->in_height = in_height;
325
326   gst_videomixer_set_master_geometry (mix);
327   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
328
329   ret = TRUE;
330
331 beach:
332   gst_object_unref (mix);
333
334   return ret;
335 }
336
337 /*
338 * We accept the caps if it has the same format as other sink pads in 
339 * the element.
340 */
341 static gboolean
342 gst_videomixer_pad_sink_acceptcaps (GstPad * pad, GstCaps * vscaps)
343 {
344   gboolean ret;
345   GstVideoMixer *mix;
346   GstCaps *acceptedCaps;
347   mix = GST_VIDEO_MIXER (gst_pad_get_parent (pad));
348   GST_DEBUG_OBJECT (pad, "TRACE: \n%" GST_PTR_FORMAT, vscaps);
349   GST_VIDEO_MIXER_STATE_LOCK (mix);
350
351   if (mix->master) {
352     acceptedCaps = gst_pad_get_fixed_caps_func (GST_PAD (mix->master));
353     acceptedCaps = gst_caps_make_writable (acceptedCaps);
354     GST_LOG ("\nmaster's caps\n%" GST_PTR_FORMAT "\n", acceptedCaps);
355     if (GST_CAPS_IS_SIMPLE (acceptedCaps)) {
356       int templCapsSize =
357           gst_caps_get_size (gst_pad_get_pad_template_caps (pad));
358       guint i;
359       for (i = 0; i < templCapsSize; i++) {
360         GstCaps *caps1 = gst_caps_copy (acceptedCaps);
361         GstCaps *caps2 =
362             gst_caps_copy_nth (gst_pad_get_pad_template_caps (pad), i);
363         gst_caps_merge (caps1, caps2);
364         gst_caps_do_simplify (caps1);
365         if (GST_CAPS_IS_SIMPLE (caps1)) {
366           gst_caps_replace (&acceptedCaps, caps1);
367           gst_caps_unref (caps1);
368           break;
369         }
370         gst_caps_unref (caps1);
371       }
372     }
373   } else {
374     acceptedCaps = gst_pad_get_fixed_caps_func (pad);
375   }
376   GST_INFO ("\n\n%" GST_PTR_FORMAT "\n\n", vscaps);
377   GST_INFO ("\n\n*********\n%" GST_PTR_FORMAT "\n\n", acceptedCaps);
378
379   ret = gst_caps_is_always_compatible (vscaps, acceptedCaps);
380   gst_caps_unref (acceptedCaps);
381   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
382   gst_object_unref (mix);
383   return ret;
384 }
385
386 static void
387 gst_videomixer_pad_link (GstPad * pad, GstPad * peer, gpointer data)
388 {
389   GST_DEBUG_OBJECT (pad, "connected");
390 }
391
392 static void
393 gst_videomixer_pad_unlink (GstPad * pad, GstPad * peer, gpointer data)
394 {
395   GST_DEBUG_OBJECT (pad, "unlinked");
396 }
397
398 static void
399 gst_videomixer_pad_init (GstVideoMixerPad * mixerpad)
400 {
401   g_signal_connect (mixerpad, "linked",
402       G_CALLBACK (gst_videomixer_pad_link), mixerpad);
403   g_signal_connect (mixerpad, "unlinked",
404       G_CALLBACK (gst_videomixer_pad_unlink), mixerpad);
405
406   /* setup some pad functions */
407   gst_pad_set_setcaps_function (GST_PAD (mixerpad),
408       gst_videomixer_pad_sink_setcaps);
409   gst_pad_set_acceptcaps_function (GST_PAD (mixerpad),
410       GST_DEBUG_FUNCPTR (gst_videomixer_pad_sink_acceptcaps));
411
412   mixerpad->zorder = DEFAULT_PAD_ZORDER;
413   mixerpad->xpos = DEFAULT_PAD_XPOS;
414   mixerpad->ypos = DEFAULT_PAD_YPOS;
415   mixerpad->alpha = DEFAULT_PAD_ALPHA;
416 }
417
418
419 /* elementfactory information */
420 static const GstElementDetails gst_videomixer_details =
421 GST_ELEMENT_DETAILS ("Video mixer",
422     "Filter/Editor/Video",
423     "Mix multiple video streams",
424     "Wim Taymans <wim@fluendo.com>");
425
426 /* VideoMixer signals and args */
427 enum
428 {
429   /* FILL ME */
430   LAST_SIGNAL
431 };
432
433 #define DEFAULT_BACKGROUND VIDEO_MIXER_BACKGROUND_CHECKER
434 enum
435 {
436   ARG_0,
437   ARG_BACKGROUND
438 };
439
440 #define GST_TYPE_VIDEO_MIXER_BACKGROUND (gst_video_mixer_background_get_type())
441 static GType
442 gst_video_mixer_background_get_type (void)
443 {
444   static GType video_mixer_background_type = 0;
445
446   static const GEnumValue video_mixer_background[] = {
447     {VIDEO_MIXER_BACKGROUND_CHECKER, "Checker pattern", "checker"},
448     {VIDEO_MIXER_BACKGROUND_BLACK, "Black", "black"},
449     {VIDEO_MIXER_BACKGROUND_WHITE, "White", "white"},
450     {0, NULL, NULL},
451   };
452
453   if (!video_mixer_background_type) {
454     video_mixer_background_type =
455         g_enum_register_static ("GstVideoMixerBackground",
456         video_mixer_background);
457   }
458   return video_mixer_background_type;
459 }
460
461 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
462     GST_PAD_SRC,
463     GST_PAD_ALWAYS,
464     GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_BGRA ";"
465         GST_VIDEO_CAPS_YUV ("I420"))
466     );
467
468 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink_%d",
469     GST_PAD_SINK,
470     GST_PAD_REQUEST,
471     GST_STATIC_CAPS (GST_VIDEO_CAPS_YUV ("AYUV") ";" GST_VIDEO_CAPS_BGRA ";"
472         GST_VIDEO_CAPS_YUV ("I420"))
473     );
474
475 static void gst_videomixer_finalize (GObject * object);
476
477 static GstCaps *gst_videomixer_getcaps (GstPad * pad);
478 static gboolean gst_videomixer_setcaps (GstPad * pad, GstCaps * caps);
479 static gboolean gst_videomixer_query (GstPad * pad, GstQuery * query);
480
481 static GstFlowReturn gst_videomixer_collected (GstCollectPads * pads,
482     GstVideoMixer * mix);
483 static GstPad *gst_videomixer_request_new_pad (GstElement * element,
484     GstPadTemplate * templ, const gchar * name);
485 static void gst_videomixer_release_pad (GstElement * element, GstPad * pad);
486
487 static void gst_videomixer_set_property (GObject * object, guint prop_id,
488     const GValue * value, GParamSpec * pspec);
489 static void gst_videomixer_get_property (GObject * object, guint prop_id,
490     GValue * value, GParamSpec * pspec);
491 static GstStateChangeReturn gst_videomixer_change_state (GstElement * element,
492     GstStateChange transition);
493
494 /*static guint gst_videomixer_signals[LAST_SIGNAL] = { 0 }; */
495
496 static void gst_videomixer_child_proxy_init (gpointer g_iface,
497     gpointer iface_data);
498 static void _do_init (GType object_type);
499
500 GST_BOILERPLATE_FULL (GstVideoMixer, gst_videomixer, GstElement,
501     GST_TYPE_ELEMENT, _do_init);
502
503 static void
504 _do_init (GType object_type)
505 {
506   const GInterfaceInfo child_proxy_info = {
507     (GInterfaceInitFunc) gst_videomixer_child_proxy_init,
508     NULL,
509     NULL
510   };
511   g_type_add_interface_static (object_type, GST_TYPE_CHILD_PROXY,
512       &child_proxy_info);
513   GST_INFO ("GstChildProxy interface registered");
514 }
515
516 static GstObject *
517 gst_videomixer_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
518     guint index)
519 {
520   GstVideoMixer *mix = GST_VIDEO_MIXER (child_proxy);
521   GstObject *obj;
522
523   GST_VIDEO_MIXER_STATE_LOCK (mix);
524   if ((obj = g_slist_nth_data (mix->sinkpads, index)))
525     gst_object_ref (obj);
526   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
527   return obj;
528 }
529
530 static guint
531 gst_videomixer_child_proxy_get_children_count (GstChildProxy * child_proxy)
532 {
533   guint count = 0;
534   GstVideoMixer *mix = GST_VIDEO_MIXER (child_proxy);
535
536   GST_VIDEO_MIXER_STATE_LOCK (mix);
537   count = mix->numpads;
538   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
539   GST_INFO ("Children Count: %d", count);
540   return count;
541 }
542
543 static void
544 gst_videomixer_child_proxy_init (gpointer g_iface, gpointer iface_data)
545 {
546   GstChildProxyInterface *iface = g_iface;
547
548   GST_INFO ("intializing child proxy interface");
549   iface->get_child_by_index = gst_videomixer_child_proxy_get_child_by_index;
550   iface->get_children_count = gst_videomixer_child_proxy_get_children_count;
551 }
552
553 static void
554 gst_videomixer_base_init (gpointer g_class)
555 {
556   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
557
558   gst_element_class_add_pad_template (element_class,
559       gst_static_pad_template_get (&src_factory));
560   gst_element_class_add_pad_template (element_class,
561       gst_static_pad_template_get (&sink_factory));
562
563   gst_element_class_set_details (element_class, &gst_videomixer_details);
564 }
565
566 static void
567 gst_videomixer_class_init (GstVideoMixerClass * klass)
568 {
569   GObjectClass *gobject_class;
570   GstElementClass *gstelement_class;
571
572   gobject_class = (GObjectClass *) klass;
573   gstelement_class = (GstElementClass *) klass;
574
575   parent_class = g_type_class_peek_parent (klass);
576
577   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_videomixer_finalize);
578
579   gobject_class->get_property = gst_videomixer_get_property;
580   gobject_class->set_property = gst_videomixer_set_property;
581
582   g_object_class_install_property (gobject_class, ARG_BACKGROUND,
583       g_param_spec_enum ("background", "Background", "Background type",
584           GST_TYPE_VIDEO_MIXER_BACKGROUND,
585           DEFAULT_BACKGROUND, G_PARAM_READWRITE));
586
587   gstelement_class->request_new_pad =
588       GST_DEBUG_FUNCPTR (gst_videomixer_request_new_pad);
589   gstelement_class->release_pad =
590       GST_DEBUG_FUNCPTR (gst_videomixer_release_pad);
591   gstelement_class->change_state =
592       GST_DEBUG_FUNCPTR (gst_videomixer_change_state);
593
594   /* Register the pad class */
595   (void) (GST_TYPE_VIDEO_MIXER_PAD);
596 }
597
598 static void
599 gst_videomixer_collect_free (GstVideoMixerCollect * mixcol)
600 {
601   if (mixcol->buffer) {
602     gst_buffer_unref (mixcol->buffer);
603     mixcol->buffer = NULL;
604   }
605 }
606
607 static void
608 gst_videomixer_reset (GstVideoMixer * mix)
609 {
610   GSList *walk;
611
612   mix->in_width = 0;
613   mix->in_height = 0;
614   mix->out_width = 0;
615   mix->out_height = 0;
616   mix->fps_n = mix->fps_d = 0;
617   mix->setcaps = FALSE;
618   mix->sendseg = FALSE;
619   mix->segment_position = 0;
620   mix->segment_rate = 1.0;
621
622   mix->last_ts = 0;
623
624   /* clean up collect data */
625   walk = mix->collect->data;
626   while (walk) {
627     GstVideoMixerCollect *data = (GstVideoMixerCollect *) walk->data;
628
629     gst_videomixer_collect_free (data);
630     walk = g_slist_next (walk);
631   }
632
633   mix->next_sinkpad = 0;
634 }
635
636 static void
637 gst_videomixer_init (GstVideoMixer * mix, GstVideoMixerClass * g_class)
638 {
639   GstElementClass *klass = GST_ELEMENT_GET_CLASS (mix);
640
641   mix->srcpad =
642       gst_pad_new_from_template (gst_element_class_get_pad_template (klass,
643           "src"), "src");
644   gst_pad_set_getcaps_function (GST_PAD (mix->srcpad),
645       GST_DEBUG_FUNCPTR (gst_videomixer_getcaps));
646   gst_pad_set_setcaps_function (GST_PAD (mix->srcpad),
647       GST_DEBUG_FUNCPTR (gst_videomixer_setcaps));
648   gst_pad_set_query_function (GST_PAD (mix->srcpad),
649       GST_DEBUG_FUNCPTR (gst_videomixer_query));
650   gst_pad_set_event_function (GST_PAD (mix->srcpad),
651       GST_DEBUG_FUNCPTR (gst_videomixer_src_event));
652   gst_element_add_pad (GST_ELEMENT (mix), mix->srcpad);
653
654   mix->collect = gst_collect_pads_new ();
655   mix->background = DEFAULT_BACKGROUND;
656
657   gst_collect_pads_set_function (mix->collect,
658       (GstCollectPadsFunction) GST_DEBUG_FUNCPTR (gst_videomixer_collected),
659       mix);
660
661   mix->state_lock = g_mutex_new ();
662   /* initialize variables */
663   gst_videomixer_reset (mix);
664 }
665
666 static void
667 gst_videomixer_finalize (GObject * object)
668 {
669   GstVideoMixer *mix = GST_VIDEO_MIXER (object);
670
671   gst_object_unref (mix->collect);
672   g_mutex_free (mix->state_lock);
673
674   G_OBJECT_CLASS (parent_class)->finalize (object);
675 }
676
677 static gboolean
678 gst_videomixer_query_duration (GstVideoMixer * mix, GstQuery * query)
679 {
680   gint64 max;
681   gboolean res;
682   GstFormat format;
683   GstIterator *it;
684   gboolean done;
685
686   /* parse format */
687   gst_query_parse_duration (query, &format, NULL);
688
689   max = -1;
690   res = TRUE;
691   done = FALSE;
692
693   /* Take maximum of all durations */
694   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mix));
695   while (!done) {
696     GstIteratorResult ires;
697     gpointer item;
698
699     ires = gst_iterator_next (it, &item);
700     switch (ires) {
701       case GST_ITERATOR_DONE:
702         done = TRUE;
703         break;
704       case GST_ITERATOR_OK:
705       {
706         GstPad *pad = GST_PAD_CAST (item);
707         gint64 duration;
708
709         /* ask sink peer for duration */
710         res &= gst_pad_query_peer_duration (pad, &format, &duration);
711         /* take max from all valid return values */
712         if (res) {
713           /* valid unknown length, stop searching */
714           if (duration == -1) {
715             max = duration;
716             done = TRUE;
717           }
718           /* else see if bigger than current max */
719           else if (duration > max)
720             max = duration;
721         }
722         gst_object_unref (pad);
723         break;
724       }
725       case GST_ITERATOR_RESYNC:
726         max = -1;
727         res = TRUE;
728         gst_iterator_resync (it);
729         break;
730       default:
731         res = FALSE;
732         done = TRUE;
733         break;
734     }
735   }
736   gst_iterator_free (it);
737
738   if (res) {
739     /* and store the max */
740     GST_DEBUG_OBJECT (mix, "Total duration in format %s: %"
741         GST_TIME_FORMAT, gst_format_get_name (format), GST_TIME_ARGS (max));
742     gst_query_set_duration (query, format, max);
743   }
744
745   return res;
746 }
747
748 static gboolean
749 gst_videomixer_query_latency (GstVideoMixer * mix, GstQuery * query)
750 {
751   GstClockTime min, max;
752   gboolean live;
753   gboolean res;
754   GstIterator *it;
755   gboolean done;
756
757   res = TRUE;
758   done = FALSE;
759   live = FALSE;
760   min = 0;
761   max = GST_CLOCK_TIME_NONE;
762
763   /* Take maximum of all latency values */
764   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mix));
765   while (!done) {
766     GstIteratorResult ires;
767     gpointer item;
768
769     ires = gst_iterator_next (it, &item);
770     switch (ires) {
771       case GST_ITERATOR_DONE:
772         done = TRUE;
773         break;
774       case GST_ITERATOR_OK:
775       {
776         GstPad *pad = GST_PAD_CAST (item);
777
778         GstQuery *peerquery;
779
780         GstClockTime min_cur, max_cur;
781
782         gboolean live_cur;
783
784         peerquery = gst_query_new_latency ();
785
786         /* Ask peer for latency */
787         res &= gst_pad_peer_query (pad, peerquery);
788
789         /* take max from all valid return values */
790         if (res) {
791           gst_query_parse_latency (peerquery, &live_cur, &min_cur, &max_cur);
792
793           if (min_cur > min)
794             min = min_cur;
795
796           if (max_cur != GST_CLOCK_TIME_NONE &&
797               ((max != GST_CLOCK_TIME_NONE && max_cur > max) ||
798                   (max == GST_CLOCK_TIME_NONE)))
799             max = max_cur;
800
801           live = live || live_cur;
802         }
803
804         gst_query_unref (peerquery);
805         gst_object_unref (pad);
806         break;
807       }
808       case GST_ITERATOR_RESYNC:
809         live = FALSE;
810         min = 0;
811         max = GST_CLOCK_TIME_NONE;
812         res = TRUE;
813         gst_iterator_resync (it);
814         break;
815       default:
816         res = FALSE;
817         done = TRUE;
818         break;
819     }
820   }
821   gst_iterator_free (it);
822
823   if (res) {
824     /* store the results */
825     GST_DEBUG_OBJECT (mix, "Calculated total latency: live %s, min %"
826         GST_TIME_FORMAT ", max %" GST_TIME_FORMAT,
827         (live ? "yes" : "no"), GST_TIME_ARGS (min), GST_TIME_ARGS (max));
828     gst_query_set_latency (query, live, min, max);
829   }
830
831   return res;
832 }
833
834 static gboolean
835 gst_videomixer_query (GstPad * pad, GstQuery * query)
836 {
837   GstVideoMixer *mix = GST_VIDEO_MIXER (gst_pad_get_parent (pad));
838   gboolean res = FALSE;
839
840   switch (GST_QUERY_TYPE (query)) {
841     case GST_QUERY_POSITION:
842     {
843       GstFormat format;
844
845       gst_query_parse_position (query, &format, NULL);
846
847       switch (format) {
848         case GST_FORMAT_TIME:
849           /* FIXME, bring to stream time, might be tricky */
850           gst_query_set_position (query, format, mix->last_ts);
851           res = TRUE;
852           break;
853         default:
854           break;
855       }
856       break;
857     }
858     case GST_QUERY_DURATION:
859       res = gst_videomixer_query_duration (mix, query);
860       break;
861     case GST_QUERY_LATENCY:
862       res = gst_videomixer_query_latency (mix, query);
863       break;
864     default:
865       /* FIXME, needs a custom query handler because we have multiple
866        * sinkpads */
867       res = gst_pad_query_default (pad, query);
868       break;
869   }
870
871   gst_object_unref (mix);
872   return res;
873 }
874
875 static GstCaps *
876 gst_videomixer_getcaps (GstPad * pad)
877 {
878   GstVideoMixer *mix;
879   GstCaps *caps;
880   GstStructure *structure;
881   int numCaps;
882   GST_LOG_OBJECT (pad, "TRACE");
883
884   mix = GST_VIDEO_MIXER (gst_pad_get_parent (pad));
885
886   if (mix->master) {
887     caps =
888         gst_caps_copy (gst_pad_get_pad_template_caps (GST_PAD (mix->master)));
889   } else {
890     caps = gst_caps_copy (gst_pad_get_pad_template_caps (mix->srcpad));
891   }
892
893   numCaps = gst_caps_get_size (caps) - 1;
894   for (; numCaps >= 0; numCaps--) {
895     structure = gst_caps_get_structure (caps, numCaps);
896     if (mix->out_width != 0) {
897       gst_structure_set (structure, "width", G_TYPE_INT, mix->out_width, NULL);
898     }
899     if (mix->out_height != 0) {
900       gst_structure_set (structure, "height", G_TYPE_INT, mix->out_height,
901           NULL);
902     }
903     if (mix->fps_d != 0) {
904       gst_structure_set (structure,
905           "framerate", GST_TYPE_FRACTION, mix->fps_n, mix->fps_d, NULL);
906     }
907   }
908
909   gst_object_unref (mix);
910
911   return caps;
912 }
913
914 static gboolean
915 gst_videomixer_setcaps (GstPad * pad, GstCaps * caps)
916 {
917   GstElement *element;
918   GstVideoMixer *mixer;
919   GstStructure *str;
920   element = gst_pad_get_parent_element (pad);
921   g_assert (element);
922   mixer = GST_VIDEO_MIXER (element);
923   g_assert (mixer);
924   GST_INFO_OBJECT (mixer, "set src caps: \n%" GST_PTR_FORMAT, caps);
925
926   str = gst_caps_get_structure (caps, 0);
927
928   if (gst_structure_has_name (str, "video/x-raw-yuv")) {
929     guint32 format;
930     int ret;
931     ret = gst_structure_get_fourcc (str, "format", &format);
932     if (!ret) {
933       mixer->blend = NULL;
934       mixer->fill_checker = NULL;
935       mixer->fill_color = NULL;
936       mixer->calculate_frame_size = NULL;
937     } else if (format == GST_STR_FOURCC ("AYUV")) {
938       mixer->blend = gst_videomixer_blend_ayuv_ayuv;
939       mixer->fill_checker = gst_videomixer_fill_ayuv_checker;
940       mixer->fill_color = gst_videomixer_fill_ayuv_color;
941       mixer->calculate_frame_size = gst_videomixer_calculate_frame_size_ayuv;
942     } else if (format == GST_STR_FOURCC ("I420")) {
943       mixer->blend = gst_videomixer_blend_i420_i420;
944       mixer->fill_checker = gst_videomixer_fill_i420_checker;
945       mixer->fill_color = gst_videomixer_fill_i420_color;
946       mixer->calculate_frame_size = gst_videomixer_calculate_frame_size_i420;
947     } else {
948       mixer->blend = NULL;
949       mixer->fill_checker = NULL;
950       mixer->fill_color = NULL;
951       mixer->calculate_frame_size = NULL;
952     }
953   } else if (gst_structure_has_name (str, "video/x-raw-rgb")) {
954     mixer->blend = gst_videomixer_blend_bgra_bgra;
955     mixer->fill_checker = gst_videomixer_fill_bgra_checker;
956     mixer->fill_color = gst_videomixer_fill_bgra_color;
957     mixer->calculate_frame_size = gst_videomixer_calculate_frame_size_bgra;
958   } else {
959     mixer->blend = NULL;
960     mixer->fill_checker = NULL;
961     mixer->fill_color = NULL;
962     mixer->calculate_frame_size = NULL;
963   }
964   gst_object_unref (element);
965
966   return TRUE;
967 }
968
969 static GstPad *
970 gst_videomixer_request_new_pad (GstElement * element,
971     GstPadTemplate * templ, const gchar * req_name)
972 {
973   GstVideoMixer *mix = NULL;
974   GstVideoMixerPad *mixpad = NULL;
975   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
976
977   g_return_val_if_fail (templ != NULL, NULL);
978
979   if (templ->direction != GST_PAD_SINK) {
980     g_warning ("videomixer: request pad that is not a SINK pad\n");
981     return NULL;
982   }
983
984   g_return_val_if_fail (GST_IS_VIDEO_MIXER (element), NULL);
985
986   mix = GST_VIDEO_MIXER (element);
987
988   if (templ == gst_element_class_get_pad_template (klass, "sink_%d")) {
989     gint serial = 0;
990     gchar *name = NULL;
991     GstVideoMixerCollect *mixcol = NULL;
992
993     if (req_name == NULL || strlen (req_name) < 6) {
994       /* no name given when requesting the pad, use next available int */
995       serial = mix->next_sinkpad++;
996     } else {
997       /* parse serial number from requested padname */
998       serial = atoi (&req_name[5]);
999       if (serial >= mix->next_sinkpad)
1000         mix->next_sinkpad = serial + 1;
1001     }
1002     /* create new pad with the name */
1003     name = g_strdup_printf ("sink_%d", serial);
1004     mixpad = g_object_new (GST_TYPE_VIDEO_MIXER_PAD, "name", name, "direction",
1005         templ->direction, "template", templ, NULL);
1006     g_free (name);
1007
1008     GST_VIDEO_MIXER_STATE_LOCK (mix);
1009     mixpad->zorder = mix->numpads;
1010     mixpad->xpos = DEFAULT_PAD_XPOS;
1011     mixpad->ypos = DEFAULT_PAD_YPOS;
1012     mixpad->alpha = DEFAULT_PAD_ALPHA;
1013
1014     mixcol = (GstVideoMixerCollect *)
1015         gst_collect_pads_add_pad (mix->collect, GST_PAD (mixpad),
1016         sizeof (GstVideoMixerCollect));
1017
1018     /* FIXME: hacked way to override/extend the event function of
1019      * GstCollectPads; because it sets its own event function giving the
1020      * element no access to events */
1021     mix->collect_event =
1022         (GstPadEventFunction) GST_PAD_EVENTFUNC (GST_PAD (mixpad));
1023     gst_pad_set_event_function (GST_PAD (mixpad),
1024         GST_DEBUG_FUNCPTR (gst_videomixer_sink_event));
1025
1026     /* Keep track of each other */
1027     mixcol->mixpad = mixpad;
1028     mixpad->mixcol = mixcol;
1029
1030     /* Keep an internal list of mixpads for zordering */
1031     mix->sinkpads = g_slist_append (mix->sinkpads, mixpad);
1032     mix->numpads++;
1033     GST_VIDEO_MIXER_STATE_UNLOCK (mix);
1034   } else {
1035     g_warning ("videomixer: this is not our template!\n");
1036     return NULL;
1037   }
1038
1039   /* add the pad to the element */
1040   gst_element_add_pad (element, GST_PAD (mixpad));
1041   gst_child_proxy_child_added (GST_OBJECT (mix), GST_OBJECT (mixpad));
1042
1043   return GST_PAD (mixpad);
1044 }
1045
1046 static void
1047 gst_videomixer_release_pad (GstElement * element, GstPad * pad)
1048 {
1049   GstVideoMixer *mix = NULL;
1050   GstVideoMixerPad *mixpad;
1051
1052   mix = GST_VIDEO_MIXER (element);
1053   GST_VIDEO_MIXER_STATE_LOCK (mix);
1054   if (G_UNLIKELY (g_slist_find (mix->sinkpads, pad) == NULL)) {
1055     g_warning ("Unknown pad %s", GST_PAD_NAME (pad));
1056     goto error;
1057   }
1058
1059   mixpad = GST_VIDEO_MIXER_PAD (pad);
1060
1061   mix->sinkpads = g_slist_remove (mix->sinkpads, pad);
1062   gst_videomixer_collect_free (mixpad->mixcol);
1063   gst_collect_pads_remove_pad (mix->collect, pad);
1064   gst_child_proxy_child_removed (GST_OBJECT (mix), GST_OBJECT (mixpad));
1065   /* determine possibly new geometry and master */
1066   gst_videomixer_set_master_geometry (mix);
1067   mix->numpads--;
1068   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
1069
1070   gst_element_remove_pad (element, pad);
1071   return;
1072 error:
1073   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
1074 }
1075
1076 static int
1077 pad_zorder_compare (const GstVideoMixerPad * pad1,
1078     const GstVideoMixerPad * pad2)
1079 {
1080   return pad1->zorder - pad2->zorder;
1081 }
1082
1083 static void
1084 gst_videomixer_sort_pads (GstVideoMixer * mix)
1085 {
1086   mix->sinkpads = g_slist_sort (mix->sinkpads,
1087       (GCompareFunc) pad_zorder_compare);
1088 }
1089
1090 /* try to get a buffer on all pads. As long as the queued value is
1091  * negative, we skip buffers */
1092 static gboolean
1093 gst_videomixer_fill_queues (GstVideoMixer * mix)
1094 {
1095   GSList *walk = NULL;
1096   gboolean eos = TRUE;
1097
1098   g_return_val_if_fail (GST_IS_VIDEO_MIXER (mix), FALSE);
1099
1100   /* try to make sure we have a buffer from each usable pad first */
1101   walk = mix->collect->data;
1102   while (walk) {
1103     GstCollectData *data = (GstCollectData *) walk->data;
1104     GstVideoMixerCollect *mixcol = (GstVideoMixerCollect *) data;
1105     GstVideoMixerPad *mixpad = mixcol->mixpad;
1106
1107     walk = g_slist_next (walk);
1108
1109     if (mixcol->buffer == NULL) {
1110       GstBuffer *buf = NULL;
1111
1112       GST_LOG ("we need a new buffer");
1113
1114       buf = gst_collect_pads_pop (mix->collect, data);
1115
1116       if (buf) {
1117         guint64 duration;
1118
1119         GST_LOG ("we have a buffer !");
1120
1121         mixcol->buffer = buf;
1122         duration = GST_BUFFER_DURATION (mixcol->buffer);
1123         /* no duration on the buffer, use the framerate */
1124         if (!GST_CLOCK_TIME_IS_VALID (duration)) {
1125           if (mixpad->fps_n == 0) {
1126             duration = GST_CLOCK_TIME_NONE;
1127           } else {
1128             duration = GST_SECOND * mixpad->fps_d / mixpad->fps_n;
1129           }
1130         }
1131         if (GST_CLOCK_TIME_IS_VALID (duration))
1132           mixpad->queued += duration;
1133         else if (!mixpad->queued)
1134           mixpad->queued = GST_CLOCK_TIME_NONE;
1135       } else {
1136         GST_LOG ("pop returned a NULL buffer");
1137       }
1138     }
1139     if (mix->sendseg && (mixpad == mix->master)) {
1140       GstEvent *event;
1141       gint64 stop, start;
1142       GstSegment *segment = &data->segment;
1143
1144       /* FIXME, use rate/applied_rate as set on all sinkpads.
1145        * - currently we just set rate as received from last seek-event
1146        * We could potentially figure out the duration as well using
1147        * the current segment positions and the stated stop positions.
1148        * Also we just start from stream time 0 which is rather
1149        * weird. For non-synchronized mixing, the time should be
1150        * the min of the stream times of all received segments,
1151        * rationale being that the duration is at least going to
1152        * be as long as the earliest stream we start mixing. This
1153        * would also be correct for synchronized mixing but then
1154        * the later streams would be delayed until the stream times
1155        * match.
1156        */
1157       GST_INFO ("_sending play segment");
1158
1159       start = segment->accum;
1160
1161       /* get the duration of the segment if we can and add it to the accumulated
1162        * time on the segment. */
1163       if (segment->stop != -1 && segment->start != -1)
1164         stop = start + (segment->stop - segment->start);
1165       else
1166         stop = -1;
1167
1168       event = gst_event_new_new_segment_full (FALSE, segment->rate, 1.0,
1169           segment->format, start, stop, start + mix->segment_position);
1170       gst_pad_push_event (mix->srcpad, event);
1171       mix->sendseg = FALSE;
1172     }
1173
1174     if (mixcol->buffer != NULL && GST_CLOCK_TIME_IS_VALID (mixpad->queued)) {
1175       /* got a buffer somewhere so we're not eos */
1176       eos = FALSE;
1177     }
1178   }
1179
1180   return eos;
1181 }
1182
1183 /* blend all buffers present on the pads */
1184 static void
1185 gst_videomixer_blend_buffers (GstVideoMixer * mix, GstBuffer * outbuf)
1186 {
1187   GSList *walk;
1188
1189   walk = mix->sinkpads;
1190   while (walk) {                /* We walk with this list because it's ordered */
1191     GstVideoMixerPad *pad = GST_VIDEO_MIXER_PAD (walk->data);
1192     GstVideoMixerCollect *mixcol = pad->mixcol;
1193
1194     walk = g_slist_next (walk);
1195
1196     if (mixcol->buffer != NULL) {
1197       GstClockTime timestamp;
1198       gint64 stream_time;
1199       GstSegment *seg;
1200
1201       seg = &mixcol->collect.segment;
1202
1203       timestamp = GST_BUFFER_TIMESTAMP (mixcol->buffer);
1204
1205       stream_time =
1206           gst_segment_to_stream_time (seg, GST_FORMAT_TIME, timestamp);
1207
1208       /* sync object properties on stream time */
1209       if (GST_CLOCK_TIME_IS_VALID (stream_time))
1210         gst_object_sync_values (G_OBJECT (pad), stream_time);
1211
1212       if (G_UNLIKELY (mix->blend == NULL)) {
1213         GST_ERROR_OBJECT (mix, "blend function not set");
1214       } else {
1215         (mix->blend) (GST_BUFFER_DATA (mixcol->buffer),
1216             pad->xpos, pad->ypos, pad->in_width, pad->in_height, pad->alpha,
1217             GST_BUFFER_DATA (outbuf), mix->out_width, mix->out_height);
1218       }
1219
1220       if (pad == mix->master) {
1221         gint64 running_time;
1222
1223         running_time =
1224             gst_segment_to_running_time (seg, GST_FORMAT_TIME, timestamp);
1225
1226         /* outgoing buffers need the running_time */
1227         GST_BUFFER_TIMESTAMP (outbuf) = running_time;
1228         GST_BUFFER_DURATION (outbuf) = GST_BUFFER_DURATION (mixcol->buffer);
1229
1230         mix->last_ts = running_time;
1231         if (GST_BUFFER_DURATION_IS_VALID (outbuf))
1232           mix->last_ts += GST_BUFFER_DURATION (outbuf);
1233       }
1234     }
1235   }
1236 }
1237
1238 /* remove buffers from the queue that were expired in the
1239  * interval of the master, we also prepare the queued value
1240  * in the pad so that we can skip and fill buffers later on */
1241 static void
1242 gst_videomixer_update_queues (GstVideoMixer * mix)
1243 {
1244   GSList *walk;
1245   guint64 interval;
1246
1247   interval = mix->master->queued;
1248   if (interval <= 0) {
1249     if (mix->fps_n == 0) {
1250       interval = G_MAXINT64;
1251     } else {
1252       interval = GST_SECOND * mix->fps_d / mix->fps_n;
1253     }
1254     GST_LOG_OBJECT (mix, "set interval to %" G_GUINT64_FORMAT, interval);
1255   }
1256
1257   walk = mix->sinkpads;
1258   while (walk) {
1259     GstVideoMixerPad *pad = GST_VIDEO_MIXER_PAD (walk->data);
1260     GstVideoMixerCollect *mixcol = pad->mixcol;
1261
1262     walk = g_slist_next (walk);
1263
1264     if (mixcol->buffer != NULL) {
1265       pad->queued -= interval;
1266       GST_LOG_OBJECT (pad, "queued now %" G_GINT64_FORMAT, pad->queued);
1267       if (pad->queued <= 0) {
1268         GST_LOG ("unreffing buffer");
1269         gst_buffer_unref (mixcol->buffer);
1270         mixcol->buffer = NULL;
1271       }
1272     }
1273   }
1274 }
1275
1276 static GstFlowReturn
1277 gst_videomixer_collected (GstCollectPads * pads, GstVideoMixer * mix)
1278 {
1279   GstFlowReturn ret = GST_FLOW_OK;
1280   GstBuffer *outbuf = NULL;
1281   size_t outsize = 0;
1282   gboolean eos = FALSE;
1283
1284   g_return_val_if_fail (GST_IS_VIDEO_MIXER (mix), GST_FLOW_ERROR);
1285
1286   GST_LOG ("all pads are collected");
1287   GST_VIDEO_MIXER_STATE_LOCK (mix);
1288
1289   eos = gst_videomixer_fill_queues (mix);
1290
1291   if (eos) {
1292     /* Push EOS downstream */
1293     GST_LOG ("all our sinkpads are EOS, pushing downstream");
1294     gst_pad_push_event (mix->srcpad, gst_event_new_eos ());
1295     ret = GST_FLOW_WRONG_STATE;
1296     goto error;
1297   }
1298
1299   /* If geometry has changed we need to set new caps on the buffer */
1300   if (mix->in_width != mix->out_width || mix->in_height != mix->out_height
1301       || mix->setcaps) {
1302     GstCaps *newcaps = NULL;
1303
1304     newcaps = gst_caps_make_writable
1305         (gst_pad_get_negotiated_caps (GST_PAD (mix->master)));
1306     gst_caps_set_simple (newcaps,
1307         "width", G_TYPE_INT, mix->in_width,
1308         "height", G_TYPE_INT, mix->in_height, NULL);
1309
1310     mix->out_width = mix->in_width;
1311     mix->out_height = mix->in_height;
1312     mix->setcaps = FALSE;
1313
1314     /* Calculating out buffer size from input size */
1315     gst_pad_set_caps (mix->srcpad, newcaps);
1316     outsize = mix->calculate_frame_size (mix->out_width, mix->out_height);
1317     ret =
1318         gst_pad_alloc_buffer_and_set_caps (mix->srcpad, GST_BUFFER_OFFSET_NONE,
1319         outsize, newcaps, &outbuf);
1320     gst_caps_unref (newcaps);
1321   } else {                      /* Otherwise we just allocate a buffer from current caps */
1322     /* Calculating out buffer size from input size */
1323     outsize = mix->calculate_frame_size (mix->out_width, mix->out_height);
1324     ret =
1325         gst_pad_alloc_buffer_and_set_caps (mix->srcpad, GST_BUFFER_OFFSET_NONE,
1326         outsize, GST_PAD_CAPS (mix->srcpad), &outbuf);
1327   }
1328
1329   if (ret != GST_FLOW_OK) {
1330     goto error;
1331   }
1332
1333   switch (mix->background) {
1334     case VIDEO_MIXER_BACKGROUND_CHECKER:
1335       if (G_UNLIKELY (mix->fill_checker == NULL)) {
1336         goto error;
1337       } else {
1338         mix->fill_checker (GST_BUFFER_DATA (outbuf), mix->out_width,
1339             mix->out_height);
1340       }
1341       break;
1342     case VIDEO_MIXER_BACKGROUND_BLACK:
1343       if (G_UNLIKELY (mix->fill_color == NULL)) {
1344         goto error;
1345       } else {
1346         mix->fill_color (GST_BUFFER_DATA (outbuf), mix->out_width,
1347             mix->out_height, 16, 128, 128);
1348       }
1349       break;
1350     case VIDEO_MIXER_BACKGROUND_WHITE:
1351
1352       if (G_UNLIKELY (mix->fill_color == NULL)) {
1353         goto error;
1354       } else {
1355         mix->fill_color (GST_BUFFER_DATA (outbuf), mix->out_width,
1356             mix->out_height, 240, 128, 128);
1357       }
1358       break;
1359   }
1360
1361   gst_videomixer_blend_buffers (mix, outbuf);
1362
1363   gst_videomixer_update_queues (mix);
1364   GST_VIDEO_MIXER_STATE_UNLOCK (mix);
1365
1366   ret = gst_pad_push (mix->srcpad, outbuf);
1367
1368 beach:
1369   return ret;
1370
1371   /* ERRORS */
1372 error:
1373   {
1374     GST_VIDEO_MIXER_STATE_UNLOCK (mix);
1375     goto beach;
1376   }
1377 }
1378
1379 static gboolean
1380 forward_event_func (GstPad * pad, GValue * ret, GstEvent * event)
1381 {
1382   gst_event_ref (event);
1383   GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
1384   if (!gst_pad_push_event (pad, event)) {
1385     g_value_set_boolean (ret, FALSE);
1386     GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
1387         event, GST_EVENT_TYPE_NAME (event));
1388   } else {
1389     GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
1390         event, GST_EVENT_TYPE_NAME (event));
1391   }
1392   gst_object_unref (pad);
1393   return TRUE;
1394 }
1395
1396 /* forwards the event to all sinkpads, takes ownership of the
1397  * event
1398  *
1399  * Returns: TRUE if the event could be forwarded on all
1400  * sinkpads.
1401  */
1402 static gboolean
1403 forward_event (GstVideoMixer * mix, GstEvent * event)
1404 {
1405   GstIterator *it;
1406   GValue vret = { 0 };
1407
1408   GST_LOG_OBJECT (mix, "Forwarding event %p (%s)", event,
1409       GST_EVENT_TYPE_NAME (event));
1410
1411   g_value_init (&vret, G_TYPE_BOOLEAN);
1412   g_value_set_boolean (&vret, TRUE);
1413   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (mix));
1414   gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func, &vret,
1415       event);
1416   gst_iterator_free (it);
1417   gst_event_unref (event);
1418
1419   return g_value_get_boolean (&vret);
1420 }
1421
1422 static gboolean
1423 gst_videomixer_src_event (GstPad * pad, GstEvent * event)
1424 {
1425   GstVideoMixer *mix;
1426   gboolean result;
1427
1428   mix = GST_VIDEO_MIXER (gst_pad_get_parent (pad));
1429
1430   switch (GST_EVENT_TYPE (event)) {
1431     case GST_EVENT_QOS:
1432       /* QoS might be tricky */
1433       result = FALSE;
1434       break;
1435     case GST_EVENT_SEEK:
1436     {
1437       GstSeekFlags flags;
1438
1439       GstSeekType curtype;
1440
1441       gint64 cur;
1442
1443       /* parse the seek parameters */
1444       gst_event_parse_seek (event, NULL, NULL, &flags, &curtype,
1445           &cur, NULL, NULL);
1446
1447       /* check if we are flushing */
1448       if (flags & GST_SEEK_FLAG_FLUSH) {
1449         /* make sure we accept nothing anymore and return WRONG_STATE */
1450         gst_collect_pads_set_flushing (mix->collect, TRUE);
1451
1452         /* flushing seek, start flush downstream, the flush will be done
1453          * when all pads received a FLUSH_STOP. */
1454         gst_pad_push_event (mix->srcpad, gst_event_new_flush_start ());
1455       }
1456
1457       /* now wait for the collected to be finished and mark a new
1458        * segment */
1459       GST_OBJECT_LOCK (mix->collect);
1460       if (curtype == GST_SEEK_TYPE_SET)
1461         mix->segment_position = cur;
1462       else
1463         mix->segment_position = 0;
1464       mix->sendseg = TRUE;
1465       GST_OBJECT_UNLOCK (mix->collect);
1466
1467       result = forward_event (mix, event);
1468       break;
1469     }
1470     case GST_EVENT_NAVIGATION:
1471       /* navigation is rather pointless. */
1472       result = FALSE;
1473       break;
1474     default:
1475       /* just forward the rest for now */
1476       result = forward_event (mix, event);
1477       break;
1478   }
1479   gst_object_unref (mix);
1480
1481   return result;
1482 }
1483
1484 static gboolean
1485 gst_videomixer_sink_event (GstPad * pad, GstEvent * event)
1486 {
1487   GstVideoMixer *videomixer;
1488   gboolean ret;
1489
1490   videomixer = GST_VIDEO_MIXER (gst_pad_get_parent (pad));
1491
1492   GST_DEBUG ("Got %s event on pad %s:%s", GST_EVENT_TYPE_NAME (event),
1493       GST_DEBUG_PAD_NAME (pad));
1494
1495   switch (GST_EVENT_TYPE (event)) {
1496     case GST_EVENT_FLUSH_STOP:
1497       /* mark a pending new segment. This event is synchronized
1498        * with the streaming thread so we can safely update the
1499        * variable without races. It's somewhat weird because we
1500        * assume the collectpads forwarded the FLUSH_STOP past us
1501        * and downstream (using our source pad, the bastard!).
1502        */
1503       videomixer->sendseg = TRUE;
1504       break;
1505     case GST_EVENT_NEWSEGMENT:
1506       videomixer->sendseg = TRUE;
1507       break;
1508     default:
1509       break;
1510   }
1511
1512   /* now GstCollectPads can take care of the rest, e.g. EOS */
1513   ret = videomixer->collect_event (pad, event);
1514
1515   gst_object_unref (videomixer);
1516   return ret;
1517 }
1518
1519
1520 static void
1521 gst_videomixer_get_property (GObject * object,
1522     guint prop_id, GValue * value, GParamSpec * pspec)
1523 {
1524   GstVideoMixer *mix = GST_VIDEO_MIXER (object);
1525
1526   switch (prop_id) {
1527     case ARG_BACKGROUND:
1528       g_value_set_enum (value, mix->background);
1529       break;
1530     default:
1531       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1532       break;
1533   }
1534 }
1535
1536 static void
1537 gst_videomixer_set_property (GObject * object,
1538     guint prop_id, const GValue * value, GParamSpec * pspec)
1539 {
1540   GstVideoMixer *mix = GST_VIDEO_MIXER (object);
1541
1542   switch (prop_id) {
1543     case ARG_BACKGROUND:
1544       mix->background = g_value_get_enum (value);
1545       break;
1546     default:
1547       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1548       break;
1549   }
1550 }
1551
1552 static GstStateChangeReturn
1553 gst_videomixer_change_state (GstElement * element, GstStateChange transition)
1554 {
1555   GstVideoMixer *mix;
1556   GstStateChangeReturn ret;
1557
1558   g_return_val_if_fail (GST_IS_VIDEO_MIXER (element), GST_STATE_CHANGE_FAILURE);
1559
1560   mix = GST_VIDEO_MIXER (element);
1561
1562   switch (transition) {
1563     case GST_STATE_CHANGE_READY_TO_PAUSED:
1564       GST_LOG ("starting collectpads");
1565       gst_collect_pads_start (mix->collect);
1566       break;
1567     case GST_STATE_CHANGE_PAUSED_TO_READY:
1568       GST_LOG ("stopping collectpads");
1569       gst_collect_pads_stop (mix->collect);
1570       break;
1571     default:
1572       break;
1573   }
1574
1575   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1576
1577   switch (transition) {
1578     case GST_STATE_CHANGE_PAUSED_TO_READY:
1579       gst_videomixer_reset (mix);
1580       break;
1581     default:
1582       break;
1583   }
1584
1585   return ret;
1586 }
1587
1588 static gboolean
1589 plugin_init (GstPlugin * plugin)
1590 {
1591   GST_DEBUG_CATEGORY_INIT (gst_videomixer_debug, "videomixer", 0,
1592       "video mixer");
1593
1594   return gst_element_register (plugin, "videomixer", GST_RANK_PRIMARY,
1595       GST_TYPE_VIDEO_MIXER);
1596 }
1597
1598 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1599     GST_VERSION_MINOR,
1600     "videomixer",
1601     "Video mixer", plugin_init, VERSION, GST_LICENSE, GST_PACKAGE_NAME,
1602     GST_PACKAGE_ORIGIN)