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