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