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