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