gst/gstutils.c: Check if caps are not NULL (fix bug #510194)
[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: gtk_get_property stuff, etc.
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 "gst-i18n-lib.h"
41
42
43 /**
44  * gst_util_dump_mem:
45  * @mem: a pointer to the memory to dump
46  * @size: the size of the memory block to dump
47  *
48  * Dumps the memory block into a hex representation. Useful for debugging.
49  */
50 void
51 gst_util_dump_mem (const guchar * mem, guint size)
52 {
53   guint i, j;
54   GString *string = g_string_sized_new (50);
55   GString *chars = g_string_sized_new (18);
56
57   i = j = 0;
58   while (i < size) {
59     if (g_ascii_isprint (mem[i]))
60       g_string_append_c (chars, mem[i]);
61     else
62       g_string_append_c (chars, '.');
63
64     g_string_append_printf (string, "%02x ", mem[i]);
65
66     j++;
67     i++;
68
69     if (j == 16 || i == size) {
70       g_print ("%08x (%p): %-48.48s %-16.16s\n", i - j, mem + i - j,
71           string->str, chars->str);
72       g_string_set_size (string, 0);
73       g_string_set_size (chars, 0);
74       j = 0;
75     }
76   }
77   g_string_free (string, TRUE);
78   g_string_free (chars, TRUE);
79 }
80
81
82 /**
83  * gst_util_set_value_from_string:
84  * @value: the value to set
85  * @value_str: the string to get the value from
86  *
87  * Converts the string to the type of the value and
88  * sets the value with it.
89  */
90 void
91 gst_util_set_value_from_string (GValue * value, const gchar * value_str)
92 {
93   gint sscanf_ret;
94
95   g_return_if_fail (value != NULL);
96   g_return_if_fail (value_str != NULL);
97
98   GST_CAT_DEBUG (GST_CAT_PARAMS, "parsing '%s' to type %s", value_str,
99       g_type_name (G_VALUE_TYPE (value)));
100
101   switch (G_VALUE_TYPE (value)) {
102     case G_TYPE_STRING:
103       g_value_set_string (value, value_str);
104       break;
105     case G_TYPE_ENUM:
106     case G_TYPE_INT:{
107       gint i;
108
109       sscanf_ret = sscanf (value_str, "%d", &i);
110       g_return_if_fail (sscanf_ret == 1);
111       g_value_set_int (value, i);
112       break;
113     }
114     case G_TYPE_UINT:{
115       guint i;
116
117       sscanf_ret = sscanf (value_str, "%u", &i);
118       g_return_if_fail (sscanf_ret == 1);
119       g_value_set_uint (value, i);
120       break;
121     }
122     case G_TYPE_LONG:{
123       glong i;
124
125       sscanf_ret = sscanf (value_str, "%ld", &i);
126       g_return_if_fail (sscanf_ret == 1);
127       g_value_set_long (value, i);
128       break;
129     }
130     case G_TYPE_ULONG:{
131       gulong i;
132
133       sscanf_ret = sscanf (value_str, "%lu", &i);
134       g_return_if_fail (sscanf_ret == 1);
135       g_value_set_ulong (value, i);
136       break;
137     }
138     case G_TYPE_BOOLEAN:{
139       gboolean i = FALSE;
140
141       if (!g_ascii_strncasecmp ("true", value_str, 4))
142         i = TRUE;
143       g_value_set_boolean (value, i);
144       break;
145     }
146     case G_TYPE_CHAR:{
147       gchar i;
148
149       sscanf_ret = sscanf (value_str, "%c", &i);
150       g_return_if_fail (sscanf_ret == 1);
151       g_value_set_char (value, i);
152       break;
153     }
154     case G_TYPE_UCHAR:{
155       guchar i;
156
157       sscanf_ret = sscanf (value_str, "%c", &i);
158       g_return_if_fail (sscanf_ret == 1);
159       g_value_set_uchar (value, i);
160       break;
161     }
162     case G_TYPE_FLOAT:{
163       gfloat i;
164
165       sscanf_ret = sscanf (value_str, "%f", &i);
166       g_return_if_fail (sscanf_ret == 1);
167       g_value_set_float (value, i);
168       break;
169     }
170     case G_TYPE_DOUBLE:{
171       gfloat i;
172
173       sscanf_ret = sscanf (value_str, "%g", &i);
174       g_return_if_fail (sscanf_ret == 1);
175       g_value_set_double (value, (gdouble) i);
176       break;
177     }
178     default:
179       break;
180   }
181 }
182
183 /**
184  * gst_util_set_object_arg:
185  * @object: the object to set the argument of
186  * @name: the name of the argument to set
187  * @value: the string value to set
188  *
189  * Convertes the string value to the type of the objects argument and
190  * sets the argument with it.
191  */
192 void
193 gst_util_set_object_arg (GObject * object, const gchar * name,
194     const gchar * value)
195 {
196   gboolean sscanf_ret;
197
198   if (name && value) {
199     GParamSpec *paramspec;
200
201     paramspec =
202         g_object_class_find_property (G_OBJECT_GET_CLASS (object), name);
203
204     if (!paramspec) {
205       return;
206     }
207
208     GST_DEBUG ("paramspec->flags is %d, paramspec->value_type is %d",
209         paramspec->flags, (gint) paramspec->value_type);
210
211     if (paramspec->flags & G_PARAM_WRITABLE) {
212       switch (paramspec->value_type) {
213         case G_TYPE_STRING:
214           g_object_set (G_OBJECT (object), name, value, NULL);
215           break;
216         case G_TYPE_ENUM:
217         case G_TYPE_INT:{
218           gint i;
219
220           sscanf_ret = sscanf (value, "%d", &i);
221           g_return_if_fail (sscanf_ret == 1);
222           g_object_set (G_OBJECT (object), name, i, NULL);
223           break;
224         }
225         case G_TYPE_UINT:{
226           guint i;
227
228           sscanf_ret = sscanf (value, "%u", &i);
229           g_return_if_fail (sscanf_ret == 1);
230           g_object_set (G_OBJECT (object), name, i, NULL);
231           break;
232         }
233         case G_TYPE_LONG:{
234           glong i;
235
236           sscanf_ret = sscanf (value, "%ld", &i);
237           g_return_if_fail (sscanf_ret == 1);
238           g_object_set (G_OBJECT (object), name, i, NULL);
239           break;
240         }
241         case G_TYPE_ULONG:{
242           gulong i;
243
244           sscanf_ret = sscanf (value, "%lu", &i);
245           g_return_if_fail (sscanf_ret == 1);
246           g_object_set (G_OBJECT (object), name, i, NULL);
247           break;
248         }
249         case G_TYPE_BOOLEAN:{
250           gboolean i = FALSE;
251
252           if (!g_ascii_strncasecmp ("true", value, 4))
253             i = TRUE;
254           g_object_set (G_OBJECT (object), name, i, NULL);
255           break;
256         }
257         case G_TYPE_CHAR:{
258           gchar i;
259
260           sscanf_ret = sscanf (value, "%c", &i);
261           g_return_if_fail (sscanf_ret == 1);
262           g_object_set (G_OBJECT (object), name, i, NULL);
263           break;
264         }
265         case G_TYPE_UCHAR:{
266           guchar i;
267
268           sscanf_ret = sscanf (value, "%c", &i);
269           g_return_if_fail (sscanf_ret == 1);
270           g_object_set (G_OBJECT (object), name, i, NULL);
271           break;
272         }
273         case G_TYPE_FLOAT:{
274           gfloat i;
275
276           sscanf_ret = sscanf (value, "%f", &i);
277           g_return_if_fail (sscanf_ret == 1);
278           g_object_set (G_OBJECT (object), name, i, NULL);
279           break;
280         }
281         case G_TYPE_DOUBLE:{
282           gfloat i;
283
284           sscanf_ret = sscanf (value, "%g", &i);
285           g_return_if_fail (sscanf_ret == 1);
286           g_object_set (G_OBJECT (object), name, (gdouble) i, NULL);
287           break;
288         }
289         default:
290           if (G_IS_PARAM_SPEC_ENUM (paramspec)) {
291             gint i;
292
293             sscanf_ret = sscanf (value, "%d", &i);
294             g_return_if_fail (sscanf_ret == 1);
295             g_object_set (G_OBJECT (object), name, i, NULL);
296           }
297           break;
298       }
299     }
300   }
301 }
302
303 /* work around error C2520: conversion from unsigned __int64 to double
304  * not implemented, use signed __int64
305  *
306  * These are implemented as functions because on some platforms a 64bit int to
307  * double conversion is not defined/implemented.
308  */
309
310 gdouble
311 gst_util_guint64_to_gdouble (guint64 value)
312 {
313   if (value & G_GINT64_CONSTANT (0x8000000000000000))
314     return (gdouble) ((gint64) value) + (gdouble) 18446744073709551616.;
315   else
316     return (gdouble) ((gint64) value);
317 }
318
319 guint64
320 gst_util_gdouble_to_guint64 (gdouble value)
321 {
322   if (value < (gdouble) 9223372036854775808.)   /* 1 << 63 */
323     return ((guint64) ((gint64) value));
324
325   value -= (gdouble) 18446744073709551616.;
326   return ((guint64) ((gint64) value));
327 }
328
329 /* convenience struct for getting high and low uint32 parts of
330  * a guint64 */
331 typedef union
332 {
333   guint64 ll;
334   struct
335   {
336 #if G_BYTE_ORDER == G_BIG_ENDIAN
337     guint32 high, low;
338 #else
339     guint32 low, high;
340 #endif
341   } l;
342 } GstUInt64;
343
344 /* based on Hacker's Delight p152 */
345 static guint64
346 gst_util_div128_64 (GstUInt64 c1, GstUInt64 c0, guint64 denom)
347 {
348   GstUInt64 q1, q0, rhat;
349   GstUInt64 v, cmp1, cmp2;
350   guint s;
351
352   v.ll = denom;
353
354   /* count number of leading zeroes, we know they must be in the high
355    * part of denom since denom > G_MAXUINT32. */
356   s = v.l.high | (v.l.high >> 1);
357   s |= (s >> 2);
358   s |= (s >> 4);
359   s |= (s >> 8);
360   s = ~(s | (s >> 16));
361   s = s - ((s >> 1) & 0x55555555);
362   s = (s & 0x33333333) + ((s >> 2) & 0x33333333);
363   s = (s + (s >> 4)) & 0x0f0f0f0f;
364   s += (s >> 8);
365   s = (s + (s >> 16)) & 0x3f;
366
367   if (s > 0) {
368     /* normalize divisor and dividend */
369     v.ll <<= s;
370     c1.ll = (c1.ll << s) | (c0.l.high >> (32 - s));
371     c0.ll <<= s;
372   }
373
374   q1.ll = c1.ll / v.l.high;
375   rhat.ll = c1.ll - q1.ll * v.l.high;
376
377   cmp1.l.high = rhat.l.low;
378   cmp1.l.low = c0.l.high;
379   cmp2.ll = q1.ll * v.l.low;
380
381   while (q1.l.high || cmp2.ll > cmp1.ll) {
382     q1.ll--;
383     rhat.ll += v.l.high;
384     if (rhat.l.high)
385       break;
386     cmp1.l.high = rhat.l.low;
387     cmp2.ll -= v.l.low;
388   }
389   c1.l.high = c1.l.low;
390   c1.l.low = c0.l.high;
391   c1.ll -= q1.ll * v.ll;
392   q0.ll = c1.ll / v.l.high;
393   rhat.ll = c1.ll - q0.ll * v.l.high;
394
395   cmp1.l.high = rhat.l.low;
396   cmp1.l.low = c0.l.low;
397   cmp2.ll = q0.ll * v.l.low;
398
399   while (q0.l.high || cmp2.ll > cmp1.ll) {
400     q0.ll--;
401     rhat.ll += v.l.high;
402     if (rhat.l.high)
403       break;
404     cmp1.l.high = rhat.l.low;
405     cmp2.ll -= v.l.low;
406   }
407   q0.l.high += q1.l.low;
408
409   return q0.ll;
410 }
411
412 static guint64
413 gst_util_uint64_scale_int64 (guint64 val, guint64 num, guint64 denom)
414 {
415   GstUInt64 a0, a1, b0, b1, c0, ct, c1, result;
416   GstUInt64 v, n;
417
418   /* prepare input */
419   v.ll = val;
420   n.ll = num;
421
422   /* do 128 bits multiply
423    *                   nh   nl
424    *                *  vh   vl
425    *                ----------
426    * a0 =              vl * nl
427    * a1 =         vl * nh
428    * b0 =         vh * nl
429    * b1 =  + vh * nh
430    *       -------------------
431    * c1,c0
432    */
433   a0.ll = (guint64) v.l.low * n.l.low;
434   a1.ll = (guint64) v.l.low * n.l.high;
435   b0.ll = (guint64) v.l.high * n.l.low;
436   b1.ll = (guint64) v.l.high * n.l.high;
437
438   /* and sum together with carry into 128 bits c1, c0 */
439   c0.l.low = a0.l.low;
440   ct.ll = (guint64) a0.l.high + a1.l.low + b0.l.low;
441   c0.l.high = ct.l.low;
442   c1.ll = (guint64) a1.l.high + b0.l.high + ct.l.high + b1.ll;
443
444   /* if high bits bigger than denom, we overflow */
445   if (c1.ll >= denom)
446     goto overflow;
447
448   /* shortcut for division by 1, c1.ll should be 0 because of the
449    * overflow check above. */
450   if (denom == 1)
451     return c0.ll;
452
453   /* and 128/64 bits division, result fits 64 bits */
454   if (denom <= G_MAXUINT32) {
455     guint32 den = (guint32) denom;
456
457     /* easy case, (c1,c0)128/(den)32 division */
458     c1.l.high %= den;
459     c1.l.high = c1.ll % den;
460     c1.l.low = c0.l.high;
461     c0.l.high = c1.ll % den;
462     result.l.high = c1.ll / den;
463     result.l.low = c0.ll / den;
464   } else {
465     result.ll = gst_util_div128_64 (c1, c0, denom);
466   }
467   return result.ll;
468
469 overflow:
470   {
471     return G_MAXUINT64;
472   }
473 }
474
475 /**
476  * gst_util_uint64_scale:
477  * @val: the number to scale
478  * @num: the numerator of the scale ratio
479  * @denom: the denominator of the scale ratio
480  *
481  * Scale @val by @num / @denom, trying to avoid overflows.
482  *
483  * This function can potentially be very slow if denom > G_MAXUINT32.
484  *
485  * Returns: @val * @num / @denom, trying to avoid overflows.
486  * In the case of an overflow, this function returns G_MAXUINT64.
487  */
488 guint64
489 gst_util_uint64_scale (guint64 val, guint64 num, guint64 denom)
490 {
491   g_return_val_if_fail (denom != 0, G_MAXUINT64);
492
493   if (num == 0)
494     return 0;
495
496   if (num == 1 && denom == 1)
497     return val;
498
499   /* if the denom is high, we need to do a 64 muldiv */
500   if (denom > G_MAXINT32)
501     goto do_int64;
502
503   /* if num and denom are low we can do a 32 bit muldiv */
504   if (num <= G_MAXINT32)
505     goto do_int32;
506
507   /* val and num are high, we need 64 muldiv */
508   if (val > G_MAXINT32)
509     goto do_int64;
510
511   /* val is low and num is high, we can swap them and do 32 muldiv */
512   return gst_util_uint64_scale_int (num, (gint) val, (gint) denom);
513
514 do_int32:
515   return gst_util_uint64_scale_int (val, (gint) num, (gint) denom);
516
517 do_int64:
518   /* to the more heavy implementations... */
519   return gst_util_uint64_scale_int64 (val, num, denom);
520 }
521
522 /**
523  * gst_util_uint64_scale_int:
524  * @val: guint64 (such as a #GstClockTime) to scale.
525  * @num: numerator of the scale factor.
526  * @denom: denominator of the scale factor.
527  *
528  * Scale a guint64 by a factor expressed as a fraction (num/denom), avoiding
529  * overflows and loss of precision.
530  *
531  * @num and @denom must be positive integers. @denom cannot be 0.
532  *
533  * Returns: @val * @num / @denom, avoiding overflow and loss of precision.
534  * In the case of an overflow, this function returns G_MAXUINT64.
535  */
536 guint64
537 gst_util_uint64_scale_int (guint64 val, gint num, gint denom)
538 {
539   GstUInt64 result;
540   GstUInt64 low, high;
541
542   g_return_val_if_fail (denom > 0, G_MAXUINT64);
543   g_return_val_if_fail (num >= 0, G_MAXUINT64);
544
545   if (num == 0)
546     return 0;
547
548   if (num == 1 && denom == 1)
549     return val;
550
551   if (val <= G_MAXUINT32)
552     /* simple case */
553     return val * num / denom;
554
555   /* do 96 bits mult/div */
556   low.ll = val;
557   result.ll = ((guint64) low.l.low) * num;
558   high.ll = ((guint64) low.l.high) * num + (result.l.high);
559
560   low.ll = high.ll / denom;
561   result.l.high = high.ll % denom;
562   result.ll /= denom;
563
564   /* avoid overflow */
565   if (low.ll + result.l.high > G_MAXUINT32)
566     goto overflow;
567
568   result.l.high += low.l.low;
569
570   return result.ll;
571
572 overflow:
573   {
574     return G_MAXUINT64;
575   }
576 }
577
578 /* -----------------------------------------------------
579  *
580  *  The following code will be moved out of the main
581  * gstreamer library someday.
582  */
583
584 #include "gstpad.h"
585
586 static void
587 string_append_indent (GString * str, gint count)
588 {
589   gint xx;
590
591   for (xx = 0; xx < count; xx++)
592     g_string_append_c (str, ' ');
593 }
594
595 /**
596  * gst_print_pad_caps:
597  * @buf: the buffer to print the caps in
598  * @indent: initial indentation
599  * @pad: the pad to print the caps from
600  *
601  * Write the pad capabilities in a human readable format into
602  * the given GString.
603  */
604 void
605 gst_print_pad_caps (GString * buf, gint indent, GstPad * pad)
606 {
607   GstCaps *caps;
608
609   caps = pad->caps;
610
611   if (!caps) {
612     string_append_indent (buf, indent);
613     g_string_printf (buf, "%s:%s has no capabilities",
614         GST_DEBUG_PAD_NAME (pad));
615   } else {
616     char *s;
617
618     s = gst_caps_to_string (caps);
619     g_string_append (buf, s);
620     g_free (s);
621   }
622 }
623
624 /**
625  * gst_print_element_args:
626  * @buf: the buffer to print the args in
627  * @indent: initial indentation
628  * @element: the element to print the args of
629  *
630  * Print the element argument in a human readable format in the given
631  * GString.
632  */
633 void
634 gst_print_element_args (GString * buf, gint indent, GstElement * element)
635 {
636   guint width;
637   GValue value = { 0, };        /* the important thing is that value.type = 0 */
638   gchar *str = NULL;
639   GParamSpec *spec, **specs, **walk;
640
641   specs = g_object_class_list_properties (G_OBJECT_GET_CLASS (element), NULL);
642
643   width = 0;
644   for (walk = specs; *walk; walk++) {
645     spec = *walk;
646     if (width < strlen (spec->name))
647       width = strlen (spec->name);
648   }
649
650   for (walk = specs; *walk; walk++) {
651     spec = *walk;
652
653     if (spec->flags & G_PARAM_READABLE) {
654       g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (spec));
655       g_object_get_property (G_OBJECT (element), spec->name, &value);
656       str = g_strdup_value_contents (&value);
657       g_value_unset (&value);
658     } else {
659       str = g_strdup ("Parameter not readable.");
660     }
661
662     string_append_indent (buf, indent);
663     g_string_append (buf, spec->name);
664     string_append_indent (buf, 2 + width - strlen (spec->name));
665     g_string_append (buf, str);
666     g_string_append_c (buf, '\n');
667
668     g_free (str);
669   }
670
671   g_free (specs);
672 }
673
674 /**
675  * gst_element_create_all_pads:
676  * @element: a #GstElement to create pads for
677  *
678  * Creates a pad for each pad template that is always available.
679  * This function is only useful during object intialization of
680  * subclasses of #GstElement.
681  */
682 void
683 gst_element_create_all_pads (GstElement * element)
684 {
685   GList *padlist;
686
687   /* FIXME: lock element */
688
689   padlist =
690       gst_element_class_get_pad_template_list (GST_ELEMENT_CLASS
691       (G_OBJECT_GET_CLASS (element)));
692
693   while (padlist) {
694     GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
695
696     if (padtempl->presence == GST_PAD_ALWAYS) {
697       GstPad *pad;
698
699       pad = gst_pad_new_from_template (padtempl, padtempl->name_template);
700
701       gst_element_add_pad (element, pad);
702     }
703     padlist = padlist->next;
704   }
705 }
706
707 /**
708  * gst_element_get_compatible_pad_template:
709  * @element: a #GstElement to get a compatible pad template for.
710  * @compattempl: the #GstPadTemplate to find a compatible template for.
711  *
712  * Retrieves a pad template from @element that is compatible with @compattempl.
713  * Pads from compatible templates can be linked together.
714  *
715  * Returns: a compatible #GstPadTemplate, or NULL if none was found. No
716  * unreferencing is necessary.
717  */
718 GstPadTemplate *
719 gst_element_get_compatible_pad_template (GstElement * element,
720     GstPadTemplate * compattempl)
721 {
722   GstPadTemplate *newtempl = NULL;
723   GList *padlist;
724   GstElementClass *class;
725
726   g_return_val_if_fail (element != NULL, NULL);
727   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
728   g_return_val_if_fail (compattempl != NULL, NULL);
729
730   class = GST_ELEMENT_GET_CLASS (element);
731
732   padlist = gst_element_class_get_pad_template_list (class);
733
734   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
735       "Looking for a suitable pad template in %s out of %d templates...",
736       GST_ELEMENT_NAME (element), g_list_length (padlist));
737
738   while (padlist) {
739     GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
740     GstCaps *intersection;
741
742     /* Ignore name
743      * Ignore presence
744      * Check direction (must be opposite)
745      * Check caps
746      */
747     GST_CAT_LOG (GST_CAT_CAPS,
748         "checking pad template %s", padtempl->name_template);
749     if (padtempl->direction != compattempl->direction) {
750       GST_CAT_DEBUG (GST_CAT_CAPS,
751           "compatible direction: found %s pad template \"%s\"",
752           padtempl->direction == GST_PAD_SRC ? "src" : "sink",
753           padtempl->name_template);
754
755       GST_CAT_DEBUG (GST_CAT_CAPS,
756           "intersecting %" GST_PTR_FORMAT, GST_PAD_TEMPLATE_CAPS (compattempl));
757       GST_CAT_DEBUG (GST_CAT_CAPS,
758           "..and %" GST_PTR_FORMAT, GST_PAD_TEMPLATE_CAPS (padtempl));
759
760       intersection = gst_caps_intersect (GST_PAD_TEMPLATE_CAPS (compattempl),
761           GST_PAD_TEMPLATE_CAPS (padtempl));
762
763       GST_CAT_DEBUG (GST_CAT_CAPS, "caps are %scompatible %" GST_PTR_FORMAT,
764           (intersection ? "" : "not "), intersection);
765
766       if (!gst_caps_is_empty (intersection))
767         newtempl = padtempl;
768       gst_caps_unref (intersection);
769       if (newtempl)
770         break;
771     }
772
773     padlist = g_list_next (padlist);
774   }
775   if (newtempl)
776     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
777         "Returning new pad template %p", newtempl);
778   else
779     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "No compatible pad template found");
780
781   return newtempl;
782 }
783
784 static GstPad *
785 gst_element_request_pad (GstElement * element, GstPadTemplate * templ,
786     const gchar * name)
787 {
788   GstPad *newpad = NULL;
789   GstElementClass *oclass;
790
791   oclass = GST_ELEMENT_GET_CLASS (element);
792
793   if (oclass->request_new_pad)
794     newpad = (oclass->request_new_pad) (element, templ, name);
795
796   if (newpad)
797     gst_object_ref (newpad);
798
799   return newpad;
800 }
801
802
803
804 /**
805  * gst_element_get_pad_from_template:
806  * @element: a #GstElement.
807  * @templ: a #GstPadTemplate belonging to @element.
808  *
809  * Gets a pad from @element described by @templ. If the presence of @templ is
810  * #GST_PAD_REQUEST, requests a new pad. Can return %NULL for #GST_PAD_SOMETIMES
811  * templates.
812  *
813  * Returns: the #GstPad, or NULL if one could not be found or created.
814  */
815 static GstPad *
816 gst_element_get_pad_from_template (GstElement * element, GstPadTemplate * templ)
817 {
818   GstPad *ret = NULL;
819   GstPadPresence presence;
820
821   /* If this function is ever exported, we need check the validity of `element'
822    * and `templ', and to make sure the template actually belongs to the
823    * element. */
824
825   presence = GST_PAD_TEMPLATE_PRESENCE (templ);
826
827   switch (presence) {
828     case GST_PAD_ALWAYS:
829     case GST_PAD_SOMETIMES:
830       ret = gst_element_get_static_pad (element, templ->name_template);
831       if (!ret && presence == GST_PAD_ALWAYS)
832         g_warning
833             ("Element %s has an ALWAYS template %s, but no pad of the same name",
834             GST_OBJECT_NAME (element), templ->name_template);
835       break;
836
837     case GST_PAD_REQUEST:
838       ret = gst_element_request_pad (element, templ, NULL);
839       break;
840   }
841
842   return ret;
843 }
844
845 /**
846  * gst_element_request_compatible_pad:
847  * @element: a #GstElement.
848  * @templ: the #GstPadTemplate to which the new pad should be able to link.
849  *
850  * Requests a pad from @element. The returned pad should be unlinked and
851  * compatible with @templ. Might return an existing pad, or request a new one.
852  *
853  * Returns: a #GstPad, or %NULL if one could not be found or created.
854  */
855 GstPad *
856 gst_element_request_compatible_pad (GstElement * element,
857     GstPadTemplate * templ)
858 {
859   GstPadTemplate *templ_new;
860   GstPad *pad = NULL;
861
862   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
863   g_return_val_if_fail (GST_IS_PAD_TEMPLATE (templ), NULL);
864
865   /* FIXME: should really loop through the templates, testing each for
866    *      compatibility and pad availability. */
867   templ_new = gst_element_get_compatible_pad_template (element, templ);
868   if (templ_new)
869     pad = gst_element_get_pad_from_template (element, templ_new);
870
871   /* This can happen for non-request pads. No need to unref. */
872   if (pad && GST_PAD_PEER (pad))
873     pad = NULL;
874
875   return pad;
876 }
877
878 /**
879  * gst_element_get_compatible_pad:
880  * @element: a #GstElement in which the pad should be found.
881  * @pad: the #GstPad to find a compatible one for.
882  * @caps: the #GstCaps to use as a filter.
883  *
884  * Looks for an unlinked pad to which the given pad can link. It is not
885  * guaranteed that linking the pads will work, though it should work in most
886  * cases.
887  *
888  * Returns: the #GstPad to which a link can be made, or %NULL if one cannot be
889  * found. gst_object_unref() after usage.
890  */
891 GstPad *
892 gst_element_get_compatible_pad (GstElement * element, GstPad * pad,
893     const GstCaps * caps)
894 {
895   GstIterator *pads;
896   GstPadTemplate *templ;
897   GstCaps *templcaps;
898   GstPad *foundpad = NULL;
899   gboolean done;
900
901   /* FIXME check for caps compatibility */
902
903   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
904   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
905
906   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
907       "finding pad in %s compatible with %s:%s",
908       GST_ELEMENT_NAME (element), GST_DEBUG_PAD_NAME (pad));
909
910   g_return_val_if_fail (GST_PAD_PEER (pad) == NULL, NULL);
911
912   done = FALSE;
913   /* try to get an existing unlinked pad */
914   pads = gst_element_iterate_pads (element);
915   while (!done) {
916     gpointer padptr;
917
918     switch (gst_iterator_next (pads, &padptr)) {
919       case GST_ITERATOR_OK:
920       {
921         GstPad *peer;
922         GstPad *current;
923
924         current = GST_PAD (padptr);
925
926         GST_CAT_LOG (GST_CAT_ELEMENT_PADS, "examining pad %s:%s",
927             GST_DEBUG_PAD_NAME (current));
928
929         peer = gst_pad_get_peer (current);
930
931         if (peer == NULL && gst_pad_can_link (pad, current)) {
932
933           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
934               "found existing unlinked pad %s:%s",
935               GST_DEBUG_PAD_NAME (current));
936
937           gst_iterator_free (pads);
938
939           return current;
940         } else {
941           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "unreffing pads");
942
943           gst_object_unref (current);
944           if (peer)
945             gst_object_unref (peer);
946         }
947         break;
948       }
949       case GST_ITERATOR_DONE:
950         done = TRUE;
951         break;
952       case GST_ITERATOR_RESYNC:
953         gst_iterator_resync (pads);
954         break;
955       case GST_ITERATOR_ERROR:
956         g_assert_not_reached ();
957         break;
958     }
959   }
960   gst_iterator_free (pads);
961
962   /* try to create a new one */
963   /* requesting is a little crazy, we need a template. Let's create one */
964   templcaps = gst_pad_get_caps (pad);
965
966   templ = gst_pad_template_new ((gchar *) GST_PAD_NAME (pad),
967       GST_PAD_DIRECTION (pad), GST_PAD_ALWAYS, templcaps);
968   foundpad = gst_element_request_compatible_pad (element, templ);
969   gst_object_unref (templ);
970
971   if (foundpad) {
972     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
973         "found existing request pad %s:%s", GST_DEBUG_PAD_NAME (foundpad));
974     return foundpad;
975   }
976
977   GST_CAT_INFO_OBJECT (GST_CAT_ELEMENT_PADS, element,
978       "Could not find a compatible pad to link to %s:%s",
979       GST_DEBUG_PAD_NAME (pad));
980   return NULL;
981 }
982
983 /**
984  * gst_element_state_get_name:
985  * @state: a #GstState to get the name of.
986  *
987  * Gets a string representing the given state.
988  *
989  * Returns: a string with the name of the state.
990  */
991 G_CONST_RETURN gchar *
992 gst_element_state_get_name (GstState state)
993 {
994   switch (state) {
995 #ifdef GST_DEBUG_COLOR
996     case GST_STATE_VOID_PENDING:
997       return "VOID_PENDING";
998     case GST_STATE_NULL:
999       return "\033[01;34mNULL\033[00m";
1000     case GST_STATE_READY:
1001       return "\033[01;31mREADY\033[00m";
1002     case GST_STATE_PLAYING:
1003       return "\033[01;32mPLAYING\033[00m";
1004     case GST_STATE_PAUSED:
1005       return "\033[01;33mPAUSED\033[00m";
1006     default:
1007       /* This is a memory leak */
1008       return g_strdup_printf ("\033[01;35;41mUNKNOWN!\033[00m(%d)", state);
1009 #else
1010     case GST_STATE_VOID_PENDING:
1011       return "VOID_PENDING";
1012     case GST_STATE_NULL:
1013       return "NULL";
1014     case GST_STATE_READY:
1015       return "READY";
1016     case GST_STATE_PLAYING:
1017       return "PLAYING";
1018     case GST_STATE_PAUSED:
1019       return "PAUSED";
1020     default:
1021       /* This is a memory leak */
1022       return g_strdup_printf ("UNKNOWN!(%d)", state);
1023 #endif
1024   }
1025 }
1026
1027 /**
1028  * gst_element_state_change_return_get_name:
1029  * @state_ret: a #GstStateChangeReturn to get the name of.
1030  *
1031  * Gets a string representing the given state change result.
1032  *
1033  * Returns: a string with the name of the state change result.
1034  *
1035  * Since: 0.10.11
1036  */
1037 G_CONST_RETURN gchar *
1038 gst_element_state_change_return_get_name (GstStateChangeReturn state_ret)
1039 {
1040   switch (state_ret) {
1041 #ifdef GST_DEBUG_COLOR
1042     case GST_STATE_CHANGE_FAILURE:
1043       return "\033[01;31mFAILURE\033[00m";
1044     case GST_STATE_CHANGE_SUCCESS:
1045       return "\033[01;32mSUCCESS\033[00m";
1046     case GST_STATE_CHANGE_ASYNC:
1047       return "\033[01;33mASYNC\033[00m";
1048     case GST_STATE_CHANGE_NO_PREROLL:
1049       return "\033[01;34mNO_PREROLL\033[00m";
1050     default:
1051       /* This is a memory leak */
1052       return g_strdup_printf ("\033[01;35;41mUNKNOWN!\033[00m(%d)", state_ret);
1053 #else
1054     case GST_STATE_CHANGE_FAILURE:
1055       return "FAILURE";
1056     case GST_STATE_CHANGE_SUCCESS:
1057       return "SUCCESS";
1058     case GST_STATE_CHANGE_ASYNC:
1059       return "ASYNC";
1060     case GST_STATE_CHANGE_NO_PREROLL:
1061       return "NO PREROLL";
1062     default:
1063       /* This is a memory leak */
1064       return g_strdup_printf ("UNKNOWN!(%d)", state_ret);
1065 #endif
1066   }
1067 }
1068
1069
1070 /**
1071  * gst_element_factory_can_src_caps :
1072  * @factory: factory to query
1073  * @caps: the caps to check
1074  *
1075  * Checks if the factory can source the given capability.
1076  *
1077  * Returns: true if it can src the capabilities
1078  */
1079 gboolean
1080 gst_element_factory_can_src_caps (GstElementFactory * factory,
1081     const GstCaps * caps)
1082 {
1083   GList *templates;
1084
1085   g_return_val_if_fail (factory != NULL, FALSE);
1086   g_return_val_if_fail (caps != NULL, FALSE);
1087
1088   templates = factory->staticpadtemplates;
1089
1090   while (templates) {
1091     GstStaticPadTemplate *template = (GstStaticPadTemplate *) templates->data;
1092
1093     if (template->direction == GST_PAD_SRC) {
1094       if (gst_caps_is_always_compatible (gst_static_caps_get (&template->
1095                   static_caps), caps))
1096         return TRUE;
1097     }
1098     templates = g_list_next (templates);
1099   }
1100
1101   return FALSE;
1102 }
1103
1104 /**
1105  * gst_element_factory_can_sink_caps :
1106  * @factory: factory to query
1107  * @caps: the caps to check
1108  *
1109  * Checks if the factory can sink the given capability.
1110  *
1111  * Returns: true if it can sink the capabilities
1112  */
1113 gboolean
1114 gst_element_factory_can_sink_caps (GstElementFactory * factory,
1115     const GstCaps * caps)
1116 {
1117   GList *templates;
1118
1119   g_return_val_if_fail (factory != NULL, FALSE);
1120   g_return_val_if_fail (caps != NULL, FALSE);
1121
1122   templates = factory->staticpadtemplates;
1123
1124   while (templates) {
1125     GstStaticPadTemplate *template = (GstStaticPadTemplate *) templates->data;
1126
1127     if (template->direction == GST_PAD_SINK) {
1128       if (gst_caps_is_always_compatible (caps,
1129               gst_static_caps_get (&template->static_caps)))
1130         return TRUE;
1131     }
1132     templates = g_list_next (templates);
1133   }
1134
1135   return FALSE;
1136 }
1137
1138
1139 /* if return val is true, *direct_child is a caller-owned ref on the direct
1140  * child of ancestor that is part of object's ancestry */
1141 static gboolean
1142 object_has_ancestor (GstObject * object, GstObject * ancestor,
1143     GstObject ** direct_child)
1144 {
1145   GstObject *child, *parent;
1146
1147   if (direct_child)
1148     *direct_child = NULL;
1149
1150   child = gst_object_ref (object);
1151   parent = gst_object_get_parent (object);
1152
1153   while (parent) {
1154     if (ancestor == parent) {
1155       if (direct_child)
1156         *direct_child = child;
1157       else
1158         gst_object_unref (child);
1159       gst_object_unref (parent);
1160       return TRUE;
1161     }
1162
1163     gst_object_unref (child);
1164     child = parent;
1165     parent = gst_object_get_parent (parent);
1166   }
1167
1168   gst_object_unref (child);
1169
1170   return FALSE;
1171 }
1172
1173 /* caller owns return */
1174 static GstObject *
1175 find_common_root (GstObject * o1, GstObject * o2)
1176 {
1177   GstObject *top = o1;
1178   GstObject *kid1, *kid2;
1179   GstObject *root = NULL;
1180
1181   while (GST_OBJECT_PARENT (top))
1182     top = GST_OBJECT_PARENT (top);
1183
1184   /* the itsy-bitsy spider... */
1185
1186   if (!object_has_ancestor (o2, top, &kid2))
1187     return NULL;
1188
1189   root = gst_object_ref (top);
1190   while (TRUE) {
1191     if (!object_has_ancestor (o1, kid2, &kid1)) {
1192       gst_object_unref (kid2);
1193       return root;
1194     }
1195     root = kid2;
1196     if (!object_has_ancestor (o2, kid1, &kid2)) {
1197       gst_object_unref (kid1);
1198       return root;
1199     }
1200     root = kid1;
1201   }
1202 }
1203
1204 /* caller does not own return */
1205 static GstPad *
1206 ghost_up (GstElement * e, GstPad * pad)
1207 {
1208   static gint ghost_pad_index = 0;
1209   GstPad *gpad;
1210   gchar *name;
1211   GstObject *parent = GST_OBJECT_PARENT (e);
1212
1213   name = g_strdup_printf ("ghost%d", ghost_pad_index++);
1214   gpad = gst_ghost_pad_new (name, pad);
1215   g_free (name);
1216
1217   if (!gst_element_add_pad ((GstElement *) parent, gpad)) {
1218     g_warning ("Pad named %s already exists in element %s\n",
1219         GST_OBJECT_NAME (gpad), GST_OBJECT_NAME (parent));
1220     gst_object_unref ((GstObject *) gpad);
1221     return NULL;
1222   }
1223
1224   return gpad;
1225 }
1226
1227 static void
1228 remove_pad (gpointer ppad, gpointer unused)
1229 {
1230   GstPad *pad = ppad;
1231
1232   if (!gst_element_remove_pad ((GstElement *) GST_OBJECT_PARENT (pad), pad))
1233     g_warning ("Couldn't remove pad %s from element %s",
1234         GST_OBJECT_NAME (pad), GST_OBJECT_NAME (GST_OBJECT_PARENT (pad)));
1235 }
1236
1237 static gboolean
1238 prepare_link_maybe_ghosting (GstPad ** src, GstPad ** sink,
1239     GSList ** pads_created)
1240 {
1241   GstObject *root;
1242   GstObject *e1, *e2;
1243   GSList *pads_created_local = NULL;
1244
1245   g_assert (pads_created);
1246
1247   e1 = GST_OBJECT_PARENT (*src);
1248   e2 = GST_OBJECT_PARENT (*sink);
1249
1250   if (G_UNLIKELY (e1 == NULL)) {
1251     GST_WARNING ("Trying to ghost a pad that doesn't have a parent: %"
1252         GST_PTR_FORMAT, *src);
1253     return FALSE;
1254   }
1255   if (G_UNLIKELY (e2 == NULL)) {
1256     GST_WARNING ("Trying to ghost a pad that doesn't have a parent: %"
1257         GST_PTR_FORMAT, *sink);
1258     return FALSE;
1259   }
1260
1261   if (GST_OBJECT_PARENT (e1) == GST_OBJECT_PARENT (e2)) {
1262     GST_CAT_INFO (GST_CAT_PADS, "%s and %s in same bin, no need for ghost pads",
1263         GST_OBJECT_NAME (e1), GST_OBJECT_NAME (e2));
1264     return TRUE;
1265   }
1266
1267   GST_CAT_INFO (GST_CAT_PADS, "%s and %s not in same bin, making ghost pads",
1268       GST_OBJECT_NAME (e1), GST_OBJECT_NAME (e2));
1269
1270   /* we need to setup some ghost pads */
1271   root = find_common_root (e1, e2);
1272   if (!root) {
1273     g_warning ("Trying to connect elements that don't share a common "
1274         "ancestor: %s and %s", GST_ELEMENT_NAME (e1), GST_ELEMENT_NAME (e2));
1275     return FALSE;
1276   }
1277
1278   while (GST_OBJECT_PARENT (e1) != root) {
1279     *src = ghost_up ((GstElement *) e1, *src);
1280     if (!*src)
1281       goto cleanup_fail;
1282     e1 = GST_OBJECT_PARENT (*src);
1283     pads_created_local = g_slist_prepend (pads_created_local, *src);
1284   }
1285   while (GST_OBJECT_PARENT (e2) != root) {
1286     *sink = ghost_up ((GstElement *) e2, *sink);
1287     if (!*sink)
1288       goto cleanup_fail;
1289     e2 = GST_OBJECT_PARENT (*sink);
1290     pads_created_local = g_slist_prepend (pads_created_local, *sink);
1291   }
1292
1293   gst_object_unref (root);
1294   *pads_created = g_slist_concat (*pads_created, pads_created_local);
1295   return TRUE;
1296
1297 cleanup_fail:
1298   gst_object_unref (root);
1299   g_slist_foreach (pads_created_local, remove_pad, NULL);
1300   g_slist_free (pads_created_local);
1301   return FALSE;
1302 }
1303
1304 static gboolean
1305 pad_link_maybe_ghosting (GstPad * src, GstPad * sink)
1306 {
1307   GSList *pads_created = NULL;
1308   gboolean ret;
1309
1310   if (!prepare_link_maybe_ghosting (&src, &sink, &pads_created)) {
1311     ret = FALSE;
1312   } else {
1313     ret = (gst_pad_link (src, sink) == GST_PAD_LINK_OK);
1314   }
1315
1316   if (!ret) {
1317     g_slist_foreach (pads_created, remove_pad, NULL);
1318   }
1319   g_slist_free (pads_created);
1320
1321   return ret;
1322 }
1323
1324 /**
1325  * gst_element_link_pads:
1326  * @src: a #GstElement containing the source pad.
1327  * @srcpadname: the name of the #GstPad in source element or NULL for any pad.
1328  * @dest: the #GstElement containing the destination pad.
1329  * @destpadname: the name of the #GstPad in destination element,
1330  * or NULL for any pad.
1331  *
1332  * Links the two named pads of the source and destination elements.
1333  * Side effect is that if one of the pads has no parent, it becomes a
1334  * child of the parent of the other element.  If they have different
1335  * parents, the link fails.
1336  *
1337  * Returns: TRUE if the pads could be linked, FALSE otherwise.
1338  */
1339 gboolean
1340 gst_element_link_pads (GstElement * src, const gchar * srcpadname,
1341     GstElement * dest, const gchar * destpadname)
1342 {
1343   const GList *srcpads, *destpads, *srctempls, *desttempls, *l;
1344   GstPad *srcpad, *destpad;
1345   GstPadTemplate *srctempl, *desttempl;
1346   GstElementClass *srcclass, *destclass;
1347
1348   /* checks */
1349   g_return_val_if_fail (GST_IS_ELEMENT (src), FALSE);
1350   g_return_val_if_fail (GST_IS_ELEMENT (dest), FALSE);
1351
1352   srcclass = GST_ELEMENT_GET_CLASS (src);
1353   destclass = GST_ELEMENT_GET_CLASS (dest);
1354
1355   GST_CAT_INFO (GST_CAT_ELEMENT_PADS,
1356       "trying to link element %s:%s to element %s:%s", GST_ELEMENT_NAME (src),
1357       srcpadname ? srcpadname : "(any)", GST_ELEMENT_NAME (dest),
1358       destpadname ? destpadname : "(any)");
1359
1360   /* get a src pad */
1361   if (srcpadname) {
1362     /* name specified, look it up */
1363     srcpad = gst_element_get_pad (src, srcpadname);
1364     if (!srcpad) {
1365       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no pad %s:%s",
1366           GST_ELEMENT_NAME (src), srcpadname);
1367       return FALSE;
1368     } else {
1369       if (!(GST_PAD_DIRECTION (srcpad) == GST_PAD_SRC)) {
1370         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is no src pad",
1371             GST_DEBUG_PAD_NAME (srcpad));
1372         gst_object_unref (srcpad);
1373         return FALSE;
1374       }
1375       if (GST_PAD_PEER (srcpad) != NULL) {
1376         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is already linked",
1377             GST_DEBUG_PAD_NAME (srcpad));
1378         gst_object_unref (srcpad);
1379         return FALSE;
1380       }
1381     }
1382     srcpads = NULL;
1383   } else {
1384     /* no name given, get the first available pad */
1385     GST_OBJECT_LOCK (src);
1386     srcpads = GST_ELEMENT_PADS (src);
1387     srcpad = srcpads ? GST_PAD_CAST (srcpads->data) : NULL;
1388     if (srcpad)
1389       gst_object_ref (srcpad);
1390     GST_OBJECT_UNLOCK (src);
1391   }
1392
1393   /* get a destination pad */
1394   if (destpadname) {
1395     /* name specified, look it up */
1396     destpad = gst_element_get_pad (dest, destpadname);
1397     if (!destpad) {
1398       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no pad %s:%s",
1399           GST_ELEMENT_NAME (dest), destpadname);
1400       return FALSE;
1401     } else {
1402       if (!(GST_PAD_DIRECTION (destpad) == GST_PAD_SINK)) {
1403         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is no sink pad",
1404             GST_DEBUG_PAD_NAME (destpad));
1405         gst_object_unref (destpad);
1406         return FALSE;
1407       }
1408       if (GST_PAD_PEER (destpad) != NULL) {
1409         GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is already linked",
1410             GST_DEBUG_PAD_NAME (destpad));
1411         gst_object_unref (destpad);
1412         return FALSE;
1413       }
1414     }
1415     destpads = NULL;
1416   } else {
1417     /* no name given, get the first available pad */
1418     GST_OBJECT_LOCK (dest);
1419     destpads = GST_ELEMENT_PADS (dest);
1420     destpad = destpads ? GST_PAD_CAST (destpads->data) : NULL;
1421     if (destpad)
1422       gst_object_ref (destpad);
1423     GST_OBJECT_UNLOCK (dest);
1424   }
1425
1426   if (srcpadname && destpadname) {
1427     gboolean result;
1428
1429     /* two explicitly specified pads */
1430     result = pad_link_maybe_ghosting (srcpad, destpad);
1431
1432     gst_object_unref (srcpad);
1433     gst_object_unref (destpad);
1434
1435     return result;
1436   }
1437
1438   if (srcpad) {
1439     /* loop through the allowed pads in the source, trying to find a
1440      * compatible destination pad */
1441     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1442         "looping through allowed src and dest pads");
1443     do {
1444       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "trying src pad %s:%s",
1445           GST_DEBUG_PAD_NAME (srcpad));
1446       if ((GST_PAD_DIRECTION (srcpad) == GST_PAD_SRC) &&
1447           (GST_PAD_PEER (srcpad) == NULL)) {
1448         GstPad *temp;
1449
1450         if (destpadname) {
1451           temp = destpad;
1452           gst_object_ref (temp);
1453         } else {
1454           temp = gst_element_get_compatible_pad (dest, srcpad, NULL);
1455         }
1456
1457         if (temp && pad_link_maybe_ghosting (srcpad, temp)) {
1458           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "linked pad %s:%s to pad %s:%s",
1459               GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (temp));
1460           if (destpad)
1461             gst_object_unref (destpad);
1462           gst_object_unref (srcpad);
1463           gst_object_unref (temp);
1464           return TRUE;
1465         }
1466
1467         if (temp) {
1468           gst_object_unref (temp);
1469         }
1470       }
1471       /* find a better way for this mess */
1472       if (srcpads) {
1473         srcpads = g_list_next (srcpads);
1474         if (srcpads) {
1475           gst_object_unref (srcpad);
1476           srcpad = GST_PAD_CAST (srcpads->data);
1477           gst_object_ref (srcpad);
1478         }
1479       }
1480     } while (srcpads);
1481   }
1482   if (srcpadname) {
1483     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s:%s to %s",
1484         GST_DEBUG_PAD_NAME (srcpad), GST_ELEMENT_NAME (dest));
1485     if (destpad)
1486       gst_object_unref (destpad);
1487     destpad = NULL;
1488   }
1489   if (srcpad)
1490     gst_object_unref (srcpad);
1491   srcpad = NULL;
1492
1493   if (destpad) {
1494     /* loop through the existing pads in the destination */
1495     do {
1496       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "trying dest pad %s:%s",
1497           GST_DEBUG_PAD_NAME (destpad));
1498       if ((GST_PAD_DIRECTION (destpad) == GST_PAD_SINK) &&
1499           (GST_PAD_PEER (destpad) == NULL)) {
1500         GstPad *temp = gst_element_get_compatible_pad (src, destpad, NULL);
1501
1502         if (temp && pad_link_maybe_ghosting (temp, destpad)) {
1503           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "linked pad %s:%s to pad %s:%s",
1504               GST_DEBUG_PAD_NAME (temp), GST_DEBUG_PAD_NAME (destpad));
1505           gst_object_unref (temp);
1506           gst_object_unref (destpad);
1507           return TRUE;
1508         }
1509         if (temp) {
1510           gst_object_unref (temp);
1511         }
1512       }
1513       if (destpads) {
1514         destpads = g_list_next (destpads);
1515         if (destpads) {
1516           gst_object_unref (destpad);
1517           destpad = GST_PAD_CAST (destpads->data);
1518           gst_object_ref (destpad);
1519         }
1520       }
1521     } while (destpads);
1522   }
1523
1524   if (destpadname) {
1525     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s to %s:%s",
1526         GST_ELEMENT_NAME (src), GST_DEBUG_PAD_NAME (destpad));
1527     gst_object_unref (destpad);
1528     return FALSE;
1529   } else {
1530     if (destpad)
1531       gst_object_unref (destpad);
1532     destpad = NULL;
1533   }
1534
1535   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1536       "we might have request pads on both sides, checking...");
1537   srctempls = gst_element_class_get_pad_template_list (srcclass);
1538   desttempls = gst_element_class_get_pad_template_list (destclass);
1539
1540   if (srctempls && desttempls) {
1541     while (srctempls) {
1542       srctempl = (GstPadTemplate *) srctempls->data;
1543       if (srctempl->presence == GST_PAD_REQUEST) {
1544         for (l = desttempls; l; l = l->next) {
1545           desttempl = (GstPadTemplate *) l->data;
1546           if (desttempl->presence == GST_PAD_REQUEST &&
1547               desttempl->direction != srctempl->direction) {
1548             if (gst_caps_is_always_compatible (gst_pad_template_get_caps
1549                     (srctempl), gst_pad_template_get_caps (desttempl))) {
1550               srcpad =
1551                   gst_element_get_request_pad (src, srctempl->name_template);
1552               destpad =
1553                   gst_element_get_request_pad (dest, desttempl->name_template);
1554               if (srcpad && destpad
1555                   && pad_link_maybe_ghosting (srcpad, destpad)) {
1556                 GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1557                     "linked pad %s:%s to pad %s:%s",
1558                     GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (destpad));
1559                 gst_object_unref (srcpad);
1560                 gst_object_unref (destpad);
1561                 return TRUE;
1562               }
1563               /* it failed, so we release the request pads */
1564               if (srcpad)
1565                 gst_element_release_request_pad (src, srcpad);
1566               if (destpad)
1567                 gst_element_release_request_pad (dest, destpad);
1568             }
1569           }
1570         }
1571       }
1572       srctempls = srctempls->next;
1573     }
1574   }
1575
1576   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "no link possible from %s to %s",
1577       GST_ELEMENT_NAME (src), GST_ELEMENT_NAME (dest));
1578   return FALSE;
1579 }
1580
1581 /**
1582  * gst_element_link_pads_filtered:
1583  * @src: a #GstElement containing the source pad.
1584  * @srcpadname: the name of the #GstPad in source element or NULL for any pad.
1585  * @dest: the #GstElement containing the destination pad.
1586  * @destpadname: the name of the #GstPad in destination element or NULL for any pad.
1587  * @filter: the #GstCaps to filter the link, or #NULL for no filter.
1588  *
1589  * Links the two named pads of the source and destination elements. Side effect
1590  * is that if one of the pads has no parent, it becomes a child of the parent of
1591  * the other element. If they have different parents, the link fails. If @caps
1592  * is not #NULL, makes sure that the caps of the link is a subset of @caps.
1593  *
1594  * Returns: TRUE if the pads could be linked, FALSE otherwise.
1595  */
1596 gboolean
1597 gst_element_link_pads_filtered (GstElement * src, const gchar * srcpadname,
1598     GstElement * dest, const gchar * destpadname, GstCaps * filter)
1599 {
1600   /* checks */
1601   g_return_val_if_fail (GST_IS_ELEMENT (src), FALSE);
1602   g_return_val_if_fail (GST_IS_ELEMENT (dest), FALSE);
1603   g_return_val_if_fail (filter == NULL || GST_IS_CAPS (filter), FALSE);
1604
1605   if (filter) {
1606     GstElement *capsfilter;
1607     GstObject *parent;
1608     GstState state, pending;
1609
1610     capsfilter = gst_element_factory_make ("capsfilter", NULL);
1611     if (!capsfilter) {
1612       GST_ERROR ("Could not make a capsfilter");
1613       return FALSE;
1614     }
1615
1616     parent = gst_object_get_parent (GST_OBJECT (src));
1617     g_return_val_if_fail (GST_IS_BIN (parent), FALSE);
1618
1619     gst_element_get_state (GST_ELEMENT_CAST (parent), &state, &pending, 0);
1620
1621     if (!gst_bin_add (GST_BIN (parent), capsfilter)) {
1622       GST_ERROR ("Could not add capsfilter");
1623       gst_object_unref (capsfilter);
1624       gst_object_unref (parent);
1625       return FALSE;
1626     }
1627
1628     if (pending != GST_STATE_VOID_PENDING)
1629       state = pending;
1630
1631     gst_element_set_state (capsfilter, state);
1632
1633     gst_object_unref (parent);
1634
1635     g_object_set (capsfilter, "caps", filter, NULL);
1636
1637     if (gst_element_link_pads (src, srcpadname, capsfilter, "sink")
1638         && gst_element_link_pads (capsfilter, "src", dest, destpadname)) {
1639       return TRUE;
1640     } else {
1641       GST_INFO ("Could not link elements");
1642       gst_element_set_state (capsfilter, GST_STATE_NULL);
1643       /* this will unlink and unref as appropriate */
1644       gst_bin_remove (GST_BIN (GST_OBJECT_PARENT (capsfilter)), capsfilter);
1645       return FALSE;
1646     }
1647   } else {
1648     return gst_element_link_pads (src, srcpadname, dest, destpadname);
1649   }
1650 }
1651
1652 /**
1653  * gst_element_link:
1654  * @src: a #GstElement containing the source pad.
1655  * @dest: the #GstElement containing the destination pad.
1656  *
1657  * Links @src to @dest. The link must be from source to
1658  * destination; the other direction will not be tried. The function looks for
1659  * existing pads that aren't linked yet. It will request new pads if necessary.
1660  * Such pads need to be released manualy when unlinking.
1661  * If multiple links are possible, only one is established.
1662  *
1663  * Make sure you have added your elements to a bin or pipeline with
1664  * gst_bin_add() before trying to link them.
1665  *
1666  * Returns: TRUE if the elements could be linked, FALSE otherwise.
1667  */
1668 gboolean
1669 gst_element_link (GstElement * src, GstElement * dest)
1670 {
1671   return gst_element_link_pads_filtered (src, NULL, dest, NULL, NULL);
1672 }
1673
1674 /**
1675  * gst_element_link_many:
1676  * @element_1: the first #GstElement in the link chain.
1677  * @element_2: the second #GstElement in the link chain.
1678  * @...: the NULL-terminated list of elements to link in order.
1679  *
1680  * Chain together a series of elements. Uses gst_element_link().
1681  * Make sure you have added your elements to a bin or pipeline with
1682  * gst_bin_add() before trying to link them.
1683  *
1684  * Returns: TRUE on success, FALSE otherwise.
1685  */
1686 gboolean
1687 gst_element_link_many (GstElement * element_1, GstElement * element_2, ...)
1688 {
1689   va_list args;
1690
1691   g_return_val_if_fail (GST_IS_ELEMENT (element_1), FALSE);
1692   g_return_val_if_fail (GST_IS_ELEMENT (element_2), FALSE);
1693
1694   va_start (args, element_2);
1695
1696   while (element_2) {
1697     if (!gst_element_link (element_1, element_2))
1698       return FALSE;
1699
1700     element_1 = element_2;
1701     element_2 = va_arg (args, GstElement *);
1702   }
1703
1704   va_end (args);
1705
1706   return TRUE;
1707 }
1708
1709 /**
1710  * gst_element_link_filtered:
1711  * @src: a #GstElement containing the source pad.
1712  * @dest: the #GstElement containing the destination pad.
1713  * @filter: the #GstCaps to filter the link, or #NULL for no filter.
1714  *
1715  * Links @src to @dest using the given caps as filtercaps.
1716  * The link must be from source to
1717  * destination; the other direction will not be tried. The function looks for
1718  * existing pads that aren't linked yet. It will request new pads if necessary.
1719  * If multiple links are possible, only one is established.
1720  *
1721  * Make sure you have added your elements to a bin or pipeline with
1722  * gst_bin_add() before trying to link them.
1723  *
1724  * Returns: TRUE if the pads could be linked, FALSE otherwise.
1725  */
1726 gboolean
1727 gst_element_link_filtered (GstElement * src, GstElement * dest,
1728     GstCaps * filter)
1729 {
1730   return gst_element_link_pads_filtered (src, NULL, dest, NULL, filter);
1731 }
1732
1733 /**
1734  * gst_element_unlink_pads:
1735  * @src: a #GstElement containing the source pad.
1736  * @srcpadname: the name of the #GstPad in source element.
1737  * @dest: a #GstElement containing the destination pad.
1738  * @destpadname: the name of the #GstPad in destination element.
1739  *
1740  * Unlinks the two named pads of the source and destination elements.
1741  */
1742 void
1743 gst_element_unlink_pads (GstElement * src, const gchar * srcpadname,
1744     GstElement * dest, const gchar * destpadname)
1745 {
1746   GstPad *srcpad, *destpad;
1747
1748   g_return_if_fail (src != NULL);
1749   g_return_if_fail (GST_IS_ELEMENT (src));
1750   g_return_if_fail (srcpadname != NULL);
1751   g_return_if_fail (dest != NULL);
1752   g_return_if_fail (GST_IS_ELEMENT (dest));
1753   g_return_if_fail (destpadname != NULL);
1754
1755   /* obtain the pads requested */
1756   srcpad = gst_element_get_pad (src, srcpadname);
1757   if (srcpad == NULL) {
1758     GST_WARNING_OBJECT (src, "source element has no pad \"%s\"", srcpadname);
1759     return;
1760   }
1761   destpad = gst_element_get_pad (dest, destpadname);
1762   if (destpad == NULL) {
1763     GST_WARNING_OBJECT (dest, "destination element has no pad \"%s\"",
1764         destpadname);
1765     gst_object_unref (srcpad);
1766     return;
1767   }
1768
1769   /* we're satisified they can be unlinked, let's do it */
1770   gst_pad_unlink (srcpad, destpad);
1771   gst_object_unref (srcpad);
1772   gst_object_unref (destpad);
1773 }
1774
1775 /**
1776  * gst_element_unlink_many:
1777  * @element_1: the first #GstElement in the link chain.
1778  * @element_2: the second #GstElement in the link chain.
1779  * @...: the NULL-terminated list of elements to unlink in order.
1780  *
1781  * Unlinks a series of elements. Uses gst_element_unlink().
1782  */
1783 void
1784 gst_element_unlink_many (GstElement * element_1, GstElement * element_2, ...)
1785 {
1786   va_list args;
1787
1788   g_return_if_fail (element_1 != NULL && element_2 != NULL);
1789   g_return_if_fail (GST_IS_ELEMENT (element_1) && GST_IS_ELEMENT (element_2));
1790
1791   va_start (args, element_2);
1792
1793   while (element_2) {
1794     gst_element_unlink (element_1, element_2);
1795
1796     element_1 = element_2;
1797     element_2 = va_arg (args, GstElement *);
1798   }
1799
1800   va_end (args);
1801 }
1802
1803 /**
1804  * gst_element_unlink:
1805  * @src: the source #GstElement to unlink.
1806  * @dest: the sink #GstElement to unlink.
1807  *
1808  * Unlinks all source pads of the source element with all sink pads
1809  * of the sink element to which they are linked.
1810  *
1811  * If the link has been made using gst_element_link(), it could have created an
1812  * requestpad, which has to be released using gst_element_release_request_pad().
1813  */
1814 void
1815 gst_element_unlink (GstElement * src, GstElement * dest)
1816 {
1817   GstIterator *pads;
1818   gboolean done = FALSE;
1819
1820   g_return_if_fail (GST_IS_ELEMENT (src));
1821   g_return_if_fail (GST_IS_ELEMENT (dest));
1822
1823   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "unlinking \"%s\" and \"%s\"",
1824       GST_ELEMENT_NAME (src), GST_ELEMENT_NAME (dest));
1825
1826   pads = gst_element_iterate_pads (src);
1827   while (!done) {
1828     gpointer data;
1829
1830     switch (gst_iterator_next (pads, &data)) {
1831       case GST_ITERATOR_OK:
1832       {
1833         GstPad *pad = GST_PAD_CAST (data);
1834
1835         if (GST_PAD_IS_SRC (pad)) {
1836           GstPad *peerpad = gst_pad_get_peer (pad);
1837
1838           /* see if the pad is connected and is really a pad
1839            * of dest */
1840           if (peerpad) {
1841             GstElement *peerelem;
1842
1843             peerelem = gst_pad_get_parent_element (peerpad);
1844
1845             if (peerelem == dest) {
1846               gst_pad_unlink (pad, peerpad);
1847             }
1848             if (peerelem)
1849               gst_object_unref (peerelem);
1850
1851             gst_object_unref (peerpad);
1852           }
1853         }
1854         gst_object_unref (pad);
1855         break;
1856       }
1857       case GST_ITERATOR_RESYNC:
1858         gst_iterator_resync (pads);
1859         break;
1860       case GST_ITERATOR_DONE:
1861         done = TRUE;
1862         break;
1863       default:
1864         g_assert_not_reached ();
1865         break;
1866     }
1867   }
1868   gst_iterator_free (pads);
1869 }
1870
1871 /**
1872  * gst_element_query_position:
1873  * @element: a #GstElement to invoke the position query on.
1874  * @format: a pointer to the #GstFormat asked for.
1875  *          On return contains the #GstFormat used.
1876  * @cur: A location in which to store the current position, or NULL.
1877  *
1878  * Queries an element for the stream position.
1879  *
1880  * Returns: TRUE if the query could be performed.
1881  */
1882 gboolean
1883 gst_element_query_position (GstElement * element, GstFormat * format,
1884     gint64 * cur)
1885 {
1886   GstQuery *query;
1887   gboolean ret;
1888
1889   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1890   g_return_val_if_fail (format != NULL, FALSE);
1891
1892   query = gst_query_new_position (*format);
1893   ret = gst_element_query (element, query);
1894
1895   if (ret)
1896     gst_query_parse_position (query, format, cur);
1897
1898   gst_query_unref (query);
1899
1900   return ret;
1901 }
1902
1903 /**
1904  * gst_element_query_duration:
1905  * @element: a #GstElement to invoke the duration query on.
1906  * @format: a pointer to the #GstFormat asked for.
1907  *          On return contains the #GstFormat used.
1908  * @duration: A location in which to store the total duration, or NULL.
1909  *
1910  * Queries an element for the total stream duration.
1911  *
1912  * Returns: TRUE if the query could be performed.
1913  */
1914 gboolean
1915 gst_element_query_duration (GstElement * element, GstFormat * format,
1916     gint64 * duration)
1917 {
1918   GstQuery *query;
1919   gboolean ret;
1920
1921   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1922   g_return_val_if_fail (format != NULL, FALSE);
1923
1924   query = gst_query_new_duration (*format);
1925   ret = gst_element_query (element, query);
1926
1927   if (ret)
1928     gst_query_parse_duration (query, format, duration);
1929
1930   gst_query_unref (query);
1931
1932   return ret;
1933 }
1934
1935 /**
1936  * gst_element_query_convert:
1937  * @element: a #GstElement to invoke the convert query on.
1938  * @src_format: a #GstFormat to convert from.
1939  * @src_val: a value to convert.
1940  * @dest_format: a pointer to the #GstFormat to convert to.
1941  * @dest_val: a pointer to the result.
1942  *
1943  * Queries an element to convert @src_val in @src_format to @dest_format.
1944  *
1945  * Returns: TRUE if the query could be performed.
1946  */
1947 gboolean
1948 gst_element_query_convert (GstElement * element, GstFormat src_format,
1949     gint64 src_val, GstFormat * dest_format, gint64 * dest_val)
1950 {
1951   GstQuery *query;
1952   gboolean ret;
1953
1954   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1955   g_return_val_if_fail (dest_format != NULL, FALSE);
1956   g_return_val_if_fail (dest_val != NULL, FALSE);
1957
1958   if (*dest_format == src_format) {
1959     *dest_val = src_val;
1960     return TRUE;
1961   }
1962
1963   query = gst_query_new_convert (src_format, src_val, *dest_format);
1964   ret = gst_element_query (element, query);
1965
1966   if (ret)
1967     gst_query_parse_convert (query, NULL, NULL, dest_format, dest_val);
1968
1969   gst_query_unref (query);
1970
1971   return ret;
1972 }
1973
1974 /**
1975  * gst_element_seek_simple
1976  * @element: a #GstElement to seek on
1977  * @format: a #GstFormat to execute the seek in, such as #GST_FORMAT_TIME
1978  * @seek_flags: seek options; playback applications will usually want to use
1979  *            GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT here
1980  * @seek_pos: position to seek to (relative to the start); if you are doing
1981  *            a seek in #GST_FORMAT_TIME this value is in nanoseconds -
1982  *            multiply with #GST_SECOND to convert seconds to nanoseconds or
1983  *            with #GST_MSECOND to convert milliseconds to nanoseconds.
1984  *
1985  * Simple API to perform a seek on the given element, meaning it just seeks
1986  * to the given position relative to the start of the stream. For more complex
1987  * operations like segment seeks (e.g. for looping) or changing the playback
1988  * rate or seeking relative to the last configured playback segment you should
1989  * use gst_element_seek().
1990  *
1991  * In a completely prerolled PAUSED or PLAYING pipeline, seeking is always
1992  * guaranteed to return %TRUE on a seekable media type or %FALSE when the media
1993  * type is certainly not seekable (such as a live stream).
1994  *
1995  * Some elements allow for seeking in the READY state, in this
1996  * case they will store the seek event and execute it when they are put to
1997  * PAUSED. If the element supports seek in READY, it will always return %TRUE when
1998  * it receives the event in the READY state.
1999  *
2000  * Returns: %TRUE if the seek operation succeeded (the seek might not always be
2001  * executed instantly though)
2002  *
2003  * Since: 0.10.7
2004  */
2005 gboolean
2006 gst_element_seek_simple (GstElement * element, GstFormat format,
2007     GstSeekFlags seek_flags, gint64 seek_pos)
2008 {
2009   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
2010   g_return_val_if_fail (seek_pos >= 0, FALSE);
2011
2012   return gst_element_seek (element, 1.0, format, seek_flags,
2013       GST_SEEK_TYPE_SET, seek_pos, GST_SEEK_TYPE_NONE, 0);
2014 }
2015
2016 /**
2017  * gst_pad_can_link:
2018  * @srcpad: the source #GstPad to link.
2019  * @sinkpad: the sink #GstPad to link.
2020  *
2021  * Checks if the source pad and the sink pad can be linked.
2022  * Both @srcpad and @sinkpad must be unlinked.
2023  *
2024  * Returns: TRUE if the pads can be linked, FALSE otherwise.
2025  */
2026 gboolean
2027 gst_pad_can_link (GstPad * srcpad, GstPad * sinkpad)
2028 {
2029   /* FIXME This function is gross.  It's almost a direct copy of
2030    * gst_pad_link_filtered().  Any decent programmer would attempt
2031    * to merge the two functions, which I will do some day. --ds
2032    */
2033
2034   /* generic checks */
2035   g_return_val_if_fail (GST_IS_PAD (srcpad), FALSE);
2036   g_return_val_if_fail (GST_IS_PAD (sinkpad), FALSE);
2037
2038   GST_CAT_INFO (GST_CAT_PADS, "trying to link %s:%s and %s:%s",
2039       GST_DEBUG_PAD_NAME (srcpad), GST_DEBUG_PAD_NAME (sinkpad));
2040
2041   /* FIXME: shouldn't we convert this to g_return_val_if_fail? */
2042   if (GST_PAD_PEER (srcpad) != NULL) {
2043     GST_CAT_INFO (GST_CAT_PADS, "Source pad %s:%s has a peer, failed",
2044         GST_DEBUG_PAD_NAME (srcpad));
2045     return FALSE;
2046   }
2047   if (GST_PAD_PEER (sinkpad) != NULL) {
2048     GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s has a peer, failed",
2049         GST_DEBUG_PAD_NAME (sinkpad));
2050     return FALSE;
2051   }
2052   if (!GST_PAD_IS_SRC (srcpad)) {
2053     GST_CAT_INFO (GST_CAT_PADS, "Src pad %s:%s is not source pad, failed",
2054         GST_DEBUG_PAD_NAME (srcpad));
2055     return FALSE;
2056   }
2057   if (!GST_PAD_IS_SINK (sinkpad)) {
2058     GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s is not sink pad, failed",
2059         GST_DEBUG_PAD_NAME (sinkpad));
2060     return FALSE;
2061   }
2062   if (GST_PAD_PARENT (srcpad) == NULL) {
2063     GST_CAT_INFO (GST_CAT_PADS, "Src pad %s:%s has no parent, failed",
2064         GST_DEBUG_PAD_NAME (srcpad));
2065     return FALSE;
2066   }
2067   if (GST_PAD_PARENT (sinkpad) == NULL) {
2068     GST_CAT_INFO (GST_CAT_PADS, "Sink pad %s:%s has no parent, failed",
2069         GST_DEBUG_PAD_NAME (srcpad));
2070     return FALSE;
2071   }
2072
2073   return TRUE;
2074 }
2075
2076 /**
2077  * gst_pad_use_fixed_caps:
2078  * @pad: the pad to use
2079  *
2080  * A helper function you can use that sets the
2081  * @gst_pad_get_fixed_caps_func as the getcaps function for the
2082  * pad. This way the function will always return the negotiated caps
2083  * or in case the pad is not negotiated, the padtemplate caps.
2084  *
2085  * Use this function on a pad that, once _set_caps() has been called
2086  * on it, cannot be renegotiated to something else.
2087  */
2088 void
2089 gst_pad_use_fixed_caps (GstPad * pad)
2090 {
2091   gst_pad_set_getcaps_function (pad, gst_pad_get_fixed_caps_func);
2092 }
2093
2094 /**
2095  * gst_pad_get_fixed_caps_func:
2096  * @pad: the pad to use
2097  *
2098  * A helper function you can use as a GetCaps function that
2099  * will return the currently negotiated caps or the padtemplate
2100  * when NULL.
2101  *
2102  * Returns: The currently negotiated caps or the padtemplate.
2103  */
2104 GstCaps *
2105 gst_pad_get_fixed_caps_func (GstPad * pad)
2106 {
2107   GstCaps *result;
2108
2109   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2110
2111   GST_OBJECT_LOCK (pad);
2112   if (GST_PAD_CAPS (pad)) {
2113     result = GST_PAD_CAPS (pad);
2114
2115     GST_CAT_DEBUG (GST_CAT_CAPS,
2116         "using pad caps %p %" GST_PTR_FORMAT, result, result);
2117
2118     result = gst_caps_ref (result);
2119     goto done;
2120   }
2121   if (GST_PAD_PAD_TEMPLATE (pad)) {
2122     GstPadTemplate *templ = GST_PAD_PAD_TEMPLATE (pad);
2123
2124     result = GST_PAD_TEMPLATE_CAPS (templ);
2125     GST_CAT_DEBUG (GST_CAT_CAPS,
2126         "using pad template %p with caps %p %" GST_PTR_FORMAT, templ, result,
2127         result);
2128
2129     result = gst_caps_ref (result);
2130     goto done;
2131   }
2132   GST_CAT_DEBUG (GST_CAT_CAPS, "pad has no caps");
2133   result = gst_caps_new_empty ();
2134
2135 done:
2136   GST_OBJECT_UNLOCK (pad);
2137
2138   return result;
2139 }
2140
2141 /**
2142  * gst_pad_get_parent_element:
2143  * @pad: a pad
2144  *
2145  * Gets the parent of @pad, cast to a #GstElement. If a @pad has no parent or
2146  * its parent is not an element, return NULL.
2147  *
2148  * Returns: The parent of the pad. The caller has a reference on the parent, so
2149  * unref when you're finished with it.
2150  *
2151  * MT safe.
2152  */
2153 GstElement *
2154 gst_pad_get_parent_element (GstPad * pad)
2155 {
2156   GstObject *p;
2157
2158   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2159
2160   p = gst_object_get_parent (GST_OBJECT_CAST (pad));
2161
2162   if (p && !GST_IS_ELEMENT (p)) {
2163     gst_object_unref (p);
2164     p = NULL;
2165   }
2166   return GST_ELEMENT_CAST (p);
2167 }
2168
2169 /**
2170  * gst_object_default_error:
2171  * @source: the #GstObject that initiated the error.
2172  * @error: the GError.
2173  * @debug: an additional debug information string, or NULL.
2174  *
2175  * A default error function.
2176  *
2177  * The default handler will simply print the error string using g_print.
2178  */
2179 void
2180 gst_object_default_error (GstObject * source, GError * error, gchar * debug)
2181 {
2182   gchar *name = gst_object_get_path_string (source);
2183
2184   g_print (_("ERROR: from element %s: %s\n"), name, error->message);
2185   if (debug)
2186     g_print (_("Additional debug info:\n%s\n"), debug);
2187
2188   g_free (name);
2189 }
2190
2191 /**
2192  * gst_bin_add_many:
2193  * @bin: a #GstBin
2194  * @element_1: the #GstElement element to add to the bin
2195  * @...: additional elements to add to the bin
2196  *
2197  * Adds a NULL-terminated list of elements to a bin.  This function is
2198  * equivalent to calling gst_bin_add() for each member of the list. The return
2199  * value of each gst_bin_add() is ignored.
2200  */
2201 void
2202 gst_bin_add_many (GstBin * bin, GstElement * element_1, ...)
2203 {
2204   va_list args;
2205
2206   g_return_if_fail (GST_IS_BIN (bin));
2207   g_return_if_fail (GST_IS_ELEMENT (element_1));
2208
2209   va_start (args, element_1);
2210
2211   while (element_1) {
2212     gst_bin_add (bin, element_1);
2213
2214     element_1 = va_arg (args, GstElement *);
2215   }
2216
2217   va_end (args);
2218 }
2219
2220 /**
2221  * gst_bin_remove_many:
2222  * @bin: a #GstBin
2223  * @element_1: the first #GstElement to remove from the bin
2224  * @...: NULL-terminated list of elements to remove from the bin
2225  *
2226  * Remove a list of elements from a bin. This function is equivalent
2227  * to calling gst_bin_remove() with each member of the list.
2228  */
2229 void
2230 gst_bin_remove_many (GstBin * bin, GstElement * element_1, ...)
2231 {
2232   va_list args;
2233
2234   g_return_if_fail (GST_IS_BIN (bin));
2235   g_return_if_fail (GST_IS_ELEMENT (element_1));
2236
2237   va_start (args, element_1);
2238
2239   while (element_1) {
2240     gst_bin_remove (bin, element_1);
2241
2242     element_1 = va_arg (args, GstElement *);
2243   }
2244
2245   va_end (args);
2246 }
2247
2248 static void
2249 gst_element_populate_std_props (GObjectClass * klass, const gchar * prop_name,
2250     guint arg_id, GParamFlags flags)
2251 {
2252   GQuark prop_id = g_quark_from_string (prop_name);
2253   GParamSpec *pspec;
2254
2255   static GQuark fd_id = 0;
2256   static GQuark blocksize_id;
2257   static GQuark bytesperread_id;
2258   static GQuark dump_id;
2259   static GQuark filesize_id;
2260   static GQuark mmapsize_id;
2261   static GQuark location_id;
2262   static GQuark offset_id;
2263   static GQuark silent_id;
2264   static GQuark touch_id;
2265
2266   if (!fd_id) {
2267     fd_id = g_quark_from_static_string ("fd");
2268     blocksize_id = g_quark_from_static_string ("blocksize");
2269     bytesperread_id = g_quark_from_static_string ("bytesperread");
2270     dump_id = g_quark_from_static_string ("dump");
2271     filesize_id = g_quark_from_static_string ("filesize");
2272     mmapsize_id = g_quark_from_static_string ("mmapsize");
2273     location_id = g_quark_from_static_string ("location");
2274     offset_id = g_quark_from_static_string ("offset");
2275     silent_id = g_quark_from_static_string ("silent");
2276     touch_id = g_quark_from_static_string ("touch");
2277   }
2278
2279   if (prop_id == fd_id) {
2280     pspec = g_param_spec_int ("fd", "File-descriptor",
2281         "File-descriptor for the file being read", 0, G_MAXINT, 0, flags);
2282   } else if (prop_id == blocksize_id) {
2283     pspec = g_param_spec_ulong ("blocksize", "Block Size",
2284         "Block size to read per buffer", 0, G_MAXULONG, 4096, flags);
2285
2286   } else if (prop_id == bytesperread_id) {
2287     pspec = g_param_spec_int ("bytesperread", "Bytes per read",
2288         "Number of bytes to read per buffer", G_MININT, G_MAXINT, 0, flags);
2289
2290   } else if (prop_id == dump_id) {
2291     pspec = g_param_spec_boolean ("dump", "Dump",
2292         "Dump bytes to stdout", FALSE, flags);
2293
2294   } else if (prop_id == filesize_id) {
2295     pspec = g_param_spec_int64 ("filesize", "File Size",
2296         "Size of the file being read", 0, G_MAXINT64, 0, flags);
2297
2298   } else if (prop_id == mmapsize_id) {
2299     pspec = g_param_spec_ulong ("mmapsize", "mmap() Block Size",
2300         "Size in bytes of mmap()d regions", 0, G_MAXULONG, 4 * 1048576, flags);
2301
2302   } else if (prop_id == location_id) {
2303     pspec = g_param_spec_string ("location", "File Location",
2304         "Location of the file to read", NULL, flags);
2305
2306   } else if (prop_id == offset_id) {
2307     pspec = g_param_spec_int64 ("offset", "File Offset",
2308         "Byte offset of current read pointer", 0, G_MAXINT64, 0, flags);
2309
2310   } else if (prop_id == silent_id) {
2311     pspec = g_param_spec_boolean ("silent", "Silent", "Don't produce events",
2312         FALSE, flags);
2313
2314   } else if (prop_id == touch_id) {
2315     pspec = g_param_spec_boolean ("touch", "Touch read data",
2316         "Touch data to force disk read before " "push ()", TRUE, flags);
2317   } else {
2318     g_warning ("Unknown - 'standard' property '%s' id %d from klass %s",
2319         prop_name, arg_id, g_type_name (G_OBJECT_CLASS_TYPE (klass)));
2320     pspec = NULL;
2321   }
2322
2323   if (pspec) {
2324     g_object_class_install_property (klass, arg_id, pspec);
2325   }
2326 }
2327
2328 /**
2329  * gst_element_class_install_std_props:
2330  * @klass: the #GstElementClass to add the properties to.
2331  * @first_name: the name of the first property.
2332  * in a NULL terminated
2333  * @...: the id and flags of the first property, followed by
2334  * further 'name', 'id', 'flags' triplets and terminated by NULL.
2335  *
2336  * Adds a list of standardized properties with types to the @klass.
2337  * the id is for the property switch in your get_prop method, and
2338  * the flags determine readability / writeability.
2339  **/
2340 void
2341 gst_element_class_install_std_props (GstElementClass * klass,
2342     const gchar * first_name, ...)
2343 {
2344   const char *name;
2345
2346   va_list args;
2347
2348   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
2349
2350   va_start (args, first_name);
2351
2352   name = first_name;
2353
2354   while (name) {
2355     int arg_id = va_arg (args, int);
2356     int flags = va_arg (args, int);
2357
2358     gst_element_populate_std_props ((GObjectClass *) klass, name, arg_id,
2359         flags);
2360
2361     name = va_arg (args, char *);
2362   }
2363
2364   va_end (args);
2365 }
2366
2367
2368 /**
2369  * gst_buffer_merge:
2370  * @buf1: the first source #GstBuffer to merge.
2371  * @buf2: the second source #GstBuffer to merge.
2372  *
2373  * Create a new buffer that is the concatenation of the two source
2374  * buffers.  The original source buffers will not be modified or
2375  * unref'd.  Make sure you unref the source buffers if they are not used
2376  * anymore afterwards.
2377  *
2378  * If the buffers point to contiguous areas of memory, the buffer
2379  * is created without copying the data.
2380  *
2381  * Returns: the new #GstBuffer which is the concatenation of the source buffers.
2382  */
2383 GstBuffer *
2384 gst_buffer_merge (GstBuffer * buf1, GstBuffer * buf2)
2385 {
2386   GstBuffer *result;
2387
2388   /* we're just a specific case of the more general gst_buffer_span() */
2389   result = gst_buffer_span (buf1, 0, buf2, buf1->size + buf2->size);
2390
2391   return result;
2392 }
2393
2394 /**
2395  * gst_buffer_join:
2396  * @buf1: the first source #GstBuffer.
2397  * @buf2: the second source #GstBuffer.
2398  *
2399  * Create a new buffer that is the concatenation of the two source
2400  * buffers, and unrefs the original source buffers.
2401  *
2402  * If the buffers point to contiguous areas of memory, the buffer
2403  * is created without copying the data.
2404  *
2405  * Returns: the new #GstBuffer which is the concatenation of the source buffers.
2406  */
2407 GstBuffer *
2408 gst_buffer_join (GstBuffer * buf1, GstBuffer * buf2)
2409 {
2410   GstBuffer *result;
2411
2412   result = gst_buffer_span (buf1, 0, buf2, buf1->size + buf2->size);
2413   gst_buffer_unref (buf1);
2414   gst_buffer_unref (buf2);
2415
2416   return result;
2417 }
2418
2419
2420 /**
2421  * gst_buffer_stamp:
2422  * @dest: buffer to stamp
2423  * @src: buffer to stamp from
2424  *
2425  * Copies additional information (the timestamp, duration, and offset start
2426  * and end) from one buffer to the other.
2427  *
2428  * This function does not copy any buffer flags or caps and is equivalent to
2429  * gst_buffer_copy_metadata(@dest, @src, GST_BUFFER_COPY_TIMESTAMPS).
2430  *
2431  * Deprecated: use gst_buffer_copy_metadata() instead, it provides more
2432  * control.
2433  */
2434 #ifndef GST_REMOVE_DEPRECATED
2435 void
2436 gst_buffer_stamp (GstBuffer * dest, const GstBuffer * src)
2437 {
2438   gst_buffer_copy_metadata (dest, src, GST_BUFFER_COPY_TIMESTAMPS);
2439 }
2440 #endif
2441
2442 static gboolean
2443 intersect_caps_func (GstPad * pad, GValue * ret, GstPad * orig)
2444 {
2445   if (pad != orig) {
2446     GstCaps *peercaps, *existing;
2447
2448     existing = g_value_get_pointer (ret);
2449     peercaps = gst_pad_peer_get_caps (pad);
2450     if (peercaps == NULL)
2451       peercaps = gst_caps_new_any ();
2452     g_value_set_pointer (ret, gst_caps_intersect (existing, peercaps));
2453     gst_caps_unref (existing);
2454     gst_caps_unref (peercaps);
2455   }
2456   gst_object_unref (pad);
2457   return TRUE;
2458 }
2459
2460 /**
2461  * gst_pad_proxy_getcaps:
2462  * @pad: a #GstPad to proxy.
2463  *
2464  * Calls gst_pad_get_allowed_caps() for every other pad belonging to the
2465  * same element as @pad, and returns the intersection of the results.
2466  *
2467  * This function is useful as a default getcaps function for an element
2468  * that can handle any stream format, but requires all its pads to have
2469  * the same caps.  Two such elements are tee and aggregator.
2470  *
2471  * Returns: the intersection of the other pads' allowed caps.
2472  */
2473 GstCaps *
2474 gst_pad_proxy_getcaps (GstPad * pad)
2475 {
2476   GstElement *element;
2477   GstCaps *caps, *intersected;
2478   GstIterator *iter;
2479   GstIteratorResult res;
2480   GValue ret = { 0, };
2481
2482   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
2483
2484   GST_DEBUG ("proxying getcaps for %s:%s", GST_DEBUG_PAD_NAME (pad));
2485
2486   element = gst_pad_get_parent_element (pad);
2487   if (element == NULL)
2488     return NULL;
2489
2490   /* value to hold the return, by default it holds ANY, the ref is taken by
2491    * the GValue. */
2492   g_value_init (&ret, G_TYPE_POINTER);
2493   g_value_set_pointer (&ret, gst_caps_new_any ());
2494
2495   iter = gst_element_iterate_pads (element);
2496   while (1) {
2497     res =
2498         gst_iterator_fold (iter, (GstIteratorFoldFunction) intersect_caps_func,
2499         &ret, pad);
2500     switch (res) {
2501       case GST_ITERATOR_RESYNC:
2502         /* unref any value stored */
2503         if ((caps = g_value_get_pointer (&ret)))
2504           gst_caps_unref (caps);
2505         /* need to reset the result again to ANY */
2506         g_value_set_pointer (&ret, gst_caps_new_any ());
2507         gst_iterator_resync (iter);
2508         break;
2509       case GST_ITERATOR_DONE:
2510         /* all pads iterated, return collected value */
2511         goto done;
2512       default:
2513         /* iterator returned _ERROR or premature end with _OK,
2514          * mark an error and exit */
2515         if ((caps = g_value_get_pointer (&ret)))
2516           gst_caps_unref (caps);
2517         g_value_set_pointer (&ret, NULL);
2518         goto error;
2519     }
2520   }
2521 done:
2522   gst_iterator_free (iter);
2523
2524   gst_object_unref (element);
2525
2526   caps = g_value_get_pointer (&ret);
2527   g_value_unset (&ret);
2528
2529   intersected = gst_caps_intersect (caps, gst_pad_get_pad_template_caps (pad));
2530   gst_caps_unref (caps);
2531
2532   return intersected;
2533
2534   /* ERRORS */
2535 error:
2536   {
2537     g_warning ("Pad list returned error on element %s",
2538         GST_ELEMENT_NAME (element));
2539     gst_iterator_free (iter);
2540     gst_object_unref (element);
2541     return NULL;
2542   }
2543 }
2544
2545 typedef struct
2546 {
2547   GstPad *orig;
2548   GstCaps *caps;
2549 } LinkData;
2550
2551 static gboolean
2552 link_fold_func (GstPad * pad, GValue * ret, LinkData * data)
2553 {
2554   gboolean success = TRUE;
2555
2556   if (pad != data->orig) {
2557     success = gst_pad_set_caps (pad, data->caps);
2558     g_value_set_boolean (ret, success);
2559   }
2560   gst_object_unref (pad);
2561
2562   return success;
2563 }
2564
2565 /**
2566  * gst_pad_proxy_setcaps
2567  * @pad: a #GstPad to proxy from
2568  * @caps: the #GstCaps to link with
2569  *
2570  * Calls gst_pad_set_caps() for every other pad belonging to the
2571  * same element as @pad.  If gst_pad_set_caps() fails on any pad,
2572  * the proxy setcaps fails. May be used only during negotiation.
2573  *
2574  * Returns: TRUE if sucessful
2575  */
2576 gboolean
2577 gst_pad_proxy_setcaps (GstPad * pad, GstCaps * caps)
2578 {
2579   GstElement *element;
2580   GstIterator *iter;
2581   GstIteratorResult res;
2582   GValue ret = { 0, };
2583   LinkData data;
2584
2585   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2586   g_return_val_if_fail (caps != NULL, FALSE);
2587
2588   GST_DEBUG ("proxying pad link for %s:%s", GST_DEBUG_PAD_NAME (pad));
2589
2590   element = gst_pad_get_parent_element (pad);
2591   if (element == NULL)
2592     return FALSE;
2593
2594   iter = gst_element_iterate_pads (element);
2595
2596   g_value_init (&ret, G_TYPE_BOOLEAN);
2597   g_value_set_boolean (&ret, TRUE);
2598   data.orig = pad;
2599   data.caps = caps;
2600
2601   res = gst_iterator_fold (iter, (GstIteratorFoldFunction) link_fold_func,
2602       &ret, &data);
2603   gst_iterator_free (iter);
2604
2605   if (res != GST_ITERATOR_DONE)
2606     goto pads_changed;
2607
2608   gst_object_unref (element);
2609
2610   /* ok not to unset the gvalue */
2611   return g_value_get_boolean (&ret);
2612
2613   /* ERRORS */
2614 pads_changed:
2615   {
2616     g_warning ("Pad list changed during proxy_pad_link for element %s",
2617         GST_ELEMENT_NAME (element));
2618     gst_object_unref (element);
2619     return FALSE;
2620   }
2621 }
2622
2623 /**
2624  * gst_pad_query_position:
2625  * @pad: a #GstPad to invoke the position query on.
2626  * @format: a pointer to the #GstFormat asked for.
2627  *          On return contains the #GstFormat used.
2628  * @cur: A location in which to store the current position, or NULL.
2629  *
2630  * Queries a pad for the stream position.
2631  *
2632  * Returns: TRUE if the query could be performed.
2633  */
2634 gboolean
2635 gst_pad_query_position (GstPad * pad, GstFormat * format, gint64 * cur)
2636 {
2637   GstQuery *query;
2638   gboolean ret;
2639
2640   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2641   g_return_val_if_fail (format != NULL, FALSE);
2642
2643   query = gst_query_new_position (*format);
2644   ret = gst_pad_query (pad, query);
2645
2646   if (ret)
2647     gst_query_parse_position (query, format, cur);
2648
2649   gst_query_unref (query);
2650
2651   return ret;
2652 }
2653
2654 /**
2655  * gst_pad_query_peer_position:
2656  * @pad: a #GstPad on whose peer to invoke the position query on.
2657  *       Must be a sink pad.
2658  * @format: a pointer to the #GstFormat asked for.
2659  *          On return contains the #GstFormat used.
2660  * @cur: A location in which to store the current position, or NULL.
2661  *
2662  * Queries the peer of a given sink pad for the stream position.
2663  *
2664  * Returns: TRUE if the query could be performed.
2665  */
2666 gboolean
2667 gst_pad_query_peer_position (GstPad * pad, GstFormat * format, gint64 * cur)
2668 {
2669   gboolean ret = FALSE;
2670   GstPad *peer;
2671
2672   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2673   g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2674   g_return_val_if_fail (format != NULL, FALSE);
2675
2676   peer = gst_pad_get_peer (pad);
2677   if (peer) {
2678     ret = gst_pad_query_position (peer, format, cur);
2679     gst_object_unref (peer);
2680   }
2681
2682   return ret;
2683 }
2684
2685 /**
2686  * gst_pad_query_duration:
2687  * @pad: a #GstPad to invoke the duration query on.
2688  * @format: a pointer to the #GstFormat asked for.
2689  *          On return contains the #GstFormat used.
2690  * @duration: A location in which to store the total duration, or NULL.
2691  *
2692  * Queries a pad for the total stream duration.
2693  *
2694  * Returns: TRUE if the query could be performed.
2695  */
2696 gboolean
2697 gst_pad_query_duration (GstPad * pad, GstFormat * format, gint64 * duration)
2698 {
2699   GstQuery *query;
2700   gboolean ret;
2701
2702   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2703   g_return_val_if_fail (format != NULL, FALSE);
2704
2705   query = gst_query_new_duration (*format);
2706   ret = gst_pad_query (pad, query);
2707
2708   if (ret)
2709     gst_query_parse_duration (query, format, duration);
2710
2711   gst_query_unref (query);
2712
2713   return ret;
2714 }
2715
2716 /**
2717  * gst_pad_query_peer_duration:
2718  * @pad: a #GstPad on whose peer pad to invoke the duration query on.
2719  *       Must be a sink pad.
2720  * @format: a pointer to the #GstFormat asked for.
2721  *          On return contains the #GstFormat used.
2722  * @duration: A location in which to store the total duration, or NULL.
2723  *
2724  * Queries the peer pad of a given sink pad for the total stream duration.
2725  *
2726  * Returns: TRUE if the query could be performed.
2727  */
2728 gboolean
2729 gst_pad_query_peer_duration (GstPad * pad, GstFormat * format,
2730     gint64 * duration)
2731 {
2732   gboolean ret = FALSE;
2733   GstPad *peer;
2734
2735   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2736   g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2737   g_return_val_if_fail (format != NULL, FALSE);
2738
2739   peer = gst_pad_get_peer (pad);
2740   if (peer) {
2741     ret = gst_pad_query_duration (peer, format, duration);
2742     gst_object_unref (peer);
2743   }
2744
2745   return ret;
2746 }
2747
2748 /**
2749  * gst_pad_query_convert:
2750  * @pad: a #GstPad to invoke the convert query on.
2751  * @src_format: a #GstFormat to convert from.
2752  * @src_val: a value to convert.
2753  * @dest_format: a pointer to the #GstFormat to convert to.
2754  * @dest_val: a pointer to the result.
2755  *
2756  * Queries a pad to convert @src_val in @src_format to @dest_format.
2757  *
2758  * Returns: TRUE if the query could be performed.
2759  */
2760 gboolean
2761 gst_pad_query_convert (GstPad * pad, GstFormat src_format, gint64 src_val,
2762     GstFormat * dest_format, gint64 * dest_val)
2763 {
2764   GstQuery *query;
2765   gboolean ret;
2766
2767   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2768   g_return_val_if_fail (src_val >= 0, FALSE);
2769   g_return_val_if_fail (dest_format != NULL, FALSE);
2770   g_return_val_if_fail (dest_val != NULL, FALSE);
2771
2772   if (*dest_format == src_format) {
2773     *dest_val = src_val;
2774     return TRUE;
2775   }
2776
2777   query = gst_query_new_convert (src_format, src_val, *dest_format);
2778   ret = gst_pad_query (pad, query);
2779
2780   if (ret)
2781     gst_query_parse_convert (query, NULL, NULL, dest_format, dest_val);
2782
2783   gst_query_unref (query);
2784
2785   return ret;
2786 }
2787
2788 /**
2789  * gst_pad_query_peer_convert:
2790  * @pad: a #GstPad, on whose peer pad to invoke the convert query on.
2791  *       Must be a sink pad.
2792  * @src_format: a #GstFormat to convert from.
2793  * @src_val: a value to convert.
2794  * @dest_format: a pointer to the #GstFormat to convert to.
2795  * @dest_val: a pointer to the result.
2796  *
2797  * Queries the peer pad of a given sink pad to convert @src_val in @src_format
2798  * to @dest_format.
2799  *
2800  * Returns: TRUE if the query could be performed.
2801  */
2802 gboolean
2803 gst_pad_query_peer_convert (GstPad * pad, GstFormat src_format, gint64 src_val,
2804     GstFormat * dest_format, gint64 * dest_val)
2805 {
2806   gboolean ret = FALSE;
2807   GstPad *peer;
2808
2809   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
2810   g_return_val_if_fail (GST_PAD_IS_SINK (pad), FALSE);
2811   g_return_val_if_fail (src_val >= 0, FALSE);
2812   g_return_val_if_fail (dest_format != NULL, FALSE);
2813   g_return_val_if_fail (dest_val != NULL, FALSE);
2814
2815   peer = gst_pad_get_peer (pad);
2816   if (peer) {
2817     ret = gst_pad_query_convert (peer, src_format, src_val, dest_format,
2818         dest_val);
2819     gst_object_unref (peer);
2820   }
2821
2822   return ret;
2823 }
2824
2825 /**
2826  * gst_atomic_int_set:
2827  * @atomic_int: pointer to an atomic integer
2828  * @value: value to set
2829  *
2830  * Unconditionally sets the atomic integer to @value.
2831  */
2832 void
2833 gst_atomic_int_set (gint * atomic_int, gint value)
2834 {
2835   int ignore;
2836
2837   *atomic_int = value;
2838   /* read acts as a memory barrier */
2839   ignore = g_atomic_int_get (atomic_int);
2840 }
2841
2842 /**
2843  * gst_pad_add_data_probe:
2844  * @pad: pad to add the data probe handler to
2845  * @handler: function to call when data is passed over pad
2846  * @data: data to pass along with the handler
2847  *
2848  * Adds a "data probe" to a pad. This function will be called whenever data
2849  * passes through a pad. In this case data means both events and buffers. The
2850  * probe will be called with the data as an argument, meaning @handler should
2851  * have the same callback signature as the 'have-data' signal of #GstPad.
2852  * Note that the data will have a reference count greater than 1, so it will
2853  * be immutable -- you must not change it.
2854  *
2855  * For source pads, the probe will be called after the blocking function, if any
2856  * (see gst_pad_set_blocked_async()), but before looking up the peer to chain
2857  * to. For sink pads, the probe function will be called before configuring the
2858  * sink with new caps, if any, and before calling the pad's chain function.
2859  *
2860  * Your data probe should return TRUE to let the data continue to flow, or FALSE
2861  * to drop it. Dropping data is rarely useful, but occasionally comes in handy
2862  * with events.
2863  *
2864  * Although probes are implemented internally by connecting @handler to the
2865  * have-data signal on the pad, if you want to remove a probe it is insufficient
2866  * to only call g_signal_handler_disconnect on the returned handler id. To
2867  * remove a probe, use the appropriate function, such as
2868  * gst_pad_remove_data_probe().
2869  *
2870  * Returns: The handler id.
2871  */
2872 gulong
2873 gst_pad_add_data_probe (GstPad * pad, GCallback handler, gpointer data)
2874 {
2875   gulong sigid;
2876
2877   g_return_val_if_fail (GST_IS_PAD (pad), 0);
2878   g_return_val_if_fail (handler != NULL, 0);
2879
2880   GST_OBJECT_LOCK (pad);
2881   sigid = g_signal_connect (pad, "have-data", handler, data);
2882   GST_PAD_DO_EVENT_SIGNALS (pad)++;
2883   GST_PAD_DO_BUFFER_SIGNALS (pad)++;
2884   GST_DEBUG ("adding data probe to pad %s:%s, now %d data, %d event probes",
2885       GST_DEBUG_PAD_NAME (pad),
2886       GST_PAD_DO_BUFFER_SIGNALS (pad), GST_PAD_DO_EVENT_SIGNALS (pad));
2887   GST_OBJECT_UNLOCK (pad);
2888
2889   return sigid;
2890 }
2891
2892 /**
2893  * gst_pad_add_event_probe:
2894  * @pad: pad to add the event probe handler to
2895  * @handler: function to call when data is passed over pad
2896  * @data: data to pass along with the handler
2897  *
2898  * Adds a probe that will be called for all events passing through a pad. See
2899  * gst_pad_add_data_probe() for more information.
2900  *
2901  * Returns: The handler id
2902  */
2903 gulong
2904 gst_pad_add_event_probe (GstPad * pad, GCallback handler, gpointer data)
2905 {
2906   gulong sigid;
2907
2908   g_return_val_if_fail (GST_IS_PAD (pad), 0);
2909   g_return_val_if_fail (handler != NULL, 0);
2910
2911   GST_OBJECT_LOCK (pad);
2912   sigid = g_signal_connect (pad, "have-data::event", handler, data);
2913   GST_PAD_DO_EVENT_SIGNALS (pad)++;
2914   GST_DEBUG ("adding event probe to pad %s:%s, now %d probes",
2915       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_EVENT_SIGNALS (pad));
2916   GST_OBJECT_UNLOCK (pad);
2917
2918   return sigid;
2919 }
2920
2921 /**
2922  * gst_pad_add_buffer_probe:
2923  * @pad: pad to add the buffer probe handler to
2924  * @handler: function to call when data is passed over pad
2925  * @data: data to pass along with the handler
2926  *
2927  * Adds a probe that will be called for all buffers passing through a pad. See
2928  * gst_pad_add_data_probe() for more information.
2929  *
2930  * Returns: The handler id
2931  */
2932 gulong
2933 gst_pad_add_buffer_probe (GstPad * pad, GCallback handler, gpointer data)
2934 {
2935   gulong sigid;
2936
2937   g_return_val_if_fail (GST_IS_PAD (pad), 0);
2938   g_return_val_if_fail (handler != NULL, 0);
2939
2940   GST_OBJECT_LOCK (pad);
2941   sigid = g_signal_connect (pad, "have-data::buffer", handler, data);
2942   GST_PAD_DO_BUFFER_SIGNALS (pad)++;
2943   GST_DEBUG ("adding buffer probe to pad %s:%s, now %d probes",
2944       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_BUFFER_SIGNALS (pad));
2945   GST_OBJECT_UNLOCK (pad);
2946
2947   return sigid;
2948 }
2949
2950 /**
2951  * gst_pad_remove_data_probe:
2952  * @pad: pad to remove the data probe handler from
2953  * @handler_id: handler id returned from gst_pad_add_data_probe
2954  *
2955  * Removes a data probe from @pad.
2956  */
2957 void
2958 gst_pad_remove_data_probe (GstPad * pad, guint handler_id)
2959 {
2960   g_return_if_fail (GST_IS_PAD (pad));
2961   g_return_if_fail (handler_id > 0);
2962
2963   GST_OBJECT_LOCK (pad);
2964   g_signal_handler_disconnect (pad, handler_id);
2965   GST_PAD_DO_BUFFER_SIGNALS (pad)--;
2966   GST_PAD_DO_EVENT_SIGNALS (pad)--;
2967   GST_DEBUG
2968       ("removed data probe from pad %s:%s, now %d event, %d buffer probes",
2969       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_EVENT_SIGNALS (pad),
2970       GST_PAD_DO_BUFFER_SIGNALS (pad));
2971   GST_OBJECT_UNLOCK (pad);
2972
2973 }
2974
2975 /**
2976  * gst_pad_remove_event_probe:
2977  * @pad: pad to remove the event probe handler from
2978  * @handler_id: handler id returned from gst_pad_add_event_probe
2979  *
2980  * Removes an event probe from @pad.
2981  */
2982 void
2983 gst_pad_remove_event_probe (GstPad * pad, guint handler_id)
2984 {
2985   g_return_if_fail (GST_IS_PAD (pad));
2986   g_return_if_fail (handler_id > 0);
2987
2988   GST_OBJECT_LOCK (pad);
2989   g_signal_handler_disconnect (pad, handler_id);
2990   GST_PAD_DO_EVENT_SIGNALS (pad)--;
2991   GST_DEBUG ("removed event probe from pad %s:%s, now %d event probes",
2992       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_EVENT_SIGNALS (pad));
2993   GST_OBJECT_UNLOCK (pad);
2994 }
2995
2996 /**
2997  * gst_pad_remove_buffer_probe:
2998  * @pad: pad to remove the buffer probe handler from
2999  * @handler_id: handler id returned from gst_pad_add_buffer_probe
3000  *
3001  * Removes a buffer probe from @pad.
3002  */
3003 void
3004 gst_pad_remove_buffer_probe (GstPad * pad, guint handler_id)
3005 {
3006   g_return_if_fail (GST_IS_PAD (pad));
3007   g_return_if_fail (handler_id > 0);
3008
3009   GST_OBJECT_LOCK (pad);
3010   g_signal_handler_disconnect (pad, handler_id);
3011   GST_PAD_DO_BUFFER_SIGNALS (pad)--;
3012   GST_DEBUG ("removed buffer probe from pad %s:%s, now %d buffer probes",
3013       GST_DEBUG_PAD_NAME (pad), GST_PAD_DO_BUFFER_SIGNALS (pad));
3014   GST_OBJECT_UNLOCK (pad);
3015
3016 }
3017
3018 /**
3019  * gst_element_found_tags_for_pad:
3020  * @element: element for which to post taglist to bus.
3021  * @pad: pad on which to push tag-event.
3022  * @list: the taglist to post on the bus and create event from.
3023  *
3024  * Posts a message to the bus that new tags were found and pushes the
3025  * tags as event. Takes ownership of the @list.
3026  *
3027  * This is a utility method for elements. Applications should use the
3028  * #GstTagSetter interface.
3029  */
3030 void
3031 gst_element_found_tags_for_pad (GstElement * element,
3032     GstPad * pad, GstTagList * list)
3033 {
3034   g_return_if_fail (element != NULL);
3035   g_return_if_fail (pad != NULL);
3036   g_return_if_fail (list != NULL);
3037
3038   gst_pad_push_event (pad, gst_event_new_tag (gst_tag_list_copy (list)));
3039   gst_element_post_message (element,
3040       gst_message_new_tag (GST_OBJECT (element), list));
3041 }
3042
3043 static void
3044 push_and_ref (GstPad * pad, GstEvent * event)
3045 {
3046   gst_pad_push_event (pad, gst_event_ref (event));
3047   /* iterator refs pad, we unref when we are done with it */
3048   gst_object_unref (pad);
3049 }
3050
3051 /**
3052  * gst_element_found_tags:
3053  * @element: element for which we found the tags.
3054  * @list: list of tags.
3055  *
3056  * Posts a message to the bus that new tags were found, and pushes an event
3057  * to all sourcepads. Takes ownership of the @list.
3058  *
3059  * This is a utility method for elements. Applications should use the
3060  * #GstTagSetter interface.
3061  */
3062 void
3063 gst_element_found_tags (GstElement * element, GstTagList * list)
3064 {
3065   GstIterator *iter;
3066   GstEvent *event;
3067
3068   g_return_if_fail (element != NULL);
3069   g_return_if_fail (list != NULL);
3070
3071   iter = gst_element_iterate_src_pads (element);
3072   event = gst_event_new_tag (gst_tag_list_copy (list));
3073   gst_iterator_foreach (iter, (GFunc) push_and_ref, event);
3074   gst_iterator_free (iter);
3075   gst_event_unref (event);
3076
3077   gst_element_post_message (element,
3078       gst_message_new_tag (GST_OBJECT (element), list));
3079 }
3080
3081 static GstPad *
3082 element_find_unconnected_pad (GstElement * element, GstPadDirection direction)
3083 {
3084   GstIterator *iter;
3085   GstPad *unconnected_pad = NULL;
3086   gboolean done;
3087
3088   switch (direction) {
3089     case GST_PAD_SRC:
3090       iter = gst_element_iterate_src_pads (element);
3091       break;
3092     case GST_PAD_SINK:
3093       iter = gst_element_iterate_sink_pads (element);
3094       break;
3095     default:
3096       g_return_val_if_reached (NULL);
3097   }
3098
3099   done = FALSE;
3100   while (!done) {
3101     gpointer pad;
3102
3103     switch (gst_iterator_next (iter, &pad)) {
3104       case GST_ITERATOR_OK:{
3105         GstPad *peer;
3106
3107         GST_CAT_LOG (GST_CAT_ELEMENT_PADS, "examining pad %s:%s",
3108             GST_DEBUG_PAD_NAME (pad));
3109
3110         peer = gst_pad_get_peer (GST_PAD (pad));
3111         if (peer == NULL) {
3112           unconnected_pad = pad;
3113           done = TRUE;
3114           GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
3115               "found existing unlinked pad %s:%s",
3116               GST_DEBUG_PAD_NAME (unconnected_pad));
3117         } else {
3118           gst_object_unref (pad);
3119           gst_object_unref (peer);
3120         }
3121         break;
3122       }
3123       case GST_ITERATOR_DONE:
3124         done = TRUE;
3125         break;
3126       case GST_ITERATOR_RESYNC:
3127         gst_iterator_resync (iter);
3128         break;
3129       case GST_ITERATOR_ERROR:
3130         g_return_val_if_reached (NULL);
3131         break;
3132     }
3133   }
3134
3135   gst_iterator_free (iter);
3136
3137   return unconnected_pad;
3138 }
3139
3140 /**
3141  * gst_bin_find_unconnected_pad:
3142  * @bin: bin in which to look for elements with unconnected pads
3143  * @direction: whether to look for an unconnected source or sink pad
3144  *
3145  * Recursively looks for elements with an unconnected pad of the given
3146  * direction within the specified bin and returns an unconnected pad
3147  * if one is found, or NULL otherwise. If a pad is found, the caller
3148  * owns a reference to it and should use gst_object_unref() on the
3149  * pad when it is not needed any longer.
3150  *
3151  * Returns: unconnected pad of the given direction, or NULL.
3152  *
3153  * Since: 0.10.3
3154  */
3155 GstPad *
3156 gst_bin_find_unconnected_pad (GstBin * bin, GstPadDirection direction)
3157 {
3158   GstIterator *iter;
3159   gboolean done;
3160   GstPad *pad = NULL;
3161
3162   g_return_val_if_fail (GST_IS_BIN (bin), NULL);
3163   g_return_val_if_fail (direction != GST_PAD_UNKNOWN, NULL);
3164
3165   done = FALSE;
3166   iter = gst_bin_iterate_recurse (bin);
3167   while (!done) {
3168     gpointer element;
3169
3170     switch (gst_iterator_next (iter, &element)) {
3171       case GST_ITERATOR_OK:
3172         pad = element_find_unconnected_pad (GST_ELEMENT (element), direction);
3173         gst_object_unref (element);
3174         if (pad != NULL)
3175           done = TRUE;
3176         break;
3177       case GST_ITERATOR_DONE:
3178         done = TRUE;
3179         break;
3180       case GST_ITERATOR_RESYNC:
3181         gst_iterator_resync (iter);
3182         break;
3183       case GST_ITERATOR_ERROR:
3184         g_return_val_if_reached (NULL);
3185         break;
3186     }
3187   }
3188
3189   gst_iterator_free (iter);
3190
3191   return pad;
3192 }
3193
3194 /**
3195  * gst_parse_bin_from_description:
3196  * @bin_description: command line describing the bin
3197  * @ghost_unconnected_pads: whether to automatically create ghost pads
3198  *                          for unconnected source or sink pads within
3199  *                          the bin
3200  * @err: where to store the error message in case of an error, or NULL
3201  *
3202  * This is a convenience wrapper around gst_parse_launch() to create a
3203  * #GstBin from a gst-launch-style pipeline description. See
3204  * gst_parse_launch() and the gst-launch man page for details about the
3205  * syntax. Ghost pads on the bin for unconnected source or sink pads
3206  * within the bin can automatically be created (but only a maximum of
3207  * one ghost pad for each direction will be created; if you expect
3208  * multiple unconnected source pads or multiple unconnected sink pads
3209  * and want them all ghosted, you will have to create the ghost pads
3210  * yourself).
3211  *
3212  * Returns: a newly-created bin, or NULL if an error occurred.
3213  *
3214  * Since: 0.10.3
3215  */
3216 GstElement *
3217 gst_parse_bin_from_description (const gchar * bin_description,
3218     gboolean ghost_unconnected_pads, GError ** err)
3219 {
3220 #ifndef GST_DISABLE_PARSE
3221   GstPad *pad = NULL;
3222   GstBin *bin;
3223   gchar *desc;
3224
3225   g_return_val_if_fail (bin_description != NULL, NULL);
3226   g_return_val_if_fail (err == NULL || *err == NULL, NULL);
3227
3228   GST_DEBUG ("Making bin from description '%s'", bin_description);
3229
3230   /* parse the pipeline to a bin */
3231   desc = g_strdup_printf ("bin.( %s )", bin_description);
3232   bin = (GstBin *) gst_parse_launch (desc, err);
3233   g_free (desc);
3234
3235   if (bin == NULL || (err && *err != NULL)) {
3236     if (bin)
3237       gst_object_unref (bin);
3238     return NULL;
3239   }
3240
3241   /* find pads and ghost them if necessary */
3242   if (ghost_unconnected_pads) {
3243     if ((pad = gst_bin_find_unconnected_pad (bin, GST_PAD_SRC))) {
3244       gst_element_add_pad (GST_ELEMENT (bin), gst_ghost_pad_new ("src", pad));
3245       gst_object_unref (pad);
3246     }
3247     if ((pad = gst_bin_find_unconnected_pad (bin, GST_PAD_SINK))) {
3248       gst_element_add_pad (GST_ELEMENT (bin), gst_ghost_pad_new ("sink", pad));
3249       gst_object_unref (pad);
3250     }
3251   }
3252
3253   return GST_ELEMENT (bin);
3254 #else
3255   gchar *msg;
3256
3257   GST_WARNING ("Disabled API called: gst_parse_bin_from_description()");
3258
3259   msg = gst_error_get_message (GST_CORE_ERROR, GST_CORE_ERROR_DISABLED);
3260   g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_DISABLED, "%s", msg);
3261   g_free (msg);
3262
3263   return NULL;
3264 #endif
3265 }
3266
3267 /**
3268  * gst_type_register_static_full:
3269  * @parent_type: The GType of the parent type the newly registered type will 
3270  *   derive from
3271  * @type_name: NULL-terminated string used as the name of the new type
3272  * @class_size: Size of the class structure.
3273  * @base_init: Location of the base initialization function (optional).
3274  * @base_finalize: Location of the base finalization function (optional).
3275  * @class_init: Location of the class initialization function for class types 
3276  *   Location of the default vtable inititalization function for interface 
3277  *   types. (optional)
3278  * @class_finalize: Location of the class finalization function for class types.
3279  *   Location of the default vtable finalization function for interface types. 
3280  *   (optional)
3281  * @class_data: User-supplied data passed to the class init/finalize functions.
3282  * @instance_size: Size of the instance (object) structure (required for 
3283  *   instantiatable types only).
3284  * @n_preallocs: The number of pre-allocated (cached) instances to reserve 
3285  *   memory for (0 indicates no caching). Ignored on recent GLib's.
3286  * @instance_init: Location of the instance initialization function (optional, 
3287  *   for instantiatable types only).
3288  * @value_table: A GTypeValueTable function table for generic handling of 
3289  *   GValues of this type (usually only useful for fundamental types). 
3290  * @flags: #GTypeFlags for this GType. E.g: G_TYPE_FLAG_ABSTRACT
3291  *
3292  * Helper function which constructs a #GTypeInfo structure and registers a 
3293  * GType, but which generates less linker overhead than a static const 
3294  * #GTypeInfo structure. For further details of the parameters, please see
3295  * #GTypeInfo in the GLib documentation.
3296  *
3297  * Registers type_name as the name of a new static type derived from 
3298  * parent_type. The value of flags determines the nature (e.g. abstract or 
3299  * not) of the type. It works by filling a GTypeInfo struct and calling 
3300  * g_type_info_register_static().
3301  *
3302  * Returns: A #GType for the newly-registered type.
3303  *
3304  * Since: 0.10.14
3305  */
3306 GType
3307 gst_type_register_static_full (GType parent_type,
3308     const gchar * type_name,
3309     guint class_size,
3310     GBaseInitFunc base_init,
3311     GBaseFinalizeFunc base_finalize,
3312     GClassInitFunc class_init,
3313     GClassFinalizeFunc class_finalize,
3314     gconstpointer class_data,
3315     guint instance_size,
3316     guint16 n_preallocs,
3317     GInstanceInitFunc instance_init,
3318     const GTypeValueTable * value_table, GTypeFlags flags)
3319 {
3320   GTypeInfo info;
3321
3322   info.class_size = class_size;
3323   info.base_init = base_init;
3324   info.base_finalize = base_finalize;
3325   info.class_init = class_init;
3326   info.class_finalize = class_finalize;
3327   info.class_data = class_data;
3328   info.instance_size = instance_size;
3329   info.n_preallocs = n_preallocs;
3330   info.instance_init = instance_init;
3331   info.value_table = value_table;
3332
3333   return g_type_register_static (parent_type, type_name, &info, flags);
3334 }
3335
3336
3337 /**
3338  * gst_util_get_timestamp:
3339  *
3340  * Get a timestamp as GstClockTime to be used for interval meassurements.
3341  * The timestamp should not be interpreted in any other way.
3342  *
3343  * Returns: the timestamp
3344  *
3345  * Since: 0.10.16
3346  */
3347 GstClockTime
3348 gst_util_get_timestamp (void)
3349 {
3350 #if defined (HAVE_POSIX_TIMERS) && defined(HAVE_MONOTONIC_CLOCK)
3351   struct timespec now;
3352
3353   clock_gettime (CLOCK_MONOTONIC, &now);
3354   return GST_TIMESPEC_TO_TIME (now);
3355 #else
3356   GTimeVal now;
3357
3358   g_get_current_time (&now);
3359   return GST_TIMEVAL_TO_TIME (now);
3360 #endif
3361 }