API: add gst_element_seek_simple() (#342238).
[platform/upstream/gstreamer.git] / gst / gstutils.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2002 Thomas Vander Stichele <thomas@apestaart.org>
5  *
6  * gstutils.c: Utility functions: gtk_get_property stuff, etc.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /**
25  * SECTION:gstutils
26  * @short_description: Various utility functions
27  *
28  * When defining own plugins, use the GST_BOILERPLATE ease gobject creation.
29  */
30
31 #include "gst_private.h"
32 #include <stdio.h>
33 #include <string.h>
34
35 #include "gstghostpad.h"
36 #include "gstutils.h"
37 #include "gstinfo.h"
38 #include "gstparse.h"
39 #include "gst-i18n-lib.h"
40
41
42 /**
43  * gst_util_dump_mem:
44  * @mem: a pointer to the memory to dump
45  * @size: the size of the memory block to dump
46  *
47  * Dumps the memory block into a hex representation. Useful for debugging.
48  */
49 void
50 gst_util_dump_mem (const guchar * mem, guint size)
51 {
52   guint i, j;
53   GString *string = g_string_sized_new (50);
54   GString *chars = g_string_sized_new (18);
55
56   i = j = 0;
57   while (i < size) {
58     if (g_ascii_isprint (mem[i]))
59       g_string_append_printf (chars, "%c", mem[i]);
60     else
61       g_string_append_printf (chars, ".");
62
63     g_string_append_printf (string, "%02x ", mem[i]);
64
65     j++;
66     i++;
67
68     if (j == 16 || i == size) {
69       g_print ("%08x (%p): %-48.48s %-16.16s\n", i - j, mem + i - j,
70           string->str, chars->str);
71       g_string_set_size (string, 0);
72       g_string_set_size (chars, 0);
73       j = 0;
74     }
75   }
76   g_string_free (string, TRUE);
77   g_string_free (chars, TRUE);
78 }
79
80
81 /**
82  * gst_util_set_value_from_string:
83  * @value: the value to set
84  * @value_str: the string to get the value from
85  *
86  * Converts the string to the type of the value and
87  * sets the value with it.
88  */
89 void
90 gst_util_set_value_from_string (GValue * value, const gchar * value_str)
91 {
92   gint sscanf_ret;
93
94   g_return_if_fail (value != NULL);
95   g_return_if_fail (value_str != NULL);
96
97   GST_CAT_DEBUG (GST_CAT_PARAMS, "parsing '%s' to type %s", value_str,
98       g_type_name (G_VALUE_TYPE (value)));
99
100   switch (G_VALUE_TYPE (value)) {
101     case G_TYPE_STRING:
102       g_value_set_string (value, g_strdup (value_str));
103       break;
104     case G_TYPE_ENUM:
105     case G_TYPE_INT:{
106       gint i;
107
108       sscanf_ret = sscanf (value_str, "%d", &i);
109       g_return_if_fail (sscanf_ret == 1);
110       g_value_set_int (value, i);
111       break;
112     }
113     case G_TYPE_UINT:{
114       guint i;
115
116       sscanf_ret = sscanf (value_str, "%u", &i);
117       g_return_if_fail (sscanf_ret == 1);
118       g_value_set_uint (value, i);
119       break;
120     }
121     case G_TYPE_LONG:{
122       glong i;
123
124       sscanf_ret = sscanf (value_str, "%ld", &i);
125       g_return_if_fail (sscanf_ret == 1);
126       g_value_set_long (value, i);
127       break;
128     }
129     case G_TYPE_ULONG:{
130       gulong i;
131
132       sscanf_ret = sscanf (value_str, "%lu", &i);
133       g_return_if_fail (sscanf_ret == 1);
134       g_value_set_ulong (value, i);
135       break;
136     }
137     case G_TYPE_BOOLEAN:{
138       gboolean i = FALSE;
139
140       if (!g_ascii_strncasecmp ("true", value_str, 4))
141         i = TRUE;
142       g_value_set_boolean (value, i);
143       break;
144     }
145     case G_TYPE_CHAR:{
146       gchar i;
147
148       sscanf_ret = sscanf (value_str, "%c", &i);
149       g_return_if_fail (sscanf_ret == 1);
150       g_value_set_char (value, i);
151       break;
152     }
153     case G_TYPE_UCHAR:{
154       guchar i;
155
156       sscanf_ret = sscanf (value_str, "%c", &i);
157       g_return_if_fail (sscanf_ret == 1);
158       g_value_set_uchar (value, i);
159       break;
160     }
161     case G_TYPE_FLOAT:{
162       gfloat i;
163
164       sscanf_ret = sscanf (value_str, "%f", &i);
165       g_return_if_fail (sscanf_ret == 1);
166       g_value_set_float (value, i);
167       break;
168     }
169     case G_TYPE_DOUBLE:{
170       gfloat i;
171
172       sscanf_ret = sscanf (value_str, "%g", &i);
173       g_return_if_fail (sscanf_ret == 1);
174       g_value_set_double (value, (gdouble) i);
175       break;
176     }
177     default:
178       break;
179   }
180 }
181
182 /**
183  * gst_util_set_object_arg:
184  * @object: the object to set the argument of
185  * @name: the name of the argument to set
186  * @value: the string value to set
187  *
188  * Convertes the string value to the type of the objects argument and
189  * sets the argument with it.
190  */
191 void
192 gst_util_set_object_arg (GObject * object, const gchar * name,
193     const gchar * value)
194 {
195   gboolean sscanf_ret;
196
197   if (name && value) {
198     GParamSpec *paramspec;
199
200     paramspec =
201         g_object_class_find_property (G_OBJECT_GET_CLASS (object), name);
202
203     if (!paramspec) {
204       return;
205     }
206
207     GST_DEBUG ("paramspec->flags is %d, paramspec->value_type is %d",
208         paramspec->flags, (gint) paramspec->value_type);
209
210     if (paramspec->flags & G_PARAM_WRITABLE) {
211       switch (paramspec->value_type) {
212         case G_TYPE_STRING:
213           g_object_set (G_OBJECT (object), name, value, NULL);
214           break;
215         case G_TYPE_ENUM:
216         case G_TYPE_INT:{
217           gint i;
218
219           sscanf_ret = sscanf (value, "%d", &i);
220           g_return_if_fail (sscanf_ret == 1);
221           g_object_set (G_OBJECT (object), name, i, NULL);
222           break;
223         }
224         case G_TYPE_UINT:{
225           guint i;
226
227           sscanf_ret = sscanf (value, "%u", &i);
228           g_return_if_fail (sscanf_ret == 1);
229           g_object_set (G_OBJECT (object), name, i, NULL);
230           break;
231         }
232         case G_TYPE_LONG:{
233           glong i;
234
235           sscanf_ret = sscanf (value, "%ld", &i);
236           g_return_if_fail (sscanf_ret == 1);
237           g_object_set (G_OBJECT (object), name, i, NULL);
238           break;
239         }
240         case G_TYPE_ULONG:{
241           gulong i;
242
243           sscanf_ret = sscanf (value, "%lu", &i);
244           g_return_if_fail (sscanf_ret == 1);
245           g_object_set (G_OBJECT (object), name, i, NULL);
246           break;
247         }
248         case G_TYPE_BOOLEAN:{
249           gboolean i = FALSE;
250
251           if (!g_ascii_strncasecmp ("true", value, 4))
252             i = TRUE;
253           g_object_set (G_OBJECT (object), name, i, NULL);
254           break;
255         }
256         case G_TYPE_CHAR:{
257           gchar i;
258
259           sscanf_ret = sscanf (value, "%c", &i);
260           g_return_if_fail (sscanf_ret == 1);
261           g_object_set (G_OBJECT (object), name, i, NULL);
262           break;
263         }
264         case G_TYPE_UCHAR:{
265           guchar i;
266
267           sscanf_ret = sscanf (value, "%c", &i);
268           g_return_if_fail (sscanf_ret == 1);
269           g_object_set (G_OBJECT (object), name, i, NULL);
270           break;
271         }
272         case G_TYPE_FLOAT:{
273           gfloat i;
274
275           sscanf_ret = sscanf (value, "%f", &i);
276           g_return_if_fail (sscanf_ret == 1);
277           g_object_set (G_OBJECT (object), name, i, NULL);
278           break;
279         }
280         case G_TYPE_DOUBLE:{
281           gfloat i;
282
283           sscanf_ret = sscanf (value, "%g", &i);
284           g_return_if_fail (sscanf_ret == 1);
285           g_object_set (G_OBJECT (object), name, (gdouble) i, NULL);
286           break;
287         }
288         default:
289           if (G_IS_PARAM_SPEC_ENUM (paramspec)) {
290             gint i;
291
292             sscanf_ret = sscanf (value, "%d", &i);
293             g_return_if_fail (sscanf_ret == 1);
294             g_object_set (G_OBJECT (object), name, i, NULL);
295           }
296           break;
297       }
298     }
299   }
300 }
301
302 /* work around error C2520: conversion from unsigned __int64 to double
303  * not implemented, use signed __int64
304  *
305  * These are implemented as functions because on some platforms a 64bit int to
306  * double conversion is not defined/implemented.
307  */
308
309 gdouble
310 gst_util_guint64_to_gdouble (guint64 value)
311 {
312   if (value & G_GINT64_CONSTANT (0x8000000000000000))
313     return (gdouble) ((gint64) value) + (gdouble) 18446744073709551616.;
314   else
315     return (gdouble) ((gint64) value);
316 }
317
318 guint64
319 gst_util_gdouble_to_guint64 (gdouble value)
320 {
321   if (value < (gdouble) 9223372036854775808.)   /* 1 << 63 */
322     return ((guint64) ((gint64) value));
323
324   value -= (gdouble) 18446744073709551616.;
325   return ((guint64) ((gint64) value));
326 }
327
328 /* convenience struct for getting high and low uint32 parts of
329  * a guint64 */
330 typedef union
331 {
332   guint64 ll;
333   struct
334   {
335 #if G_BYTE_ORDER == G_BIG_ENDIAN
336     guint32 high, low;
337 #else
338     guint32 low, high;
339 #endif
340   } l;
341 } GstUInt64;
342
343 /* based on Hacker's Delight p152 */
344 static guint64
345 gst_util_div128_64 (GstUInt64 c1, GstUInt64 c0, guint64 denom)
346 {
347   GstUInt64 q1, q0, rhat;
348   GstUInt64 v, cmp1, cmp2;
349   guint s;
350
351   v.ll = denom;
352
353   /* count number of leading zeroes, we know they must be in the high
354    * part of denom since denom > G_MAXUINT32. */
355   s = v.l.high | (v.l.high >> 1);
356   s |= (s >> 2);
357   s |= (s >> 4);
358   s |= (s >> 8);
359   s = ~(s | (s >> 16));
360   s = s - ((s >> 1) & 0x55555555);
361   s = (s & 0x33333333) + ((s >> 2) & 0x33333333);
362   s = (s + (s >> 4)) & 0x0f0f0f0f;
363   s += (s >> 8);
364   s = (s + (s >> 16)) & 0x3f;
365
366   if (s > 0) {
367     /* normalize divisor and dividend */
368     v.ll <<= s;
369     c1.ll = (c1.ll << s) | (c0.l.high >> (32 - s));
370     c0.ll <<= s;
371   }
372
373   q1.ll = c1.ll / v.l.high;
374   rhat.ll = c1.ll - q1.ll * v.l.high;
375
376   cmp1.l.high = rhat.l.low;
377   cmp1.l.low = c0.l.high;
378   cmp2.ll = q1.ll * v.l.low;
379
380   while (q1.l.high || cmp2.ll > cmp1.ll) {
381     q1.ll--;
382     rhat.ll += v.l.high;
383     if (rhat.l.high)
384       break;
385     cmp1.l.high = rhat.l.low;
386     cmp2.ll -= v.l.low;
387   }
388   c1.l.high = c1.l.low;
389   c1.l.low = c0.l.high;
390   c1.ll -= q1.ll * v.ll;
391   q0.ll = c1.ll / v.l.high;
392   rhat.ll = c1.ll - q0.ll * v.l.high;
393
394   cmp1.l.high = rhat.l.low;
395   cmp1.l.low = c0.l.low;
396   cmp2.ll = q0.ll * v.l.low;
397
398   while (q0.l.high || cmp2.ll > cmp1.ll) {
399     q0.ll--;
400     rhat.ll += v.l.high;
401     if (rhat.l.high)
402       break;
403     cmp1.l.high = rhat.l.low;
404     cmp2.ll -= v.l.low;
405   }
406   q0.l.high += q1.l.low;
407
408   return q0.ll;
409 }
410
411 static guint64
412 gst_util_uint64_scale_int64 (guint64 val, guint64 num, guint64 denom)
413 {
414   GstUInt64 a0, a1, b0, b1, c0, ct, c1, result;
415   GstUInt64 v, n;
416
417   /* prepare input */
418   v.ll = val;
419   n.ll = num;
420
421   /* do 128 bits multiply
422    *                   nh   nl
423    *                *  vh   vl
424    *                ----------
425    * a0 =              vl * nl
426    * a1 =         vl * nh
427    * b0 =         vh * nl
428    * b1 =  + vh * nh
429    *       -------------------
430    * c1,c0
431    */
432   a0.ll = (guint64) v.l.low * n.l.low;
433   a1.ll = (guint64) v.l.low * n.l.high;
434   b0.ll = (guint64) v.l.high * n.l.low;
435   b1.ll = (guint64) v.l.high * n.l.high;
436
437   /* and sum together with carry into 128 bits c1, c0 */
438   c0.l.low = a0.l.low;
439   ct.ll = (guint64) a0.l.high + a1.l.low + b0.l.low;
440   c0.l.high = ct.l.low;
441   c1.ll = (guint64) a1.l.high + b0.l.high + ct.l.high + b1.ll;
442
443   /* if high bits bigger than denom, we overflow */
444   if (c1.ll >= denom)
445     goto overflow;
446
447   /* shortcut for division by 1, c1.ll should be 0 because of the
448    * overflow check above. */
449   if (denom == 1)
450     return c0.ll;
451
452   /* and 128/64 bits division, result fits 64 bits */
453   if (denom <= G_MAXUINT32) {
454     guint32 den = (guint32) denom;
455
456     /* easy case, (c1,c0)128/(den)32 division */
457     c1.l.high %= den;
458     c1.l.high = c1.ll % den;
459     c1.l.low = c0.l.high;
460     c0.l.high = c1.ll % den;
461     result.l.high = c1.ll / den;
462     result.l.low = c0.ll / den;
463   } else {
464     result.ll = gst_util_div128_64 (c1, c0, denom);
465   }
466   return result.ll;
467
468 overflow:
469   {
470     return G_MAXUINT64;
471   }
472 }
473
474 /**
475  * gst_util_uint64_scale:
476  * @val: the number to scale
477  * @num: the numerator of the scale ratio
478  * @denom: the denominator of the scale ratio
479  *
480  * Scale @val by @num / @denom, trying to avoid overflows.
481  *
482  * This function can potentially be very slow if denom > G_MAXUINT32.
483  *
484  * Returns: @val * @num / @denom, trying to avoid overflows.
485  * In the case of an overflow, this function returns G_MAXUINT64.
486  */
487 guint64
488 gst_util_uint64_scale (guint64 val, guint64 num, guint64 denom)
489 {
490   g_return_val_if_fail (denom != 0, G_MAXUINT64);
491
492   if (num == 0)
493     return 0;
494
495   if (num == 1 && denom == 1)
496     return val;
497
498   /* if the denom is high, we need to do a 64 muldiv */
499   if (denom > G_MAXINT32)
500     goto do_int64;
501
502   /* if num and denom are low we can do a 32 bit muldiv */
503   if (num <= G_MAXINT32)
504     goto do_int32;
505
506   /* val and num are high, we need 64 muldiv */
507   if (val > G_MAXINT32)
508     goto do_int64;
509
510   /* val is low and num is high, we can swap them and do 32 muldiv */
511   return gst_util_uint64_scale_int (num, (gint) val, (gint) denom);
512
513 do_int32:
514   return gst_util_uint64_scale_int (val, (gint) num, (gint) denom);
515
516 do_int64:
517   /* to the more heavy implementations... */
518   return gst_util_uint64_scale_int64 (val, num, denom);
519 }
520
521 /**
522  * gst_util_uint64_scale_int:
523  * @val: guint64 (such as a #GstClockTime) to scale.
524  * @num: numerator of the scale factor.
525  * @denom: denominator of the scale factor.
526  *
527  * Scale a guint64 by a factor expressed as a fraction (num/denom), avoiding
528  * overflows and loss of precision.
529  *
530  * @num and @denom must be positive integers. @denom cannot be 0.
531  *
532  * Returns: @val * @num / @denom, avoiding overflow and loss of precision.
533  * In the case of an overflow, this function returns G_MAXUINT64.
534  */
535 guint64
536 gst_util_uint64_scale_int (guint64 val, gint num, gint denom)
537 {
538   GstUInt64 result;
539   GstUInt64 low, high;
540
541   g_return_val_if_fail (denom > 0, G_MAXUINT64);
542   g_return_val_if_fail (num >= 0, G_MAXUINT64);
543
544   if (num == 0)
545     return 0;
546
547   if (num == 1 && denom == 1)
548     return val;
549
550   if (val <= G_MAXUINT32)
551     /* simple case */
552     return val * num / denom;
553
554   /* do 96 bits mult/div */
555   low.ll = val;
556   result.ll = ((guint64) low.l.low) * num;
557   high.ll = ((guint64) low.l.high) * num + (result.l.high);
558
559   low.ll = high.ll / denom;
560   result.l.high = high.ll % denom;
561   result.ll /= denom;
562
563   /* avoid overflow */
564   if (low.ll + result.l.high > G_MAXUINT32)
565     goto overflow;
566
567   result.l.high += low.l.low;
568
569   return result.ll;
570
571 overflow:
572   {
573     return G_MAXUINT64;
574   }
575 }
576
577 /* -----------------------------------------------------
578  *
579  *  The following code will be moved out of the main
580  * gstreamer library someday.
581  */
582
583 #include "gstpad.h"
584
585 static void
586 string_append_indent (GString * str, gint count)
587 {
588   gint xx;
589
590   for (xx = 0; xx < count; xx++)
591     g_string_append_c (str, ' ');
592 }
593
594 /**
595  * gst_print_pad_caps:
596  * @buf: the buffer to print the caps in
597  * @indent: initial indentation
598  * @pad: the pad to print the caps from
599  *
600  * Write the pad capabilities in a human readable format into
601  * the given GString.
602  */
603 void
604 gst_print_pad_caps (GString * buf, gint indent, GstPad * pad)
605 {
606   GstCaps *caps;
607
608   caps = pad->caps;
609
610   if (!caps) {
611     string_append_indent (buf, indent);
612     g_string_printf (buf, "%s:%s has no capabilities",
613         GST_DEBUG_PAD_NAME (pad));
614   } else {
615     char *s;
616
617     s = gst_caps_to_string (caps);
618     g_string_append (buf, s);
619     g_free (s);
620   }
621 }
622
623 /**
624  * gst_print_element_args:
625  * @buf: the buffer to print the args in
626  * @indent: initial indentation
627  * @element: the element to print the args of
628  *
629  * Print the element argument in a human readable format in the given
630  * GString.
631  */
632 void
633 gst_print_element_args (GString * buf, gint indent, GstElement * element)
634 {
635   guint width;
636   GValue value = { 0, };        /* the important thing is that value.type = 0 */
637   gchar *str = NULL;
638   GParamSpec *spec, **specs, **walk;
639
640   specs = g_object_class_list_properties (G_OBJECT_GET_CLASS (element), NULL);
641
642   width = 0;
643   for (walk = specs; *walk; walk++) {
644     spec = *walk;
645     if (width < strlen (spec->name))
646       width = strlen (spec->name);
647   }
648
649   for (walk = specs; *walk; walk++) {
650     spec = *walk;
651
652     if (spec->flags & G_PARAM_READABLE) {
653       g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (spec));
654       g_object_get_property (G_OBJECT (element), spec->name, &value);
655       str = g_strdup_value_contents (&value);
656       g_value_unset (&value);
657     } else {
658       str = g_strdup ("Parameter not readable.");
659     }
660
661     string_append_indent (buf, indent);
662     g_string_append (buf, spec->name);
663     string_append_indent (buf, 2 + width - strlen (spec->name));
664     g_string_append (buf, str);
665     g_string_append_c (buf, '\n');
666
667     g_free (str);
668   }
669
670   g_free (specs);
671 }
672
673 /**
674  * gst_element_create_all_pads:
675  * @element: a #GstElement to create pads for
676  *
677  * Creates a pad for each pad template that is always available.
678  * This function is only useful during object intialization of
679  * subclasses of #GstElement.
680  */
681 void
682 gst_element_create_all_pads (GstElement * element)
683 {
684   GList *padlist;
685
686   /* FIXME: lock element */
687
688   padlist =
689       gst_element_class_get_pad_template_list (GST_ELEMENT_CLASS
690       (G_OBJECT_GET_CLASS (element)));
691
692   while (padlist) {
693     GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
694
695     if (padtempl->presence == GST_PAD_ALWAYS) {
696       GstPad *pad;
697
698       pad = gst_pad_new_from_template (padtempl, padtempl->name_template);
699
700       gst_element_add_pad (element, pad);
701     }
702     padlist = padlist->next;
703   }
704 }
705
706 /**
707  * gst_element_get_compatible_pad_template:
708  * @element: a #GstElement to get a compatible pad template for.
709  * @compattempl: the #GstPadTemplate to find a compatible template for.
710  *
711  * Retrieves a pad template from @element that is compatible with @compattempl.
712  * Pads from compatible templates can be linked together.
713  *
714  * Returns: a compatible #GstPadTemplate, or NULL if none was found. No
715  * unreferencing is necessary.
716  */
717 GstPadTemplate *
718 gst_element_get_compatible_pad_template (GstElement * element,
719     GstPadTemplate * compattempl)
720 {
721   GstPadTemplate *newtempl = NULL;
722   GList *padlist;
723   GstElementClass *class;
724
725   g_return_val_if_fail (element != NULL, NULL);
726   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
727   g_return_val_if_fail (compattempl != NULL, NULL);
728
729   class = GST_ELEMENT_GET_CLASS (element);
730
731   padlist = gst_element_class_get_pad_template_list (class);
732
733   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
734       "Looking for a suitable pad template in %s out of %d templates...",
735       GST_ELEMENT_NAME (element), g_list_length (padlist));
736
737   while (padlist) {
738     GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
739     GstCaps *intersection;
740
741     /* Ignore name
742      * Ignore presence
743      * Check direction (must be opposite)
744      * Check caps
745      */
746     GST_CAT_LOG (GST_CAT_CAPS,
747         "checking pad template %s", padtempl->name_template);
748     if (padtempl->direction != compattempl->direction) {
749       GST_CAT_DEBUG (GST_CAT_CAPS,
750           "compatible direction: found %s pad template \"%s\"",
751           padtempl->direction == GST_PAD_SRC ? "src" : "sink",
752           padtempl->name_template);
753
754       GST_CAT_DEBUG (GST_CAT_CAPS,
755           "intersecting %" GST_PTR_FORMAT, GST_PAD_TEMPLATE_CAPS (compattempl));
756       GST_CAT_DEBUG (GST_CAT_CAPS,
757           "..and %" GST_PTR_FORMAT, GST_PAD_TEMPLATE_CAPS (padtempl));
758
759       intersection = gst_caps_intersect (GST_PAD_TEMPLATE_CAPS (compattempl),
760           GST_PAD_TEMPLATE_CAPS (padtempl));
761
762       GST_CAT_DEBUG (GST_CAT_CAPS, "caps are %scompatible %" GST_PTR_FORMAT,
763           (intersection ? "" : "not "), intersection);
764
765       if (!gst_caps_is_empty (intersection))
766         newtempl = padtempl;
767       gst_caps_unref (intersection);
768       if (newtempl)
769         break;
770     }
771
772     padlist = g_list_next (padlist);
773   }
774   if (newtempl)
775     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
776         "Returning new pad template %p", newtempl);
777   else
778     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "No compatible pad template found");
779
780   return newtempl;
781 }
782
783 static GstPad *
784 gst_element_request_pad (GstElement * element, GstPadTemplate * templ,
785     const gchar * name)
786 {
787   GstPad *newpad = NULL;
788   GstElementClass *oclass;
789
790   oclass = GST_ELEMENT_GET_CLASS (element);
791
792   if (oclass->request_new_pad)
793     newpad = (oclass->request_new_pad) (element, templ, name);
794
795   if (newpad)
796     gst_object_ref (newpad);
797
798   return newpad;
799 }
800
801
802
803 /**
804  * gst_element_get_pad_from_template:
805  * @element: a #GstElement.
806  * @templ: a #GstPadTemplate belonging to @element.
807  *
808  * Gets a pad from @element described by @templ. If the presence of @templ is
809  * #GST_PAD_REQUEST, requests a new pad. Can return %NULL for #GST_PAD_SOMETIMES
810  * templates.
811  *
812  * Returns: the #GstPad, or NULL if one could not be found or created.
813  */
814 static GstPad *
815 gst_element_get_pad_from_template (GstElement * element, GstPadTemplate * templ)
816 {
817   GstPad *ret = NULL;
818   GstPadPresence presence;
819
820   /* If this function is ever exported, we need check the validity of `element'
821    * and `templ', and to make sure the template actually belongs to the
822    * element. */
823
824   presence = GST_PAD_TEMPLATE_PRESENCE (templ);
825
826   switch (presence) {
827     case GST_PAD_ALWAYS:
828     case GST_PAD_SOMETIMES:
829       ret = gst_element_get_static_pad (element, templ->name_template);
830       if (!ret && presence == GST_PAD_ALWAYS)
831         g_warning
832             ("Element %s has an ALWAYS template %s, but no pad of the same name",
833             GST_OBJECT_NAME (element), templ->name_template);
834       break;
835
836     case GST_PAD_REQUEST:
837       ret = gst_element_request_pad (element, templ, NULL);
838       break;
839   }
840
841   return ret;
842 }
843
844 /**
845  * gst_element_request_compatible_pad:
846  * @element: a #GstElement.
847  * @templ: the #GstPadTemplate to which the new pad should be able to link.
848  *
849  * Requests a pad from @element. The returned pad should be unlinked and
850  * compatible with @templ. Might return an existing pad, or request a new one.
851  *
852  * Returns: a #GstPad, or %NULL if one could not be found or created.
853  */
854 GstPad *
855 gst_element_request_compatible_pad (GstElement * element,
856     GstPadTemplate * templ)
857 {
858   GstPadTemplate *templ_new;
859   GstPad *pad = NULL;
860
861   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
862   g_return_val_if_fail (GST_IS_PAD_TEMPLATE (templ), NULL);
863
864   /* FIXME: should really loop through the templates, testing each for
865    *      compatibility and pad availability. */
866   templ_new = gst_element_get_compatible_pad_template (element, templ);
867   if (templ_new)
868     pad = gst_element_get_pad_from_template (element, templ_new);
869
870   /* This can happen for non-request pads. No need to unref. */
871   if (pad && GST_PAD_PEER (pad))
872     pad = NULL;
873
874   return pad;
875 }
876
877 /**
878  * gst_element_get_compatible_pad:
879  * @element: a #GstElement in which the pad should be found.
880  * @pad: the #GstPad to find a compatible one for.
881  * @caps: the #GstCaps to use as a filter.
882  *
883  * Looks for an unlinked pad to which the given pad can link. It is not
884  * guaranteed that linking the pads will work, though it should work in most
885  * cases.
886  *
887  * Returns: the #GstPad to which a link can be made, or %NULL if one cannot be
888  * found.
889  */
890 GstPad *
891 gst_element_get_compatible_pad (GstElement * element, GstPad * pad,
892     const GstCaps * caps)
893 {
894   GstIterator *pads;
895   GstPadTemplate *templ;
896   GstCaps *templcaps;
897   GstPad *foundpad = NULL;
898   gboolean done;
899
900   /* FIXME check for caps compatibility */
901
902   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
903   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
904
905   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
906       "finding pad in %s compatible with %s:%s",
907       GST_ELEMENT_NAME (element), GST_DEBUG_PAD_NAME (pad));
908
909   g_return_val_if_fail (GST_PAD_PEER (pad) == NULL, NULL);
910
911   done = FALSE;
912   /* try to get an existing unlinked pad */
913   pads = gst_element_iterate_pads (element);
914   while (!done) {
915     gpointer padptr;
916
917     switch (gst_iterator_next (pads, &padptr)) {
918       case GST_ITERATOR_OK:
919       {
920         GstPad *peer;
921         GstPad *current;
922
923         current = GST_PAD (padptr);
924
925         GST_CAT_LOG (GST_CAT_ELEMENT_PADS, "examining pad %s:%s",
926             GST_DEBUG_PAD_NAME (current));
927
928         peer = gst_pad_get_peer (current);
929
930         if (peer == NULL && gst_pad_can_link (pad, current)) {
931
932           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
933               "found existing unlinked pad %s:%s",
934               GST_DEBUG_PAD_NAME (current));
935
936           gst_iterator_free (pads);
937
938           return current;
939         } else {
940           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "unreffing pads");
941
942           gst_object_unref (current);
943           if (peer)
944             gst_object_unref (peer);
945         }
946         break;
947       }
948       case GST_ITERATOR_DONE:
949         done = TRUE;
950         break;
951       case GST_ITERATOR_RESYNC:
952         gst_iterator_resync (pads);
953         break;
954       case GST_ITERATOR_ERROR:
955         g_assert_not_reached ();
956         break;
957     }
958   }
959   gst_iterator_free (pads);
960
961   /* try to create a new one */
962   /* requesting is a little crazy, we need a template. Let's create one */
963   templcaps = gst_pad_get_caps (pad);
964
965   templ = gst_pad_template_new ((gchar *) GST_PAD_NAME (pad),
966       GST_PAD_DIRECTION (pad), GST_PAD_ALWAYS, templcaps);
967   foundpad = gst_element_request_compatible_pad (element, templ);
968   gst_object_unref (templ);
969
970   if (foundpad) {
971     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
972         "found existing request pad %s:%s", GST_DEBUG_PAD_NAME (foundpad));
973     return foundpad;
974   }
975
976   GST_CAT_INFO_OBJECT (GST_CAT_ELEMENT_PADS, element,
977       "Could not find a compatible pad to link to %s:%s",
978       GST_DEBUG_PAD_NAME (pad));
979   return NULL;
980 }
981
982 /**
983  * gst_element_state_get_name:
984  * @state: a #GstState to get the name of.
985  *
986  * Gets a string representing the given state.
987  *
988  * Returns: a string with the name of the state.
989  */
990 const gchar *
991 gst_element_state_get_name (GstState state)
992 {
993   switch (state) {
994 #ifdef GST_DEBUG_COLOR
995     case GST_STATE_VOID_PENDING:
996       return "VOID_PENDING";
997       break;
998     case GST_STATE_NULL:
999       return "\033[01;34mNULL\033[00m";
1000       break;
1001     case GST_STATE_READY:
1002       return "\033[01;31mREADY\033[00m";
1003       break;
1004     case GST_STATE_PLAYING:
1005       return "\033[01;32mPLAYING\033[00m";
1006       break;
1007     case GST_STATE_PAUSED:
1008       return "\033[01;33mPAUSED\033[00m";
1009       break;
1010     default:
1011       /* This is a memory leak */
1012       return g_strdup_printf ("\033[01;35;41mUNKNOWN!\033[00m(%d)", state);
1013 #else
1014     case GST_STATE_VOID_PENDING:
1015       return "VOID_PENDING";
1016       break;
1017     case GST_STATE_NULL:
1018       return "NULL";
1019       break;
1020     case GST_STATE_READY:
1021       return "READY";
1022       break;
1023     case GST_STATE_PLAYING:
1024       return "PLAYING";
1025       break;
1026     case GST_STATE_PAUSED:
1027       return "PAUSED";
1028       break;
1029     default:
1030       /* This is a memory leak */
1031       return g_strdup_printf ("UNKNOWN!(%d)", state);
1032 #endif
1033   }
1034   return "";
1035 }
1036
1037 /**
1038  * gst_element_factory_can_src_caps :
1039  * @factory: factory to query
1040  * @caps: the caps to check
1041  *
1042  * Checks if the factory can source the given capability.
1043  *
1044  * Returns: true if it can src the capabilities
1045  */
1046 gboolean
1047 gst_element_factory_can_src_caps (GstElementFactory * factory,
1048     const GstCaps * caps)
1049 {
1050   GList *templates;
1051
1052   g_return_val_if_fail (factory != NULL, FALSE);
1053   g_return_val_if_fail (caps != NULL, FALSE);
1054
1055   templates = factory->staticpadtemplates;
1056
1057   while (templates) {
1058     GstStaticPadTemplate *template = (GstStaticPadTemplate *) templates->data;
1059
1060     if (template->direction == GST_PAD_SRC) {
1061       if (gst_caps_is_always_compatible (gst_static_caps_get (&template->
1062                   static_caps), caps))
1063         return TRUE;
1064     }
1065     templates = g_list_next (templates);
1066   }
1067
1068   return FALSE;
1069 }
1070
1071 /**
1072  * gst_element_factory_can_sink_caps :
1073  * @factory: factory to query
1074  * @caps: the caps to check
1075  *
1076  * Checks if the factory can sink the given capability.
1077  *
1078  * Returns: true if it can sink the capabilities
1079  */
1080 gboolean
1081 gst_element_factory_can_sink_caps (GstElementFactory * factory,
1082     const GstCaps * caps)
1083 {
1084   GList *templates;
1085
1086   g_return_val_if_fail (factory != NULL, FALSE);
1087   g_return_val_if_fail (caps != NULL, FALSE);
1088
1089   templates = factory->staticpadtemplates;
1090
1091   while (templates) {
1092     GstStaticPadTemplate *template = (GstStaticPadTemplate *) templates->data;
1093
1094     if (template->direction == GST_PAD_SINK) {
1095       if (gst_caps_is_always_compatible (caps,
1096               gst_static_caps_get (&template->static_caps)))
1097         return TRUE;
1098     }
1099     templates = g_list_next (templates);
1100   }
1101
1102   return FALSE;
1103 }
1104
1105
1106 /* if return val is true, *direct_child is a caller-owned ref on the direct
1107  * child of ancestor that is part of object's ancestry */
1108 static gboolean
1109 object_has_ancestor (GstObject * object, GstObject * ancestor,
1110     GstObject ** direct_child)
1111 {
1112   GstObject *child, *parent;
1113
1114   if (direct_child)
1115     *direct_child = NULL;
1116
1117   child = gst_object_ref (object);
1118   parent = gst_object_get_parent (object);
1119
1120   while (parent) {
1121     if (ancestor == parent) {
1122       if (direct_child)
1123         *direct_child = child;
1124       else
1125         gst_object_unref (child);
1126       gst_object_unref (parent);
1127       return TRUE;
1128     }
1129
1130     gst_object_unref (child);
1131     child = parent;
1132     parent = gst_object_get_parent (parent);
1133   }
1134
1135   gst_object_unref (child);
1136
1137   return FALSE;
1138 }
1139
1140 /* caller owns return */
1141 static GstObject *
1142 find_common_root (GstObject * o1, GstObject * o2)
1143 {
1144   GstObject *top = o1;
1145   GstObject *kid1, *kid2;
1146   GstObject *root = NULL;
1147
1148   while (GST_OBJECT_PARENT (top))
1149     top = GST_OBJECT_PARENT (top);
1150
1151   /* the itsy-bitsy spider... */
1152
1153   if (!object_has_ancestor (o2, top, &kid2))
1154     return NULL;
1155
1156   root = gst_object_ref (top);
1157   while (TRUE) {
1158     if (!object_has_ancestor (o1, kid2, &kid1)) {
1159       gst_object_unref (kid2);
1160       return root;
1161     }
1162     root = kid2;
1163     if (!object_has_ancestor (o2, kid1, &kid2)) {
1164       gst_object_unref (kid1);
1165       return root;
1166     }
1167     root = kid1;
1168   }
1169 }
1170
1171 /* caller does not own return */
1172 static GstPad *
1173 ghost_up (GstElement * e, GstPad * pad)
1174 {
1175   static gint ghost_pad_index = 0;
1176   GstPad *gpad;
1177   gchar *name;
1178   GstObject *parent = GST_OBJECT_PARENT (e);
1179
1180   name = g_strdup_printf ("ghost%d", ghost_pad_index++);
1181   gpad = gst_ghost_pad_new (name, pad);
1182   g_free (name);
1183
1184   if (!gst_element_add_pad ((GstElement *) parent, gpad)) {
1185     g_warning ("Pad named %s already exists in element %s\n",
1186         GST_OBJECT_NAME (gpad), GST_OBJECT_NAME (parent));
1187     gst_object_unref ((GstObject *) gpad);
1188     return NULL;
1189   }
1190
1191   return gpad;
1192 }
1193
1194 static void
1195 remove_pad (gpointer ppad, gpointer unused)
1196 {
1197   GstPad *pad = ppad;
1198
1199   if (!gst_element_remove_pad ((GstElement *) GST_OBJECT_PARENT (pad), pad))
1200     g_warning ("Couldn't remove pad %s from element %s",
1201         GST_OBJECT_NAME (pad), GST_OBJECT_NAME (GST_OBJECT_PARENT (pad)));
1202 }
1203
1204 static gboolean
1205 prepare_link_maybe_ghosting (GstPad ** src, GstPad ** sink,
1206     GSList ** pads_created)
1207 {
1208   GstObject *root;
1209   GstObject *e1, *e2;
1210   GSList *pads_created_local = NULL;
1211
1212   g_assert (pads_created);
1213
1214   e1 = GST_OBJECT_PARENT (*src);
1215   e2 = GST_OBJECT_PARENT (*sink);
1216
1217   if (GST_OBJECT_PARENT (e1) == GST_OBJECT_PARENT (e2)) {
1218     GST_CAT_INFO (GST_CAT_PADS, "%s and %s in same bin, no need for ghost pads",
1219         GST_OBJECT_NAME (e1), GST_OBJECT_NAME (e2));
1220     return TRUE;
1221   }
1222
1223   GST_CAT_INFO (GST_CAT_PADS, "%s and %s not in same bin, making ghost pads",
1224       GST_OBJECT_NAME (e1), GST_OBJECT_NAME (e2));
1225
1226   /* we need to setup some ghost pads */
1227   root = find_common_root (e1, e2);
1228   if (!root) {
1229     g_warning
1230         ("Trying to connect elements that don't share a common ancestor: %s and %s\n",
1231         GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (e2));
1232     return FALSE;
1233   }
1234
1235   while (GST_OBJECT_PARENT (e1) != root) {
1236     *src = ghost_up ((GstElement *) e1, *src);
1237     if (!*src)
1238       goto cleanup_fail;
1239     e1 = GST_OBJECT_PARENT (*src);
1240     pads_created_local = g_slist_prepend (pads_created_local, *src);
1241   }
1242   while (GST_OBJECT_PARENT (e2) != root) {
1243     *sink = ghost_up ((GstElement *) e2, *sink);
1244     if (!*sink)
1245       goto cleanup_fail;
1246     e2 = GST_OBJECT_PARENT (*sink);
1247     pads_created_local = g_slist_prepend (pads_created_local, *sink);
1248   }
1249
1250   gst_object_unref (root);
1251   *pads_created = g_slist_concat (*pads_created, pads_created_local);
1252   return TRUE;
1253
1254 cleanup_fail:
1255   gst_object_unref (root);
1256   g_slist_foreach (pads_created_local, remove_pad, NULL);
1257   g_slist_free (pads_created_local);
1258   return FALSE;
1259 }
1260
1261 static gboolean
1262 pad_link_maybe_ghosting (GstPad * src, GstPad * sink)
1263 {
1264   GSList *pads_created = NULL;
1265   gboolean ret;
1266
1267   if (!prepare_link_maybe_ghosting (&src, &sink, &pads_created)) {
1268     ret = FALSE;
1269   } else {
1270     ret = (gst_pad_link (src, sink) == GST_PAD_LINK_OK);
1271   }
1272
1273   if (!ret) {
1274     g_slist_foreach (pads_created, remove_pad, NULL);
1275   }
1276   g_slist_free (pads_created);
1277
1278   return ret;
1279 }
1280
1281 /**
1282  * gst_element_link_pads:
1283  * @src: a #GstElement containing the source pad.
1284  * @srcpadname: the name of the #GstPad in source element or NULL for any pad.
1285  * @dest: the #GstElement containing the destination pad.
1286  * @destpadname: the name of the #GstPad in destination element,
1287  * or NULL for any pad.
1288  *
1289  * Links the two named pads of the source and destination elements.
1290  * Side effect is that if one of the pads has no parent, it becomes a
1291  * child of the parent of the other element.  If they have different
1292  * parents, the link fails.
1293  *
1294  * Returns: TRUE if the pads could be linked, FALSE otherwise.
1295  */
1296 gboolean
1297 gst_element_link_pads (GstElement * src, const gchar * srcpadname,
1298     GstElement * dest, const gchar * destpadname)
1299 {
1300   const GList *srcpads, *destpads, *srctempls, *desttempls, *l;
1301   GstPad *srcpad, *destpad;
1302   GstPadTemplate *srctempl, *desttempl;
1303   GstElementClass *srcclass, *destclass;
1304
1305   /* checks */
1306   g_return_val_if_fail (GST_IS_ELEMENT (src), FALSE);
1307   g_return_val_if_fail (GST_IS_ELEMENT (dest), FALSE);
1308
1309   srcclass = GST_ELEMENT_GET_CLASS (src);
1310   destclass = GST_ELEMENT_GET_CLASS (dest);
1311
1312   GST_CAT_INFO (GST_CAT_ELEMENT_PADS,
1313       "trying to link element %s:%s to element %s:%s", GST_ELEMENT_NAME (src),
1314       srcpadname ? srcpadname : "(any)", GST_ELEMENT_NAME (dest),
1315       destpadname ? destpadname : "(any)");
1316
1317   /* get a src pad */
1318   if (srcpadname) {
1319     /* name specified, look it up */
1320     srcpad = gst_element_get_pad (src, srcpadname);
1321     if (!srcpad) {
1322       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no pad %s:%s",
1323           GST_ELEMENT_NAME (src), srcpadname);
1324       return FALSE;
1325     } else {
1326       if (!(GST_PAD_DIRECTION (srcpad) == GST_PAD_SRC)) {
1327         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is no src pad",
1328             GST_DEBUG_PAD_NAME (srcpad));
1329         gst_object_unref (srcpad);
1330         return FALSE;
1331       }
1332       if (GST_PAD_PEER (srcpad) != NULL) {
1333         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is already linked",
1334             GST_DEBUG_PAD_NAME (srcpad));
1335         gst_object_unref (srcpad);
1336         return FALSE;
1337       }
1338     }
1339     srcpads = NULL;
1340   } else {
1341     /* no name given, get the first available pad */
1342     GST_OBJECT_LOCK (src);
1343     srcpads = GST_ELEMENT_PADS (src);
1344     srcpad = srcpads ? GST_PAD_CAST (srcpads->data) : NULL;
1345     if (srcpad)
1346       gst_object_ref (srcpad);
1347     GST_OBJECT_UNLOCK (src);
1348   }
1349
1350   /* get a destination pad */
1351   if (destpadname) {
1352     /* name specified, look it up */
1353     destpad = gst_element_get_pad (dest, destpadname);
1354     if (!destpad) {
1355       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no pad %s:%s",
1356           GST_ELEMENT_NAME (dest), destpadname);
1357       return FALSE;
1358     } else {
1359       if (!(GST_PAD_DIRECTION (destpad) == GST_PAD_SINK)) {
1360         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is no sink pad",
1361             GST_DEBUG_PAD_NAME (destpad));
1362         gst_object_unref (destpad);
1363         return FALSE;
1364       }
1365       if (GST_PAD_PEER (destpad) != NULL) {
1366         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is already linked",
1367             GST_DEBUG_PAD_NAME (destpad));
1368         gst_object_unref (destpad);
1369         return FALSE;
1370       }
1371     }
1372     destpads = NULL;
1373   } else {
1374     /* no name given, get the first available pad */
1375     GST_OBJECT_LOCK (dest);
1376     destpads = GST_ELEMENT_PADS (dest);
1377     destpad = destpads ? GST_PAD_CAST (destpads->data) : NULL;
1378     if (destpad)
1379       gst_object_ref (destpad);
1380     GST_OBJECT_UNLOCK (dest);
1381   }
1382
1383   if (srcpadname && destpadname) {
1384     gboolean result;
1385
1386     /* two explicitly specified pads */
1387     result = pad_link_maybe_ghosting (srcpad, destpad);
1388
1389     gst_object_unref (srcpad);
1390     gst_object_unref (destpad);
1391
1392     return result;
1393   }
1394
1395   if (srcpad) {
1396     /* loop through the allowed pads in the source, trying to find a
1397      * compatible destination pad */
1398     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1399         "looping through allowed src and dest pads");
1400     do {
1401       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "trying src pad %s:%s",
1402           GST_DEBUG_PAD_NAME (srcpad));
1403       if ((GST_PAD_DIRECTION (srcpad) == GST_PAD_SRC) &&
1404           (GST_PAD_PEER (srcpad) == NULL)) {
1405         GstPad *temp;
1406
1407         if (destpadname) {
1408           temp = destpad;
1409           gst_object_ref (temp);
1410         } else {
1411           temp = gst_element_get_compatible_pad (dest, srcpad, NULL);
1412         }
1413
1414         if (temp && pad_link_maybe_ghosting (srcpad, temp)) {
1415           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "linked pad %s:%s to pad %s:%s",
1416               GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (temp));
1417           if (destpad)
1418             gst_object_unref (destpad);
1419           gst_object_unref (srcpad);
1420           gst_object_unref (temp);
1421           return TRUE;
1422         }
1423
1424         if (temp) {
1425           gst_object_unref (temp);
1426         }
1427       }
1428       /* find a better way for this mess */
1429       if (srcpads) {
1430         srcpads = g_list_next (srcpads);
1431         if (srcpads) {
1432           gst_object_unref (srcpad);
1433           srcpad = GST_PAD_CAST (srcpads->data);
1434           gst_object_ref (srcpad);
1435         }
1436       }
1437     } while (srcpads);
1438   }
1439   if (srcpadname) {
1440     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s:%s to %s",
1441         GST_DEBUG_PAD_NAME (srcpad), GST_ELEMENT_NAME (dest));
1442     if (destpad)
1443       gst_object_unref (destpad);
1444     destpad = NULL;
1445   }
1446   if (srcpad)
1447     gst_object_unref (srcpad);
1448   srcpad = NULL;
1449
1450   if (destpad) {
1451     /* loop through the existing pads in the destination */
1452     do {
1453       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "trying dest pad %s:%s",
1454           GST_DEBUG_PAD_NAME (destpad));
1455       if ((GST_PAD_DIRECTION (destpad) == GST_PAD_SINK) &&
1456           (GST_PAD_PEER (destpad) == NULL)) {
1457         GstPad *temp = gst_element_get_compatible_pad (src, destpad, NULL);
1458
1459         if (temp && pad_link_maybe_ghosting (temp, destpad)) {
1460           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "linked pad %s:%s to pad %s:%s",
1461               GST_DEBUG_PAD_NAME (temp), GST_DEBUG_PAD_NAME (destpad));
1462           gst_object_unref (temp);
1463           gst_object_unref (destpad);
1464           return TRUE;
1465         }
1466         if (temp) {
1467           gst_object_unref (temp);
1468         }
1469       }
1470       if (destpads) {
1471         destpads = g_list_next (destpads);
1472         if (destpads) {
1473           gst_object_unref (destpad);
1474           destpad = GST_PAD_CAST (destpads->data);
1475           gst_object_ref (destpad);
1476         }
1477       }
1478     } while (destpads);
1479   }
1480
1481   if (destpadname) {
1482     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s to %s:%s",
1483         GST_ELEMENT_NAME (src), GST_DEBUG_PAD_NAME (destpad));
1484     gst_object_unref (destpad);
1485     if (srcpad)
1486       gst_object_unref (srcpad);
1487     return FALSE;
1488   } else {
1489     if (srcpad)
1490       gst_object_unref (srcpad);
1491     srcpad = NULL;
1492     if (destpad)
1493       gst_object_unref (destpad);
1494     destpad = NULL;
1495   }
1496
1497   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1498       "we might have request pads on both sides, checking...");
1499   srctempls = gst_element_class_get_pad_template_list (srcclass);
1500   desttempls = gst_element_class_get_pad_template_list (destclass);
1501
1502   if (srctempls && desttempls) {
1503     while (srctempls) {
1504       srctempl = (GstPadTemplate *) srctempls->data;
1505       if (srctempl->presence == GST_PAD_REQUEST) {
1506         for (l = desttempls; l; l = l->next) {
1507           desttempl = (GstPadTemplate *) l->data;
1508           if (desttempl->presence == GST_PAD_REQUEST &&
1509               desttempl->direction != srctempl->direction) {
1510             if (gst_caps_is_always_compatible (gst_pad_template_get_caps
1511                     (srctempl), gst_pad_template_get_caps (desttempl))) {
1512               srcpad =
1513                   gst_element_get_request_pad (src, srctempl->name_template);
1514               destpad =
1515                   gst_element_get_request_pad (dest, desttempl->name_template);
1516               if (pad_link_maybe_ghosting (srcpad, destpad)) {
1517                 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1518                     "linked pad %s:%s to pad %s:%s",
1519                     GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (destpad));
1520                 gst_object_unref (srcpad);
1521                 gst_object_unref (destpad);
1522                 return TRUE;
1523               }
1524               /* it failed, so we release the request pads */
1525               gst_element_release_request_pad (src, srcpad);
1526               gst_element_release_request_pad (dest, destpad);
1527             }
1528           }
1529         }
1530       }
1531       srctempls = srctempls->next;
1532     }
1533   }
1534
1535   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s to %s",
1536       GST_ELEMENT_NAME (src), GST_ELEMENT_NAME (dest));
1537   return FALSE;
1538 }
1539
1540 /**
1541  * gst_element_link_pads_filtered:
1542  * @src: a #GstElement containing the source pad.
1543  * @srcpadname: the name of the #GstPad in source element or NULL for any pad.
1544  * @dest: the #GstElement containing the destination pad.
1545  * @destpadname: the name of the #GstPad in destination element or NULL for any pad.
1546  * @filter: the #GstCaps to filter the link, or #NULL for no filter.
1547  *
1548  * Links the two named pads of the source and destination elements. Side effect
1549  * is that if one of the pads has no parent, it becomes a child of the parent of
1550  * the other element. If they have different parents, the link fails. If @caps
1551  * is not #NULL, makes sure that the caps of the link is a subset of @caps.
1552  *
1553  * Returns: TRUE if the pads could be linked, FALSE otherwise.
1554  */
1555 gboolean
1556 gst_element_link_pads_filtered (GstElement * src, const gchar * srcpadname,
1557     GstElement * dest, const gchar * destpadname, GstCaps * filter)
1558 {
1559   /* checks */
1560   g_return_val_if_fail (GST_IS_ELEMENT (src), FALSE);
1561   g_return_val_if_fail (GST_IS_ELEMENT (dest), FALSE);
1562   g_return_val_if_fail (filter == NULL || GST_IS_CAPS (filter), FALSE);
1563
1564   if (filter) {
1565     GstElement *capsfilter;
1566     GstObject *parent;
1567     GstState state, pending;
1568
1569     capsfilter = gst_element_factory_make ("capsfilter", NULL);
1570     if (!capsfilter) {
1571       GST_ERROR ("Could not make a capsfilter");
1572       return FALSE;
1573     }
1574
1575     parent = gst_object_get_parent (GST_OBJECT (src));
1576     g_return_val_if_fail (GST_IS_BIN (parent), FALSE);
1577
1578     gst_element_get_state (GST_ELEMENT_CAST (parent), &state, &pending, 0);
1579
1580     if (!gst_bin_add (GST_BIN (parent), capsfilter)) {
1581       GST_ERROR ("Could not add capsfilter");
1582       gst_object_unref (capsfilter);
1583       gst_object_unref (parent);
1584       return FALSE;
1585     }
1586
1587     if (pending != GST_STATE_VOID_PENDING)
1588       state = pending;
1589
1590     gst_element_set_state (capsfilter, state);
1591
1592     gst_object_unref (parent);
1593
1594     g_object_set (capsfilter, "caps", filter, NULL);
1595
1596     if (gst_element_link_pads (src, srcpadname, capsfilter, "sink")
1597         && gst_element_link_pads (capsfilter, "src", dest, destpadname)) {
1598       return TRUE;
1599     } else {
1600       GST_INFO ("Could not link elements");
1601       gst_bin_remove (GST_BIN (GST_OBJECT_PARENT (capsfilter)), capsfilter);
1602       /* will unref and unlink as appropriate */
1603       return FALSE;
1604     }
1605   } else {
1606     return gst_element_link_pads (src, srcpadname, dest, destpadname);
1607   }
1608 }
1609
1610 /**
1611  * gst_element_link:
1612  * @src: a #GstElement containing the source pad.
1613  * @dest: the #GstElement containing the destination pad.
1614  *
1615  * Links @src to @dest. The link must be from source to
1616  * destination; the other direction will not be tried. The function looks for
1617  * existing pads that aren't linked yet. It will request new pads if necessary.
1618  * If multiple links are possible, only one is established.
1619  *
1620  * Returns: TRUE if the elements could be linked, FALSE otherwise.
1621  */
1622 gboolean
1623 gst_element_link (GstElement * src, GstElement * dest)
1624 {
1625   return gst_element_link_pads_filtered (src, NULL, dest, NULL, NULL);
1626 }
1627
1628 /**
1629  * gst_element_link_many:
1630  * @element_1: the first #GstElement in the link chain.
1631  * @element_2: the second #GstElement in the link chain.
1632  * @...: the NULL-terminated list of elements to link in order.
1633  *
1634  * Chain together a series of elements. Uses gst_element_link().
1635  *
1636  * Returns: TRUE on success, FALSE otherwise.
1637  */
1638 gboolean
1639 gst_element_link_many (GstElement * element_1, GstElement * element_2, ...)
1640 {
1641   va_list args;
1642
1643   g_return_val_if_fail (GST_IS_ELEMENT (element_1), FALSE);
1644   g_return_val_if_fail (GST_IS_ELEMENT (element_2), FALSE);
1645
1646   va_start (args, element_2);
1647
1648   while (element_2) {
1649     if (!gst_element_link (element_1, element_2))
1650       return FALSE;
1651
1652     element_1 = element_2;
1653     element_2 = va_arg (args, GstElement *);
1654   }
1655
1656   va_end (args);
1657
1658   return TRUE;
1659 }
1660
1661 /**
1662  * gst_element_link_filtered:
1663  * @src: a #GstElement containing the source pad.
1664  * @dest: the #GstElement containing the destination pad.
1665  * @filter: the #GstCaps to filter the link, or #NULL for no filter.
1666  *
1667  * Links @src to @dest using the given caps as filtercaps.
1668  * The link must be from source to
1669  * destination; the other direction will not be tried. The function looks for
1670  * existing pads that aren't linked yet. It will request new pads if necessary.
1671  * If multiple links are possible, only one is established.
1672  *
1673  * Returns: TRUE if the pads could be linked, FALSE otherwise.
1674  */
1675 gboolean
1676 gst_element_link_filtered (GstElement * src, GstElement * dest,
1677     GstCaps * filter)
1678 {
1679   return gst_element_link_pads_filtered (src, NULL, dest, NULL, filter);
1680 }
1681
1682 /**
1683  * gst_element_unlink_pads:
1684  * @src: a #GstElement containing the source pad.
1685  * @srcpadname: the name of the #GstPad in source element.
1686  * @dest: a #GstElement containing the destination pad.
1687  * @destpadname: the name of the #GstPad in destination element.
1688  *
1689  * Unlinks the two named pads of the source and destination elements.
1690  */
1691 void
1692 gst_element_unlink_pads (GstElement * src, const gchar * srcpadname,
1693     GstElement * dest, const gchar * destpadname)
1694 {
1695   GstPad *srcpad, *destpad;
1696
1697   g_return_if_fail (src != NULL);
1698   g_return_if_fail (GST_IS_ELEMENT (src));
1699   g_return_if_fail (srcpadname != NULL);
1700   g_return_if_fail (dest != NULL);
1701   g_return_if_fail (GST_IS_ELEMENT (dest));
1702   g_return_if_fail (destpadname != NULL);
1703
1704   /* obtain the pads requested */
1705   srcpad = gst_element_get_pad (src, srcpadname);
1706   if (srcpad == NULL) {
1707     GST_WARNING_OBJECT (src, "source element has no pad \"%s\"", srcpadname);
1708     return;
1709   }
1710   destpad = gst_element_get_pad (dest, destpadname);
1711   if (destpad == NULL) {
1712     GST_WARNING_OBJECT (dest, "destination element has no pad \"%s\"",
1713         destpadname);
1714     gst_object_unref (srcpad);
1715     return;
1716   }
1717
1718   /* we're satisified they can be unlinked, let's do it */
1719   gst_pad_unlink (srcpad, destpad);
1720   gst_object_unref (srcpad);
1721   gst_object_unref (destpad);
1722 }
1723
1724 /**
1725  * gst_element_unlink_many:
1726  * @element_1: the first #GstElement in the link chain.
1727  * @element_2: the second #GstElement in the link chain.
1728  * @...: the NULL-terminated list of elements to unlink in order.
1729  *
1730  * Unlinks a series of elements. Uses gst_element_unlink().
1731  */
1732 void
1733 gst_element_unlink_many (GstElement * element_1, GstElement * element_2, ...)
1734 {
1735   va_list args;
1736
1737   g_return_if_fail (element_1 != NULL && element_2 != NULL);
1738   g_return_if_fail (GST_IS_ELEMENT (element_1) && GST_IS_ELEMENT (element_2));
1739
1740   va_start (args, element_2);
1741
1742   while (element_2) {
1743     gst_element_unlink (element_1, element_2);
1744
1745     element_1 = element_2;
1746     element_2 = va_arg (args, GstElement *);
1747   }
1748
1749   va_end (args);
1750 }
1751
1752 /**
1753  * gst_element_unlink:
1754  * @src: the source #GstElement to unlink.
1755  * @dest: the sink #GstElement to unlink.
1756  *
1757  * Unlinks all source pads of the source element with all sink pads
1758  * of the sink element to which they are linked.
1759  */
1760 void
1761 gst_element_unlink (GstElement * src, GstElement * dest)
1762 {
1763   GstIterator *pads;
1764   gboolean done = FALSE;
1765
1766   g_return_if_fail (GST_IS_ELEMENT (src));
1767   g_return_if_fail (GST_IS_ELEMENT (dest));
1768
1769   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "unlinking \"%s\" and \"%s\"",
1770       GST_ELEMENT_NAME (src), GST_ELEMENT_NAME (dest));
1771
1772   pads = gst_element_iterate_pads (src);
1773   while (!done) {
1774     gpointer data;
1775
1776     switch (gst_iterator_next (pads, &data)) {
1777       case GST_ITERATOR_OK:
1778       {
1779         GstPad *pad = GST_PAD_CAST (data);
1780
1781         if (GST_PAD_IS_SRC (pad)) {
1782           GstPad *peerpad = gst_pad_get_peer (pad);
1783
1784           /* see if the pad is connected and is really a pad
1785            * of dest */
1786           if (peerpad) {
1787             GstElement *peerelem;
1788
1789             peerelem = gst_pad_get_parent_element (peerpad);
1790
1791             if (peerelem == dest) {
1792               gst_pad_unlink (pad, peerpad);
1793             }
1794             if (peerelem)
1795               gst_object_unref (peerelem);
1796
1797             gst_object_unref (peerpad);
1798           }
1799         }
1800         gst_object_unref (pad);
1801         break;
1802       }
1803       case GST_ITERATOR_RESYNC:
1804         gst_iterator_resync (pads);
1805         break;
1806       case GST_ITERATOR_DONE:
1807         done = TRUE;
1808         break;
1809       default:
1810         g_assert_not_reached ();
1811         break;
1812     }
1813   }
1814 }
1815
1816 /**
1817  * gst_element_query_position:
1818  * @element: a #GstElement to invoke the position query on.
1819  * @format: a pointer to the #GstFormat asked for.
1820  *          On return contains the #GstFormat used.
1821  * @cur: A location in which to store the current position, or NULL.
1822  *
1823  * Queries an element for the stream position.
1824  *
1825  * Returns: TRUE if the query could be performed.
1826  */
1827 gboolean
1828 gst_element_query_position (GstElement * element, GstFormat * format,
1829     gint64 * cur)
1830 {
1831   GstQuery *query;
1832   gboolean ret;
1833
1834   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1835   g_return_val_if_fail (format != NULL, FALSE);
1836
1837   query = gst_query_new_position (*format);
1838   ret = gst_element_query (element, query);
1839
1840   if (ret)
1841     gst_query_parse_position (query, format, cur);
1842
1843   gst_query_unref (query);
1844
1845   return ret;
1846 }
1847
1848 /**
1849  * gst_element_query_duration:
1850  * @element: a #GstElement to invoke the duration query on.
1851  * @format: a pointer to the #GstFormat asked for.
1852  *          On return contains the #GstFormat used.
1853  * @duration: A location in which to store the total duration, or NULL.
1854  *
1855  * Queries an element for the total stream duration.
1856  *
1857  * Returns: TRUE if the query could be performed.
1858  */
1859 gboolean
1860 gst_element_query_duration (GstElement * element, GstFormat * format,
1861     gint64 * duration)
1862 {
1863   GstQuery *query;
1864   gboolean ret;
1865
1866   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1867   g_return_val_if_fail (format != NULL, FALSE);
1868
1869   query = gst_query_new_duration (*format);
1870   ret = gst_element_query (element, query);
1871
1872   if (ret)
1873     gst_query_parse_duration (query, format, duration);
1874
1875   gst_query_unref (query);
1876
1877   return ret;
1878 }
1879
1880 /**
1881  * gst_element_query_convert:
1882  * @element: a #GstElement to invoke the convert query on.
1883  * @src_format: a #GstFormat to convert from.
1884  * @src_val: a value to convert.
1885  * @dest_format: a pointer to the #GstFormat to convert to.
1886  * @dest_val: a pointer to the result.
1887  *
1888  * Queries an element to convert @src_val in @src_format to @dest_format.
1889  *
1890  * Returns: TRUE if the query could be performed.
1891  */
1892 gboolean
1893 gst_element_query_convert (GstElement * element, GstFormat src_format,
1894     gint64 src_val, GstFormat * dest_format, gint64 * dest_val)
1895 {
1896   GstQuery *query;
1897   gboolean ret;
1898
1899   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1900   g_return_val_if_fail (dest_format != NULL, FALSE);
1901   g_return_val_if_fail (dest_val != NULL, FALSE);
1902
1903   if (*dest_format == src_format) {
1904     *dest_val = src_val;
1905     return TRUE;
1906   }
1907
1908   query = gst_query_new_convert (src_format, src_val, *dest_format);
1909   ret = gst_element_query (element, query);
1910
1911   if (ret)
1912     gst_query_parse_convert (query, NULL, NULL, dest_format, dest_val);
1913
1914   gst_query_unref (query);
1915
1916   return ret;
1917 }
1918
1919 /**
1920  * gst_element_seek_simple
1921  * @element: a #GstElement to seek on
1922  * @format: a #GstFormat to execute the seek in, such as #GST_FORMAT_TIME
1923  * @seek_flags: seek options
1924  * @seek_pos: position to seek to (relative to the start); if you are doing
1925  *            a seek in #GST_FORMAT_TIME this value is in nanoseconds -
1926  *            multiply with #GST_SECOND to convert seconds to nanoseconds or
1927  *            with #GST_MSECOND to convert milliseconds to nanoseconds.
1928  *
1929  * Simple API to perform a seek on the given element, meaning it just seeks
1930  * to the given position relative to the start of the stream. For more complex
1931  * operations like segment seeks (e.g. for looping) or changing the playback
1932  * rate or seeking relative to the current position or seeking relative to
1933  * the end of the stream you should use gst_element_seek ().
1934  *
1935  * Note that seeking is usually only possible in PAUSED or PLAYING state.
1936  *
1937  * Returns: TRUE if the seek operation succeeded (the seek
1938  *          might not always be executed instantly though)
1939  *
1940  * Since: 0.10.7
1941  */
1942 gboolean
1943 gst_element_seek_simple (GstElement * element, GstFormat format,
1944     GstSeekFlags seek_flags, gint64 seek_pos)
1945 {
1946   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1947   g_return_val_if_fail (seek_pos >= 0, FALSE);
1948
1949   return gst_element_seek (element, 1.0, format, seek_flags,
1950       GST_SEEK_TYPE_SET, seek_pos, GST_SEEK_TYPE_NONE, 0);
1951 }
1952
1953 /**
1954  * gst_pad_can_link:
1955  * @srcpad: the source #GstPad to link.
1956  * @sinkpad: the sink #GstPad to link.
1957  *
1958  * Checks if the source pad and the sink pad can be linked.
1959  * Both @srcpad and @sinkpad must be unlinked.
1960  *
1961  * Returns: TRUE if the pads can be linked, FALSE otherwise.
1962  */
1963 gboolean
1964 gst_pad_can_link (GstPad * srcpad, GstPad * sinkpad)
1965 {
1966   /* FIXME This function is gross.  It's almost a direct copy of
1967    * gst_pad_link_filtered().  Any decent programmer would attempt
1968    * to merge the two functions, which I will do some day. --ds
1969    */
1970
1971   /* generic checks */
1972   g_return_val_if_fail (GST_IS_PAD (srcpad), FALSE);
1973   g_return_val_if_fail (GST_IS_PAD (sinkpad), FALSE);
1974
1975   GST_CAT_INFO (GST_CAT_PADS, "trying to link %s:%s and %s:%s",
1976       GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (sinkpad));
1977
1978   /* FIXME: shouldn't we convert this to g_return_val_if_fail? */
1979   if (GST_PAD_PEER (srcpad) != NULL) {
1980     GST_CAT_INFO (GST_CAT_PADS, "Source pad %s:%s has a peer, failed",
1981         GST_DEBUG_PAD_NAME (srcpad));
1982     return FALSE;
1983   }
1984   if (GST_PAD_PEER (sinkpad) != NULL) {
1985     GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s has a peer, failed",
1986         GST_DEBUG_PAD_NAME (sinkpad));
1987     return FALSE;
1988   }
1989   if (!GST_PAD_IS_SRC (srcpad)) {
1990     GST_CAT_INFO (GST_CAT_PADS, "Src pad %s:%s is not source pad, failed",
1991         GST_DEBUG_PAD_NAME (srcpad));
1992     return FALSE;
1993   }
1994   if (!GST_PAD_IS_SINK (sinkpad)) {
1995     GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s is not sink pad, failed",
1996         GST_DEBUG_PAD_NAME (sinkpad));
1997     return FALSE;
1998   }
1999   if (GST_PAD_PARENT (srcpad) == NULL) {
2000     GST_CAT_INFO (GST_CAT_PADS, "Src pad %s:%s has no parent, failed",
2001         GST_DEBUG_PAD_NAME (srcpad));
2002     return FALSE;
2003   }
2004   if (GST_PAD_PARENT (sinkpad) == NULL) {
2005     GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s has no parent, failed",
2006         GST_DEBUG_PAD_NAME (srcpad));
2007     return FALSE;
2008   }
2009
2010   return TRUE;
2011 }
2012
2013 /**
2014  * gst_pad_use_fixed_caps:
2015  * @pad: the pad to use
2016  *
2017  * A helper function you can use that sets the
2018  * @gst_pad_get_fixed_caps_func as the getcaps function for the
2019  * pad. This way the function will always return the negotiated caps
2020  * or in case the pad is not negotiated, the padtemplate caps.
2021  *
2022  * Use this function on a pad that, once _set_caps() has been called
2023  * on it, cannot be renegotiated to something else.
2024  */
2025 void
2026 gst_pad_use_fixed_caps (GstPad * pad)
2027 {
2028   gst_pad_set_getcaps_function (pad, gst_pad_get_fixed_caps_func);
2029 }
2030
2031 /**
2032  * gst_pad_get_fixed_caps_func:
2033  * @pad: the pad to use
2034  *
2035  * A helper function you can use as a GetCaps function that
2036  * will return the currently negotiated caps or the padtemplate
2037  * when NULL.
2038  *
2039  * Returns: The currently negotiated caps or the padtemplate.
2040  */
2041 GstCaps *
2042 gst_pad_get_fixed_caps_func (GstPad * pad)
2043 {
2044   GstCaps *result;
2045
2046   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2047
2048   if (GST_PAD_CAPS (pad)) {
2049     result = GST_PAD_CAPS (pad);
2050
2051     GST_CAT_DEBUG (GST_CAT_CAPS,
2052         "using pad caps %p %" GST_PTR_FORMAT, result, result);
2053
2054     result = gst_caps_ref (result);
2055     goto done;
2056   }
2057   if (GST_PAD_PAD_TEMPLATE (pad)) {
2058     GstPadTemplate *templ = GST_PAD_PAD_TEMPLATE (pad);
2059
2060     result = GST_PAD_TEMPLATE_CAPS (templ);
2061     GST_CAT_DEBUG (GST_CAT_CAPS,
2062         "using pad template %p with caps %p %" GST_PTR_FORMAT, templ, result,
2063         result);
2064
2065     result = gst_caps_ref (result);
2066     goto done;
2067   }
2068   GST_CAT_DEBUG (GST_CAT_CAPS, "pad has no caps");
2069   result = gst_caps_new_empty ();
2070
2071 done:
2072   return result;
2073 }
2074
2075 /**
2076  * gst_pad_get_parent_element:
2077  * @pad: a pad
2078  *
2079  * Gets the parent of @pad, cast to a #GstElement. If a @pad has no parent or
2080  * its parent is not an element, return NULL.
2081  *
2082  * Returns: The parent of the pad. The caller has a reference on the parent, so
2083  * unref when you're finished with it.
2084  *
2085  * MT safe.
2086  */
2087 GstElement *
2088 gst_pad_get_parent_element (GstPad * pad)
2089 {
2090   GstObject *p;
2091
2092   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2093
2094   p = gst_object_get_parent (GST_OBJECT_CAST (pad));
2095
2096   if (p && !GST_IS_ELEMENT (p)) {
2097     gst_object_unref (p);
2098     p = NULL;
2099   }
2100   return GST_ELEMENT_CAST (p);
2101 }
2102
2103 /**
2104  * gst_object_default_error:
2105  * @source: the #GstObject that initiated the error.
2106  * @error: the GError.
2107  * @debug: an additional debug information string, or NULL.
2108  *
2109  * A default error function.
2110  *
2111  * The default handler will simply print the error string using g_print.
2112  */
2113 void
2114 gst_object_default_error (GstObject * source, GError * error, gchar * debug)
2115 {
2116   gchar *name = gst_object_get_path_string (source);
2117
2118   g_print (_("ERROR: from element %s: %s\n"), name, error->message);
2119   if (debug)
2120     g_print (_("Additional debug info:\n%s\n"), debug);
2121
2122   g_free (name);
2123 }
2124
2125 /**
2126  * gst_bin_add_many:
2127  * @bin: a #GstBin
2128  * @element_1: the #GstElement element to add to the bin
2129  * @...: additional elements to add to the bin
2130  *
2131  * Adds a NULL-terminated list of elements to a bin.  This function is
2132  * equivalent to calling gst_bin_add() for each member of the list.
2133  */
2134 void
2135 gst_bin_add_many (GstBin * bin, GstElement * element_1, ...)
2136 {
2137   va_list args;
2138
2139   g_return_if_fail (GST_IS_BIN (bin));
2140   g_return_if_fail (GST_IS_ELEMENT (element_1));
2141
2142   va_start (args, element_1);
2143
2144   while (element_1) {
2145     gst_bin_add (bin, element_1);
2146
2147     element_1 = va_arg (args, GstElement *);
2148   }
2149
2150   va_end (args);
2151 }
2152
2153 /**
2154  * gst_bin_remove_many:
2155  * @bin: a #GstBin
2156  * @element_1: the first #GstElement to remove from the bin
2157  * @...: NULL-terminated list of elements to remove from the bin
2158  *
2159  * Remove a list of elements from a bin. This function is equivalent
2160  * to calling gst_bin_remove() with each member of the list.
2161  */
2162 void
2163 gst_bin_remove_many (GstBin * bin, GstElement * element_1, ...)
2164 {
2165   va_list args;
2166
2167   g_return_if_fail (GST_IS_BIN (bin));
2168   g_return_if_fail (GST_IS_ELEMENT (element_1));
2169
2170   va_start (args, element_1);
2171
2172   while (element_1) {
2173     gst_bin_remove (bin, element_1);
2174
2175     element_1 = va_arg (args, GstElement *);
2176   }
2177
2178   va_end (args);
2179 }
2180
2181 static void
2182 gst_element_populate_std_props (GObjectClass * klass, const gchar * prop_name,
2183     guint arg_id, GParamFlags flags)
2184 {
2185   GQuark prop_id = g_quark_from_string (prop_name);
2186   GParamSpec *pspec;
2187
2188   static GQuark fd_id = 0;
2189   static GQuark blocksize_id;
2190   static GQuark bytesperread_id;
2191   static GQuark dump_id;
2192   static GQuark filesize_id;
2193   static GQuark mmapsize_id;
2194   static GQuark location_id;
2195   static GQuark offset_id;
2196   static GQuark silent_id;
2197   static GQuark touch_id;
2198
2199   if (!fd_id) {
2200     fd_id = g_quark_from_static_string ("fd");
2201     blocksize_id = g_quark_from_static_string ("blocksize");
2202     bytesperread_id = g_quark_from_static_string ("bytesperread");
2203     dump_id = g_quark_from_static_string ("dump");
2204     filesize_id = g_quark_from_static_string ("filesize");
2205     mmapsize_id = g_quark_from_static_string ("mmapsize");
2206     location_id = g_quark_from_static_string ("location");
2207     offset_id = g_quark_from_static_string ("offset");
2208     silent_id = g_quark_from_static_string ("silent");
2209     touch_id = g_quark_from_static_string ("touch");
2210   }
2211
2212   if (prop_id == fd_id) {
2213     pspec = g_param_spec_int ("fd", "File-descriptor",
2214         "File-descriptor for the file being read", 0, G_MAXINT, 0, flags);
2215   } else if (prop_id == blocksize_id) {
2216     pspec = g_param_spec_ulong ("blocksize", "Block Size",
2217         "Block size to read per buffer", 0, G_MAXULONG, 4096, flags);
2218
2219   } else if (prop_id == bytesperread_id) {
2220     pspec = g_param_spec_int ("bytesperread", "Bytes per read",
2221         "Number of bytes to read per buffer", G_MININT, G_MAXINT, 0, flags);
2222
2223   } else if (prop_id == dump_id) {
2224     pspec = g_param_spec_boolean ("dump", "Dump",
2225         "Dump bytes to stdout", FALSE, flags);
2226
2227   } else if (prop_id == filesize_id) {
2228     pspec = g_param_spec_int64 ("filesize", "File Size",
2229         "Size of the file being read", 0, G_MAXINT64, 0, flags);
2230
2231   } else if (prop_id == mmapsize_id) {
2232     pspec = g_param_spec_ulong ("mmapsize", "mmap() Block Size",
2233         "Size in bytes of mmap()d regions", 0, G_MAXULONG, 4 * 1048576, flags);
2234
2235   } else if (prop_id == location_id) {
2236     pspec = g_param_spec_string ("location", "File Location",
2237         "Location of the file to read", NULL, flags);
2238
2239   } else if (prop_id == offset_id) {
2240     pspec = g_param_spec_int64 ("offset", "File Offset",
2241         "Byte offset of current read pointer", 0, G_MAXINT64, 0, flags);
2242
2243   } else if (prop_id == silent_id) {
2244     pspec = g_param_spec_boolean ("silent", "Silent", "Don't produce events",
2245         FALSE, flags);
2246
2247   } else if (prop_id == touch_id) {
2248     pspec = g_param_spec_boolean ("touch", "Touch read data",
2249         "Touch data to force disk read before " "push ()", TRUE, flags);
2250   } else {
2251     g_warning ("Unknown - 'standard' property '%s' id %d from klass %s",
2252         prop_name, arg_id, g_type_name (G_OBJECT_CLASS_TYPE (klass)));
2253     pspec = NULL;
2254   }
2255
2256   if (pspec) {
2257     g_object_class_install_property (klass, arg_id, pspec);
2258   }
2259 }
2260
2261 /**
2262  * gst_element_class_install_std_props:
2263  * @klass: the #GstElementClass to add the properties to.
2264  * @first_name: the name of the first property.
2265  * in a NULL terminated
2266  * @...: the id and flags of the first property, followed by
2267  * further 'name', 'id', 'flags' triplets and terminated by NULL.
2268  *
2269  * Adds a list of standardized properties with types to the @klass.
2270  * the id is for the property switch in your get_prop method, and
2271  * the flags determine readability / writeability.
2272  **/
2273 void
2274 gst_element_class_install_std_props (GstElementClass * klass,
2275     const gchar * first_name, ...)
2276 {
2277   const char *name;
2278
2279   va_list args;
2280
2281   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
2282
2283   va_start (args, first_name);
2284
2285   name = first_name;
2286
2287   while (name) {
2288     int arg_id = va_arg (args, int);
2289     int flags = va_arg (args, int);
2290
2291     gst_element_populate_std_props ((GObjectClass *) klass, name, arg_id,
2292         flags);
2293
2294     name = va_arg (args, char *);
2295   }
2296
2297   va_end (args);
2298 }
2299
2300
2301 /**
2302  * gst_buffer_merge:
2303  * @buf1: the first source #GstBuffer to merge.
2304  * @buf2: the second source #GstBuffer to merge.
2305  *
2306  * Create a new buffer that is the concatenation of the two source
2307  * buffers.  The original source buffers will not be modified or
2308  * unref'd.  Make sure you unref the source buffers if they are not used
2309  * anymore afterwards.
2310  *
2311  * If the buffers point to contiguous areas of memory, the buffer
2312  * is created without copying the data.
2313  *
2314  * Returns: the new #GstBuffer which is the concatenation of the source buffers.
2315  */
2316 GstBuffer *
2317 gst_buffer_merge (GstBuffer * buf1, GstBuffer * buf2)
2318 {
2319   GstBuffer *result;
2320
2321   /* we're just a specific case of the more general gst_buffer_span() */
2322   result = gst_buffer_span (buf1, 0, buf2, buf1->size + buf2->size);
2323
2324   return result;
2325 }
2326
2327 /**
2328  * gst_buffer_join:
2329  * @buf1: the first source #GstBuffer.
2330  * @buf2: the second source #GstBuffer.
2331  *
2332  * Create a new buffer that is the concatenation of the two source
2333  * buffers, and unrefs the original source buffers.
2334  *
2335  * If the buffers point to contiguous areas of memory, the buffer
2336  * is created without copying the data.
2337  *
2338  * Returns: the new #GstBuffer which is the concatenation of the source buffers.
2339  */
2340 GstBuffer *
2341 gst_buffer_join (GstBuffer * buf1, GstBuffer * buf2)
2342 {
2343   GstBuffer *result;
2344
2345   result = gst_buffer_span (buf1, 0, buf2, buf1->size + buf2->size);
2346   gst_buffer_unref (buf1);
2347   gst_buffer_unref (buf2);
2348
2349   return result;
2350 }
2351
2352
2353 /**
2354  * gst_buffer_stamp:
2355  * @dest: buffer to stamp
2356  * @src: buffer to stamp from
2357  *
2358  * Copies additional information (the timestamp, duration, and offset start
2359  * and end) from one buffer to the other.
2360  *
2361  * This function does not copy any buffer flags or caps.
2362  */
2363 void
2364 gst_buffer_stamp (GstBuffer * dest, const GstBuffer * src)
2365 {
2366   g_return_if_fail (dest != NULL);
2367   g_return_if_fail (src != NULL);
2368
2369   GST_BUFFER_TIMESTAMP (dest) = GST_BUFFER_TIMESTAMP (src);
2370   GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
2371   GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
2372   GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
2373 }
2374
2375 static gboolean
2376 intersect_caps_func (GstPad * pad, GValue * ret, GstPad * orig)
2377 {
2378   if (pad != orig) {
2379     GstCaps *peercaps, *existing;
2380
2381     existing = g_value_get_pointer (ret);
2382     peercaps = gst_pad_peer_get_caps (pad);
2383     if (peercaps == NULL)
2384       peercaps = gst_caps_new_any ();
2385     g_value_set_pointer (ret, gst_caps_intersect (existing, peercaps));
2386     gst_caps_unref (existing);
2387     gst_caps_unref (peercaps);
2388   }
2389   gst_object_unref (pad);
2390   return TRUE;
2391 }
2392
2393 /**
2394  * gst_pad_proxy_getcaps:
2395  * @pad: a #GstPad to proxy.
2396  *
2397  * Calls gst_pad_get_allowed_caps() for every other pad belonging to the
2398  * same element as @pad, and returns the intersection of the results.
2399  *
2400  * This function is useful as a default getcaps function for an element
2401  * that can handle any stream format, but requires all its pads to have
2402  * the same caps.  Two such elements are tee and aggregator.
2403  *
2404  * Returns: the intersection of the other pads' allowed caps.
2405  */
2406 GstCaps *
2407 gst_pad_proxy_getcaps (GstPad * pad)
2408 {
2409   GstElement *element;
2410   GstCaps *caps, *intersected;
2411   GstIterator *iter;
2412   GstIteratorResult res;
2413   GValue ret = { 0, };
2414
2415   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2416
2417   GST_DEBUG ("proxying getcaps for %s:%s", GST_DEBUG_PAD_NAME (pad));
2418
2419   element = gst_pad_get_parent_element (pad);
2420   if (element == NULL)
2421     return NULL;
2422
2423   iter = gst_element_iterate_pads (element);
2424
2425   g_value_init (&ret, G_TYPE_POINTER);
2426   g_value_set_pointer (&ret, gst_caps_new_any ());
2427
2428   res = gst_iterator_fold (iter, (GstIteratorFoldFunction) intersect_caps_func,
2429       &ret, pad);
2430   gst_iterator_free (iter);
2431
2432   if (res != GST_ITERATOR_DONE)
2433     goto pads_changed;
2434
2435   gst_object_unref (element);
2436
2437   caps = g_value_get_pointer (&ret);
2438   g_value_unset (&ret);
2439
2440   intersected = gst_caps_intersect (caps, gst_pad_get_pad_template_caps (pad));
2441   gst_caps_unref (caps);
2442
2443   return intersected;
2444
2445   /* ERRORS */
2446 pads_changed:
2447   {
2448     g_warning ("Pad list changed during capsnego for element %s",
2449         GST_ELEMENT_NAME (element));
2450     gst_object_unref (element);
2451     return NULL;
2452   }
2453 }
2454
2455 typedef struct
2456 {
2457   GstPad *orig;
2458   GstCaps *caps;
2459 } LinkData;
2460
2461 static gboolean
2462 link_fold_func (GstPad * pad, GValue * ret, LinkData * data)
2463 {
2464   gboolean success = TRUE;
2465
2466   if (pad != data->orig) {
2467     success = gst_pad_set_caps (pad, data->caps);
2468     g_value_set_boolean (ret, success);
2469   }
2470   gst_object_unref (pad);
2471
2472   return success;
2473 }
2474
2475 /**
2476  * gst_pad_proxy_setcaps
2477  * @pad: a #GstPad to proxy from
2478  * @caps: the #GstCaps to link with
2479  *
2480  * Calls gst_pad_set_caps() for every other pad belonging to the
2481  * same element as @pad.  If gst_pad_set_caps() fails on any pad,
2482  * the proxy setcaps fails. May be used only during negotiation.
2483  *
2484  * Returns: TRUE if sucessful
2485  */
2486 gboolean
2487 gst_pad_proxy_setcaps (GstPad * pad, GstCaps * caps)
2488 {
2489   GstElement *element;
2490   GstIterator *iter;
2491   GstIteratorResult res;
2492   GValue ret = { 0, };
2493   LinkData data;
2494
2495   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2496   g_return_val_if_fail (caps != NULL, FALSE);
2497
2498   GST_DEBUG ("proxying pad link for %s:%s", GST_DEBUG_PAD_NAME (pad));
2499
2500   element = gst_pad_get_parent_element (pad);
2501   if (element == NULL)
2502     return FALSE;
2503
2504   iter = gst_element_iterate_pads (element);
2505
2506   g_value_init (&ret, G_TYPE_BOOLEAN);
2507   g_value_set_boolean (&ret, TRUE);
2508   data.orig = pad;
2509   data.caps = caps;
2510
2511   res = gst_iterator_fold (iter, (GstIteratorFoldFunction) link_fold_func,
2512       &ret, &data);
2513   gst_iterator_free (iter);
2514
2515   if (res != GST_ITERATOR_DONE)
2516     goto pads_changed;
2517
2518   gst_object_unref (element);
2519
2520   /* ok not to unset the gvalue */
2521   return g_value_get_boolean (&ret);
2522
2523   /* ERRORS */
2524 pads_changed:
2525   {
2526     g_warning ("Pad list changed during proxy_pad_link for element %s",
2527         GST_ELEMENT_NAME (element));
2528     gst_object_unref (element);
2529     return FALSE;
2530   }
2531 }
2532
2533 /**
2534  * gst_pad_query_position:
2535  * @pad: a #GstPad to invoke the position query on.
2536  * @format: a pointer to the #GstFormat asked for.
2537  *          On return contains the #GstFormat used.
2538  * @cur: A location in which to store the current position, or NULL.
2539  *
2540  * Queries a pad for the stream position.
2541  *
2542  * Returns: TRUE if the query could be performed.
2543  */
2544 gboolean
2545 gst_pad_query_position (GstPad * pad, GstFormat * format, gint64 * cur)
2546 {
2547   GstQuery *query;
2548   gboolean ret;
2549
2550   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2551   g_return_val_if_fail (format != NULL, FALSE);
2552
2553   query = gst_query_new_position (*format);
2554   ret = gst_pad_query (pad, query);
2555
2556   if (ret)
2557     gst_query_parse_position (query, format, cur);
2558
2559   gst_query_unref (query);
2560
2561   return ret;
2562 }
2563
2564 /**
2565  * gst_pad_query_peer_position:
2566  * @pad: a #GstPad on whose peer to invoke the position query on.
2567  *       Must be a sink pad.
2568  * @format: a pointer to the #GstFormat asked for.
2569  *          On return contains the #GstFormat used.
2570  * @cur: A location in which to store the current position, or NULL.
2571  *
2572  * Queries the peer of a given sink pad for the stream position.
2573  *
2574  * Returns: TRUE if the query could be performed.
2575  */
2576 gboolean
2577 gst_pad_query_peer_position (GstPad * pad, GstFormat * format, gint64 * cur)
2578 {
2579   gboolean ret = FALSE;
2580   GstPad *peer;
2581
2582   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2583   g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2584   g_return_val_if_fail (format != NULL, FALSE);
2585
2586   peer = gst_pad_get_peer (pad);
2587   if (peer) {
2588     ret = gst_pad_query_position (peer, format, cur);
2589     gst_object_unref (peer);
2590   }
2591
2592   return ret;
2593 }
2594
2595 /**
2596  * gst_pad_query_duration:
2597  * @pad: a #GstPad to invoke the duration query on.
2598  * @format: a pointer to the #GstFormat asked for.
2599  *          On return contains the #GstFormat used.
2600  * @duration: A location in which to store the total duration, or NULL.
2601  *
2602  * Queries a pad for the total stream duration.
2603  *
2604  * Returns: TRUE if the query could be performed.
2605  */
2606 gboolean
2607 gst_pad_query_duration (GstPad * pad, GstFormat * format, gint64 * duration)
2608 {
2609   GstQuery *query;
2610   gboolean ret;
2611
2612   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2613   g_return_val_if_fail (format != NULL, FALSE);
2614
2615   query = gst_query_new_duration (*format);
2616   ret = gst_pad_query (pad, query);
2617
2618   if (ret)
2619     gst_query_parse_duration (query, format, duration);
2620
2621   gst_query_unref (query);
2622
2623   return ret;
2624 }
2625
2626 /**
2627  * gst_pad_query_peer_duration:
2628  * @pad: a #GstPad on whose peer pad to invoke the duration query on.
2629  *       Must be a sink pad.
2630  * @format: a pointer to the #GstFormat asked for.
2631  *          On return contains the #GstFormat used.
2632  * @duration: A location in which to store the total duration, or NULL.
2633  *
2634  * Queries the peer pad of a given sink pad for the total stream duration.
2635  *
2636  * Returns: TRUE if the query could be performed.
2637  */
2638 gboolean
2639 gst_pad_query_peer_duration (GstPad * pad, GstFormat * format,
2640     gint64 * duration)
2641 {
2642   gboolean ret = FALSE;
2643   GstPad *peer;
2644
2645   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2646   g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2647   g_return_val_if_fail (format != NULL, FALSE);
2648
2649   peer = gst_pad_get_peer (pad);
2650   if (peer) {
2651     ret = gst_pad_query_duration (peer, format, duration);
2652     gst_object_unref (peer);
2653   }
2654
2655   return ret;
2656 }
2657
2658 /**
2659  * gst_pad_query_convert:
2660  * @pad: a #GstPad to invoke the convert query on.
2661  * @src_format: a #GstFormat to convert from.
2662  * @src_val: a value to convert.
2663  * @dest_format: a pointer to the #GstFormat to convert to.
2664  * @dest_val: a pointer to the result.
2665  *
2666  * Queries a pad to convert @src_val in @src_format to @dest_format.
2667  *
2668  * Returns: TRUE if the query could be performed.
2669  */
2670 gboolean
2671 gst_pad_query_convert (GstPad * pad, GstFormat src_format, gint64 src_val,
2672     GstFormat * dest_format, gint64 * dest_val)
2673 {
2674   GstQuery *query;
2675   gboolean ret;
2676
2677   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2678   g_return_val_if_fail (src_val >= 0, FALSE);
2679   g_return_val_if_fail (dest_format != NULL, FALSE);
2680   g_return_val_if_fail (dest_val != NULL, FALSE);
2681
2682   if (*dest_format == src_format) {
2683     *dest_val = src_val;
2684     return TRUE;
2685   }
2686
2687   query = gst_query_new_convert (src_format, src_val, *dest_format);
2688   ret = gst_pad_query (pad, query);
2689
2690   if (ret)
2691     gst_query_parse_convert (query, NULL, NULL, dest_format, dest_val);
2692
2693   gst_query_unref (query);
2694
2695   return ret;
2696 }
2697
2698 /**
2699  * gst_pad_query_peer_convert:
2700  * @pad: a #GstPad, on whose peer pad to invoke the convert query on.
2701  *       Must be a sink pad.
2702  * @src_format: a #GstFormat to convert from.
2703  * @src_val: a value to convert.
2704  * @dest_format: a pointer to the #GstFormat to convert to.
2705  * @dest_val: a pointer to the result.
2706  *
2707  * Queries the peer pad of a given sink pad to convert @src_val in @src_format
2708  * to @dest_format.
2709  *
2710  * Returns: TRUE if the query could be performed.
2711  */
2712 gboolean
2713 gst_pad_query_peer_convert (GstPad * pad, GstFormat src_format, gint64 src_val,
2714     GstFormat * dest_format, gint64 * dest_val)
2715 {
2716   gboolean ret = FALSE;
2717   GstPad *peer;
2718
2719   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2720   g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2721   g_return_val_if_fail (src_val >= 0, FALSE);
2722   g_return_val_if_fail (dest_format != NULL, FALSE);
2723   g_return_val_if_fail (dest_val != NULL, FALSE);
2724
2725   peer = gst_pad_get_peer (pad);
2726   if (peer) {
2727     ret = gst_pad_query_convert (peer, src_format, src_val, dest_format,
2728         dest_val);
2729     gst_object_unref (peer);
2730   }
2731
2732   return ret;
2733 }
2734
2735 /**
2736  * gst_atomic_int_set:
2737  * @atomic_int: pointer to an atomic integer
2738  * @value: value to set
2739  *
2740  * Unconditionally sets the atomic integer to @value.
2741  */
2742 void
2743 gst_atomic_int_set (gint * atomic_int, gint value)
2744 {
2745   int ignore;
2746
2747   *atomic_int = value;
2748   /* read acts as a memory barrier */
2749   ignore = g_atomic_int_get (atomic_int);
2750 }
2751
2752 /**
2753  * gst_pad_add_data_probe:
2754  * @pad: pad to add the data probe handler to
2755  * @handler: function to call when data is passed over pad
2756  * @data: data to pass along with the handler
2757  *
2758  * Adds a "data probe" to a pad. This function will be called whenever data
2759  * passes through a pad. In this case data means both events and buffers. The
2760  * probe will be called with the data as an argument, meaning @handler should
2761  * have the same callback signature as the 'have-data' signal of #GstPad.
2762  * Note that the data will have a reference count greater than 1, so it will
2763  * be immutable -- you must not change it.
2764  *
2765  * For source pads, the probe will be called after the blocking function, if any
2766  * (see gst_pad_set_blocked_async()), but before looking up the peer to chain
2767  * to. For sink pads, the probe function will be called before configuring the
2768  * sink with new caps, if any, and before calling the pad's chain function.
2769  *
2770  * Your data probe should return TRUE to let the data continue to flow, or FALSE
2771  * to drop it. Dropping data is rarely useful, but occasionally comes in handy
2772  * with events.
2773  *
2774  * Although probes are implemented internally by connecting @handler to the
2775  * have-data signal on the pad, if you want to remove a probe it is insufficient
2776  * to only call g_signal_handler_disconnect on the returned handler id. To
2777  * remove a probe, use the appropriate function, such as
2778  * gst_pad_remove_data_probe().
2779  *
2780  * Returns: The handler id.
2781  */
2782 gulong
2783 gst_pad_add_data_probe (GstPad * pad, GCallback handler, gpointer data)
2784 {
2785   gulong sigid;
2786   gboolean was_ghost = FALSE;
2787
2788   g_return_val_if_fail (GST_IS_PAD (pad), 0);
2789   g_return_val_if_fail (handler != NULL, 0);
2790
2791   if (GST_IS_GHOST_PAD (pad)) {
2792     pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
2793     if (!pad) {
2794       return 0;
2795     }
2796     was_ghost = TRUE;
2797   }
2798
2799   GST_OBJECT_LOCK (pad);
2800   sigid = g_signal_connect (pad, "have-data", handler, data);
2801   GST_PAD_DO_EVENT_SIGNALS (pad)++;
2802   GST_PAD_DO_BUFFER_SIGNALS (pad)++;
2803   GST_DEBUG ("adding data probe to pad %s:%s, now %d data, %d event probes",
2804       GST_DEBUG_PAD_NAME (pad),
2805       GST_PAD_DO_BUFFER_SIGNALS (pad), GST_PAD_DO_EVENT_SIGNALS (pad));
2806   GST_OBJECT_UNLOCK (pad);
2807
2808   if (was_ghost) {
2809     gst_object_unref (pad);
2810   }
2811
2812   return sigid;
2813 }
2814
2815 /**
2816  * gst_pad_add_event_probe:
2817  * @pad: pad to add the event probe handler to
2818  * @handler: function to call when data is passed over pad
2819  * @data: data to pass along with the handler
2820  *
2821  * Adds a probe that will be called for all events passing through a pad. See
2822  * gst_pad_add_data_probe() for more information.
2823  *
2824  * Returns: The handler id
2825  */
2826 gulong
2827 gst_pad_add_event_probe (GstPad * pad, GCallback handler, gpointer data)
2828 {
2829   gulong sigid;
2830   gboolean was_ghost = FALSE;
2831
2832   g_return_val_if_fail (GST_IS_PAD (pad), 0);
2833   g_return_val_if_fail (handler != NULL, 0);
2834
2835   if (GST_IS_GHOST_PAD (pad)) {
2836     pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
2837     if (!pad) {
2838       return 0;
2839     }
2840     was_ghost = TRUE;
2841   }
2842
2843   GST_OBJECT_LOCK (pad);
2844   sigid = g_signal_connect (pad, "have-data::event", handler, data);
2845   GST_PAD_DO_EVENT_SIGNALS (pad)++;
2846   GST_DEBUG ("adding event probe to pad %s:%s, now %d probes",
2847       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_EVENT_SIGNALS (pad));
2848   GST_OBJECT_UNLOCK (pad);
2849
2850   if (was_ghost) {
2851     gst_object_unref (pad);
2852   }
2853
2854   return sigid;
2855 }
2856
2857 /**
2858  * gst_pad_add_buffer_probe:
2859  * @pad: pad to add the buffer probe handler to
2860  * @handler: function to call when data is passed over pad
2861  * @data: data to pass along with the handler
2862  *
2863  * Adds a probe that will be called for all buffers passing through a pad. See
2864  * gst_pad_add_data_probe() for more information.
2865  *
2866  * Returns: The handler id
2867  */
2868 gulong
2869 gst_pad_add_buffer_probe (GstPad * pad, GCallback handler, gpointer data)
2870 {
2871   gulong sigid;
2872   gboolean was_ghost = FALSE;
2873
2874   g_return_val_if_fail (GST_IS_PAD (pad), 0);
2875   g_return_val_if_fail (handler != NULL, 0);
2876
2877   if (GST_IS_GHOST_PAD (pad)) {
2878     pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
2879     if (!pad) {
2880       return 0;
2881     }
2882     was_ghost = TRUE;
2883   }
2884
2885   GST_OBJECT_LOCK (pad);
2886   sigid = g_signal_connect (pad, "have-data::buffer", handler, data);
2887   GST_PAD_DO_BUFFER_SIGNALS (pad)++;
2888   GST_DEBUG ("adding buffer probe to pad %s:%s, now %d probes",
2889       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_BUFFER_SIGNALS (pad));
2890   GST_OBJECT_UNLOCK (pad);
2891
2892   if (was_ghost) {
2893     gst_object_unref (pad);
2894   }
2895
2896   return sigid;
2897 }
2898
2899 /**
2900  * gst_pad_remove_data_probe:
2901  * @pad: pad to remove the data probe handler from
2902  * @handler_id: handler id returned from gst_pad_add_data_probe
2903  *
2904  * Removes a data probe from @pad.
2905  */
2906 void
2907 gst_pad_remove_data_probe (GstPad * pad, guint handler_id)
2908 {
2909   gboolean was_ghost = FALSE;
2910
2911   g_return_if_fail (GST_IS_PAD (pad));
2912   g_return_if_fail (handler_id > 0);
2913
2914   if (GST_IS_GHOST_PAD (pad)) {
2915     pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
2916     if (!pad) {
2917       return;
2918     }
2919     was_ghost = TRUE;
2920   }
2921
2922   GST_OBJECT_LOCK (pad);
2923   g_signal_handler_disconnect (pad, handler_id);
2924   GST_PAD_DO_BUFFER_SIGNALS (pad)--;
2925   GST_PAD_DO_EVENT_SIGNALS (pad)--;
2926   GST_DEBUG
2927       ("removed data probe from pad %s:%s, now %d event, %d buffer probes",
2928       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_EVENT_SIGNALS (pad),
2929       GST_PAD_DO_BUFFER_SIGNALS (pad));
2930   GST_OBJECT_UNLOCK (pad);
2931
2932   if (was_ghost) {
2933     gst_object_unref (pad);
2934   }
2935 }
2936
2937 /**
2938  * gst_pad_remove_event_probe:
2939  * @pad: pad to remove the event probe handler from
2940  * @handler_id: handler id returned from gst_pad_add_event_probe
2941  *
2942  * Removes an event probe from @pad.
2943  */
2944 void
2945 gst_pad_remove_event_probe (GstPad * pad, guint handler_id)
2946 {
2947   gboolean was_ghost = FALSE;
2948
2949   g_return_if_fail (GST_IS_PAD (pad));
2950   g_return_if_fail (handler_id > 0);
2951
2952   if (GST_IS_GHOST_PAD (pad)) {
2953     pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
2954     if (!pad) {
2955       return;
2956     }
2957     was_ghost = TRUE;
2958   }
2959
2960   GST_OBJECT_LOCK (pad);
2961   g_signal_handler_disconnect (pad, handler_id);
2962   GST_PAD_DO_EVENT_SIGNALS (pad)--;
2963   GST_DEBUG ("removed event probe from pad %s:%s, now %d event probes",
2964       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_EVENT_SIGNALS (pad));
2965   GST_OBJECT_UNLOCK (pad);
2966
2967   if (was_ghost) {
2968     gst_object_unref (pad);
2969   }
2970 }
2971
2972 /**
2973  * gst_pad_remove_buffer_probe:
2974  * @pad: pad to remove the buffer probe handler from
2975  * @handler_id: handler id returned from gst_pad_add_buffer_probe
2976  *
2977  * Removes a buffer probe from @pad.
2978  */
2979 void
2980 gst_pad_remove_buffer_probe (GstPad * pad, guint handler_id)
2981 {
2982   gboolean was_ghost = FALSE;
2983
2984   g_return_if_fail (GST_IS_PAD (pad));
2985   g_return_if_fail (handler_id > 0);
2986
2987   if (GST_IS_GHOST_PAD (pad)) {
2988     pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad));
2989     if (!pad) {
2990       return;
2991     }
2992     was_ghost = TRUE;
2993   }
2994
2995   GST_OBJECT_LOCK (pad);
2996   g_signal_handler_disconnect (pad, handler_id);
2997   GST_PAD_DO_BUFFER_SIGNALS (pad)--;
2998   GST_DEBUG ("removed buffer probe from pad %s:%s, now %d buffer probes",
2999       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_BUFFER_SIGNALS (pad));
3000   GST_OBJECT_UNLOCK (pad);
3001
3002   if (was_ghost) {
3003     gst_object_unref (pad);
3004   }
3005 }
3006
3007 /**
3008  * gst_element_found_tags_for_pad:
3009  * @element: element for which to post taglist to bus.
3010  * @pad: pad on which to push tag-event.
3011  * @list: the taglist to post on the bus and create event from.
3012  *
3013  * Posts a message to the bus that new tags were found and pushes the
3014  * tags as event. Takes ownership of the @list.
3015  *
3016  * This is a utility method for elements. Applications should use the
3017  * #GstTagSetter interface.
3018  */
3019 void
3020 gst_element_found_tags_for_pad (GstElement * element,
3021     GstPad * pad, GstTagList * list)
3022 {
3023   g_return_if_fail (element != NULL);
3024   g_return_if_fail (pad != NULL);
3025   g_return_if_fail (list != NULL);
3026
3027   gst_pad_push_event (pad, gst_event_new_tag (gst_tag_list_copy (list)));
3028   gst_element_post_message (element,
3029       gst_message_new_tag (GST_OBJECT (element), list));
3030 }
3031
3032 static void
3033 push_and_ref (GstPad * pad, GstEvent * event)
3034 {
3035   gst_pad_push_event (pad, gst_event_ref (event));
3036   /* iterator refs pad, we unref when we are done with it */
3037   gst_object_unref (pad);
3038 }
3039
3040 /**
3041  * gst_element_found_tags:
3042  * @element: element for which we found the tags.
3043  * @list: list of tags.
3044  *
3045  * Posts a message to the bus that new tags were found, and pushes an event
3046  * to all sourcepads. Takes ownership of the @list.
3047  *
3048  * This is a utility method for elements. Applications should use the
3049  * #GstTagSetter interface.
3050  */
3051 void
3052 gst_element_found_tags (GstElement * element, GstTagList * list)
3053 {
3054   GstIterator *iter;
3055   GstEvent *event;
3056
3057   g_return_if_fail (element != NULL);
3058   g_return_if_fail (list != NULL);
3059
3060   iter = gst_element_iterate_src_pads (element);
3061   event = gst_event_new_tag (gst_tag_list_copy (list));
3062   gst_iterator_foreach (iter, (GFunc) push_and_ref, event);
3063   gst_iterator_free (iter);
3064   gst_event_unref (event);
3065
3066   gst_element_post_message (element,
3067       gst_message_new_tag (GST_OBJECT (element), list));
3068 }
3069
3070 static GstPad *
3071 element_find_unconnected_pad (GstElement * element, GstPadDirection direction)
3072 {
3073   GstIterator *iter;
3074   GstPad *unconnected_pad = NULL;
3075   gboolean done;
3076
3077   switch (direction) {
3078     case GST_PAD_SRC:
3079       iter = gst_element_iterate_src_pads (element);
3080       break;
3081     case GST_PAD_SINK:
3082       iter = gst_element_iterate_sink_pads (element);
3083       break;
3084     default:
3085       g_assert_not_reached ();
3086   }
3087
3088   done = FALSE;
3089   while (!done) {
3090     gpointer pad;
3091
3092     switch (gst_iterator_next (iter, &pad)) {
3093       case GST_ITERATOR_OK:{
3094         GstPad *peer;
3095
3096         GST_CAT_LOG (GST_CAT_ELEMENT_PADS, "examining pad %s:%s",
3097             GST_DEBUG_PAD_NAME (pad));
3098
3099         peer = gst_pad_get_peer (GST_PAD (pad));
3100         if (peer == NULL) {
3101           unconnected_pad = pad;
3102           done = TRUE;
3103           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
3104               "found existing unlinked pad %s:%s",
3105               GST_DEBUG_PAD_NAME (unconnected_pad));
3106         } else {
3107           gst_object_unref (pad);
3108           gst_object_unref (peer);
3109         }
3110         break;
3111       }
3112       case GST_ITERATOR_DONE:
3113         done = TRUE;
3114         break;
3115       case GST_ITERATOR_RESYNC:
3116         gst_iterator_resync (iter);
3117         break;
3118       case GST_ITERATOR_ERROR:
3119         g_return_val_if_reached (NULL);
3120         break;
3121     }
3122   }
3123
3124   gst_iterator_free (iter);
3125
3126   return unconnected_pad;
3127 }
3128
3129 /**
3130  * gst_bin_find_unconnected_pad:
3131  * @bin: bin in which to look for elements with unconnected pads
3132  * @direction: whether to look for an unconnected source or sink pad
3133  *
3134  * Recursively looks for elements with an unconnected pad of the given
3135  * direction within the specified bin and returns an unconnected pad
3136  * if one is found, or NULL otherwise. If a pad is found, the caller
3137  * owns a reference to it and should use gst_object_unref() on the
3138  * pad when it is not needed any longer.
3139  *
3140  * Returns: unconnected pad of the given direction, or NULL.
3141  *
3142  * Since: 0.10.3
3143  */
3144 GstPad *
3145 gst_bin_find_unconnected_pad (GstBin * bin, GstPadDirection direction)
3146 {
3147   GstIterator *iter;
3148   gboolean done;
3149   GstPad *pad = NULL;
3150
3151   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3152   g_return_val_if_fail (direction != GST_PAD_UNKNOWN, NULL);
3153
3154   done = FALSE;
3155   iter = gst_bin_iterate_recurse (bin);
3156   while (!done) {
3157     gpointer element;
3158
3159     switch (gst_iterator_next (iter, &element)) {
3160       case GST_ITERATOR_OK:
3161         pad = element_find_unconnected_pad (GST_ELEMENT (element), direction);
3162         gst_object_unref (element);
3163         if (pad != NULL)
3164           done = TRUE;
3165         break;
3166       case GST_ITERATOR_DONE:
3167         done = TRUE;
3168         break;
3169       case GST_ITERATOR_RESYNC:
3170         gst_iterator_resync (iter);
3171         break;
3172       case GST_ITERATOR_ERROR:
3173         g_return_val_if_reached (NULL);
3174         break;
3175     }
3176   }
3177
3178   gst_iterator_free (iter);
3179
3180   return pad;
3181 }
3182
3183 #ifndef GST_DISABLE_PARSE
3184 /**
3185  * gst_parse_bin_from_description:
3186  * @bin_description: command line describing the bin
3187  * @ghost_unconnected_pads: whether to automatically create ghost pads
3188  *                          for unconnected source or sink pads within
3189  *                          the bin
3190  * @err: where to store the error message in case of an error, or NULL
3191  *
3192  * This is a convenience wrapper around gst_parse_launch() to create a
3193  * #GstBin from a gst-launch-style pipeline description. See
3194  * gst_parse_launch() and the gst-launch man page for details about the
3195  * syntax. Ghost pads on the bin for unconnected source or sink pads
3196  * within the bin can automatically be created (but only a maximum of
3197  * one ghost pad for each direction will be created; if you expect
3198  * multiple unconnected source pads or multiple unconnected sink pads
3199  * and want them all ghosted, you will have to create the ghost pads
3200  * yourself).
3201  *
3202  * Returns: a newly-created bin, or NULL if an error occurred.
3203  *
3204  * Since: 0.10.3
3205  */
3206 GstElement *
3207 gst_parse_bin_from_description (const gchar * bin_description,
3208     gboolean ghost_unconnected_pads, GError ** err)
3209 {
3210   GstPad *pad = NULL;
3211   GstBin *bin;
3212   gchar *desc;
3213
3214   g_return_val_if_fail (bin_description != NULL, NULL);
3215   g_return_val_if_fail (err == NULL || *err == NULL, NULL);
3216
3217   GST_DEBUG ("Making bin from description '%s'", bin_description);
3218
3219   /* parse the pipeline to a bin */
3220   desc = g_strdup_printf ("bin.( %s )", bin_description);
3221   bin = (GstBin *) gst_parse_launch (desc, err);
3222   g_free (desc);
3223
3224   if (bin == NULL || (err && *err != NULL)) {
3225     if (bin)
3226       gst_object_unref (bin);
3227     return NULL;
3228   }
3229
3230   /* find pads and ghost them if necessary */
3231   if (ghost_unconnected_pads) {
3232     if ((pad = gst_bin_find_unconnected_pad (bin, GST_PAD_SRC))) {
3233       gst_element_add_pad (GST_ELEMENT (bin), gst_ghost_pad_new ("src", pad));
3234       gst_object_unref (pad);
3235     }
3236     if ((pad = gst_bin_find_unconnected_pad (bin, GST_PAD_SINK))) {
3237       gst_element_add_pad (GST_ELEMENT (bin), gst_ghost_pad_new ("sink", pad));
3238       gst_object_unref (pad);
3239     }
3240   }
3241
3242   return GST_ELEMENT (bin);
3243 }
3244 #endif