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