gst: Use g_once_init* or G_DEFINE_TYPE
[platform/upstream/gstreamer.git] / libs / gst / base / gstbasesink.c
1 /* GStreamer
2  * Copyright (C) 2005-2007 Wim Taymans <wim.taymans@gmail.com>
3  *
4  * gstbasesink.c: Base class for sink elements
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gstbasesink
24  * @short_description: Base class for sink elements
25  * @see_also: #GstBaseTransform, #GstBaseSource
26  *
27  * #GstBaseSink is the base class for sink elements in GStreamer, such as
28  * xvimagesink or filesink. It is a layer on top of #GstElement that provides a
29  * simplified interface to plugin writers. #GstBaseSink handles many details
30  * for you, for example: preroll, clock synchronization, state changes,
31  * activation in push or pull mode, and queries.
32  *
33  * In most cases, when writing sink elements, there is no need to implement
34  * class methods from #GstElement or to set functions on pads, because the
35  * #GstBaseSink infrastructure should be sufficient.
36  *
37  * #GstBaseSink provides support for exactly one sink pad, which should be
38  * named "sink". A sink implementation (subclass of #GstBaseSink) should
39  * install a pad template in its base_init function, like so:
40  * <programlisting>
41  * static void
42  * my_element_base_init (gpointer g_class)
43  * {
44  *   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
45  *   
46  *   // sinktemplate should be a #GstStaticPadTemplate with direction
47  *   // #GST_PAD_SINK and name "sink"
48  *   gst_element_class_add_pad_template (gstelement_class,
49  *       gst_static_pad_template_get (&amp;sinktemplate));
50  *   // see #GstElementDetails
51  *   gst_element_class_set_details (gstelement_class, &amp;details);
52  * }
53  * </programlisting>
54  *
55  * #GstBaseSink will handle the prerolling correctly. This means that it will
56  * return #GST_STATE_CHANGE_ASYNC from a state change to PAUSED until the first
57  * buffer arrives in this element. The base class will call the
58  * #GstBaseSink::preroll vmethod with this preroll buffer and will then commit
59  * the state change to the next asynchronously pending state.
60  *
61  * When the element is set to PLAYING, #GstBaseSink will synchronise on the
62  * clock using the times returned from ::get_times. If this function returns
63  * #GST_CLOCK_TIME_NONE for the start time, no synchronisation will be done.
64  * Synchronisation can be disabled entirely by setting the object "sync"
65  * property to %FALSE.
66  *
67  * After synchronisation the virtual method #GstBaseSink::render will be called.
68  * Subclasses should minimally implement this method.
69  *
70  * Since 0.10.3 subclasses that synchronise on the clock in the ::render method
71  * are supported as well. These classes typically receive a buffer in the render
72  * method and can then potentially block on the clock while rendering. A typical
73  * example is an audiosink. Since 0.10.11 these subclasses can use
74  * gst_base_sink_wait_preroll() to perform the blocking wait.
75  *
76  * Upon receiving the EOS event in the PLAYING state, #GstBaseSink will wait
77  * for the clock to reach the time indicated by the stop time of the last
78  * ::get_times call before posting an EOS message. When the element receives
79  * EOS in PAUSED, preroll completes, the event is queued and an EOS message is
80  * posted when going to PLAYING.
81  *
82  * #GstBaseSink will internally use the #GST_EVENT_NEWSEGMENT events to schedule
83  * synchronisation and clipping of buffers. Buffers that fall completely outside
84  * of the current segment are dropped. Buffers that fall partially in the
85  * segment are rendered (and prerolled). Subclasses should do any subbuffer
86  * clipping themselves when needed.
87  *
88  * #GstBaseSink will by default report the current playback position in
89  * #GST_FORMAT_TIME based on the current clock time and segment information.
90  * If no clock has been set on the element, the query will be forwarded
91  * upstream.
92  *
93  * The ::set_caps function will be called when the subclass should configure
94  * itself to process a specific media type.
95  *
96  * The ::start and ::stop virtual methods will be called when resources should
97  * be allocated. Any ::preroll, ::render  and ::set_caps function will be
98  * called between the ::start and ::stop calls.
99  *
100  * The ::event virtual method will be called when an event is received by
101  * #GstBaseSink. Normally this method should only be overriden by very specific
102  * elements (such as file sinks) which need to handle the newsegment event
103  * specially.
104  *
105  * #GstBaseSink provides an overridable ::buffer_alloc function that can be
106  * used by sinks that want to do reverse negotiation or to provide
107  * custom buffers (hardware buffers for example) to upstream elements.
108  *
109  * The ::unlock method is called when the elements should unblock any blocking
110  * operations they perform in the ::render method. This is mostly useful when
111  * the ::render method performs a blocking write on a file descriptor, for
112  * example.
113  *
114  * The max-lateness property affects how the sink deals with buffers that
115  * arrive too late in the sink. A buffer arrives too late in the sink when
116  * the presentation time (as a combination of the last segment, buffer
117  * timestamp and element base_time) plus the duration is before the current
118  * time of the clock.
119  * If the frame is later than max-lateness, the sink will drop the buffer
120  * without calling the render method.
121  * This feature is disabled if sync is disabled, the ::get-times method does
122  * not return a valid start time or max-lateness is set to -1 (the default).
123  * Subclasses can use gst_base_sink_set_max_lateness() to configure the
124  * max-lateness value.
125  *
126  * The qos property will enable the quality-of-service features of the basesink
127  * which gather statistics about the real-time performance of the clock
128  * synchronisation. For each buffer received in the sink, statistics are
129  * gathered and a QOS event is sent upstream with these numbers. This
130  * information can then be used by upstream elements to reduce their processing
131  * rate, for example.
132  *
133  * Since 0.10.15 the async property can be used to instruct the sink to never
134  * perform an ASYNC state change. This feature is mostly usable when dealing
135  * with non-synchronized streams or sparse streams.
136  *
137  * Last reviewed on 2007-08-29 (0.10.15)
138  */
139
140 #ifdef HAVE_CONFIG_H
141 #  include "config.h"
142 #endif
143
144 #include "gstbasesink.h"
145 #include <gst/gstmarshal.h>
146 #include <gst/gst_private.h>
147 #include <gst/gst-i18n-lib.h>
148
149 GST_DEBUG_CATEGORY_STATIC (gst_base_sink_debug);
150 #define GST_CAT_DEFAULT gst_base_sink_debug
151
152 #define GST_BASE_SINK_GET_PRIVATE(obj)  \
153    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_SINK, GstBaseSinkPrivate))
154
155 /* FIXME, some stuff in ABI.data and other in Private...
156  * Make up your mind please.
157  */
158 struct _GstBaseSinkPrivate
159 {
160   gint qos_enabled;             /* ATOMIC */
161   gboolean async_enabled;
162   GstClockTimeDiff ts_offset;
163   GstClockTime render_delay;
164
165   /* start, stop of current buffer, stream time, used to report position */
166   GstClockTime current_sstart;
167   GstClockTime current_sstop;
168
169   /* start, stop and jitter of current buffer, running time */
170   GstClockTime current_rstart;
171   GstClockTime current_rstop;
172   GstClockTimeDiff current_jitter;
173
174   /* EOS sync time in running time */
175   GstClockTime eos_rtime;
176
177   /* last buffer that arrived in time, running time */
178   GstClockTime last_in_time;
179   /* when the last buffer left the sink, running time */
180   GstClockTime last_left;
181
182   /* running averages go here these are done on running time */
183   GstClockTime avg_pt;
184   GstClockTime avg_duration;
185   gdouble avg_rate;
186
187   /* these are done on system time. avg_jitter and avg_render are
188    * compared to eachother to see if the rendering time takes a
189    * huge amount of the processing, If so we are flooded with
190    * buffers. */
191   GstClockTime last_left_systime;
192   GstClockTime avg_jitter;
193   GstClockTime start, stop;
194   GstClockTime avg_render;
195
196   /* number of rendered and dropped frames */
197   guint64 rendered;
198   guint64 dropped;
199
200   /* latency stuff */
201   GstClockTime latency;
202
203   /* if we already commited the state */
204   gboolean commited;
205
206   /* when we received EOS */
207   gboolean received_eos;
208
209   /* when we are prerolled and able to report latency */
210   gboolean have_latency;
211
212   /* the last buffer we prerolled or rendered. Useful for making snapshots */
213   GstBuffer *last_buffer;
214
215   /* caps for pull based scheduling */
216   GstCaps *pull_caps;
217
218   /* blocksize for pulling */
219   guint blocksize;
220
221   gboolean discont;
222
223   /* seqnum of the stream */
224   guint32 seqnum;
225
226   gboolean call_preroll;
227 };
228
229 #define DO_RUNNING_AVG(avg,val,size) (((val) + ((size)-1) * (avg)) / (size))
230
231 /* generic running average, this has a neutral window size */
232 #define UPDATE_RUNNING_AVG(avg,val)   DO_RUNNING_AVG(avg,val,8)
233
234 /* the windows for these running averages are experimentally obtained.
235  * possitive values get averaged more while negative values use a small
236  * window so we can react faster to badness. */
237 #define UPDATE_RUNNING_AVG_P(avg,val) DO_RUNNING_AVG(avg,val,16)
238 #define UPDATE_RUNNING_AVG_N(avg,val) DO_RUNNING_AVG(avg,val,4)
239
240 /* BaseSink properties */
241
242 #define DEFAULT_CAN_ACTIVATE_PULL FALSE /* fixme: enable me */
243 #define DEFAULT_CAN_ACTIVATE_PUSH TRUE
244
245 #define DEFAULT_PREROLL_QUEUE_LEN       0
246 #define DEFAULT_SYNC                    TRUE
247 #define DEFAULT_MAX_LATENESS            -1
248 #define DEFAULT_QOS                     FALSE
249 #define DEFAULT_ASYNC                   TRUE
250 #define DEFAULT_TS_OFFSET               0
251 #define DEFAULT_BLOCKSIZE               4096
252 #define DEFAULT_RENDER_DELAY            0
253
254 enum
255 {
256   PROP_0,
257   PROP_PREROLL_QUEUE_LEN,
258   PROP_SYNC,
259   PROP_MAX_LATENESS,
260   PROP_QOS,
261   PROP_ASYNC,
262   PROP_TS_OFFSET,
263   PROP_LAST_BUFFER,
264   PROP_BLOCKSIZE,
265   PROP_RENDER_DELAY,
266   PROP_LAST
267 };
268
269 static GstElementClass *parent_class = NULL;
270
271 static void gst_base_sink_class_init (GstBaseSinkClass * klass);
272 static void gst_base_sink_init (GstBaseSink * trans, gpointer g_class);
273 static void gst_base_sink_finalize (GObject * object);
274
275 GType
276 gst_base_sink_get_type (void)
277 {
278   static volatile gsize base_sink_type = 0;
279
280   if (g_once_init_enter (&base_sink_type)) {
281     GType _type;
282     static const GTypeInfo base_sink_info = {
283       sizeof (GstBaseSinkClass),
284       NULL,
285       NULL,
286       (GClassInitFunc) gst_base_sink_class_init,
287       NULL,
288       NULL,
289       sizeof (GstBaseSink),
290       0,
291       (GInstanceInitFunc) gst_base_sink_init,
292     };
293
294     _type = g_type_register_static (GST_TYPE_ELEMENT,
295         "GstBaseSink", &base_sink_info, G_TYPE_FLAG_ABSTRACT);
296     g_once_init_leave (&base_sink_type, _type);
297   }
298   return base_sink_type;
299 }
300
301 static void gst_base_sink_set_property (GObject * object, guint prop_id,
302     const GValue * value, GParamSpec * pspec);
303 static void gst_base_sink_get_property (GObject * object, guint prop_id,
304     GValue * value, GParamSpec * pspec);
305
306 static gboolean gst_base_sink_send_event (GstElement * element,
307     GstEvent * event);
308 static gboolean gst_base_sink_query (GstElement * element, GstQuery * query);
309
310 static GstCaps *gst_base_sink_get_caps (GstBaseSink * sink);
311 static gboolean gst_base_sink_set_caps (GstBaseSink * sink, GstCaps * caps);
312 static GstFlowReturn gst_base_sink_buffer_alloc (GstBaseSink * sink,
313     guint64 offset, guint size, GstCaps * caps, GstBuffer ** buf);
314 static void gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
315     GstClockTime * start, GstClockTime * end);
316 static gboolean gst_base_sink_set_flushing (GstBaseSink * basesink,
317     GstPad * pad, gboolean flushing);
318 static gboolean gst_base_sink_default_activate_pull (GstBaseSink * basesink,
319     gboolean active);
320 static gboolean gst_base_sink_default_do_seek (GstBaseSink * sink,
321     GstSegment * segment);
322 static gboolean gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
323     GstEvent * event, GstSegment * segment);
324
325 static GstStateChangeReturn gst_base_sink_change_state (GstElement * element,
326     GstStateChange transition);
327
328 static GstFlowReturn gst_base_sink_chain (GstPad * pad, GstBuffer * buffer);
329 static void gst_base_sink_loop (GstPad * pad);
330 static gboolean gst_base_sink_pad_activate (GstPad * pad);
331 static gboolean gst_base_sink_pad_activate_push (GstPad * pad, gboolean active);
332 static gboolean gst_base_sink_pad_activate_pull (GstPad * pad, gboolean active);
333 static gboolean gst_base_sink_event (GstPad * pad, GstEvent * event);
334 static gboolean gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query);
335
336 static gboolean gst_base_sink_negotiate_pull (GstBaseSink * basesink);
337
338 /* check if an object was too late */
339 static gboolean gst_base_sink_is_too_late (GstBaseSink * basesink,
340     GstMiniObject * obj, GstClockTime start, GstClockTime stop,
341     GstClockReturn status, GstClockTimeDiff jitter);
342 static GstFlowReturn gst_base_sink_preroll_object (GstBaseSink * basesink,
343     GstMiniObject * obj);
344
345 static void
346 gst_base_sink_class_init (GstBaseSinkClass * klass)
347 {
348   GObjectClass *gobject_class;
349   GstElementClass *gstelement_class;
350
351   gobject_class = G_OBJECT_CLASS (klass);
352   gstelement_class = GST_ELEMENT_CLASS (klass);
353
354   GST_DEBUG_CATEGORY_INIT (gst_base_sink_debug, "basesink", 0,
355       "basesink element");
356
357   g_type_class_add_private (klass, sizeof (GstBaseSinkPrivate));
358
359   parent_class = g_type_class_peek_parent (klass);
360
361   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_sink_finalize);
362   gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_base_sink_set_property);
363   gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_base_sink_get_property);
364
365   /* FIXME, this next value should be configured using an event from the
366    * upstream element, ie, the BUFFER_SIZE event. */
367   g_object_class_install_property (gobject_class, PROP_PREROLL_QUEUE_LEN,
368       g_param_spec_uint ("preroll-queue-len", "Preroll queue length",
369           "Number of buffers to queue during preroll", 0, G_MAXUINT,
370           DEFAULT_PREROLL_QUEUE_LEN,
371           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
372
373   g_object_class_install_property (gobject_class, PROP_SYNC,
374       g_param_spec_boolean ("sync", "Sync", "Sync on the clock", DEFAULT_SYNC,
375           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
376
377   g_object_class_install_property (gobject_class, PROP_MAX_LATENESS,
378       g_param_spec_int64 ("max-lateness", "Max Lateness",
379           "Maximum number of nanoseconds that a buffer can be late before it "
380           "is dropped (-1 unlimited)", -1, G_MAXINT64, DEFAULT_MAX_LATENESS,
381           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
382
383   g_object_class_install_property (gobject_class, PROP_QOS,
384       g_param_spec_boolean ("qos", "Qos",
385           "Generate Quality-of-Service events upstream", DEFAULT_QOS,
386           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
387   /**
388    * GstBaseSink:async
389    *
390    * If set to #TRUE, the basesink will perform asynchronous state changes.
391    * When set to #FALSE, the sink will not signal the parent when it prerolls.
392    * Use this option when dealing with sparse streams or when synchronisation is
393    * not required.
394    *
395    * Since: 0.10.15
396    */
397   g_object_class_install_property (gobject_class, PROP_ASYNC,
398       g_param_spec_boolean ("async", "Async",
399           "Go asynchronously to PAUSED", DEFAULT_ASYNC,
400           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
401   /**
402    * GstBaseSink:ts-offset
403    *
404    * Controls the final synchronisation, a negative value will render the buffer
405    * earlier while a positive value delays playback. This property can be 
406    * used to fix synchronisation in bad files.
407    *
408    * Since: 0.10.15
409    */
410   g_object_class_install_property (gobject_class, PROP_TS_OFFSET,
411       g_param_spec_int64 ("ts-offset", "TS Offset",
412           "Timestamp offset in nanoseconds", G_MININT64, G_MAXINT64,
413           DEFAULT_TS_OFFSET, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
414   /**
415    * GstBaseSink:last-buffer
416    *
417    * The last buffer that arrived in the sink and was used for preroll or for
418    * rendering. This property can be used to generate thumbnails. This property
419    * can be NULL when the sink has not yet received a bufer.
420    *
421    * Since: 0.10.15
422    */
423   g_object_class_install_property (gobject_class, PROP_LAST_BUFFER,
424       gst_param_spec_mini_object ("last-buffer", "Last Buffer",
425           "The last buffer received in the sink", GST_TYPE_BUFFER,
426           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
427   /**
428    * GstBaseSink:blocksize
429    *
430    * The amount of bytes to pull when operating in pull mode.
431    *
432    * Since: 0.10.22
433    */
434   g_object_class_install_property (gobject_class, PROP_BLOCKSIZE,
435       g_param_spec_uint ("blocksize", "Block size",
436           "Size in bytes to pull per buffer (0 = default)", 0, G_MAXUINT,
437           DEFAULT_BLOCKSIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
438   /**
439    * GstBaseSink:render-delay
440    *
441    * The additional delay between synchronisation and actual rendering of the
442    * media. This property will add additional latency to the device in order to
443    * make other sinks compensate for the delay.
444    *
445    * Since: 0.10.22
446    */
447   g_object_class_install_property (gobject_class, PROP_RENDER_DELAY,
448       g_param_spec_uint64 ("render-delay", "Render Delay",
449           "Additional render delay of the sink in nanoseconds", 0, G_MAXUINT64,
450           DEFAULT_RENDER_DELAY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
451
452   gstelement_class->change_state =
453       GST_DEBUG_FUNCPTR (gst_base_sink_change_state);
454   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_base_sink_send_event);
455   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_base_sink_query);
456
457   klass->get_caps = GST_DEBUG_FUNCPTR (gst_base_sink_get_caps);
458   klass->set_caps = GST_DEBUG_FUNCPTR (gst_base_sink_set_caps);
459   klass->buffer_alloc = GST_DEBUG_FUNCPTR (gst_base_sink_buffer_alloc);
460   klass->get_times = GST_DEBUG_FUNCPTR (gst_base_sink_get_times);
461   klass->activate_pull =
462       GST_DEBUG_FUNCPTR (gst_base_sink_default_activate_pull);
463 }
464
465 static GstCaps *
466 gst_base_sink_pad_getcaps (GstPad * pad)
467 {
468   GstBaseSinkClass *bclass;
469   GstBaseSink *bsink;
470   GstCaps *caps = NULL;
471
472   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
473   bclass = GST_BASE_SINK_GET_CLASS (bsink);
474
475   if (bsink->pad_mode == GST_ACTIVATE_PULL) {
476     /* if we are operating in pull mode we only accept the negotiated caps */
477     GST_OBJECT_LOCK (pad);
478     if ((caps = GST_PAD_CAPS (pad)))
479       gst_caps_ref (caps);
480     GST_OBJECT_UNLOCK (pad);
481   }
482   if (caps == NULL) {
483     if (bclass->get_caps)
484       caps = bclass->get_caps (bsink);
485
486     if (caps == NULL) {
487       GstPadTemplate *pad_template;
488
489       pad_template =
490           gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass),
491           "sink");
492       if (pad_template != NULL) {
493         caps = gst_caps_ref (gst_pad_template_get_caps (pad_template));
494       }
495     }
496   }
497   gst_object_unref (bsink);
498
499   return caps;
500 }
501
502 static gboolean
503 gst_base_sink_pad_setcaps (GstPad * pad, GstCaps * caps)
504 {
505   GstBaseSinkClass *bclass;
506   GstBaseSink *bsink;
507   gboolean res = TRUE;
508
509   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
510   bclass = GST_BASE_SINK_GET_CLASS (bsink);
511
512   if (res && bclass->set_caps)
513     res = bclass->set_caps (bsink, caps);
514
515   gst_object_unref (bsink);
516
517   return res;
518 }
519
520 static void
521 gst_base_sink_pad_fixate (GstPad * pad, GstCaps * caps)
522 {
523   GstBaseSinkClass *bclass;
524   GstBaseSink *bsink;
525
526   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
527   bclass = GST_BASE_SINK_GET_CLASS (bsink);
528
529   if (bclass->fixate)
530     bclass->fixate (bsink, caps);
531
532   gst_object_unref (bsink);
533 }
534
535 static GstFlowReturn
536 gst_base_sink_pad_buffer_alloc (GstPad * pad, guint64 offset, guint size,
537     GstCaps * caps, GstBuffer ** buf)
538 {
539   GstBaseSinkClass *bclass;
540   GstBaseSink *bsink;
541   GstFlowReturn result = GST_FLOW_OK;
542
543   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
544   bclass = GST_BASE_SINK_GET_CLASS (bsink);
545
546   if (bclass->buffer_alloc)
547     result = bclass->buffer_alloc (bsink, offset, size, caps, buf);
548   else
549     *buf = NULL;                /* fallback in gstpad.c will allocate generic buffer */
550
551   gst_object_unref (bsink);
552
553   return result;
554 }
555
556 static void
557 gst_base_sink_init (GstBaseSink * basesink, gpointer g_class)
558 {
559   GstPadTemplate *pad_template;
560   GstBaseSinkPrivate *priv;
561
562   basesink->priv = priv = GST_BASE_SINK_GET_PRIVATE (basesink);
563
564   pad_template =
565       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (g_class), "sink");
566   g_return_if_fail (pad_template != NULL);
567
568   basesink->sinkpad = gst_pad_new_from_template (pad_template, "sink");
569
570   gst_pad_set_getcaps_function (basesink->sinkpad,
571       GST_DEBUG_FUNCPTR (gst_base_sink_pad_getcaps));
572   gst_pad_set_setcaps_function (basesink->sinkpad,
573       GST_DEBUG_FUNCPTR (gst_base_sink_pad_setcaps));
574   gst_pad_set_fixatecaps_function (basesink->sinkpad,
575       GST_DEBUG_FUNCPTR (gst_base_sink_pad_fixate));
576   gst_pad_set_bufferalloc_function (basesink->sinkpad,
577       GST_DEBUG_FUNCPTR (gst_base_sink_pad_buffer_alloc));
578   gst_pad_set_activate_function (basesink->sinkpad,
579       GST_DEBUG_FUNCPTR (gst_base_sink_pad_activate));
580   gst_pad_set_activatepush_function (basesink->sinkpad,
581       GST_DEBUG_FUNCPTR (gst_base_sink_pad_activate_push));
582   gst_pad_set_activatepull_function (basesink->sinkpad,
583       GST_DEBUG_FUNCPTR (gst_base_sink_pad_activate_pull));
584   gst_pad_set_event_function (basesink->sinkpad,
585       GST_DEBUG_FUNCPTR (gst_base_sink_event));
586   gst_pad_set_chain_function (basesink->sinkpad,
587       GST_DEBUG_FUNCPTR (gst_base_sink_chain));
588   gst_element_add_pad (GST_ELEMENT_CAST (basesink), basesink->sinkpad);
589
590   basesink->pad_mode = GST_ACTIVATE_NONE;
591   basesink->preroll_queue = g_queue_new ();
592   basesink->abidata.ABI.clip_segment = gst_segment_new ();
593   priv->have_latency = FALSE;
594
595   basesink->can_activate_push = DEFAULT_CAN_ACTIVATE_PUSH;
596   basesink->can_activate_pull = DEFAULT_CAN_ACTIVATE_PULL;
597
598   basesink->sync = DEFAULT_SYNC;
599   basesink->abidata.ABI.max_lateness = DEFAULT_MAX_LATENESS;
600   g_atomic_int_set (&priv->qos_enabled, DEFAULT_QOS);
601   priv->async_enabled = DEFAULT_ASYNC;
602   priv->ts_offset = DEFAULT_TS_OFFSET;
603   priv->render_delay = DEFAULT_RENDER_DELAY;
604   priv->blocksize = DEFAULT_BLOCKSIZE;
605
606   GST_OBJECT_FLAG_SET (basesink, GST_ELEMENT_IS_SINK);
607 }
608
609 static void
610 gst_base_sink_finalize (GObject * object)
611 {
612   GstBaseSink *basesink;
613
614   basesink = GST_BASE_SINK (object);
615
616   g_queue_free (basesink->preroll_queue);
617   gst_segment_free (basesink->abidata.ABI.clip_segment);
618
619   G_OBJECT_CLASS (parent_class)->finalize (object);
620 }
621
622 /**
623  * gst_base_sink_set_sync:
624  * @sink: the sink
625  * @sync: the new sync value.
626  *
627  * Configures @sink to synchronize on the clock or not. When
628  * @sync is FALSE, incomming samples will be played as fast as
629  * possible. If @sync is TRUE, the timestamps of the incomming
630  * buffers will be used to schedule the exact render time of its
631  * contents.
632  *
633  * Since: 0.10.4
634  */
635 void
636 gst_base_sink_set_sync (GstBaseSink * sink, gboolean sync)
637 {
638   g_return_if_fail (GST_IS_BASE_SINK (sink));
639
640   GST_OBJECT_LOCK (sink);
641   sink->sync = sync;
642   GST_OBJECT_UNLOCK (sink);
643 }
644
645 /**
646  * gst_base_sink_get_sync:
647  * @sink: the sink
648  *
649  * Checks if @sink is currently configured to synchronize against the
650  * clock.
651  *
652  * Returns: TRUE if the sink is configured to synchronize against the clock.
653  *
654  * Since: 0.10.4
655  */
656 gboolean
657 gst_base_sink_get_sync (GstBaseSink * sink)
658 {
659   gboolean res;
660
661   g_return_val_if_fail (GST_IS_BASE_SINK (sink), FALSE);
662
663   GST_OBJECT_LOCK (sink);
664   res = sink->sync;
665   GST_OBJECT_UNLOCK (sink);
666
667   return res;
668 }
669
670 /**
671  * gst_base_sink_set_max_lateness:
672  * @sink: the sink
673  * @max_lateness: the new max lateness value.
674  *
675  * Sets the new max lateness value to @max_lateness. This value is
676  * used to decide if a buffer should be dropped or not based on the
677  * buffer timestamp and the current clock time. A value of -1 means
678  * an unlimited time.
679  *
680  * Since: 0.10.4
681  */
682 void
683 gst_base_sink_set_max_lateness (GstBaseSink * sink, gint64 max_lateness)
684 {
685   g_return_if_fail (GST_IS_BASE_SINK (sink));
686
687   GST_OBJECT_LOCK (sink);
688   sink->abidata.ABI.max_lateness = max_lateness;
689   GST_OBJECT_UNLOCK (sink);
690 }
691
692 /**
693  * gst_base_sink_get_max_lateness:
694  * @sink: the sink
695  *
696  * Gets the max lateness value. See gst_base_sink_set_max_lateness for
697  * more details.
698  *
699  * Returns: The maximum time in nanoseconds that a buffer can be late
700  * before it is dropped and not rendered. A value of -1 means an
701  * unlimited time.
702  *
703  * Since: 0.10.4
704  */
705 gint64
706 gst_base_sink_get_max_lateness (GstBaseSink * sink)
707 {
708   gint64 res;
709
710   g_return_val_if_fail (GST_IS_BASE_SINK (sink), -1);
711
712   GST_OBJECT_LOCK (sink);
713   res = sink->abidata.ABI.max_lateness;
714   GST_OBJECT_UNLOCK (sink);
715
716   return res;
717 }
718
719 /**
720  * gst_base_sink_set_qos_enabled:
721  * @sink: the sink
722  * @enabled: the new qos value.
723  *
724  * Configures @sink to send Quality-of-Service events upstream.
725  *
726  * Since: 0.10.5
727  */
728 void
729 gst_base_sink_set_qos_enabled (GstBaseSink * sink, gboolean enabled)
730 {
731   g_return_if_fail (GST_IS_BASE_SINK (sink));
732
733   g_atomic_int_set (&sink->priv->qos_enabled, enabled);
734 }
735
736 /**
737  * gst_base_sink_is_qos_enabled:
738  * @sink: the sink
739  *
740  * Checks if @sink is currently configured to send Quality-of-Service events
741  * upstream.
742  *
743  * Returns: TRUE if the sink is configured to perform Quality-of-Service.
744  *
745  * Since: 0.10.5
746  */
747 gboolean
748 gst_base_sink_is_qos_enabled (GstBaseSink * sink)
749 {
750   gboolean res;
751
752   g_return_val_if_fail (GST_IS_BASE_SINK (sink), FALSE);
753
754   res = g_atomic_int_get (&sink->priv->qos_enabled);
755
756   return res;
757 }
758
759 /**
760  * gst_base_sink_set_async_enabled:
761  * @sink: the sink
762  * @enabled: the new async value.
763  *
764  * Configures @sink to perform all state changes asynchronusly. When async is
765  * disabled, the sink will immediatly go to PAUSED instead of waiting for a
766  * preroll buffer. This feature is usefull if the sink does not synchronize
767  * against the clock or when it is dealing with sparse streams.
768  *
769  * Since: 0.10.15
770  */
771 void
772 gst_base_sink_set_async_enabled (GstBaseSink * sink, gboolean enabled)
773 {
774   g_return_if_fail (GST_IS_BASE_SINK (sink));
775
776   GST_PAD_PREROLL_LOCK (sink->sinkpad);
777   sink->priv->async_enabled = enabled;
778   GST_LOG_OBJECT (sink, "set async enabled to %d", enabled);
779   GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
780 }
781
782 /**
783  * gst_base_sink_is_async_enabled:
784  * @sink: the sink
785  *
786  * Checks if @sink is currently configured to perform asynchronous state
787  * changes to PAUSED.
788  *
789  * Returns: TRUE if the sink is configured to perform asynchronous state
790  * changes.
791  *
792  * Since: 0.10.15
793  */
794 gboolean
795 gst_base_sink_is_async_enabled (GstBaseSink * sink)
796 {
797   gboolean res;
798
799   g_return_val_if_fail (GST_IS_BASE_SINK (sink), FALSE);
800
801   GST_PAD_PREROLL_LOCK (sink->sinkpad);
802   res = sink->priv->async_enabled;
803   GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
804
805   return res;
806 }
807
808 /**
809  * gst_base_sink_set_ts_offset:
810  * @sink: the sink
811  * @offset: the new offset
812  *
813  * Adjust the synchronisation of @sink with @offset. A negative value will
814  * render buffers earlier than their timestamp. A positive value will delay
815  * rendering. This function can be used to fix playback of badly timestamped
816  * buffers.
817  *
818  * Since: 0.10.15
819  */
820 void
821 gst_base_sink_set_ts_offset (GstBaseSink * sink, GstClockTimeDiff offset)
822 {
823   g_return_if_fail (GST_IS_BASE_SINK (sink));
824
825   GST_OBJECT_LOCK (sink);
826   sink->priv->ts_offset = offset;
827   GST_LOG_OBJECT (sink, "set time offset to %" G_GINT64_FORMAT, offset);
828   GST_OBJECT_UNLOCK (sink);
829 }
830
831 /**
832  * gst_base_sink_get_ts_offset:
833  * @sink: the sink
834  *
835  * Get the synchronisation offset of @sink.
836  *
837  * Returns: The synchronisation offset.
838  *
839  * Since: 0.10.15
840  */
841 GstClockTimeDiff
842 gst_base_sink_get_ts_offset (GstBaseSink * sink)
843 {
844   GstClockTimeDiff res;
845
846   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
847
848   GST_OBJECT_LOCK (sink);
849   res = sink->priv->ts_offset;
850   GST_OBJECT_UNLOCK (sink);
851
852   return res;
853 }
854
855 /**
856  * gst_base_sink_get_last_buffer:
857  * @sink: the sink
858  *
859  * Get the last buffer that arrived in the sink and was used for preroll or for
860  * rendering. This property can be used to generate thumbnails.
861  *
862  * The #GstCaps on the buffer can be used to determine the type of the buffer.
863  * 
864  * Returns: a #GstBuffer. gst_buffer_unref() after usage. This function returns
865  * NULL when no buffer has arrived in the sink yet or when the sink is not in
866  * PAUSED or PLAYING.
867  *
868  * Since: 0.10.15
869  */
870 GstBuffer *
871 gst_base_sink_get_last_buffer (GstBaseSink * sink)
872 {
873   GstBuffer *res;
874
875   g_return_val_if_fail (GST_IS_BASE_SINK (sink), NULL);
876
877   GST_OBJECT_LOCK (sink);
878   if ((res = sink->priv->last_buffer))
879     gst_buffer_ref (res);
880   GST_OBJECT_UNLOCK (sink);
881
882   return res;
883 }
884
885 static void
886 gst_base_sink_set_last_buffer (GstBaseSink * sink, GstBuffer * buffer)
887 {
888   GstBuffer *old;
889
890   GST_OBJECT_LOCK (sink);
891   old = sink->priv->last_buffer;
892   if (G_LIKELY (old != buffer)) {
893     GST_DEBUG_OBJECT (sink, "setting last buffer to %p", buffer);
894     if (G_LIKELY (buffer))
895       gst_buffer_ref (buffer);
896     sink->priv->last_buffer = buffer;
897   } else {
898     old = NULL;
899   }
900   GST_OBJECT_UNLOCK (sink);
901
902   /* avoid unreffing with the lock because cleanup code might want to take the
903    * lock too */
904   if (G_LIKELY (old))
905     gst_buffer_unref (old);
906 }
907
908 /**
909  * gst_base_sink_get_latency:
910  * @sink: the sink
911  *
912  * Get the currently configured latency.
913  *
914  * Returns: The configured latency.
915  *
916  * Since: 0.10.12
917  */
918 GstClockTime
919 gst_base_sink_get_latency (GstBaseSink * sink)
920 {
921   GstClockTime res;
922
923   GST_OBJECT_LOCK (sink);
924   res = sink->priv->latency;
925   GST_OBJECT_UNLOCK (sink);
926
927   return res;
928 }
929
930 /**
931  * gst_base_sink_query_latency:
932  * @sink: the sink
933  * @live: if the sink is live
934  * @upstream_live: if an upstream element is live
935  * @min_latency: the min latency of the upstream elements
936  * @max_latency: the max latency of the upstream elements
937  *
938  * Query the sink for the latency parameters. The latency will be queried from
939  * the upstream elements. @live will be TRUE if @sink is configured to
940  * synchronize against the clock. @upstream_live will be TRUE if an upstream
941  * element is live. 
942  *
943  * If both @live and @upstream_live are TRUE, the sink will want to compensate
944  * for the latency introduced by the upstream elements by setting the
945  * @min_latency to a strictly possitive value.
946  *
947  * This function is mostly used by subclasses. 
948  *
949  * Returns: TRUE if the query succeeded.
950  *
951  * Since: 0.10.12
952  */
953 gboolean
954 gst_base_sink_query_latency (GstBaseSink * sink, gboolean * live,
955     gboolean * upstream_live, GstClockTime * min_latency,
956     GstClockTime * max_latency)
957 {
958   gboolean l, us_live, res, have_latency;
959   GstClockTime min, max, render_delay;
960   GstQuery *query;
961   GstClockTime us_min, us_max;
962
963   /* we are live when we sync to the clock */
964   GST_OBJECT_LOCK (sink);
965   l = sink->sync;
966   have_latency = sink->priv->have_latency;
967   render_delay = sink->priv->render_delay;
968   GST_OBJECT_UNLOCK (sink);
969
970   /* assume no latency */
971   min = 0;
972   max = -1;
973   us_live = FALSE;
974
975   if (have_latency) {
976     GST_DEBUG_OBJECT (sink, "we are ready for LATENCY query");
977     /* we are ready for a latency query this is when we preroll or when we are
978      * not async. */
979     query = gst_query_new_latency ();
980
981     /* ask the peer for the latency */
982     if ((res = gst_base_sink_peer_query (sink, query))) {
983       /* get upstream min and max latency */
984       gst_query_parse_latency (query, &us_live, &us_min, &us_max);
985
986       if (us_live) {
987         /* upstream live, use its latency, subclasses should use these
988          * values to create the complete latency. */
989         min = us_min;
990         max = us_max;
991       }
992       if (l) {
993         /* we need to add the render delay if we are live */
994         if (min != -1)
995           min += render_delay;
996         if (max != -1)
997           max += render_delay;
998       }
999     }
1000     gst_query_unref (query);
1001   } else {
1002     GST_DEBUG_OBJECT (sink, "we are not yet ready for LATENCY query");
1003     res = FALSE;
1004   }
1005
1006   /* not live, we tried to do the query, if it failed we return TRUE anyway */
1007   if (!res) {
1008     if (!l) {
1009       res = TRUE;
1010       GST_DEBUG_OBJECT (sink, "latency query failed but we are not live");
1011     } else {
1012       GST_DEBUG_OBJECT (sink, "latency query failed and we are live");
1013     }
1014   }
1015
1016   if (res) {
1017     GST_DEBUG_OBJECT (sink, "latency query: live: %d, have_latency %d,"
1018         " upstream: %d, min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT, l,
1019         have_latency, us_live, GST_TIME_ARGS (min), GST_TIME_ARGS (max));
1020
1021     if (live)
1022       *live = l;
1023     if (upstream_live)
1024       *upstream_live = us_live;
1025     if (min_latency)
1026       *min_latency = min;
1027     if (max_latency)
1028       *max_latency = max;
1029   }
1030   return res;
1031 }
1032
1033 /**
1034  * gst_base_sink_set_render_delay:
1035  * @sink: a #GstBaseSink
1036  * @delay: the new delay
1037  *
1038  * Set the render delay in @sink to @delay. The render delay is the time 
1039  * between actual rendering of a buffer and its synchronisation time. Some
1040  * devices might delay media rendering which can be compensated for with this
1041  * function. 
1042  *
1043  * After calling this function, this sink will report additional latency and
1044  * other sinks will adjust their latency to delay the rendering of their media.
1045  *
1046  * This function is usually called by subclasses.
1047  *
1048  * Since: 0.10.21
1049  */
1050 void
1051 gst_base_sink_set_render_delay (GstBaseSink * sink, GstClockTime delay)
1052 {
1053   GstClockTime old_render_delay;
1054
1055   g_return_if_fail (GST_IS_BASE_SINK (sink));
1056
1057   GST_OBJECT_LOCK (sink);
1058   old_render_delay = sink->priv->render_delay;
1059   sink->priv->render_delay = delay;
1060   GST_LOG_OBJECT (sink, "set render delay to %" GST_TIME_FORMAT,
1061       GST_TIME_ARGS (delay));
1062   GST_OBJECT_UNLOCK (sink);
1063
1064   if (delay != old_render_delay) {
1065     GST_DEBUG_OBJECT (sink, "posting latency changed");
1066     gst_element_post_message (GST_ELEMENT_CAST (sink),
1067         gst_message_new_latency (GST_OBJECT_CAST (sink)));
1068   }
1069 }
1070
1071 /**
1072  * gst_base_sink_get_render_delay:
1073  * @sink: a #GstBaseSink
1074  *
1075  * Get the render delay of @sink. see gst_base_sink_set_render_delay() for more
1076  * information about the render delay.
1077  *
1078  * Returns: the render delay of @sink.
1079  *
1080  * Since: 0.10.21
1081  */
1082 GstClockTime
1083 gst_base_sink_get_render_delay (GstBaseSink * sink)
1084 {
1085   GstClockTimeDiff res;
1086
1087   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1088
1089   GST_OBJECT_LOCK (sink);
1090   res = sink->priv->render_delay;
1091   GST_OBJECT_UNLOCK (sink);
1092
1093   return res;
1094 }
1095
1096 /**
1097  * gst_base_sink_set_blocksize:
1098  * @sink: a #GstBaseSink
1099  * @blocksize: the blocksize in bytes
1100  *
1101  * Set the number of bytes that the sink will pull when it is operating in pull
1102  * mode.
1103  *
1104  * Since: 0.10.22
1105  */
1106 void
1107 gst_base_sink_set_blocksize (GstBaseSink * sink, guint blocksize)
1108 {
1109   g_return_if_fail (GST_IS_BASE_SINK (sink));
1110
1111   GST_OBJECT_LOCK (sink);
1112   sink->priv->blocksize = blocksize;
1113   GST_LOG_OBJECT (sink, "set blocksize to %u", blocksize);
1114   GST_OBJECT_UNLOCK (sink);
1115 }
1116
1117 /**
1118  * gst_base_sink_get_blocksize:
1119  * @sink: a #GstBaseSink
1120  *
1121  * Get the number of bytes that the sink will pull when it is operating in pull
1122  * mode.
1123  *
1124  * Returns: the number of bytes @sink will pull in pull mode.
1125  *
1126  * Since: 0.10.22
1127  */
1128 guint
1129 gst_base_sink_get_blocksize (GstBaseSink * sink)
1130 {
1131   guint res;
1132
1133   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1134
1135   GST_OBJECT_LOCK (sink);
1136   res = sink->priv->blocksize;
1137   GST_OBJECT_UNLOCK (sink);
1138
1139   return res;
1140 }
1141
1142 static void
1143 gst_base_sink_set_property (GObject * object, guint prop_id,
1144     const GValue * value, GParamSpec * pspec)
1145 {
1146   GstBaseSink *sink = GST_BASE_SINK (object);
1147
1148   switch (prop_id) {
1149     case PROP_PREROLL_QUEUE_LEN:
1150       /* preroll lock necessary to serialize with finish_preroll */
1151       GST_PAD_PREROLL_LOCK (sink->sinkpad);
1152       sink->preroll_queue_max_len = g_value_get_uint (value);
1153       GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
1154       break;
1155     case PROP_SYNC:
1156       gst_base_sink_set_sync (sink, g_value_get_boolean (value));
1157       break;
1158     case PROP_MAX_LATENESS:
1159       gst_base_sink_set_max_lateness (sink, g_value_get_int64 (value));
1160       break;
1161     case PROP_QOS:
1162       gst_base_sink_set_qos_enabled (sink, g_value_get_boolean (value));
1163       break;
1164     case PROP_ASYNC:
1165       gst_base_sink_set_async_enabled (sink, g_value_get_boolean (value));
1166       break;
1167     case PROP_TS_OFFSET:
1168       gst_base_sink_set_ts_offset (sink, g_value_get_int64 (value));
1169       break;
1170     case PROP_BLOCKSIZE:
1171       gst_base_sink_set_blocksize (sink, g_value_get_uint (value));
1172       break;
1173     case PROP_RENDER_DELAY:
1174       gst_base_sink_set_render_delay (sink, g_value_get_uint64 (value));
1175       break;
1176     default:
1177       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1178       break;
1179   }
1180 }
1181
1182 static void
1183 gst_base_sink_get_property (GObject * object, guint prop_id, GValue * value,
1184     GParamSpec * pspec)
1185 {
1186   GstBaseSink *sink = GST_BASE_SINK (object);
1187
1188   switch (prop_id) {
1189     case PROP_PREROLL_QUEUE_LEN:
1190       GST_PAD_PREROLL_LOCK (sink->sinkpad);
1191       g_value_set_uint (value, sink->preroll_queue_max_len);
1192       GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
1193       break;
1194     case PROP_SYNC:
1195       g_value_set_boolean (value, gst_base_sink_get_sync (sink));
1196       break;
1197     case PROP_MAX_LATENESS:
1198       g_value_set_int64 (value, gst_base_sink_get_max_lateness (sink));
1199       break;
1200     case PROP_QOS:
1201       g_value_set_boolean (value, gst_base_sink_is_qos_enabled (sink));
1202       break;
1203     case PROP_ASYNC:
1204       g_value_set_boolean (value, gst_base_sink_is_async_enabled (sink));
1205       break;
1206     case PROP_TS_OFFSET:
1207       g_value_set_int64 (value, gst_base_sink_get_ts_offset (sink));
1208       break;
1209     case PROP_LAST_BUFFER:
1210       gst_value_take_buffer (value, gst_base_sink_get_last_buffer (sink));
1211       break;
1212     case PROP_BLOCKSIZE:
1213       g_value_set_uint (value, gst_base_sink_get_blocksize (sink));
1214       break;
1215     case PROP_RENDER_DELAY:
1216       g_value_set_uint64 (value, gst_base_sink_get_render_delay (sink));
1217       break;
1218     default:
1219       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1220       break;
1221   }
1222 }
1223
1224
1225 static GstCaps *
1226 gst_base_sink_get_caps (GstBaseSink * sink)
1227 {
1228   return NULL;
1229 }
1230
1231 static gboolean
1232 gst_base_sink_set_caps (GstBaseSink * sink, GstCaps * caps)
1233 {
1234   return TRUE;
1235 }
1236
1237 static GstFlowReturn
1238 gst_base_sink_buffer_alloc (GstBaseSink * sink, guint64 offset, guint size,
1239     GstCaps * caps, GstBuffer ** buf)
1240 {
1241   *buf = NULL;
1242   return GST_FLOW_OK;
1243 }
1244
1245 /* with PREROLL_LOCK, STREAM_LOCK */
1246 static void
1247 gst_base_sink_preroll_queue_flush (GstBaseSink * basesink, GstPad * pad)
1248 {
1249   GstMiniObject *obj;
1250
1251   GST_DEBUG_OBJECT (basesink, "flushing queue %p", basesink);
1252   while ((obj = g_queue_pop_head (basesink->preroll_queue))) {
1253     GST_DEBUG_OBJECT (basesink, "popped %p", obj);
1254     gst_mini_object_unref (obj);
1255   }
1256   /* we can't have EOS anymore now */
1257   basesink->eos = FALSE;
1258   basesink->priv->received_eos = FALSE;
1259   basesink->have_preroll = FALSE;
1260   basesink->eos_queued = FALSE;
1261   basesink->preroll_queued = 0;
1262   basesink->buffers_queued = 0;
1263   basesink->events_queued = 0;
1264   /* can't report latency anymore until we preroll again */
1265   if (basesink->priv->async_enabled) {
1266     GST_OBJECT_LOCK (basesink);
1267     basesink->priv->have_latency = FALSE;
1268     GST_OBJECT_UNLOCK (basesink);
1269   }
1270   /* and signal any waiters now */
1271   GST_PAD_PREROLL_SIGNAL (pad);
1272 }
1273
1274 /* with STREAM_LOCK, configures given segment with the event information. */
1275 static void
1276 gst_base_sink_configure_segment (GstBaseSink * basesink, GstPad * pad,
1277     GstEvent * event, GstSegment * segment)
1278 {
1279   gboolean update;
1280   gdouble rate, arate;
1281   GstFormat format;
1282   gint64 start;
1283   gint64 stop;
1284   gint64 time;
1285
1286   /* the newsegment event is needed to bring the buffer timestamps to the
1287    * stream time and to drop samples outside of the playback segment. */
1288   gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
1289       &start, &stop, &time);
1290
1291   /* The segment is protected with both the STREAM_LOCK and the OBJECT_LOCK.
1292    * We protect with the OBJECT_LOCK so that we can use the values to
1293    * safely answer a POSITION query. */
1294   GST_OBJECT_LOCK (basesink);
1295   gst_segment_set_newsegment_full (segment, update, rate, arate, format, start,
1296       stop, time);
1297
1298   if (format == GST_FORMAT_TIME) {
1299     GST_DEBUG_OBJECT (basesink,
1300         "configured NEWSEGMENT update %d, rate %lf, applied rate %lf, "
1301         "format GST_FORMAT_TIME, "
1302         "%" GST_TIME_FORMAT " -- %" GST_TIME_FORMAT
1303         ", time %" GST_TIME_FORMAT ", accum %" GST_TIME_FORMAT,
1304         update, rate, arate, GST_TIME_ARGS (segment->start),
1305         GST_TIME_ARGS (segment->stop), GST_TIME_ARGS (segment->time),
1306         GST_TIME_ARGS (segment->accum));
1307   } else {
1308     GST_DEBUG_OBJECT (basesink,
1309         "configured NEWSEGMENT update %d, rate %lf, applied rate %lf, "
1310         "format %d, "
1311         "%" G_GINT64_FORMAT " -- %" G_GINT64_FORMAT ", time %"
1312         G_GINT64_FORMAT ", accum %" G_GINT64_FORMAT, update, rate, arate,
1313         segment->format, segment->start, segment->stop, segment->time,
1314         segment->accum);
1315   }
1316   GST_OBJECT_UNLOCK (basesink);
1317 }
1318
1319 /* with PREROLL_LOCK, STREAM_LOCK */
1320 static gboolean
1321 gst_base_sink_commit_state (GstBaseSink * basesink)
1322 {
1323   /* commit state and proceed to next pending state */
1324   GstState current, next, pending, post_pending;
1325   gboolean post_paused = FALSE;
1326   gboolean post_async_done = FALSE;
1327   gboolean post_playing = FALSE;
1328
1329   /* we are certainly not playing async anymore now */
1330   basesink->playing_async = FALSE;
1331
1332   GST_OBJECT_LOCK (basesink);
1333   current = GST_STATE (basesink);
1334   next = GST_STATE_NEXT (basesink);
1335   pending = GST_STATE_PENDING (basesink);
1336   post_pending = pending;
1337
1338   switch (pending) {
1339     case GST_STATE_PLAYING:
1340     {
1341       GstBaseSinkClass *bclass;
1342       GstStateChangeReturn ret;
1343
1344       bclass = GST_BASE_SINK_GET_CLASS (basesink);
1345
1346       GST_DEBUG_OBJECT (basesink, "commiting state to PLAYING");
1347
1348       basesink->need_preroll = FALSE;
1349       post_async_done = TRUE;
1350       basesink->priv->commited = TRUE;
1351       post_playing = TRUE;
1352       /* post PAUSED too when we were READY */
1353       if (current == GST_STATE_READY) {
1354         post_paused = TRUE;
1355       }
1356
1357       /* make sure we notify the subclass of async playing */
1358       if (bclass->async_play) {
1359         GST_WARNING_OBJECT (basesink, "deprecated async_play");
1360         ret = bclass->async_play (basesink);
1361         if (ret == GST_STATE_CHANGE_FAILURE)
1362           goto async_failed;
1363       }
1364       break;
1365     }
1366     case GST_STATE_PAUSED:
1367       GST_DEBUG_OBJECT (basesink, "commiting state to PAUSED");
1368       post_paused = TRUE;
1369       post_async_done = TRUE;
1370       basesink->priv->commited = TRUE;
1371       post_pending = GST_STATE_VOID_PENDING;
1372       break;
1373     case GST_STATE_READY:
1374     case GST_STATE_NULL:
1375       goto stopping;
1376     case GST_STATE_VOID_PENDING:
1377       goto nothing_pending;
1378     default:
1379       break;
1380   }
1381
1382   /* we can report latency queries now */
1383   basesink->priv->have_latency = TRUE;
1384
1385   GST_STATE (basesink) = pending;
1386   GST_STATE_NEXT (basesink) = GST_STATE_VOID_PENDING;
1387   GST_STATE_PENDING (basesink) = GST_STATE_VOID_PENDING;
1388   GST_STATE_RETURN (basesink) = GST_STATE_CHANGE_SUCCESS;
1389   GST_OBJECT_UNLOCK (basesink);
1390
1391   if (post_paused) {
1392     GST_DEBUG_OBJECT (basesink, "posting PAUSED state change message");
1393     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1394         gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
1395             current, next, post_pending));
1396   }
1397   if (post_async_done) {
1398     GST_DEBUG_OBJECT (basesink, "posting async-done message");
1399     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1400         gst_message_new_async_done (GST_OBJECT_CAST (basesink)));
1401   }
1402   if (post_playing) {
1403     GST_DEBUG_OBJECT (basesink, "posting PLAYING state change message");
1404     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1405         gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
1406             next, pending, GST_STATE_VOID_PENDING));
1407   }
1408
1409   GST_STATE_BROADCAST (basesink);
1410
1411   return TRUE;
1412
1413 nothing_pending:
1414   {
1415     /* Depending on the state, set our vars. We get in this situation when the
1416      * state change function got a change to update the state vars before the
1417      * streaming thread did. This is fine but we need to make sure that we
1418      * update the need_preroll var since it was TRUE when we got here and might
1419      * become FALSE if we got to PLAYING. */
1420     GST_DEBUG_OBJECT (basesink, "nothing to commit, now in %s",
1421         gst_element_state_get_name (current));
1422     switch (current) {
1423       case GST_STATE_PLAYING:
1424         basesink->need_preroll = FALSE;
1425         break;
1426       case GST_STATE_PAUSED:
1427         basesink->need_preroll = TRUE;
1428         break;
1429       default:
1430         basesink->need_preroll = FALSE;
1431         basesink->flushing = TRUE;
1432         break;
1433     }
1434     /* we can report latency queries now */
1435     basesink->priv->have_latency = TRUE;
1436     GST_OBJECT_UNLOCK (basesink);
1437     return TRUE;
1438   }
1439 stopping:
1440   {
1441     /* app is going to READY */
1442     GST_DEBUG_OBJECT (basesink, "stopping");
1443     basesink->need_preroll = FALSE;
1444     basesink->flushing = TRUE;
1445     GST_OBJECT_UNLOCK (basesink);
1446     return FALSE;
1447   }
1448 async_failed:
1449   {
1450     GST_DEBUG_OBJECT (basesink, "async commit failed");
1451     GST_STATE_RETURN (basesink) = GST_STATE_CHANGE_FAILURE;
1452     GST_OBJECT_UNLOCK (basesink);
1453     return FALSE;
1454   }
1455 }
1456
1457
1458 /* with STREAM_LOCK, PREROLL_LOCK
1459  *
1460  * Returns TRUE if the object needs synchronisation and takes therefore
1461  * part in prerolling.
1462  *
1463  * rsstart/rsstop contain the start/stop in stream time.
1464  * rrstart/rrstop contain the start/stop in running time.
1465  */
1466 static gboolean
1467 gst_base_sink_get_sync_times (GstBaseSink * basesink, GstMiniObject * obj,
1468     GstClockTime * rsstart, GstClockTime * rsstop,
1469     GstClockTime * rrstart, GstClockTime * rrstop, gboolean * do_sync,
1470     GstSegment * segment)
1471 {
1472   GstBaseSinkClass *bclass;
1473   GstBuffer *buffer;
1474   GstClockTime start, stop;     /* raw start/stop timestamps */
1475   gint64 cstart, cstop;         /* clipped raw timestamps */
1476   gint64 rstart, rstop;         /* clipped timestamps converted to running time */
1477   GstClockTime sstart, sstop;   /* clipped timestamps converted to stream time */
1478   GstFormat format;
1479   GstBaseSinkPrivate *priv;
1480
1481   priv = basesink->priv;
1482
1483   /* start with nothing */
1484   start = stop = sstart = sstop = rstart = rstop = -1;
1485
1486   if (G_UNLIKELY (GST_IS_EVENT (obj))) {
1487     GstEvent *event = GST_EVENT_CAST (obj);
1488
1489     switch (GST_EVENT_TYPE (event)) {
1490         /* EOS event needs syncing */
1491       case GST_EVENT_EOS:
1492       {
1493         if (basesink->segment.rate >= 0.0) {
1494           sstart = sstop = priv->current_sstop;
1495           if (sstart == -1) {
1496             /* we have not seen a buffer yet, use the segment values */
1497             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1498                 basesink->segment.format, basesink->segment.stop);
1499           }
1500         } else {
1501           sstart = sstop = priv->current_sstart;
1502           if (sstart == -1) {
1503             /* we have not seen a buffer yet, use the segment values */
1504             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1505                 basesink->segment.format, basesink->segment.start);
1506           }
1507         }
1508
1509         rstart = rstop = priv->eos_rtime;
1510         *do_sync = rstart != -1;
1511         GST_DEBUG_OBJECT (basesink, "sync times for EOS %" GST_TIME_FORMAT,
1512             GST_TIME_ARGS (rstart));
1513         goto done;
1514       }
1515       default:
1516         /* other events do not need syncing */
1517         /* FIXME, maybe NEWSEGMENT might need synchronisation
1518          * since the POSITION query depends on accumulated times and
1519          * we cannot accumulate the current segment before the previous
1520          * one completed.
1521          */
1522         return FALSE;
1523     }
1524   }
1525
1526   /* else do buffer sync code */
1527   buffer = GST_BUFFER_CAST (obj);
1528
1529   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1530
1531   /* just get the times to see if we need syncing */
1532   if (bclass->get_times)
1533     bclass->get_times (basesink, buffer, &start, &stop);
1534
1535   if (start == -1) {
1536     gst_base_sink_get_times (basesink, buffer, &start, &stop);
1537     *do_sync = FALSE;
1538   } else {
1539     *do_sync = TRUE;
1540   }
1541
1542   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
1543       ", stop: %" GST_TIME_FORMAT ", do_sync %d", GST_TIME_ARGS (start),
1544       GST_TIME_ARGS (stop), *do_sync);
1545
1546   /* collect segment and format for code clarity */
1547   format = segment->format;
1548
1549   /* no timestamp clipping if we did not * get a TIME segment format */
1550   if (G_UNLIKELY (format != GST_FORMAT_TIME)) {
1551     cstart = start;
1552     cstop = stop;
1553     /* do running and stream time in TIME format */
1554     format = GST_FORMAT_TIME;
1555     goto do_times;
1556   }
1557
1558   /* clip */
1559   if (G_UNLIKELY (!gst_segment_clip (segment, GST_FORMAT_TIME,
1560               (gint64) start, (gint64) stop, &cstart, &cstop)))
1561     goto out_of_segment;
1562
1563   if (G_UNLIKELY (start != cstart || stop != cstop)) {
1564     GST_DEBUG_OBJECT (basesink, "clipped to: start %" GST_TIME_FORMAT
1565         ", stop: %" GST_TIME_FORMAT, GST_TIME_ARGS (cstart),
1566         GST_TIME_ARGS (cstop));
1567   }
1568
1569   /* set last stop position */
1570   if (G_LIKELY (cstop != GST_CLOCK_TIME_NONE))
1571     gst_segment_set_last_stop (segment, GST_FORMAT_TIME, cstop);
1572   else
1573     gst_segment_set_last_stop (segment, GST_FORMAT_TIME, cstart);
1574
1575 do_times:
1576   /* this can produce wrong values if we accumulated non-TIME segments. If this happens,
1577    * upstream is behaving very badly */
1578   sstart = gst_segment_to_stream_time (segment, format, cstart);
1579   sstop = gst_segment_to_stream_time (segment, format, cstop);
1580   rstart = gst_segment_to_running_time (segment, format, cstart);
1581   rstop = gst_segment_to_running_time (segment, format, cstop);
1582
1583 done:
1584   /* save times */
1585   *rsstart = sstart;
1586   *rsstop = sstop;
1587   *rrstart = rstart;
1588   *rrstop = rstop;
1589
1590   /* buffers and EOS always need syncing and preroll */
1591   return TRUE;
1592
1593   /* special cases */
1594 out_of_segment:
1595   {
1596     /* should not happen since we clip them in the chain function already, 
1597      * we return FALSE so that we don't try to sync on it. */
1598     GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
1599         (NULL), ("unexpected buffer out of segment found."));
1600     GST_LOG_OBJECT (basesink, "buffer skipped, not in segment");
1601     return FALSE;
1602   }
1603 }
1604
1605 /* with STREAM_LOCK, PREROLL_LOCK, LOCK
1606  * adjust a timestamp with the latency and timestamp offset */
1607 static GstClockTime
1608 gst_base_sink_adjust_time (GstBaseSink * basesink, GstClockTime time)
1609 {
1610   GstClockTimeDiff ts_offset;
1611
1612   /* don't do anything funny with invalid timestamps */
1613   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1614     return time;
1615
1616   time += basesink->priv->latency;
1617
1618   /* apply offset, be carefull for underflows */
1619   ts_offset = basesink->priv->ts_offset;
1620   if (ts_offset < 0) {
1621     ts_offset = -ts_offset;
1622     if (ts_offset < time)
1623       time -= ts_offset;
1624     else
1625       time = 0;
1626   } else
1627     time += ts_offset;
1628
1629   return time;
1630 }
1631
1632 /**
1633  * gst_base_sink_wait_clock:
1634  * @sink: the sink
1635  * @time: the running_time to be reached
1636  * @jitter: the jitter to be filled with time diff (can be NULL)
1637  *
1638  * This function will block until @time is reached. It is usually called by
1639  * subclasses that use their own internal synchronisation.
1640  *
1641  * If @time is not valid, no sycnhronisation is done and #GST_CLOCK_BADTIME is
1642  * returned. Likewise, if synchronisation is disabled in the element or there
1643  * is no clock, no synchronisation is done and #GST_CLOCK_BADTIME is returned.
1644  *
1645  * This function should only be called with the PREROLL_LOCK held, like when
1646  * receiving an EOS event in the ::event vmethod or when receiving a buffer in
1647  * the ::render vmethod.
1648  *
1649  * The @time argument should be the running_time of when this method should
1650  * return and is not adjusted with any latency or offset configured in the
1651  * sink.
1652  *
1653  * Since 0.10.20
1654  *
1655  * Returns: #GstClockReturn
1656  */
1657 GstClockReturn
1658 gst_base_sink_wait_clock (GstBaseSink * sink, GstClockTime time,
1659     GstClockTimeDiff * jitter)
1660 {
1661   GstClockID id;
1662   GstClockReturn ret;
1663   GstClock *clock;
1664
1665   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1666     goto invalid_time;
1667
1668   GST_OBJECT_LOCK (sink);
1669   if (G_UNLIKELY (!sink->sync))
1670     goto no_sync;
1671
1672   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (sink)) == NULL))
1673     goto no_clock;
1674
1675   /* add base_time to running_time to get the time against the clock */
1676   time += GST_ELEMENT_CAST (sink)->base_time;
1677
1678   id = gst_clock_new_single_shot_id (clock, time);
1679   GST_OBJECT_UNLOCK (sink);
1680
1681   /* A blocking wait is performed on the clock. We save the ClockID
1682    * so we can unlock the entry at any time. While we are blocking, we 
1683    * release the PREROLL_LOCK so that other threads can interrupt the
1684    * entry. */
1685   sink->clock_id = id;
1686   /* release the preroll lock while waiting */
1687   GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
1688
1689   ret = gst_clock_id_wait (id, jitter);
1690
1691   GST_PAD_PREROLL_LOCK (sink->sinkpad);
1692   gst_clock_id_unref (id);
1693   sink->clock_id = NULL;
1694
1695   return ret;
1696
1697   /* no syncing needed */
1698 invalid_time:
1699   {
1700     GST_DEBUG_OBJECT (sink, "time not valid, no sync needed");
1701     return GST_CLOCK_BADTIME;
1702   }
1703 no_sync:
1704   {
1705     GST_DEBUG_OBJECT (sink, "sync disabled");
1706     GST_OBJECT_UNLOCK (sink);
1707     return GST_CLOCK_BADTIME;
1708   }
1709 no_clock:
1710   {
1711     GST_DEBUG_OBJECT (sink, "no clock, can't sync");
1712     GST_OBJECT_UNLOCK (sink);
1713     return GST_CLOCK_BADTIME;
1714   }
1715 }
1716
1717 /**
1718  * gst_base_sink_wait_preroll:
1719  * @sink: the sink
1720  *
1721  * If the #GstBaseSinkClass::render method performs its own synchronisation against
1722  * the clock it must unblock when going from PLAYING to the PAUSED state and call
1723  * this method before continuing to render the remaining data.
1724  *
1725  * This function will block until a state change to PLAYING happens (in which
1726  * case this function returns #GST_FLOW_OK) or the processing must be stopped due
1727  * to a state change to READY or a FLUSH event (in which case this function
1728  * returns #GST_FLOW_WRONG_STATE).
1729  *
1730  * This function should only be called with the PREROLL_LOCK held, like in the
1731  * render function.
1732  *
1733  * Since: 0.10.11
1734  *
1735  * Returns: #GST_FLOW_OK if the preroll completed and processing can
1736  * continue. Any other return value should be returned from the render vmethod.
1737  */
1738 GstFlowReturn
1739 gst_base_sink_wait_preroll (GstBaseSink * sink)
1740 {
1741   sink->have_preroll = TRUE;
1742   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
1743   /* block until the state changes, or we get a flush, or something */
1744   GST_PAD_PREROLL_WAIT (sink->sinkpad);
1745   sink->have_preroll = FALSE;
1746   if (G_UNLIKELY (sink->flushing))
1747     goto stopping;
1748   GST_DEBUG_OBJECT (sink, "continue after preroll");
1749
1750   return GST_FLOW_OK;
1751
1752   /* ERRORS */
1753 stopping:
1754   {
1755     GST_DEBUG_OBJECT (sink, "preroll interrupted");
1756     return GST_FLOW_WRONG_STATE;
1757   }
1758 }
1759
1760 /**
1761  * gst_base_sink_do_preroll:
1762  * @sink: the sink
1763  * @obj: the object that caused the preroll
1764  *
1765  * If the @sink spawns its own thread for pulling buffers from upstream it
1766  * should call this method after it has pulled a buffer. If the element needed
1767  * to preroll, this function will perform the preroll and will then block
1768  * until the element state is changed.
1769  *
1770  * This function should be called with the PREROLL_LOCK held.
1771  *
1772  * Since 0.10.22
1773  *
1774  * Returns: #GST_FLOW_OK if the preroll completed and processing can
1775  * continue. Any other return value should be returned from the render vmethod.
1776  */
1777 GstFlowReturn
1778 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
1779 {
1780   GstFlowReturn ret;
1781
1782   while (G_UNLIKELY (sink->need_preroll)) {
1783     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
1784
1785     ret = gst_base_sink_preroll_object (sink, obj);
1786     if (ret != GST_FLOW_OK)
1787       goto preroll_failed;
1788
1789     /* need to recheck here because the commit state could have
1790      * made us not need the preroll anymore */
1791     if (G_LIKELY (sink->need_preroll)) {
1792       /* block until the state changes, or we get a flush, or something */
1793       ret = gst_base_sink_wait_preroll (sink);
1794       if (ret != GST_FLOW_OK)
1795         goto preroll_failed;
1796     }
1797   }
1798   return GST_FLOW_OK;
1799
1800   /* ERRORS */
1801 preroll_failed:
1802   {
1803     GST_DEBUG_OBJECT (sink, "preroll failed %d", ret);
1804     return ret;
1805   }
1806 }
1807
1808 /**
1809  * gst_base_sink_wait_eos:
1810  * @sink: the sink
1811  * @time: the running_time to be reached
1812  * @jitter: the jitter to be filled with time diff (can be NULL)
1813  *
1814  * This function will block until @time is reached. It is usually called by
1815  * subclasses that use their own internal synchronisation but want to let the
1816  * EOS be handled by the base class.
1817  *
1818  * This function should only be called with the PREROLL_LOCK held, like when
1819  * receiving an EOS event in the ::event vmethod.
1820  *
1821  * The @time argument should be the running_time of when the EOS should happen
1822  * and will be adjusted with any latency and offset configured in the sink.
1823  *
1824  * Since 0.10.15
1825  *
1826  * Returns: #GstFlowReturn
1827  */
1828 GstFlowReturn
1829 gst_base_sink_wait_eos (GstBaseSink * sink, GstClockTime time,
1830     GstClockTimeDiff * jitter)
1831 {
1832   GstClockReturn status;
1833   GstFlowReturn ret;
1834
1835   do {
1836     GstClockTime stime;
1837
1838     GST_DEBUG_OBJECT (sink, "checking preroll");
1839
1840     /* first wait for the playing state before we can continue */
1841     if (G_UNLIKELY (sink->need_preroll)) {
1842       ret = gst_base_sink_wait_preroll (sink);
1843       if (ret != GST_FLOW_OK)
1844         goto flushing;
1845     }
1846
1847     /* preroll done, we can sync since we are in PLAYING now. */
1848     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
1849         GST_TIME_FORMAT, GST_TIME_ARGS (time));
1850
1851     /* compensate for latency and ts_offset. We don't adjust for render delay
1852      * because we don't interact with the device on EOS normally. */
1853     stime = gst_base_sink_adjust_time (sink, time);
1854
1855     /* wait for the clock, this can be interrupted because we got shut down or 
1856      * we PAUSED. */
1857     status = gst_base_sink_wait_clock (sink, stime, jitter);
1858
1859     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
1860
1861     /* invalid time, no clock or sync disabled, just continue then */
1862     if (status == GST_CLOCK_BADTIME)
1863       break;
1864
1865     /* waiting could have been interrupted and we can be flushing now */
1866     if (G_UNLIKELY (sink->flushing))
1867       goto flushing;
1868
1869     /* retry if we got unscheduled, which means we did not reach the timeout
1870      * yet. if some other error occures, we continue. */
1871   } while (status == GST_CLOCK_UNSCHEDULED);
1872
1873   GST_DEBUG_OBJECT (sink, "end of stream");
1874
1875   return GST_FLOW_OK;
1876
1877   /* ERRORS */
1878 flushing:
1879   {
1880     GST_DEBUG_OBJECT (sink, "we are flushing");
1881     return GST_FLOW_WRONG_STATE;
1882   }
1883 }
1884
1885 /* with STREAM_LOCK, PREROLL_LOCK
1886  *
1887  * Make sure we are in PLAYING and synchronize an object to the clock.
1888  *
1889  * If we need preroll, we are not in PLAYING. We try to commit the state
1890  * if needed and then block if we still are not PLAYING.
1891  *
1892  * We start waiting on the clock in PLAYING. If we got interrupted, we
1893  * immediatly try to re-preroll.
1894  *
1895  * Some objects do not need synchronisation (most events) and so this function
1896  * immediatly returns GST_FLOW_OK.
1897  *
1898  * for objects that arrive later than max-lateness to be synchronized to the 
1899  * clock have the @late boolean set to TRUE.
1900  *
1901  * This function keeps a running average of the jitter (the diff between the
1902  * clock time and the requested sync time). The jitter is negative for
1903  * objects that arrive in time and positive for late buffers.
1904  *
1905  * does not take ownership of obj.
1906  */
1907 static GstFlowReturn
1908 gst_base_sink_do_sync (GstBaseSink * basesink, GstPad * pad,
1909     GstMiniObject * obj, gboolean * late)
1910 {
1911   GstClockTimeDiff jitter;
1912   gboolean syncable;
1913   GstClockReturn status = GST_CLOCK_OK;
1914   GstClockTime rstart, rstop, sstart, sstop, stime;
1915   gboolean do_sync;
1916   GstBaseSinkPrivate *priv;
1917   GstFlowReturn ret;
1918
1919   priv = basesink->priv;
1920
1921   sstart = sstop = rstart = rstop = -1;
1922   do_sync = TRUE;
1923
1924   priv->current_rstart = -1;
1925
1926   /* get timing information for this object against the render segment */
1927   syncable = gst_base_sink_get_sync_times (basesink, obj,
1928       &sstart, &sstop, &rstart, &rstop, &do_sync, &basesink->segment);
1929
1930   /* a syncable object needs to participate in preroll and
1931    * clocking. All buffers and EOS are syncable. */
1932   if (G_UNLIKELY (!syncable))
1933     goto not_syncable;
1934
1935   /* store timing info for current object */
1936   priv->current_rstart = rstart;
1937   priv->current_rstop = (rstop != -1 ? rstop : rstart);
1938   /* save sync time for eos when the previous object needed sync */
1939   priv->eos_rtime = (do_sync ? priv->current_rstop : -1);
1940
1941 again:
1942   /* first do preroll, this makes sure we commit our state
1943    * to PAUSED and can continue to PLAYING. We cannot perform
1944    * any clock sync in PAUSED because there is no clock. 
1945    */
1946   ret = gst_base_sink_do_preroll (basesink, obj);
1947   if (G_UNLIKELY (ret != GST_FLOW_OK))
1948     goto preroll_failed;
1949
1950   /* After rendering we store the position of the last buffer so that we can use
1951    * it to report the position. We need to take the lock here. */
1952   GST_OBJECT_LOCK (basesink);
1953   priv->current_sstart = sstart;
1954   priv->current_sstop = (sstop != -1 ? sstop : sstart);
1955   GST_OBJECT_UNLOCK (basesink);
1956
1957   if (!do_sync)
1958     goto done;
1959
1960   /* adjust for latency */
1961   stime = gst_base_sink_adjust_time (basesink, rstart);
1962
1963   /* adjust for render-delay, avoid underflows */
1964   if (stime != -1) {
1965     if (stime > priv->render_delay)
1966       stime -= priv->render_delay;
1967     else
1968       stime = 0;
1969   }
1970
1971   /* preroll done, we can sync since we are in PLAYING now. */
1972   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
1973       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
1974       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
1975
1976   /* This function will return immediatly if start == -1, no clock
1977    * or sync is disabled with GST_CLOCK_BADTIME. */
1978   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
1979
1980   GST_DEBUG_OBJECT (basesink, "clock returned %d", status);
1981
1982   /* invalid time, no clock or sync disabled, just render */
1983   if (status == GST_CLOCK_BADTIME)
1984     goto done;
1985
1986   /* waiting could have been interrupted and we can be flushing now */
1987   if (G_UNLIKELY (basesink->flushing))
1988     goto flushing;
1989
1990   /* check for unlocked by a state change, we are not flushing so
1991    * we can try to preroll on the current buffer. */
1992   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1993     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
1994     priv->call_preroll = TRUE;
1995     goto again;
1996   }
1997
1998   /* successful syncing done, record observation */
1999   priv->current_jitter = jitter;
2000
2001   /* check if the object should be dropped */
2002   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
2003       status, jitter);
2004
2005 done:
2006   return GST_FLOW_OK;
2007
2008   /* ERRORS */
2009 not_syncable:
2010   {
2011     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2012     return GST_FLOW_OK;
2013   }
2014 flushing:
2015   {
2016     GST_DEBUG_OBJECT (basesink, "we are flushing");
2017     return GST_FLOW_WRONG_STATE;
2018   }
2019 preroll_failed:
2020   {
2021     GST_DEBUG_OBJECT (basesink, "preroll failed");
2022     return ret;
2023   }
2024 }
2025
2026 static gboolean
2027 gst_base_sink_send_qos (GstBaseSink * basesink,
2028     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2029 {
2030   GstEvent *event;
2031   gboolean res;
2032
2033   /* generate Quality-of-Service event */
2034   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2035       "qos: proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2036       GST_TIME_FORMAT, proportion, diff, GST_TIME_ARGS (time));
2037
2038   event = gst_event_new_qos (proportion, diff, time);
2039
2040   /* send upstream */
2041   res = gst_pad_push_event (basesink->sinkpad, event);
2042
2043   return res;
2044 }
2045
2046 static void
2047 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2048 {
2049   GstBaseSinkPrivate *priv;
2050   GstClockTime start, stop;
2051   GstClockTimeDiff jitter;
2052   GstClockTime pt, entered, left;
2053   GstClockTime duration;
2054   gdouble rate;
2055
2056   priv = sink->priv;
2057
2058   start = priv->current_rstart;
2059
2060   /* if Quality-of-Service disabled, do nothing */
2061   if (!g_atomic_int_get (&priv->qos_enabled) || start == -1)
2062     return;
2063
2064   stop = priv->current_rstop;
2065   jitter = priv->current_jitter;
2066
2067   if (jitter < 0) {
2068     /* this is the time the buffer entered the sink */
2069     if (start < -jitter)
2070       entered = 0;
2071     else
2072       entered = start + jitter;
2073     left = start;
2074   } else {
2075     /* this is the time the buffer entered the sink */
2076     entered = start + jitter;
2077     /* this is the time the buffer left the sink */
2078     left = start + jitter;
2079   }
2080
2081   /* calculate duration of the buffer */
2082   if (stop != -1)
2083     duration = stop - start;
2084   else
2085     duration = -1;
2086
2087   /* if we have the time when the last buffer left us, calculate
2088    * processing time */
2089   if (priv->last_left != -1) {
2090     if (entered > priv->last_left) {
2091       pt = entered - priv->last_left;
2092     } else {
2093       pt = 0;
2094     }
2095   } else {
2096     pt = priv->avg_pt;
2097   }
2098
2099   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2100       ", entered %" GST_TIME_FORMAT ", left %" GST_TIME_FORMAT ", pt: %"
2101       GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT ",jitter %"
2102       G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (entered),
2103       GST_TIME_ARGS (left), GST_TIME_ARGS (pt), GST_TIME_ARGS (duration),
2104       jitter);
2105
2106   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "avg_duration: %" GST_TIME_FORMAT
2107       ", avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2108       GST_TIME_ARGS (priv->avg_duration), GST_TIME_ARGS (priv->avg_pt),
2109       priv->avg_rate);
2110
2111   /* collect running averages. for first observations, we copy the
2112    * values */
2113   if (priv->avg_duration == -1)
2114     priv->avg_duration = duration;
2115   else
2116     priv->avg_duration = UPDATE_RUNNING_AVG (priv->avg_duration, duration);
2117
2118   if (priv->avg_pt == -1)
2119     priv->avg_pt = pt;
2120   else
2121     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2122
2123   if (priv->avg_duration != 0)
2124     rate =
2125         gst_guint64_to_gdouble (priv->avg_pt) /
2126         gst_guint64_to_gdouble (priv->avg_duration);
2127   else
2128     rate = 0.0;
2129
2130   if (priv->last_left != -1) {
2131     if (dropped || priv->avg_rate < 0.0) {
2132       priv->avg_rate = rate;
2133     } else {
2134       if (rate > 1.0)
2135         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2136       else
2137         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2138     }
2139   }
2140
2141   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2142       "updated: avg_duration: %" GST_TIME_FORMAT ", avg_pt: %" GST_TIME_FORMAT
2143       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_duration),
2144       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2145
2146
2147   if (priv->avg_rate >= 0.0) {
2148     /* if we have a valid rate, start sending QoS messages */
2149     if (priv->current_jitter < 0) {
2150       /* make sure we never go below 0 when adding the jitter to the
2151        * timestamp. */
2152       if (priv->current_rstart < -priv->current_jitter)
2153         priv->current_jitter = -priv->current_rstart;
2154     }
2155     gst_base_sink_send_qos (sink, priv->avg_rate, priv->current_rstart,
2156         priv->current_jitter);
2157   }
2158
2159   /* record when this buffer will leave us */
2160   priv->last_left = left;
2161 }
2162
2163 /* reset all qos measuring */
2164 static void
2165 gst_base_sink_reset_qos (GstBaseSink * sink)
2166 {
2167   GstBaseSinkPrivate *priv;
2168
2169   priv = sink->priv;
2170
2171   priv->last_in_time = -1;
2172   priv->last_left = -1;
2173   priv->avg_duration = -1;
2174   priv->avg_pt = -1;
2175   priv->avg_rate = -1.0;
2176   priv->avg_render = -1;
2177   priv->rendered = 0;
2178   priv->dropped = 0;
2179
2180 }
2181
2182 /* Checks if the object was scheduled too late.
2183  *
2184  * start/stop contain the raw timestamp start and stop values
2185  * of the object.
2186  *
2187  * status and jitter contain the return values from the clock wait.
2188  *
2189  * returns TRUE if the buffer was too late.
2190  */
2191 static gboolean
2192 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2193     GstClockTime start, GstClockTime stop,
2194     GstClockReturn status, GstClockTimeDiff jitter)
2195 {
2196   gboolean late;
2197   gint64 max_lateness;
2198   GstBaseSinkPrivate *priv;
2199
2200   priv = basesink->priv;
2201
2202   late = FALSE;
2203
2204   /* only for objects that were too late */
2205   if (G_LIKELY (status != GST_CLOCK_EARLY))
2206     goto in_time;
2207
2208   max_lateness = basesink->abidata.ABI.max_lateness;
2209
2210   /* check if frame dropping is enabled */
2211   if (max_lateness == -1)
2212     goto no_drop;
2213
2214   /* only check for buffers */
2215   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2216     goto not_buffer;
2217
2218   /* can't do check if we don't have a timestamp */
2219   if (G_UNLIKELY (start == -1))
2220     goto no_timestamp;
2221
2222   /* we can add a valid stop time */
2223   if (stop != -1)
2224     max_lateness += stop;
2225   else
2226     max_lateness += start;
2227
2228   /* if the jitter bigger than duration and lateness we are too late */
2229   if ((late = start + jitter > max_lateness)) {
2230     GST_DEBUG_OBJECT (basesink, "buffer is too late %" GST_TIME_FORMAT
2231         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (start + jitter),
2232         GST_TIME_ARGS (max_lateness));
2233     /* !!emergency!!, if we did not receive anything valid for more than a 
2234      * second, render it anyway so the user sees something */
2235     if (priv->last_in_time != -1 && start - priv->last_in_time > GST_SECOND) {
2236       late = FALSE;
2237       GST_DEBUG_OBJECT (basesink,
2238           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
2239           GST_TIME_ARGS (priv->last_in_time));
2240     }
2241   }
2242
2243 done:
2244   if (!late) {
2245     priv->last_in_time = start;
2246   }
2247   return late;
2248
2249   /* all is fine */
2250 in_time:
2251   {
2252     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
2253     goto done;
2254   }
2255 no_drop:
2256   {
2257     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
2258     goto done;
2259   }
2260 not_buffer:
2261   {
2262     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
2263     return FALSE;
2264   }
2265 no_timestamp:
2266   {
2267     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
2268     return FALSE;
2269   }
2270 }
2271
2272 /* called before and after calling the render vmethod. It keeps track of how
2273  * much time was spent in the render method and is used to check if we are
2274  * flooded */
2275 static void
2276 gst_base_sink_do_render_stats (GstBaseSink * basesink, gboolean start)
2277 {
2278   GstBaseSinkPrivate *priv;
2279
2280   priv = basesink->priv;
2281
2282   if (start) {
2283     priv->start = gst_util_get_timestamp ();
2284   } else {
2285     GstClockTime elapsed;
2286
2287     priv->stop = gst_util_get_timestamp ();
2288
2289     elapsed = GST_CLOCK_DIFF (priv->start, priv->stop);
2290
2291     if (priv->avg_render == -1)
2292       priv->avg_render = elapsed;
2293     else
2294       priv->avg_render = UPDATE_RUNNING_AVG (priv->avg_render, elapsed);
2295
2296     GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2297         "avg_render: %" GST_TIME_FORMAT, GST_TIME_ARGS (priv->avg_render));
2298   }
2299 }
2300
2301 /* with STREAM_LOCK, PREROLL_LOCK,
2302  *
2303  * Synchronize the object on the clock and then render it.
2304  *
2305  * takes ownership of obj.
2306  */
2307 static GstFlowReturn
2308 gst_base_sink_render_object (GstBaseSink * basesink, GstPad * pad,
2309     GstMiniObject * obj)
2310 {
2311   GstFlowReturn ret = GST_FLOW_OK;
2312   GstBaseSinkClass *bclass;
2313   gboolean late = FALSE;
2314   GstBaseSinkPrivate *priv;
2315
2316   priv = basesink->priv;
2317
2318   /* synchronize this object, non syncable objects return OK
2319    * immediatly. */
2320   ret = gst_base_sink_do_sync (basesink, pad, obj, &late);
2321   if (G_UNLIKELY (ret != GST_FLOW_OK))
2322     goto sync_failed;
2323
2324   /* and now render, event or buffer. */
2325   if (G_LIKELY (GST_IS_BUFFER (obj))) {
2326     GstBuffer *buf;
2327
2328     /* drop late buffers unconditionally, let's hope it's unlikely */
2329     if (G_UNLIKELY (late))
2330       goto dropped;
2331
2332     buf = GST_BUFFER_CAST (obj);
2333
2334     gst_base_sink_set_last_buffer (basesink, buf);
2335
2336     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2337
2338     if (G_LIKELY (bclass->render)) {
2339       gint do_qos;
2340
2341       /* read once, to get same value before and after */
2342       do_qos = g_atomic_int_get (&priv->qos_enabled);
2343
2344       GST_DEBUG_OBJECT (basesink, "rendering buffer %p", obj);
2345
2346       /* record rendering time for QoS and stats */
2347       if (do_qos)
2348         gst_base_sink_do_render_stats (basesink, TRUE);
2349
2350       ret = bclass->render (basesink, buf);
2351
2352       priv->rendered++;
2353
2354       if (do_qos)
2355         gst_base_sink_do_render_stats (basesink, FALSE);
2356     }
2357   } else {
2358     GstEvent *event = GST_EVENT_CAST (obj);
2359     gboolean event_res = TRUE;
2360     GstEventType type;
2361
2362     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2363
2364     type = GST_EVENT_TYPE (event);
2365
2366     GST_DEBUG_OBJECT (basesink, "rendering event %p, type %s", obj,
2367         gst_event_type_get_name (type));
2368
2369     if (bclass->event)
2370       event_res = bclass->event (basesink, event);
2371
2372     /* when we get here we could be flushing again when the event handler calls
2373      * _wait_eos(). We have to ignore this object in that case. */
2374     if (G_UNLIKELY (basesink->flushing))
2375       goto flushing;
2376
2377     if (G_LIKELY (event_res)) {
2378       guint32 seqnum;
2379
2380       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
2381       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
2382
2383       switch (type) {
2384         case GST_EVENT_EOS:
2385         {
2386           GstMessage *message;
2387
2388           /* the EOS event is completely handled so we mark
2389            * ourselves as being in the EOS state. eos is also 
2390            * protected by the object lock so we can read it when 
2391            * answering the POSITION query. */
2392           GST_OBJECT_LOCK (basesink);
2393           basesink->eos = TRUE;
2394           GST_OBJECT_UNLOCK (basesink);
2395
2396           /* ok, now we can post the message */
2397           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
2398
2399           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
2400           gst_message_set_seqnum (message, seqnum);
2401           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
2402           break;
2403         }
2404         case GST_EVENT_NEWSEGMENT:
2405           /* configure the segment */
2406           gst_base_sink_configure_segment (basesink, pad, event,
2407               &basesink->segment);
2408           break;
2409         default:
2410           break;
2411       }
2412     }
2413   }
2414
2415 done:
2416   gst_base_sink_perform_qos (basesink, late);
2417
2418   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
2419   gst_mini_object_unref (obj);
2420
2421   return ret;
2422
2423   /* ERRORS */
2424 sync_failed:
2425   {
2426     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
2427     goto done;
2428   }
2429 dropped:
2430   {
2431     priv->dropped++;
2432     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
2433     goto done;
2434   }
2435 flushing:
2436   {
2437     GST_DEBUG_OBJECT (basesink, "we are flushing, ignore object");
2438     gst_mini_object_unref (obj);
2439     return GST_FLOW_WRONG_STATE;
2440   }
2441 }
2442
2443 /* with STREAM_LOCK, PREROLL_LOCK
2444  *
2445  * Perform preroll on the given object. For buffers this means 
2446  * calling the preroll subclass method. 
2447  * If that succeeds, the state will be commited.
2448  *
2449  * function does not take ownership of obj.
2450  */
2451 static GstFlowReturn
2452 gst_base_sink_preroll_object (GstBaseSink * basesink, GstMiniObject * obj)
2453 {
2454   GstFlowReturn ret;
2455
2456   GST_DEBUG_OBJECT (basesink, "prerolling object %p", obj);
2457
2458   /* if it's a buffer, we need to call the preroll method */
2459   if (G_LIKELY (GST_IS_BUFFER (obj)) && basesink->priv->call_preroll) {
2460     GstBaseSinkClass *bclass;
2461     GstBuffer *buf;
2462     GstClockTime timestamp;
2463
2464     buf = GST_BUFFER_CAST (obj);
2465     timestamp = GST_BUFFER_TIMESTAMP (buf);
2466
2467     GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
2468         GST_TIME_ARGS (timestamp));
2469
2470     gst_base_sink_set_last_buffer (basesink, buf);
2471
2472     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2473     if (bclass->preroll)
2474       if ((ret = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
2475         goto preroll_failed;
2476
2477     basesink->priv->call_preroll = FALSE;
2478   }
2479
2480   /* commit state */
2481   if (G_LIKELY (basesink->playing_async)) {
2482     if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
2483       goto stopping;
2484   }
2485
2486   return GST_FLOW_OK;
2487
2488   /* ERRORS */
2489 preroll_failed:
2490   {
2491     GST_DEBUG_OBJECT (basesink, "preroll failed, abort state");
2492     gst_element_abort_state (GST_ELEMENT_CAST (basesink));
2493     return ret;
2494   }
2495 stopping:
2496   {
2497     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
2498     return GST_FLOW_WRONG_STATE;
2499   }
2500 }
2501
2502 /* with STREAM_LOCK, PREROLL_LOCK 
2503  *
2504  * Queue an object for rendering.
2505  * The first prerollable object queued will complete the preroll. If the
2506  * preroll queue if filled, we render all the objects in the queue.
2507  *
2508  * This function takes ownership of the object.
2509  */
2510 static GstFlowReturn
2511 gst_base_sink_queue_object_unlocked (GstBaseSink * basesink, GstPad * pad,
2512     GstMiniObject * obj, gboolean prerollable)
2513 {
2514   GstFlowReturn ret = GST_FLOW_OK;
2515   gint length;
2516   GQueue *q;
2517
2518   if (G_UNLIKELY (basesink->need_preroll)) {
2519     if (G_LIKELY (prerollable))
2520       basesink->preroll_queued++;
2521
2522     length = basesink->preroll_queued;
2523
2524     GST_DEBUG_OBJECT (basesink, "now %d prerolled items", length);
2525
2526     /* first prerollable item needs to finish the preroll */
2527     if (length == 1) {
2528       ret = gst_base_sink_preroll_object (basesink, obj);
2529       if (G_UNLIKELY (ret != GST_FLOW_OK))
2530         goto preroll_failed;
2531     }
2532     /* need to recheck if we need preroll, commmit state during preroll 
2533      * could have made us not need more preroll. */
2534     if (G_UNLIKELY (basesink->need_preroll)) {
2535       /* see if we can render now, if we can't add the object to the preroll
2536        * queue. */
2537       if (G_UNLIKELY (length <= basesink->preroll_queue_max_len))
2538         goto more_preroll;
2539     }
2540   }
2541
2542   /* we can start rendering (or blocking) the queued object
2543    * if any. */
2544   q = basesink->preroll_queue;
2545   while (G_UNLIKELY (!g_queue_is_empty (q))) {
2546     GstMiniObject *o;
2547
2548     o = g_queue_pop_head (q);
2549     GST_DEBUG_OBJECT (basesink, "rendering queued object %p", o);
2550
2551     /* do something with the return value */
2552     ret = gst_base_sink_render_object (basesink, pad, o);
2553     if (ret != GST_FLOW_OK)
2554       goto dequeue_failed;
2555   }
2556
2557   /* now render the object */
2558   ret = gst_base_sink_render_object (basesink, pad, obj);
2559   basesink->preroll_queued = 0;
2560
2561   return ret;
2562
2563   /* special cases */
2564 preroll_failed:
2565   {
2566     GST_DEBUG_OBJECT (basesink, "preroll failed, reason %s",
2567         gst_flow_get_name (ret));
2568     gst_mini_object_unref (obj);
2569     return ret;
2570   }
2571 more_preroll:
2572   {
2573     /* add object to the queue and return */
2574     GST_DEBUG_OBJECT (basesink, "need more preroll data %d <= %d",
2575         length, basesink->preroll_queue_max_len);
2576     g_queue_push_tail (basesink->preroll_queue, obj);
2577     return GST_FLOW_OK;
2578   }
2579 dequeue_failed:
2580   {
2581     GST_DEBUG_OBJECT (basesink, "rendering queued objects failed, reason %s",
2582         gst_flow_get_name (ret));
2583     gst_mini_object_unref (obj);
2584     return ret;
2585   }
2586 }
2587
2588 /* with STREAM_LOCK
2589  *
2590  * This function grabs the PREROLL_LOCK and adds the object to
2591  * the queue.
2592  *
2593  * This function takes ownership of obj.
2594  */
2595 static GstFlowReturn
2596 gst_base_sink_queue_object (GstBaseSink * basesink, GstPad * pad,
2597     GstMiniObject * obj, gboolean prerollable)
2598 {
2599   GstFlowReturn ret;
2600
2601   GST_PAD_PREROLL_LOCK (pad);
2602   if (G_UNLIKELY (basesink->flushing))
2603     goto flushing;
2604
2605   if (G_UNLIKELY (basesink->priv->received_eos))
2606     goto was_eos;
2607
2608   ret = gst_base_sink_queue_object_unlocked (basesink, pad, obj, prerollable);
2609   GST_PAD_PREROLL_UNLOCK (pad);
2610
2611   return ret;
2612
2613   /* ERRORS */
2614 flushing:
2615   {
2616     GST_DEBUG_OBJECT (basesink, "sink is flushing");
2617     GST_PAD_PREROLL_UNLOCK (pad);
2618     gst_mini_object_unref (obj);
2619     return GST_FLOW_WRONG_STATE;
2620   }
2621 was_eos:
2622   {
2623     GST_DEBUG_OBJECT (basesink,
2624         "we are EOS, dropping object, return UNEXPECTED");
2625     GST_PAD_PREROLL_UNLOCK (pad);
2626     gst_mini_object_unref (obj);
2627     return GST_FLOW_UNEXPECTED;
2628   }
2629 }
2630
2631 static void
2632 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
2633 {
2634   /* make sure we are not blocked on the clock also clear any pending
2635    * eos state. */
2636   gst_base_sink_set_flushing (basesink, pad, TRUE);
2637
2638   /* we grab the stream lock but that is not needed since setting the
2639    * sink to flushing would make sure no state commit is being done
2640    * anymore */
2641   GST_PAD_STREAM_LOCK (pad);
2642   gst_base_sink_reset_qos (basesink);
2643   if (basesink->priv->async_enabled) {
2644     /* and we need to commit our state again on the next
2645      * prerolled buffer */
2646     basesink->playing_async = TRUE;
2647     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
2648   } else {
2649     basesink->priv->have_latency = TRUE;
2650     basesink->need_preroll = FALSE;
2651   }
2652   gst_base_sink_set_last_buffer (basesink, NULL);
2653   GST_PAD_STREAM_UNLOCK (pad);
2654 }
2655
2656 static void
2657 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad)
2658 {
2659   /* unset flushing so we can accept new data, this also flushes out any EOS
2660    * event. */
2661   gst_base_sink_set_flushing (basesink, pad, FALSE);
2662
2663   /* for position reporting */
2664   GST_OBJECT_LOCK (basesink);
2665   basesink->priv->current_sstart = -1;
2666   basesink->priv->current_sstop = -1;
2667   basesink->priv->eos_rtime = -1;
2668   basesink->priv->call_preroll = TRUE;
2669   if (basesink->pad_mode == GST_ACTIVATE_PUSH) {
2670     /* we need new segment info after the flush. */
2671     basesink->have_newsegment = FALSE;
2672     gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
2673     gst_segment_init (basesink->abidata.ABI.clip_segment, GST_FORMAT_UNDEFINED);
2674   }
2675   GST_OBJECT_UNLOCK (basesink);
2676 }
2677
2678 static gboolean
2679 gst_base_sink_event (GstPad * pad, GstEvent * event)
2680 {
2681   GstBaseSink *basesink;
2682   gboolean result = TRUE;
2683   GstBaseSinkClass *bclass;
2684
2685   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
2686
2687   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2688
2689   GST_DEBUG_OBJECT (basesink, "event %p (%s)", event,
2690       GST_EVENT_TYPE_NAME (event));
2691
2692   switch (GST_EVENT_TYPE (event)) {
2693     case GST_EVENT_EOS:
2694     {
2695       GstFlowReturn ret;
2696
2697       GST_PAD_PREROLL_LOCK (pad);
2698       if (G_UNLIKELY (basesink->flushing))
2699         goto flushing;
2700
2701       if (G_UNLIKELY (basesink->priv->received_eos)) {
2702         /* we can't accept anything when we are EOS */
2703         result = FALSE;
2704         gst_event_unref (event);
2705       } else {
2706         /* we set the received EOS flag here so that we can use it when testing if
2707          * we are prerolled and to refuse more buffers. */
2708         basesink->priv->received_eos = TRUE;
2709
2710         /* EOS is a prerollable object, we call the unlocked version because it
2711          * does not check the received_eos flag. */
2712         ret = gst_base_sink_queue_object_unlocked (basesink, pad,
2713             GST_MINI_OBJECT_CAST (event), TRUE);
2714         if (G_UNLIKELY (ret != GST_FLOW_OK))
2715           result = FALSE;
2716       }
2717       GST_PAD_PREROLL_UNLOCK (pad);
2718       break;
2719     }
2720     case GST_EVENT_NEWSEGMENT:
2721     {
2722       GstFlowReturn ret;
2723
2724       GST_DEBUG_OBJECT (basesink, "newsegment %p", event);
2725
2726       GST_PAD_PREROLL_LOCK (pad);
2727       if (G_UNLIKELY (basesink->flushing))
2728         goto flushing;
2729
2730       if (G_UNLIKELY (basesink->priv->received_eos)) {
2731         /* we can't accept anything when we are EOS */
2732         result = FALSE;
2733         gst_event_unref (event);
2734       } else {
2735         /* the new segment is a non prerollable item and does not block anything,
2736          * we need to configure the current clipping segment and insert the event 
2737          * in the queue to serialize it with the buffers for rendering. */
2738         gst_base_sink_configure_segment (basesink, pad, event,
2739             basesink->abidata.ABI.clip_segment);
2740
2741         ret =
2742             gst_base_sink_queue_object_unlocked (basesink, pad,
2743             GST_MINI_OBJECT_CAST (event), FALSE);
2744         if (G_UNLIKELY (ret != GST_FLOW_OK))
2745           result = FALSE;
2746         else {
2747           GST_OBJECT_LOCK (basesink);
2748           basesink->have_newsegment = TRUE;
2749           GST_OBJECT_UNLOCK (basesink);
2750         }
2751       }
2752       GST_PAD_PREROLL_UNLOCK (pad);
2753       break;
2754     }
2755     case GST_EVENT_FLUSH_START:
2756       if (bclass->event)
2757         bclass->event (basesink, event);
2758
2759       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
2760
2761       gst_base_sink_flush_start (basesink, pad);
2762
2763       gst_event_unref (event);
2764       break;
2765     case GST_EVENT_FLUSH_STOP:
2766       if (bclass->event)
2767         bclass->event (basesink, event);
2768
2769       GST_DEBUG_OBJECT (basesink, "flush-stop %p", event);
2770
2771       gst_base_sink_flush_stop (basesink, pad);
2772
2773       gst_event_unref (event);
2774       break;
2775     default:
2776       /* other events are sent to queue or subclass depending on if they
2777        * are serialized. */
2778       if (GST_EVENT_IS_SERIALIZED (event)) {
2779         gst_base_sink_queue_object (basesink, pad,
2780             GST_MINI_OBJECT_CAST (event), FALSE);
2781       } else {
2782         if (bclass->event)
2783           bclass->event (basesink, event);
2784         gst_event_unref (event);
2785       }
2786       break;
2787   }
2788 done:
2789   gst_object_unref (basesink);
2790
2791   return result;
2792
2793   /* ERRORS */
2794 flushing:
2795   {
2796     GST_DEBUG_OBJECT (basesink, "we are flushing");
2797     GST_PAD_PREROLL_UNLOCK (pad);
2798     result = FALSE;
2799     gst_event_unref (event);
2800     goto done;
2801   }
2802 }
2803
2804 /* default implementation to calculate the start and end
2805  * timestamps on a buffer, subclasses can override
2806  */
2807 static void
2808 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
2809     GstClockTime * start, GstClockTime * end)
2810 {
2811   GstClockTime timestamp, duration;
2812
2813   timestamp = GST_BUFFER_TIMESTAMP (buffer);
2814   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
2815
2816     /* get duration to calculate end time */
2817     duration = GST_BUFFER_DURATION (buffer);
2818     if (GST_CLOCK_TIME_IS_VALID (duration)) {
2819       *end = timestamp + duration;
2820     }
2821     *start = timestamp;
2822   }
2823 }
2824
2825 /* must be called with PREROLL_LOCK */
2826 static gboolean
2827 gst_base_sink_needs_preroll (GstBaseSink * basesink)
2828 {
2829   gboolean is_prerolled, res;
2830
2831   /* we have 2 cases where the PREROLL_LOCK is released:
2832    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
2833    *  2) we are syncing on the clock
2834    */
2835   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
2836   res = !is_prerolled;
2837
2838   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
2839       basesink->have_preroll, basesink->priv->received_eos, res);
2840
2841   return res;
2842 }
2843
2844 /* with STREAM_LOCK, PREROLL_LOCK 
2845  *
2846  * Takes a buffer and compare the timestamps with the last segment.
2847  * If the buffer falls outside of the segment boundaries, drop it.
2848  * Else queue the buffer for preroll and rendering.
2849  *
2850  * This function takes ownership of the buffer.
2851  */
2852 static GstFlowReturn
2853 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
2854     GstBuffer * buf)
2855 {
2856   GstBaseSinkClass *bclass;
2857   GstFlowReturn result;
2858   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
2859   GstSegment *clip_segment;
2860
2861   if (G_UNLIKELY (basesink->flushing))
2862     goto flushing;
2863
2864   if (G_UNLIKELY (basesink->priv->received_eos))
2865     goto was_eos;
2866
2867   /* for code clarity */
2868   clip_segment = basesink->abidata.ABI.clip_segment;
2869
2870   if (G_UNLIKELY (!basesink->have_newsegment)) {
2871     gboolean sync;
2872
2873     sync = gst_base_sink_get_sync (basesink);
2874     if (sync) {
2875       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
2876           (_("Internal data flow problem.")),
2877           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
2878     }
2879
2880     /* this means this sink will assume timestamps start from 0 */
2881     GST_OBJECT_LOCK (basesink);
2882     clip_segment->start = 0;
2883     clip_segment->stop = -1;
2884     basesink->segment.start = 0;
2885     basesink->segment.stop = -1;
2886     basesink->have_newsegment = TRUE;
2887     GST_OBJECT_UNLOCK (basesink);
2888   }
2889
2890   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2891
2892   /* check if the buffer needs to be dropped, we first ask the subclass for the
2893    * start and end */
2894   if (bclass->get_times)
2895     bclass->get_times (basesink, buf, &start, &end);
2896
2897   if (start == -1) {
2898     /* if the subclass does not want sync, we use our own values so that we at
2899      * least clip the buffer to the segment */
2900     gst_base_sink_get_times (basesink, buf, &start, &end);
2901   }
2902
2903   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
2904       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
2905
2906   /* a dropped buffer does not participate in anything */
2907   if (GST_CLOCK_TIME_IS_VALID (start) &&
2908       (clip_segment->format == GST_FORMAT_TIME)) {
2909     if (G_UNLIKELY (!gst_segment_clip (clip_segment,
2910                 GST_FORMAT_TIME, (gint64) start, (gint64) end, NULL, NULL)))
2911       goto out_of_segment;
2912   }
2913
2914   /* now we can process the buffer in the queue, this function takes ownership
2915    * of the buffer */
2916   result = gst_base_sink_queue_object_unlocked (basesink, pad,
2917       GST_MINI_OBJECT_CAST (buf), TRUE);
2918
2919   return result;
2920
2921   /* ERRORS */
2922 flushing:
2923   {
2924     GST_DEBUG_OBJECT (basesink, "sink is flushing");
2925     gst_buffer_unref (buf);
2926     return GST_FLOW_WRONG_STATE;
2927   }
2928 was_eos:
2929   {
2930     GST_DEBUG_OBJECT (basesink,
2931         "we are EOS, dropping object, return UNEXPECTED");
2932     gst_buffer_unref (buf);
2933     return GST_FLOW_UNEXPECTED;
2934   }
2935 out_of_segment:
2936   {
2937     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
2938     gst_buffer_unref (buf);
2939     return GST_FLOW_OK;
2940   }
2941 }
2942
2943 /* with STREAM_LOCK
2944  */
2945 static GstFlowReturn
2946 gst_base_sink_chain (GstPad * pad, GstBuffer * buf)
2947 {
2948   GstBaseSink *basesink;
2949   GstFlowReturn result;
2950
2951   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
2952
2953   if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH))
2954     goto wrong_mode;
2955
2956   GST_PAD_PREROLL_LOCK (pad);
2957   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
2958   GST_PAD_PREROLL_UNLOCK (pad);
2959
2960 done:
2961   return result;
2962
2963   /* ERRORS */
2964 wrong_mode:
2965   {
2966     GST_OBJECT_LOCK (pad);
2967     GST_WARNING_OBJECT (basesink,
2968         "Push on pad %s:%s, but it was not activated in push mode",
2969         GST_DEBUG_PAD_NAME (pad));
2970     GST_OBJECT_UNLOCK (pad);
2971     gst_buffer_unref (buf);
2972     /* we don't post an error message this will signal to the peer
2973      * pushing that EOS is reached. */
2974     result = GST_FLOW_UNEXPECTED;
2975     goto done;
2976   }
2977 }
2978
2979 static gboolean
2980 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
2981 {
2982   gboolean res = TRUE;
2983
2984   /* update our offset if the start/stop position was updated */
2985   if (segment->format == GST_FORMAT_BYTES) {
2986     segment->time = segment->start;
2987   } else if (segment->start == 0) {
2988     /* seek to start, we can implement a default for this. */
2989     segment->time = 0;
2990   } else {
2991     res = FALSE;
2992     GST_INFO_OBJECT (sink, "Can't do a default seek");
2993   }
2994
2995   return res;
2996 }
2997
2998 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
2999
3000 static gboolean
3001 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3002     GstEvent * event, GstSegment * segment)
3003 {
3004   /* By default, we try one of 2 things:
3005    *   - For absolute seek positions, convert the requested position to our 
3006    *     configured processing format and place it in the output segment \
3007    *   - For relative seek positions, convert our current (input) values to the
3008    *     seek format, adjust by the relative seek offset and then convert back to
3009    *     the processing format
3010    */
3011   GstSeekType cur_type, stop_type;
3012   gint64 cur, stop;
3013   GstSeekFlags flags;
3014   GstFormat seek_format, dest_format;
3015   gdouble rate;
3016   gboolean update;
3017   gboolean res = TRUE;
3018
3019   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3020       &cur_type, &cur, &stop_type, &stop);
3021   dest_format = segment->format;
3022
3023   if (seek_format == dest_format) {
3024     gst_segment_set_seek (segment, rate, seek_format, flags,
3025         cur_type, cur, stop_type, stop, &update);
3026     return TRUE;
3027   }
3028
3029   if (cur_type != GST_SEEK_TYPE_NONE) {
3030     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3031     res =
3032         gst_pad_query_convert (sink->sinkpad, seek_format, cur, &dest_format,
3033         &cur);
3034     cur_type = GST_SEEK_TYPE_SET;
3035   }
3036
3037   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3038     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3039     res =
3040         gst_pad_query_convert (sink->sinkpad, seek_format, stop, &dest_format,
3041         &stop);
3042     stop_type = GST_SEEK_TYPE_SET;
3043   }
3044
3045   /* And finally, configure our output segment in the desired format */
3046   gst_segment_set_seek (segment, rate, dest_format, flags, cur_type, cur,
3047       stop_type, stop, &update);
3048
3049   if (!res)
3050     goto no_format;
3051
3052   return res;
3053
3054 no_format:
3055   {
3056     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3057     return FALSE;
3058   }
3059 }
3060
3061 /* perform a seek, only executed in pull mode */
3062 static gboolean
3063 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3064 {
3065   gboolean flush;
3066   gdouble rate;
3067   GstFormat seek_format, dest_format;
3068   GstSeekFlags flags;
3069   GstSeekType cur_type, stop_type;
3070   gboolean seekseg_configured = FALSE;
3071   gint64 cur, stop;
3072   gboolean update, res = TRUE;
3073   GstSegment seeksegment;
3074
3075   dest_format = sink->segment.format;
3076
3077   if (event) {
3078     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3079     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3080         &cur_type, &cur, &stop_type, &stop);
3081
3082     flush = flags & GST_SEEK_FLAG_FLUSH;
3083   } else {
3084     GST_DEBUG_OBJECT (sink, "performing seek without event");
3085     flush = FALSE;
3086   }
3087
3088   if (flush) {
3089     GST_DEBUG_OBJECT (sink, "flushing upstream");
3090     gst_pad_push_event (pad, gst_event_new_flush_start ());
3091     gst_base_sink_flush_start (sink, pad);
3092   } else {
3093     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3094   }
3095
3096   GST_PAD_STREAM_LOCK (pad);
3097
3098   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3099    * copy the current segment info into the temp segment that we can actually
3100    * attempt the seek with. We only update the real segment if the seek suceeds. */
3101   if (!seekseg_configured) {
3102     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3103
3104     /* now configure the final seek segment */
3105     if (event) {
3106       if (sink->segment.format != seek_format) {
3107         /* OK, here's where we give the subclass a chance to convert the relative
3108          * seek into an absolute one in the processing format. We set up any
3109          * absolute seek above, before taking the stream lock. */
3110         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3111                 &seeksegment)) {
3112           GST_DEBUG_OBJECT (sink,
3113               "Preparing the seek failed after flushing. " "Aborting seek");
3114           res = FALSE;
3115         }
3116       } else {
3117         /* The seek format matches our processing format, no need to ask the
3118          * the subclass to configure the segment. */
3119         gst_segment_set_seek (&seeksegment, rate, seek_format, flags,
3120             cur_type, cur, stop_type, stop, &update);
3121       }
3122     }
3123     /* Else, no seek event passed, so we're just (re)starting the 
3124        current segment. */
3125   }
3126
3127   if (res) {
3128     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3129         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3130         seeksegment.start, seeksegment.stop, seeksegment.last_stop);
3131
3132     /* do the seek, segment.last_stop contains the new position. */
3133     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3134   }
3135
3136
3137   if (flush) {
3138     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3139     gst_pad_push_event (pad, gst_event_new_flush_stop ());
3140     gst_base_sink_flush_stop (sink, pad);
3141   } else if (res && sink->abidata.ABI.running) {
3142     /* we are running the current segment and doing a non-flushing seek, 
3143      * close the segment first based on the last_stop. */
3144     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3145         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.last_stop);
3146   }
3147
3148   /* The subclass must have converted the segment to the processing format 
3149    * by now */
3150   if (res && seeksegment.format != dest_format) {
3151     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3152         "in the correct format. Aborting seek.");
3153     res = FALSE;
3154   }
3155
3156   /* if successfull seek, we update our real segment and push
3157    * out the new segment. */
3158   if (res) {
3159     memcpy (&sink->segment, &seeksegment, sizeof (GstSegment));
3160
3161     if (sink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3162       gst_element_post_message (GST_ELEMENT (sink),
3163           gst_message_new_segment_start (GST_OBJECT (sink),
3164               sink->segment.format, sink->segment.last_stop));
3165     }
3166   }
3167
3168   sink->priv->discont = TRUE;
3169   sink->abidata.ABI.running = TRUE;
3170
3171   GST_PAD_STREAM_UNLOCK (pad);
3172
3173   return res;
3174 }
3175
3176 /* with STREAM_LOCK
3177  */
3178 static void
3179 gst_base_sink_loop (GstPad * pad)
3180 {
3181   GstBaseSink *basesink;
3182   GstBuffer *buf = NULL;
3183   GstFlowReturn result;
3184   guint blocksize;
3185   guint64 offset;
3186
3187   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3188
3189   g_assert (basesink->pad_mode == GST_ACTIVATE_PULL);
3190
3191   if ((blocksize = basesink->priv->blocksize) == 0)
3192     blocksize = -1;
3193
3194   offset = basesink->segment.last_stop;
3195
3196   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
3197       offset, blocksize);
3198
3199   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
3200   if (G_UNLIKELY (result != GST_FLOW_OK))
3201     goto paused;
3202
3203   if (G_UNLIKELY (buf == NULL))
3204     goto no_buffer;
3205
3206   offset += GST_BUFFER_SIZE (buf);
3207
3208   gst_segment_set_last_stop (&basesink->segment, GST_FORMAT_BYTES, offset);
3209
3210   GST_PAD_PREROLL_LOCK (pad);
3211   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
3212   GST_PAD_PREROLL_UNLOCK (pad);
3213   if (G_UNLIKELY (result != GST_FLOW_OK))
3214     goto paused;
3215
3216   return;
3217
3218   /* ERRORS */
3219 paused:
3220   {
3221     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
3222         gst_flow_get_name (result));
3223     gst_pad_pause_task (pad);
3224     /* fatal errors and NOT_LINKED cause EOS */
3225     if (GST_FLOW_IS_FATAL (result) || result == GST_FLOW_NOT_LINKED) {
3226       if (result == GST_FLOW_UNEXPECTED) {
3227         /* perform EOS logic */
3228         if (basesink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3229           gst_element_post_message (GST_ELEMENT_CAST (basesink),
3230               gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
3231                   basesink->segment.format, basesink->segment.last_stop));
3232         } else {
3233           gst_base_sink_event (pad, gst_event_new_eos ());
3234         }
3235       } else {
3236         /* for fatal errors we post an error message, post the error
3237          * first so the app knows about the error first. */
3238         GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3239             (_("Internal data stream error.")),
3240             ("stream stopped, reason %s", gst_flow_get_name (result)));
3241         gst_base_sink_event (pad, gst_event_new_eos ());
3242       }
3243     }
3244     return;
3245   }
3246 no_buffer:
3247   {
3248     GST_LOG_OBJECT (basesink, "no buffer, pausing");
3249     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3250         (_("Internal data flow error.")), ("element returned NULL buffer"));
3251     result = GST_FLOW_ERROR;
3252     goto paused;
3253   }
3254 }
3255
3256 static gboolean
3257 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
3258     gboolean flushing)
3259 {
3260   GstBaseSinkClass *bclass;
3261
3262   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3263
3264   if (flushing) {
3265     /* unlock any subclasses, we need to do this before grabbing the
3266      * PREROLL_LOCK since we hold this lock before going into ::render. */
3267     if (bclass->unlock)
3268       bclass->unlock (basesink);
3269   }
3270
3271   GST_PAD_PREROLL_LOCK (pad);
3272   basesink->flushing = flushing;
3273   if (flushing) {
3274     /* step 1, now that we have the PREROLL lock, clear our unlock request */
3275     if (bclass->unlock_stop)
3276       bclass->unlock_stop (basesink);
3277
3278     /* set need_preroll before we unblock the clock. If the clock is unblocked
3279      * before timing out, we can reuse the buffer for preroll. */
3280     basesink->need_preroll = TRUE;
3281
3282     /* step 2, unblock clock sync (if any) or any other blocking thing */
3283     if (basesink->clock_id) {
3284       gst_clock_id_unschedule (basesink->clock_id);
3285     }
3286
3287     /* flush out the data thread if it's locked in finish_preroll, this will
3288      * also flush out the EOS state */
3289     GST_DEBUG_OBJECT (basesink,
3290         "flushing out data thread, need preroll to TRUE");
3291     gst_base_sink_preroll_queue_flush (basesink, pad);
3292   }
3293   GST_PAD_PREROLL_UNLOCK (pad);
3294
3295   return TRUE;
3296 }
3297
3298 static gboolean
3299 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
3300 {
3301   gboolean result;
3302
3303   if (active) {
3304     /* start task */
3305     result = gst_pad_start_task (basesink->sinkpad,
3306         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad);
3307   } else {
3308     /* step 2, make sure streaming finishes */
3309     result = gst_pad_stop_task (basesink->sinkpad);
3310   }
3311
3312   return result;
3313 }
3314
3315 static gboolean
3316 gst_base_sink_pad_activate (GstPad * pad)
3317 {
3318   gboolean result = FALSE;
3319   GstBaseSink *basesink;
3320
3321   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3322
3323   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
3324
3325   gst_base_sink_set_flushing (basesink, pad, FALSE);
3326
3327   /* we need to have the pull mode enabled */
3328   if (!basesink->can_activate_pull) {
3329     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
3330     goto fallback;
3331   }
3332
3333   /* check if downstreams supports pull mode at all */
3334   if (!gst_pad_check_pull_range (pad)) {
3335     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
3336     goto fallback;
3337   }
3338
3339   /* set the pad mode before starting the task so that it's in the
3340    * correct state for the new thread. also the sink set_caps and get_caps
3341    * function checks this */
3342   basesink->pad_mode = GST_ACTIVATE_PULL;
3343
3344   /* we first try to negotiate a format so that when we try to activate
3345    * downstream, it knows about our format */
3346   if (!gst_base_sink_negotiate_pull (basesink)) {
3347     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
3348     goto fallback;
3349   }
3350
3351   /* ok activate now */
3352   if (!gst_pad_activate_pull (pad, TRUE)) {
3353     /* clear any pending caps */
3354     GST_OBJECT_LOCK (basesink);
3355     gst_caps_replace (&basesink->priv->pull_caps, NULL);
3356     GST_OBJECT_UNLOCK (basesink);
3357     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
3358     goto fallback;
3359   }
3360
3361   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
3362   result = TRUE;
3363   goto done;
3364
3365   /* push mode fallback */
3366 fallback:
3367   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
3368   if ((result = gst_pad_activate_push (pad, TRUE))) {
3369     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
3370   }
3371
3372 done:
3373   if (!result) {
3374     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
3375     gst_base_sink_set_flushing (basesink, pad, TRUE);
3376   }
3377
3378   gst_object_unref (basesink);
3379
3380   return result;
3381 }
3382
3383 static gboolean
3384 gst_base_sink_pad_activate_push (GstPad * pad, gboolean active)
3385 {
3386   gboolean result;
3387   GstBaseSink *basesink;
3388
3389   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3390
3391   if (active) {
3392     if (!basesink->can_activate_push) {
3393       result = FALSE;
3394       basesink->pad_mode = GST_ACTIVATE_NONE;
3395     } else {
3396       result = TRUE;
3397       basesink->pad_mode = GST_ACTIVATE_PUSH;
3398     }
3399   } else {
3400     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH)) {
3401       g_warning ("Internal GStreamer activation error!!!");
3402       result = FALSE;
3403     } else {
3404       gst_base_sink_set_flushing (basesink, pad, TRUE);
3405       result = TRUE;
3406       basesink->pad_mode = GST_ACTIVATE_NONE;
3407     }
3408   }
3409
3410   gst_object_unref (basesink);
3411
3412   return result;
3413 }
3414
3415 static gboolean
3416 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
3417 {
3418   GstCaps *caps;
3419   gboolean result;
3420
3421   result = FALSE;
3422
3423   /* this returns the intersection between our caps and the peer caps. If there
3424    * is no peer, it returns NULL and we can't operate in pull mode so we can
3425    * fail the negotiation. */
3426   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
3427   if (caps == NULL || gst_caps_is_empty (caps))
3428     goto no_caps_possible;
3429
3430   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
3431
3432   caps = gst_caps_make_writable (caps);
3433   /* get the first (prefered) format */
3434   gst_caps_truncate (caps);
3435   /* try to fixate */
3436   gst_pad_fixate_caps (GST_BASE_SINK_PAD (basesink), caps);
3437
3438   GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
3439
3440   if (gst_caps_is_any (caps)) {
3441     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
3442         "allowing pull()");
3443     /* neither side has template caps in this case, so they are prepared for
3444        pull() without setcaps() */
3445     result = TRUE;
3446   } else if (gst_caps_is_fixed (caps)) {
3447     if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
3448       goto could_not_set_caps;
3449
3450     GST_OBJECT_LOCK (basesink);
3451     gst_caps_replace (&basesink->priv->pull_caps, caps);
3452     GST_OBJECT_UNLOCK (basesink);
3453
3454     result = TRUE;
3455   }
3456
3457   gst_caps_unref (caps);
3458
3459   return result;
3460
3461 no_caps_possible:
3462   {
3463     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
3464     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
3465     if (caps)
3466       gst_caps_unref (caps);
3467     return FALSE;
3468   }
3469 could_not_set_caps:
3470   {
3471     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
3472     gst_caps_unref (caps);
3473     return FALSE;
3474   }
3475 }
3476
3477 /* this won't get called until we implement an activate function */
3478 static gboolean
3479 gst_base_sink_pad_activate_pull (GstPad * pad, gboolean active)
3480 {
3481   gboolean result = FALSE;
3482   GstBaseSink *basesink;
3483   GstBaseSinkClass *bclass;
3484
3485   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3486   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3487
3488   if (active) {
3489     GstFormat format;
3490     gint64 duration;
3491
3492     /* we mark we have a newsegment here because pull based
3493      * mode works just fine without having a newsegment before the
3494      * first buffer */
3495     format = GST_FORMAT_BYTES;
3496
3497     gst_segment_init (&basesink->segment, format);
3498     gst_segment_init (basesink->abidata.ABI.clip_segment, format);
3499     GST_OBJECT_LOCK (basesink);
3500     basesink->have_newsegment = TRUE;
3501     GST_OBJECT_UNLOCK (basesink);
3502
3503     /* get the peer duration in bytes */
3504     result = gst_pad_query_peer_duration (pad, &format, &duration);
3505     if (result) {
3506       GST_DEBUG_OBJECT (basesink,
3507           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
3508       gst_segment_set_duration (basesink->abidata.ABI.clip_segment, format,
3509           duration);
3510       gst_segment_set_duration (&basesink->segment, format, duration);
3511     } else {
3512       GST_DEBUG_OBJECT (basesink, "unknown duration");
3513     }
3514
3515     if (bclass->activate_pull)
3516       result = bclass->activate_pull (basesink, TRUE);
3517     else
3518       result = FALSE;
3519
3520     if (!result)
3521       goto activate_failed;
3522
3523   } else {
3524     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PULL)) {
3525       g_warning ("Internal GStreamer activation error!!!");
3526       result = FALSE;
3527     } else {
3528       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
3529       if (bclass->activate_pull)
3530         result &= bclass->activate_pull (basesink, FALSE);
3531       basesink->pad_mode = GST_ACTIVATE_NONE;
3532       /* clear any pending caps */
3533       GST_OBJECT_LOCK (basesink);
3534       gst_caps_replace (&basesink->priv->pull_caps, NULL);
3535       GST_OBJECT_UNLOCK (basesink);
3536     }
3537   }
3538   gst_object_unref (basesink);
3539
3540   return result;
3541
3542   /* ERRORS */
3543 activate_failed:
3544   {
3545     /* reset, as starting the thread failed */
3546     basesink->pad_mode = GST_ACTIVATE_NONE;
3547
3548     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
3549     return FALSE;
3550   }
3551 }
3552
3553 /* send an event to our sinkpad peer. */
3554 static gboolean
3555 gst_base_sink_send_event (GstElement * element, GstEvent * event)
3556 {
3557   GstPad *pad;
3558   GstBaseSink *basesink = GST_BASE_SINK (element);
3559   gboolean forward, result = TRUE;
3560   GstActivateMode mode;
3561
3562   GST_OBJECT_LOCK (element);
3563   /* get the pad and the scheduling mode */
3564   pad = gst_object_ref (basesink->sinkpad);
3565   mode = basesink->pad_mode;
3566   GST_OBJECT_UNLOCK (element);
3567
3568   /* only push UPSTREAM events upstream */
3569   forward = GST_EVENT_IS_UPSTREAM (event);
3570
3571   switch (GST_EVENT_TYPE (event)) {
3572     case GST_EVENT_LATENCY:
3573     {
3574       GstClockTime latency;
3575
3576       gst_event_parse_latency (event, &latency);
3577
3578       /* store the latency. We use this to adjust the running_time before syncing
3579        * it to the clock. */
3580       GST_OBJECT_LOCK (element);
3581       basesink->priv->latency = latency;
3582       if (!basesink->priv->have_latency)
3583         forward = FALSE;
3584       GST_OBJECT_UNLOCK (element);
3585       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
3586           GST_TIME_ARGS (latency));
3587
3588       /* We forward this event so that all elements know about the global pipeline
3589        * latency. This is interesting for an element when it wants to figure out
3590        * when a particular piece of data will be rendered. */
3591       break;
3592     }
3593     case GST_EVENT_SEEK:
3594       /* in pull mode we will execute the seek */
3595       if (mode == GST_ACTIVATE_PULL)
3596         result = gst_base_sink_perform_seek (basesink, pad, event);
3597       break;
3598     default:
3599       break;
3600   }
3601
3602   if (forward) {
3603     result = gst_pad_push_event (pad, event);
3604   } else {
3605     /* not forwarded, unref the event */
3606     gst_event_unref (event);
3607   }
3608
3609   gst_object_unref (pad);
3610   return result;
3611 }
3612
3613 static gboolean
3614 gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query)
3615 {
3616   GstPad *peer;
3617   gboolean res = FALSE;
3618
3619   if ((peer = gst_pad_get_peer (sink->sinkpad))) {
3620     res = gst_pad_query (peer, query);
3621     gst_object_unref (peer);
3622   }
3623   return res;
3624 }
3625
3626 /* get the end position of the last seen object, this is used
3627  * for EOS and for making sure that we don't report a position we
3628  * have not reached yet. With LOCK. */
3629 static gboolean
3630 gst_base_sink_get_position_last (GstBaseSink * basesink, GstFormat format,
3631     gint64 * cur)
3632 {
3633   GstFormat oformat;
3634   GstSegment *segment;
3635   gboolean ret = TRUE;
3636
3637   segment = &basesink->segment;
3638   oformat = segment->format;
3639
3640   if (oformat == GST_FORMAT_TIME) {
3641     /* return last observed stream time, we keep the stream time around in the
3642      * time format. */
3643     *cur = basesink->priv->current_sstop;
3644   } else {
3645     /* convert last stop to stream time */
3646     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3647   }
3648
3649   if (*cur != -1 && oformat != format) {
3650     GST_OBJECT_UNLOCK (basesink);
3651     /* convert to the target format if we need to, release lock first */
3652     ret =
3653         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3654     if (!ret)
3655       *cur = -1;
3656     GST_OBJECT_LOCK (basesink);
3657   }
3658
3659   GST_DEBUG_OBJECT (basesink, "POSITION: %" GST_TIME_FORMAT,
3660       GST_TIME_ARGS (*cur));
3661
3662   return ret;
3663 }
3664
3665 /* get the position when we are PAUSED, this is the stream time of the buffer
3666  * that prerolled. If no buffer is prerolled (we are still flushing), this
3667  * value will be -1. With LOCK. */
3668 static gboolean
3669 gst_base_sink_get_position_paused (GstBaseSink * basesink, GstFormat format,
3670     gint64 * cur)
3671 {
3672   gboolean res;
3673   gint64 time;
3674   GstSegment *segment;
3675   GstFormat oformat;
3676
3677   /* we don't use the clip segment in pull mode, when seeking we update the
3678    * main segment directly with the new segment values without it having to be
3679    * activated by the rendering after preroll */
3680   if (basesink->pad_mode == GST_ACTIVATE_PUSH)
3681     segment = basesink->abidata.ABI.clip_segment;
3682   else
3683     segment = &basesink->segment;
3684   oformat = segment->format;
3685
3686   if (oformat == GST_FORMAT_TIME) {
3687     *cur = basesink->priv->current_sstart;
3688   } else {
3689     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3690   }
3691
3692   time = segment->time;
3693
3694   if (*cur != -1) {
3695     *cur = MAX (*cur, time);
3696     GST_DEBUG_OBJECT (basesink, "POSITION as max: %" GST_TIME_FORMAT
3697         ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (*cur), GST_TIME_ARGS (time));
3698   } else {
3699     /* we have no buffer, use the segment times. */
3700     if (segment->rate >= 0.0) {
3701       /* forward, next position is always the time of the segment */
3702       *cur = time;
3703       GST_DEBUG_OBJECT (basesink, "POSITION as time: %" GST_TIME_FORMAT,
3704           GST_TIME_ARGS (*cur));
3705     } else {
3706       /* reverse, next expected timestamp is segment->stop. We use the function
3707        * to get things right for negative applied_rates. */
3708       *cur = gst_segment_to_stream_time (segment, oformat, segment->stop);
3709       GST_DEBUG_OBJECT (basesink, "reverse POSITION: %" GST_TIME_FORMAT,
3710           GST_TIME_ARGS (*cur));
3711     }
3712   }
3713
3714   res = (*cur != -1);
3715   if (res && oformat != format) {
3716     GST_OBJECT_UNLOCK (basesink);
3717     res =
3718         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3719     if (!res)
3720       *cur = -1;
3721     GST_OBJECT_LOCK (basesink);
3722   }
3723
3724   return res;
3725 }
3726
3727 static gboolean
3728 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
3729     gint64 * cur, gboolean * upstream)
3730 {
3731   GstClock *clock;
3732   gboolean res = FALSE;
3733   GstFormat oformat, tformat;
3734   GstClockTime now, base, latency;
3735   gint64 time, accum, duration;
3736   gdouble rate;
3737   gint64 last;
3738
3739   GST_OBJECT_LOCK (basesink);
3740   /* our intermediate time format */
3741   tformat = GST_FORMAT_TIME;
3742   /* get the format in the segment */
3743   oformat = basesink->segment.format;
3744
3745   /* can only give answer based on the clock if not EOS */
3746   if (G_UNLIKELY (basesink->eos))
3747     goto in_eos;
3748
3749   /* we can only get the segment when we are not NULL or READY */
3750   if (!basesink->have_newsegment)
3751     goto wrong_state;
3752
3753   /* when not in PLAYING or when we're busy with a state change, we
3754    * cannot read from the clock so we report time based on the
3755    * last seen timestamp. */
3756   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
3757       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING)
3758     goto in_pause;
3759
3760   /* we need to sync on the clock. */
3761   if (basesink->sync == FALSE)
3762     goto no_sync;
3763
3764   /* and we need a clock */
3765   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
3766     goto no_sync;
3767
3768   /* collect all data we need holding the lock */
3769   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.time))
3770     time = basesink->segment.time;
3771   else
3772     time = 0;
3773
3774   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.stop))
3775     duration = basesink->segment.stop - basesink->segment.start;
3776   else
3777     duration = 0;
3778
3779   base = GST_ELEMENT_CAST (basesink)->base_time;
3780   accum = basesink->segment.accum;
3781   rate = basesink->segment.rate * basesink->segment.applied_rate;
3782   latency = basesink->priv->latency;
3783
3784   gst_object_ref (clock);
3785
3786   /* this function might release the LOCK */
3787   gst_base_sink_get_position_last (basesink, format, &last);
3788
3789   /* need to release the object lock before we can get the time, 
3790    * a clock might take the LOCK of the provider, which could be
3791    * a basesink subclass. */
3792   GST_OBJECT_UNLOCK (basesink);
3793
3794   now = gst_clock_get_time (clock);
3795
3796   if (oformat != tformat) {
3797     /* convert accum, time and duration to time */
3798     if (!gst_pad_query_convert (basesink->sinkpad, oformat, accum, &tformat,
3799             &accum))
3800       goto convert_failed;
3801     if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration, &tformat,
3802             &duration))
3803       goto convert_failed;
3804     if (!gst_pad_query_convert (basesink->sinkpad, oformat, time, &tformat,
3805             &time))
3806       goto convert_failed;
3807   }
3808
3809   /* subtract base time and accumulated time from the clock time. 
3810    * Make sure we don't go negative. This is the current time in
3811    * the segment which we need to scale with the combined 
3812    * rate and applied rate. */
3813   base += accum;
3814   base += latency;
3815   base = MIN (now, base);
3816
3817   /* for negative rates we need to count back from from the segment
3818    * duration. */
3819   if (rate < 0.0)
3820     time += duration;
3821
3822   *cur = time + gst_guint64_to_gdouble (now - base) * rate;
3823
3824   /* never report more than last seen position */
3825   if (last != -1)
3826     *cur = MIN (last, *cur);
3827
3828   gst_object_unref (clock);
3829
3830   GST_DEBUG_OBJECT (basesink,
3831       "now %" GST_TIME_FORMAT " - base %" GST_TIME_FORMAT " - accum %"
3832       GST_TIME_FORMAT " + time %" GST_TIME_FORMAT,
3833       GST_TIME_ARGS (now), GST_TIME_ARGS (base),
3834       GST_TIME_ARGS (accum), GST_TIME_ARGS (time));
3835
3836   if (oformat != format) {
3837     /* convert time to final format */
3838     if (!gst_pad_query_convert (basesink->sinkpad, tformat, *cur, &format, cur))
3839       goto convert_failed;
3840   }
3841
3842   res = TRUE;
3843
3844 done:
3845   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
3846       res, GST_TIME_ARGS (*cur));
3847   return res;
3848
3849   /* special cases */
3850 in_eos:
3851   {
3852     GST_DEBUG_OBJECT (basesink, "position in EOS");
3853     res = gst_base_sink_get_position_last (basesink, format, cur);
3854     GST_OBJECT_UNLOCK (basesink);
3855     goto done;
3856   }
3857 in_pause:
3858   {
3859     GST_DEBUG_OBJECT (basesink, "position in PAUSED");
3860     res = gst_base_sink_get_position_paused (basesink, format, cur);
3861     GST_OBJECT_UNLOCK (basesink);
3862     goto done;
3863   }
3864 wrong_state:
3865   {
3866     /* in NULL or READY we always return FALSE and -1 */
3867     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
3868     res = FALSE;
3869     *cur = -1;
3870     GST_OBJECT_UNLOCK (basesink);
3871     goto done;
3872   }
3873 no_sync:
3874   {
3875     /* report last seen timestamp if any, else ask upstream to answer */
3876     if ((*cur = basesink->priv->current_sstart) != -1)
3877       res = TRUE;
3878     else
3879       *upstream = TRUE;
3880
3881     GST_DEBUG_OBJECT (basesink, "no sync, res %d, POSITION %" GST_TIME_FORMAT,
3882         res, GST_TIME_ARGS (*cur));
3883     GST_OBJECT_UNLOCK (basesink);
3884     return res;
3885   }
3886 convert_failed:
3887   {
3888     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
3889     *upstream = TRUE;
3890     return FALSE;
3891   }
3892 }
3893
3894 static gboolean
3895 gst_base_sink_query (GstElement * element, GstQuery * query)
3896 {
3897   gboolean res = FALSE;
3898
3899   GstBaseSink *basesink = GST_BASE_SINK (element);
3900
3901   switch (GST_QUERY_TYPE (query)) {
3902     case GST_QUERY_POSITION:
3903     {
3904       gint64 cur = 0;
3905       GstFormat format;
3906       gboolean upstream = FALSE;
3907
3908       gst_query_parse_position (query, &format, NULL);
3909
3910       GST_DEBUG_OBJECT (basesink, "position format %d", format);
3911
3912       /* first try to get the position based on the clock */
3913       if ((res =
3914               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
3915         gst_query_set_position (query, format, cur);
3916       } else if (upstream) {
3917         /* fallback to peer query */
3918         res = gst_base_sink_peer_query (basesink, query);
3919       }
3920       break;
3921     }
3922     case GST_QUERY_DURATION:
3923     {
3924       GstFormat format, uformat;
3925       gint64 duration, uduration;
3926
3927       gst_query_parse_duration (query, &format, NULL);
3928
3929       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
3930           gst_format_get_name (format));
3931
3932       if (basesink->pad_mode == GST_ACTIVATE_PULL) {
3933         uformat = GST_FORMAT_BYTES;
3934
3935         /* get the duration in bytes, in pull mode that's all we are sure to
3936          * know. We have to explicitly get this value from upstream instead of
3937          * using our cached value because it might change. Duration caching
3938          * should be done at a higher level. */
3939         res = gst_pad_query_peer_duration (basesink->sinkpad, &uformat,
3940             &uduration);
3941         if (res) {
3942           gst_segment_set_duration (&basesink->segment, uformat, uduration);
3943           if (format != uformat) {
3944             /* convert to the requested format */
3945             res = gst_pad_query_convert (basesink->sinkpad, uformat, uduration,
3946                 &format, &duration);
3947           } else {
3948             duration = uduration;
3949           }
3950           if (res) {
3951             /* set the result */
3952             gst_query_set_duration (query, format, duration);
3953           }
3954         }
3955       } else {
3956         /* in push mode we simply forward upstream */
3957         res = gst_base_sink_peer_query (basesink, query);
3958       }
3959       break;
3960     }
3961     case GST_QUERY_LATENCY:
3962     {
3963       gboolean live, us_live;
3964       GstClockTime min, max;
3965
3966       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
3967                   &max))) {
3968         gst_query_set_latency (query, live, min, max);
3969       }
3970       break;
3971     }
3972     case GST_QUERY_JITTER:
3973       break;
3974     case GST_QUERY_RATE:
3975       /* gst_query_set_rate (query, basesink->segment_rate); */
3976       res = TRUE;
3977       break;
3978     case GST_QUERY_SEGMENT:
3979     {
3980       /* FIXME, bring start/stop to stream time */
3981       gst_query_set_segment (query, basesink->segment.rate,
3982           GST_FORMAT_TIME, basesink->segment.start, basesink->segment.stop);
3983       break;
3984     }
3985     case GST_QUERY_SEEKING:
3986     case GST_QUERY_CONVERT:
3987     case GST_QUERY_FORMATS:
3988     default:
3989       res = gst_base_sink_peer_query (basesink, query);
3990       break;
3991   }
3992   return res;
3993 }
3994
3995 static GstStateChangeReturn
3996 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
3997 {
3998   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3999   GstBaseSink *basesink = GST_BASE_SINK (element);
4000   GstBaseSinkClass *bclass;
4001   GstBaseSinkPrivate *priv;
4002
4003   priv = basesink->priv;
4004
4005   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4006
4007   switch (transition) {
4008     case GST_STATE_CHANGE_NULL_TO_READY:
4009       if (bclass->start)
4010         if (!bclass->start (basesink))
4011           goto start_failed;
4012       break;
4013     case GST_STATE_CHANGE_READY_TO_PAUSED:
4014       /* need to complete preroll before this state change completes, there
4015        * is no data flow in READY so we can safely assume we need to preroll. */
4016       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4017       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
4018       basesink->have_newsegment = FALSE;
4019       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
4020       gst_segment_init (basesink->abidata.ABI.clip_segment,
4021           GST_FORMAT_UNDEFINED);
4022       basesink->offset = 0;
4023       basesink->have_preroll = FALSE;
4024       basesink->need_preroll = TRUE;
4025       basesink->playing_async = TRUE;
4026       priv->current_sstart = -1;
4027       priv->current_sstop = -1;
4028       priv->eos_rtime = -1;
4029       priv->latency = 0;
4030       basesink->eos = FALSE;
4031       priv->received_eos = FALSE;
4032       gst_base_sink_reset_qos (basesink);
4033       priv->commited = FALSE;
4034       priv->call_preroll = TRUE;
4035       if (priv->async_enabled) {
4036         GST_DEBUG_OBJECT (basesink, "doing async state change");
4037         /* when async enabled, post async-start message and return ASYNC from
4038          * the state change function */
4039         ret = GST_STATE_CHANGE_ASYNC;
4040         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4041             gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4042       } else {
4043         priv->have_latency = TRUE;
4044       }
4045       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4046       break;
4047     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4048       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4049       if (!gst_base_sink_needs_preroll (basesink)) {
4050         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
4051         /* no preroll needed anymore now. */
4052         basesink->playing_async = FALSE;
4053         basesink->need_preroll = FALSE;
4054         if (basesink->eos) {
4055           GstMessage *message;
4056
4057           /* need to post EOS message here */
4058           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
4059           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
4060           gst_message_set_seqnum (message, basesink->priv->seqnum);
4061           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
4062         } else {
4063           GST_DEBUG_OBJECT (basesink, "signal preroll");
4064           GST_PAD_PREROLL_SIGNAL (basesink->sinkpad);
4065         }
4066       } else {
4067         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
4068         basesink->need_preroll = TRUE;
4069         basesink->playing_async = TRUE;
4070         priv->call_preroll = TRUE;
4071         priv->commited = FALSE;
4072         if (priv->async_enabled) {
4073           GST_DEBUG_OBJECT (basesink, "doing async state change");
4074           ret = GST_STATE_CHANGE_ASYNC;
4075           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4076               gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4077         }
4078       }
4079       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4080       break;
4081     default:
4082       break;
4083   }
4084
4085   {
4086     GstStateChangeReturn bret;
4087
4088     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4089     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
4090       goto activate_failed;
4091   }
4092
4093   switch (transition) {
4094     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4095       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
4096       /* FIXME, make sure we cannot enter _render first */
4097
4098       /* we need to call ::unlock before locking PREROLL_LOCK
4099        * since we lock it before going into ::render */
4100       if (bclass->unlock)
4101         bclass->unlock (basesink);
4102
4103       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4104       /* now that we have the PREROLL lock, clear our unlock request */
4105       if (bclass->unlock_stop)
4106         bclass->unlock_stop (basesink);
4107
4108       /* we need preroll again and we set the flag before unlocking the clockid
4109        * because if the clockid is unlocked before a current buffer expired, we
4110        * can use that buffer to preroll with */
4111       basesink->need_preroll = TRUE;
4112
4113       if (basesink->clock_id) {
4114         gst_clock_id_unschedule (basesink->clock_id);
4115       }
4116
4117       /* if we don't have a preroll buffer we need to wait for a preroll and
4118        * return ASYNC. */
4119       if (!gst_base_sink_needs_preroll (basesink)) {
4120         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
4121         basesink->playing_async = FALSE;
4122       } else {
4123         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
4124           ret = GST_STATE_CHANGE_SUCCESS;
4125         } else {
4126           GST_DEBUG_OBJECT (basesink,
4127               "PLAYING to PAUSED, we are not prerolled");
4128           basesink->playing_async = TRUE;
4129           priv->commited = FALSE;
4130           priv->call_preroll = TRUE;
4131           if (priv->async_enabled) {
4132             GST_DEBUG_OBJECT (basesink, "doing async state change");
4133             ret = GST_STATE_CHANGE_ASYNC;
4134             gst_element_post_message (GST_ELEMENT_CAST (basesink),
4135                 gst_message_new_async_start (GST_OBJECT_CAST (basesink),
4136                     FALSE));
4137           }
4138         }
4139       }
4140       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
4141           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
4142
4143       gst_base_sink_reset_qos (basesink);
4144       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4145       break;
4146     case GST_STATE_CHANGE_PAUSED_TO_READY:
4147       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4148       /* start by reseting our position state with the object lock so that the
4149        * position query gets the right idea. We do this before we post the
4150        * messages so that the message handlers pick this up. */
4151       GST_OBJECT_LOCK (basesink);
4152       basesink->have_newsegment = FALSE;
4153       priv->current_sstart = -1;
4154       priv->current_sstop = -1;
4155       priv->have_latency = FALSE;
4156       GST_OBJECT_UNLOCK (basesink);
4157
4158       gst_base_sink_set_last_buffer (basesink, NULL);
4159       priv->call_preroll = FALSE;
4160
4161       if (!priv->commited) {
4162         if (priv->async_enabled) {
4163           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
4164
4165           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4166               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
4167                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
4168
4169           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4170               gst_message_new_async_done (GST_OBJECT_CAST (basesink)));
4171         }
4172         priv->commited = TRUE;
4173       } else {
4174         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
4175       }
4176       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4177       break;
4178     case GST_STATE_CHANGE_READY_TO_NULL:
4179       if (bclass->stop) {
4180         if (!bclass->stop (basesink)) {
4181           GST_WARNING_OBJECT (basesink, "failed to stop");
4182         }
4183       }
4184       gst_base_sink_set_last_buffer (basesink, NULL);
4185       priv->call_preroll = FALSE;
4186       break;
4187     default:
4188       break;
4189   }
4190
4191   return ret;
4192
4193   /* ERRORS */
4194 start_failed:
4195   {
4196     GST_DEBUG_OBJECT (basesink, "failed to start");
4197     return GST_STATE_CHANGE_FAILURE;
4198   }
4199 activate_failed:
4200   {
4201     GST_DEBUG_OBJECT (basesink,
4202         "element failed to change states -- activation problem?");
4203     return GST_STATE_CHANGE_FAILURE;
4204   }
4205 }