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