GST_REFCOUNTING: Add logging of pointer address for dispose, finalize, etc messages
[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_static_pad_template:
1234  * @klass: the #GstElementClass to add the pad template to.
1235  * @static_templ: #GstStaticPadTemplate to add as pad template to the element class.
1236  *
1237  * Adds a pad template to an element class based on the static pad template
1238  * @templ. This is mainly used in the _class_init functions of element
1239  * implementations. If a pad template with the same name already exists,
1240  * the old one is replaced by the new one.
1241  *
1242  * Since: 1.8
1243  */
1244 void
1245 gst_element_class_add_static_pad_template (GstElementClass * klass,
1246     GstStaticPadTemplate * static_templ)
1247 {
1248   gst_element_class_add_pad_template (klass,
1249       gst_static_pad_template_get (static_templ));
1250 }
1251
1252 /**
1253  * gst_element_class_add_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 void
1261 gst_element_class_add_metadata (GstElementClass * klass,
1262     const gchar * key, const gchar * value)
1263 {
1264   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1265   g_return_if_fail (key != NULL);
1266   g_return_if_fail (value != NULL);
1267
1268   gst_structure_set ((GstStructure *) klass->metadata,
1269       key, G_TYPE_STRING, value, NULL);
1270 }
1271
1272 /**
1273  * gst_element_class_add_static_metadata:
1274  * @klass: class to set metadata for
1275  * @key: the key to set
1276  * @value: the value to set
1277  *
1278  * Set @key with @value as metadata in @klass.
1279  *
1280  * Same as gst_element_class_add_metadata(), but @value must be a static string
1281  * or an inlined string, as it will not be copied. (GStreamer plugins will
1282  * be made resident once loaded, so this function can be used even from
1283  * dynamically loaded plugins.)
1284  */
1285 void
1286 gst_element_class_add_static_metadata (GstElementClass * klass,
1287     const gchar * key, const gchar * value)
1288 {
1289   GValue val = G_VALUE_INIT;
1290
1291   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1292   g_return_if_fail (key != NULL);
1293   g_return_if_fail (value != NULL);
1294
1295   g_value_init (&val, G_TYPE_STRING);
1296   g_value_set_static_string (&val, value);
1297   gst_structure_take_value ((GstStructure *) klass->metadata, key, &val);
1298 }
1299
1300 /**
1301  * gst_element_class_set_metadata:
1302  * @klass: class to set metadata for
1303  * @longname: The long English name of the element. E.g. "File Sink"
1304  * @classification: String describing the type of element, as an unordered list
1305  * separated with slashes ('/'). See draft-klass.txt of the design docs
1306  * for more details and common types. E.g: "Sink/File"
1307  * @description: Sentence describing the purpose of the element.
1308  * E.g: "Write stream to a file"
1309  * @author: Name and contact details of the author(s). Use \n to separate
1310  * multiple author metadata. E.g: "Joe Bloggs &lt;joe.blogs at foo.com&gt;"
1311  *
1312  * Sets the detailed information for a #GstElementClass.
1313  * <note>This function is for use in _class_init functions only.</note>
1314  */
1315 void
1316 gst_element_class_set_metadata (GstElementClass * klass,
1317     const gchar * longname, const gchar * classification,
1318     const gchar * description, const gchar * author)
1319 {
1320   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1321   g_return_if_fail (longname != NULL && *longname != '\0');
1322   g_return_if_fail (classification != NULL && *classification != '\0');
1323   g_return_if_fail (description != NULL && *description != '\0');
1324   g_return_if_fail (author != NULL && *author != '\0');
1325
1326   gst_structure_id_set ((GstStructure *) klass->metadata,
1327       GST_QUARK (ELEMENT_METADATA_LONGNAME), G_TYPE_STRING, longname,
1328       GST_QUARK (ELEMENT_METADATA_KLASS), G_TYPE_STRING, classification,
1329       GST_QUARK (ELEMENT_METADATA_DESCRIPTION), G_TYPE_STRING, description,
1330       GST_QUARK (ELEMENT_METADATA_AUTHOR), G_TYPE_STRING, author, NULL);
1331 }
1332
1333 /**
1334  * gst_element_class_set_static_metadata:
1335  * @klass: class to set metadata for
1336  * @longname: The long English name of the element. E.g. "File Sink"
1337  * @classification: String describing the type of element, as an unordered list
1338  * separated with slashes ('/'). See draft-klass.txt of the design docs
1339  * for more details and common types. E.g: "Sink/File"
1340  * @description: Sentence describing the purpose of the element.
1341  * E.g: "Write stream to a file"
1342  * @author: Name and contact details of the author(s). Use \n to separate
1343  * multiple author metadata. E.g: "Joe Bloggs &lt;joe.blogs at foo.com&gt;"
1344  *
1345  * Sets the detailed information for a #GstElementClass.
1346  * <note>This function is for use in _class_init functions only.</note>
1347  *
1348  * Same as gst_element_class_set_metadata(), but @longname, @classification,
1349  * @description, and @author must be static strings or inlined strings, as
1350  * they will not be copied. (GStreamer plugins will be made resident once
1351  * loaded, so this function can be used even from dynamically loaded plugins.)
1352  */
1353 void
1354 gst_element_class_set_static_metadata (GstElementClass * klass,
1355     const gchar * longname, const gchar * classification,
1356     const gchar * description, const gchar * author)
1357 {
1358   GstStructure *s = (GstStructure *) klass->metadata;
1359   GValue val = G_VALUE_INIT;
1360
1361   g_return_if_fail (GST_IS_ELEMENT_CLASS (klass));
1362   g_return_if_fail (longname != NULL && *longname != '\0');
1363   g_return_if_fail (classification != NULL && *classification != '\0');
1364   g_return_if_fail (description != NULL && *description != '\0');
1365   g_return_if_fail (author != NULL && *author != '\0');
1366
1367   g_value_init (&val, G_TYPE_STRING);
1368
1369   g_value_set_static_string (&val, longname);
1370   gst_structure_id_set_value (s, GST_QUARK (ELEMENT_METADATA_LONGNAME), &val);
1371
1372   g_value_set_static_string (&val, classification);
1373   gst_structure_id_set_value (s, GST_QUARK (ELEMENT_METADATA_KLASS), &val);
1374
1375   g_value_set_static_string (&val, description);
1376   gst_structure_id_set_value (s, GST_QUARK (ELEMENT_METADATA_DESCRIPTION),
1377       &val);
1378
1379   g_value_set_static_string (&val, author);
1380   gst_structure_id_take_value (s, GST_QUARK (ELEMENT_METADATA_AUTHOR), &val);
1381 }
1382
1383 /**
1384  * gst_element_class_get_metadata:
1385  * @klass: class to get metadata for
1386  * @key: the key to get
1387  *
1388  * Get metadata with @key in @klass.
1389  *
1390  * Returns: the metadata for @key.
1391  */
1392 const gchar *
1393 gst_element_class_get_metadata (GstElementClass * klass, const gchar * key)
1394 {
1395   g_return_val_if_fail (GST_IS_ELEMENT_CLASS (klass), NULL);
1396   g_return_val_if_fail (key != NULL, NULL);
1397
1398   return gst_structure_get_string ((GstStructure *) klass->metadata, key);
1399 }
1400
1401 /**
1402  * gst_element_class_get_pad_template_list:
1403  * @element_class: a #GstElementClass to get pad templates of.
1404  *
1405  * Retrieves a list of the pad templates associated with @element_class. The
1406  * list must not be modified by the calling code.
1407  * <note>If you use this function in the #GInstanceInitFunc of an object class
1408  * that has subclasses, make sure to pass the g_class parameter of the
1409  * #GInstanceInitFunc here.</note>
1410  *
1411  * Returns: (transfer none) (element-type Gst.PadTemplate): the #GList of
1412  *     pad templates.
1413  */
1414 GList *
1415 gst_element_class_get_pad_template_list (GstElementClass * element_class)
1416 {
1417   g_return_val_if_fail (GST_IS_ELEMENT_CLASS (element_class), NULL);
1418
1419   return element_class->padtemplates;
1420 }
1421
1422 /**
1423  * gst_element_class_get_pad_template:
1424  * @element_class: a #GstElementClass to get the pad template of.
1425  * @name: the name of the #GstPadTemplate to get.
1426  *
1427  * Retrieves a padtemplate from @element_class with the given name.
1428  * <note>If you use this function in the #GInstanceInitFunc of an object class
1429  * that has subclasses, make sure to pass the g_class parameter of the
1430  * #GInstanceInitFunc here.</note>
1431  *
1432  * Returns: (transfer none) (nullable): the #GstPadTemplate with the
1433  *     given name, or %NULL if none was found. No unreferencing is
1434  *     necessary.
1435  */
1436 GstPadTemplate *
1437 gst_element_class_get_pad_template (GstElementClass *
1438     element_class, const gchar * name)
1439 {
1440   GList *padlist;
1441
1442   g_return_val_if_fail (GST_IS_ELEMENT_CLASS (element_class), NULL);
1443   g_return_val_if_fail (name != NULL, NULL);
1444
1445   padlist = element_class->padtemplates;
1446
1447   while (padlist) {
1448     GstPadTemplate *padtempl = (GstPadTemplate *) padlist->data;
1449
1450     if (strcmp (padtempl->name_template, name) == 0)
1451       return padtempl;
1452
1453     padlist = g_list_next (padlist);
1454   }
1455
1456   return NULL;
1457 }
1458
1459 static GstPadTemplate *
1460 gst_element_class_get_request_pad_template (GstElementClass *
1461     element_class, const gchar * name)
1462 {
1463   GstPadTemplate *tmpl;
1464
1465   tmpl = gst_element_class_get_pad_template (element_class, name);
1466   if (tmpl != NULL && tmpl->presence == GST_PAD_REQUEST)
1467     return tmpl;
1468
1469   return NULL;
1470 }
1471
1472 /* get a random pad on element of the given direction.
1473  * The pad is random in a sense that it is the first pad that is (optionaly) linked.
1474  */
1475 static GstPad *
1476 gst_element_get_random_pad (GstElement * element,
1477     gboolean need_linked, GstPadDirection dir)
1478 {
1479   GstPad *result = NULL;
1480   GList *pads;
1481
1482   GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "getting a random pad");
1483
1484   switch (dir) {
1485     case GST_PAD_SRC:
1486       GST_OBJECT_LOCK (element);
1487       pads = element->srcpads;
1488       break;
1489     case GST_PAD_SINK:
1490       GST_OBJECT_LOCK (element);
1491       pads = element->sinkpads;
1492       break;
1493     default:
1494       goto wrong_direction;
1495   }
1496   for (; pads; pads = g_list_next (pads)) {
1497     GstPad *pad = GST_PAD_CAST (pads->data);
1498
1499     GST_OBJECT_LOCK (pad);
1500     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "checking pad %s:%s",
1501         GST_DEBUG_PAD_NAME (pad));
1502
1503     if (need_linked && !GST_PAD_IS_LINKED (pad)) {
1504       /* if we require a linked pad, and it is not linked, continue the
1505        * search */
1506       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "pad %s:%s is not linked",
1507           GST_DEBUG_PAD_NAME (pad));
1508       GST_OBJECT_UNLOCK (pad);
1509       continue;
1510     } else {
1511       /* found a pad, stop search */
1512       GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "found pad %s:%s",
1513           GST_DEBUG_PAD_NAME (pad));
1514       GST_OBJECT_UNLOCK (pad);
1515       result = pad;
1516       break;
1517     }
1518   }
1519   if (result)
1520     gst_object_ref (result);
1521
1522   GST_OBJECT_UNLOCK (element);
1523
1524   return result;
1525
1526   /* ERROR handling */
1527 wrong_direction:
1528   {
1529     g_warning ("unknown pad direction %d", dir);
1530     return NULL;
1531   }
1532 }
1533
1534 static gboolean
1535 gst_element_default_send_event (GstElement * element, GstEvent * event)
1536 {
1537   gboolean result = FALSE;
1538   GstPad *pad;
1539
1540   pad = GST_EVENT_IS_DOWNSTREAM (event) ?
1541       gst_element_get_random_pad (element, TRUE, GST_PAD_SINK) :
1542       gst_element_get_random_pad (element, TRUE, GST_PAD_SRC);
1543
1544   if (pad) {
1545     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS,
1546         "pushing %s event to random %s pad %s:%s",
1547         GST_EVENT_TYPE_NAME (event),
1548         (GST_PAD_DIRECTION (pad) == GST_PAD_SRC ? "src" : "sink"),
1549         GST_DEBUG_PAD_NAME (pad));
1550
1551     result = gst_pad_send_event (pad, event);
1552     gst_object_unref (pad);
1553   } else {
1554     GST_CAT_INFO (GST_CAT_ELEMENT_PADS, "can't send %s event on element %s",
1555         GST_EVENT_TYPE_NAME (event), GST_ELEMENT_NAME (element));
1556     gst_event_unref (event);
1557   }
1558   return result;
1559 }
1560
1561 /**
1562  * gst_element_send_event:
1563  * @element: a #GstElement to send the event to.
1564  * @event: (transfer full): the #GstEvent to send to the element.
1565  *
1566  * Sends an event to an element. If the element doesn't implement an
1567  * event handler, the event will be pushed on a random linked sink pad for
1568  * downstream events or a random linked source pad for upstream events.
1569  *
1570  * This function takes ownership of the provided event so you should
1571  * gst_event_ref() it if you want to reuse the event after this call.
1572  *
1573  * MT safe.
1574  *
1575  * Returns: %TRUE if the event was handled. Events that trigger a preroll (such
1576  * as flushing seeks and steps) will emit %GST_MESSAGE_ASYNC_DONE.
1577  */
1578 gboolean
1579 gst_element_send_event (GstElement * element, GstEvent * event)
1580 {
1581   GstElementClass *oclass;
1582   gboolean result = FALSE;
1583
1584   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1585   g_return_val_if_fail (event != NULL, FALSE);
1586
1587   oclass = GST_ELEMENT_GET_CLASS (element);
1588
1589   GST_STATE_LOCK (element);
1590   if (oclass->send_event) {
1591     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "send %s event on element %s",
1592         GST_EVENT_TYPE_NAME (event), GST_ELEMENT_NAME (element));
1593     result = oclass->send_event (element, event);
1594   } else {
1595     gst_event_unref (event);
1596   }
1597   GST_STATE_UNLOCK (element);
1598
1599   return result;
1600 }
1601
1602 /**
1603  * gst_element_seek:
1604  * @element: a #GstElement to send the event to.
1605  * @rate: The new playback rate
1606  * @format: The format of the seek values
1607  * @flags: The optional seek flags.
1608  * @start_type: The type and flags for the new start position
1609  * @start: The value of the new start position
1610  * @stop_type: The type and flags for the new stop position
1611  * @stop: The value of the new stop position
1612  *
1613  * Sends a seek event to an element. See gst_event_new_seek() for the details of
1614  * the parameters. The seek event is sent to the element using
1615  * gst_element_send_event().
1616  *
1617  * MT safe.
1618  *
1619  * Returns: %TRUE if the event was handled. Flushing seeks will trigger a
1620  * preroll, which will emit %GST_MESSAGE_ASYNC_DONE.
1621  */
1622 gboolean
1623 gst_element_seek (GstElement * element, gdouble rate, GstFormat format,
1624     GstSeekFlags flags, GstSeekType start_type, gint64 start,
1625     GstSeekType stop_type, gint64 stop)
1626 {
1627   GstEvent *event;
1628   gboolean result;
1629
1630   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1631
1632   event =
1633       gst_event_new_seek (rate, format, flags, start_type, start, stop_type,
1634       stop);
1635   result = gst_element_send_event (element, event);
1636
1637   return result;
1638 }
1639
1640 static gboolean
1641 gst_element_default_query (GstElement * element, GstQuery * query)
1642 {
1643   gboolean result = FALSE;
1644   GstPad *pad;
1645
1646   pad = gst_element_get_random_pad (element, FALSE, GST_PAD_SRC);
1647   if (pad) {
1648     result = gst_pad_query (pad, query);
1649
1650     gst_object_unref (pad);
1651   } else {
1652     pad = gst_element_get_random_pad (element, TRUE, GST_PAD_SINK);
1653     if (pad) {
1654       GstPad *peer = gst_pad_get_peer (pad);
1655
1656       if (peer) {
1657         result = gst_pad_query (peer, query);
1658
1659         gst_object_unref (peer);
1660       }
1661       gst_object_unref (pad);
1662     }
1663   }
1664   return result;
1665 }
1666
1667 /**
1668  * gst_element_query:
1669  * @element: a #GstElement to perform the query on.
1670  * @query: (transfer none): the #GstQuery.
1671  *
1672  * Performs a query on the given element.
1673  *
1674  * For elements that don't implement a query handler, this function
1675  * forwards the query to a random srcpad or to the peer of a
1676  * random linked sinkpad of this element.
1677  *
1678  * Please note that some queries might need a running pipeline to work.
1679  *
1680  * Returns: %TRUE if the query could be performed.
1681  *
1682  * MT safe.
1683  */
1684 gboolean
1685 gst_element_query (GstElement * element, GstQuery * query)
1686 {
1687   GstElementClass *klass;
1688   gboolean res = FALSE;
1689
1690   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1691   g_return_val_if_fail (query != NULL, FALSE);
1692
1693   GST_TRACER_ELEMENT_QUERY_PRE (element, query);
1694
1695   klass = GST_ELEMENT_GET_CLASS (element);
1696   if (klass->query) {
1697     GST_CAT_DEBUG (GST_CAT_ELEMENT_PADS, "send query on element %s",
1698         GST_ELEMENT_NAME (element));
1699     res = klass->query (element, query);
1700   }
1701
1702   GST_TRACER_ELEMENT_QUERY_POST (element, query, res);
1703   return res;
1704 }
1705
1706 static gboolean
1707 gst_element_post_message_default (GstElement * element, GstMessage * message)
1708 {
1709   GstBus *bus;
1710   gboolean result = FALSE;
1711
1712   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1713   g_return_val_if_fail (message != NULL, FALSE);
1714
1715   GST_OBJECT_LOCK (element);
1716   bus = element->bus;
1717
1718   if (G_UNLIKELY (bus == NULL))
1719     goto no_bus;
1720
1721   gst_object_ref (bus);
1722   GST_OBJECT_UNLOCK (element);
1723
1724   /* we release the element lock when posting the message so that any
1725    * (synchronous) message handlers can operate on the element */
1726   result = gst_bus_post (bus, message);
1727   gst_object_unref (bus);
1728
1729   return result;
1730
1731   /* ERRORS */
1732 no_bus:
1733   {
1734     GST_CAT_DEBUG_OBJECT (GST_CAT_MESSAGE, element,
1735         "not posting message %p: no bus", message);
1736     GST_OBJECT_UNLOCK (element);
1737     gst_message_unref (message);
1738     return FALSE;
1739   }
1740 }
1741
1742 /**
1743  * gst_element_post_message:
1744  * @element: a #GstElement posting the message
1745  * @message: (transfer full): a #GstMessage to post
1746  *
1747  * Post a message on the element's #GstBus. This function takes ownership of the
1748  * message; if you want to access the message after this call, you should add an
1749  * additional reference before calling.
1750  *
1751  * Returns: %TRUE if the message was successfully posted. The function returns
1752  * %FALSE if the element did not have a bus.
1753  *
1754  * MT safe.
1755  */
1756 gboolean
1757 gst_element_post_message (GstElement * element, GstMessage * message)
1758 {
1759   GstElementClass *klass;
1760   gboolean res = FALSE;
1761
1762   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1763   g_return_val_if_fail (message != NULL, FALSE);
1764
1765   GST_TRACER_ELEMENT_POST_MESSAGE_PRE (element, message);
1766
1767   klass = GST_ELEMENT_GET_CLASS (element);
1768   if (klass->post_message)
1769     res = klass->post_message (element, message);
1770   else
1771     gst_message_unref (message);
1772
1773   GST_TRACER_ELEMENT_POST_MESSAGE_POST (element, res);
1774   return res;
1775 }
1776
1777 /**
1778  * _gst_element_error_printf:
1779  * @format: (allow-none): the printf-like format to use, or %NULL
1780  *
1781  * This function is only used internally by the gst_element_error() macro.
1782  *
1783  * Returns: (transfer full) (nullable): a newly allocated string, or
1784  *     %NULL if the format was %NULL or ""
1785  *
1786  * MT safe.
1787  */
1788 gchar *
1789 _gst_element_error_printf (const gchar * format, ...)
1790 {
1791   va_list args;
1792   gchar *buffer;
1793   int len;
1794
1795   if (format == NULL)
1796     return NULL;
1797   if (format[0] == 0)
1798     return NULL;
1799
1800   va_start (args, format);
1801
1802   len = __gst_vasprintf (&buffer, format, args);
1803
1804   va_end (args);
1805
1806   if (len < 0)
1807     buffer = NULL;
1808
1809   return buffer;
1810 }
1811
1812 /**
1813  * gst_element_message_full:
1814  * @element:  a #GstElement to send message from
1815  * @type:     the #GstMessageType
1816  * @domain:   the GStreamer GError domain this message belongs to
1817  * @code:     the GError code belonging to the domain
1818  * @text:     (allow-none) (transfer full): an allocated text string to be used
1819  *            as a replacement for the default message connected to code,
1820  *            or %NULL
1821  * @debug:    (allow-none) (transfer full): an allocated debug message to be
1822  *            used as a replacement for the default debugging information,
1823  *            or %NULL
1824  * @file:     the source code file where the error was generated
1825  * @function: the source code function where the error was generated
1826  * @line:     the source code line where the error was generated
1827  *
1828  * Post an error, warning or info message on the bus from inside an element.
1829  *
1830  * @type must be of #GST_MESSAGE_ERROR, #GST_MESSAGE_WARNING or
1831  * #GST_MESSAGE_INFO.
1832  *
1833  * MT safe.
1834  */
1835 void gst_element_message_full
1836     (GstElement * element, GstMessageType type,
1837     GQuark domain, gint code, gchar * text,
1838     gchar * debug, const gchar * file, const gchar * function, gint line)
1839 {
1840   GError *gerror = NULL;
1841   gchar *name;
1842   gchar *sent_text;
1843   gchar *sent_debug;
1844   gboolean has_debug = TRUE;
1845   GstMessage *message = NULL;
1846
1847   /* checks */
1848   GST_CAT_DEBUG_OBJECT (GST_CAT_MESSAGE, element, "start");
1849   g_return_if_fail (GST_IS_ELEMENT (element));
1850   g_return_if_fail ((type == GST_MESSAGE_ERROR) ||
1851       (type == GST_MESSAGE_WARNING) || (type == GST_MESSAGE_INFO));
1852
1853   /* check if we send the given text or the default error text */
1854   if ((text == NULL) || (text[0] == 0)) {
1855     /* text could have come from g_strdup_printf (""); */
1856     g_free (text);
1857     sent_text = gst_error_get_message (domain, code);
1858   } else
1859     sent_text = text;
1860
1861   /* construct a sent_debug with extra information from source */
1862   if ((debug == NULL) || (debug[0] == 0)) {
1863     /* debug could have come from g_strdup_printf (""); */
1864     has_debug = FALSE;
1865   }
1866
1867   name = gst_object_get_path_string (GST_OBJECT_CAST (element));
1868   if (has_debug)
1869     sent_debug = g_strdup_printf ("%s(%d): %s (): %s:\n%s",
1870         file, line, function, name, debug);
1871   else
1872     sent_debug = g_strdup_printf ("%s(%d): %s (): %s",
1873         file, line, function, name);
1874   g_free (name);
1875   g_free (debug);
1876
1877   /* create gerror and post message */
1878   GST_CAT_INFO_OBJECT (GST_CAT_ERROR_SYSTEM, element, "posting message: %s",
1879       sent_text);
1880   gerror = g_error_new_literal (domain, code, sent_text);
1881
1882   switch (type) {
1883     case GST_MESSAGE_ERROR:
1884       message =
1885           gst_message_new_error (GST_OBJECT_CAST (element), gerror, sent_debug);
1886       break;
1887     case GST_MESSAGE_WARNING:
1888       message = gst_message_new_warning (GST_OBJECT_CAST (element), gerror,
1889           sent_debug);
1890       break;
1891     case GST_MESSAGE_INFO:
1892       message = gst_message_new_info (GST_OBJECT_CAST (element), gerror,
1893           sent_debug);
1894       break;
1895     default:
1896       g_assert_not_reached ();
1897       break;
1898   }
1899   gst_element_post_message (element, message);
1900
1901   GST_CAT_INFO_OBJECT (GST_CAT_ERROR_SYSTEM, element, "posted %s message: %s",
1902       (type == GST_MESSAGE_ERROR ? "error" : "warning"), sent_text);
1903
1904   /* cleanup */
1905   g_error_free (gerror);
1906   g_free (sent_debug);
1907   g_free (sent_text);
1908 }
1909
1910 /**
1911  * gst_element_is_locked_state:
1912  * @element: a #GstElement.
1913  *
1914  * Checks if the state of an element is locked.
1915  * If the state of an element is locked, state changes of the parent don't
1916  * affect the element.
1917  * This way you can leave currently unused elements inside bins. Just lock their
1918  * state before changing the state from #GST_STATE_NULL.
1919  *
1920  * MT safe.
1921  *
1922  * Returns: %TRUE, if the element's state is locked.
1923  */
1924 gboolean
1925 gst_element_is_locked_state (GstElement * element)
1926 {
1927   gboolean result;
1928
1929   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1930
1931   GST_OBJECT_LOCK (element);
1932   result = GST_ELEMENT_IS_LOCKED_STATE (element);
1933   GST_OBJECT_UNLOCK (element);
1934
1935   return result;
1936 }
1937
1938 /**
1939  * gst_element_set_locked_state:
1940  * @element: a #GstElement
1941  * @locked_state: %TRUE to lock the element's state
1942  *
1943  * Locks the state of an element, so state changes of the parent don't affect
1944  * this element anymore.
1945  *
1946  * MT safe.
1947  *
1948  * Returns: %TRUE if the state was changed, %FALSE if bad parameters were given
1949  * or the elements state-locking needed no change.
1950  */
1951 gboolean
1952 gst_element_set_locked_state (GstElement * element, gboolean locked_state)
1953 {
1954   gboolean old;
1955
1956   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
1957
1958   GST_OBJECT_LOCK (element);
1959   old = GST_ELEMENT_IS_LOCKED_STATE (element);
1960
1961   if (G_UNLIKELY (old == locked_state))
1962     goto was_ok;
1963
1964   if (locked_state) {
1965     GST_CAT_DEBUG (GST_CAT_STATES, "locking state of element %s",
1966         GST_ELEMENT_NAME (element));
1967     GST_OBJECT_FLAG_SET (element, GST_ELEMENT_FLAG_LOCKED_STATE);
1968   } else {
1969     GST_CAT_DEBUG (GST_CAT_STATES, "unlocking state of element %s",
1970         GST_ELEMENT_NAME (element));
1971     GST_OBJECT_FLAG_UNSET (element, GST_ELEMENT_FLAG_LOCKED_STATE);
1972   }
1973   GST_OBJECT_UNLOCK (element);
1974
1975   return TRUE;
1976
1977 was_ok:
1978   {
1979     GST_CAT_DEBUG (GST_CAT_STATES,
1980         "elements %s was already in locked state %d",
1981         GST_ELEMENT_NAME (element), old);
1982     GST_OBJECT_UNLOCK (element);
1983
1984     return FALSE;
1985   }
1986 }
1987
1988 /**
1989  * gst_element_sync_state_with_parent:
1990  * @element: a #GstElement.
1991  *
1992  * Tries to change the state of the element to the same as its parent.
1993  * If this function returns %FALSE, the state of element is undefined.
1994  *
1995  * Returns: %TRUE, if the element's state could be synced to the parent's state.
1996  *
1997  * MT safe.
1998  */
1999 gboolean
2000 gst_element_sync_state_with_parent (GstElement * element)
2001 {
2002   GstElement *parent;
2003   GstState target;
2004   GstStateChangeReturn ret;
2005
2006   g_return_val_if_fail (GST_IS_ELEMENT (element), FALSE);
2007
2008   if ((parent = GST_ELEMENT_CAST (gst_element_get_parent (element)))) {
2009     GstState parent_current, parent_pending;
2010
2011     GST_OBJECT_LOCK (parent);
2012     parent_current = GST_STATE (parent);
2013     parent_pending = GST_STATE_PENDING (parent);
2014     GST_OBJECT_UNLOCK (parent);
2015
2016     /* set to pending if there is one, else we set it to the current state of
2017      * the parent */
2018     if (parent_pending != GST_STATE_VOID_PENDING)
2019       target = parent_pending;
2020     else
2021       target = parent_current;
2022
2023     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2024         "syncing state (%s) to parent %s %s (%s, %s)",
2025         gst_element_state_get_name (GST_STATE (element)),
2026         GST_ELEMENT_NAME (parent), gst_element_state_get_name (target),
2027         gst_element_state_get_name (parent_current),
2028         gst_element_state_get_name (parent_pending));
2029
2030     ret = gst_element_set_state (element, target);
2031     if (ret == GST_STATE_CHANGE_FAILURE)
2032       goto failed;
2033
2034     gst_object_unref (parent);
2035
2036     return TRUE;
2037   } else {
2038     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "element has no parent");
2039   }
2040   return FALSE;
2041
2042   /* ERROR */
2043 failed:
2044   {
2045     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2046         "syncing state failed (%s)",
2047         gst_element_state_change_return_get_name (ret));
2048     gst_object_unref (parent);
2049     return FALSE;
2050   }
2051 }
2052
2053 /* MT safe */
2054 static GstStateChangeReturn
2055 gst_element_get_state_func (GstElement * element,
2056     GstState * state, GstState * pending, GstClockTime timeout)
2057 {
2058   GstStateChangeReturn ret = GST_STATE_CHANGE_FAILURE;
2059   GstState old_pending;
2060
2061   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "getting state, timeout %"
2062       GST_TIME_FORMAT, GST_TIME_ARGS (timeout));
2063
2064   GST_OBJECT_LOCK (element);
2065   ret = GST_STATE_RETURN (element);
2066   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "RETURN is %s",
2067       gst_element_state_change_return_get_name (ret));
2068
2069   /* we got an error, report immediately */
2070   if (ret == GST_STATE_CHANGE_FAILURE)
2071     goto done;
2072
2073   /* we got no_preroll, report immediately */
2074   if (ret == GST_STATE_CHANGE_NO_PREROLL)
2075     goto done;
2076
2077   /* no need to wait async if we are not async */
2078   if (ret != GST_STATE_CHANGE_ASYNC)
2079     goto done;
2080
2081   old_pending = GST_STATE_PENDING (element);
2082   if (old_pending != GST_STATE_VOID_PENDING) {
2083     gboolean signaled;
2084     guint32 cookie;
2085
2086     /* get cookie to detect state changes during waiting */
2087     cookie = element->state_cookie;
2088
2089     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2090         "waiting for element to commit state");
2091
2092     /* we have a pending state change, wait for it to complete */
2093     if (timeout != GST_CLOCK_TIME_NONE) {
2094       gint64 end_time;
2095       /* make timeout absolute */
2096       end_time = g_get_monotonic_time () + (timeout / 1000);
2097       signaled = GST_STATE_WAIT_UNTIL (element, end_time);
2098     } else {
2099       GST_STATE_WAIT (element);
2100       signaled = TRUE;
2101     }
2102
2103     if (!signaled) {
2104       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "timed out");
2105       /* timeout triggered */
2106       ret = GST_STATE_CHANGE_ASYNC;
2107     } else {
2108       if (cookie != element->state_cookie)
2109         goto interrupted;
2110
2111       /* could be success or failure */
2112       if (old_pending == GST_STATE (element)) {
2113         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "got success");
2114         ret = GST_STATE_CHANGE_SUCCESS;
2115       } else {
2116         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "got failure");
2117         ret = GST_STATE_CHANGE_FAILURE;
2118       }
2119     }
2120     /* if nothing is pending anymore we can return SUCCESS */
2121     if (GST_STATE_PENDING (element) == GST_STATE_VOID_PENDING) {
2122       GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "nothing pending");
2123       ret = GST_STATE_CHANGE_SUCCESS;
2124     }
2125   }
2126
2127 done:
2128   if (state)
2129     *state = GST_STATE (element);
2130   if (pending)
2131     *pending = GST_STATE_PENDING (element);
2132
2133   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2134       "state current: %s, pending: %s, result: %s",
2135       gst_element_state_get_name (GST_STATE (element)),
2136       gst_element_state_get_name (GST_STATE_PENDING (element)),
2137       gst_element_state_change_return_get_name (ret));
2138   GST_OBJECT_UNLOCK (element);
2139
2140   return ret;
2141
2142 interrupted:
2143   {
2144     if (state)
2145       *state = GST_STATE_VOID_PENDING;
2146     if (pending)
2147       *pending = GST_STATE_VOID_PENDING;
2148
2149     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "interruped");
2150
2151     GST_OBJECT_UNLOCK (element);
2152
2153     return GST_STATE_CHANGE_FAILURE;
2154   }
2155 }
2156
2157 /**
2158  * gst_element_get_state:
2159  * @element: a #GstElement to get the state of.
2160  * @state: (out) (allow-none): a pointer to #GstState to hold the state.
2161  *     Can be %NULL.
2162  * @pending: (out) (allow-none): a pointer to #GstState to hold the pending
2163  *     state. Can be %NULL.
2164  * @timeout: a #GstClockTime to specify the timeout for an async
2165  *           state change or %GST_CLOCK_TIME_NONE for infinite timeout.
2166  *
2167  * Gets the state of the element.
2168  *
2169  * For elements that performed an ASYNC state change, as reported by
2170  * gst_element_set_state(), this function will block up to the
2171  * specified timeout value for the state change to complete.
2172  * If the element completes the state change or goes into
2173  * an error, this function returns immediately with a return value of
2174  * %GST_STATE_CHANGE_SUCCESS or %GST_STATE_CHANGE_FAILURE respectively.
2175  *
2176  * For elements that did not return %GST_STATE_CHANGE_ASYNC, this function
2177  * returns the current and pending state immediately.
2178  *
2179  * This function returns %GST_STATE_CHANGE_NO_PREROLL if the element
2180  * successfully changed its state but is not able to provide data yet.
2181  * This mostly happens for live sources that only produce data in
2182  * %GST_STATE_PLAYING. While the state change return is equivalent to
2183  * %GST_STATE_CHANGE_SUCCESS, it is returned to the application to signal that
2184  * some sink elements might not be able to complete their state change because
2185  * an element is not producing data to complete the preroll. When setting the
2186  * element to playing, the preroll will complete and playback will start.
2187  *
2188  * Returns: %GST_STATE_CHANGE_SUCCESS if the element has no more pending state
2189  *          and the last state change succeeded, %GST_STATE_CHANGE_ASYNC if the
2190  *          element is still performing a state change or
2191  *          %GST_STATE_CHANGE_FAILURE if the last state change failed.
2192  *
2193  * MT safe.
2194  */
2195 GstStateChangeReturn
2196 gst_element_get_state (GstElement * element,
2197     GstState * state, GstState * pending, GstClockTime timeout)
2198 {
2199   GstElementClass *oclass;
2200   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
2201
2202   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2203
2204   oclass = GST_ELEMENT_GET_CLASS (element);
2205
2206   if (oclass->get_state)
2207     result = (oclass->get_state) (element, state, pending, timeout);
2208
2209   return result;
2210 }
2211
2212 /**
2213  * gst_element_abort_state:
2214  * @element: a #GstElement to abort the state of.
2215  *
2216  * Abort the state change of the element. This function is used
2217  * by elements that do asynchronous state changes and find out
2218  * something is wrong.
2219  *
2220  * This function should be called with the STATE_LOCK held.
2221  *
2222  * MT safe.
2223  */
2224 void
2225 gst_element_abort_state (GstElement * element)
2226 {
2227   GstState pending;
2228
2229 #ifndef GST_DISABLE_GST_DEBUG
2230   GstState old_state;
2231 #endif
2232
2233   g_return_if_fail (GST_IS_ELEMENT (element));
2234
2235   GST_OBJECT_LOCK (element);
2236   pending = GST_STATE_PENDING (element);
2237
2238   if (pending == GST_STATE_VOID_PENDING ||
2239       GST_STATE_RETURN (element) == GST_STATE_CHANGE_FAILURE)
2240     goto nothing_aborted;
2241
2242 #ifndef GST_DISABLE_GST_DEBUG
2243   old_state = GST_STATE (element);
2244
2245   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2246       "aborting state from %s to %s", gst_element_state_get_name (old_state),
2247       gst_element_state_get_name (pending));
2248 #endif
2249
2250   /* flag error */
2251   GST_STATE_RETURN (element) = GST_STATE_CHANGE_FAILURE;
2252
2253   GST_STATE_BROADCAST (element);
2254   GST_OBJECT_UNLOCK (element);
2255
2256   return;
2257
2258 nothing_aborted:
2259   {
2260     GST_OBJECT_UNLOCK (element);
2261     return;
2262   }
2263 }
2264
2265 /* Not static because GstBin has manual state handling too */
2266 void
2267 _priv_gst_element_state_changed (GstElement * element, GstState oldstate,
2268     GstState newstate, GstState pending)
2269 {
2270   GstElementClass *klass = GST_ELEMENT_GET_CLASS (element);
2271   GstMessage *message;
2272
2273   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2274       "notifying about state-changed %s to %s (%s pending)",
2275       gst_element_state_get_name (oldstate),
2276       gst_element_state_get_name (newstate),
2277       gst_element_state_get_name (pending));
2278
2279   if (klass->state_changed)
2280     klass->state_changed (element, oldstate, newstate, pending);
2281
2282   message = gst_message_new_state_changed (GST_OBJECT_CAST (element),
2283       oldstate, newstate, pending);
2284   gst_element_post_message (element, message);
2285 }
2286
2287 /**
2288  * gst_element_continue_state:
2289  * @element: a #GstElement to continue the state change of.
2290  * @ret: The previous state return value
2291  *
2292  * Commit the state change of the element and proceed to the next
2293  * pending state if any. This function is used
2294  * by elements that do asynchronous state changes.
2295  * The core will normally call this method automatically when an
2296  * element returned %GST_STATE_CHANGE_SUCCESS from the state change function.
2297  *
2298  * If after calling this method the element still has not reached
2299  * the pending state, the next state change is performed.
2300  *
2301  * This method is used internally and should normally not be called by plugins
2302  * or applications.
2303  *
2304  * Returns: The result of the commit state change.
2305  *
2306  * MT safe.
2307  */
2308 GstStateChangeReturn
2309 gst_element_continue_state (GstElement * element, GstStateChangeReturn ret)
2310 {
2311   GstStateChangeReturn old_ret;
2312   GstState old_state, old_next;
2313   GstState current, next, pending;
2314   GstStateChange transition;
2315
2316   GST_OBJECT_LOCK (element);
2317   old_ret = GST_STATE_RETURN (element);
2318   GST_STATE_RETURN (element) = ret;
2319   pending = GST_STATE_PENDING (element);
2320
2321   /* check if there is something to commit */
2322   if (pending == GST_STATE_VOID_PENDING)
2323     goto nothing_pending;
2324
2325   old_state = GST_STATE (element);
2326   /* this is the state we should go to next */
2327   old_next = GST_STATE_NEXT (element);
2328   /* update current state */
2329   current = GST_STATE (element) = old_next;
2330
2331   /* see if we reached the final state */
2332   if (pending == current)
2333     goto complete;
2334
2335   next = GST_STATE_GET_NEXT (current, pending);
2336   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
2337
2338   GST_STATE_NEXT (element) = next;
2339   /* mark busy */
2340   GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2341   GST_OBJECT_UNLOCK (element);
2342
2343   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2344       "committing state from %s to %s, pending %s, next %s",
2345       gst_element_state_get_name (old_state),
2346       gst_element_state_get_name (old_next),
2347       gst_element_state_get_name (pending), gst_element_state_get_name (next));
2348
2349   _priv_gst_element_state_changed (element, old_state, old_next, pending);
2350
2351   GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2352       "continue state change %s to %s, final %s",
2353       gst_element_state_get_name (current),
2354       gst_element_state_get_name (next), gst_element_state_get_name (pending));
2355
2356   ret = gst_element_change_state (element, transition);
2357
2358   return ret;
2359
2360 nothing_pending:
2361   {
2362     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element, "nothing pending");
2363     GST_OBJECT_UNLOCK (element);
2364     return ret;
2365   }
2366 complete:
2367   {
2368     GST_STATE_PENDING (element) = GST_STATE_VOID_PENDING;
2369     GST_STATE_NEXT (element) = GST_STATE_VOID_PENDING;
2370
2371     GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2372         "completed state change to %s", gst_element_state_get_name (pending));
2373     GST_OBJECT_UNLOCK (element);
2374
2375     /* don't post silly messages with the same state. This can happen
2376      * when an element state is changed to what it already was. For bins
2377      * this can be the result of a lost state, which we check with the
2378      * previous return value.
2379      * We do signal the cond though as a _get_state() might be blocking
2380      * on it. */
2381     if (old_state != old_next || old_ret == GST_STATE_CHANGE_ASYNC)
2382       _priv_gst_element_state_changed (element, old_state, old_next,
2383           GST_STATE_VOID_PENDING);
2384
2385     GST_STATE_BROADCAST (element);
2386
2387     return ret;
2388   }
2389 }
2390
2391 /**
2392  * gst_element_lost_state:
2393  * @element: a #GstElement the state is lost of
2394  *
2395  * Brings the element to the lost state. The current state of the
2396  * element is copied to the pending state so that any call to
2397  * gst_element_get_state() will return %GST_STATE_CHANGE_ASYNC.
2398  *
2399  * An ASYNC_START message is posted. If the element was PLAYING, it will
2400  * go to PAUSED. The element will be restored to its PLAYING state by
2401  * the parent pipeline when it prerolls again.
2402  *
2403  * This is mostly used for elements that lost their preroll buffer
2404  * in the %GST_STATE_PAUSED or %GST_STATE_PLAYING state after a flush,
2405  * they will go to their pending state again when a new preroll buffer is
2406  * queued. This function can only be called when the element is currently
2407  * not in error or an async state change.
2408  *
2409  * This function is used internally and should normally not be called from
2410  * plugins or applications.
2411  */
2412 void
2413 gst_element_lost_state (GstElement * element)
2414 {
2415   GstState old_state, new_state;
2416   GstMessage *message;
2417
2418   g_return_if_fail (GST_IS_ELEMENT (element));
2419
2420   GST_OBJECT_LOCK (element);
2421   if (GST_STATE_RETURN (element) == GST_STATE_CHANGE_FAILURE)
2422     goto nothing_lost;
2423
2424   if (GST_STATE_PENDING (element) != GST_STATE_VOID_PENDING)
2425     goto only_async_start;
2426
2427   old_state = GST_STATE (element);
2428
2429   /* when we were PLAYING, the new state is PAUSED. We will also not
2430    * automatically go to PLAYING but let the parent bin(s) set us to PLAYING
2431    * when we preroll. */
2432   if (old_state > GST_STATE_PAUSED)
2433     new_state = GST_STATE_PAUSED;
2434   else
2435     new_state = old_state;
2436
2437   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2438       "lost state of %s to %s", gst_element_state_get_name (old_state),
2439       gst_element_state_get_name (new_state));
2440
2441   GST_STATE (element) = new_state;
2442   GST_STATE_NEXT (element) = new_state;
2443   GST_STATE_PENDING (element) = new_state;
2444   GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2445   GST_OBJECT_UNLOCK (element);
2446
2447   _priv_gst_element_state_changed (element, new_state, new_state, new_state);
2448
2449   message = gst_message_new_async_start (GST_OBJECT_CAST (element));
2450   gst_element_post_message (element, message);
2451
2452   return;
2453
2454 nothing_lost:
2455   {
2456     GST_OBJECT_UNLOCK (element);
2457     return;
2458   }
2459 only_async_start:
2460   {
2461     GST_OBJECT_UNLOCK (element);
2462
2463     message = gst_message_new_async_start (GST_OBJECT_CAST (element));
2464     gst_element_post_message (element, message);
2465     return;
2466   }
2467 }
2468
2469 /**
2470  * gst_element_set_state:
2471  * @element: a #GstElement to change state of.
2472  * @state: the element's new #GstState.
2473  *
2474  * Sets the state of the element. This function will try to set the
2475  * requested state by going through all the intermediary states and calling
2476  * the class's state change function for each.
2477  *
2478  * This function can return #GST_STATE_CHANGE_ASYNC, in which case the
2479  * element will perform the remainder of the state change asynchronously in
2480  * another thread.
2481  * An application can use gst_element_get_state() to wait for the completion
2482  * of the state change or it can wait for a %GST_MESSAGE_ASYNC_DONE or
2483  * %GST_MESSAGE_STATE_CHANGED on the bus.
2484  *
2485  * State changes to %GST_STATE_READY or %GST_STATE_NULL never return
2486  * #GST_STATE_CHANGE_ASYNC.
2487  *
2488  * Returns: Result of the state change using #GstStateChangeReturn.
2489  *
2490  * MT safe.
2491  */
2492 GstStateChangeReturn
2493 gst_element_set_state (GstElement * element, GstState state)
2494 {
2495   GstElementClass *oclass;
2496   GstStateChangeReturn result = GST_STATE_CHANGE_FAILURE;
2497
2498   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2499
2500   oclass = GST_ELEMENT_GET_CLASS (element);
2501
2502   if (oclass->set_state)
2503     result = (oclass->set_state) (element, state);
2504
2505   return result;
2506 }
2507
2508 /*
2509  * default set state function, calculates the next state based
2510  * on current state and calls the change_state function
2511  */
2512 static GstStateChangeReturn
2513 gst_element_set_state_func (GstElement * element, GstState state)
2514 {
2515   GstState current, next, old_pending;
2516   GstStateChangeReturn ret;
2517   GstStateChange transition;
2518   GstStateChangeReturn old_ret;
2519
2520   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2521
2522   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "set_state to %s",
2523       gst_element_state_get_name (state));
2524
2525   /* state lock is taken to protect the set_state() and get_state()
2526    * procedures, it does not lock any variables. */
2527   GST_STATE_LOCK (element);
2528
2529   /* now calculate how to get to the new state */
2530   GST_OBJECT_LOCK (element);
2531   old_ret = GST_STATE_RETURN (element);
2532   /* previous state change returned an error, remove all pending
2533    * and next states */
2534   if (old_ret == GST_STATE_CHANGE_FAILURE) {
2535     GST_STATE_NEXT (element) = GST_STATE_VOID_PENDING;
2536     GST_STATE_PENDING (element) = GST_STATE_VOID_PENDING;
2537     GST_STATE_RETURN (element) = GST_STATE_CHANGE_SUCCESS;
2538   }
2539
2540   current = GST_STATE (element);
2541   next = GST_STATE_NEXT (element);
2542   old_pending = GST_STATE_PENDING (element);
2543
2544   /* this is the (new) state we should go to. TARGET is the last state we set on
2545    * the element. */
2546   if (state != GST_STATE_TARGET (element)) {
2547     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2548         "setting target state to %s", gst_element_state_get_name (state));
2549     GST_STATE_TARGET (element) = state;
2550     /* increment state cookie so that we can track each state change. We only do
2551      * this if this is actually a new state change. */
2552     element->state_cookie++;
2553   }
2554   GST_STATE_PENDING (element) = state;
2555
2556   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2557       "current %s, old_pending %s, next %s, old return %s",
2558       gst_element_state_get_name (current),
2559       gst_element_state_get_name (old_pending),
2560       gst_element_state_get_name (next),
2561       gst_element_state_change_return_get_name (old_ret));
2562
2563   /* if the element was busy doing a state change, we just update the
2564    * target state, it'll get to it async then. */
2565   if (old_pending != GST_STATE_VOID_PENDING) {
2566     /* upwards state change will happen ASYNC */
2567     if (old_pending <= state)
2568       goto was_busy;
2569     /* element is going to this state already */
2570     else if (next == state)
2571       goto was_busy;
2572     /* element was performing an ASYNC upward state change and
2573      * we request to go downward again. Start from the next pending
2574      * state then. */
2575     else if (next > state
2576         && GST_STATE_RETURN (element) == GST_STATE_CHANGE_ASYNC) {
2577       current = next;
2578     }
2579   }
2580   next = GST_STATE_GET_NEXT (current, state);
2581   /* now we store the next state */
2582   GST_STATE_NEXT (element) = next;
2583   /* mark busy, we need to check that there is actually a state change
2584    * to be done else we could accidentally override SUCCESS/NO_PREROLL and
2585    * the default element change_state function has no way to know what the
2586    * old value was... could consider this a FIXME...*/
2587   if (current != next)
2588     GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2589
2590   transition = (GstStateChange) GST_STATE_TRANSITION (current, next);
2591
2592   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2593       "%s: setting state from %s to %s",
2594       (next != state ? "intermediate" : "final"),
2595       gst_element_state_get_name (current), gst_element_state_get_name (next));
2596
2597   /* now signal any waiters, they will error since the cookie was incremented */
2598   GST_STATE_BROADCAST (element);
2599
2600   GST_OBJECT_UNLOCK (element);
2601
2602   ret = gst_element_change_state (element, transition);
2603
2604   GST_STATE_UNLOCK (element);
2605
2606   GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element, "returned %s",
2607       gst_element_state_change_return_get_name (ret));
2608
2609   return ret;
2610
2611 was_busy:
2612   {
2613     GST_STATE_RETURN (element) = GST_STATE_CHANGE_ASYNC;
2614     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2615         "element was busy with async state change");
2616     GST_OBJECT_UNLOCK (element);
2617
2618     GST_STATE_UNLOCK (element);
2619
2620     return GST_STATE_CHANGE_ASYNC;
2621   }
2622 }
2623
2624 /**
2625  * gst_element_change_state:
2626  * @element: a #GstElement
2627  * @transition: the requested transition
2628  *
2629  * Perform @transition on @element.
2630  *
2631  * This function must be called with STATE_LOCK held and is mainly used
2632  * internally.
2633  *
2634  * Returns: the #GstStateChangeReturn of the state transition.
2635  */
2636 GstStateChangeReturn
2637 gst_element_change_state (GstElement * element, GstStateChange transition)
2638 {
2639   GstElementClass *oclass;
2640   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2641
2642   oclass = GST_ELEMENT_GET_CLASS (element);
2643
2644   GST_TRACER_ELEMENT_CHANGE_STATE_PRE (element, transition);
2645
2646   /* call the state change function so it can set the state */
2647   if (oclass->change_state)
2648     ret = (oclass->change_state) (element, transition);
2649   else
2650     ret = GST_STATE_CHANGE_FAILURE;
2651
2652   GST_TRACER_ELEMENT_CHANGE_STATE_POST (element, transition, ret);
2653
2654   switch (ret) {
2655     case GST_STATE_CHANGE_FAILURE:
2656       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2657           "have FAILURE change_state return");
2658       /* state change failure */
2659       gst_element_abort_state (element);
2660       break;
2661     case GST_STATE_CHANGE_ASYNC:
2662     {
2663       GstState target;
2664
2665       GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2666           "element will change state ASYNC");
2667
2668       target = GST_STATE_TARGET (element);
2669
2670       if (target > GST_STATE_READY)
2671         goto async;
2672
2673       /* else we just continue the state change downwards */
2674       GST_CAT_INFO_OBJECT (GST_CAT_STATES, element,
2675           "forcing commit state %s <= %s",
2676           gst_element_state_get_name (target),
2677           gst_element_state_get_name (GST_STATE_READY));
2678
2679       ret = gst_element_continue_state (element, GST_STATE_CHANGE_SUCCESS);
2680       break;
2681     }
2682     case GST_STATE_CHANGE_SUCCESS:
2683       GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2684           "element changed state SUCCESS");
2685       /* we can commit the state now which will proceeed to
2686        * the next state */
2687       ret = gst_element_continue_state (element, ret);
2688       break;
2689     case GST_STATE_CHANGE_NO_PREROLL:
2690       GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2691           "element changed state NO_PREROLL");
2692       /* we can commit the state now which will proceeed to
2693        * the next state */
2694       ret = gst_element_continue_state (element, ret);
2695       break;
2696     default:
2697       goto invalid_return;
2698   }
2699
2700   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "exit state change %d", ret);
2701
2702   return ret;
2703
2704 async:
2705   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "exit async state change %d",
2706       ret);
2707
2708   return ret;
2709
2710   /* ERROR */
2711 invalid_return:
2712   {
2713     GST_OBJECT_LOCK (element);
2714     /* somebody added a GST_STATE_ and forgot to do stuff here ! */
2715     g_critical ("%s: unknown return value %d from a state change function",
2716         GST_ELEMENT_NAME (element), ret);
2717
2718     /* we are in error now */
2719     ret = GST_STATE_CHANGE_FAILURE;
2720     GST_STATE_RETURN (element) = ret;
2721     GST_OBJECT_UNLOCK (element);
2722
2723     return ret;
2724   }
2725 }
2726
2727 /* gst_iterator_fold functions for pads_activate
2728  * Stop the iterator if activating one pad failed, but only if that pad
2729  * has not been removed from the element. */
2730 static gboolean
2731 activate_pads (const GValue * vpad, GValue * ret, gboolean * active)
2732 {
2733   GstPad *pad = g_value_get_object (vpad);
2734   gboolean cont = TRUE;
2735
2736   if (!gst_pad_set_active (pad, *active)) {
2737     if (GST_PAD_PARENT (pad) != NULL) {
2738       cont = FALSE;
2739       g_value_set_boolean (ret, FALSE);
2740     }
2741   }
2742
2743   return cont;
2744 }
2745
2746 /* returns false on error or early cutout of the fold, true if all
2747  * pads in @iter were (de)activated successfully. */
2748 static gboolean
2749 iterator_activate_fold_with_resync (GstIterator * iter,
2750     GstIteratorFoldFunction func, gpointer user_data)
2751 {
2752   GstIteratorResult ires;
2753   GValue ret = { 0 };
2754
2755   /* no need to unset this later, it's just a boolean */
2756   g_value_init (&ret, G_TYPE_BOOLEAN);
2757   g_value_set_boolean (&ret, TRUE);
2758
2759   while (1) {
2760     ires = gst_iterator_fold (iter, func, &ret, user_data);
2761     switch (ires) {
2762       case GST_ITERATOR_RESYNC:
2763         /* need to reset the result again */
2764         g_value_set_boolean (&ret, TRUE);
2765         gst_iterator_resync (iter);
2766         break;
2767       case GST_ITERATOR_DONE:
2768         /* all pads iterated, return collected value */
2769         goto done;
2770       default:
2771         /* iterator returned _ERROR or premature end with _OK,
2772          * mark an error and exit */
2773         g_value_set_boolean (&ret, FALSE);
2774         goto done;
2775     }
2776   }
2777 done:
2778   /* return collected value */
2779   return g_value_get_boolean (&ret);
2780 }
2781
2782 /* is called with STATE_LOCK
2783  *
2784  * Pads are activated from source pads to sinkpads.
2785  */
2786 static gboolean
2787 gst_element_pads_activate (GstElement * element, gboolean active)
2788 {
2789   GstIterator *iter;
2790   gboolean res;
2791
2792   GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2793       "%s pads", active ? "activate" : "deactivate");
2794
2795   iter = gst_element_iterate_src_pads (element);
2796   res =
2797       iterator_activate_fold_with_resync (iter,
2798       (GstIteratorFoldFunction) activate_pads, &active);
2799   gst_iterator_free (iter);
2800   if (G_UNLIKELY (!res))
2801     goto src_failed;
2802
2803   iter = gst_element_iterate_sink_pads (element);
2804   res =
2805       iterator_activate_fold_with_resync (iter,
2806       (GstIteratorFoldFunction) activate_pads, &active);
2807   gst_iterator_free (iter);
2808   if (G_UNLIKELY (!res))
2809     goto sink_failed;
2810
2811   GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2812       "pad %sactivation successful", active ? "" : "de");
2813
2814   return TRUE;
2815
2816   /* ERRORS */
2817 src_failed:
2818   {
2819     GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2820         "pad %sactivation failed", active ? "" : "de");
2821     return FALSE;
2822   }
2823 sink_failed:
2824   {
2825     GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2826         "sink pads_activate failed");
2827     return FALSE;
2828   }
2829 }
2830
2831 /* is called with STATE_LOCK */
2832 static GstStateChangeReturn
2833 gst_element_change_state_func (GstElement * element, GstStateChange transition)
2834 {
2835   GstState state, next;
2836   GstStateChangeReturn result = GST_STATE_CHANGE_SUCCESS;
2837
2838   g_return_val_if_fail (GST_IS_ELEMENT (element), GST_STATE_CHANGE_FAILURE);
2839
2840   state = (GstState) GST_STATE_TRANSITION_CURRENT (transition);
2841   next = GST_STATE_TRANSITION_NEXT (transition);
2842
2843   /* if the element already is in the given state, we just return success */
2844   if (next == GST_STATE_VOID_PENDING || state == next)
2845     goto was_ok;
2846
2847   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element,
2848       "default handler tries setting state from %s to %s (%04x)",
2849       gst_element_state_get_name (state),
2850       gst_element_state_get_name (next), transition);
2851
2852   switch (transition) {
2853     case GST_STATE_CHANGE_NULL_TO_READY:
2854       break;
2855     case GST_STATE_CHANGE_READY_TO_PAUSED:
2856       if (!gst_element_pads_activate (element, TRUE)) {
2857         result = GST_STATE_CHANGE_FAILURE;
2858       }
2859       break;
2860     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2861       break;
2862     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2863       break;
2864     case GST_STATE_CHANGE_PAUSED_TO_READY:
2865     case GST_STATE_CHANGE_READY_TO_NULL:{
2866       GList *l;
2867
2868       /* deactivate pads in both cases, since they are activated on
2869          ready->paused but the element might not have made it to paused */
2870       if (!gst_element_pads_activate (element, FALSE)) {
2871         result = GST_STATE_CHANGE_FAILURE;
2872       }
2873
2874       /* Remove all non-persistent contexts */
2875       GST_OBJECT_LOCK (element);
2876       for (l = element->contexts; l;) {
2877         GstContext *context = l->data;
2878
2879         if (!gst_context_is_persistent (context)) {
2880           GList *next;
2881
2882           gst_context_unref (context);
2883           next = l->next;
2884           element->contexts = g_list_delete_link (element->contexts, l);
2885           l = next;
2886         } else {
2887           l = l->next;
2888         }
2889       }
2890       GST_OBJECT_UNLOCK (element);
2891       break;
2892     }
2893     default:
2894       /* this will catch real but unhandled state changes;
2895        * can only be caused by:
2896        * - a new state was added
2897        * - somehow the element was asked to jump across an intermediate state
2898        */
2899       g_warning ("Unhandled state change from %s to %s",
2900           gst_element_state_get_name (state),
2901           gst_element_state_get_name (next));
2902       break;
2903   }
2904   return result;
2905
2906 was_ok:
2907   {
2908     GST_OBJECT_LOCK (element);
2909     result = GST_STATE_RETURN (element);
2910     GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, element,
2911         "element is already in the %s state",
2912         gst_element_state_get_name (state));
2913     GST_OBJECT_UNLOCK (element);
2914
2915     return result;
2916   }
2917 }
2918
2919 /**
2920  * gst_element_get_factory:
2921  * @element: a #GstElement to request the element factory of.
2922  *
2923  * Retrieves the factory that was used to create this element.
2924  *
2925  * Returns: (transfer none): the #GstElementFactory used for creating this
2926  *     element. no refcounting is needed.
2927  */
2928 GstElementFactory *
2929 gst_element_get_factory (GstElement * element)
2930 {
2931   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
2932
2933   return GST_ELEMENT_GET_CLASS (element)->elementfactory;
2934 }
2935
2936 static void
2937 gst_element_dispose (GObject * object)
2938 {
2939   GstElement *element = GST_ELEMENT_CAST (object);
2940   GstClock **clock_p;
2941   GstBus **bus_p;
2942   GstElementClass *oclass;
2943   GList *walk;
2944
2945   oclass = GST_ELEMENT_GET_CLASS (element);
2946
2947   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "%p dispose", element);
2948
2949   if (GST_STATE (element) != GST_STATE_NULL)
2950     goto not_null;
2951
2952   /* start by releasing all request pads, this might also remove some dynamic
2953    * pads */
2954   walk = element->pads;
2955   while (walk) {
2956     GstPad *pad = GST_PAD_CAST (walk->data);
2957
2958     walk = walk->next;
2959
2960     if (oclass->release_pad && GST_PAD_PAD_TEMPLATE (pad) &&
2961         GST_PAD_TEMPLATE_PRESENCE (GST_PAD_PAD_TEMPLATE (pad))
2962         == GST_PAD_REQUEST) {
2963       GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2964           "removing request pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2965       oclass->release_pad (element, pad);
2966
2967       /* in case the release_pad function removed the next pad too */
2968       if (walk && g_list_position (element->pads, walk) == -1)
2969         walk = element->pads;
2970     }
2971   }
2972   /* remove the remaining pads */
2973   while (element->pads) {
2974     GstPad *pad = GST_PAD_CAST (element->pads->data);
2975     GST_CAT_DEBUG_OBJECT (GST_CAT_ELEMENT_PADS, element,
2976         "removing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2977     if (!gst_element_remove_pad (element, pad)) {
2978       /* only happens when someone unparented our pad.. */
2979       g_critical ("failed to remove pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2980       break;
2981     }
2982   }
2983
2984   GST_OBJECT_LOCK (element);
2985   clock_p = &element->clock;
2986   bus_p = &element->bus;
2987   gst_object_replace ((GstObject **) clock_p, NULL);
2988   gst_object_replace ((GstObject **) bus_p, NULL);
2989   g_list_free_full (element->contexts, (GDestroyNotify) gst_context_unref);
2990   GST_OBJECT_UNLOCK (element);
2991
2992   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "%p parent class dispose",
2993       element);
2994
2995   G_OBJECT_CLASS (parent_class)->dispose (object);
2996
2997   return;
2998
2999   /* ERRORS */
3000 not_null:
3001   {
3002     gboolean is_locked;
3003
3004     is_locked = GST_ELEMENT_IS_LOCKED_STATE (element);
3005     g_critical
3006         ("\nTrying to dispose element %s, but it is in %s%s instead of the NULL"
3007         " state.\n"
3008         "You need to explicitly set elements to the NULL state before\n"
3009         "dropping the final reference, to allow them to clean up.\n"
3010         "This problem may also be caused by a refcounting bug in the\n"
3011         "application or some element.\n",
3012         GST_OBJECT_NAME (element),
3013         gst_element_state_get_name (GST_STATE (element)),
3014         is_locked ? " (locked)" : "");
3015     return;
3016   }
3017 }
3018
3019 static void
3020 gst_element_finalize (GObject * object)
3021 {
3022   GstElement *element = GST_ELEMENT_CAST (object);
3023
3024   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "%p finalize", element);
3025
3026   g_cond_clear (&element->state_cond);
3027   g_rec_mutex_clear (&element->state_lock);
3028
3029   GST_CAT_INFO_OBJECT (GST_CAT_REFCOUNTING, element, "%p finalize parent",
3030       element);
3031
3032   G_OBJECT_CLASS (parent_class)->finalize (object);
3033 }
3034
3035 static void
3036 gst_element_set_bus_func (GstElement * element, GstBus * bus)
3037 {
3038   GstBus **bus_p;
3039
3040   g_return_if_fail (GST_IS_ELEMENT (element));
3041
3042   GST_CAT_DEBUG_OBJECT (GST_CAT_PARENTAGE, element, "setting bus to %p", bus);
3043
3044   GST_OBJECT_LOCK (element);
3045   bus_p = &GST_ELEMENT_BUS (element);
3046   gst_object_replace ((GstObject **) bus_p, GST_OBJECT_CAST (bus));
3047   GST_OBJECT_UNLOCK (element);
3048 }
3049
3050 /**
3051  * gst_element_set_bus:
3052  * @element: a #GstElement to set the bus of.
3053  * @bus: (transfer none): the #GstBus to set.
3054  *
3055  * Sets the bus of the element. Increases the refcount on the bus.
3056  * For internal use only, unless you're testing elements.
3057  *
3058  * MT safe.
3059  */
3060 void
3061 gst_element_set_bus (GstElement * element, GstBus * bus)
3062 {
3063   GstElementClass *oclass;
3064
3065   g_return_if_fail (GST_IS_ELEMENT (element));
3066
3067   oclass = GST_ELEMENT_GET_CLASS (element);
3068
3069   if (oclass->set_bus)
3070     oclass->set_bus (element, bus);
3071 }
3072
3073 /**
3074  * gst_element_get_bus:
3075  * @element: a #GstElement to get the bus of.
3076  *
3077  * Returns the bus of the element. Note that only a #GstPipeline will provide a
3078  * bus for the application.
3079  *
3080  * Returns: (transfer full): the element's #GstBus. unref after usage.
3081  *
3082  * MT safe.
3083  */
3084 GstBus *
3085 gst_element_get_bus (GstElement * element)
3086 {
3087   GstBus *result = NULL;
3088
3089   g_return_val_if_fail (GST_IS_ELEMENT (element), result);
3090
3091   GST_OBJECT_LOCK (element);
3092   if ((result = GST_ELEMENT_BUS (element)))
3093     gst_object_ref (result);
3094   GST_OBJECT_UNLOCK (element);
3095
3096   GST_CAT_DEBUG_OBJECT (GST_CAT_BUS, element, "got bus %" GST_PTR_FORMAT,
3097       result);
3098
3099   return result;
3100 }
3101
3102 static void
3103 gst_element_set_context_default (GstElement * element, GstContext * context)
3104 {
3105   const gchar *context_type;
3106   GList *l;
3107
3108   GST_OBJECT_LOCK (element);
3109   context_type = gst_context_get_context_type (context);
3110   for (l = element->contexts; l; l = l->next) {
3111     GstContext *tmp = l->data;
3112     const gchar *tmp_type = gst_context_get_context_type (tmp);
3113
3114     /* Always store newest context but never replace
3115      * a persistent one by a non-persistent one */
3116     if (strcmp (context_type, tmp_type) == 0 &&
3117         (gst_context_is_persistent (context) ||
3118             !gst_context_is_persistent (tmp))) {
3119       gst_context_replace ((GstContext **) & l->data, context);
3120       break;
3121     }
3122   }
3123   /* Not found? Add */
3124   if (l == NULL) {
3125     element->contexts =
3126         g_list_prepend (element->contexts, gst_context_ref (context));
3127   }
3128   GST_OBJECT_UNLOCK (element);
3129 }
3130
3131 /**
3132  * gst_element_set_context:
3133  * @element: a #GstElement to set the context of.
3134  * @context: (transfer none): the #GstContext to set.
3135  *
3136  * Sets the context of the element. Increases the refcount of the context.
3137  *
3138  * MT safe.
3139  */
3140 void
3141 gst_element_set_context (GstElement * element, GstContext * context)
3142 {
3143   GstElementClass *oclass;
3144
3145   g_return_if_fail (GST_IS_ELEMENT (element));
3146
3147   oclass = GST_ELEMENT_GET_CLASS (element);
3148
3149   GST_CAT_DEBUG_OBJECT (GST_CAT_CONTEXT, element,
3150       "set context %p %" GST_PTR_FORMAT, context,
3151       gst_context_get_structure (context));
3152
3153   if (oclass->set_context)
3154     oclass->set_context (element, context);
3155 }
3156
3157 /**
3158  * gst_element_get_contexts:
3159  * @element: a #GstElement to set the context of.
3160  *
3161  * Gets the contexts set on the element.
3162  *
3163  * MT safe.
3164  *
3165  * Returns: (element-type Gst.Context) (transfer full): List of #GstContext
3166  *
3167  * Since: 1.8
3168  */
3169 GList *
3170 gst_element_get_contexts (GstElement * element)
3171 {
3172   GList *ret;
3173
3174   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
3175
3176   GST_OBJECT_LOCK (element);
3177   ret = g_list_copy_deep (element->contexts, (GCopyFunc) gst_context_ref, NULL);
3178   GST_OBJECT_UNLOCK (element);
3179
3180   return ret;
3181 }
3182
3183 static gint
3184 _match_context_type (GstContext * c1, const gchar * context_type)
3185 {
3186   const gchar *c1_type;
3187
3188   c1_type = gst_context_get_context_type (c1);
3189
3190   return g_strcmp0 (c1_type, context_type);
3191 }
3192
3193 /**
3194  * gst_element_get_context_unlocked:
3195  * @element: a #GstElement to get the context of.
3196  * @context_type: a name of a context to retrieve
3197  *
3198  * Gets the context with @context_type set on the element or NULL.
3199  *
3200  * Returns: (transfer full): A #GstContext or NULL
3201  *
3202  * Since: 1.8
3203  */
3204 GstContext *
3205 gst_element_get_context_unlocked (GstElement * element,
3206     const gchar * context_type)
3207 {
3208   GstContext *ret = NULL;
3209   GList *node;
3210
3211   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
3212
3213   node =
3214       g_list_find_custom (element->contexts, context_type,
3215       (GCompareFunc) _match_context_type);
3216   if (node && node->data)
3217     ret = gst_context_ref (node->data);
3218
3219   return ret;
3220 }
3221
3222 /**
3223  * gst_element_get_context:
3224  * @element: a #GstElement to get the context of.
3225  * @context_type: a name of a context to retrieve
3226  *
3227  * Gets the context with @context_type set on the element or NULL.
3228  *
3229  * MT safe.
3230  *
3231  * Returns: (transfer full): A #GstContext or NULL
3232  *
3233  * Since: 1.8
3234  */
3235 GstContext *
3236 gst_element_get_context (GstElement * element, const gchar * context_type)
3237 {
3238   GstContext *ret = NULL;
3239
3240   g_return_val_if_fail (GST_IS_ELEMENT (element), NULL);
3241
3242   GST_OBJECT_LOCK (element);
3243   ret = gst_element_get_context_unlocked (element, context_type);
3244   GST_OBJECT_UNLOCK (element);
3245
3246   return ret;
3247 }