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