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