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