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