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