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