0f352d4ab40d027a0e87a8c785aad50bafa93e58
[platform/upstream/gstreamer.git] / libs / gst / base / gstbasesrc.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *               2000,2005 Wim Taymans <wim@fluendo.com>
4  *
5  * gstbasesrc.c:
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., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gstbasesrc
25  * @short_description: Base class for getrange based source elements
26  * @see_also: #GstPushSrc, #GstBaseTransform, #GstBaseSink
27  *
28  * This is a generice base class for source elements. The following
29  * types of sources are supported:
30  * <itemizedlist>
31  *   <listitem><para>random access sources like files</para></listitem>
32  *   <listitem><para>seekable sources</para></listitem>
33  *   <listitem><para>live sources</para></listitem>
34  * </itemizedlist>
35  *
36  * The source can be configured to operate in any #GstFormat with the
37  * gst_base_src_set_format() method. The currently set format determines
38  * the format of the internal #GstSegment and any #GST_EVENT_NEWSEGMENT
39  * events. The default format for #GstBaseSrc is #GST_FORMAT_BYTES.
40  *
41  * #GstBaseSrc always supports push mode scheduling. If the following
42  * conditions are met, it also supports pull mode scheduling:
43  * <itemizedlist>
44  *   <listitem><para>The format is set to #GST_FORMAT_BYTES (default).</para>
45  *   </listitem>
46  *   <listitem><para>#GstBaseSrcClass.is_seekable() returns %TRUE.</para>
47  *   </listitem>
48  * </itemizedlist>
49  *
50  * Since 0.10.9, any #GstBaseSrc can enable pull based scheduling at any time
51  * by overriding #GstBaseSrcClass.check_get_range() so that it returns %TRUE.
52  *
53  * If all the conditions are met for operating in pull mode, #GstBaseSrc is
54  * automatically seekable in push mode as well. The following conditions must
55  * be met to make the element seekable in push mode when the format is not
56  * #GST_FORMAT_BYTES:
57  * <itemizedlist>
58  *   <listitem><para>
59  *     #GstBaseSrcClass.is_seekable() returns %TRUE.
60  *   </para></listitem>
61  *   <listitem><para>
62  *     #GstBaseSrcClass.query() can convert all supported seek formats to the
63  *     internal format as set with gst_base_src_set_format().
64  *   </para></listitem>
65  *   <listitem><para>
66  *     #GstBaseSrcClass.do_seek() is implemented, performs the seek and returns
67  *      %TRUE.
68  *   </para></listitem>
69  * </itemizedlist>
70  *
71  * When the element does not meet the requirements to operate in pull mode, the
72  * offset and length in the #GstBaseSrcClass.create() method should be ignored.
73  * It is recommended to subclass #GstPushSrc instead, in this situation. If the
74  * element can operate in pull mode but only with specific offsets and
75  * lengths, it is allowed to generate an error when the wrong values are passed
76  * to the #GstBaseSrcClass.create() function.
77  *
78  * #GstBaseSrc has support for live sources. Live sources are sources that when
79  * paused discard data, such as audio or video capture devices. A typical live
80  * source also produces data at a fixed rate and thus provides a clock to publish
81  * this rate.
82  * Use gst_base_src_set_live() to activate the live source mode.
83  *
84  * A live source does not produce data in the PAUSED state. This means that the
85  * #GstBaseSrcClass.create() method will not be called in PAUSED but only in
86  * PLAYING. To signal the pipeline that the element will not produce data, the
87  * return value from the READY to PAUSED state will be
88  * #GST_STATE_CHANGE_NO_PREROLL.
89  *
90  * A typical live source will timestamp the buffers it creates with the
91  * current running time of the pipeline. This is one reason why a live source
92  * can only produce data in the PLAYING state, when the clock is actually
93  * distributed and running.
94  *
95  * Live sources that synchronize and block on the clock (an audio source, for
96  * example) can since 0.10.12 use gst_base_src_wait_playing() when the
97  * #GstBaseSrcClass.create() function was interrupted by a state change to
98  * PAUSED.
99  *
100  * The #GstBaseSrcClass.get_times() method can be used to implement pseudo-live
101  * sources. It only makes sense to implement the #GstBaseSrcClass.get_times()
102  * function if the source is a live source. The #GstBaseSrcClass.get_times()
103  * function should return timestamps starting from 0, as if it were a non-live
104  * source. The base class will make sure that the timestamps are transformed
105  * into the current running_time. The base source will then wait for the
106  * calculated running_time before pushing out the buffer.
107  *
108  * For live sources, the base class will by default report a latency of 0.
109  * For pseudo live sources, the base class will by default measure the difference
110  * between the first buffer timestamp and the start time of get_times and will
111  * report this value as the latency.
112  * Subclasses should override the query function when this behaviour is not
113  * acceptable.
114  *
115  * There is only support in #GstBaseSrc for exactly one source pad, which
116  * should be named "src". A source implementation (subclass of #GstBaseSrc)
117  * should install a pad template in its class_init function, like so:
118  * |[
119  * static void
120  * my_element_class_init (GstMyElementClass *klass)
121  * {
122  *   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
123  *   // srctemplate should be a #GstStaticPadTemplate with direction
124  *   // #GST_PAD_SRC and name "src"
125  *   gst_element_class_add_pad_template (gstelement_class,
126  *       gst_static_pad_template_get (&amp;srctemplate));
127  *   // see #GstElementDetails
128  *   gst_element_class_set_details (gstelement_class, &amp;details);
129  * }
130  * ]|
131  *
132  * <refsect2>
133  * <title>Controlled shutdown of live sources in applications</title>
134  * <para>
135  * Applications that record from a live source may want to stop recording
136  * in a controlled way, so that the recording is stopped, but the data
137  * already in the pipeline is processed to the end (remember that many live
138  * sources would go on recording forever otherwise). For that to happen the
139  * application needs to make the source stop recording and send an EOS
140  * event down the pipeline. The application would then wait for an
141  * EOS message posted on the pipeline's bus to know when all data has
142  * been processed and the pipeline can safely be stopped.
143  *
144  * Since GStreamer 0.10.16 an application may send an EOS event to a source
145  * element to make it perform the EOS logic (send EOS event downstream or post a
146  * #GST_MESSAGE_SEGMENT_DONE on the bus). This can typically be done
147  * with the gst_element_send_event() function on the element or its parent bin.
148  *
149  * After the EOS has been sent to the element, the application should wait for
150  * an EOS message to be posted on the pipeline's bus. Once this EOS message is
151  * received, it may safely shut down the entire pipeline.
152  *
153  * The old behaviour for controlled shutdown introduced since GStreamer 0.10.3
154  * is still available but deprecated as it is dangerous and less flexible.
155  *
156  * Last reviewed on 2007-12-19 (0.10.16)
157  * </para>
158  * </refsect2>
159  */
160
161 #ifdef HAVE_CONFIG_H
162 #  include "config.h"
163 #endif
164
165 #include <stdlib.h>
166 #include <string.h>
167
168 /* FIXME 0.11: suppress warnings for deprecated API such as GStaticRecMutex
169  * with newer GLib versions (>= 2.31.0) */
170 #define GLIB_DISABLE_DEPRECATION_WARNINGS
171 #include <gst/gst_private.h>
172 #include <gst/glib-compat-private.h>
173
174 #include "gstbasesrc.h"
175 #include "gsttypefindhelper.h"
176 #include <gst/gstmarshal.h>
177 #include <gst/gst-i18n-lib.h>
178
179 GST_DEBUG_CATEGORY_STATIC (gst_base_src_debug);
180 #define GST_CAT_DEFAULT gst_base_src_debug
181
182 #define GST_LIVE_GET_LOCK(elem)               (GST_BASE_SRC_CAST(elem)->live_lock)
183 #define GST_LIVE_LOCK(elem)                   g_mutex_lock(GST_LIVE_GET_LOCK(elem))
184 #define GST_LIVE_TRYLOCK(elem)                g_mutex_trylock(GST_LIVE_GET_LOCK(elem))
185 #define GST_LIVE_UNLOCK(elem)                 g_mutex_unlock(GST_LIVE_GET_LOCK(elem))
186 #define GST_LIVE_GET_COND(elem)               (GST_BASE_SRC_CAST(elem)->live_cond)
187 #define GST_LIVE_WAIT(elem)                   g_cond_wait (GST_LIVE_GET_COND (elem), GST_LIVE_GET_LOCK (elem))
188 #define GST_LIVE_TIMED_WAIT(elem, timeval)    g_cond_timed_wait (GST_LIVE_GET_COND (elem), GST_LIVE_GET_LOCK (elem),\
189                                                                                 timeval)
190 #define GST_LIVE_SIGNAL(elem)                 g_cond_signal (GST_LIVE_GET_COND (elem));
191 #define GST_LIVE_BROADCAST(elem)              g_cond_broadcast (GST_LIVE_GET_COND (elem));
192
193 /* BaseSrc signals and args */
194 enum
195 {
196   /* FILL ME */
197   LAST_SIGNAL
198 };
199
200 #define DEFAULT_BLOCKSIZE       4096
201 #define DEFAULT_NUM_BUFFERS     -1
202 #define DEFAULT_TYPEFIND        FALSE
203 #define DEFAULT_DO_TIMESTAMP    FALSE
204
205 enum
206 {
207   PROP_0,
208   PROP_BLOCKSIZE,
209   PROP_NUM_BUFFERS,
210   PROP_TYPEFIND,
211   PROP_DO_TIMESTAMP
212 };
213
214 #define GST_BASE_SRC_GET_PRIVATE(obj)  \
215    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_SRC, GstBaseSrcPrivate))
216
217 struct _GstBaseSrcPrivate
218 {
219   gboolean last_sent_eos;       /* last thing we did was send an EOS (we set this
220                                  * to avoid the sending of two EOS in some cases) */
221   gboolean discont;
222   gboolean flushing;
223
224   /* two segments to be sent in the streaming thread with STREAM_LOCK */
225   GstEvent *close_segment;
226   GstEvent *start_segment;
227   gboolean newsegment_pending;
228
229   /* if EOS is pending (atomic) */
230   gint pending_eos;
231
232   /* startup latency is the time it takes between going to PLAYING and producing
233    * the first BUFFER with running_time 0. This value is included in the latency
234    * reporting. */
235   GstClockTime latency;
236   /* timestamp offset, this is the offset add to the values of gst_times for
237    * pseudo live sources */
238   GstClockTimeDiff ts_offset;
239
240   gboolean do_timestamp;
241   volatile gint dynamic_size;
242
243   /* stream sequence number */
244   guint32 seqnum;
245
246   /* pending events (TAG, CUSTOM_BOTH, CUSTOM_DOWNSTREAM) to be
247    * pushed in the data stream */
248   GList *pending_events;
249   volatile gint have_events;
250
251   /* QoS *//* with LOCK */
252   gboolean qos_enabled;
253   gdouble proportion;
254   GstClockTime earliest_time;
255 };
256
257 static GstElementClass *parent_class = NULL;
258
259 static void gst_base_src_base_init (gpointer g_class);
260 static void gst_base_src_class_init (GstBaseSrcClass * klass);
261 static void gst_base_src_init (GstBaseSrc * src, gpointer g_class);
262 static void gst_base_src_finalize (GObject * object);
263
264
265 GType
266 gst_base_src_get_type (void)
267 {
268   static volatile gsize base_src_type = 0;
269
270   if (g_once_init_enter (&base_src_type)) {
271     GType _type;
272     static const GTypeInfo base_src_info = {
273       sizeof (GstBaseSrcClass),
274       (GBaseInitFunc) gst_base_src_base_init,
275       NULL,
276       (GClassInitFunc) gst_base_src_class_init,
277       NULL,
278       NULL,
279       sizeof (GstBaseSrc),
280       0,
281       (GInstanceInitFunc) gst_base_src_init,
282     };
283
284     _type = g_type_register_static (GST_TYPE_ELEMENT,
285         "GstBaseSrc", &base_src_info, G_TYPE_FLAG_ABSTRACT);
286     g_once_init_leave (&base_src_type, _type);
287   }
288   return base_src_type;
289 }
290
291 static GstCaps *gst_base_src_getcaps (GstPad * pad);
292 static gboolean gst_base_src_setcaps (GstPad * pad, GstCaps * caps);
293 static void gst_base_src_fixate (GstPad * pad, GstCaps * caps);
294
295 static gboolean gst_base_src_activate_push (GstPad * pad, gboolean active);
296 static gboolean gst_base_src_activate_pull (GstPad * pad, gboolean active);
297 static void gst_base_src_set_property (GObject * object, guint prop_id,
298     const GValue * value, GParamSpec * pspec);
299 static void gst_base_src_get_property (GObject * object, guint prop_id,
300     GValue * value, GParamSpec * pspec);
301 static gboolean gst_base_src_event_handler (GstPad * pad, GstEvent * event);
302 static gboolean gst_base_src_send_event (GstElement * elem, GstEvent * event);
303 static gboolean gst_base_src_default_event (GstBaseSrc * src, GstEvent * event);
304 static const GstQueryType *gst_base_src_get_query_types (GstElement * element);
305
306 static gboolean gst_base_src_query (GstPad * pad, GstQuery * query);
307
308 static gboolean gst_base_src_default_negotiate (GstBaseSrc * basesrc);
309 static gboolean gst_base_src_default_do_seek (GstBaseSrc * src,
310     GstSegment * segment);
311 static gboolean gst_base_src_default_query (GstBaseSrc * src, GstQuery * query);
312 static gboolean gst_base_src_default_prepare_seek_segment (GstBaseSrc * src,
313     GstEvent * event, GstSegment * segment);
314
315 static gboolean gst_base_src_set_flushing (GstBaseSrc * basesrc,
316     gboolean flushing, gboolean live_play, gboolean unlock, gboolean * playing);
317 static gboolean gst_base_src_start (GstBaseSrc * basesrc);
318 static gboolean gst_base_src_stop (GstBaseSrc * basesrc);
319
320 static GstStateChangeReturn gst_base_src_change_state (GstElement * element,
321     GstStateChange transition);
322
323 static void gst_base_src_loop (GstPad * pad);
324 static gboolean gst_base_src_pad_check_get_range (GstPad * pad);
325 static gboolean gst_base_src_default_check_get_range (GstBaseSrc * bsrc);
326 static GstFlowReturn gst_base_src_pad_get_range (GstPad * pad, guint64 offset,
327     guint length, GstBuffer ** buf);
328 static GstFlowReturn gst_base_src_get_range (GstBaseSrc * src, guint64 offset,
329     guint length, GstBuffer ** buf);
330 static gboolean gst_base_src_seekable (GstBaseSrc * src);
331 static gboolean gst_base_src_update_length (GstBaseSrc * src, guint64 offset,
332     guint * length);
333
334 static void
335 gst_base_src_base_init (gpointer g_class)
336 {
337   GST_DEBUG_CATEGORY_INIT (gst_base_src_debug, "basesrc", 0, "basesrc element");
338 }
339
340 static void
341 gst_base_src_class_init (GstBaseSrcClass * klass)
342 {
343   GObjectClass *gobject_class;
344   GstElementClass *gstelement_class;
345
346   gobject_class = G_OBJECT_CLASS (klass);
347   gstelement_class = GST_ELEMENT_CLASS (klass);
348
349   g_type_class_add_private (klass, sizeof (GstBaseSrcPrivate));
350
351   parent_class = g_type_class_peek_parent (klass);
352
353   gobject_class->finalize = gst_base_src_finalize;
354   gobject_class->set_property = gst_base_src_set_property;
355   gobject_class->get_property = gst_base_src_get_property;
356
357 /* FIXME 0.11: blocksize property should be int, not ulong (min is >max here) */
358   g_object_class_install_property (gobject_class, PROP_BLOCKSIZE,
359       g_param_spec_ulong ("blocksize", "Block size",
360           "Size in bytes to read per buffer (-1 = default)", 0, G_MAXULONG,
361           DEFAULT_BLOCKSIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
362   g_object_class_install_property (gobject_class, PROP_NUM_BUFFERS,
363       g_param_spec_int ("num-buffers", "num-buffers",
364           "Number of buffers to output before sending EOS (-1 = unlimited)",
365           -1, G_MAXINT, DEFAULT_NUM_BUFFERS, G_PARAM_READWRITE |
366           G_PARAM_STATIC_STRINGS));
367   g_object_class_install_property (gobject_class, PROP_TYPEFIND,
368       g_param_spec_boolean ("typefind", "Typefind",
369           "Run typefind before negotiating", DEFAULT_TYPEFIND,
370           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
371   g_object_class_install_property (gobject_class, PROP_DO_TIMESTAMP,
372       g_param_spec_boolean ("do-timestamp", "Do timestamp",
373           "Apply current stream time to buffers", DEFAULT_DO_TIMESTAMP,
374           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
375
376   gstelement_class->change_state =
377       GST_DEBUG_FUNCPTR (gst_base_src_change_state);
378   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_base_src_send_event);
379   gstelement_class->get_query_types =
380       GST_DEBUG_FUNCPTR (gst_base_src_get_query_types);
381
382   klass->negotiate = GST_DEBUG_FUNCPTR (gst_base_src_default_negotiate);
383   klass->event = GST_DEBUG_FUNCPTR (gst_base_src_default_event);
384   klass->do_seek = GST_DEBUG_FUNCPTR (gst_base_src_default_do_seek);
385   klass->query = GST_DEBUG_FUNCPTR (gst_base_src_default_query);
386   klass->check_get_range =
387       GST_DEBUG_FUNCPTR (gst_base_src_default_check_get_range);
388   klass->prepare_seek_segment =
389       GST_DEBUG_FUNCPTR (gst_base_src_default_prepare_seek_segment);
390
391   /* Registering debug symbols for function pointers */
392   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_activate_push);
393   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_activate_pull);
394   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_event_handler);
395   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_query);
396   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_pad_get_range);
397   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_pad_check_get_range);
398   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_getcaps);
399   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_setcaps);
400   GST_DEBUG_REGISTER_FUNCPTR (gst_base_src_fixate);
401 }
402
403 static void
404 gst_base_src_init (GstBaseSrc * basesrc, gpointer g_class)
405 {
406   GstPad *pad;
407   GstPadTemplate *pad_template;
408
409   basesrc->priv = GST_BASE_SRC_GET_PRIVATE (basesrc);
410
411   basesrc->is_live = FALSE;
412   basesrc->live_lock = g_mutex_new ();
413   basesrc->live_cond = g_cond_new ();
414   basesrc->num_buffers = DEFAULT_NUM_BUFFERS;
415   basesrc->num_buffers_left = -1;
416
417   basesrc->can_activate_push = TRUE;
418   basesrc->pad_mode = GST_ACTIVATE_NONE;
419
420   pad_template =
421       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (g_class), "src");
422   g_return_if_fail (pad_template != NULL);
423
424   GST_DEBUG_OBJECT (basesrc, "creating src pad");
425   pad = gst_pad_new_from_template (pad_template, "src");
426
427   GST_DEBUG_OBJECT (basesrc, "setting functions on src pad");
428   gst_pad_set_activatepush_function (pad, gst_base_src_activate_push);
429   gst_pad_set_activatepull_function (pad, gst_base_src_activate_pull);
430   gst_pad_set_event_function (pad, gst_base_src_event_handler);
431   gst_pad_set_query_function (pad, gst_base_src_query);
432   gst_pad_set_checkgetrange_function (pad, gst_base_src_pad_check_get_range);
433   gst_pad_set_getrange_function (pad, gst_base_src_pad_get_range);
434   gst_pad_set_getcaps_function (pad, gst_base_src_getcaps);
435   gst_pad_set_setcaps_function (pad, gst_base_src_setcaps);
436   gst_pad_set_fixatecaps_function (pad, gst_base_src_fixate);
437
438   /* hold pointer to pad */
439   basesrc->srcpad = pad;
440   GST_DEBUG_OBJECT (basesrc, "adding src pad");
441   gst_element_add_pad (GST_ELEMENT (basesrc), pad);
442
443   basesrc->blocksize = DEFAULT_BLOCKSIZE;
444   basesrc->clock_id = NULL;
445   /* we operate in BYTES by default */
446   gst_base_src_set_format (basesrc, GST_FORMAT_BYTES);
447   basesrc->data.ABI.typefind = DEFAULT_TYPEFIND;
448   basesrc->priv->do_timestamp = DEFAULT_DO_TIMESTAMP;
449   g_atomic_int_set (&basesrc->priv->have_events, FALSE);
450
451   GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_STARTED);
452   GST_OBJECT_FLAG_SET (basesrc, GST_ELEMENT_IS_SOURCE);
453
454   GST_DEBUG_OBJECT (basesrc, "init done");
455 }
456
457 static void
458 gst_base_src_finalize (GObject * object)
459 {
460   GstBaseSrc *basesrc;
461   GstEvent **event_p;
462
463   basesrc = GST_BASE_SRC (object);
464
465   g_mutex_free (basesrc->live_lock);
466   g_cond_free (basesrc->live_cond);
467
468   event_p = &basesrc->data.ABI.pending_seek;
469   gst_event_replace (event_p, NULL);
470
471   if (basesrc->priv->pending_events) {
472     g_list_foreach (basesrc->priv->pending_events, (GFunc) gst_event_unref,
473         NULL);
474     g_list_free (basesrc->priv->pending_events);
475   }
476
477   G_OBJECT_CLASS (parent_class)->finalize (object);
478 }
479
480 /**
481  * gst_base_src_wait_playing:
482  * @src: the src
483  *
484  * If the #GstBaseSrcClass.create() method performs its own synchronisation
485  * against the clock it must unblock when going from PLAYING to the PAUSED state
486  * and call this method before continuing to produce the remaining data.
487  *
488  * This function will block until a state change to PLAYING happens (in which
489  * case this function returns #GST_FLOW_OK) or the processing must be stopped due
490  * to a state change to READY or a FLUSH event (in which case this function
491  * returns #GST_FLOW_WRONG_STATE).
492  *
493  * Since: 0.10.12
494  *
495  * Returns: #GST_FLOW_OK if @src is PLAYING and processing can
496  * continue. Any other return value should be returned from the create vmethod.
497  */
498 GstFlowReturn
499 gst_base_src_wait_playing (GstBaseSrc * src)
500 {
501   g_return_val_if_fail (GST_IS_BASE_SRC (src), GST_FLOW_ERROR);
502
503   do {
504     /* block until the state changes, or we get a flush, or something */
505     GST_DEBUG_OBJECT (src, "live source waiting for running state");
506     GST_LIVE_WAIT (src);
507     GST_DEBUG_OBJECT (src, "live source unlocked");
508     if (src->priv->flushing)
509       goto flushing;
510   } while (G_UNLIKELY (!src->live_running));
511
512   return GST_FLOW_OK;
513
514   /* ERRORS */
515 flushing:
516   {
517     GST_DEBUG_OBJECT (src, "we are flushing");
518     return GST_FLOW_WRONG_STATE;
519   }
520 }
521
522 /**
523  * gst_base_src_set_live:
524  * @src: base source instance
525  * @live: new live-mode
526  *
527  * If the element listens to a live source, @live should
528  * be set to %TRUE.
529  *
530  * A live source will not produce data in the PAUSED state and
531  * will therefore not be able to participate in the PREROLL phase
532  * of a pipeline. To signal this fact to the application and the
533  * pipeline, the state change return value of the live source will
534  * be GST_STATE_CHANGE_NO_PREROLL.
535  */
536 void
537 gst_base_src_set_live (GstBaseSrc * src, gboolean live)
538 {
539   g_return_if_fail (GST_IS_BASE_SRC (src));
540
541   GST_OBJECT_LOCK (src);
542   src->is_live = live;
543   GST_OBJECT_UNLOCK (src);
544 }
545
546 /**
547  * gst_base_src_is_live:
548  * @src: base source instance
549  *
550  * Check if an element is in live mode.
551  *
552  * Returns: %TRUE if element is in live mode.
553  */
554 gboolean
555 gst_base_src_is_live (GstBaseSrc * src)
556 {
557   gboolean result;
558
559   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
560
561   GST_OBJECT_LOCK (src);
562   result = src->is_live;
563   GST_OBJECT_UNLOCK (src);
564
565   return result;
566 }
567
568 /**
569  * gst_base_src_set_format:
570  * @src: base source instance
571  * @format: the format to use
572  *
573  * Sets the default format of the source. This will be the format used
574  * for sending NEW_SEGMENT events and for performing seeks.
575  *
576  * If a format of GST_FORMAT_BYTES is set, the element will be able to
577  * operate in pull mode if the #GstBaseSrcClass.is_seekable() returns TRUE.
578  *
579  * This function must only be called in states < %GST_STATE_PAUSED.
580  *
581  * Since: 0.10.1
582  */
583 void
584 gst_base_src_set_format (GstBaseSrc * src, GstFormat format)
585 {
586   g_return_if_fail (GST_IS_BASE_SRC (src));
587   g_return_if_fail (GST_STATE (src) <= GST_STATE_READY);
588
589   GST_OBJECT_LOCK (src);
590   gst_segment_init (&src->segment, format);
591   GST_OBJECT_UNLOCK (src);
592 }
593
594 /**
595  * gst_base_src_set_dynamic_size:
596  * @src: base source instance
597  * @dynamic: new dynamic size mode
598  *
599  * If not @dynamic, size is only updated when needed, such as when trying to
600  * read past current tracked size.  Otherwise, size is checked for upon each
601  * read.
602  *
603  * Since: 0.10.36
604  */
605 void
606 gst_base_src_set_dynamic_size (GstBaseSrc * src, gboolean dynamic)
607 {
608   g_return_if_fail (GST_IS_BASE_SRC (src));
609
610   g_atomic_int_set (&src->priv->dynamic_size, dynamic);
611 }
612
613 /**
614  * gst_base_src_query_latency:
615  * @src: the source
616  * @live: (out) (allow-none): if the source is live
617  * @min_latency: (out) (allow-none): the min latency of the source
618  * @max_latency: (out) (allow-none): the max latency of the source
619  *
620  * Query the source for the latency parameters. @live will be TRUE when @src is
621  * configured as a live source. @min_latency will be set to the difference
622  * between the running time and the timestamp of the first buffer.
623  * @max_latency is always the undefined value of -1.
624  *
625  * This function is mostly used by subclasses.
626  *
627  * Returns: TRUE if the query succeeded.
628  *
629  * Since: 0.10.13
630  */
631 gboolean
632 gst_base_src_query_latency (GstBaseSrc * src, gboolean * live,
633     GstClockTime * min_latency, GstClockTime * max_latency)
634 {
635   GstClockTime min;
636
637   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
638
639   GST_OBJECT_LOCK (src);
640   if (live)
641     *live = src->is_live;
642
643   /* if we have a startup latency, report this one, else report 0. Subclasses
644    * are supposed to override the query function if they want something
645    * else. */
646   if (src->priv->latency != -1)
647     min = src->priv->latency;
648   else
649     min = 0;
650
651   if (min_latency)
652     *min_latency = min;
653   if (max_latency)
654     *max_latency = -1;
655
656   GST_LOG_OBJECT (src, "latency: live %d, min %" GST_TIME_FORMAT
657       ", max %" GST_TIME_FORMAT, src->is_live, GST_TIME_ARGS (min),
658       GST_TIME_ARGS (-1));
659   GST_OBJECT_UNLOCK (src);
660
661   return TRUE;
662 }
663
664 /**
665  * gst_base_src_set_blocksize:
666  * @src: the source
667  * @blocksize: the new blocksize in bytes
668  *
669  * Set the number of bytes that @src will push out with each buffer. When
670  * @blocksize is set to -1, a default length will be used.
671  *
672  * Since: 0.10.22
673  */
674 /* FIXME 0.11: blocksize property should be int, not ulong */
675 void
676 gst_base_src_set_blocksize (GstBaseSrc * src, gulong blocksize)
677 {
678   g_return_if_fail (GST_IS_BASE_SRC (src));
679
680   GST_OBJECT_LOCK (src);
681   src->blocksize = blocksize;
682   GST_OBJECT_UNLOCK (src);
683 }
684
685 /**
686  * gst_base_src_get_blocksize:
687  * @src: the source
688  *
689  * Get the number of bytes that @src will push out with each buffer.
690  *
691  * Returns: the number of bytes pushed with each buffer.
692  *
693  * Since: 0.10.22
694  */
695 /* FIXME 0.11: blocksize property should be int, not ulong */
696 gulong
697 gst_base_src_get_blocksize (GstBaseSrc * src)
698 {
699   gulong res;
700
701   g_return_val_if_fail (GST_IS_BASE_SRC (src), 0);
702
703   GST_OBJECT_LOCK (src);
704   res = src->blocksize;
705   GST_OBJECT_UNLOCK (src);
706
707   return res;
708 }
709
710
711 /**
712  * gst_base_src_set_do_timestamp:
713  * @src: the source
714  * @timestamp: enable or disable timestamping
715  *
716  * Configure @src to automatically timestamp outgoing buffers based on the
717  * current running_time of the pipeline. This property is mostly useful for live
718  * sources.
719  *
720  * Since: 0.10.15
721  */
722 void
723 gst_base_src_set_do_timestamp (GstBaseSrc * src, gboolean timestamp)
724 {
725   g_return_if_fail (GST_IS_BASE_SRC (src));
726
727   GST_OBJECT_LOCK (src);
728   src->priv->do_timestamp = timestamp;
729   GST_OBJECT_UNLOCK (src);
730 }
731
732 /**
733  * gst_base_src_get_do_timestamp:
734  * @src: the source
735  *
736  * Query if @src timestamps outgoing buffers based on the current running_time.
737  *
738  * Returns: %TRUE if the base class will automatically timestamp outgoing buffers.
739  *
740  * Since: 0.10.15
741  */
742 gboolean
743 gst_base_src_get_do_timestamp (GstBaseSrc * src)
744 {
745   gboolean res;
746
747   g_return_val_if_fail (GST_IS_BASE_SRC (src), FALSE);
748
749   GST_OBJECT_LOCK (src);
750   res = src->priv->do_timestamp;
751   GST_OBJECT_UNLOCK (src);
752
753   return res;
754 }
755
756 /**
757  * gst_base_src_new_seamless_segment:
758  * @src: The source
759  * @start: The new start value for the segment
760  * @stop: Stop value for the new segment
761  * @position: The position value for the new segent
762  *
763  * Prepare a new seamless segment for emission downstream. This function must
764  * only be called by derived sub-classes, and only from the create() function,
765  * as the stream-lock needs to be held.
766  *
767  * The format for the new segment will be the current format of the source, as
768  * configured with gst_base_src_set_format()
769  *
770  * Returns: %TRUE if preparation of the seamless segment succeeded.
771  *
772  * Since: 0.10.26
773  */
774 gboolean
775 gst_base_src_new_seamless_segment (GstBaseSrc * src, gint64 start, gint64 stop,
776     gint64 position)
777 {
778   gboolean res = TRUE;
779
780   GST_DEBUG_OBJECT (src,
781       "Starting new seamless segment. Start %" GST_TIME_FORMAT " stop %"
782       GST_TIME_FORMAT " position %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
783       GST_TIME_ARGS (stop), GST_TIME_ARGS (position));
784
785   GST_OBJECT_LOCK (src);
786   if (src->data.ABI.running && !src->priv->newsegment_pending) {
787     if (src->priv->close_segment)
788       gst_event_unref (src->priv->close_segment);
789     src->priv->close_segment =
790         gst_event_new_new_segment_full (TRUE,
791         src->segment.rate, src->segment.applied_rate, src->segment.format,
792         src->segment.start, src->segment.last_stop, src->segment.time);
793   }
794
795   gst_segment_set_newsegment_full (&src->segment, FALSE, src->segment.rate,
796       src->segment.applied_rate, src->segment.format, start, stop, position);
797
798   if (src->priv->start_segment)
799     gst_event_unref (src->priv->start_segment);
800   if (src->segment.rate >= 0.0) {
801     /* forward, we send data from last_stop to stop */
802     src->priv->start_segment =
803         gst_event_new_new_segment_full (FALSE,
804         src->segment.rate, src->segment.applied_rate, src->segment.format,
805         src->segment.last_stop, stop, src->segment.time);
806   } else {
807     /* reverse, we send data from last_stop to start */
808     src->priv->start_segment =
809         gst_event_new_new_segment_full (FALSE,
810         src->segment.rate, src->segment.applied_rate, src->segment.format,
811         src->segment.start, src->segment.last_stop, src->segment.time);
812   }
813   GST_OBJECT_UNLOCK (src);
814
815   src->priv->discont = TRUE;
816   src->data.ABI.running = TRUE;
817
818   return res;
819 }
820
821 static gboolean
822 gst_base_src_setcaps (GstPad * pad, GstCaps * caps)
823 {
824   GstBaseSrcClass *bclass;
825   GstBaseSrc *bsrc;
826   gboolean res = TRUE;
827
828   bsrc = GST_BASE_SRC (GST_PAD_PARENT (pad));
829   bclass = GST_BASE_SRC_GET_CLASS (bsrc);
830
831   if (bclass->set_caps)
832     res = bclass->set_caps (bsrc, caps);
833
834   return res;
835 }
836
837 static GstCaps *
838 gst_base_src_getcaps (GstPad * pad)
839 {
840   GstBaseSrcClass *bclass;
841   GstBaseSrc *bsrc;
842   GstCaps *caps = NULL;
843
844   bsrc = GST_BASE_SRC (GST_PAD_PARENT (pad));
845   bclass = GST_BASE_SRC_GET_CLASS (bsrc);
846   if (bclass->get_caps)
847     caps = bclass->get_caps (bsrc);
848
849   if (caps == NULL) {
850     GstPadTemplate *pad_template;
851
852     pad_template =
853         gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
854     if (pad_template != NULL) {
855       caps = gst_caps_ref (gst_pad_template_get_caps (pad_template));
856     }
857   }
858   return caps;
859 }
860
861 static void
862 gst_base_src_fixate (GstPad * pad, GstCaps * caps)
863 {
864   GstBaseSrcClass *bclass;
865   GstBaseSrc *bsrc;
866
867   bsrc = GST_BASE_SRC (gst_pad_get_parent (pad));
868   bclass = GST_BASE_SRC_GET_CLASS (bsrc);
869
870   if (bclass->fixate)
871     bclass->fixate (bsrc, caps);
872
873   gst_object_unref (bsrc);
874 }
875
876 static gboolean
877 gst_base_src_default_query (GstBaseSrc * src, GstQuery * query)
878 {
879   gboolean res;
880
881   switch (GST_QUERY_TYPE (query)) {
882     case GST_QUERY_POSITION:
883     {
884       GstFormat format;
885
886       gst_query_parse_position (query, &format, NULL);
887
888       GST_DEBUG_OBJECT (src, "position query in format %s",
889           gst_format_get_name (format));
890
891       switch (format) {
892         case GST_FORMAT_PERCENT:
893         {
894           gint64 percent;
895           gint64 position;
896           gint64 duration;
897
898           GST_OBJECT_LOCK (src);
899           position = src->segment.last_stop;
900           duration = src->segment.duration;
901           GST_OBJECT_UNLOCK (src);
902
903           if (position != -1 && duration != -1) {
904             if (position < duration)
905               percent = gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX, position,
906                   duration);
907             else
908               percent = GST_FORMAT_PERCENT_MAX;
909           } else
910             percent = -1;
911
912           gst_query_set_position (query, GST_FORMAT_PERCENT, percent);
913           res = TRUE;
914           break;
915         }
916         default:
917         {
918           gint64 position;
919           GstFormat seg_format;
920
921           GST_OBJECT_LOCK (src);
922           position =
923               gst_segment_to_stream_time (&src->segment, src->segment.format,
924               src->segment.last_stop);
925           seg_format = src->segment.format;
926           GST_OBJECT_UNLOCK (src);
927
928           if (position != -1) {
929             /* convert to requested format */
930             res =
931                 gst_pad_query_convert (src->srcpad, seg_format,
932                 position, &format, &position);
933           } else
934             res = TRUE;
935
936           gst_query_set_position (query, format, position);
937           break;
938         }
939       }
940       break;
941     }
942     case GST_QUERY_DURATION:
943     {
944       GstFormat format;
945
946       gst_query_parse_duration (query, &format, NULL);
947
948       GST_DEBUG_OBJECT (src, "duration query in format %s",
949           gst_format_get_name (format));
950
951       switch (format) {
952         case GST_FORMAT_PERCENT:
953           gst_query_set_duration (query, GST_FORMAT_PERCENT,
954               GST_FORMAT_PERCENT_MAX);
955           res = TRUE;
956           break;
957         default:
958         {
959           gint64 duration;
960           GstFormat seg_format;
961           guint length = 0;
962
963           /* may have to refresh duration */
964           if (g_atomic_int_get (&src->priv->dynamic_size))
965             gst_base_src_update_length (src, 0, &length);
966
967           /* this is the duration as configured by the subclass. */
968           GST_OBJECT_LOCK (src);
969           duration = src->segment.duration;
970           seg_format = src->segment.format;
971           GST_OBJECT_UNLOCK (src);
972
973           GST_LOG_OBJECT (src, "duration %" G_GINT64_FORMAT ", format %s",
974               duration, gst_format_get_name (seg_format));
975
976           if (duration != -1) {
977             /* convert to requested format, if this fails, we have a duration
978              * but we cannot answer the query, we must return FALSE. */
979             res =
980                 gst_pad_query_convert (src->srcpad, seg_format,
981                 duration, &format, &duration);
982           } else {
983             /* The subclass did not configure a duration, we assume that the
984              * media has an unknown duration then and we return TRUE to report
985              * this. Note that this is not the same as returning FALSE, which
986              * means that we cannot report the duration at all. */
987             res = TRUE;
988           }
989           gst_query_set_duration (query, format, duration);
990           break;
991         }
992       }
993       break;
994     }
995
996     case GST_QUERY_SEEKING:
997     {
998       GstFormat format, seg_format;
999       gint64 duration;
1000
1001       GST_OBJECT_LOCK (src);
1002       duration = src->segment.duration;
1003       seg_format = src->segment.format;
1004       GST_OBJECT_UNLOCK (src);
1005
1006       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
1007       if (format == seg_format) {
1008         gst_query_set_seeking (query, seg_format,
1009             gst_base_src_seekable (src), 0, duration);
1010         res = TRUE;
1011       } else {
1012         /* FIXME 0.11: return TRUE + seekable=FALSE for SEEKING query here */
1013         /* Don't reply to the query to make up for demuxers which don't
1014          * handle the SEEKING query yet. Players like Totem will fall back
1015          * to the duration when the SEEKING query isn't answered. */
1016         res = FALSE;
1017       }
1018       break;
1019     }
1020     case GST_QUERY_SEGMENT:
1021     {
1022       gint64 start, stop;
1023
1024       GST_OBJECT_LOCK (src);
1025       /* no end segment configured, current duration then */
1026       if ((stop = src->segment.stop) == -1)
1027         stop = src->segment.duration;
1028       start = src->segment.start;
1029
1030       /* adjust to stream time */
1031       if (src->segment.time != -1) {
1032         start -= src->segment.time;
1033         if (stop != -1)
1034           stop -= src->segment.time;
1035       }
1036
1037       gst_query_set_segment (query, src->segment.rate, src->segment.format,
1038           start, stop);
1039       GST_OBJECT_UNLOCK (src);
1040       res = TRUE;
1041       break;
1042     }
1043
1044     case GST_QUERY_FORMATS:
1045     {
1046       gst_query_set_formats (query, 3, GST_FORMAT_DEFAULT,
1047           GST_FORMAT_BYTES, GST_FORMAT_PERCENT);
1048       res = TRUE;
1049       break;
1050     }
1051     case GST_QUERY_CONVERT:
1052     {
1053       GstFormat src_fmt, dest_fmt;
1054       gint64 src_val, dest_val;
1055
1056       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1057
1058       /* we can only convert between equal formats... */
1059       if (src_fmt == dest_fmt) {
1060         dest_val = src_val;
1061         res = TRUE;
1062       } else
1063         res = FALSE;
1064
1065       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1066       break;
1067     }
1068     case GST_QUERY_LATENCY:
1069     {
1070       GstClockTime min, max;
1071       gboolean live;
1072
1073       /* Subclasses should override and implement something useful */
1074       res = gst_base_src_query_latency (src, &live, &min, &max);
1075
1076       GST_LOG_OBJECT (src, "report latency: live %d, min %" GST_TIME_FORMAT
1077           ", max %" GST_TIME_FORMAT, live, GST_TIME_ARGS (min),
1078           GST_TIME_ARGS (max));
1079
1080       gst_query_set_latency (query, live, min, max);
1081       break;
1082     }
1083     case GST_QUERY_JITTER:
1084     case GST_QUERY_RATE:
1085       res = FALSE;
1086       break;
1087     case GST_QUERY_BUFFERING:
1088     {
1089       GstFormat format, seg_format;
1090       gint64 start, stop, estimated;
1091
1092       gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
1093
1094       GST_DEBUG_OBJECT (src, "buffering query in format %s",
1095           gst_format_get_name (format));
1096
1097       GST_OBJECT_LOCK (src);
1098       if (src->random_access) {
1099         estimated = 0;
1100         start = 0;
1101         if (format == GST_FORMAT_PERCENT)
1102           stop = GST_FORMAT_PERCENT_MAX;
1103         else
1104           stop = src->segment.duration;
1105       } else {
1106         estimated = -1;
1107         start = -1;
1108         stop = -1;
1109       }
1110       seg_format = src->segment.format;
1111       GST_OBJECT_UNLOCK (src);
1112
1113       /* convert to required format. When the conversion fails, we can't answer
1114        * the query. When the value is unknown, we can don't perform conversion
1115        * but report TRUE. */
1116       if (format != GST_FORMAT_PERCENT && stop != -1) {
1117         res = gst_pad_query_convert (src->srcpad, seg_format,
1118             stop, &format, &stop);
1119       } else {
1120         res = TRUE;
1121       }
1122       if (res && format != GST_FORMAT_PERCENT && start != -1)
1123         res = gst_pad_query_convert (src->srcpad, seg_format,
1124             start, &format, &start);
1125
1126       gst_query_set_buffering_range (query, format, start, stop, estimated);
1127       break;
1128     }
1129     default:
1130       res = FALSE;
1131       break;
1132   }
1133   GST_DEBUG_OBJECT (src, "query %s returns %d", GST_QUERY_TYPE_NAME (query),
1134       res);
1135   return res;
1136 }
1137
1138 static gboolean
1139 gst_base_src_query (GstPad * pad, GstQuery * query)
1140 {
1141   GstBaseSrc *src;
1142   GstBaseSrcClass *bclass;
1143   gboolean result = FALSE;
1144
1145   src = GST_BASE_SRC (gst_pad_get_parent (pad));
1146   if (G_UNLIKELY (src == NULL))
1147     return FALSE;
1148
1149   bclass = GST_BASE_SRC_GET_CLASS (src);
1150
1151   if (bclass->query)
1152     result = bclass->query (src, query);
1153   else
1154     result = gst_pad_query_default (pad, query);
1155
1156   gst_object_unref (src);
1157
1158   return result;
1159 }
1160
1161 static gboolean
1162 gst_base_src_default_do_seek (GstBaseSrc * src, GstSegment * segment)
1163 {
1164   gboolean res = TRUE;
1165
1166   /* update our offset if the start/stop position was updated */
1167   if (segment->format == GST_FORMAT_BYTES) {
1168     segment->time = segment->start;
1169   } else if (segment->start == 0) {
1170     /* seek to start, we can implement a default for this. */
1171     segment->time = 0;
1172   } else {
1173     res = FALSE;
1174     GST_INFO_OBJECT (src, "Can't do a default seek");
1175   }
1176
1177   return res;
1178 }
1179
1180 static gboolean
1181 gst_base_src_do_seek (GstBaseSrc * src, GstSegment * segment)
1182 {
1183   GstBaseSrcClass *bclass;
1184   gboolean result = FALSE;
1185
1186   bclass = GST_BASE_SRC_GET_CLASS (src);
1187
1188   if (bclass->do_seek)
1189     result = bclass->do_seek (src, segment);
1190
1191   return result;
1192 }
1193
1194 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
1195
1196 static gboolean
1197 gst_base_src_default_prepare_seek_segment (GstBaseSrc * src, GstEvent * event,
1198     GstSegment * segment)
1199 {
1200   /* By default, we try one of 2 things:
1201    *   - For absolute seek positions, convert the requested position to our
1202    *     configured processing format and place it in the output segment \
1203    *   - For relative seek positions, convert our current (input) values to the
1204    *     seek format, adjust by the relative seek offset and then convert back to
1205    *     the processing format
1206    */
1207   GstSeekType cur_type, stop_type;
1208   gint64 cur, stop;
1209   GstSeekFlags flags;
1210   GstFormat seek_format, dest_format;
1211   gdouble rate;
1212   gboolean update;
1213   gboolean res = TRUE;
1214
1215   gst_event_parse_seek (event, &rate, &seek_format, &flags,
1216       &cur_type, &cur, &stop_type, &stop);
1217   dest_format = segment->format;
1218
1219   if (seek_format == dest_format) {
1220     gst_segment_set_seek (segment, rate, seek_format, flags,
1221         cur_type, cur, stop_type, stop, &update);
1222     return TRUE;
1223   }
1224
1225   if (cur_type != GST_SEEK_TYPE_NONE) {
1226     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
1227     res =
1228         gst_pad_query_convert (src->srcpad, seek_format, cur, &dest_format,
1229         &cur);
1230     cur_type = GST_SEEK_TYPE_SET;
1231   }
1232
1233   if (res && stop_type != GST_SEEK_TYPE_NONE) {
1234     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
1235     res =
1236         gst_pad_query_convert (src->srcpad, seek_format, stop, &dest_format,
1237         &stop);
1238     stop_type = GST_SEEK_TYPE_SET;
1239   }
1240
1241   /* And finally, configure our output segment in the desired format */
1242   gst_segment_set_seek (segment, rate, dest_format, flags, cur_type, cur,
1243       stop_type, stop, &update);
1244
1245   if (!res)
1246     goto no_format;
1247
1248   return res;
1249
1250 no_format:
1251   {
1252     GST_DEBUG_OBJECT (src, "undefined format given, seek aborted.");
1253     return FALSE;
1254   }
1255 }
1256
1257 static gboolean
1258 gst_base_src_prepare_seek_segment (GstBaseSrc * src, GstEvent * event,
1259     GstSegment * seeksegment)
1260 {
1261   GstBaseSrcClass *bclass;
1262   gboolean result = FALSE;
1263
1264   bclass = GST_BASE_SRC_GET_CLASS (src);
1265
1266   if (bclass->prepare_seek_segment)
1267     result = bclass->prepare_seek_segment (src, event, seeksegment);
1268
1269   return result;
1270 }
1271
1272 /* this code implements the seeking. It is a good example
1273  * handling all cases.
1274  *
1275  * A seek updates the currently configured segment.start
1276  * and segment.stop values based on the SEEK_TYPE. If the
1277  * segment.start value is updated, a seek to this new position
1278  * should be performed.
1279  *
1280  * The seek can only be executed when we are not currently
1281  * streaming any data, to make sure that this is the case, we
1282  * acquire the STREAM_LOCK which is taken when we are in the
1283  * _loop() function or when a getrange() is called. Normally
1284  * we will not receive a seek if we are operating in pull mode
1285  * though. When we operate as a live source we might block on the live
1286  * cond, which does not release the STREAM_LOCK. Therefore we will try
1287  * to grab the LIVE_LOCK instead of the STREAM_LOCK to make sure it is
1288  * safe to perform the seek.
1289  *
1290  * When we are in the loop() function, we might be in the middle
1291  * of pushing a buffer, which might block in a sink. To make sure
1292  * that the push gets unblocked we push out a FLUSH_START event.
1293  * Our loop function will get a WRONG_STATE return value from
1294  * the push and will pause, effectively releasing the STREAM_LOCK.
1295  *
1296  * For a non-flushing seek, we pause the task, which might eventually
1297  * release the STREAM_LOCK. We say eventually because when the sink
1298  * blocks on the sample we might wait a very long time until the sink
1299  * unblocks the sample. In any case we acquire the STREAM_LOCK and
1300  * can continue the seek. A non-flushing seek is normally done in a
1301  * running pipeline to perform seamless playback, this means that the sink is
1302  * PLAYING and will return from its chain function.
1303  * In the case of a non-flushing seek we need to make sure that the
1304  * data we output after the seek is continuous with the previous data,
1305  * this is because a non-flushing seek does not reset the running-time
1306  * to 0. We do this by closing the currently running segment, ie. sending
1307  * a new_segment event with the stop position set to the last processed
1308  * position.
1309  *
1310  * After updating the segment.start/stop values, we prepare for
1311  * streaming again. We push out a FLUSH_STOP to make the peer pad
1312  * accept data again and we start our task again.
1313  *
1314  * A segment seek posts a message on the bus saying that the playback
1315  * of the segment started. We store the segment flag internally because
1316  * when we reach the segment.stop we have to post a segment.done
1317  * instead of EOS when doing a segment seek.
1318  */
1319 /* FIXME (0.11), we have the unlock gboolean here because most current
1320  * implementations (fdsrc, -base/gst/tcp/, ...) unconditionally unlock, even when
1321  * the streaming thread isn't running, resulting in bogus unlocks later when it
1322  * starts. This is fixed by adding unlock_stop, but we should still avoid unlocking
1323  * unnecessarily for backwards compatibility. Ergo, the unlock variable stays
1324  * until 0.11
1325  */
1326 static gboolean
1327 gst_base_src_perform_seek (GstBaseSrc * src, GstEvent * event, gboolean unlock)
1328 {
1329   gboolean res = TRUE, tres;
1330   gdouble rate;
1331   GstFormat seek_format, dest_format;
1332   GstSeekFlags flags;
1333   GstSeekType cur_type, stop_type;
1334   gint64 cur, stop;
1335   gboolean flush, playing;
1336   gboolean update;
1337   gboolean relative_seek = FALSE;
1338   gboolean seekseg_configured = FALSE;
1339   GstSegment seeksegment;
1340   guint32 seqnum;
1341   GstEvent *tevent;
1342
1343   GST_DEBUG_OBJECT (src, "doing seek: %" GST_PTR_FORMAT, event);
1344
1345   GST_OBJECT_LOCK (src);
1346   dest_format = src->segment.format;
1347   GST_OBJECT_UNLOCK (src);
1348
1349   if (event) {
1350     gst_event_parse_seek (event, &rate, &seek_format, &flags,
1351         &cur_type, &cur, &stop_type, &stop);
1352
1353     relative_seek = SEEK_TYPE_IS_RELATIVE (cur_type) ||
1354         SEEK_TYPE_IS_RELATIVE (stop_type);
1355
1356     if (dest_format != seek_format && !relative_seek) {
1357       /* If we have an ABSOLUTE position (SEEK_SET only), we can convert it
1358        * here before taking the stream lock, otherwise we must convert it later,
1359        * once we have the stream lock and can read the last configures segment
1360        * start and stop positions */
1361       gst_segment_init (&seeksegment, dest_format);
1362
1363       if (!gst_base_src_prepare_seek_segment (src, event, &seeksegment))
1364         goto prepare_failed;
1365
1366       seekseg_configured = TRUE;
1367     }
1368
1369     flush = flags & GST_SEEK_FLAG_FLUSH;
1370     seqnum = gst_event_get_seqnum (event);
1371   } else {
1372     flush = FALSE;
1373     /* get next seqnum */
1374     seqnum = gst_util_seqnum_next ();
1375   }
1376
1377   /* send flush start */
1378   if (flush) {
1379     tevent = gst_event_new_flush_start ();
1380     gst_event_set_seqnum (tevent, seqnum);
1381     gst_pad_push_event (src->srcpad, tevent);
1382   } else
1383     gst_pad_pause_task (src->srcpad);
1384
1385   /* unblock streaming thread. */
1386   gst_base_src_set_flushing (src, TRUE, FALSE, unlock, &playing);
1387
1388   /* grab streaming lock, this should eventually be possible, either
1389    * because the task is paused, our streaming thread stopped
1390    * or because our peer is flushing. */
1391   GST_PAD_STREAM_LOCK (src->srcpad);
1392   if (G_UNLIKELY (src->priv->seqnum == seqnum)) {
1393     /* we have seen this event before, issue a warning for now */
1394     GST_WARNING_OBJECT (src, "duplicate event found %" G_GUINT32_FORMAT,
1395         seqnum);
1396   } else {
1397     src->priv->seqnum = seqnum;
1398     GST_DEBUG_OBJECT (src, "seek with seqnum %" G_GUINT32_FORMAT, seqnum);
1399   }
1400
1401   gst_base_src_set_flushing (src, FALSE, playing, unlock, NULL);
1402
1403   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
1404    * copy the current segment info into the temp segment that we can actually
1405    * attempt the seek with. We only update the real segment if the seek succeeds. */
1406   if (!seekseg_configured) {
1407     memcpy (&seeksegment, &src->segment, sizeof (GstSegment));
1408
1409     /* now configure the final seek segment */
1410     if (event) {
1411       if (seeksegment.format != seek_format) {
1412         /* OK, here's where we give the subclass a chance to convert the relative
1413          * seek into an absolute one in the processing format. We set up any
1414          * absolute seek above, before taking the stream lock. */
1415         if (!gst_base_src_prepare_seek_segment (src, event, &seeksegment)) {
1416           GST_DEBUG_OBJECT (src, "Preparing the seek failed after flushing. "
1417               "Aborting seek");
1418           res = FALSE;
1419         }
1420       } else {
1421         /* The seek format matches our processing format, no need to ask the
1422          * the subclass to configure the segment. */
1423         gst_segment_set_seek (&seeksegment, rate, seek_format, flags,
1424             cur_type, cur, stop_type, stop, &update);
1425       }
1426     }
1427     /* Else, no seek event passed, so we're just (re)starting the
1428        current segment. */
1429   }
1430
1431   if (res) {
1432     GST_DEBUG_OBJECT (src, "segment configured from %" G_GINT64_FORMAT
1433         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
1434         seeksegment.start, seeksegment.stop, seeksegment.last_stop);
1435
1436     /* do the seek, segment.last_stop contains the new position. */
1437     res = gst_base_src_do_seek (src, &seeksegment);
1438   }
1439
1440   /* and prepare to continue streaming */
1441   if (flush) {
1442     tevent = gst_event_new_flush_stop ();
1443     gst_event_set_seqnum (tevent, seqnum);
1444     /* send flush stop, peer will accept data and events again. We
1445      * are not yet providing data as we still have the STREAM_LOCK. */
1446     gst_pad_push_event (src->srcpad, tevent);
1447   } else if (res && src->data.ABI.running) {
1448     /* we are running the current segment and doing a non-flushing seek,
1449      * close the segment first based on the last_stop. */
1450     GST_DEBUG_OBJECT (src, "closing running segment %" G_GINT64_FORMAT
1451         " to %" G_GINT64_FORMAT, src->segment.start, src->segment.last_stop);
1452
1453     /* queue the segment for sending in the stream thread */
1454     if (src->priv->close_segment)
1455       gst_event_unref (src->priv->close_segment);
1456     src->priv->close_segment =
1457         gst_event_new_new_segment_full (TRUE,
1458         src->segment.rate, src->segment.applied_rate, src->segment.format,
1459         src->segment.start, src->segment.last_stop, src->segment.time);
1460     seeksegment.time = gst_segment_to_stream_time (&src->segment,
1461         src->segment.format, src->segment.last_stop);
1462     seeksegment.start = src->segment.last_stop;
1463     gst_event_set_seqnum (src->priv->close_segment, seqnum);
1464   }
1465
1466   /* The subclass must have converted the segment to the processing format
1467    * by now */
1468   if (res && seeksegment.format != dest_format) {
1469     GST_DEBUG_OBJECT (src, "Subclass failed to prepare a seek segment "
1470         "in the correct format. Aborting seek.");
1471     res = FALSE;
1472   }
1473
1474   /* if the seek was successful, we update our real segment and push
1475    * out the new segment. */
1476   if (res) {
1477     GST_OBJECT_LOCK (src);
1478     memcpy (&src->segment, &seeksegment, sizeof (GstSegment));
1479     GST_OBJECT_UNLOCK (src);
1480
1481     if (seeksegment.flags & GST_SEEK_FLAG_SEGMENT) {
1482       GstMessage *message;
1483
1484       message = gst_message_new_segment_start (GST_OBJECT (src),
1485           seeksegment.format, seeksegment.last_stop);
1486       gst_message_set_seqnum (message, seqnum);
1487
1488       gst_element_post_message (GST_ELEMENT (src), message);
1489     }
1490
1491     /* for deriving a stop position for the playback segment from the seek
1492      * segment, we must take the duration when the stop is not set */
1493     if ((stop = seeksegment.stop) == -1)
1494       stop = seeksegment.duration;
1495
1496     GST_DEBUG_OBJECT (src, "Sending newsegment from %" G_GINT64_FORMAT
1497         " to %" G_GINT64_FORMAT, seeksegment.start, stop);
1498
1499     /* now replace the old segment so that we send it in the stream thread the
1500      * next time it is scheduled. */
1501     if (src->priv->start_segment)
1502       gst_event_unref (src->priv->start_segment);
1503     if (seeksegment.rate >= 0.0) {
1504       /* forward, we send data from last_stop to stop */
1505       src->priv->start_segment =
1506           gst_event_new_new_segment_full (FALSE,
1507           seeksegment.rate, seeksegment.applied_rate, seeksegment.format,
1508           seeksegment.last_stop, stop, seeksegment.time);
1509     } else {
1510       /* reverse, we send data from last_stop to start */
1511       src->priv->start_segment =
1512           gst_event_new_new_segment_full (FALSE,
1513           seeksegment.rate, seeksegment.applied_rate, seeksegment.format,
1514           seeksegment.start, seeksegment.last_stop, seeksegment.time);
1515     }
1516     gst_event_set_seqnum (src->priv->start_segment, seqnum);
1517     src->priv->newsegment_pending = TRUE;
1518   }
1519
1520   src->priv->discont = TRUE;
1521   src->data.ABI.running = TRUE;
1522   /* and restart the task in case it got paused explicitly or by
1523    * the FLUSH_START event we pushed out. */
1524   tres = gst_pad_start_task (src->srcpad, (GstTaskFunction) gst_base_src_loop,
1525       src->srcpad);
1526   if (res && !tres)
1527     res = FALSE;
1528
1529   /* and release the lock again so we can continue streaming */
1530   GST_PAD_STREAM_UNLOCK (src->srcpad);
1531
1532   return res;
1533
1534   /* ERROR */
1535 prepare_failed:
1536   GST_DEBUG_OBJECT (src, "Preparing the seek failed before flushing. "
1537       "Aborting seek");
1538   return FALSE;
1539 }
1540
1541 static const GstQueryType *
1542 gst_base_src_get_query_types (GstElement * element)
1543 {
1544   static const GstQueryType query_types[] = {
1545     GST_QUERY_DURATION,
1546     GST_QUERY_POSITION,
1547     GST_QUERY_SEEKING,
1548     GST_QUERY_SEGMENT,
1549     GST_QUERY_FORMATS,
1550     GST_QUERY_LATENCY,
1551     GST_QUERY_JITTER,
1552     GST_QUERY_RATE,
1553     GST_QUERY_CONVERT,
1554     0
1555   };
1556
1557   return query_types;
1558 }
1559
1560 /* all events send to this element directly. This is mainly done from the
1561  * application.
1562  */
1563 static gboolean
1564 gst_base_src_send_event (GstElement * element, GstEvent * event)
1565 {
1566   GstBaseSrc *src;
1567   gboolean result = FALSE;
1568
1569   src = GST_BASE_SRC (element);
1570
1571   GST_DEBUG_OBJECT (src, "handling event %p %" GST_PTR_FORMAT, event, event);
1572
1573   switch (GST_EVENT_TYPE (event)) {
1574       /* bidirectional events */
1575     case GST_EVENT_FLUSH_START:
1576     case GST_EVENT_FLUSH_STOP:
1577       /* sending random flushes downstream can break stuff,
1578        * especially sync since all segment info will get flushed */
1579       break;
1580
1581       /* downstream serialized events */
1582     case GST_EVENT_EOS:
1583     {
1584       GstBaseSrcClass *bclass;
1585
1586       bclass = GST_BASE_SRC_GET_CLASS (src);
1587
1588       /* queue EOS and make sure the task or pull function performs the EOS
1589        * actions.
1590        *
1591        * We have two possibilities:
1592        *
1593        *  - Before we are to enter the _create function, we check the pending_eos
1594        *    first and do EOS instead of entering it.
1595        *  - If we are in the _create function or we did not manage to set the
1596        *    flag fast enough and we are about to enter the _create function,
1597        *    we unlock it so that we exit with WRONG_STATE immediately. We then
1598        *    check the EOS flag and do the EOS logic.
1599        */
1600       g_atomic_int_set (&src->priv->pending_eos, TRUE);
1601       GST_DEBUG_OBJECT (src, "EOS marked, calling unlock");
1602
1603       /* unlock the _create function so that we can check the pending_eos flag
1604        * and we can do EOS. This will eventually release the LIVE_LOCK again so
1605        * that we can grab it and stop the unlock again. We don't take the stream
1606        * lock so that this operation is guaranteed to never block. */
1607       if (bclass->unlock)
1608         bclass->unlock (src);
1609
1610       GST_DEBUG_OBJECT (src, "unlock called, waiting for LIVE_LOCK");
1611
1612       GST_LIVE_LOCK (src);
1613       GST_DEBUG_OBJECT (src, "LIVE_LOCK acquired, calling unlock_stop");
1614       /* now stop the unlock of the streaming thread again. Grabbing the live
1615        * lock is enough because that protects the create function. */
1616       if (bclass->unlock_stop)
1617         bclass->unlock_stop (src);
1618       GST_LIVE_UNLOCK (src);
1619
1620       result = TRUE;
1621       break;
1622     }
1623     case GST_EVENT_NEWSEGMENT:
1624       /* sending random NEWSEGMENT downstream can break sync. */
1625       break;
1626     case GST_EVENT_TAG:
1627     case GST_EVENT_CUSTOM_DOWNSTREAM:
1628     case GST_EVENT_CUSTOM_BOTH:
1629       /* Insert TAG, CUSTOM_DOWNSTREAM, CUSTOM_BOTH in the dataflow */
1630       GST_OBJECT_LOCK (src);
1631       src->priv->pending_events =
1632           g_list_append (src->priv->pending_events, event);
1633       g_atomic_int_set (&src->priv->have_events, TRUE);
1634       GST_OBJECT_UNLOCK (src);
1635       event = NULL;
1636       result = TRUE;
1637       break;
1638     case GST_EVENT_BUFFERSIZE:
1639       /* does not seem to make much sense currently */
1640       break;
1641
1642       /* upstream events */
1643     case GST_EVENT_QOS:
1644       /* elements should override send_event and do something */
1645       break;
1646     case GST_EVENT_SEEK:
1647     {
1648       gboolean started;
1649
1650       GST_OBJECT_LOCK (src->srcpad);
1651       if (GST_PAD_ACTIVATE_MODE (src->srcpad) == GST_ACTIVATE_PULL)
1652         goto wrong_mode;
1653       started = GST_PAD_ACTIVATE_MODE (src->srcpad) == GST_ACTIVATE_PUSH;
1654       GST_OBJECT_UNLOCK (src->srcpad);
1655
1656       if (started) {
1657         GST_DEBUG_OBJECT (src, "performing seek");
1658         /* when we are running in push mode, we can execute the
1659          * seek right now, we need to unlock. */
1660         result = gst_base_src_perform_seek (src, event, TRUE);
1661       } else {
1662         GstEvent **event_p;
1663
1664         /* else we store the event and execute the seek when we
1665          * get activated */
1666         GST_OBJECT_LOCK (src);
1667         GST_DEBUG_OBJECT (src, "queueing seek");
1668         event_p = &src->data.ABI.pending_seek;
1669         gst_event_replace ((GstEvent **) event_p, event);
1670         GST_OBJECT_UNLOCK (src);
1671         /* assume the seek will work */
1672         result = TRUE;
1673       }
1674       break;
1675     }
1676     case GST_EVENT_NAVIGATION:
1677       /* could make sense for elements that do something with navigation events
1678        * but then they would need to override the send_event function */
1679       break;
1680     case GST_EVENT_LATENCY:
1681       /* does not seem to make sense currently */
1682       break;
1683
1684       /* custom events */
1685     case GST_EVENT_CUSTOM_UPSTREAM:
1686       /* override send_event if you want this */
1687       break;
1688     case GST_EVENT_CUSTOM_DOWNSTREAM_OOB:
1689     case GST_EVENT_CUSTOM_BOTH_OOB:
1690       /* insert a random custom event into the pipeline */
1691       GST_DEBUG_OBJECT (src, "pushing custom OOB event downstream");
1692       result = gst_pad_push_event (src->srcpad, event);
1693       /* we gave away the ref to the event in the push */
1694       event = NULL;
1695       break;
1696     default:
1697       break;
1698   }
1699 done:
1700   /* if we still have a ref to the event, unref it now */
1701   if (event)
1702     gst_event_unref (event);
1703
1704   return result;
1705
1706   /* ERRORS */
1707 wrong_mode:
1708   {
1709     GST_DEBUG_OBJECT (src, "cannot perform seek when operating in pull mode");
1710     GST_OBJECT_UNLOCK (src->srcpad);
1711     result = FALSE;
1712     goto done;
1713   }
1714 }
1715
1716 static gboolean
1717 gst_base_src_seekable (GstBaseSrc * src)
1718 {
1719   GstBaseSrcClass *bclass;
1720   bclass = GST_BASE_SRC_GET_CLASS (src);
1721   if (bclass->is_seekable)
1722     return bclass->is_seekable (src);
1723   else
1724     return FALSE;
1725 }
1726
1727 static void
1728 gst_base_src_update_qos (GstBaseSrc * src,
1729     gdouble proportion, GstClockTimeDiff diff, GstClockTime timestamp)
1730 {
1731   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, src,
1732       "qos: proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
1733       GST_TIME_FORMAT, proportion, diff, GST_TIME_ARGS (timestamp));
1734
1735   GST_OBJECT_LOCK (src);
1736   src->priv->proportion = proportion;
1737   src->priv->earliest_time = timestamp + diff;
1738   GST_OBJECT_UNLOCK (src);
1739 }
1740
1741
1742 static gboolean
1743 gst_base_src_default_event (GstBaseSrc * src, GstEvent * event)
1744 {
1745   gboolean result;
1746
1747   GST_DEBUG_OBJECT (src, "handle event %" GST_PTR_FORMAT, event);
1748
1749   switch (GST_EVENT_TYPE (event)) {
1750     case GST_EVENT_SEEK:
1751       /* is normally called when in push mode */
1752       if (!gst_base_src_seekable (src))
1753         goto not_seekable;
1754
1755       result = gst_base_src_perform_seek (src, event, TRUE);
1756       break;
1757     case GST_EVENT_FLUSH_START:
1758       /* cancel any blocking getrange, is normally called
1759        * when in pull mode. */
1760       result = gst_base_src_set_flushing (src, TRUE, FALSE, TRUE, NULL);
1761       break;
1762     case GST_EVENT_FLUSH_STOP:
1763       result = gst_base_src_set_flushing (src, FALSE, TRUE, TRUE, NULL);
1764       break;
1765     case GST_EVENT_QOS:
1766     {
1767       gdouble proportion;
1768       GstClockTimeDiff diff;
1769       GstClockTime timestamp;
1770
1771       gst_event_parse_qos (event, &proportion, &diff, &timestamp);
1772       gst_base_src_update_qos (src, proportion, diff, timestamp);
1773       result = TRUE;
1774       break;
1775     }
1776     default:
1777       result = FALSE;
1778       break;
1779   }
1780   return result;
1781
1782   /* ERRORS */
1783 not_seekable:
1784   {
1785     GST_DEBUG_OBJECT (src, "is not seekable");
1786     return FALSE;
1787   }
1788 }
1789
1790 static gboolean
1791 gst_base_src_event_handler (GstPad * pad, GstEvent * event)
1792 {
1793   GstBaseSrc *src;
1794   GstBaseSrcClass *bclass;
1795   gboolean result = FALSE;
1796
1797   src = GST_BASE_SRC (gst_pad_get_parent (pad));
1798   if (G_UNLIKELY (src == NULL)) {
1799     gst_event_unref (event);
1800     return FALSE;
1801   }
1802
1803   bclass = GST_BASE_SRC_GET_CLASS (src);
1804
1805   if (bclass->event) {
1806     if (!(result = bclass->event (src, event)))
1807       goto subclass_failed;
1808   }
1809
1810 done:
1811   gst_event_unref (event);
1812   gst_object_unref (src);
1813
1814   return result;
1815
1816   /* ERRORS */
1817 subclass_failed:
1818   {
1819     GST_DEBUG_OBJECT (src, "subclass refused event");
1820     goto done;
1821   }
1822 }
1823
1824 static void
1825 gst_base_src_set_property (GObject * object, guint prop_id,
1826     const GValue * value, GParamSpec * pspec)
1827 {
1828   GstBaseSrc *src;
1829
1830   src = GST_BASE_SRC (object);
1831
1832   switch (prop_id) {
1833     case PROP_BLOCKSIZE:
1834       gst_base_src_set_blocksize (src, g_value_get_ulong (value));
1835       break;
1836     case PROP_NUM_BUFFERS:
1837       src->num_buffers = g_value_get_int (value);
1838       break;
1839     case PROP_TYPEFIND:
1840       src->data.ABI.typefind = g_value_get_boolean (value);
1841       break;
1842     case PROP_DO_TIMESTAMP:
1843       gst_base_src_set_do_timestamp (src, g_value_get_boolean (value));
1844       break;
1845     default:
1846       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1847       break;
1848   }
1849 }
1850
1851 static void
1852 gst_base_src_get_property (GObject * object, guint prop_id, GValue * value,
1853     GParamSpec * pspec)
1854 {
1855   GstBaseSrc *src;
1856
1857   src = GST_BASE_SRC (object);
1858
1859   switch (prop_id) {
1860     case PROP_BLOCKSIZE:
1861       g_value_set_ulong (value, gst_base_src_get_blocksize (src));
1862       break;
1863     case PROP_NUM_BUFFERS:
1864       g_value_set_int (value, src->num_buffers);
1865       break;
1866     case PROP_TYPEFIND:
1867       g_value_set_boolean (value, src->data.ABI.typefind);
1868       break;
1869     case PROP_DO_TIMESTAMP:
1870       g_value_set_boolean (value, gst_base_src_get_do_timestamp (src));
1871       break;
1872     default:
1873       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1874       break;
1875   }
1876 }
1877
1878 /* with STREAM_LOCK and LOCK */
1879 static GstClockReturn
1880 gst_base_src_wait (GstBaseSrc * basesrc, GstClock * clock, GstClockTime time)
1881 {
1882   GstClockReturn ret;
1883   GstClockID id;
1884
1885   id = gst_clock_new_single_shot_id (clock, time);
1886
1887   basesrc->clock_id = id;
1888   /* release the live lock while waiting */
1889   GST_LIVE_UNLOCK (basesrc);
1890
1891   ret = gst_clock_id_wait (id, NULL);
1892
1893   GST_LIVE_LOCK (basesrc);
1894   gst_clock_id_unref (id);
1895   basesrc->clock_id = NULL;
1896
1897   return ret;
1898 }
1899
1900 /* perform synchronisation on a buffer.
1901  * with STREAM_LOCK.
1902  */
1903 static GstClockReturn
1904 gst_base_src_do_sync (GstBaseSrc * basesrc, GstBuffer * buffer)
1905 {
1906   GstClockReturn result;
1907   GstClockTime start, end;
1908   GstBaseSrcClass *bclass;
1909   GstClockTime base_time;
1910   GstClock *clock;
1911   GstClockTime now = GST_CLOCK_TIME_NONE, timestamp;
1912   gboolean do_timestamp, first, pseudo_live;
1913
1914   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
1915
1916   start = end = -1;
1917   if (bclass->get_times)
1918     bclass->get_times (basesrc, buffer, &start, &end);
1919
1920   /* get buffer timestamp */
1921   timestamp = GST_BUFFER_TIMESTAMP (buffer);
1922
1923   /* grab the lock to prepare for clocking and calculate the startup
1924    * latency. */
1925   GST_OBJECT_LOCK (basesrc);
1926
1927   /* if we are asked to sync against the clock we are a pseudo live element */
1928   pseudo_live = (start != -1 && basesrc->is_live);
1929   /* check for the first buffer */
1930   first = (basesrc->priv->latency == -1);
1931
1932   if (timestamp != -1 && pseudo_live) {
1933     GstClockTime latency;
1934
1935     /* we have a timestamp and a sync time, latency is the diff */
1936     if (timestamp <= start)
1937       latency = start - timestamp;
1938     else
1939       latency = 0;
1940
1941     if (first) {
1942       GST_DEBUG_OBJECT (basesrc, "pseudo_live with latency %" GST_TIME_FORMAT,
1943           GST_TIME_ARGS (latency));
1944       /* first time we calculate latency, just configure */
1945       basesrc->priv->latency = latency;
1946     } else {
1947       if (basesrc->priv->latency != latency) {
1948         /* we have a new latency, FIXME post latency message */
1949         basesrc->priv->latency = latency;
1950         GST_DEBUG_OBJECT (basesrc, "latency changed to %" GST_TIME_FORMAT,
1951             GST_TIME_ARGS (latency));
1952       }
1953     }
1954   } else if (first) {
1955     GST_DEBUG_OBJECT (basesrc, "no latency needed, live %d, sync %d",
1956         basesrc->is_live, start != -1);
1957     basesrc->priv->latency = 0;
1958   }
1959
1960   /* get clock, if no clock, we can't sync or do timestamps */
1961   if ((clock = GST_ELEMENT_CLOCK (basesrc)) == NULL)
1962     goto no_clock;
1963
1964   base_time = GST_ELEMENT_CAST (basesrc)->base_time;
1965
1966   do_timestamp = basesrc->priv->do_timestamp;
1967
1968   /* first buffer, calculate the timestamp offset */
1969   if (first) {
1970     GstClockTime running_time;
1971
1972     now = gst_clock_get_time (clock);
1973     running_time = now - base_time;
1974
1975     GST_LOG_OBJECT (basesrc,
1976         "startup timestamp: %" GST_TIME_FORMAT ", running_time %"
1977         GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
1978         GST_TIME_ARGS (running_time));
1979
1980     if (pseudo_live && timestamp != -1) {
1981       /* live source and we need to sync, add startup latency to all timestamps
1982        * to get the real running_time. Live sources should always timestamp
1983        * according to the current running time. */
1984       basesrc->priv->ts_offset = GST_CLOCK_DIFF (timestamp, running_time);
1985
1986       GST_LOG_OBJECT (basesrc, "live with sync, ts_offset %" GST_TIME_FORMAT,
1987           GST_TIME_ARGS (basesrc->priv->ts_offset));
1988     } else {
1989       basesrc->priv->ts_offset = 0;
1990       GST_LOG_OBJECT (basesrc, "no timestamp offset needed");
1991     }
1992
1993     if (!GST_CLOCK_TIME_IS_VALID (timestamp)) {
1994       if (do_timestamp)
1995         timestamp = running_time;
1996       else
1997         timestamp = 0;
1998
1999       GST_BUFFER_TIMESTAMP (buffer) = timestamp;
2000
2001       GST_LOG_OBJECT (basesrc, "created timestamp: %" GST_TIME_FORMAT,
2002           GST_TIME_ARGS (timestamp));
2003     }
2004
2005     /* add the timestamp offset we need for sync */
2006     timestamp += basesrc->priv->ts_offset;
2007   } else {
2008     /* not the first buffer, the timestamp is the diff between the clock and
2009      * base_time */
2010     if (do_timestamp && !GST_CLOCK_TIME_IS_VALID (timestamp)) {
2011       now = gst_clock_get_time (clock);
2012
2013       GST_BUFFER_TIMESTAMP (buffer) = now - base_time;
2014
2015       GST_LOG_OBJECT (basesrc, "created timestamp: %" GST_TIME_FORMAT,
2016           GST_TIME_ARGS (now - base_time));
2017     }
2018   }
2019
2020   /* if we don't have a buffer timestamp, we don't sync */
2021   if (!GST_CLOCK_TIME_IS_VALID (start))
2022     goto no_sync;
2023
2024   if (basesrc->is_live && GST_CLOCK_TIME_IS_VALID (timestamp)) {
2025     /* for pseudo live sources, add our ts_offset to the timestamp */
2026     GST_BUFFER_TIMESTAMP (buffer) += basesrc->priv->ts_offset;
2027     start += basesrc->priv->ts_offset;
2028   }
2029
2030   GST_LOG_OBJECT (basesrc,
2031       "waiting for clock, base time %" GST_TIME_FORMAT
2032       ", stream_start %" GST_TIME_FORMAT,
2033       GST_TIME_ARGS (base_time), GST_TIME_ARGS (start));
2034   GST_OBJECT_UNLOCK (basesrc);
2035
2036   result = gst_base_src_wait (basesrc, clock, start + base_time);
2037
2038   GST_LOG_OBJECT (basesrc, "clock entry done: %d", result);
2039
2040   return result;
2041
2042   /* special cases */
2043 no_clock:
2044   {
2045     GST_DEBUG_OBJECT (basesrc, "we have no clock");
2046     GST_OBJECT_UNLOCK (basesrc);
2047     return GST_CLOCK_OK;
2048   }
2049 no_sync:
2050   {
2051     GST_DEBUG_OBJECT (basesrc, "no sync needed");
2052     GST_OBJECT_UNLOCK (basesrc);
2053     return GST_CLOCK_OK;
2054   }
2055 }
2056
2057 /* Called with STREAM_LOCK and LIVE_LOCK */
2058 static gboolean
2059 gst_base_src_update_length (GstBaseSrc * src, guint64 offset, guint * length)
2060 {
2061   guint64 size, maxsize;
2062   GstBaseSrcClass *bclass;
2063   GstFormat format;
2064   gint64 stop;
2065   gboolean dynamic;
2066
2067   bclass = GST_BASE_SRC_GET_CLASS (src);
2068
2069   format = src->segment.format;
2070   stop = src->segment.stop;
2071   /* get total file size */
2072   size = (guint64) src->segment.duration;
2073
2074   /* only operate if we are working with bytes */
2075   if (format != GST_FORMAT_BYTES)
2076     return TRUE;
2077
2078   /* the max amount of bytes to read is the total size or
2079    * up to the segment.stop if present. */
2080   if (stop != -1)
2081     maxsize = MIN (size, stop);
2082   else
2083     maxsize = size;
2084
2085   GST_DEBUG_OBJECT (src,
2086       "reading offset %" G_GUINT64_FORMAT ", length %u, size %" G_GINT64_FORMAT
2087       ", segment.stop %" G_GINT64_FORMAT ", maxsize %" G_GINT64_FORMAT, offset,
2088       *length, size, stop, maxsize);
2089
2090   dynamic = g_atomic_int_get (&src->priv->dynamic_size);
2091   GST_DEBUG_OBJECT (src, "dynamic size: %d", dynamic);
2092
2093   /* check size if we have one */
2094   if (maxsize != -1) {
2095     /* if we run past the end, check if the file became bigger and
2096      * retry. */
2097     if (G_UNLIKELY (offset + *length >= maxsize || dynamic)) {
2098       /* see if length of the file changed */
2099       if (bclass->get_size)
2100         if (!bclass->get_size (src, &size))
2101           size = -1;
2102
2103       /* make sure we don't exceed the configured segment stop
2104        * if it was set */
2105       if (stop != -1)
2106         maxsize = MIN (size, stop);
2107       else
2108         maxsize = size;
2109
2110       /* if we are at or past the end, EOS */
2111       if (G_UNLIKELY (offset >= maxsize))
2112         goto unexpected_length;
2113
2114       /* else we can clip to the end */
2115       if (G_UNLIKELY (offset + *length >= maxsize))
2116         *length = maxsize - offset;
2117
2118     }
2119   }
2120
2121   /* keep track of current position and update duration.
2122    * segment is in bytes, we checked that above. */
2123   GST_OBJECT_LOCK (src);
2124   gst_segment_set_duration (&src->segment, GST_FORMAT_BYTES, size);
2125   GST_OBJECT_UNLOCK (src);
2126
2127   return TRUE;
2128
2129   /* ERRORS */
2130 unexpected_length:
2131   {
2132     return FALSE;
2133   }
2134 }
2135
2136 /* must be called with LIVE_LOCK */
2137 static GstFlowReturn
2138 gst_base_src_get_range (GstBaseSrc * src, guint64 offset, guint length,
2139     GstBuffer ** buf)
2140 {
2141   GstFlowReturn ret;
2142   GstBaseSrcClass *bclass;
2143   GstClockReturn status;
2144
2145   bclass = GST_BASE_SRC_GET_CLASS (src);
2146
2147 again:
2148   if (src->is_live) {
2149     if (G_UNLIKELY (!src->live_running)) {
2150       ret = gst_base_src_wait_playing (src);
2151       if (ret != GST_FLOW_OK)
2152         goto stopped;
2153     }
2154   }
2155
2156   if (G_UNLIKELY (!GST_OBJECT_FLAG_IS_SET (src, GST_BASE_SRC_STARTED)))
2157     goto not_started;
2158
2159   if (G_UNLIKELY (!bclass->create))
2160     goto no_function;
2161
2162   if (G_UNLIKELY (!gst_base_src_update_length (src, offset, &length)))
2163     goto unexpected_length;
2164
2165   /* track position */
2166   GST_OBJECT_LOCK (src);
2167   if (src->segment.format == GST_FORMAT_BYTES)
2168     gst_segment_set_last_stop (&src->segment, GST_FORMAT_BYTES, offset);
2169   GST_OBJECT_UNLOCK (src);
2170
2171   /* normally we don't count buffers */
2172   if (G_UNLIKELY (src->num_buffers_left >= 0)) {
2173     if (src->num_buffers_left == 0)
2174       goto reached_num_buffers;
2175     else
2176       src->num_buffers_left--;
2177   }
2178
2179   /* don't enter the create function if a pending EOS event was set. For the
2180    * logic of the pending_eos, check the event function of this class. */
2181   if (G_UNLIKELY (g_atomic_int_get (&src->priv->pending_eos)))
2182     goto eos;
2183
2184   GST_DEBUG_OBJECT (src,
2185       "calling create offset %" G_GUINT64_FORMAT " length %u, time %"
2186       G_GINT64_FORMAT, offset, length, src->segment.time);
2187
2188   ret = bclass->create (src, offset, length, buf);
2189
2190   /* The create function could be unlocked because we have a pending EOS. It's
2191    * possible that we have a valid buffer from create that we need to
2192    * discard when the create function returned _OK. */
2193   if (G_UNLIKELY (g_atomic_int_get (&src->priv->pending_eos))) {
2194     if (ret == GST_FLOW_OK) {
2195       gst_buffer_unref (*buf);
2196       *buf = NULL;
2197     }
2198     goto eos;
2199   }
2200
2201   if (G_UNLIKELY (ret != GST_FLOW_OK))
2202     goto not_ok;
2203
2204   /* no timestamp set and we are at offset 0, we can timestamp with 0 */
2205   if (offset == 0 && src->segment.time == 0
2206       && GST_BUFFER_TIMESTAMP (*buf) == -1 && !src->is_live) {
2207     *buf = gst_buffer_make_metadata_writable (*buf);
2208     GST_BUFFER_TIMESTAMP (*buf) = 0;
2209   }
2210
2211   /* set pad caps on the buffer if the buffer had no caps */
2212   if (GST_BUFFER_CAPS (*buf) == NULL) {
2213     *buf = gst_buffer_make_metadata_writable (*buf);
2214     gst_buffer_set_caps (*buf, GST_PAD_CAPS (src->srcpad));
2215   }
2216
2217   /* now sync before pushing the buffer */
2218   status = gst_base_src_do_sync (src, *buf);
2219
2220   /* waiting for the clock could have made us flushing */
2221   if (G_UNLIKELY (src->priv->flushing))
2222     goto flushing;
2223
2224   switch (status) {
2225     case GST_CLOCK_EARLY:
2226       /* the buffer is too late. We currently don't drop the buffer. */
2227       GST_DEBUG_OBJECT (src, "buffer too late!, returning anyway");
2228       break;
2229     case GST_CLOCK_OK:
2230       /* buffer synchronised properly */
2231       GST_DEBUG_OBJECT (src, "buffer ok");
2232       break;
2233     case GST_CLOCK_UNSCHEDULED:
2234       /* this case is triggered when we were waiting for the clock and
2235        * it got unlocked because we did a state change. In any case, get rid of
2236        * the buffer. */
2237       gst_buffer_unref (*buf);
2238       *buf = NULL;
2239       if (!src->live_running) {
2240         /* We return WRONG_STATE when we are not running to stop the dataflow also
2241          * get rid of the produced buffer. */
2242         GST_DEBUG_OBJECT (src,
2243             "clock was unscheduled (%d), returning WRONG_STATE", status);
2244         ret = GST_FLOW_WRONG_STATE;
2245       } else {
2246         /* If we are running when this happens, we quickly switched between
2247          * pause and playing. We try to produce a new buffer */
2248         GST_DEBUG_OBJECT (src,
2249             "clock was unscheduled (%d), but we are running", status);
2250         goto again;
2251       }
2252       break;
2253     default:
2254       /* all other result values are unexpected and errors */
2255       GST_ELEMENT_ERROR (src, CORE, CLOCK,
2256           (_("Internal clock error.")),
2257           ("clock returned unexpected return value %d", status));
2258       gst_buffer_unref (*buf);
2259       *buf = NULL;
2260       ret = GST_FLOW_ERROR;
2261       break;
2262   }
2263   return ret;
2264
2265   /* ERROR */
2266 stopped:
2267   {
2268     GST_DEBUG_OBJECT (src, "wait_playing returned %d (%s)", ret,
2269         gst_flow_get_name (ret));
2270     return ret;
2271   }
2272 not_ok:
2273   {
2274     GST_DEBUG_OBJECT (src, "create returned %d (%s)", ret,
2275         gst_flow_get_name (ret));
2276     return ret;
2277   }
2278 not_started:
2279   {
2280     GST_DEBUG_OBJECT (src, "getrange but not started");
2281     return GST_FLOW_WRONG_STATE;
2282   }
2283 no_function:
2284   {
2285     GST_DEBUG_OBJECT (src, "no create function");
2286     return GST_FLOW_ERROR;
2287   }
2288 unexpected_length:
2289   {
2290     GST_DEBUG_OBJECT (src, "unexpected length %u (offset=%" G_GUINT64_FORMAT
2291         ", size=%" G_GINT64_FORMAT ")", length, offset, src->segment.duration);
2292     return GST_FLOW_UNEXPECTED;
2293   }
2294 reached_num_buffers:
2295   {
2296     GST_DEBUG_OBJECT (src, "sent all buffers");
2297     return GST_FLOW_UNEXPECTED;
2298   }
2299 flushing:
2300   {
2301     GST_DEBUG_OBJECT (src, "we are flushing");
2302     gst_buffer_unref (*buf);
2303     *buf = NULL;
2304     return GST_FLOW_WRONG_STATE;
2305   }
2306 eos:
2307   {
2308     GST_DEBUG_OBJECT (src, "we are EOS");
2309     return GST_FLOW_UNEXPECTED;
2310   }
2311 }
2312
2313 static GstFlowReturn
2314 gst_base_src_pad_get_range (GstPad * pad, guint64 offset, guint length,
2315     GstBuffer ** buf)
2316 {
2317   GstBaseSrc *src;
2318   GstFlowReturn res;
2319
2320   src = GST_BASE_SRC_CAST (gst_object_ref (GST_OBJECT_PARENT (pad)));
2321
2322   GST_LIVE_LOCK (src);
2323   if (G_UNLIKELY (src->priv->flushing))
2324     goto flushing;
2325
2326   res = gst_base_src_get_range (src, offset, length, buf);
2327
2328 done:
2329   GST_LIVE_UNLOCK (src);
2330
2331   gst_object_unref (src);
2332
2333   return res;
2334
2335   /* ERRORS */
2336 flushing:
2337   {
2338     GST_DEBUG_OBJECT (src, "we are flushing");
2339     res = GST_FLOW_WRONG_STATE;
2340     goto done;
2341   }
2342 }
2343
2344 static gboolean
2345 gst_base_src_default_check_get_range (GstBaseSrc * src)
2346 {
2347   gboolean res;
2348
2349   if (!GST_OBJECT_FLAG_IS_SET (src, GST_BASE_SRC_STARTED)) {
2350     GST_LOG_OBJECT (src, "doing start/stop to check get_range support");
2351     if (G_LIKELY (gst_base_src_start (src)))
2352       gst_base_src_stop (src);
2353   }
2354
2355   /* we can operate in getrange mode if the native format is bytes
2356    * and we are seekable, this condition is set in the random_access
2357    * flag and is set in the _start() method. */
2358   res = src->random_access;
2359
2360   return res;
2361 }
2362
2363 static gboolean
2364 gst_base_src_check_get_range (GstBaseSrc * src)
2365 {
2366   GstBaseSrcClass *bclass;
2367   gboolean res;
2368
2369   bclass = GST_BASE_SRC_GET_CLASS (src);
2370
2371   if (bclass->check_get_range == NULL)
2372     goto no_function;
2373
2374   res = bclass->check_get_range (src);
2375   GST_LOG_OBJECT (src, "%s() returned %d",
2376       GST_DEBUG_FUNCPTR_NAME (bclass->check_get_range), (gint) res);
2377
2378   return res;
2379
2380   /* ERRORS */
2381 no_function:
2382   {
2383     GST_WARNING_OBJECT (src, "no check_get_range function set");
2384     return FALSE;
2385   }
2386 }
2387
2388 static gboolean
2389 gst_base_src_pad_check_get_range (GstPad * pad)
2390 {
2391   GstBaseSrc *src;
2392   gboolean res;
2393
2394   src = GST_BASE_SRC (GST_OBJECT_PARENT (pad));
2395
2396   res = gst_base_src_check_get_range (src);
2397
2398   return res;
2399 }
2400
2401 static void
2402 gst_base_src_loop (GstPad * pad)
2403 {
2404   GstBaseSrc *src;
2405   GstBuffer *buf = NULL;
2406   GstFlowReturn ret;
2407   gint64 position;
2408   gboolean eos;
2409   gulong blocksize;
2410   GList *pending_events = NULL, *tmp;
2411
2412   eos = FALSE;
2413
2414   src = GST_BASE_SRC (GST_OBJECT_PARENT (pad));
2415
2416   GST_LIVE_LOCK (src);
2417
2418   if (G_UNLIKELY (src->priv->flushing))
2419     goto flushing;
2420
2421   src->priv->last_sent_eos = FALSE;
2422
2423   blocksize = src->blocksize;
2424
2425   /* if we operate in bytes, we can calculate an offset */
2426   if (src->segment.format == GST_FORMAT_BYTES) {
2427     position = src->segment.last_stop;
2428     /* for negative rates, start with subtracting the blocksize */
2429     if (src->segment.rate < 0.0) {
2430       /* we cannot go below segment.start */
2431       if (position > src->segment.start + blocksize)
2432         position -= blocksize;
2433       else {
2434         /* last block, remainder up to segment.start */
2435         blocksize = position - src->segment.start;
2436         position = src->segment.start;
2437       }
2438     }
2439   } else
2440     position = -1;
2441
2442   GST_LOG_OBJECT (src, "next_ts %" GST_TIME_FORMAT " size %lu",
2443       GST_TIME_ARGS (position), blocksize);
2444
2445   ret = gst_base_src_get_range (src, position, blocksize, &buf);
2446   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2447     GST_INFO_OBJECT (src, "pausing after gst_base_src_get_range() = %s",
2448         gst_flow_get_name (ret));
2449     GST_LIVE_UNLOCK (src);
2450     goto pause;
2451   }
2452   /* this should not happen */
2453   if (G_UNLIKELY (buf == NULL))
2454     goto null_buffer;
2455
2456   /* push events to close/start our segment before we push the buffer. */
2457   if (G_UNLIKELY (src->priv->close_segment)) {
2458     gst_pad_push_event (pad, src->priv->close_segment);
2459     src->priv->close_segment = NULL;
2460   }
2461   if (G_UNLIKELY (src->priv->start_segment)) {
2462     gst_pad_push_event (pad, src->priv->start_segment);
2463     src->priv->start_segment = NULL;
2464   }
2465   src->priv->newsegment_pending = FALSE;
2466
2467   if (g_atomic_int_get (&src->priv->have_events)) {
2468     GST_OBJECT_LOCK (src);
2469     /* take the events */
2470     pending_events = src->priv->pending_events;
2471     src->priv->pending_events = NULL;
2472     g_atomic_int_set (&src->priv->have_events, FALSE);
2473     GST_OBJECT_UNLOCK (src);
2474   }
2475
2476   /* Push out pending events if any */
2477   if (G_UNLIKELY (pending_events != NULL)) {
2478     for (tmp = pending_events; tmp; tmp = g_list_next (tmp)) {
2479       GstEvent *ev = (GstEvent *) tmp->data;
2480       gst_pad_push_event (pad, ev);
2481     }
2482     g_list_free (pending_events);
2483   }
2484
2485   /* figure out the new position */
2486   switch (src->segment.format) {
2487     case GST_FORMAT_BYTES:
2488     {
2489       guint bufsize = GST_BUFFER_SIZE (buf);
2490
2491       /* we subtracted above for negative rates */
2492       if (src->segment.rate >= 0.0)
2493         position += bufsize;
2494       break;
2495     }
2496     case GST_FORMAT_TIME:
2497     {
2498       GstClockTime start, duration;
2499
2500       start = GST_BUFFER_TIMESTAMP (buf);
2501       duration = GST_BUFFER_DURATION (buf);
2502
2503       if (GST_CLOCK_TIME_IS_VALID (start))
2504         position = start;
2505       else
2506         position = src->segment.last_stop;
2507
2508       if (GST_CLOCK_TIME_IS_VALID (duration)) {
2509         if (src->segment.rate >= 0.0)
2510           position += duration;
2511         else if (position > duration)
2512           position -= duration;
2513         else
2514           position = 0;
2515       }
2516       break;
2517     }
2518     case GST_FORMAT_DEFAULT:
2519       if (src->segment.rate >= 0.0)
2520         position = GST_BUFFER_OFFSET_END (buf);
2521       else
2522         position = GST_BUFFER_OFFSET (buf);
2523       break;
2524     default:
2525       position = -1;
2526       break;
2527   }
2528   if (position != -1) {
2529     if (src->segment.rate >= 0.0) {
2530       /* positive rate, check if we reached the stop */
2531       if (src->segment.stop != -1) {
2532         if (position >= src->segment.stop) {
2533           eos = TRUE;
2534           position = src->segment.stop;
2535         }
2536       }
2537     } else {
2538       /* negative rate, check if we reached the start. start is always set to
2539        * something different from -1 */
2540       if (position <= src->segment.start) {
2541         eos = TRUE;
2542         position = src->segment.start;
2543       }
2544       /* when going reverse, all buffers are DISCONT */
2545       src->priv->discont = TRUE;
2546     }
2547     GST_OBJECT_LOCK (src);
2548     gst_segment_set_last_stop (&src->segment, src->segment.format, position);
2549     GST_OBJECT_UNLOCK (src);
2550   }
2551
2552   if (G_UNLIKELY (src->priv->discont)) {
2553     buf = gst_buffer_make_metadata_writable (buf);
2554     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
2555     src->priv->discont = FALSE;
2556   }
2557   GST_LIVE_UNLOCK (src);
2558
2559   ret = gst_pad_push (pad, buf);
2560   if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2561     GST_INFO_OBJECT (src, "pausing after gst_pad_push() = %s",
2562         gst_flow_get_name (ret));
2563     goto pause;
2564   }
2565
2566   if (G_UNLIKELY (eos)) {
2567     GST_INFO_OBJECT (src, "pausing after end of segment");
2568     ret = GST_FLOW_UNEXPECTED;
2569     goto pause;
2570   }
2571
2572 done:
2573   return;
2574
2575   /* special cases */
2576 flushing:
2577   {
2578     GST_DEBUG_OBJECT (src, "we are flushing");
2579     GST_LIVE_UNLOCK (src);
2580     ret = GST_FLOW_WRONG_STATE;
2581     goto pause;
2582   }
2583 pause:
2584   {
2585     const gchar *reason = gst_flow_get_name (ret);
2586     GstEvent *event;
2587
2588     GST_DEBUG_OBJECT (src, "pausing task, reason %s", reason);
2589     src->data.ABI.running = FALSE;
2590     gst_pad_pause_task (pad);
2591     if (ret == GST_FLOW_UNEXPECTED) {
2592       gboolean flag_segment;
2593       GstFormat format;
2594       gint64 last_stop;
2595
2596       /* perform EOS logic */
2597       flag_segment = (src->segment.flags & GST_SEEK_FLAG_SEGMENT) != 0;
2598       format = src->segment.format;
2599       last_stop = src->segment.last_stop;
2600
2601       if (flag_segment) {
2602         GstMessage *message;
2603
2604         message = gst_message_new_segment_done (GST_OBJECT_CAST (src),
2605             format, last_stop);
2606         gst_message_set_seqnum (message, src->priv->seqnum);
2607         gst_element_post_message (GST_ELEMENT_CAST (src), message);
2608       } else {
2609         event = gst_event_new_eos ();
2610         gst_event_set_seqnum (event, src->priv->seqnum);
2611         gst_pad_push_event (pad, event);
2612         src->priv->last_sent_eos = TRUE;
2613       }
2614     } else if (ret == GST_FLOW_NOT_LINKED || ret <= GST_FLOW_UNEXPECTED) {
2615       event = gst_event_new_eos ();
2616       gst_event_set_seqnum (event, src->priv->seqnum);
2617       /* for fatal errors we post an error message, post the error
2618        * first so the app knows about the error first.
2619        * Also don't do this for WRONG_STATE because it happens
2620        * due to flushing and posting an error message because of
2621        * that is the wrong thing to do, e.g. when we're doing
2622        * a flushing seek. */
2623       GST_ELEMENT_ERROR (src, STREAM, FAILED,
2624           (_("Internal data flow error.")),
2625           ("streaming task paused, reason %s (%d)", reason, ret));
2626       gst_pad_push_event (pad, event);
2627       src->priv->last_sent_eos = TRUE;
2628     }
2629     goto done;
2630   }
2631 null_buffer:
2632   {
2633     GST_ELEMENT_ERROR (src, STREAM, FAILED,
2634         (_("Internal data flow error.")), ("element returned NULL buffer"));
2635     GST_LIVE_UNLOCK (src);
2636     goto done;
2637   }
2638 }
2639
2640 /* default negotiation code.
2641  *
2642  * Take intersection between src and sink pads, take first
2643  * caps and fixate.
2644  */
2645 static gboolean
2646 gst_base_src_default_negotiate (GstBaseSrc * basesrc)
2647 {
2648   GstCaps *thiscaps;
2649   GstCaps *caps = NULL;
2650   GstCaps *peercaps = NULL;
2651   gboolean result = FALSE;
2652
2653   /* first see what is possible on our source pad */
2654   thiscaps = gst_pad_get_caps_reffed (GST_BASE_SRC_PAD (basesrc));
2655   GST_DEBUG_OBJECT (basesrc, "caps of src: %" GST_PTR_FORMAT, thiscaps);
2656   /* nothing or anything is allowed, we're done */
2657   if (thiscaps == NULL || gst_caps_is_any (thiscaps))
2658     goto no_nego_needed;
2659
2660   if (G_UNLIKELY (gst_caps_is_empty (thiscaps)))
2661     goto no_caps;
2662
2663   /* get the peer caps */
2664   peercaps = gst_pad_peer_get_caps_reffed (GST_BASE_SRC_PAD (basesrc));
2665   GST_DEBUG_OBJECT (basesrc, "caps of peer: %" GST_PTR_FORMAT, peercaps);
2666   if (peercaps) {
2667     /* get intersection */
2668     caps =
2669         gst_caps_intersect_full (peercaps, thiscaps, GST_CAPS_INTERSECT_FIRST);
2670     GST_DEBUG_OBJECT (basesrc, "intersect: %" GST_PTR_FORMAT, caps);
2671     gst_caps_unref (peercaps);
2672   } else {
2673     /* no peer, work with our own caps then */
2674     caps = gst_caps_copy (thiscaps);
2675   }
2676   gst_caps_unref (thiscaps);
2677   if (caps) {
2678     /* take first (and best, since they are sorted) possibility */
2679     gst_caps_truncate (caps);
2680
2681     /* now fixate */
2682     if (!gst_caps_is_empty (caps)) {
2683       gst_pad_fixate_caps (GST_BASE_SRC_PAD (basesrc), caps);
2684       GST_DEBUG_OBJECT (basesrc, "fixated to: %" GST_PTR_FORMAT, caps);
2685
2686       if (gst_caps_is_any (caps)) {
2687         /* hmm, still anything, so element can do anything and
2688          * nego is not needed */
2689         result = TRUE;
2690       } else if (gst_caps_is_fixed (caps)) {
2691         /* yay, fixed caps, use those then, it's possible that the subclass does
2692          * not accept this caps after all and we have to fail. */
2693         result = gst_pad_set_caps (GST_BASE_SRC_PAD (basesrc), caps);
2694       }
2695     }
2696     gst_caps_unref (caps);
2697   } else {
2698     GST_DEBUG_OBJECT (basesrc, "no common caps");
2699   }
2700   return result;
2701
2702 no_nego_needed:
2703   {
2704     GST_DEBUG_OBJECT (basesrc, "no negotiation needed");
2705     if (thiscaps)
2706       gst_caps_unref (thiscaps);
2707     return TRUE;
2708   }
2709 no_caps:
2710   {
2711     GST_ELEMENT_ERROR (basesrc, STREAM, FORMAT,
2712         ("No supported formats found"),
2713         ("This element did not produce valid caps"));
2714     if (thiscaps)
2715       gst_caps_unref (thiscaps);
2716     return TRUE;
2717   }
2718 }
2719
2720 static gboolean
2721 gst_base_src_negotiate (GstBaseSrc * basesrc)
2722 {
2723   GstBaseSrcClass *bclass;
2724   gboolean result = TRUE;
2725
2726   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
2727
2728   if (bclass->negotiate)
2729     result = bclass->negotiate (basesrc);
2730
2731   return result;
2732 }
2733
2734 static gboolean
2735 gst_base_src_start (GstBaseSrc * basesrc)
2736 {
2737   GstBaseSrcClass *bclass;
2738   gboolean result;
2739   guint64 size;
2740   gboolean seekable;
2741   GstFormat format;
2742
2743   if (GST_OBJECT_FLAG_IS_SET (basesrc, GST_BASE_SRC_STARTED))
2744     return TRUE;
2745
2746   GST_DEBUG_OBJECT (basesrc, "starting source");
2747
2748   basesrc->num_buffers_left = basesrc->num_buffers;
2749
2750   GST_OBJECT_LOCK (basesrc);
2751   gst_segment_init (&basesrc->segment, basesrc->segment.format);
2752   GST_OBJECT_UNLOCK (basesrc);
2753
2754   basesrc->data.ABI.running = FALSE;
2755   basesrc->priv->newsegment_pending = FALSE;
2756
2757   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
2758   if (bclass->start)
2759     result = bclass->start (basesrc);
2760   else
2761     result = TRUE;
2762
2763   if (!result)
2764     goto could_not_start;
2765
2766   GST_OBJECT_FLAG_SET (basesrc, GST_BASE_SRC_STARTED);
2767
2768   format = basesrc->segment.format;
2769
2770   /* figure out the size */
2771   if (format == GST_FORMAT_BYTES) {
2772     if (bclass->get_size) {
2773       if (!(result = bclass->get_size (basesrc, &size)))
2774         size = -1;
2775     } else {
2776       result = FALSE;
2777       size = -1;
2778     }
2779     GST_DEBUG_OBJECT (basesrc, "setting size %" G_GUINT64_FORMAT, size);
2780     /* only update the size when operating in bytes, subclass is supposed
2781      * to set duration in the start method for other formats */
2782     GST_OBJECT_LOCK (basesrc);
2783     gst_segment_set_duration (&basesrc->segment, GST_FORMAT_BYTES, size);
2784     GST_OBJECT_UNLOCK (basesrc);
2785   } else {
2786     size = -1;
2787   }
2788
2789   GST_DEBUG_OBJECT (basesrc,
2790       "format: %s, have size: %d, size: %" G_GUINT64_FORMAT ", duration: %"
2791       G_GINT64_FORMAT, gst_format_get_name (format), result, size,
2792       basesrc->segment.duration);
2793
2794   seekable = gst_base_src_seekable (basesrc);
2795   GST_DEBUG_OBJECT (basesrc, "is seekable: %d", seekable);
2796
2797   /* update for random access flag */
2798   basesrc->random_access = seekable && format == GST_FORMAT_BYTES;
2799
2800   GST_DEBUG_OBJECT (basesrc, "is random_access: %d", basesrc->random_access);
2801
2802   /* run typefind if we are random_access and the typefinding is enabled. */
2803   if (basesrc->random_access && basesrc->data.ABI.typefind && size != -1) {
2804     GstCaps *caps;
2805
2806     if (!(caps = gst_type_find_helper (basesrc->srcpad, size)))
2807       goto typefind_failed;
2808
2809     result = gst_pad_set_caps (basesrc->srcpad, caps);
2810     gst_caps_unref (caps);
2811   } else {
2812     /* use class or default negotiate function */
2813     if (!(result = gst_base_src_negotiate (basesrc)))
2814       goto could_not_negotiate;
2815   }
2816
2817   return result;
2818
2819   /* ERROR */
2820 could_not_start:
2821   {
2822     GST_DEBUG_OBJECT (basesrc, "could not start");
2823     /* subclass is supposed to post a message. We don't have to call _stop. */
2824     return FALSE;
2825   }
2826 could_not_negotiate:
2827   {
2828     GST_DEBUG_OBJECT (basesrc, "could not negotiate, stopping");
2829     GST_ELEMENT_ERROR (basesrc, STREAM, FORMAT,
2830         ("Could not negotiate format"), ("Check your filtered caps, if any"));
2831     /* we must call stop */
2832     gst_base_src_stop (basesrc);
2833     return FALSE;
2834   }
2835 typefind_failed:
2836   {
2837     GST_DEBUG_OBJECT (basesrc, "could not typefind, stopping");
2838     GST_ELEMENT_ERROR (basesrc, STREAM, TYPE_NOT_FOUND, (NULL), (NULL));
2839     /* we must call stop */
2840     gst_base_src_stop (basesrc);
2841     return FALSE;
2842   }
2843 }
2844
2845 static gboolean
2846 gst_base_src_stop (GstBaseSrc * basesrc)
2847 {
2848   GstBaseSrcClass *bclass;
2849   gboolean result = TRUE;
2850
2851   if (!GST_OBJECT_FLAG_IS_SET (basesrc, GST_BASE_SRC_STARTED))
2852     return TRUE;
2853
2854   GST_DEBUG_OBJECT (basesrc, "stopping source");
2855
2856   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
2857   if (bclass->stop)
2858     result = bclass->stop (basesrc);
2859
2860   if (result)
2861     GST_OBJECT_FLAG_UNSET (basesrc, GST_BASE_SRC_STARTED);
2862
2863   return result;
2864 }
2865
2866 /* start or stop flushing dataprocessing
2867  */
2868 static gboolean
2869 gst_base_src_set_flushing (GstBaseSrc * basesrc,
2870     gboolean flushing, gboolean live_play, gboolean unlock, gboolean * playing)
2871 {
2872   GstBaseSrcClass *bclass;
2873
2874   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
2875
2876   if (flushing && unlock) {
2877     /* unlock any subclasses, we need to do this before grabbing the
2878      * LIVE_LOCK since we hold this lock before going into ::create. We pass an
2879      * unlock to the params because of backwards compat (see seek handler)*/
2880     if (bclass->unlock)
2881       bclass->unlock (basesrc);
2882   }
2883
2884   /* the live lock is released when we are blocked, waiting for playing or
2885    * when we sync to the clock. */
2886   GST_LIVE_LOCK (basesrc);
2887   if (playing)
2888     *playing = basesrc->live_running;
2889   basesrc->priv->flushing = flushing;
2890   if (flushing) {
2891     /* if we are locked in the live lock, signal it to make it flush */
2892     basesrc->live_running = TRUE;
2893
2894     /* clear pending EOS if any */
2895     g_atomic_int_set (&basesrc->priv->pending_eos, FALSE);
2896
2897     /* step 1, now that we have the LIVE lock, clear our unlock request */
2898     if (bclass->unlock_stop)
2899       bclass->unlock_stop (basesrc);
2900
2901     /* step 2, unblock clock sync (if any) or any other blocking thing */
2902     if (basesrc->clock_id)
2903       gst_clock_id_unschedule (basesrc->clock_id);
2904   } else {
2905     /* signal the live source that it can start playing */
2906     basesrc->live_running = live_play;
2907
2908     /* When unlocking drop all delayed events */
2909     if (unlock) {
2910       GST_OBJECT_LOCK (basesrc);
2911       if (basesrc->priv->pending_events) {
2912         g_list_foreach (basesrc->priv->pending_events, (GFunc) gst_event_unref,
2913             NULL);
2914         g_list_free (basesrc->priv->pending_events);
2915         basesrc->priv->pending_events = NULL;
2916         g_atomic_int_set (&basesrc->priv->have_events, FALSE);
2917       }
2918       GST_OBJECT_UNLOCK (basesrc);
2919     }
2920   }
2921   GST_LIVE_SIGNAL (basesrc);
2922   GST_LIVE_UNLOCK (basesrc);
2923
2924   return TRUE;
2925 }
2926
2927 /* the purpose of this function is to make sure that a live source blocks in the
2928  * LIVE lock or leaves the LIVE lock and continues playing. */
2929 static gboolean
2930 gst_base_src_set_playing (GstBaseSrc * basesrc, gboolean live_play)
2931 {
2932   GstBaseSrcClass *bclass;
2933
2934   bclass = GST_BASE_SRC_GET_CLASS (basesrc);
2935
2936   /* unlock subclasses locked in ::create, we only do this when we stop playing. */
2937   if (!live_play) {
2938     GST_DEBUG_OBJECT (basesrc, "unlock");
2939     if (bclass->unlock)
2940       bclass->unlock (basesrc);
2941   }
2942
2943   /* we are now able to grab the LIVE lock, when we get it, we can be
2944    * waiting for PLAYING while blocked in the LIVE cond or we can be waiting
2945    * for the clock. */
2946   GST_LIVE_LOCK (basesrc);
2947   GST_DEBUG_OBJECT (basesrc, "unschedule clock");
2948
2949   /* unblock clock sync (if any) */
2950   if (basesrc->clock_id)
2951     gst_clock_id_unschedule (basesrc->clock_id);
2952
2953   /* configure what to do when we get to the LIVE lock. */
2954   GST_DEBUG_OBJECT (basesrc, "live running %d", live_play);
2955   basesrc->live_running = live_play;
2956
2957   if (live_play) {
2958     gboolean start;
2959
2960     /* clear our unlock request when going to PLAYING */
2961     GST_DEBUG_OBJECT (basesrc, "unlock stop");
2962     if (bclass->unlock_stop)
2963       bclass->unlock_stop (basesrc);
2964
2965     /* for live sources we restart the timestamp correction */
2966     basesrc->priv->latency = -1;
2967     /* have to restart the task in case it stopped because of the unlock when
2968      * we went to PAUSED. Only do this if we operating in push mode. */
2969     GST_OBJECT_LOCK (basesrc->srcpad);
2970     start = (GST_PAD_ACTIVATE_MODE (basesrc->srcpad) == GST_ACTIVATE_PUSH);
2971     GST_OBJECT_UNLOCK (basesrc->srcpad);
2972     if (start)
2973       gst_pad_start_task (basesrc->srcpad, (GstTaskFunction) gst_base_src_loop,
2974           basesrc->srcpad);
2975     GST_DEBUG_OBJECT (basesrc, "signal");
2976     GST_LIVE_SIGNAL (basesrc);
2977   }
2978   GST_LIVE_UNLOCK (basesrc);
2979
2980   return TRUE;
2981 }
2982
2983 static gboolean
2984 gst_base_src_activate_push (GstPad * pad, gboolean active)
2985 {
2986   GstBaseSrc *basesrc;
2987   GstEvent *event;
2988
2989   basesrc = GST_BASE_SRC (GST_OBJECT_PARENT (pad));
2990
2991   /* prepare subclass first */
2992   if (active) {
2993     GST_DEBUG_OBJECT (basesrc, "Activating in push mode");
2994
2995     if (G_UNLIKELY (!basesrc->can_activate_push))
2996       goto no_push_activation;
2997
2998     if (G_UNLIKELY (!gst_base_src_start (basesrc)))
2999       goto error_start;
3000
3001     basesrc->priv->last_sent_eos = FALSE;
3002     basesrc->priv->discont = TRUE;
3003     gst_base_src_set_flushing (basesrc, FALSE, FALSE, FALSE, NULL);
3004
3005     /* do initial seek, which will start the task */
3006     GST_OBJECT_LOCK (basesrc);
3007     event = basesrc->data.ABI.pending_seek;
3008     basesrc->data.ABI.pending_seek = NULL;
3009     GST_OBJECT_UNLOCK (basesrc);
3010
3011     /* no need to unlock anything, the task is certainly
3012      * not running here. The perform seek code will start the task when
3013      * finished. */
3014     if (G_UNLIKELY (!gst_base_src_perform_seek (basesrc, event, FALSE)))
3015       goto seek_failed;
3016
3017     if (event)
3018       gst_event_unref (event);
3019   } else {
3020     GST_DEBUG_OBJECT (basesrc, "Deactivating in push mode");
3021     /* flush all */
3022     gst_base_src_set_flushing (basesrc, TRUE, FALSE, TRUE, NULL);
3023     /* stop the task */
3024     gst_pad_stop_task (pad);
3025     /* now we can stop the source */
3026     if (G_UNLIKELY (!gst_base_src_stop (basesrc)))
3027       goto error_stop;
3028   }
3029   return TRUE;
3030
3031   /* ERRORS */
3032 no_push_activation:
3033   {
3034     GST_WARNING_OBJECT (basesrc, "Subclass disabled push-mode activation");
3035     return FALSE;
3036   }
3037 error_start:
3038   {
3039     GST_WARNING_OBJECT (basesrc, "Failed to start in push mode");
3040     return FALSE;
3041   }
3042 seek_failed:
3043   {
3044     GST_ERROR_OBJECT (basesrc, "Failed to perform initial seek");
3045     /* flush all */
3046     gst_base_src_set_flushing (basesrc, TRUE, FALSE, TRUE, NULL);
3047     /* stop the task */
3048     gst_pad_stop_task (pad);
3049     /* Stop the basesrc */
3050     gst_base_src_stop (basesrc);
3051     if (event)
3052       gst_event_unref (event);
3053     return FALSE;
3054   }
3055 error_stop:
3056   {
3057     GST_DEBUG_OBJECT (basesrc, "Failed to stop in push mode");
3058     return FALSE;
3059   }
3060 }
3061
3062 static gboolean
3063 gst_base_src_activate_pull (GstPad * pad, gboolean active)
3064 {
3065   GstBaseSrc *basesrc;
3066
3067   basesrc = GST_BASE_SRC (GST_OBJECT_PARENT (pad));
3068
3069   /* prepare subclass first */
3070   if (active) {
3071     GST_DEBUG_OBJECT (basesrc, "Activating in pull mode");
3072     if (G_UNLIKELY (!gst_base_src_start (basesrc)))
3073       goto error_start;
3074
3075     /* if not random_access, we cannot operate in pull mode for now */
3076     if (G_UNLIKELY (!gst_base_src_check_get_range (basesrc)))
3077       goto no_get_range;
3078
3079     /* stop flushing now but for live sources, still block in the LIVE lock when
3080      * we are not yet PLAYING */
3081     gst_base_src_set_flushing (basesrc, FALSE, FALSE, FALSE, NULL);
3082   } else {
3083     GST_DEBUG_OBJECT (basesrc, "Deactivating in pull mode");
3084     /* flush all, there is no task to stop */
3085     gst_base_src_set_flushing (basesrc, TRUE, FALSE, TRUE, NULL);
3086
3087     /* don't send EOS when going from PAUSED => READY when in pull mode */
3088     basesrc->priv->last_sent_eos = TRUE;
3089
3090     if (G_UNLIKELY (!gst_base_src_stop (basesrc)))
3091       goto error_stop;
3092   }
3093   return TRUE;
3094
3095   /* ERRORS */
3096 error_start:
3097   {
3098     GST_ERROR_OBJECT (basesrc, "Failed to start in pull mode");
3099     return FALSE;
3100   }
3101 no_get_range:
3102   {
3103     GST_ERROR_OBJECT (basesrc, "Cannot operate in pull mode, stopping");
3104     gst_base_src_stop (basesrc);
3105     return FALSE;
3106   }
3107 error_stop:
3108   {
3109     GST_ERROR_OBJECT (basesrc, "Failed to stop in pull mode");
3110     return FALSE;
3111   }
3112 }
3113
3114 static GstStateChangeReturn
3115 gst_base_src_change_state (GstElement * element, GstStateChange transition)
3116 {
3117   GstBaseSrc *basesrc;
3118   GstStateChangeReturn result;
3119   gboolean no_preroll = FALSE;
3120
3121   basesrc = GST_BASE_SRC (element);
3122
3123   switch (transition) {
3124     case GST_STATE_CHANGE_NULL_TO_READY:
3125       break;
3126     case GST_STATE_CHANGE_READY_TO_PAUSED:
3127       no_preroll = gst_base_src_is_live (basesrc);
3128       break;
3129     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3130       GST_DEBUG_OBJECT (basesrc, "PAUSED->PLAYING");
3131       if (gst_base_src_is_live (basesrc)) {
3132         /* now we can start playback */
3133         gst_base_src_set_playing (basesrc, TRUE);
3134       }
3135       break;
3136     default:
3137       break;
3138   }
3139
3140   if ((result =
3141           GST_ELEMENT_CLASS (parent_class)->change_state (element,
3142               transition)) == GST_STATE_CHANGE_FAILURE)
3143     goto failure;
3144
3145   switch (transition) {
3146     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3147       GST_DEBUG_OBJECT (basesrc, "PLAYING->PAUSED");
3148       if (gst_base_src_is_live (basesrc)) {
3149         /* make sure we block in the live lock in PAUSED */
3150         gst_base_src_set_playing (basesrc, FALSE);
3151         no_preroll = TRUE;
3152       }
3153       break;
3154     case GST_STATE_CHANGE_PAUSED_TO_READY:
3155     {
3156       GstEvent **event_p, *event;
3157
3158       /* we don't need to unblock anything here, the pad deactivation code
3159        * already did this */
3160
3161       /* FIXME, deprecate this behaviour, it is very dangerous.
3162        * the preferred way of sending EOS downstream is by sending
3163        * the EOS event to the element */
3164       if (!basesrc->priv->last_sent_eos) {
3165         GST_DEBUG_OBJECT (basesrc, "Sending EOS event");
3166         event = gst_event_new_eos ();
3167         gst_event_set_seqnum (event, basesrc->priv->seqnum);
3168         gst_pad_push_event (basesrc->srcpad, event);
3169         basesrc->priv->last_sent_eos = TRUE;
3170       }
3171       g_atomic_int_set (&basesrc->priv->pending_eos, FALSE);
3172       event_p = &basesrc->data.ABI.pending_seek;
3173       gst_event_replace (event_p, NULL);
3174       event_p = &basesrc->priv->close_segment;
3175       gst_event_replace (event_p, NULL);
3176       event_p = &basesrc->priv->start_segment;
3177       gst_event_replace (event_p, NULL);
3178       break;
3179     }
3180     case GST_STATE_CHANGE_READY_TO_NULL:
3181       break;
3182     default:
3183       break;
3184   }
3185
3186   if (no_preroll && result == GST_STATE_CHANGE_SUCCESS)
3187     result = GST_STATE_CHANGE_NO_PREROLL;
3188
3189   return result;
3190
3191   /* ERRORS */
3192 failure:
3193   {
3194     GST_DEBUG_OBJECT (basesrc, "parent failed state change");
3195     return result;
3196   }
3197 }