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