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