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