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