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