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