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