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