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