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