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