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