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