gstelement: unref the clock when the element changes to null state
[platform/upstream/gstreamer.git] / gst / gstelement.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2004 Wim Taymans <wim@fluendo.com>
4  *
5  * gstelement.c: The base element, all elements derive from this
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gstelement
25  * @short_description: Abstract base class for all pipeline elements
26  * @see_also: #GstElementFactory, #GstPad
27  *
28  * GstElement is the abstract base class needed to construct an element that
29  * can be used in a GStreamer pipeline. Please refer to the plugin writers
30  * guide for more information on creating #GstElement subclasses.
31  *
32  * The name of a #GstElement can be get with gst_element_get_name() and set with
33  * gst_element_set_name().  For speed, GST_ELEMENT_NAME() can be used in the
34  * core when using the appropriate locking. Do not use this in plug-ins or
35  * applications in order to retain ABI compatibility.
36  *
37  * All elements have pads (of the type #GstPad).  These pads link to pads on
38  * other elements.  #GstBuffer flow between these linked pads.
39  * A #GstElement has a #GList of #GstPad structures for all their input (or sink)
40  * and output (or source) pads.
41  * Core and plug-in writers can add and remove pads with gst_element_add_pad()
42  * and gst_element_remove_pad().
43  *
44  * A pad of an element can be retrieved by name with gst_element_get_pad().
45  * An iterator of all pads can be retrieved with gst_element_iterate_pads().
46  *
47  * Elements can be linked through their pads.
48  * If the link is straightforward, use the gst_element_link()
49  * convenience function to link two elements, or gst_element_link_many()
50  * for more elements in a row.
51  * Use gst_element_link_filtered() to link two elements constrained by
52  * a specified set of #GstCaps.
53  * For finer control, use gst_element_link_pads() and
54  * gst_element_link_pads_filtered() to specify the pads to link on
55  * each element by name.
56  *
57  * Each element has a state (see #GstState).  You can get and set the state
58  * of an element with gst_element_get_state() and gst_element_set_state().
59  * To get a string representation of a #GstState, use
60  * gst_element_state_get_name().
61  *
62  * You can get and set a #GstClock on an element using gst_element_get_clock()
63  * and gst_element_set_clock().
64  * Some elements can provide a clock for the pipeline if
65  * gst_element_provides_clock() returns %TRUE. With the
66  * gst_element_provide_clock() method one can retrieve the clock provided by
67  * such an element.
68  * Not all elements require a clock to operate correctly. If
69  * gst_element_requires_clock() returns %TRUE, a clock should be set on the
70  * element with gst_element_set_clock().
71  *
72  * Note that clock slection and distribution is normally handled by the
73  * toplevel #GstPipeline so the clock functions are only to be used in very
74  * specific situations.
75  *
76  * Last reviewed on 2009-05-29 (0.10.24)
77  */
78
79 #include "gst_private.h"
80 #include <glib.h>
81 #include <stdarg.h>
82 #include <gobject/gvaluecollector.h>
83
84 #include "gstelement.h"
85 #include "gstenumtypes.h"
86 #include "gstbus.h"
87 #include "gstmarshal.h"
88 #include "gsterror.h"
89 #include "gstevent.h"
90 #include "gstutils.h"
91 #include "gstinfo.h"
92 #include "gstvalue.h"
93 #include "gst-i18n-lib.h"
94
95 /* Element signals and args */
96 enum
97 {
98   PAD_ADDED,
99   PAD_REMOVED,
100   NO_MORE_PADS,
101   /* add more above */
102   LAST_SIGNAL
103 };
104
105 enum
106 {
107   ARG_0
108       /* FILL ME */
109 };
110
111 extern void __gst_element_details_clear (GstElementDetails * dp);
112 extern void __gst_element_details_copy (GstElementDetails * dest,
113     const GstElementDetails * src);
114
115 static void gst_element_class_init (GstElementClass * klass);
116 static void gst_element_init (GstElement * element);
117 static void gst_element_base_class_init (gpointer g_class);
118 static void gst_element_base_class_finalize (gpointer g_class);
119
120 static void gst_element_dispose (GObject * object);
121 static void gst_element_finalize (GObject * object);
122
123 static GstStateChangeReturn gst_element_change_state_func (GstElement * element,
124     GstStateChange transition);
125 static GstStateChangeReturn gst_element_get_state_func (GstElement * element,
126     GstState * state, GstState * pending, GstClockTime timeout);
127 static GstStateChangeReturn gst_element_set_state_func (GstElement * element,
128     GstState state);
129 static void gst_element_set_bus_func (GstElement * element, GstBus * bus);
130
131 static gboolean gst_element_default_send_event (GstElement * element,
132     GstEvent * event);
133 static gboolean gst_element_default_query (GstElement * element,
134     GstQuery * query);
135
136 static GstPadTemplate
137     * gst_element_class_get_request_pad_template (GstElementClass *
138     element_class, const gchar * name);
139
140 #ifndef GST_DISABLE_LOADSAVE
141 static xmlNodePtr gst_element_save_thyself (GstObject * object,
142     xmlNodePtr parent);
143 static void gst_element_restore_thyself (GstObject * parent, xmlNodePtr self);
144 #endif
145
146 static GstObjectClass *parent_class = NULL;
147 static guint gst_element_signals[LAST_SIGNAL] = { 0 };
148
149 /* this is used in gstelementfactory.c:gst_element_register() */
150 GQuark _gst_elementclass_factory = 0;
151
152 GType
153 gst_element_get_type (void)
154 {
155   static volatile gsize gst_element_type = 0;
156
157   if (g_once_init_enter (&gst_element_type)) {
158     GType _type;
159     static const GTypeInfo element_info = {
160       sizeof (GstElementClass),
161       gst_element_base_class_init,
162       gst_element_base_class_finalize,
163       (GClassInitFunc) gst_element_class_init,
164       NULL,
165       NULL,
166       sizeof (GstElement),
167       0,
168       (GInstanceInitFunc) gst_element_init,
169       NULL
170     };
171
172     _type = g_type_register_static (GST_TYPE_OBJECT, "GstElement",
173         &element_info, G_TYPE_FLAG_ABSTRACT);
174
175     _gst_elementclass_factory =
176         g_quark_from_static_string ("GST_ELEMENTCLASS_FACTORY");
177     g_once_init_leave (&gst_element_type, _type);
178   }
179   return gst_element_type;
180 }
181
182 static void
183 gst_element_class_init (GstElementClass * klass)
184 {
185   GObjectClass *gobject_class;
186   GstObjectClass *gstobject_class;
187
188   gobject_class = (GObjectClass *) klass;
189   gstobject_class = (GstObjectClass *) klass;
190
191   parent_class = g_type_class_peek_parent (klass);
192
193   /**
194    * GstElement::pad-added:
195    * @gstelement: the object which received the signal
196    * @new_pad: the pad that has been added
197    *
198    * a new #GstPad has been added to the element.
199    */
200   gst_element_signals[PAD_ADDED] =
201       g_signal_new ("pad-added", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
202       G_STRUCT_OFFSET (GstElementClass, pad_added), NULL, NULL,
203       gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_PAD);
204   /**
205    * GstElement::pad-removed:
206    * @gstelement: the object which received the signal
207    * @old_pad: the pad that has been removed
208    *
209    * a #GstPad has been removed from the element
210    */
211   gst_element_signals[PAD_REMOVED] =
212       g_signal_new ("pad-removed", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
213       G_STRUCT_OFFSET (GstElementClass, pad_removed), NULL, NULL,
214       gst_marshal_VOID__OBJECT, G_TYPE_NONE, 1, GST_TYPE_PAD);
215   /**
216    * GstElement::no-more-pads:
217    * @gstelement: the object which received the signal
218    *
219    * This signals that the element will not generate more dynamic pads.
220    */
221   gst_element_signals[NO_MORE_PADS] =
222       g_signal_new ("no-more-pads", G_TYPE_FROM_CLASS (klass),
223       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstElementClass, no_more_pads), NULL,
224       NULL, gst_marshal_VOID__VOID, G_TYPE_NONE, 0);
225
226   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_element_dispose);
227   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_element_finalize);
228
229 #ifndef GST_DISABLE_LOADSAVE
230   gstobject_class->save_thyself = GST_DEBUG_FUNCPTR (gst_element_save_thyself);
231   gstobject_class->restore_thyself =
232       GST_DEBUG_FUNCPTR (gst_element_restore_thyself);
233 #endif
234
235   klass->change_state = GST_DEBUG_FUNCPTR (gst_element_change_state_func);
236   klass->set_state = GST_DEBUG_FUNCPTR (gst_element_set_state_func);
237   klass->get_state = GST_DEBUG_FUNCPTR (gst_element_get_state_func);
238   klass->set_bus = GST_DEBUG_FUNCPTR (gst_element_set_bus_func);
239   klass->query = GST_DEBUG_FUNCPTR (gst_element_default_query);
240   klass->send_event = GST_DEBUG_FUNCPTR (gst_element_default_send_event);
241   klass->numpadtemplates = 0;
242
243   klass->elementfactory = NULL;
244 }
245
246 static void
247 gst_element_base_class_init (gpointer g_class)
248 {
249   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
250
251   /* FIXME 0.11: Copy the element details and instead of clearing the
252    * pad template list copy the list and increase the refcount of
253    * the pad templates by one.
254    *
255    * This will make it possible to add pad templates and set element
256    * details in the class_init functions and is the real GObject way
257    * of doing things.
258    * See http://bugzilla.gnome.org/show_bug.cgi?id=491501
259    */
260   memset (&element_class->details, 0, sizeof (GstElementDetails));
261   element_class->padtemplates = NULL;
262
263   /* set the factory, see gst_element_register() */
264   element_class->elementfactory =
265       g_type_get_qdata (G_TYPE_FROM_CLASS (element_class),
266       _gst_elementclass_factory);
267   GST_DEBUG ("type %s : factory %p", G_OBJECT_CLASS_NAME (element_class),
268       element_class->elementfactory);
269 }
270
271 static void
272 gst_element_base_class_finalize (gpointer g_class)
273 {
274   GstElementClass *klass = GST_ELEMENT_CLASS (g_class);
275
276   g_list_foreach (klass->padtemplates, (GFunc) gst_object_unref, NULL);
277   g_list_free (klass->padtemplates);
278   __gst_element_details_clear (&klass->details);
279 }
280
281 static void
282 gst_element_init (GstElement * element)
283 {
284   GST_STATE (element) = GST_STATE_NULL;
285   GST_STATE_TARGET (element) = GST_STATE_NULL;
286   GST_STATE_NEXT (element) = GST_STATE_VOID_PENDING;
287   GST_STATE_PENDING (element) = GST_STATE_VOID_PENDING;
288   GST_STATE_RETURN (element) = GST_STATE_CHANGE_SUCCESS;
289
290   element->state_lock = g_new0 (GStaticRecMutex, 1);
291   g_static_rec_mutex_init (element->state_lock);
292   element->state_cond = g_cond_new ();
293 }
294
295 /**
296  * gst_element_default_error:
297  * @object: a #GObject that signalled the error.
298  * @orig: the #GstObject that initiated the error.
299  * @error: the GError.
300  * @debug: an additional debug information string, or %NULL.
301  *
302  * A default error signal callback to attach to an element.
303  * The user data passed to the g_signal_connect is ignored.
304  *
305  * The default handler will simply print the error string using g_print.
306  *
307  * MT safe.
308  */
309 void
310 gst_element_default_error (GObject * object, GstObject * source, GError * error,
311     gchar * debug)
312 {
313   gchar *name = gst_object_get_path_string (source);
314
315   g_print (_("ERROR: from element %s: %s\n"), name, error->message);
316   if (debug)
317     g_print (_("Additional debug info:\n%s\n"), debug);
318
319   g_free (name);
320 }
321
322 /**
323  * gst_element_release_request_pad:
324  * @element: a #GstElement to release the request pad of.
325  * @pad: the #GstPad to release.
326  *
327  * Makes the element free the previously requested pad as obtained
328  * with gst_element_get_request_pad().
329  *
330  * MT safe.
331  */
332 void
333 gst_element_release_request_pad (GstElement * element, GstPad * pad)
334 {
335   GstElementClass *oclass;
336
337   g_return_if_fail (GST_IS_ELEMENT (element));
338   g_return_if_fail (GST_IS_PAD (pad));
339
340   oclass = GST_ELEMENT_GET_CLASS (element);
341
342   /* if the element implements a custom release function we call that, else we
343    * simply remove the pad from the element */
344   if (oclass->release_pad)
345     (oclass->release_pad) (element, pad);
346   else
347     gst_element_remove_pad (element, pad);
348 }
349
350 /**
351  * gst_element_requires_clock:
352  * @element: a #GstElement to query
353  *
354  * Query if the element requires a clock.
355  *
356  * Returns: %TRUE if the element requires a clock
357  *
358  * MT safe.
359  */
360 gboolean
361 gst_element_requires_clock (GstElement * element)
362 {
363   gboolean result;
364
365   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
366
367   result = (GST_ELEMENT_GET_CLASS (element)->set_clock != NULL);
368
369   return result;
370 }
371
372 /**
373  * gst_element_provides_clock:
374  * @element: a #GstElement to query
375  *
376  * Query if the element provides a clock. A #GstClock provided by an
377  * element can be used as the global #GstClock for the pipeline.
378  * An element that can provide a clock is only required to do so in the PAUSED
379  * state, this means when it is fully negotiated and has allocated the resources
380  * to operate the clock.
381  *
382  * Returns: %TRUE if the element provides a clock
383  *
384  * MT safe.
385  */
386 gboolean
387 gst_element_provides_clock (GstElement * element)
388 {
389   gboolean result;
390
391   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
392
393   result = (GST_ELEMENT_GET_CLASS (element)->provide_clock != NULL);
394
395   return result;
396 }
397
398 /**
399  * gst_element_provide_clock:
400  * @element: a #GstElement to query
401  *
402  * Get the clock provided by the given element.
403  * <note>An element is only required to provide a clock in the PAUSED
404  * state. Some elements can provide a clock in other states.</note>
405  *
406  * Returns: the GstClock provided by the element or %NULL
407  * if no clock could be provided.  Unref after usage.
408  *
409  * MT safe.
410  */
411 GstClock *
412 gst_element_provide_clock (GstElement * element)
413 {
414   GstClock *result = NULL;
415   GstElementClass *oclass;
416
417   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
418
419   oclass = GST_ELEMENT_GET_CLASS (element);
420
421   if (oclass->provide_clock)
422     result = oclass->provide_clock (element);
423
424   return result;
425 }
426
427 /**
428  * gst_element_set_clock:
429  * @element: a #GstElement to set the clock for.
430  * @clock: the #GstClock to set for the element.
431  *
432  * Sets the clock for the element. This function increases the
433  * refcount on the clock. Any previously set clock on the object
434  * is unreffed.
435  *
436  * Returns: %TRUE if the element accepted the clock. An element can refuse a
437  * clock when it, for example, is not able to slave its internal clock to the
438  * @clock or when it requires a specific clock to operate.
439  *
440  * MT safe.
441  */
442 gboolean
443 gst_element_set_clock (GstElement * element, GstClock * clock)
444 {
445   GstElementClass *oclass;
446   gboolean res = TRUE;
447   GstClock **clock_p;
448
449   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
450
451   oclass = GST_ELEMENT_GET_CLASS (element);
452
453   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, element, "setting clock %p", clock);
454
455   if (oclass->set_clock)
456     res = oclass->set_clock (element, clock);
457
458   if (res) {
459     /* only update the clock pointer if the element accepted the clock */
460     GST_OBJECT_LOCK (element);
461     clock_p = &element->clock;
462     gst_object_replace ((GstObject **) clock_p, (GstObject *) clock);
463     GST_OBJECT_UNLOCK (element);
464   }
465   return res;
466 }
467
468 /**
469  * gst_element_get_clock:
470  * @element: a #GstElement to get the clock of.
471  *
472  * Gets the currently configured clock of the element. This is the clock as was
473  * last set with gst_element_set_clock().
474  *
475  * Returns: the #GstClock of the element. unref after usage.
476  *
477  * MT safe.
478  */
479 GstClock *
480 gst_element_get_clock (GstElement * element)
481 {
482   GstClock *result;
483
484   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
485
486   GST_OBJECT_LOCK (element);
487   if ((result = element->clock))
488     gst_object_ref (result);
489   GST_OBJECT_UNLOCK (element);
490
491   return result;
492 }
493
494 /**
495  * gst_element_set_base_time:
496  * @element: a #GstElement.
497  * @time: the base time to set.
498  *
499  * Set the base time of an element. See gst_element_get_base_time().
500  *
501  * MT safe.
502  */
503 void
504 gst_element_set_base_time (GstElement * element, GstClockTime time)
505 {
506   GstClockTime old;
507
508   g_return_if_fail (GST_IS_ELEMENT (element));
509
510   GST_OBJECT_LOCK (element);
511   old = element->base_time;
512   element->base_time = time;
513   GST_OBJECT_UNLOCK (element);
514
515   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, element,
516       "set base_time=%" GST_TIME_FORMAT ", old %" GST_TIME_FORMAT,
517       GST_TIME_ARGS (time), GST_TIME_ARGS (old));
518 }
519
520 /**
521  * gst_element_get_base_time:
522  * @element: a #GstElement.
523  *
524  * Returns the base time of the element. The base time is the
525  * absolute time of the clock when this element was last put to
526  * PLAYING. Subtracting the base time from the clock time gives
527  * the running time of the element.
528  *
529  * Returns: the base time of the element.
530  *
531  * MT safe.
532  */
533 GstClockTime
534 gst_element_get_base_time (GstElement * element)
535 {
536   GstClockTime result;
537
538   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_CLOCK_TIME_NONE);
539
540   GST_OBJECT_LOCK (element);
541   result = element->base_time;
542   GST_OBJECT_UNLOCK (element);
543
544   return result;
545 }
546
547 /**
548  * gst_element_set_start_time:
549  * @element: a #GstElement.
550  * @time: the base time to set.
551  *
552  * Set the start time of an element. The start time of the element is the
553  * running time of the element when it last went to the PAUSED state. In READY
554  * or after a flushing seek, it is set to 0.
555  *
556  * Toplevel elements like #GstPipeline will manage the start_time and
557  * base_time on its children. Setting the start_time to #GST_CLOCK_TIME_NONE
558  * on such a toplevel element will disable the distribution of the base_time to
559  * the children and can be useful if the application manages the base_time
560  * itself, for example if you want to synchronize capture from multiple
561  * pipelines, and you can also ensure that the pipelines have the same clock.
562  *
563  * MT safe.
564  *
565  * Since: 0.10.24
566  */
567 void
568 gst_element_set_start_time (GstElement * element, GstClockTime time)
569 {
570   GstClockTime old;
571
572   g_return_if_fail (GST_IS_ELEMENT (element));
573
574   GST_OBJECT_LOCK (element);
575   old = GST_ELEMENT_START_TIME (element);
576   GST_ELEMENT_START_TIME (element) = time;
577   GST_OBJECT_UNLOCK (element);
578
579   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, element,
580       "set start_time=%" GST_TIME_FORMAT ", old %" GST_TIME_FORMAT,
581       GST_TIME_ARGS (time), GST_TIME_ARGS (old));
582 }
583
584 /**
585  * gst_element_get_start_time:
586  * @element: a #GstElement.
587  *
588  * Returns the start time of the element. The start time is the
589  * running time of the clock when this element was last put to PAUSED. 
590  *
591  * Usually the start_time is managed by a toplevel element such as
592  * #GstPipeline. 
593  *
594  * MT safe.
595  *
596  * Returns: the start time of the element.
597  *
598  * Since: 0.10.24
599  */
600 GstClockTime
601 gst_element_get_start_time (GstElement * element)
602 {
603   GstClockTime result;
604
605   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_CLOCK_TIME_NONE);
606
607   GST_OBJECT_LOCK (element);
608   result = GST_ELEMENT_START_TIME (element);
609   GST_OBJECT_UNLOCK (element);
610
611   return result;
612 }
613
614 /**
615  * gst_element_is_indexable:
616  * @element: a #GstElement.
617  *
618  * Queries if the element can be indexed.
619  *
620  * Returns: TRUE if the element can be indexed.
621  *
622  * MT safe.
623  */
624 gboolean
625 gst_element_is_indexable (GstElement * element)
626 {
627   gboolean result;
628
629   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
630
631   result = (GST_ELEMENT_GET_CLASS (element)->set_index != NULL);
632
633   return result;
634 }
635
636 /**
637  * gst_element_set_index:
638  * @element: a #GstElement.
639  * @index: a #GstIndex.
640  *
641  * Set @index on the element. The refcount of the index
642  * will be increased, any previously set index is unreffed.
643  *
644  * MT safe.
645  */
646 void
647 gst_element_set_index (GstElement * element, GstIndex * index)
648 {
649   GstElementClass *oclass;
650
651   g_return_if_fail (GST_IS_ELEMENT (element));
652   g_return_if_fail (GST_IS_INDEX (index));
653
654   oclass = GST_ELEMENT_GET_CLASS (element);
655
656   if (oclass->set_index)
657     oclass->set_index (element, index);
658 }
659
660 /**
661  * gst_element_get_index:
662  * @element: a #GstElement.
663  *
664  * Gets the index from the element.
665  *
666  * Returns: a #GstIndex or %NULL when no index was set on the
667  * element. unref after usage.
668  *
669  * MT safe.
670  */
671 GstIndex *
672 gst_element_get_index (GstElement * element)
673 {
674   GstElementClass *oclass;
675   GstIndex *result = NULL;
676
677   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
678
679   oclass = GST_ELEMENT_GET_CLASS (element);
680
681   if (oclass->get_index)
682     result = oclass->get_index (element);
683
684   return result;
685 }
686
687 /**
688  * gst_element_add_pad:
689  * @element: a #GstElement to add the pad to.
690  * @pad: the #GstPad to add to the element.
691  *
692  * Adds a pad (link point) to @element. @pad's parent will be set to @element;
693  * see gst_object_set_parent() for refcounting information.
694  *
695  * Pads are not automatically activated so elements should perform the needed
696  * steps to activate the pad in case this pad is added in the PAUSED or PLAYING
697  * state. See gst_pad_set_active() for more information about activating pads.
698  *
699  * The pad and the element should be unlocked when calling this function.
700  *
701  * This function will emit the #GstElement::pad-added signal on the element.
702  *
703  * Returns: %TRUE if the pad could be added. This function can fail when
704  * a pad with the same name already existed or the pad already had another
705  * parent.
706  *
707  * MT safe.
708  */
709 gboolean
710 gst_element_add_pad (GstElement * element, GstPad * pad)
711 {
712   gchar *pad_name;
713   gboolean flushing;
714
715   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
716   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
717
718   /* locking pad to look at the name */
719   GST_OBJECT_LOCK (pad);
720   pad_name = g_strdup (GST_PAD_NAME (pad));
721   GST_CAT_INFO_OBJECT (GST_CAT_ELEMENT_PADS, element, "adding pad '%s'",
722       GST_STR_NULL (pad_name));
723   flushing = GST_PAD_IS_FLUSHING (pad);
724   GST_OBJECT_UNLOCK (pad);
725
726   /* then check to see if there's already a pad by that name here */
727   GST_OBJECT_LOCK (element);
728   if (G_UNLIKELY (!gst_object_check_uniqueness (element->pads, pad_name)))
729     goto name_exists;
730
731   /* try to set the pad's parent */
732   if (G_UNLIKELY (!gst_object_set_parent (GST_OBJECT_CAST (pad),
733               GST_OBJECT_CAST (element))))
734     goto had_parent;
735
736   /* check for flushing pads */
737   if (flushing && (GST_STATE (element) > GST_STATE_READY ||
738           GST_STATE_NEXT (element) == GST_STATE_PAUSED)) {
739     g_warning ("adding flushing pad '%s' to running element '%s'",
740         GST_STR_NULL (pad_name), GST_ELEMENT_NAME (element));
741     /* unset flushing */
742     GST_OBJECT_LOCK (pad);
743     GST_PAD_UNSET_FLUSHING (pad);
744     GST_OBJECT_UNLOCK (pad);
745   }
746
747   g_free (pad_name);
748
749   /* add it to the list */
750   switch (gst_pad_get_direction (pad)) {
751     case GST_PAD_SRC:
752       element->srcpads = g_list_prepend (element->srcpads, pad);
753       element->numsrcpads++;
754       break;
755     case GST_PAD_SINK:
756       element->sinkpads = g_list_prepend (element->sinkpads, pad);
757       element->numsinkpads++;
758       break;
759     default:
760       goto no_direction;
761   }
762   element->pads = g_list_prepend (element->pads, pad);
763   element->numpads++;
764   element->pads_cookie++;
765   GST_OBJECT_UNLOCK (element);
766
767   /* emit the PAD_ADDED signal */
768   g_signal_emit (element, gst_element_signals[PAD_ADDED], 0, pad);
769
770   return TRUE;
771
772   /* ERROR cases */
773 name_exists:
774   {
775     g_critical ("Padname %s is not unique in element %s, not adding",
776         pad_name, GST_ELEMENT_NAME (element));
777     GST_OBJECT_UNLOCK (element);
778     g_free (pad_name);
779     return FALSE;
780   }
781 had_parent:
782   {
783     g_critical
784         ("Pad %s already has parent when trying to add to element %s",
785         pad_name, GST_ELEMENT_NAME (element));
786     GST_OBJECT_UNLOCK (element);
787     g_free (pad_name);
788     return FALSE;
789   }
790 no_direction:
791   {
792     GST_OBJECT_LOCK (pad);
793     g_critical
794         ("Trying to add pad %s to element %s, but it has no direction",
795         GST_OBJECT_NAME (pad), GST_ELEMENT_NAME (element));
796     GST_OBJECT_UNLOCK (pad);
797     GST_OBJECT_UNLOCK (element);
798     return FALSE;
799   }
800 }
801
802 /**
803  * gst_element_remove_pad:
804  * @element: a #GstElement to remove pad from.
805  * @pad: the #GstPad to remove from the element.
806  *
807  * Removes @pad from @element. @pad will be destroyed if it has not been
808  * referenced elsewhere using gst_object_unparent().
809  *
810  * This function is used by plugin developers and should not be used
811  * by applications. Pads that were dynamically requested from elements
812  * with gst_element_get_request_pad() should be released with the
813  * gst_element_release_request_pad() function instead.
814  *
815  * Pads are not automatically deactivated so elements should perform the needed
816  * steps to deactivate the pad in case this pad is removed in the PAUSED or
817  * PLAYING state. See gst_pad_set_active() for more information about
818  * deactivating pads.
819  *
820  * The pad and the element should be unlocked when calling this function.
821  *
822  * This function will emit the #GstElement::pad-removed signal on the element.
823  *
824  * Returns: %TRUE if the pad could be removed. Can return %FALSE if the
825  * pad does not belong to the provided element.
826  *
827  * MT safe.
828  */
829 gboolean
830 gst_element_remove_pad (GstElement * element, GstPad * pad)
831 {
832   GstPad *peer;
833
834   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
835   g_return_val_if_fail (GST_IS_PAD (pad), FALSE);
836
837   /* locking pad to look at the name and parent */
838   GST_OBJECT_LOCK (pad);
839   GST_CAT_INFO_OBJECT (GST_CAT_ELEMENT_PADS, element, "removing pad '%s'",
840       GST_STR_NULL (GST_PAD_NAME (pad)));
841
842   if (G_UNLIKELY (GST_PAD_PARENT (pad) != element))
843     goto not_our_pad;
844   GST_OBJECT_UNLOCK (pad);
845
846   /* unlink */
847   if ((peer = gst_pad_get_peer (pad))) {
848     /* window for MT unsafeness, someone else could unlink here
849      * and then we call unlink with wrong pads. The unlink
850      * function would catch this and safely return failed. */
851     if (GST_PAD_IS_SRC (pad))
852       gst_pad_unlink (pad, peer);
853     else
854       gst_pad_unlink (peer, pad);
855
856     gst_object_unref (peer);
857   }
858
859   GST_OBJECT_LOCK (element);
860   /* remove it from the list */
861   switch (gst_pad_get_direction (pad)) {
862     case GST_PAD_SRC:
863       element->srcpads = g_list_remove (element->srcpads, pad);
864       element->numsrcpads--;
865       break;
866     case GST_PAD_SINK:
867       element->sinkpads = g_list_remove (element->sinkpads, pad);
868       element->numsinkpads--;
869       break;
870     default:
871       g_critical ("Removing pad without direction???");
872       break;
873   }
874   element->pads = g_list_remove (element->pads, pad);
875   element->numpads--;
876   element->pads_cookie++;
877   GST_OBJECT_UNLOCK (element);
878
879   /* emit the PAD_REMOVED signal before unparenting and losing the last ref. */
880   g_signal_emit (element, gst_element_signals[PAD_REMOVED], 0, pad);
881
882   gst_object_unparent (GST_OBJECT_CAST (pad));
883
884   return TRUE;
885
886   /* ERRORS */
887 not_our_pad:
888   {
889     /* FIXME, locking order? */
890     GST_OBJECT_LOCK (element);
891     g_critical ("Padname %s:%s does not belong to element %s when removing",
892         GST_DEBUG_PAD_NAME (pad), GST_ELEMENT_NAME (element));
893     GST_OBJECT_UNLOCK (element);
894     GST_OBJECT_UNLOCK (pad);
895     return FALSE;
896   }
897 }
898
899 /**
900  * gst_element_no_more_pads:
901  * @element: a #GstElement
902  *
903  * Use this function to signal that the element does not expect any more pads
904  * to show up in the current pipeline. This function should be called whenever
905  * pads have been added by the element itself. Elements with #GST_PAD_SOMETIMES
906  * pad templates use this in combination with autopluggers to figure out that
907  * the element is done initializing its pads.
908  *
909  * This function emits the #GstElement::no-more-pads signal.
910  *
911  * MT safe.
912  */
913 void
914 gst_element_no_more_pads (GstElement * element)
915 {
916   g_return_if_fail (GST_IS_ELEMENT (element));
917
918   g_signal_emit (element, gst_element_signals[NO_MORE_PADS], 0);
919 }
920
921 static gint
922 pad_compare_name (GstPad * pad1, const gchar * name)
923 {
924   gint result;
925
926   GST_OBJECT_LOCK (pad1);
927   result = strcmp (GST_PAD_NAME (pad1), name);
928   GST_OBJECT_UNLOCK (pad1);
929
930   return result;
931 }
932
933 /**
934  * gst_element_get_static_pad:
935  * @element: a #GstElement to find a static pad of.
936  * @name: the name of the static #GstPad to retrieve.
937  *
938  * Retrieves a pad from @element by name. This version only retrieves
939  * already-existing (i.e. 'static') pads.
940  *
941  * Returns: the requested #GstPad if found, otherwise %NULL. unref after
942  * usage.
943  *
944  * MT safe.
945  */
946 GstPad *
947 gst_element_get_static_pad (GstElement * element, const gchar * name)
948 {
949   GList *find;
950   GstPad *result = NULL;
951
952   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
953   g_return_val_if_fail (name != NULL, NULL);
954
955   GST_OBJECT_LOCK (element);
956   find =
957       g_list_find_custom (element->pads, name, (GCompareFunc) pad_compare_name);
958   if (find) {
959     result = GST_PAD_CAST (find->data);
960     gst_object_ref (result);
961   }
962
963   if (result == NULL) {
964     GST_CAT_INFO (GST_CAT_ELEMENT_PADS, "no such pad '%s' in element \"%s\"",
965         name, GST_ELEMENT_NAME (element));
966   } else {
967     GST_CAT_INFO (GST_CAT_ELEMENT_PADS, "found pad %s:%s",
968         GST_ELEMENT_NAME (element), name);
969   }
970   GST_OBJECT_UNLOCK (element);
971
972   return result;
973 }
974
975 static GstPad *
976 gst_element_request_pad (GstElement * element, GstPadTemplate * templ,
977     const gchar * name)
978 {
979   GstPad *newpad = NULL;
980   GstElementClass *oclass;
981
982   oclass = GST_ELEMENT_GET_CLASS (element);
983
984   if (oclass->request_new_pad)
985     newpad = (oclass->request_new_pad) (element, templ, name);
986
987   if (newpad)
988     gst_object_ref (newpad);
989
990   return newpad;
991 }
992
993 /**
994  * gst_element_get_request_pad:
995  * @element: a #GstElement to find a request pad of.
996  * @name: the name of the request #GstPad to retrieve.
997  *
998  * Retrieves a pad from the element by name. This version only retrieves
999  * request pads. The pad should be released with
1000  * gst_element_release_request_pad().
1001  *
1002  * Returns: requested #GstPad if found, otherwise %NULL. Release after usage.
1003  */
1004 GstPad *
1005 gst_element_get_request_pad (GstElement * element, const gchar * name)
1006 {
1007   GstPadTemplate *templ = NULL;
1008   GstPad *pad;
1009   const gchar *req_name = NULL;
1010   gboolean templ_found = FALSE;
1011   GList *list;
1012   gint n;
1013   const gchar *data;
1014   gchar *str, *endptr = NULL;
1015   GstElementClass *class;
1016
1017   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1018   g_return_val_if_fail (name != NULL, NULL);
1019
1020   class = GST_ELEMENT_GET_CLASS (element);
1021
1022   /* if the name contains a %, we assume it's the complete template name. Get
1023    * the template and try to get a pad */
1024   if (strstr (name, "%")) {
1025     templ = gst_element_class_get_request_pad_template (class, name);
1026     req_name = NULL;
1027     if (templ)
1028       templ_found = TRUE;
1029   } else {
1030     /* there is no % in the name, try to find a matching template */
1031     list = gst_element_class_get_pad_template_list (class);
1032     while (!templ_found && list) {
1033       templ = (GstPadTemplate *) list->data;
1034       if (templ->presence == GST_PAD_REQUEST) {
1035         GST_CAT_DEBUG (GST_CAT_PADS, "comparing %s to %s", name,
1036             templ->name_template);
1037         /* see if we find an exact match */
1038         if (strcmp (name, templ->name_template) == 0) {
1039           templ_found = TRUE;
1040           req_name = name;
1041           break;
1042         }
1043         /* Because of sanity checks in gst_pad_template_new(), we know that %s
1044            and %d, occurring at the end of the name_template, are the only
1045            possibilities. */
1046         else if ((str = strchr (templ->name_template, '%'))
1047             && strncmp (templ->name_template, name,
1048                 str - templ->name_template) == 0
1049             && strlen (name) > str - templ->name_template) {
1050           data = name + (str - templ->name_template);
1051           if (*(str + 1) == 'd') {
1052             /* it's an int */
1053             n = (gint) strtol (data, &endptr, 10);
1054             if (endptr && *endptr == '\0') {
1055               templ_found = TRUE;
1056               req_name = name;
1057               break;
1058             }
1059           } else {
1060             /* it's a string */
1061             templ_found = TRUE;
1062             req_name = name;
1063             break;
1064           }
1065         }
1066       }
1067       list = list->next;
1068     }
1069   }
1070
1071   if (!templ_found)
1072     return NULL;
1073
1074   pad = gst_element_request_pad (element, templ, req_name);
1075
1076   return pad;
1077 }
1078
1079 /**
1080  * gst_element_get_pad:
1081  * @element: a #GstElement.
1082  * @name: the name of the pad to retrieve.
1083  *
1084  * Retrieves a pad from @element by name. Tries gst_element_get_static_pad()
1085  * first, then gst_element_get_request_pad().
1086  *
1087  * Deprecated: This function is deprecated as it's unclear if the reference
1088  * to the result pad should be released with gst_object_unref() in case of a static pad
1089  * or gst_element_release_request_pad() in case of a request pad.
1090  * Use gst_element_get_static_pad() or gst_element_get_request_pad() instead.
1091  *
1092  * Returns: the #GstPad if found, otherwise %NULL. Unref or Release after usage,
1093  * depending on the type of the pad.
1094  */
1095 #ifndef GST_REMOVE_DEPRECATED
1096 GstPad *
1097 gst_element_get_pad (GstElement * element, const gchar * name)
1098 {
1099   GstPad *pad;
1100
1101   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1102   g_return_val_if_fail (name != NULL, NULL);
1103
1104   pad = gst_element_get_static_pad (element, name);
1105   if (!pad)
1106     pad = gst_element_get_request_pad (element, name);
1107
1108   return pad;
1109 }
1110 #endif /* GST_REMOVE_DEPRECATED */
1111
1112 static GstIteratorItem
1113 iterate_pad (GstIterator * it, GstPad * pad)
1114 {
1115   gst_object_ref (pad);
1116   return GST_ITERATOR_ITEM_PASS;
1117 }
1118
1119 static GstIterator *
1120 gst_element_iterate_pad_list (GstElement * element, GList ** padlist)
1121 {
1122   GstIterator *result;
1123
1124   GST_OBJECT_LOCK (element);
1125   gst_object_ref (element);
1126   result = gst_iterator_new_list (GST_TYPE_PAD,
1127       GST_OBJECT_GET_LOCK (element),
1128       &element->pads_cookie,
1129       padlist,
1130       element,
1131       (GstIteratorItemFunction) iterate_pad,
1132       (GstIteratorDisposeFunction) gst_object_unref);
1133   GST_OBJECT_UNLOCK (element);
1134
1135   return result;
1136 }
1137
1138 /**
1139  * gst_element_iterate_pads:
1140  * @element: a #GstElement to iterate pads of.
1141  *
1142  * Retrieves an iterattor of @element's pads. The iterator should
1143  * be freed after usage.
1144  *
1145  * Returns: the #GstIterator of #GstPad. Unref each pad after use.
1146  *
1147  * MT safe.
1148  */
1149 GstIterator *
1150 gst_element_iterate_pads (GstElement * element)
1151 {
1152   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1153
1154   return gst_element_iterate_pad_list (element, &element->pads);
1155 }
1156
1157 /**
1158  * gst_element_iterate_src_pads:
1159  * @element: a #GstElement.
1160  *
1161  * Retrieves an iterator of @element's source pads.
1162  *
1163  * Returns: the #GstIterator of #GstPad. Unref each pad after use.
1164  *
1165  * MT safe.
1166  */
1167 GstIterator *
1168 gst_element_iterate_src_pads (GstElement * element)
1169 {
1170   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1171
1172   return gst_element_iterate_pad_list (element, &element->srcpads);
1173 }
1174
1175 /**
1176  * gst_element_iterate_sink_pads:
1177  * @element: a #GstElement.
1178  *
1179  * Retrieves an iterator of @element's sink pads.
1180  *
1181  * Returns: the #GstIterator of #GstPad. Unref each pad after use.
1182  *
1183  * MT safe.
1184  */
1185 GstIterator *
1186 gst_element_iterate_sink_pads (GstElement * element)
1187 {
1188   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1189
1190   return gst_element_iterate_pad_list (element, &element->sinkpads);
1191 }
1192
1193 /**
1194  * gst_element_class_add_pad_template:
1195  * @klass: the #GstElementClass to add the pad template to.
1196  * @templ: a #GstPadTemplate to add to the element class.
1197  *
1198  * Adds a padtemplate to an element class. This is mainly used in the _base_init
1199  * functions of classes.
1200  */
1201 void
1202 gst_element_class_add_pad_template (GstElementClass * klass,
1203     GstPadTemplate * templ)
1204 {
1205   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1206   g_return_if_fail (GST_IS_PAD_TEMPLATE (templ));
1207
1208   /* FIXME 0.11: allow replacing the pad templates by
1209    * calling this with the same name as an already existing pad
1210    * template. For this we _must_ _not_ ref the added pad template
1211    * a second time and _must_ document that this function takes
1212    * ownership of the pad template. Otherwise we will leak pad templates
1213    * or the caller unref's the pad template and it disappears */
1214   /* avoid registering pad templates with the same name */
1215   g_return_if_fail (gst_element_class_get_pad_template (klass,
1216           templ->name_template) == NULL);
1217
1218   klass->padtemplates = g_list_append (klass->padtemplates,
1219       gst_object_ref (templ));
1220   klass->numpadtemplates++;
1221 }
1222
1223 /**
1224  * gst_element_class_set_details:
1225  * @klass: class to set details for
1226  * @details: details to set
1227  *
1228  * Sets the detailed information for a #GstElementClass.
1229  * <note>This function is for use in _base_init functions only.</note>
1230  *
1231  * The @details are copied.
1232  */
1233 void
1234 gst_element_class_set_details (GstElementClass * klass,
1235     const GstElementDetails * details)
1236 {
1237   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1238   g_return_if_fail (GST_IS_ELEMENT_DETAILS (details));
1239
1240   __gst_element_details_copy (&klass->details, details);
1241 }
1242
1243 /**
1244  * gst_element_class_set_details_simple:
1245  * @klass: class to set details for
1246  * @longname: The long English name of the element. E.g. "File Sink"
1247  * @classification: String describing the type of element, as an unordered list
1248  * separated with slashes ('/'). See draft-klass.txt of the design docs
1249  * for more details and common types. E.g: "Sink/File"
1250  * @description: Sentence describing the purpose of the element. 
1251  * E.g: "Write stream to a file"
1252  * @author: Name and contact details of the author(s). Use \n to separate 
1253  * multiple author details. E.g: "Joe Bloggs &lt;joe.blogs at foo.com&gt;"
1254  *
1255  * Sets the detailed information for a #GstElementClass. Simpler version of 
1256  * gst_element_class_set_details() that generates less linker overhead.
1257  * <note>This function is for use in _base_init functions only.</note>
1258  *
1259  * The detail parameter strings are copied into the #GstElementDetails for
1260  * the element class.
1261  *
1262  * Since: 0.10.14
1263  */
1264 void
1265 gst_element_class_set_details_simple (GstElementClass * klass,
1266     const gchar * longname, const gchar * classification,
1267     const gchar * description, const gchar * author)
1268 {
1269   const GstElementDetails details =
1270       GST_ELEMENT_DETAILS ((gchar *) longname, (gchar *) classification,
1271       (gchar *) description, (gchar *) author);
1272
1273   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1274
1275   __gst_element_details_copy (&klass->details, &details);
1276 }
1277
1278 /**
1279  * gst_element_class_get_pad_template_list:
1280  * @element_class: a #GstElementClass to get pad templates of.
1281  *
1282  * Retrieves a list of the pad templates associated with @element_class. The
1283  * list must not be modified by the calling code.
1284  * <note>If you use this function in the #GInstanceInitFunc of an object class
1285  * that has subclasses, make sure to pass the g_class parameter of the
1286  * #GInstanceInitFunc here.</note>
1287  *
1288  * Returns: the #GList of padtemplates.
1289  */
1290 GList *
1291 gst_element_class_get_pad_template_list (GstElementClass * element_class)
1292 {
1293   g_return_val_if_fail (GST_IS_ELEMENT_CLASS (element_class), NULL);
1294
1295   return element_class->padtemplates;
1296 }
1297
1298 /**
1299  * gst_element_class_get_pad_template:
1300  * @element_class: a #GstElementClass to get the pad template of.
1301  * @name: the name of the #GstPadTemplate to get.
1302  *
1303  * Retrieves a padtemplate from @element_class with the given name.
1304  * <note>If you use this function in the #GInstanceInitFunc of an object class
1305  * that has subclasses, make sure to pass the g_class parameter of the
1306  * #GInstanceInitFunc here.</note>
1307  *
1308  * Returns: the #GstPadTemplate with the given name, or %NULL if none was found.
1309  * No unreferencing is necessary.
1310  */
1311 GstPadTemplate *
1312 gst_element_class_get_pad_template (GstElementClass * element_class,
1313     const gchar * name)
1314 {
1315   GList *padlist;
1316
1317   g_return_val_if_fail (GST_IS_ELEMENT_CLASS (element_class), NULL);
1318   g_return_val_if_fail (name != NULL, NULL);
1319
1320   padlist = gst_element_class_get_pad_template_list (element_class);
1321
1322   while (padlist) {
1323     GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
1324
1325     if (strcmp (padtempl->name_template, name) == 0)
1326       return padtempl;
1327
1328     padlist = g_list_next (padlist);
1329   }
1330
1331   return NULL;
1332 }
1333
1334 static GstPadTemplate *
1335 gst_element_class_get_request_pad_template (GstElementClass * element_class,
1336     const gchar * name)
1337 {
1338   GstPadTemplate *tmpl;
1339
1340   tmpl = gst_element_class_get_pad_template (element_class, name);
1341   if (tmpl != NULL && tmpl->presence == GST_PAD_REQUEST)
1342     return tmpl;
1343
1344   return NULL;
1345 }
1346
1347 /* get a random pad on element of the given direction.
1348  * The pad is random in a sense that it is the first pad that is (optionaly) linked.
1349  */
1350 static GstPad *
1351 gst_element_get_random_pad (GstElement * element, gboolean need_linked,
1352     GstPadDirection dir)
1353 {
1354   GstPad *result = NULL;
1355   GList *pads;
1356
1357   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "getting a random pad");
1358
1359   switch (dir) {
1360     case GST_PAD_SRC:
1361       GST_OBJECT_LOCK (element);
1362       pads = element->srcpads;
1363       break;
1364     case GST_PAD_SINK:
1365       GST_OBJECT_LOCK (element);
1366       pads = element->sinkpads;
1367       break;
1368     default:
1369       goto wrong_direction;
1370   }
1371   for (; pads; pads = g_list_next (pads)) {
1372     GstPad *pad = GST_PAD_CAST (pads->data);
1373
1374     GST_OBJECT_LOCK (pad);
1375     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "checking pad %s:%s",
1376         GST_DEBUG_PAD_NAME (pad));
1377
1378     if (need_linked && !GST_PAD_IS_LINKED (pad)) {
1379       /* if we require a linked pad, and it is not linked, continue the
1380        * search */
1381       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is not linked",
1382           GST_DEBUG_PAD_NAME (pad));
1383       GST_OBJECT_UNLOCK (pad);
1384       continue;
1385     } else {
1386       /* found a pad, stop search */
1387       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "found pad %s:%s",
1388           GST_DEBUG_PAD_NAME (pad));
1389       GST_OBJECT_UNLOCK (pad);
1390       result = pad;
1391       break;
1392     }
1393   }
1394   if (result)
1395     gst_object_ref (result);
1396
1397   GST_OBJECT_UNLOCK (element);
1398
1399   return result;
1400
1401   /* ERROR handling */
1402 wrong_direction:
1403   {
1404     g_warning ("unknown pad direction %d", dir);
1405     return NULL;
1406   }
1407 }
1408
1409 static gboolean
1410 gst_element_default_send_event (GstElement * element, GstEvent * event)
1411 {
1412   gboolean result = FALSE;
1413   GstPad *pad;
1414
1415   pad = GST_EVENT_IS_DOWNSTREAM (event) ?
1416       gst_element_get_random_pad (element, TRUE, GST_PAD_SRC) :
1417       gst_element_get_random_pad (element, TRUE, GST_PAD_SINK);
1418
1419   if (pad) {
1420     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1421         "pushing %s event to random %s pad %s:%s",
1422         GST_EVENT_TYPE_NAME (event),
1423         (GST_PAD_DIRECTION (pad) == GST_PAD_SRC ? "src" : "sink"),
1424         GST_DEBUG_PAD_NAME (pad));
1425
1426     result = gst_pad_push_event (pad, event);
1427     gst_object_unref (pad);
1428   } else {
1429     GST_CAT_INFO (GST_CAT_ELEMENT_PADS, "can't send %s event on element %s",
1430         GST_EVENT_TYPE_NAME (event), GST_ELEMENT_NAME (element));
1431   }
1432   return result;
1433 }
1434
1435 /**
1436  * gst_element_send_event:
1437  * @element: a #GstElement to send the event to.
1438  * @event: the #GstEvent to send to the element.
1439  *
1440  * Sends an event to an element. If the element doesn't implement an
1441  * event handler, the event will be pushed on a random linked sink pad for
1442  * upstream events or a random linked source pad for downstream events.
1443  *
1444  * This function takes owership of the provided event so you should
1445  * gst_event_ref() it if you want to reuse the event after this call.
1446  *
1447  * Returns: %TRUE if the event was handled.
1448  *
1449  * MT safe.
1450  */
1451 gboolean
1452 gst_element_send_event (GstElement * element, GstEvent * event)
1453 {
1454   GstElementClass *oclass;
1455   gboolean result = FALSE;
1456
1457   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1458   g_return_val_if_fail (event != NULL, FALSE);
1459
1460   oclass = GST_ELEMENT_GET_CLASS (element);
1461
1462   GST_STATE_LOCK (element);
1463   if (oclass->send_event) {
1464     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "send %s event on element %s",
1465         GST_EVENT_TYPE_NAME (event), GST_ELEMENT_NAME (element));
1466     result = oclass->send_event (element, event);
1467   } else {
1468     result = gst_element_default_send_event (element, event);
1469   }
1470   GST_STATE_UNLOCK (element);
1471
1472   return result;
1473 }
1474
1475 /**
1476  * gst_element_seek:
1477  * @element: a #GstElement to send the event to.
1478  * @rate: The new playback rate
1479  * @format: The format of the seek values
1480  * @flags: The optional seek flags.
1481  * @cur_type: The type and flags for the new current position
1482  * @cur: The value of the new current position
1483  * @stop_type: The type and flags for the new stop position
1484  * @stop: The value of the new stop position
1485  *
1486  * Sends a seek event to an element. See gst_event_new_seek() for the details of
1487  * the parameters. The seek event is sent to the element using
1488  * gst_element_send_event().
1489  *
1490  * Returns: %TRUE if the event was handled.
1491  *
1492  * MT safe.
1493  */
1494 gboolean
1495 gst_element_seek (GstElement * element, gdouble rate, GstFormat format,
1496     GstSeekFlags flags, GstSeekType cur_type, gint64 cur,
1497     GstSeekType stop_type, gint64 stop)
1498 {
1499   GstEvent *event;
1500   gboolean result;
1501
1502   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1503
1504   event =
1505       gst_event_new_seek (rate, format, flags, cur_type, cur, stop_type, stop);
1506   result = gst_element_send_event (element, event);
1507
1508   return result;
1509 }
1510
1511 /**
1512  * gst_element_get_query_types:
1513  * @element: a #GstElement to query
1514  *
1515  * Get an array of query types from the element.
1516  * If the element doesn't implement a query types function,
1517  * the query will be forwarded to the peer of a random linked sink pad.
1518  *
1519  * Returns: An array of #GstQueryType elements that should not
1520  * be freed or modified.
1521  *
1522  * MT safe.
1523  */
1524 const GstQueryType *
1525 gst_element_get_query_types (GstElement * element)
1526 {
1527   GstElementClass *oclass;
1528   const GstQueryType *result = NULL;
1529
1530   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
1531
1532   oclass = GST_ELEMENT_GET_CLASS (element);
1533
1534   if (oclass->get_query_types) {
1535     result = oclass->get_query_types (element);
1536   } else {
1537     GstPad *pad = gst_element_get_random_pad (element, TRUE, GST_PAD_SINK);
1538
1539     if (pad) {
1540       GstPad *peer = gst_pad_get_peer (pad);
1541
1542       if (peer) {
1543         result = gst_pad_get_query_types (peer);
1544
1545         gst_object_unref (peer);
1546       }
1547       gst_object_unref (pad);
1548     }
1549   }
1550   return result;
1551 }
1552
1553 static gboolean
1554 gst_element_default_query (GstElement * element, GstQuery * query)
1555 {
1556   gboolean result = FALSE;
1557   GstPad *pad;
1558
1559   pad = gst_element_get_random_pad (element, FALSE, GST_PAD_SRC);
1560   if (pad) {
1561     result = gst_pad_query (pad, query);
1562
1563     gst_object_unref (pad);
1564   } else {
1565     pad = gst_element_get_random_pad (element, TRUE, GST_PAD_SINK);
1566     if (pad) {
1567       GstPad *peer = gst_pad_get_peer (pad);
1568
1569       if (peer) {
1570         result = gst_pad_query (peer, query);
1571
1572         gst_object_unref (peer);
1573       }
1574       gst_object_unref (pad);
1575     }
1576   }
1577   return result;
1578 }
1579
1580 /**
1581  * gst_element_query:
1582  * @element: a #GstElement to perform the query on.
1583  * @query: the #GstQuery.
1584  *
1585  * Performs a query on the given element.
1586  *
1587  * For elements that don't implement a query handler, this function
1588  * forwards the query to a random srcpad or to the peer of a
1589  * random linked sinkpad of this element.
1590  *
1591  * Returns: TRUE if the query could be performed.
1592  *
1593  * MT safe.
1594  */
1595 gboolean
1596 gst_element_query (GstElement * element, GstQuery * query)
1597 {
1598   GstElementClass *oclass;
1599   gboolean result = FALSE;
1600
1601   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1602   g_return_val_if_fail (query != NULL, FALSE);
1603
1604   oclass = GST_ELEMENT_GET_CLASS (element);
1605
1606   if (oclass->query) {
1607     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "send query on element %s",
1608         GST_ELEMENT_NAME (element));
1609     result = oclass->query (element, query);
1610   } else {
1611     result = gst_element_default_query (element, query);
1612   }
1613   return result;
1614 }
1615
1616 /**
1617  * gst_element_post_message:
1618  * @element: a #GstElement posting the message
1619  * @message: a #GstMessage to post
1620  *
1621  * Post a message on the element's #GstBus. This function takes ownership of the
1622  * message; if you want to access the message after this call, you should add an
1623  * additional reference before calling.
1624  *
1625  * Returns: %TRUE if the message was successfully posted. The function returns
1626  * %FALSE if the element did not have a bus.
1627  *
1628  * MT safe.
1629  */
1630 gboolean
1631 gst_element_post_message (GstElement * element, GstMessage * message)
1632 {
1633   GstBus *bus;
1634   gboolean result = FALSE;
1635
1636   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1637   g_return_val_if_fail (message != NULL, FALSE);
1638
1639   GST_OBJECT_LOCK (element);
1640   bus = element->bus;
1641
1642   if (G_UNLIKELY (bus == NULL))
1643     goto no_bus;
1644
1645   gst_object_ref (bus);
1646   GST_OBJECT_UNLOCK (element);
1647
1648   /* we release the element lock when posting the message so that any
1649    * (synchronous) message handlers can operate on the element */
1650   result = gst_bus_post (bus, message);
1651   gst_object_unref (bus);
1652
1653   return result;
1654
1655   /* ERRORS */
1656 no_bus:
1657   {
1658     GST_CAT_DEBUG_OBJECT (GST_CAT_MESSAGE, element,
1659         "not posting message %p: no bus", message);
1660     GST_OBJECT_UNLOCK (element);
1661     gst_message_unref (message);
1662     return FALSE;
1663   }
1664 }
1665
1666 /**
1667  * _gst_element_error_printf:
1668  * @format: the printf-like format to use, or %NULL
1669  *
1670  * This function is only used internally by the gst_element_error() macro.
1671  *
1672  * Returns: a newly allocated string, or %NULL if the format was %NULL or ""
1673  *
1674  * MT safe.
1675  */
1676 gchar *
1677 _gst_element_error_printf (const gchar * format, ...)
1678 {
1679   va_list args;
1680   gchar *buffer;
1681
1682   if (format == NULL)
1683     return NULL;
1684   if (format[0] == 0)
1685     return NULL;
1686
1687   va_start (args, format);
1688   buffer = g_strdup_vprintf (format, args);
1689   va_end (args);
1690   return buffer;
1691 }
1692
1693 /**
1694  * gst_element_message_full:
1695  * @element:  a #GstElement to send message from
1696  * @type:     the #GstMessageType
1697  * @domain:   the GStreamer GError domain this message belongs to
1698  * @code:     the GError code belonging to the domain
1699  * @text:     an allocated text string to be used as a replacement for the
1700  *            default message connected to code, or %NULL
1701  * @debug:    an allocated debug message to be used as a replacement for the
1702  *            default debugging information, or %NULL
1703  * @file:     the source code file where the error was generated
1704  * @function: the source code function where the error was generated
1705  * @line:     the source code line where the error was generated
1706  *
1707  * Post an error, warning or info message on the bus from inside an element.
1708  *
1709  * @type must be of #GST_MESSAGE_ERROR, #GST_MESSAGE_WARNING or
1710  * #GST_MESSAGE_INFO.
1711  *
1712  * MT safe.
1713  */
1714 void gst_element_message_full
1715     (GstElement * element, GstMessageType type,
1716     GQuark domain, gint code, gchar * text,
1717     gchar * debug, const gchar * file, const gchar * function, gint line)
1718 {
1719   GError *gerror = NULL;
1720   gchar *name;
1721   gchar *sent_text;
1722   gchar *sent_debug;
1723   gboolean has_debug = TRUE;
1724   GstMessage *message = NULL;
1725
1726   /* checks */
1727   GST_CAT_DEBUG_OBJECT (GST_CAT_MESSAGE, element, "start");
1728   g_return_if_fail (GST_IS_ELEMENT (element));
1729   g_return_if_fail ((type == GST_MESSAGE_ERROR) ||
1730       (type == GST_MESSAGE_WARNING) || (type == GST_MESSAGE_INFO));
1731
1732   /* check if we send the given text or the default error text */
1733   if ((text == NULL) || (text[0] == 0)) {
1734     /* text could have come from g_strdup_printf (""); */
1735     g_free (text);
1736     sent_text = gst_error_get_message (domain, code);
1737   } else
1738     sent_text = text;
1739
1740   /* construct a sent_debug with extra information from source */
1741   if ((debug == NULL) || (debug[0] == 0)) {
1742     /* debug could have come from g_strdup_printf (""); */
1743     has_debug = FALSE;
1744   }
1745
1746   name = gst_object_get_path_string (GST_OBJECT_CAST (element));
1747   if (has_debug)
1748     sent_debug = g_strdup_printf ("%s(%d): %s (): %s:\n%s",
1749         file, line, function, name, debug);
1750   else
1751     sent_debug = g_strdup_printf ("%s(%d): %s (): %s",
1752         file, line, function, name);
1753   g_free (name);
1754   g_free (debug);
1755
1756   /* create gerror and post message */
1757   GST_CAT_INFO_OBJECT (GST_CAT_ERROR_SYSTEM, element, "posting message: %s",
1758       sent_text);
1759   gerror = g_error_new_literal (domain, code, sent_text);
1760
1761   switch (type) {
1762     case GST_MESSAGE_ERROR:
1763       message =
1764           gst_message_new_error (GST_OBJECT_CAST (element), gerror, sent_debug);
1765       break;
1766     case GST_MESSAGE_WARNING:
1767       message = gst_message_new_warning (GST_OBJECT_CAST (element), gerror,
1768           sent_debug);
1769       break;
1770     case GST_MESSAGE_INFO:
1771       message = gst_message_new_info (GST_OBJECT_CAST (element), gerror,
1772           sent_debug);
1773       break;
1774     default:
1775       g_assert_not_reached ();
1776       break;
1777   }
1778   gst_element_post_message (element, message);
1779
1780   GST_CAT_INFO_OBJECT (GST_CAT_ERROR_SYSTEM, element, "posted %s message: %s",
1781       (type == GST_MESSAGE_ERROR ? "error" : "warning"), sent_text);
1782
1783   /* cleanup */
1784   g_error_free (gerror);
1785   g_free (sent_debug);
1786   g_free (sent_text);
1787 }
1788
1789 /**
1790  * gst_element_is_locked_state:
1791  * @element: a #GstElement.
1792  *
1793  * Checks if the state of an element is locked.
1794  * If the state of an element is locked, state changes of the parent don't
1795  * affect the element.
1796  * This way you can leave currently unused elements inside bins. Just lock their
1797  * state before changing the state from #GST_STATE_NULL.
1798  *
1799  * MT safe.
1800  *
1801  * Returns: TRUE, if the element's state is locked.
1802  */
1803 gboolean
1804 gst_element_is_locked_state (GstElement * element)
1805 {
1806   gboolean result;
1807
1808   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1809
1810   GST_OBJECT_LOCK (element);
1811   result = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_LOCKED_STATE);
1812   GST_OBJECT_UNLOCK (element);
1813
1814   return result;
1815 }
1816
1817 /**
1818  * gst_element_set_locked_state:
1819  * @element: a #GstElement
1820  * @locked_state: TRUE to lock the element's state
1821  *
1822  * Locks the state of an element, so state changes of the parent don't affect
1823  * this element anymore.
1824  *
1825  * MT safe.
1826  *
1827  * Returns: TRUE if the state was changed, FALSE if bad parameters were given
1828  * or the elements state-locking needed no change.
1829  */
1830 gboolean
1831 gst_element_set_locked_state (GstElement * element, gboolean locked_state)
1832 {
1833   gboolean old;
1834
1835   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1836
1837   GST_OBJECT_LOCK (element);
1838   old = GST_OBJECT_FLAG_IS_SET (element, GST_ELEMENT_LOCKED_STATE);
1839
1840   if (G_UNLIKELY (old == locked_state))
1841     goto was_ok;
1842
1843   if (locked_state) {
1844     GST_CAT_DEBUG (GST_CAT_STATES, "locking state of element %s",
1845         GST_ELEMENT_NAME (element));
1846     GST_OBJECT_FLAG_SET (element, GST_ELEMENT_LOCKED_STATE);
1847   } else {
1848     GST_CAT_DEBUG (GST_CAT_STATES, "unlocking state of element %s",
1849         GST_ELEMENT_NAME (element));
1850     GST_OBJECT_FLAG_UNSET (element, GST_ELEMENT_LOCKED_STATE);
1851   }
1852   GST_OBJECT_UNLOCK (element);
1853
1854   return TRUE;
1855
1856 was_ok:
1857   {
1858     GST_CAT_DEBUG (GST_CAT_STATES, "elements %s was already in locked state %d",
1859         GST_ELEMENT_NAME (element), old);
1860     GST_OBJECT_UNLOCK (element);
1861
1862     return FALSE;
1863   }
1864 }
1865
1866 /**
1867  * gst_element_sync_state_with_parent:
1868  * @element: a #GstElement.
1869  *
1870  * Tries to change the state of the element to the same as its parent.
1871  * If this function returns FALSE, the state of element is undefined.
1872  *
1873  * Returns: TRUE, if the element's state could be synced to the parent's state.
1874  *
1875  * MT safe.
1876  */
1877 gboolean
1878 gst_element_sync_state_with_parent (GstElement * element)
1879 {
1880   GstElement *parent;
1881   GstState target;
1882   GstStateChangeReturn ret;
1883
1884   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1885
1886   if ((parent = GST_ELEMENT_CAST (gst_element_get_parent (element)))) {
1887     GstState parent_current, parent_pending;
1888
1889     GST_OBJECT_LOCK (parent);
1890     parent_current = GST_STATE (parent);
1891     parent_pending = GST_STATE_PENDING (parent);
1892     GST_OBJECT_UNLOCK (parent);
1893
1894     /* set to pending if there is one, else we set it to the current state of
1895      * the parent */
1896     if (parent_pending != GST_STATE_VOID_PENDING)
1897       target = parent_pending;
1898     else
1899       target = parent_current;
1900
1901     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
1902         "syncing state (%s) to parent %s %s (%s, %s)",
1903         gst_element_state_get_name (GST_STATE (element)),
1904         GST_ELEMENT_NAME (parent), gst_element_state_get_name (target),
1905         gst_element_state_get_name (parent_current),
1906         gst_element_state_get_name (parent_pending));
1907
1908     ret = gst_element_set_state (element, target);
1909     if (ret == GST_STATE_CHANGE_FAILURE)
1910       goto failed;
1911
1912     gst_object_unref (parent);
1913
1914     return TRUE;
1915   } else {
1916     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "element has no parent");
1917   }
1918   return FALSE;
1919
1920   /* ERROR */
1921 failed:
1922   {
1923     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
1924         "syncing state failed (%s)",
1925         gst_element_state_change_return_get_name (ret));
1926     gst_object_unref (parent);
1927     return FALSE;
1928   }
1929 }
1930
1931 /* MT safe */
1932 static GstStateChangeReturn
1933 gst_element_get_state_func (GstElement * element,
1934     GstState * state, GstState * pending, GstClockTime timeout)
1935 {
1936   GstStateChangeReturn ret = GST_STATE_CHANGE_FAILURE;
1937   GstState old_pending;
1938
1939   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "getting state, timeout %"
1940       GST_TIME_FORMAT, GST_TIME_ARGS (timeout));
1941
1942   GST_OBJECT_LOCK (element);
1943   ret = GST_STATE_RETURN (element);
1944   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "RETURN is %s",
1945       gst_element_state_change_return_get_name (ret));
1946
1947   /* we got an error, report immediatly */
1948   if (ret == GST_STATE_CHANGE_FAILURE)
1949     goto done;
1950
1951   /* we got no_preroll, report immediatly */
1952   if (ret == GST_STATE_CHANGE_NO_PREROLL)
1953     goto done;
1954
1955   /* no need to wait async if we are not async */
1956   if (ret != GST_STATE_CHANGE_ASYNC)
1957     goto done;
1958
1959   old_pending = GST_STATE_PENDING (element);
1960   if (old_pending != GST_STATE_VOID_PENDING) {
1961     GTimeVal *timeval, abstimeout;
1962     guint32 cookie;
1963
1964     if (timeout != GST_CLOCK_TIME_NONE) {
1965       glong add = timeout / 1000;
1966
1967       if (add == 0)
1968         goto done;
1969
1970       /* make timeout absolute */
1971       g_get_current_time (&abstimeout);
1972       g_time_val_add (&abstimeout, add);
1973       timeval = &abstimeout;
1974     } else {
1975       timeval = NULL;
1976     }
1977     /* get cookie to detect state changes during waiting */
1978     cookie = element->state_cookie;
1979
1980     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
1981         "waiting for element to commit state");
1982
1983     /* we have a pending state change, wait for it to complete */
1984     if (!GST_STATE_TIMED_WAIT (element, timeval)) {
1985       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "timed out");
1986       /* timeout triggered */
1987       ret = GST_STATE_CHANGE_ASYNC;
1988     } else {
1989       if (cookie != element->state_cookie)
1990         goto interrupted;
1991
1992       /* could be success or failure */
1993       if (old_pending == GST_STATE (element)) {
1994         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "got success");
1995         ret = GST_STATE_CHANGE_SUCCESS;
1996       } else {
1997         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "got failure");
1998         ret = GST_STATE_CHANGE_FAILURE;
1999       }
2000     }
2001     /* if nothing is pending anymore we can return SUCCESS */
2002     if (GST_STATE_PENDING (element) == GST_STATE_VOID_PENDING) {
2003       GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "nothing pending");
2004       ret = GST_STATE_CHANGE_SUCCESS;
2005     }
2006   }
2007
2008 done:
2009   if (state)
2010     *state = GST_STATE (element);
2011   if (pending)
2012     *pending = GST_STATE_PENDING (element);
2013
2014   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2015       "state current: %s, pending: %s, result: %s",
2016       gst_element_state_get_name (GST_STATE (element)),
2017       gst_element_state_get_name (GST_STATE_PENDING (element)),
2018       gst_element_state_change_return_get_name (ret));
2019   GST_OBJECT_UNLOCK (element);
2020
2021   return ret;
2022
2023 interrupted:
2024   {
2025     if (state)
2026       *state = GST_STATE_VOID_PENDING;
2027     if (pending)
2028       *pending = GST_STATE_VOID_PENDING;
2029
2030     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "interruped");
2031
2032     GST_OBJECT_UNLOCK (element);
2033
2034     return GST_STATE_CHANGE_FAILURE;
2035   }
2036 }
2037
2038 /**
2039  * gst_element_get_state:
2040  * @element: a #GstElement to get the state of.
2041  * @state: a pointer to #GstState to hold the state. Can be %NULL.
2042  * @pending: a pointer to #GstState to hold the pending state.
2043  *           Can be %NULL.
2044  * @timeout: a #GstClockTime to specify the timeout for an async
2045  *           state change or %GST_CLOCK_TIME_NONE for infinite timeout.
2046  *
2047  * Gets the state of the element.
2048  *
2049  * For elements that performed an ASYNC state change, as reported by
2050  * gst_element_set_state(), this function will block up to the
2051  * specified timeout value for the state change to complete.
2052  * If the element completes the state change or goes into
2053  * an error, this function returns immediately with a return value of
2054  * %GST_STATE_CHANGE_SUCCESS or %GST_STATE_CHANGE_FAILURE respectively.
2055  *
2056  * For elements that did not return %GST_STATE_CHANGE_ASYNC, this function
2057  * returns the current and pending state immediately.
2058  *
2059  * This function returns %GST_STATE_CHANGE_NO_PREROLL if the element
2060  * successfully changed its state but is not able to provide data yet.
2061  * This mostly happens for live sources that only produce data in the PLAYING
2062  * state. While the state change return is equivalent to
2063  * %GST_STATE_CHANGE_SUCCESS, it is returned to the application to signal that
2064  * some sink elements might not be able to complete their state change because
2065  * an element is not producing data to complete the preroll. When setting the
2066  * element to playing, the preroll will complete and playback will start.
2067  *
2068  * Returns: %GST_STATE_CHANGE_SUCCESS if the element has no more pending state
2069  *          and the last state change succeeded, %GST_STATE_CHANGE_ASYNC if the
2070  *          element is still performing a state change or
2071  *          %GST_STATE_CHANGE_FAILURE if the last state change failed.
2072  *
2073  * MT safe.
2074  */
2075 GstStateChangeReturn
2076 gst_element_get_state (GstElement * element,
2077     GstState * state, GstState * pending, GstClockTime timeout)
2078 {
2079   GstElementClass *oclass;
2080   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
2081
2082   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2083
2084   oclass = GST_ELEMENT_GET_CLASS (element);
2085
2086   if (oclass->get_state)
2087     result = (oclass->get_state) (element, state, pending, timeout);
2088
2089   return result;
2090 }
2091
2092 /**
2093  * gst_element_abort_state:
2094  * @element: a #GstElement to abort the state of.
2095  *
2096  * Abort the state change of the element. This function is used
2097  * by elements that do asynchronous state changes and find out
2098  * something is wrong.
2099  *
2100  * This function should be called with the STATE_LOCK held.
2101  *
2102  * MT safe.
2103  */
2104 void
2105 gst_element_abort_state (GstElement * element)
2106 {
2107   GstState pending;
2108
2109 #ifndef GST_DISABLE_GST_DEBUG
2110   GstState old_state;
2111 #endif
2112
2113   g_return_if_fail (GST_IS_ELEMENT (element));
2114
2115   GST_OBJECT_LOCK (element);
2116   pending = GST_STATE_PENDING (element);
2117
2118   if (pending == GST_STATE_VOID_PENDING ||
2119       GST_STATE_RETURN (element) == GST_STATE_CHANGE_FAILURE)
2120     goto nothing_aborted;
2121
2122 #ifndef GST_DISABLE_GST_DEBUG
2123   old_state = GST_STATE (element);
2124
2125   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2126       "aborting state from %s to %s", gst_element_state_get_name (old_state),
2127       gst_element_state_get_name (pending));
2128 #endif
2129
2130   /* flag error */
2131   GST_STATE_RETURN (element) = GST_STATE_CHANGE_FAILURE;
2132
2133   GST_STATE_BROADCAST (element);
2134   GST_OBJECT_UNLOCK (element);
2135
2136   return;
2137
2138 nothing_aborted:
2139   {
2140     GST_OBJECT_UNLOCK (element);
2141     return;
2142   }
2143 }
2144
2145 /**
2146  * gst_element_continue_state:
2147  * @element: a #GstElement to continue the state change of.
2148  * @ret: The previous state return value
2149  *
2150  * Commit the state change of the element and proceed to the next
2151  * pending state if any. This function is used
2152  * by elements that do asynchronous state changes.
2153  * The core will normally call this method automatically when an
2154  * element returned %GST_STATE_CHANGE_SUCCESS from the state change function.
2155  *
2156  * If after calling this method the element still has not reached
2157  * the pending state, the next state change is performed.
2158  *
2159  * This method is used internally and should normally not be called by plugins
2160  * or applications.
2161  *
2162  * Returns: The result of the commit state change.
2163  *
2164  * MT safe.
2165  */
2166 GstStateChangeReturn
2167 gst_element_continue_state (GstElement * element, GstStateChangeReturn ret)
2168 {
2169   GstStateChangeReturn old_ret;
2170   GstState old_state, old_next;
2171   GstState current, next, pending;
2172   GstMessage *message;
2173   GstStateChange transition;
2174
2175   GST_OBJECT_LOCK (element);
2176   old_ret = GST_STATE_RETURN (element);
2177   GST_STATE_RETURN (element) = ret;
2178   pending = GST_STATE_PENDING (element);
2179
2180   /* check if there is something to commit */
2181   if (pending == GST_STATE_VOID_PENDING)
2182     goto nothing_pending;
2183
2184   old_state = GST_STATE (element);
2185   /* this is the state we should go to next */
2186   old_next = GST_STATE_NEXT (element);
2187   /* update current state */
2188   current = GST_STATE (element) = old_next;
2189
2190   /* see if we reached the final state */
2191   if (pending == current)
2192     goto complete;
2193
2194   next = GST_STATE_GET_NEXT (current, pending);
2195   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
2196
2197   GST_STATE_NEXT (element) = next;
2198   /* mark busy */
2199   GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2200   GST_OBJECT_UNLOCK (element);
2201
2202   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2203       "committing state from %s to %s, pending %s, next %s",
2204       gst_element_state_get_name (old_state),
2205       gst_element_state_get_name (old_next),
2206       gst_element_state_get_name (pending), gst_element_state_get_name (next));
2207
2208   message = gst_message_new_state_changed (GST_OBJECT_CAST (element),
2209       old_state, old_next, pending);
2210   gst_element_post_message (element, message);
2211
2212   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2213       "continue state change %s to %s, final %s",
2214       gst_element_state_get_name (current),
2215       gst_element_state_get_name (next), gst_element_state_get_name (pending));
2216
2217   ret = gst_element_change_state (element, transition);
2218
2219   return ret;
2220
2221 nothing_pending:
2222   {
2223     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "nothing pending");
2224     GST_OBJECT_UNLOCK (element);
2225     return ret;
2226   }
2227 complete:
2228   {
2229     GST_STATE_PENDING (element) = GST_STATE_VOID_PENDING;
2230     GST_STATE_NEXT (element) = GST_STATE_VOID_PENDING;
2231
2232     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2233         "completed state change to %s", gst_element_state_get_name (pending));
2234     GST_OBJECT_UNLOCK (element);
2235
2236     /* don't post silly messages with the same state. This can happen
2237      * when an element state is changed to what it already was. For bins
2238      * this can be the result of a lost state, which we check with the
2239      * previous return value.
2240      * We do signal the cond though as a _get_state() might be blocking
2241      * on it. */
2242     if (old_state != old_next || old_ret == GST_STATE_CHANGE_ASYNC) {
2243       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2244           "posting state-changed %s to %s",
2245           gst_element_state_get_name (old_state),
2246           gst_element_state_get_name (old_next));
2247       message =
2248           gst_message_new_state_changed (GST_OBJECT_CAST (element), old_state,
2249           old_next, GST_STATE_VOID_PENDING);
2250       gst_element_post_message (element, message);
2251     }
2252
2253     GST_STATE_BROADCAST (element);
2254
2255     return ret;
2256   }
2257 }
2258
2259 /**
2260  * gst_element_lost_state_full:
2261  * @element: a #GstElement the state is lost of
2262  * @new_base_time: if a new base time should be distributed
2263  *
2264  * Brings the element to the lost state. The current state of the
2265  * element is copied to the pending state so that any call to
2266  * gst_element_get_state() will return %GST_STATE_CHANGE_ASYNC.
2267  *
2268  * An ASYNC_START message is posted with indication to distribute a new
2269  * base_time to the element when @new_base_time is %TRUE.
2270  * If the element was PLAYING, it will go to PAUSED. The element
2271  * will be restored to its PLAYING state by the parent pipeline when it
2272  * prerolls again.
2273  *
2274  * This is mostly used for elements that lost their preroll buffer
2275  * in the %GST_STATE_PAUSED or %GST_STATE_PLAYING state after a flush,
2276  * they will go to their pending state again when a new preroll buffer is
2277  * queued. This function can only be called when the element is currently
2278  * not in error or an async state change.
2279  *
2280  * This function is used internally and should normally not be called from
2281  * plugins or applications.
2282  *
2283  * MT safe.
2284  *
2285  * Since: 0.10.24
2286  */
2287 void
2288 gst_element_lost_state_full (GstElement * element, gboolean new_base_time)
2289 {
2290   GstState old_state, new_state;
2291   GstMessage *message;
2292
2293   g_return_if_fail (GST_IS_ELEMENT (element));
2294
2295   GST_OBJECT_LOCK (element);
2296   if (GST_STATE_RETURN (element) == GST_STATE_CHANGE_FAILURE)
2297     goto nothing_lost;
2298
2299   if (GST_STATE_PENDING (element) != GST_STATE_VOID_PENDING)
2300     goto only_async_start;
2301
2302   old_state = GST_STATE (element);
2303
2304   /* when we were PLAYING, the new state is PAUSED. We will also not
2305    * automatically go to PLAYING but let the parent bin(s) set us to PLAYING
2306    * when we preroll. */
2307   if (old_state > GST_STATE_PAUSED)
2308     new_state = GST_STATE_PAUSED;
2309   else
2310     new_state = old_state;
2311
2312   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2313       "lost state of %s to %s", gst_element_state_get_name (old_state),
2314       gst_element_state_get_name (new_state));
2315
2316   GST_STATE (element) = new_state;
2317   GST_STATE_NEXT (element) = new_state;
2318   GST_STATE_PENDING (element) = new_state;
2319   GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2320   if (new_base_time)
2321     GST_ELEMENT_START_TIME (element) = 0;
2322   GST_OBJECT_UNLOCK (element);
2323
2324   message = gst_message_new_state_changed (GST_OBJECT_CAST (element),
2325       new_state, new_state, new_state);
2326   gst_element_post_message (element, message);
2327
2328   message =
2329       gst_message_new_async_start (GST_OBJECT_CAST (element), new_base_time);
2330   gst_element_post_message (element, message);
2331
2332   return;
2333
2334 nothing_lost:
2335   {
2336     GST_OBJECT_UNLOCK (element);
2337     return;
2338   }
2339 only_async_start:
2340   {
2341     GST_OBJECT_UNLOCK (element);
2342
2343     message = gst_message_new_async_start (GST_OBJECT_CAST (element), TRUE);
2344     gst_element_post_message (element, message);
2345     return;
2346   }
2347 }
2348
2349 /**
2350  * gst_element_lost_state:
2351  * @element: a #GstElement the state is lost of
2352  *
2353  * Brings the element to the lost state. This function calls
2354  * gst_element_lost_state_full() with the new_base_time set to %TRUE.
2355  *
2356  * This function is used internally and should normally not be called from
2357  * plugins or applications.
2358  *
2359  * MT safe.
2360  */
2361 void
2362 gst_element_lost_state (GstElement * element)
2363 {
2364   gst_element_lost_state_full (element, TRUE);
2365 }
2366
2367 /**
2368  * gst_element_set_state:
2369  * @element: a #GstElement to change state of.
2370  * @state: the element's new #GstState.
2371  *
2372  * Sets the state of the element. This function will try to set the
2373  * requested state by going through all the intermediary states and calling
2374  * the class's state change function for each.
2375  *
2376  * This function can return #GST_STATE_CHANGE_ASYNC, in which case the
2377  * element will perform the remainder of the state change asynchronously in
2378  * another thread.
2379  * An application can use gst_element_get_state() to wait for the completion
2380  * of the state change or it can wait for a state change message on the bus.
2381  *
2382  * State changes to %GST_STATE_READY or %GST_STATE_NULL never return
2383  * #GST_STATE_CHANGE_ASYNC.
2384  *
2385  * Returns: Result of the state change using #GstStateChangeReturn.
2386  *
2387  * MT safe.
2388  */
2389 GstStateChangeReturn
2390 gst_element_set_state (GstElement * element, GstState state)
2391 {
2392   GstElementClass *oclass;
2393   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
2394
2395   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2396
2397   oclass = GST_ELEMENT_GET_CLASS (element);
2398
2399   if (oclass->set_state)
2400     result = (oclass->set_state) (element, state);
2401
2402   return result;
2403 }
2404
2405 /*
2406  * default set state function, calculates the next state based
2407  * on current state and calls the change_state function
2408  */
2409 static GstStateChangeReturn
2410 gst_element_set_state_func (GstElement * element, GstState state)
2411 {
2412   GstState current, next, old_pending;
2413   GstStateChangeReturn ret;
2414   GstStateChange transition;
2415   GstStateChangeReturn old_ret;
2416
2417   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2418
2419   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "set_state to %s",
2420       gst_element_state_get_name (state));
2421
2422   /* state lock is taken to protect the set_state() and get_state()
2423    * procedures, it does not lock any variables. */
2424   GST_STATE_LOCK (element);
2425
2426   /* now calculate how to get to the new state */
2427   GST_OBJECT_LOCK (element);
2428   old_ret = GST_STATE_RETURN (element);
2429   /* previous state change returned an error, remove all pending
2430    * and next states */
2431   if (old_ret == GST_STATE_CHANGE_FAILURE) {
2432     GST_STATE_NEXT (element) = GST_STATE_VOID_PENDING;
2433     GST_STATE_PENDING (element) = GST_STATE_VOID_PENDING;
2434     GST_STATE_RETURN (element) = GST_STATE_CHANGE_SUCCESS;
2435   }
2436
2437   current = GST_STATE (element);
2438   next = GST_STATE_NEXT (element);
2439   old_pending = GST_STATE_PENDING (element);
2440
2441   /* this is the (new) state we should go to. TARGET is the last state we set on
2442    * the element. */
2443   if (state != GST_STATE_TARGET (element)) {
2444     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2445         "setting target state to %s", gst_element_state_get_name (state));
2446     GST_STATE_TARGET (element) = state;
2447     /* increment state cookie so that we can track each state change. We only do
2448      * this if this is actually a new state change. */
2449     element->state_cookie++;
2450   }
2451   GST_STATE_PENDING (element) = state;
2452
2453   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2454       "current %s, old_pending %s, next %s, old return %s",
2455       gst_element_state_get_name (current),
2456       gst_element_state_get_name (old_pending),
2457       gst_element_state_get_name (next),
2458       gst_element_state_change_return_get_name (old_ret));
2459
2460   /* if the element was busy doing a state change, we just update the
2461    * target state, it'll get to it async then. */
2462   if (old_pending != GST_STATE_VOID_PENDING) {
2463     /* upwards state change will happen ASYNC */
2464     if (old_pending <= state)
2465       goto was_busy;
2466     /* element is going to this state already */
2467     else if (next == state)
2468       goto was_busy;
2469     /* element was performing an ASYNC upward state change and
2470      * we request to go downward again. Start from the next pending
2471      * state then. */
2472     else if (next > state
2473         && GST_STATE_RETURN (element) == GST_STATE_CHANGE_ASYNC) {
2474       current = next;
2475     }
2476   }
2477   next = GST_STATE_GET_NEXT (current, state);
2478   /* now we store the next state */
2479   GST_STATE_NEXT (element) = next;
2480   /* mark busy, we need to check that there is actually a state change
2481    * to be done else we could accidentally override SUCCESS/NO_PREROLL and
2482    * the default element change_state function has no way to know what the
2483    * old value was... could consider this a FIXME...*/
2484   if (current != next)
2485     GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2486
2487   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
2488
2489   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2490       "%s: setting state from %s to %s",
2491       (next != state ? "intermediate" : "final"),
2492       gst_element_state_get_name (current), gst_element_state_get_name (next));
2493
2494   /* now signal any waiters, they will error since the cookie was incremented */
2495   GST_STATE_BROADCAST (element);
2496
2497   GST_OBJECT_UNLOCK (element);
2498
2499   ret = gst_element_change_state (element, transition);
2500
2501   GST_STATE_UNLOCK (element);
2502
2503   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "returned %s",
2504       gst_element_state_change_return_get_name (ret));
2505
2506   return ret;
2507
2508 was_busy:
2509   {
2510     GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2511     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2512         "element was busy with async state change");
2513     GST_OBJECT_UNLOCK (element);
2514
2515     GST_STATE_UNLOCK (element);
2516
2517     return GST_STATE_CHANGE_ASYNC;
2518   }
2519 }
2520
2521 /**
2522  * gst_element_change_state:
2523  * @element: a #GstElement
2524  * @transition: the requested transition
2525  *
2526  * Perform @transition on @element.
2527  *
2528  * This function must be called with STATE_LOCK held and is mainly used
2529  * internally.
2530  *
2531  * Returns: the #GstStateChangeReturn of the state transition.
2532  */
2533 GstStateChangeReturn
2534 gst_element_change_state (GstElement * element, GstStateChange transition)
2535 {
2536   GstElementClass *oclass;
2537   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2538
2539   oclass = GST_ELEMENT_GET_CLASS (element);
2540
2541   /* call the state change function so it can set the state */
2542   if (oclass->change_state)
2543     ret = (oclass->change_state) (element, transition);
2544   else
2545     ret = GST_STATE_CHANGE_FAILURE;
2546
2547   switch (ret) {
2548     case GST_STATE_CHANGE_FAILURE:
2549       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2550           "have FAILURE change_state return");
2551       /* state change failure */
2552       gst_element_abort_state (element);
2553       break;
2554     case GST_STATE_CHANGE_ASYNC:
2555     {
2556       GstState target;
2557
2558       GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2559           "element will change state ASYNC");
2560
2561       target = GST_STATE_TARGET (element);
2562
2563       if (target > GST_STATE_READY)
2564         goto async;
2565
2566       /* else we just continue the state change downwards */
2567       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2568           "forcing commit state %s <= %s",
2569           gst_element_state_get_name (target),
2570           gst_element_state_get_name (GST_STATE_READY));
2571
2572       ret = gst_element_continue_state (element, GST_STATE_CHANGE_SUCCESS);
2573       break;
2574     }
2575     case GST_STATE_CHANGE_SUCCESS:
2576       GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2577           "element changed state SUCCESS");
2578       /* we can commit the state now which will proceeed to
2579        * the next state */
2580       ret = gst_element_continue_state (element, ret);
2581       /* In null state release the reference to the clock */
2582       if (GST_STATE (element) == GST_STATE_NULL) {
2583         GstClock **clock_p;
2584         GST_OBJECT_LOCK (element);
2585         clock_p = &element->clock;
2586         gst_object_replace ((GstObject **) clock_p, NULL);
2587         GST_OBJECT_UNLOCK (element);
2588       }
2589       break;
2590     case GST_STATE_CHANGE_NO_PREROLL:
2591       GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2592           "element changed state NO_PREROLL");
2593       /* we can commit the state now which will proceeed to
2594        * the next state */
2595       ret = gst_element_continue_state (element, ret);
2596       break;
2597     default:
2598       goto invalid_return;
2599   }
2600
2601   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "exit state change %d", ret);
2602
2603   return ret;
2604
2605 async:
2606   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "exit async state change %d",
2607       ret);
2608
2609   return ret;
2610
2611   /* ERROR */
2612 invalid_return:
2613   {
2614     GST_OBJECT_LOCK (element);
2615     /* somebody added a GST_STATE_ and forgot to do stuff here ! */
2616     g_critical ("%s: unknown return value %d from a state change function",
2617         GST_ELEMENT_NAME (element), ret);
2618
2619     /* we are in error now */
2620     ret = GST_STATE_CHANGE_FAILURE;
2621     GST_STATE_RETURN (element) = ret;
2622     GST_OBJECT_UNLOCK (element);
2623
2624     return ret;
2625   }
2626 }
2627
2628 /* gst_iterator_fold functions for pads_activate
2629  * Note how we don't stop the iterator when we fail an activation. This is
2630  * probably a FIXME since when one pad activation fails, we don't want to
2631  * continue our state change. */
2632 static gboolean
2633 activate_pads (GstPad * pad, GValue * ret, gboolean * active)
2634 {
2635   if (!gst_pad_set_active (pad, *active))
2636     g_value_set_boolean (ret, FALSE);
2637
2638   /* unref the object that was reffed for us by _fold */
2639   gst_object_unref (pad);
2640   return TRUE;
2641 }
2642
2643 /* set the caps on the pad to NULL */
2644 static gboolean
2645 clear_caps (GstPad * pad, GValue * ret, gboolean * active)
2646 {
2647   gst_pad_set_caps (pad, NULL);
2648   gst_object_unref (pad);
2649   return TRUE;
2650 }
2651
2652 /* returns false on error or early cutout (will never happen because the fold
2653  * function always returns TRUE, see FIXME above) of the fold, true if all
2654  * pads in @iter were (de)activated successfully. */
2655 static gboolean
2656 iterator_activate_fold_with_resync (GstIterator * iter,
2657     GstIteratorFoldFunction func, gpointer user_data)
2658 {
2659   GstIteratorResult ires;
2660   GValue ret = { 0 };
2661
2662   /* no need to unset this later, it's just a boolean */
2663   g_value_init (&ret, G_TYPE_BOOLEAN);
2664   g_value_set_boolean (&ret, TRUE);
2665
2666   while (1) {
2667     ires = gst_iterator_fold (iter, func, &ret, user_data);
2668     switch (ires) {
2669       case GST_ITERATOR_RESYNC:
2670         /* need to reset the result again */
2671         g_value_set_boolean (&ret, TRUE);
2672         gst_iterator_resync (iter);
2673         break;
2674       case GST_ITERATOR_DONE:
2675         /* all pads iterated, return collected value */
2676         goto done;
2677       default:
2678         /* iterator returned _ERROR or premature end with _OK,
2679          * mark an error and exit */
2680         g_value_set_boolean (&ret, FALSE);
2681         goto done;
2682     }
2683   }
2684 done:
2685   /* return collected value */
2686   return g_value_get_boolean (&ret);
2687 }
2688
2689 /* is called with STATE_LOCK
2690  *
2691  * Pads are activated from source pads to sinkpads.
2692  */
2693 static gboolean
2694 gst_element_pads_activate (GstElement * element, gboolean active)
2695 {
2696   GstIterator *iter;
2697   gboolean res;
2698
2699   GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2700       "pads_activate with active %d", active);
2701
2702   iter = gst_element_iterate_src_pads (element);
2703   res =
2704       iterator_activate_fold_with_resync (iter,
2705       (GstIteratorFoldFunction) activate_pads, &active);
2706   gst_iterator_free (iter);
2707   if (G_UNLIKELY (!res))
2708     goto src_failed;
2709
2710   iter = gst_element_iterate_sink_pads (element);
2711   res =
2712       iterator_activate_fold_with_resync (iter,
2713       (GstIteratorFoldFunction) activate_pads, &active);
2714   gst_iterator_free (iter);
2715   if (G_UNLIKELY (!res))
2716     goto sink_failed;
2717
2718   if (!active) {
2719     /* clear the caps on all pads, this should never fail */
2720     iter = gst_element_iterate_pads (element);
2721     res =
2722         iterator_activate_fold_with_resync (iter,
2723         (GstIteratorFoldFunction) clear_caps, &active);
2724     gst_iterator_free (iter);
2725     if (G_UNLIKELY (!res))
2726       goto caps_failed;
2727   }
2728
2729   GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2730       "pads_activate successful");
2731
2732   return TRUE;
2733
2734   /* ERRORS */
2735 src_failed:
2736   {
2737     GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2738         "source pads_activate failed");
2739     return FALSE;
2740   }
2741 sink_failed:
2742   {
2743     GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2744         "sink pads_activate failed");
2745     return FALSE;
2746   }
2747 caps_failed:
2748   {
2749     GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2750         "failed to clear caps on pads");
2751     return FALSE;
2752   }
2753 }
2754
2755 /* is called with STATE_LOCK */
2756 static GstStateChangeReturn
2757 gst_element_change_state_func (GstElement * element, GstStateChange transition)
2758 {
2759   GstState state, next;
2760   GstStateChangeReturn result = GST_STATE_CHANGE_SUCCESS;
2761
2762   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2763
2764   state = (GstState) GST_STATE_TRANSITION_CURRENT (transition);
2765   next = GST_STATE_TRANSITION_NEXT (transition);
2766
2767   /* if the element already is in the given state, we just return success */
2768   if (next == GST_STATE_VOID_PENDING || state == next)
2769     goto was_ok;
2770
2771   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element,
2772       "default handler tries setting state from %s to %s (%04x)",
2773       gst_element_state_get_name (state),
2774       gst_element_state_get_name (next), transition);
2775
2776   switch (transition) {
2777     case GST_STATE_CHANGE_NULL_TO_READY:
2778       break;
2779     case GST_STATE_CHANGE_READY_TO_PAUSED:
2780       if (!gst_element_pads_activate (element, TRUE)) {
2781         result = GST_STATE_CHANGE_FAILURE;
2782       }
2783       break;
2784     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2785       break;
2786     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2787       break;
2788     case GST_STATE_CHANGE_PAUSED_TO_READY:
2789     case GST_STATE_CHANGE_READY_TO_NULL:
2790       /* deactivate pads in both cases, since they are activated on
2791          ready->paused but the element might not have made it to paused */
2792       if (!gst_element_pads_activate (element, FALSE)) {
2793         result = GST_STATE_CHANGE_FAILURE;
2794       } else {
2795         gst_element_set_base_time (element, 0);
2796       }
2797       break;
2798     default:
2799       /* this will catch real but unhandled state changes;
2800        * can only be caused by:
2801        * - a new state was added
2802        * - somehow the element was asked to jump across an intermediate state
2803        */
2804       g_warning ("Unhandled state change from %s to %s",
2805           gst_element_state_get_name (state),
2806           gst_element_state_get_name (next));
2807       break;
2808   }
2809   return result;
2810
2811 was_ok:
2812   {
2813     GST_OBJECT_LOCK (element);
2814     result = GST_STATE_RETURN (element);
2815     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2816         "element is already in the %s state",
2817         gst_element_state_get_name (state));
2818     GST_OBJECT_UNLOCK (element);
2819
2820     return result;
2821   }
2822 }
2823
2824 /**
2825  * gst_element_get_factory:
2826  * @element: a #GstElement to request the element factory of.
2827  *
2828  * Retrieves the factory that was used to create this element.
2829  *
2830  * Returns: the #GstElementFactory used for creating this element.
2831  * no refcounting is needed.
2832  */
2833 GstElementFactory *
2834 gst_element_get_factory (GstElement * element)
2835 {
2836   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
2837
2838   return GST_ELEMENT_GET_CLASS (element)->elementfactory;
2839 }
2840
2841 static void
2842 gst_element_dispose (GObject * object)
2843 {
2844   GstElement *element = GST_ELEMENT (object);
2845   GstClock **clock_p;
2846   GstBus **bus_p;
2847
2848   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "dispose");
2849
2850   if (GST_STATE (element) != GST_STATE_NULL)
2851     goto not_null;
2852
2853   GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2854       "removing %d pads", g_list_length (element->pads));
2855   /* first we break all our links with the outside */
2856   while (element->pads && element->pads->data) {
2857     /* don't call _remove_pad with NULL */
2858     gst_element_remove_pad (element, GST_PAD_CAST (element->pads->data));
2859   }
2860   if (G_UNLIKELY (element->pads != 0)) {
2861     g_critical ("could not remove pads from element %s",
2862         GST_STR_NULL (GST_OBJECT_NAME (object)));
2863   }
2864
2865   GST_OBJECT_LOCK (element);
2866   clock_p = &element->clock;
2867   bus_p = &element->bus;
2868   gst_object_replace ((GstObject **) clock_p, NULL);
2869   gst_object_replace ((GstObject **) bus_p, NULL);
2870   GST_OBJECT_UNLOCK (element);
2871
2872   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "parent class dispose");
2873
2874   G_OBJECT_CLASS (parent_class)->dispose (object);
2875
2876   return;
2877
2878   /* ERRORS */
2879 not_null:
2880   {
2881     g_critical
2882         ("\nTrying to dispose element %s, but it is not in the NULL state.\n"
2883         "You need to explicitly set elements to the NULL state before\n"
2884         "dropping the final reference, to allow them to clean up.\n",
2885         GST_OBJECT_NAME (element));
2886     return;
2887   }
2888 }
2889
2890 static void
2891 gst_element_finalize (GObject * object)
2892 {
2893   GstElement *element = GST_ELEMENT (object);
2894
2895   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "finalize");
2896
2897   GST_STATE_LOCK (element);
2898   if (element->state_cond)
2899     g_cond_free (element->state_cond);
2900   element->state_cond = NULL;
2901   GST_STATE_UNLOCK (element);
2902   g_static_rec_mutex_free (element->state_lock);
2903   g_free (element->state_lock);
2904   element->state_lock = NULL;
2905
2906   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "finalize parent");
2907
2908   G_OBJECT_CLASS (parent_class)->finalize (object);
2909 }
2910
2911 #ifndef GST_DISABLE_LOADSAVE
2912 /**
2913  * gst_element_save_thyself:
2914  * @element: a #GstElement to save.
2915  * @parent: the xml parent node.
2916  *
2917  * Saves the element as part of the given XML structure.
2918  *
2919  * Returns: the new #xmlNodePtr.
2920  */
2921 static xmlNodePtr
2922 gst_element_save_thyself (GstObject * object, xmlNodePtr parent)
2923 {
2924   GList *pads;
2925   GstElementClass *oclass;
2926   GParamSpec **specs, *spec;
2927   guint nspecs;
2928   guint i;
2929   GValue value = { 0, };
2930   GstElement *element;
2931
2932   g_return_val_if_fail (GST_IS_ELEMENT (object), parent);
2933
2934   element = GST_ELEMENT (object);
2935
2936   oclass = GST_ELEMENT_GET_CLASS (element);
2937
2938   xmlNewChild (parent, NULL, (xmlChar *) "name",
2939       (xmlChar *) GST_ELEMENT_NAME (element));
2940
2941   if (oclass->elementfactory != NULL) {
2942     GstElementFactory *factory = (GstElementFactory *) oclass->elementfactory;
2943
2944     xmlNewChild (parent, NULL, (xmlChar *) "type",
2945         (xmlChar *) GST_PLUGIN_FEATURE (factory)->name);
2946   }
2947
2948   /* params */
2949   specs = g_object_class_list_properties (G_OBJECT_GET_CLASS (object), &nspecs);
2950
2951   for (i = 0; i < nspecs; i++) {
2952     spec = specs[i];
2953     if (spec->flags & G_PARAM_READABLE) {
2954       xmlNodePtr param;
2955       char *contents;
2956
2957       g_value_init (&value, G_PARAM_SPEC_VALUE_TYPE (spec));
2958
2959       g_object_get_property (G_OBJECT (element), spec->name, &value);
2960       param = xmlNewChild (parent, NULL, (xmlChar *) "param", NULL);
2961       xmlNewChild (param, NULL, (xmlChar *) "name", (xmlChar *) spec->name);
2962
2963       if (G_IS_PARAM_SPEC_STRING (spec))
2964         contents = g_value_dup_string (&value);
2965       else if (G_IS_PARAM_SPEC_ENUM (spec))
2966         contents = g_strdup_printf ("%d", g_value_get_enum (&value));
2967       else if (G_IS_PARAM_SPEC_INT64 (spec))
2968         contents = g_strdup_printf ("%" G_GINT64_FORMAT,
2969             g_value_get_int64 (&value));
2970       else if (GST_VALUE_HOLDS_STRUCTURE (&value)) {
2971         if (g_value_get_boxed (&value) != NULL) {
2972           contents = g_strdup_value_contents (&value);
2973         } else {
2974           contents = g_strdup ("NULL");
2975         }
2976       } else
2977         contents = g_strdup_value_contents (&value);
2978
2979       xmlNewChild (param, NULL, (xmlChar *) "value", (xmlChar *) contents);
2980       g_free (contents);
2981
2982       g_value_unset (&value);
2983     }
2984   }
2985
2986   g_free (specs);
2987
2988   pads = g_list_last (GST_ELEMENT_PADS (element));
2989
2990   while (pads) {
2991     GstPad *pad = GST_PAD_CAST (pads->data);
2992
2993     /* figure out if it's a direct pad or a ghostpad */
2994     if (GST_ELEMENT (GST_OBJECT_PARENT (pad)) == element) {
2995       xmlNodePtr padtag = xmlNewChild (parent, NULL, (xmlChar *) "pad", NULL);
2996
2997       gst_object_save_thyself (GST_OBJECT_CAST (pad), padtag);
2998     }
2999     pads = g_list_previous (pads);
3000   }
3001
3002   return parent;
3003 }
3004
3005 static void
3006 gst_element_restore_thyself (GstObject * object, xmlNodePtr self)
3007 {
3008   xmlNodePtr children;
3009   GstElement *element;
3010   gchar *name = NULL;
3011   gchar *value = NULL;
3012
3013   element = GST_ELEMENT (object);
3014   g_return_if_fail (element != NULL);
3015
3016   /* parameters */
3017   children = self->xmlChildrenNode;
3018   while (children) {
3019     if (!strcmp ((char *) children->name, "param")) {
3020       xmlNodePtr child = children->xmlChildrenNode;
3021
3022       while (child) {
3023         if (!strcmp ((char *) child->name, "name")) {
3024           name = (gchar *) xmlNodeGetContent (child);
3025         } else if (!strcmp ((char *) child->name, "value")) {
3026           value = (gchar *) xmlNodeGetContent (child);
3027         }
3028         child = child->next;
3029       }
3030       /* FIXME: can this just be g_object_set ? */
3031       gst_util_set_object_arg (G_OBJECT (element), name, value);
3032       /* g_object_set (G_OBJECT (element), name, value, NULL); */
3033       g_free (name);
3034       g_free (value);
3035     }
3036     children = children->next;
3037   }
3038
3039   /* pads */
3040   children = self->xmlChildrenNode;
3041   while (children) {
3042     if (!strcmp ((char *) children->name, "pad")) {
3043       gst_pad_load_and_link (children, GST_OBJECT_CAST (element));
3044     }
3045     children = children->next;
3046   }
3047
3048   if (GST_OBJECT_CLASS (parent_class)->restore_thyself)
3049     (GST_OBJECT_CLASS (parent_class)->restore_thyself) (object, self);
3050 }
3051 #endif /* GST_DISABLE_LOADSAVE */
3052
3053 static void
3054 gst_element_set_bus_func (GstElement * element, GstBus * bus)
3055 {
3056   GstBus **bus_p;
3057
3058   g_return_if_fail (GST_IS_ELEMENT (element));
3059
3060   GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, element, "setting bus to %p", bus);
3061
3062   GST_OBJECT_LOCK (element);
3063   bus_p = &GST_ELEMENT_BUS (element);
3064   gst_object_replace ((GstObject **) bus_p, GST_OBJECT_CAST (bus));
3065   GST_OBJECT_UNLOCK (element);
3066 }
3067
3068 /**
3069  * gst_element_set_bus:
3070  * @element: a #GstElement to set the bus of.
3071  * @bus: the #GstBus to set.
3072  *
3073  * Sets the bus of the element. Increases the refcount on the bus.
3074  * For internal use only, unless you're testing elements.
3075  *
3076  * MT safe.
3077  */
3078 void
3079 gst_element_set_bus (GstElement * element, GstBus * bus)
3080 {
3081   GstElementClass *oclass;
3082
3083   g_return_if_fail (GST_IS_ELEMENT (element));
3084
3085   oclass = GST_ELEMENT_GET_CLASS (element);
3086
3087   if (oclass->set_bus)
3088     oclass->set_bus (element, bus);
3089 }
3090
3091 /**
3092  * gst_element_get_bus:
3093  * @element: a #GstElement to get the bus of.
3094  *
3095  * Returns the bus of the element. Note that only a #GstPipeline will provide a
3096  * bus for the application.
3097  *
3098  * Returns: the element's #GstBus. unref after usage.
3099  *
3100  * MT safe.
3101  */
3102 GstBus *
3103 gst_element_get_bus (GstElement * element)
3104 {
3105   GstBus *result = NULL;
3106
3107   g_return_val_if_fail (GST_IS_ELEMENT (element), result);
3108
3109   GST_OBJECT_LOCK (element);
3110   if ((result = GST_ELEMENT_BUS (element)))
3111     gst_object_ref (result);
3112   GST_OBJECT_UNLOCK (element);
3113
3114   GST_CAT_DEBUG_OBJECT (GST_CAT_BUS, element, "got bus %" GST_PTR_FORMAT,
3115       result);
3116
3117   return result;
3118 }