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