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