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