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