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