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