framestep: implement backwards framestep
[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   GST_DEBUG_OBJECT (sink,
1518       "step stop at running_time %" GST_TIME_FORMAT ", timestamp %"
1519       GST_TIME_FORMAT, GST_TIME_ARGS (*rstart), GST_TIME_ARGS (cstart));
1520
1521   /* configure the duration of the elapsed segment */
1522   if (segment->rate > 0.0)
1523     current->duration = *rstart - current->start;
1524   else
1525     current->duration = *rstop - current->start;
1526
1527   GST_DEBUG_OBJECT (sink, "step elapsed running_time %" GST_TIME_FORMAT,
1528       GST_TIME_ARGS (current->duration));
1529
1530   /* update the segment, discarding what was consumed, running time goes
1531    * backwards with the duration of the data we skipped. FIXME, this only works
1532    * in PAUSED. */
1533   if (segment->rate > 0.0) {
1534     segment->time =
1535         gst_segment_to_stream_time (segment, segment->format, cstart);
1536     segment->start = cstart;
1537
1538     *rstart = current->start;
1539     *rstop -= current->duration;
1540   } else {
1541     segment->stop = cstop;
1542     *rstop = current->start;
1543     *rstart -= current->duration;
1544   }
1545   segment->accum = current->start;
1546
1547   /* the clip segment is used for position report in paused... */
1548   memcpy (sink->abidata.ABI.clip_segment, segment, sizeof (GstSegment));
1549
1550   message =
1551       gst_message_new_step_done (GST_OBJECT_CAST (sink), current->format,
1552       current->amount, current->rate, current->flush, current->intermediate,
1553       current->duration);
1554   gst_message_set_seqnum (message, current->seqnum);
1555   gst_element_post_message (GST_ELEMENT_CAST (sink), message);
1556
1557   if (!current->intermediate)
1558     sink->need_preroll = current->need_preroll;
1559
1560   /* and the current step info finished and becomes invalid */
1561   current->valid = FALSE;
1562 }
1563
1564 static gboolean
1565 handle_stepping (GstBaseSink * sink, GstSegment * segment,
1566     GstStepInfo * current, gint64 * cstart, gint64 * cstop, gint64 * rstart,
1567     gint64 * rstop)
1568 {
1569   GstBaseSinkPrivate *priv;
1570   gboolean step_end = FALSE;
1571
1572   priv = sink->priv;
1573
1574   /* see if we need to skip this buffer because of stepping */
1575   switch (current->format) {
1576     case GST_FORMAT_TIME:
1577     {
1578       guint64 end;
1579
1580       end = current->start + current->amount;
1581
1582       current->position = *rstart - current->start;
1583
1584       GST_DEBUG_OBJECT (sink,
1585           "got time step %" GST_TIME_FORMAT "/%" GST_TIME_FORMAT,
1586           GST_TIME_ARGS (current->position), GST_TIME_ARGS (current->amount));
1587
1588       if (current->position >= current->amount || *rstop >= end) {
1589         step_end = TRUE;
1590         *cstart += end - *rstart;
1591         *rstart = end;
1592       }
1593       break;
1594     }
1595     case GST_FORMAT_BUFFERS:
1596       GST_DEBUG_OBJECT (sink,
1597           "got default step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1598           current->position, current->amount);
1599
1600       if (current->position < current->amount) {
1601         current->position++;
1602       } else {
1603         step_end = TRUE;
1604       }
1605       break;
1606     case GST_FORMAT_DEFAULT:
1607     default:
1608       GST_DEBUG_OBJECT (sink,
1609           "got unknown step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1610           current->position, current->amount);
1611       break;
1612   }
1613   return step_end;
1614 }
1615
1616 /* with STREAM_LOCK, PREROLL_LOCK
1617  *
1618  * Returns TRUE if the object needs synchronisation and takes therefore
1619  * part in prerolling.
1620  *
1621  * rsstart/rsstop contain the start/stop in stream time.
1622  * rrstart/rrstop contain the start/stop in running time.
1623  */
1624 static gboolean
1625 gst_base_sink_get_sync_times (GstBaseSink * basesink, GstMiniObject * obj,
1626     GstClockTime * rsstart, GstClockTime * rsstop,
1627     GstClockTime * rrstart, GstClockTime * rrstop, gboolean * do_sync,
1628     gboolean * stepped, GstSegment * segment, GstStepInfo * step)
1629 {
1630   GstBaseSinkClass *bclass;
1631   GstBuffer *buffer;
1632   GstClockTime start, stop;     /* raw start/stop timestamps */
1633   gint64 cstart, cstop;         /* clipped raw timestamps */
1634   gint64 rstart, rstop;         /* clipped timestamps converted to running time */
1635   GstClockTime sstart, sstop;   /* clipped timestamps converted to stream time */
1636   GstFormat format;
1637   GstBaseSinkPrivate *priv;
1638   gboolean step_end;
1639
1640   priv = basesink->priv;
1641
1642   /* start with nothing */
1643   start = stop = -1;
1644
1645   step_end = FALSE;
1646
1647   if (G_UNLIKELY (GST_IS_EVENT (obj))) {
1648     GstEvent *event = GST_EVENT_CAST (obj);
1649
1650     switch (GST_EVENT_TYPE (event)) {
1651         /* EOS event needs syncing */
1652       case GST_EVENT_EOS:
1653       {
1654         if (basesink->segment.rate >= 0.0) {
1655           sstart = sstop = priv->current_sstop;
1656           if (sstart == -1) {
1657             /* we have not seen a buffer yet, use the segment values */
1658             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1659                 basesink->segment.format, basesink->segment.stop);
1660           }
1661         } else {
1662           sstart = sstop = priv->current_sstart;
1663           if (sstart == -1) {
1664             /* we have not seen a buffer yet, use the segment values */
1665             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1666                 basesink->segment.format, basesink->segment.start);
1667           }
1668         }
1669
1670         rstart = rstop = priv->eos_rtime;
1671         *do_sync = rstart != -1;
1672         GST_DEBUG_OBJECT (basesink, "sync times for EOS %" GST_TIME_FORMAT,
1673             GST_TIME_ARGS (rstart));
1674         /* if we are stepping, we end now */
1675         step_end = step->valid;
1676         goto eos_done;
1677       }
1678       default:
1679         /* other events do not need syncing */
1680         /* FIXME, maybe NEWSEGMENT might need synchronisation
1681          * since the POSITION query depends on accumulated times and
1682          * we cannot accumulate the current segment before the previous
1683          * one completed.
1684          */
1685         return FALSE;
1686     }
1687   }
1688
1689   /* else do buffer sync code */
1690   buffer = GST_BUFFER_CAST (obj);
1691
1692   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1693
1694   /* just get the times to see if we need syncing, if the start returns -1 we
1695    * don't sync. */
1696   if (bclass->get_times)
1697     bclass->get_times (basesink, buffer, &start, &stop);
1698
1699   if (start == -1) {
1700     /* we don't need to sync but we still want to get the timestamps for
1701      * tracking the position */
1702     gst_base_sink_get_times (basesink, buffer, &start, &stop);
1703     *do_sync = FALSE;
1704   } else {
1705     *do_sync = TRUE;
1706   }
1707
1708   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
1709       ", stop: %" GST_TIME_FORMAT ", do_sync %d", GST_TIME_ARGS (start),
1710       GST_TIME_ARGS (stop), *do_sync);
1711
1712   /* collect segment and format for code clarity */
1713   format = segment->format;
1714
1715   /* no timestamp clipping if we did not get a TIME segment format */
1716   if (G_UNLIKELY (format != GST_FORMAT_TIME)) {
1717     cstart = start;
1718     cstop = stop;
1719     /* do running and stream time in TIME format */
1720     format = GST_FORMAT_TIME;
1721     goto do_times;
1722   }
1723
1724   /* clip, only when we know about time */
1725   if (G_UNLIKELY (!gst_segment_clip (segment, GST_FORMAT_TIME,
1726               (gint64) start, (gint64) stop, &cstart, &cstop)))
1727     goto out_of_segment;
1728
1729   if (G_UNLIKELY (start != cstart || stop != cstop)) {
1730     GST_DEBUG_OBJECT (basesink, "clipped to: start %" GST_TIME_FORMAT
1731         ", stop: %" GST_TIME_FORMAT, GST_TIME_ARGS (cstart),
1732         GST_TIME_ARGS (cstop));
1733   }
1734
1735   /* set last stop position */
1736   if (G_LIKELY (cstop != GST_CLOCK_TIME_NONE))
1737     gst_segment_set_last_stop (segment, GST_FORMAT_TIME, cstop);
1738   else
1739     gst_segment_set_last_stop (segment, GST_FORMAT_TIME, cstart);
1740
1741 do_times:
1742   /* this can produce wrong values if we accumulated non-TIME segments. If this happens,
1743    * upstream is behaving very badly */
1744   sstart = gst_segment_to_stream_time (segment, format, cstart);
1745   sstop = gst_segment_to_stream_time (segment, format, cstop);
1746   rstart = gst_segment_to_running_time (segment, format, cstart);
1747   rstop = gst_segment_to_running_time (segment, format, cstop);
1748
1749   if (G_UNLIKELY (step->valid)) {
1750     if (!(step_end = handle_stepping (basesink, segment, step, &cstart, &cstop,
1751                 &rstart, &rstop)))
1752       *stepped = TRUE;
1753   }
1754
1755 eos_done:
1756   /* done label only called when doing EOS, we also stop stepping then */
1757   if (step_end)
1758     stop_stepping (basesink, segment, step, cstart, cstop, &rstart, &rstop);
1759
1760   /* save times */
1761   *rsstart = sstart;
1762   *rsstop = sstop;
1763   *rrstart = rstart;
1764   *rrstop = rstop;
1765
1766   /* buffers and EOS always need syncing and preroll */
1767   return TRUE;
1768
1769   /* special cases */
1770 out_of_segment:
1771   {
1772     /* should not happen since we clip them in the chain function already, 
1773      * we return FALSE so that we don't try to sync on it. */
1774     GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
1775         (NULL), ("unexpected buffer out of segment found."));
1776     GST_LOG_OBJECT (basesink, "buffer skipped, not in segment");
1777     return FALSE;
1778   }
1779 }
1780
1781 /* with STREAM_LOCK, PREROLL_LOCK, LOCK
1782  * adjust a timestamp with the latency and timestamp offset */
1783 static GstClockTime
1784 gst_base_sink_adjust_time (GstBaseSink * basesink, GstClockTime time)
1785 {
1786   GstClockTimeDiff ts_offset;
1787
1788   /* don't do anything funny with invalid timestamps */
1789   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1790     return time;
1791
1792   time += basesink->priv->latency;
1793
1794   /* apply offset, be carefull for underflows */
1795   ts_offset = basesink->priv->ts_offset;
1796   if (ts_offset < 0) {
1797     ts_offset = -ts_offset;
1798     if (ts_offset < time)
1799       time -= ts_offset;
1800     else
1801       time = 0;
1802   } else
1803     time += ts_offset;
1804
1805   return time;
1806 }
1807
1808 /**
1809  * gst_base_sink_wait_clock:
1810  * @sink: the sink
1811  * @time: the running_time to be reached
1812  * @jitter: the jitter to be filled with time diff (can be NULL)
1813  *
1814  * This function will block until @time is reached. It is usually called by
1815  * subclasses that use their own internal synchronisation.
1816  *
1817  * If @time is not valid, no sycnhronisation is done and #GST_CLOCK_BADTIME is
1818  * returned. Likewise, if synchronisation is disabled in the element or there
1819  * is no clock, no synchronisation is done and #GST_CLOCK_BADTIME is returned.
1820  *
1821  * This function should only be called with the PREROLL_LOCK held, like when
1822  * receiving an EOS event in the ::event vmethod or when receiving a buffer in
1823  * the ::render vmethod.
1824  *
1825  * The @time argument should be the running_time of when this method should
1826  * return and is not adjusted with any latency or offset configured in the
1827  * sink.
1828  *
1829  * Since 0.10.20
1830  *
1831  * Returns: #GstClockReturn
1832  */
1833 GstClockReturn
1834 gst_base_sink_wait_clock (GstBaseSink * sink, GstClockTime time,
1835     GstClockTimeDiff * jitter)
1836 {
1837   GstClockID id;
1838   GstClockReturn ret;
1839   GstClock *clock;
1840
1841   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1842     goto invalid_time;
1843
1844   GST_OBJECT_LOCK (sink);
1845   if (G_UNLIKELY (!sink->sync))
1846     goto no_sync;
1847
1848   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (sink)) == NULL))
1849     goto no_clock;
1850
1851   /* add base_time to running_time to get the time against the clock */
1852   time += GST_ELEMENT_CAST (sink)->base_time;
1853
1854   id = gst_clock_new_single_shot_id (clock, time);
1855   GST_OBJECT_UNLOCK (sink);
1856
1857   /* A blocking wait is performed on the clock. We save the ClockID
1858    * so we can unlock the entry at any time. While we are blocking, we 
1859    * release the PREROLL_LOCK so that other threads can interrupt the
1860    * entry. */
1861   sink->clock_id = id;
1862   /* release the preroll lock while waiting */
1863   GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
1864
1865   ret = gst_clock_id_wait (id, jitter);
1866
1867   GST_PAD_PREROLL_LOCK (sink->sinkpad);
1868   gst_clock_id_unref (id);
1869   sink->clock_id = NULL;
1870
1871   return ret;
1872
1873   /* no syncing needed */
1874 invalid_time:
1875   {
1876     GST_DEBUG_OBJECT (sink, "time not valid, no sync needed");
1877     return GST_CLOCK_BADTIME;
1878   }
1879 no_sync:
1880   {
1881     GST_DEBUG_OBJECT (sink, "sync disabled");
1882     GST_OBJECT_UNLOCK (sink);
1883     return GST_CLOCK_BADTIME;
1884   }
1885 no_clock:
1886   {
1887     GST_DEBUG_OBJECT (sink, "no clock, can't sync");
1888     GST_OBJECT_UNLOCK (sink);
1889     return GST_CLOCK_BADTIME;
1890   }
1891 }
1892
1893 /**
1894  * gst_base_sink_wait_preroll:
1895  * @sink: the sink
1896  *
1897  * If the #GstBaseSinkClass::render method performs its own synchronisation against
1898  * the clock it must unblock when going from PLAYING to the PAUSED state and call
1899  * this method before continuing to render the remaining data.
1900  *
1901  * This function will block until a state change to PLAYING happens (in which
1902  * case this function returns #GST_FLOW_OK) or the processing must be stopped due
1903  * to a state change to READY or a FLUSH event (in which case this function
1904  * returns #GST_FLOW_WRONG_STATE).
1905  *
1906  * This function should only be called with the PREROLL_LOCK held, like in the
1907  * render function.
1908  *
1909  * Since: 0.10.11
1910  *
1911  * Returns: #GST_FLOW_OK if the preroll completed and processing can
1912  * continue. Any other return value should be returned from the render vmethod.
1913  */
1914 GstFlowReturn
1915 gst_base_sink_wait_preroll (GstBaseSink * sink)
1916 {
1917   sink->have_preroll = TRUE;
1918   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
1919   /* block until the state changes, or we get a flush, or something */
1920   GST_PAD_PREROLL_WAIT (sink->sinkpad);
1921   sink->have_preroll = FALSE;
1922   if (G_UNLIKELY (sink->flushing))
1923     goto stopping;
1924   GST_DEBUG_OBJECT (sink, "continue after preroll");
1925
1926   return GST_FLOW_OK;
1927
1928   /* ERRORS */
1929 stopping:
1930   {
1931     GST_DEBUG_OBJECT (sink, "preroll interrupted");
1932     return GST_FLOW_WRONG_STATE;
1933   }
1934 }
1935
1936 /**
1937  * gst_base_sink_do_preroll:
1938  * @sink: the sink
1939  * @obj: the object that caused the preroll
1940  *
1941  * If the @sink spawns its own thread for pulling buffers from upstream it
1942  * should call this method after it has pulled a buffer. If the element needed
1943  * to preroll, this function will perform the preroll and will then block
1944  * until the element state is changed.
1945  *
1946  * This function should be called with the PREROLL_LOCK held.
1947  *
1948  * Since 0.10.22
1949  *
1950  * Returns: #GST_FLOW_OK if the preroll completed and processing can
1951  * continue. Any other return value should be returned from the render vmethod.
1952  */
1953 GstFlowReturn
1954 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
1955 {
1956   GstFlowReturn ret;
1957
1958   while (G_UNLIKELY (sink->need_preroll)) {
1959     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
1960
1961     ret = gst_base_sink_preroll_object (sink, obj);
1962     if (ret != GST_FLOW_OK)
1963       goto preroll_failed;
1964
1965     /* need to recheck here because the commit state could have
1966      * made us not need the preroll anymore */
1967     if (G_LIKELY (sink->need_preroll)) {
1968       /* block until the state changes, or we get a flush, or something */
1969       ret = gst_base_sink_wait_preroll (sink);
1970       if (ret != GST_FLOW_OK)
1971         goto preroll_failed;
1972     }
1973   }
1974   return GST_FLOW_OK;
1975
1976   /* ERRORS */
1977 preroll_failed:
1978   {
1979     GST_DEBUG_OBJECT (sink, "preroll failed %d", ret);
1980     return ret;
1981   }
1982 }
1983
1984 /**
1985  * gst_base_sink_wait_eos:
1986  * @sink: the sink
1987  * @time: the running_time to be reached
1988  * @jitter: the jitter to be filled with time diff (can be NULL)
1989  *
1990  * This function will block until @time is reached. It is usually called by
1991  * subclasses that use their own internal synchronisation but want to let the
1992  * EOS be handled by the base class.
1993  *
1994  * This function should only be called with the PREROLL_LOCK held, like when
1995  * receiving an EOS event in the ::event vmethod.
1996  *
1997  * The @time argument should be the running_time of when the EOS should happen
1998  * and will be adjusted with any latency and offset configured in the sink.
1999  *
2000  * Since 0.10.15
2001  *
2002  * Returns: #GstFlowReturn
2003  */
2004 GstFlowReturn
2005 gst_base_sink_wait_eos (GstBaseSink * sink, GstClockTime time,
2006     GstClockTimeDiff * jitter)
2007 {
2008   GstClockReturn status;
2009   GstFlowReturn ret;
2010
2011   do {
2012     GstClockTime stime;
2013
2014     GST_DEBUG_OBJECT (sink, "checking preroll");
2015
2016     /* first wait for the playing state before we can continue */
2017     if (G_UNLIKELY (sink->need_preroll)) {
2018       ret = gst_base_sink_wait_preroll (sink);
2019       if (ret != GST_FLOW_OK)
2020         goto flushing;
2021     }
2022
2023     /* preroll done, we can sync since we are in PLAYING now. */
2024     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
2025         GST_TIME_FORMAT, GST_TIME_ARGS (time));
2026
2027     /* compensate for latency and ts_offset. We don't adjust for render delay
2028      * because we don't interact with the device on EOS normally. */
2029     stime = gst_base_sink_adjust_time (sink, time);
2030
2031     /* wait for the clock, this can be interrupted because we got shut down or 
2032      * we PAUSED. */
2033     status = gst_base_sink_wait_clock (sink, stime, jitter);
2034
2035     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
2036
2037     /* invalid time, no clock or sync disabled, just continue then */
2038     if (status == GST_CLOCK_BADTIME)
2039       break;
2040
2041     /* waiting could have been interrupted and we can be flushing now */
2042     if (G_UNLIKELY (sink->flushing))
2043       goto flushing;
2044
2045     /* retry if we got unscheduled, which means we did not reach the timeout
2046      * yet. if some other error occures, we continue. */
2047   } while (status == GST_CLOCK_UNSCHEDULED);
2048
2049   GST_DEBUG_OBJECT (sink, "end of stream");
2050
2051   return GST_FLOW_OK;
2052
2053   /* ERRORS */
2054 flushing:
2055   {
2056     GST_DEBUG_OBJECT (sink, "we are flushing");
2057     return GST_FLOW_WRONG_STATE;
2058   }
2059 }
2060
2061 /* with STREAM_LOCK, PREROLL_LOCK
2062  *
2063  * Make sure we are in PLAYING and synchronize an object to the clock.
2064  *
2065  * If we need preroll, we are not in PLAYING. We try to commit the state
2066  * if needed and then block if we still are not PLAYING.
2067  *
2068  * We start waiting on the clock in PLAYING. If we got interrupted, we
2069  * immediatly try to re-preroll.
2070  *
2071  * Some objects do not need synchronisation (most events) and so this function
2072  * immediatly returns GST_FLOW_OK.
2073  *
2074  * for objects that arrive later than max-lateness to be synchronized to the 
2075  * clock have the @late boolean set to TRUE.
2076  *
2077  * This function keeps a running average of the jitter (the diff between the
2078  * clock time and the requested sync time). The jitter is negative for
2079  * objects that arrive in time and positive for late buffers.
2080  *
2081  * does not take ownership of obj.
2082  */
2083 static GstFlowReturn
2084 gst_base_sink_do_sync (GstBaseSink * basesink, GstPad * pad,
2085     GstMiniObject * obj, gboolean * late)
2086 {
2087   GstClockTimeDiff jitter;
2088   gboolean syncable;
2089   GstClockReturn status = GST_CLOCK_OK;
2090   GstClockTime rstart, rstop, sstart, sstop, stime;
2091   gboolean do_sync;
2092   GstBaseSinkPrivate *priv;
2093   GstFlowReturn ret;
2094   GstStepInfo *current, *pending;
2095   gboolean stepped;
2096
2097   priv = basesink->priv;
2098
2099 do_step:
2100   sstart = sstop = rstart = rstop = -1;
2101   do_sync = TRUE;
2102   stepped = FALSE;
2103
2104   priv->current_rstart = -1;
2105
2106   /* get stepping info */
2107   current = &priv->current_step;
2108   pending = &priv->pending_step;
2109
2110   /* get timing information for this object against the render segment */
2111   syncable = gst_base_sink_get_sync_times (basesink, obj,
2112       &sstart, &sstop, &rstart, &rstop, &do_sync, &stepped, &basesink->segment,
2113       current);
2114
2115   if (G_UNLIKELY (stepped))
2116     goto step_skipped;
2117
2118   /* a syncable object needs to participate in preroll and
2119    * clocking. All buffers and EOS are syncable. */
2120   if (G_UNLIKELY (!syncable))
2121     goto not_syncable;
2122
2123   /* store timing info for current object */
2124   priv->current_rstart = rstart;
2125   priv->current_rstop = (rstop != -1 ? rstop : rstart);
2126
2127   /* save sync time for eos when the previous object needed sync */
2128   priv->eos_rtime = (do_sync ? priv->current_rstop : -1);
2129
2130 again:
2131   /* first do preroll, this makes sure we commit our state
2132    * to PAUSED and can continue to PLAYING. We cannot perform
2133    * any clock sync in PAUSED because there is no clock. */
2134   ret = gst_base_sink_do_preroll (basesink, obj);
2135   if (G_UNLIKELY (ret != GST_FLOW_OK))
2136     goto preroll_failed;
2137
2138   /* update the segment with a pending step if the current one is invalid and we
2139    * have a new pending one. We only accept new step updates after a preroll */
2140   if (G_UNLIKELY (pending->valid && !current->valid)) {
2141     start_stepping (basesink, &basesink->segment, pending, current);
2142     goto do_step;
2143   }
2144
2145   /* After rendering we store the position of the last buffer so that we can use
2146    * it to report the position. We need to take the lock here. */
2147   GST_OBJECT_LOCK (basesink);
2148   priv->current_sstart = sstart;
2149   priv->current_sstop = (sstop != -1 ? sstop : sstart);
2150   GST_OBJECT_UNLOCK (basesink);
2151
2152   if (!do_sync)
2153     goto done;
2154
2155   /* adjust for latency */
2156   stime = gst_base_sink_adjust_time (basesink, rstart);
2157
2158   /* adjust for render-delay, avoid underflows */
2159   if (stime != -1) {
2160     if (stime > priv->render_delay)
2161       stime -= priv->render_delay;
2162     else
2163       stime = 0;
2164   }
2165
2166   /* preroll done, we can sync since we are in PLAYING now. */
2167   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
2168       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
2169       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
2170
2171   /* This function will return immediatly if start == -1, no clock
2172    * or sync is disabled with GST_CLOCK_BADTIME. */
2173   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
2174
2175   GST_DEBUG_OBJECT (basesink, "clock returned %d", status);
2176
2177   /* invalid time, no clock or sync disabled, just render */
2178   if (status == GST_CLOCK_BADTIME)
2179     goto done;
2180
2181   /* waiting could have been interrupted and we can be flushing now */
2182   if (G_UNLIKELY (basesink->flushing))
2183     goto flushing;
2184
2185   /* check for unlocked by a state change, we are not flushing so
2186    * we can try to preroll on the current buffer. */
2187   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
2188     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
2189     priv->call_preroll = TRUE;
2190     goto again;
2191   }
2192
2193   /* successful syncing done, record observation */
2194   priv->current_jitter = jitter;
2195
2196   /* check if the object should be dropped */
2197   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
2198       status, jitter);
2199
2200 done:
2201   return GST_FLOW_OK;
2202
2203   /* ERRORS */
2204 step_skipped:
2205   {
2206     GST_DEBUG_OBJECT (basesink, "skipped stepped object %p", obj);
2207     *late = TRUE;
2208     return GST_FLOW_OK;
2209   }
2210 not_syncable:
2211   {
2212     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2213     return GST_FLOW_OK;
2214   }
2215 flushing:
2216   {
2217     GST_DEBUG_OBJECT (basesink, "we are flushing");
2218     return GST_FLOW_WRONG_STATE;
2219   }
2220 preroll_failed:
2221   {
2222     GST_DEBUG_OBJECT (basesink, "preroll failed");
2223     return ret;
2224   }
2225 }
2226
2227 static gboolean
2228 gst_base_sink_send_qos (GstBaseSink * basesink,
2229     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2230 {
2231   GstEvent *event;
2232   gboolean res;
2233
2234   /* generate Quality-of-Service event */
2235   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2236       "qos: proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2237       GST_TIME_FORMAT, proportion, diff, GST_TIME_ARGS (time));
2238
2239   event = gst_event_new_qos (proportion, diff, time);
2240
2241   /* send upstream */
2242   res = gst_pad_push_event (basesink->sinkpad, event);
2243
2244   return res;
2245 }
2246
2247 static void
2248 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2249 {
2250   GstBaseSinkPrivate *priv;
2251   GstClockTime start, stop;
2252   GstClockTimeDiff jitter;
2253   GstClockTime pt, entered, left;
2254   GstClockTime duration;
2255   gdouble rate;
2256
2257   priv = sink->priv;
2258
2259   start = priv->current_rstart;
2260
2261   /* if Quality-of-Service disabled, do nothing */
2262   if (!g_atomic_int_get (&priv->qos_enabled) || start == -1)
2263     return;
2264
2265   stop = priv->current_rstop;
2266   jitter = priv->current_jitter;
2267
2268   if (jitter < 0) {
2269     /* this is the time the buffer entered the sink */
2270     if (start < -jitter)
2271       entered = 0;
2272     else
2273       entered = start + jitter;
2274     left = start;
2275   } else {
2276     /* this is the time the buffer entered the sink */
2277     entered = start + jitter;
2278     /* this is the time the buffer left the sink */
2279     left = start + jitter;
2280   }
2281
2282   /* calculate duration of the buffer */
2283   if (stop != -1)
2284     duration = stop - start;
2285   else
2286     duration = -1;
2287
2288   /* if we have the time when the last buffer left us, calculate
2289    * processing time */
2290   if (priv->last_left != -1) {
2291     if (entered > priv->last_left) {
2292       pt = entered - priv->last_left;
2293     } else {
2294       pt = 0;
2295     }
2296   } else {
2297     pt = priv->avg_pt;
2298   }
2299
2300   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2301       ", entered %" GST_TIME_FORMAT ", left %" GST_TIME_FORMAT ", pt: %"
2302       GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT ",jitter %"
2303       G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (entered),
2304       GST_TIME_ARGS (left), GST_TIME_ARGS (pt), GST_TIME_ARGS (duration),
2305       jitter);
2306
2307   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "avg_duration: %" GST_TIME_FORMAT
2308       ", avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2309       GST_TIME_ARGS (priv->avg_duration), GST_TIME_ARGS (priv->avg_pt),
2310       priv->avg_rate);
2311
2312   /* collect running averages. for first observations, we copy the
2313    * values */
2314   if (priv->avg_duration == -1)
2315     priv->avg_duration = duration;
2316   else
2317     priv->avg_duration = UPDATE_RUNNING_AVG (priv->avg_duration, duration);
2318
2319   if (priv->avg_pt == -1)
2320     priv->avg_pt = pt;
2321   else
2322     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2323
2324   if (priv->avg_duration != 0)
2325     rate =
2326         gst_guint64_to_gdouble (priv->avg_pt) /
2327         gst_guint64_to_gdouble (priv->avg_duration);
2328   else
2329     rate = 0.0;
2330
2331   if (priv->last_left != -1) {
2332     if (dropped || priv->avg_rate < 0.0) {
2333       priv->avg_rate = rate;
2334     } else {
2335       if (rate > 1.0)
2336         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2337       else
2338         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2339     }
2340   }
2341
2342   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2343       "updated: avg_duration: %" GST_TIME_FORMAT ", avg_pt: %" GST_TIME_FORMAT
2344       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_duration),
2345       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2346
2347
2348   if (priv->avg_rate >= 0.0) {
2349     /* if we have a valid rate, start sending QoS messages */
2350     if (priv->current_jitter < 0) {
2351       /* make sure we never go below 0 when adding the jitter to the
2352        * timestamp. */
2353       if (priv->current_rstart < -priv->current_jitter)
2354         priv->current_jitter = -priv->current_rstart;
2355     }
2356     gst_base_sink_send_qos (sink, priv->avg_rate, priv->current_rstart,
2357         priv->current_jitter);
2358   }
2359
2360   /* record when this buffer will leave us */
2361   priv->last_left = left;
2362 }
2363
2364 /* reset all qos measuring */
2365 static void
2366 gst_base_sink_reset_qos (GstBaseSink * sink)
2367 {
2368   GstBaseSinkPrivate *priv;
2369
2370   priv = sink->priv;
2371
2372   priv->last_in_time = -1;
2373   priv->last_left = -1;
2374   priv->avg_duration = -1;
2375   priv->avg_pt = -1;
2376   priv->avg_rate = -1.0;
2377   priv->avg_render = -1;
2378   priv->rendered = 0;
2379   priv->dropped = 0;
2380
2381 }
2382
2383 /* Checks if the object was scheduled too late.
2384  *
2385  * start/stop contain the raw timestamp start and stop values
2386  * of the object.
2387  *
2388  * status and jitter contain the return values from the clock wait.
2389  *
2390  * returns TRUE if the buffer was too late.
2391  */
2392 static gboolean
2393 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2394     GstClockTime start, GstClockTime stop,
2395     GstClockReturn status, GstClockTimeDiff jitter)
2396 {
2397   gboolean late;
2398   gint64 max_lateness;
2399   GstBaseSinkPrivate *priv;
2400
2401   priv = basesink->priv;
2402
2403   late = FALSE;
2404
2405   /* only for objects that were too late */
2406   if (G_LIKELY (status != GST_CLOCK_EARLY))
2407     goto in_time;
2408
2409   max_lateness = basesink->abidata.ABI.max_lateness;
2410
2411   /* check if frame dropping is enabled */
2412   if (max_lateness == -1)
2413     goto no_drop;
2414
2415   /* only check for buffers */
2416   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2417     goto not_buffer;
2418
2419   /* can't do check if we don't have a timestamp */
2420   if (G_UNLIKELY (start == -1))
2421     goto no_timestamp;
2422
2423   /* we can add a valid stop time */
2424   if (stop != -1)
2425     max_lateness += stop;
2426   else
2427     max_lateness += start;
2428
2429   /* if the jitter bigger than duration and lateness we are too late */
2430   if ((late = start + jitter > max_lateness)) {
2431     GST_DEBUG_OBJECT (basesink, "buffer is too late %" GST_TIME_FORMAT
2432         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (start + jitter),
2433         GST_TIME_ARGS (max_lateness));
2434     /* !!emergency!!, if we did not receive anything valid for more than a 
2435      * second, render it anyway so the user sees something */
2436     if (priv->last_in_time != -1 && start - priv->last_in_time > GST_SECOND) {
2437       late = FALSE;
2438       GST_DEBUG_OBJECT (basesink,
2439           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
2440           GST_TIME_ARGS (priv->last_in_time));
2441     }
2442   }
2443
2444 done:
2445   if (!late) {
2446     priv->last_in_time = start;
2447   }
2448   return late;
2449
2450   /* all is fine */
2451 in_time:
2452   {
2453     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
2454     goto done;
2455   }
2456 no_drop:
2457   {
2458     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
2459     goto done;
2460   }
2461 not_buffer:
2462   {
2463     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
2464     return FALSE;
2465   }
2466 no_timestamp:
2467   {
2468     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
2469     return FALSE;
2470   }
2471 }
2472
2473 /* called before and after calling the render vmethod. It keeps track of how
2474  * much time was spent in the render method and is used to check if we are
2475  * flooded */
2476 static void
2477 gst_base_sink_do_render_stats (GstBaseSink * basesink, gboolean start)
2478 {
2479   GstBaseSinkPrivate *priv;
2480
2481   priv = basesink->priv;
2482
2483   if (start) {
2484     priv->start = gst_util_get_timestamp ();
2485   } else {
2486     GstClockTime elapsed;
2487
2488     priv->stop = gst_util_get_timestamp ();
2489
2490     elapsed = GST_CLOCK_DIFF (priv->start, priv->stop);
2491
2492     if (priv->avg_render == -1)
2493       priv->avg_render = elapsed;
2494     else
2495       priv->avg_render = UPDATE_RUNNING_AVG (priv->avg_render, elapsed);
2496
2497     GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2498         "avg_render: %" GST_TIME_FORMAT, GST_TIME_ARGS (priv->avg_render));
2499   }
2500 }
2501
2502 /* with STREAM_LOCK, PREROLL_LOCK,
2503  *
2504  * Synchronize the object on the clock and then render it.
2505  *
2506  * takes ownership of obj.
2507  */
2508 static GstFlowReturn
2509 gst_base_sink_render_object (GstBaseSink * basesink, GstPad * pad,
2510     GstMiniObject * obj)
2511 {
2512   GstFlowReturn ret = GST_FLOW_OK;
2513   GstBaseSinkClass *bclass;
2514   gboolean late = FALSE;
2515   GstBaseSinkPrivate *priv;
2516
2517   priv = basesink->priv;
2518
2519   /* synchronize this object, non syncable objects return OK
2520    * immediatly. */
2521   ret = gst_base_sink_do_sync (basesink, pad, obj, &late);
2522   if (G_UNLIKELY (ret != GST_FLOW_OK))
2523     goto sync_failed;
2524
2525   /* and now render, event or buffer. */
2526   if (G_LIKELY (GST_IS_BUFFER (obj))) {
2527     GstBuffer *buf;
2528
2529     /* drop late buffers unconditionally, let's hope it's unlikely */
2530     if (G_UNLIKELY (late))
2531       goto dropped;
2532
2533     buf = GST_BUFFER_CAST (obj);
2534
2535     gst_base_sink_set_last_buffer (basesink, buf);
2536
2537     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2538
2539     if (G_LIKELY (bclass->render)) {
2540       gint do_qos;
2541
2542       /* read once, to get same value before and after */
2543       do_qos = g_atomic_int_get (&priv->qos_enabled);
2544
2545       GST_DEBUG_OBJECT (basesink, "rendering buffer %p", obj);
2546
2547       /* record rendering time for QoS and stats */
2548       if (do_qos)
2549         gst_base_sink_do_render_stats (basesink, TRUE);
2550
2551       ret = bclass->render (basesink, buf);
2552
2553       priv->rendered++;
2554
2555       if (do_qos)
2556         gst_base_sink_do_render_stats (basesink, FALSE);
2557     }
2558   } else {
2559     GstEvent *event = GST_EVENT_CAST (obj);
2560     gboolean event_res = TRUE;
2561     GstEventType type;
2562
2563     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2564
2565     type = GST_EVENT_TYPE (event);
2566
2567     GST_DEBUG_OBJECT (basesink, "rendering event %p, type %s", obj,
2568         gst_event_type_get_name (type));
2569
2570     if (bclass->event)
2571       event_res = bclass->event (basesink, event);
2572
2573     /* when we get here we could be flushing again when the event handler calls
2574      * _wait_eos(). We have to ignore this object in that case. */
2575     if (G_UNLIKELY (basesink->flushing))
2576       goto flushing;
2577
2578     if (G_LIKELY (event_res)) {
2579       guint32 seqnum;
2580
2581       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
2582       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
2583
2584       switch (type) {
2585         case GST_EVENT_EOS:
2586         {
2587           GstMessage *message;
2588
2589           /* the EOS event is completely handled so we mark
2590            * ourselves as being in the EOS state. eos is also 
2591            * protected by the object lock so we can read it when 
2592            * answering the POSITION query. */
2593           GST_OBJECT_LOCK (basesink);
2594           basesink->eos = TRUE;
2595           GST_OBJECT_UNLOCK (basesink);
2596
2597           /* ok, now we can post the message */
2598           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
2599
2600           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
2601           gst_message_set_seqnum (message, seqnum);
2602           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
2603           break;
2604         }
2605         case GST_EVENT_NEWSEGMENT:
2606           /* configure the segment */
2607           gst_base_sink_configure_segment (basesink, pad, event,
2608               &basesink->segment);
2609           break;
2610         default:
2611           break;
2612       }
2613     }
2614   }
2615
2616 done:
2617   gst_base_sink_perform_qos (basesink, late);
2618
2619   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
2620   gst_mini_object_unref (obj);
2621
2622   return ret;
2623
2624   /* ERRORS */
2625 sync_failed:
2626   {
2627     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
2628     goto done;
2629   }
2630 dropped:
2631   {
2632     priv->dropped++;
2633     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
2634     goto done;
2635   }
2636 flushing:
2637   {
2638     GST_DEBUG_OBJECT (basesink, "we are flushing, ignore object");
2639     gst_mini_object_unref (obj);
2640     return GST_FLOW_WRONG_STATE;
2641   }
2642 }
2643
2644 /* with STREAM_LOCK, PREROLL_LOCK
2645  *
2646  * Perform preroll on the given object. For buffers this means 
2647  * calling the preroll subclass method. 
2648  * If that succeeds, the state will be commited.
2649  *
2650  * function does not take ownership of obj.
2651  */
2652 static GstFlowReturn
2653 gst_base_sink_preroll_object (GstBaseSink * basesink, GstMiniObject * obj)
2654 {
2655   GstFlowReturn ret;
2656
2657   GST_DEBUG_OBJECT (basesink, "prerolling object %p", obj);
2658
2659   /* if it's a buffer, we need to call the preroll method */
2660   if (G_LIKELY (GST_IS_BUFFER (obj)) && basesink->priv->call_preroll) {
2661     GstBaseSinkClass *bclass;
2662     GstBuffer *buf;
2663     GstClockTime timestamp;
2664
2665     buf = GST_BUFFER_CAST (obj);
2666     timestamp = GST_BUFFER_TIMESTAMP (buf);
2667
2668     GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
2669         GST_TIME_ARGS (timestamp));
2670
2671     gst_base_sink_set_last_buffer (basesink, buf);
2672
2673     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2674     if (bclass->preroll)
2675       if ((ret = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
2676         goto preroll_failed;
2677
2678     basesink->priv->call_preroll = FALSE;
2679   }
2680
2681   /* commit state */
2682   if (G_LIKELY (basesink->playing_async)) {
2683     if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
2684       goto stopping;
2685   }
2686
2687   return GST_FLOW_OK;
2688
2689   /* ERRORS */
2690 preroll_failed:
2691   {
2692     GST_DEBUG_OBJECT (basesink, "preroll failed, abort state");
2693     gst_element_abort_state (GST_ELEMENT_CAST (basesink));
2694     return ret;
2695   }
2696 stopping:
2697   {
2698     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
2699     return GST_FLOW_WRONG_STATE;
2700   }
2701 }
2702
2703 /* with STREAM_LOCK, PREROLL_LOCK 
2704  *
2705  * Queue an object for rendering.
2706  * The first prerollable object queued will complete the preroll. If the
2707  * preroll queue if filled, we render all the objects in the queue.
2708  *
2709  * This function takes ownership of the object.
2710  */
2711 static GstFlowReturn
2712 gst_base_sink_queue_object_unlocked (GstBaseSink * basesink, GstPad * pad,
2713     GstMiniObject * obj, gboolean prerollable)
2714 {
2715   GstFlowReturn ret = GST_FLOW_OK;
2716   gint length;
2717   GQueue *q;
2718
2719   if (G_UNLIKELY (basesink->need_preroll)) {
2720     if (G_LIKELY (prerollable))
2721       basesink->preroll_queued++;
2722
2723     length = basesink->preroll_queued;
2724
2725     GST_DEBUG_OBJECT (basesink, "now %d prerolled items", length);
2726
2727     /* first prerollable item needs to finish the preroll */
2728     if (length == 1) {
2729       ret = gst_base_sink_preroll_object (basesink, obj);
2730       if (G_UNLIKELY (ret != GST_FLOW_OK))
2731         goto preroll_failed;
2732     }
2733     /* need to recheck if we need preroll, commmit state during preroll 
2734      * could have made us not need more preroll. */
2735     if (G_UNLIKELY (basesink->need_preroll)) {
2736       /* see if we can render now, if we can't add the object to the preroll
2737        * queue. */
2738       if (G_UNLIKELY (length <= basesink->preroll_queue_max_len))
2739         goto more_preroll;
2740     }
2741   }
2742
2743   /* we can start rendering (or blocking) the queued object
2744    * if any. */
2745   q = basesink->preroll_queue;
2746   while (G_UNLIKELY (!g_queue_is_empty (q))) {
2747     GstMiniObject *o;
2748
2749     o = g_queue_pop_head (q);
2750     GST_DEBUG_OBJECT (basesink, "rendering queued object %p", o);
2751
2752     /* do something with the return value */
2753     ret = gst_base_sink_render_object (basesink, pad, o);
2754     if (ret != GST_FLOW_OK)
2755       goto dequeue_failed;
2756   }
2757
2758   /* now render the object */
2759   ret = gst_base_sink_render_object (basesink, pad, obj);
2760   basesink->preroll_queued = 0;
2761
2762   return ret;
2763
2764   /* special cases */
2765 preroll_failed:
2766   {
2767     GST_DEBUG_OBJECT (basesink, "preroll failed, reason %s",
2768         gst_flow_get_name (ret));
2769     gst_mini_object_unref (obj);
2770     return ret;
2771   }
2772 more_preroll:
2773   {
2774     /* add object to the queue and return */
2775     GST_DEBUG_OBJECT (basesink, "need more preroll data %d <= %d",
2776         length, basesink->preroll_queue_max_len);
2777     g_queue_push_tail (basesink->preroll_queue, obj);
2778     return GST_FLOW_OK;
2779   }
2780 dequeue_failed:
2781   {
2782     GST_DEBUG_OBJECT (basesink, "rendering queued objects failed, reason %s",
2783         gst_flow_get_name (ret));
2784     gst_mini_object_unref (obj);
2785     return ret;
2786   }
2787 }
2788
2789 /* with STREAM_LOCK
2790  *
2791  * This function grabs the PREROLL_LOCK and adds the object to
2792  * the queue.
2793  *
2794  * This function takes ownership of obj.
2795  */
2796 static GstFlowReturn
2797 gst_base_sink_queue_object (GstBaseSink * basesink, GstPad * pad,
2798     GstMiniObject * obj, gboolean prerollable)
2799 {
2800   GstFlowReturn ret;
2801
2802   GST_PAD_PREROLL_LOCK (pad);
2803   if (G_UNLIKELY (basesink->flushing))
2804     goto flushing;
2805
2806   if (G_UNLIKELY (basesink->priv->received_eos))
2807     goto was_eos;
2808
2809   ret = gst_base_sink_queue_object_unlocked (basesink, pad, obj, prerollable);
2810   GST_PAD_PREROLL_UNLOCK (pad);
2811
2812   return ret;
2813
2814   /* ERRORS */
2815 flushing:
2816   {
2817     GST_DEBUG_OBJECT (basesink, "sink is flushing");
2818     GST_PAD_PREROLL_UNLOCK (pad);
2819     gst_mini_object_unref (obj);
2820     return GST_FLOW_WRONG_STATE;
2821   }
2822 was_eos:
2823   {
2824     GST_DEBUG_OBJECT (basesink,
2825         "we are EOS, dropping object, return UNEXPECTED");
2826     GST_PAD_PREROLL_UNLOCK (pad);
2827     gst_mini_object_unref (obj);
2828     return GST_FLOW_UNEXPECTED;
2829   }
2830 }
2831
2832 static void
2833 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
2834 {
2835   /* make sure we are not blocked on the clock also clear any pending
2836    * eos state. */
2837   gst_base_sink_set_flushing (basesink, pad, TRUE);
2838
2839   /* we grab the stream lock but that is not needed since setting the
2840    * sink to flushing would make sure no state commit is being done
2841    * anymore */
2842   GST_PAD_STREAM_LOCK (pad);
2843   gst_base_sink_reset_qos (basesink);
2844   if (basesink->priv->async_enabled) {
2845     /* and we need to commit our state again on the next
2846      * prerolled buffer */
2847     basesink->playing_async = TRUE;
2848     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
2849   } else {
2850     basesink->priv->have_latency = TRUE;
2851     basesink->need_preroll = FALSE;
2852   }
2853   gst_base_sink_set_last_buffer (basesink, NULL);
2854   GST_PAD_STREAM_UNLOCK (pad);
2855 }
2856
2857 static void
2858 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad)
2859 {
2860   /* unset flushing so we can accept new data, this also flushes out any EOS
2861    * event. */
2862   gst_base_sink_set_flushing (basesink, pad, FALSE);
2863
2864   /* for position reporting */
2865   GST_OBJECT_LOCK (basesink);
2866   basesink->priv->current_sstart = -1;
2867   basesink->priv->current_sstop = -1;
2868   basesink->priv->eos_rtime = -1;
2869   basesink->priv->call_preroll = TRUE;
2870   if (basesink->pad_mode == GST_ACTIVATE_PUSH) {
2871     /* we need new segment info after the flush. */
2872     basesink->have_newsegment = FALSE;
2873     gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
2874     gst_segment_init (basesink->abidata.ABI.clip_segment, GST_FORMAT_UNDEFINED);
2875   }
2876   GST_OBJECT_UNLOCK (basesink);
2877 }
2878
2879 static gboolean
2880 gst_base_sink_event (GstPad * pad, GstEvent * event)
2881 {
2882   GstBaseSink *basesink;
2883   gboolean result = TRUE;
2884   GstBaseSinkClass *bclass;
2885
2886   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
2887
2888   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2889
2890   GST_DEBUG_OBJECT (basesink, "event %p (%s)", event,
2891       GST_EVENT_TYPE_NAME (event));
2892
2893   switch (GST_EVENT_TYPE (event)) {
2894     case GST_EVENT_EOS:
2895     {
2896       GstFlowReturn ret;
2897
2898       GST_PAD_PREROLL_LOCK (pad);
2899       if (G_UNLIKELY (basesink->flushing))
2900         goto flushing;
2901
2902       if (G_UNLIKELY (basesink->priv->received_eos)) {
2903         /* we can't accept anything when we are EOS */
2904         result = FALSE;
2905         gst_event_unref (event);
2906       } else {
2907         /* we set the received EOS flag here so that we can use it when testing if
2908          * we are prerolled and to refuse more buffers. */
2909         basesink->priv->received_eos = TRUE;
2910
2911         /* EOS is a prerollable object, we call the unlocked version because it
2912          * does not check the received_eos flag. */
2913         ret = gst_base_sink_queue_object_unlocked (basesink, pad,
2914             GST_MINI_OBJECT_CAST (event), TRUE);
2915         if (G_UNLIKELY (ret != GST_FLOW_OK))
2916           result = FALSE;
2917       }
2918       GST_PAD_PREROLL_UNLOCK (pad);
2919       break;
2920     }
2921     case GST_EVENT_NEWSEGMENT:
2922     {
2923       GstFlowReturn ret;
2924
2925       GST_DEBUG_OBJECT (basesink, "newsegment %p", event);
2926
2927       GST_PAD_PREROLL_LOCK (pad);
2928       if (G_UNLIKELY (basesink->flushing))
2929         goto flushing;
2930
2931       if (G_UNLIKELY (basesink->priv->received_eos)) {
2932         /* we can't accept anything when we are EOS */
2933         result = FALSE;
2934         gst_event_unref (event);
2935       } else {
2936         /* the new segment is a non prerollable item and does not block anything,
2937          * we need to configure the current clipping segment and insert the event 
2938          * in the queue to serialize it with the buffers for rendering. */
2939         gst_base_sink_configure_segment (basesink, pad, event,
2940             basesink->abidata.ABI.clip_segment);
2941
2942         ret =
2943             gst_base_sink_queue_object_unlocked (basesink, pad,
2944             GST_MINI_OBJECT_CAST (event), FALSE);
2945         if (G_UNLIKELY (ret != GST_FLOW_OK))
2946           result = FALSE;
2947         else {
2948           GST_OBJECT_LOCK (basesink);
2949           basesink->have_newsegment = TRUE;
2950           GST_OBJECT_UNLOCK (basesink);
2951         }
2952       }
2953       GST_PAD_PREROLL_UNLOCK (pad);
2954       break;
2955     }
2956     case GST_EVENT_FLUSH_START:
2957       if (bclass->event)
2958         bclass->event (basesink, event);
2959
2960       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
2961
2962       gst_base_sink_flush_start (basesink, pad);
2963
2964       gst_event_unref (event);
2965       break;
2966     case GST_EVENT_FLUSH_STOP:
2967       if (bclass->event)
2968         bclass->event (basesink, event);
2969
2970       GST_DEBUG_OBJECT (basesink, "flush-stop %p", event);
2971
2972       gst_base_sink_flush_stop (basesink, pad);
2973
2974       gst_event_unref (event);
2975       break;
2976     default:
2977       /* other events are sent to queue or subclass depending on if they
2978        * are serialized. */
2979       if (GST_EVENT_IS_SERIALIZED (event)) {
2980         gst_base_sink_queue_object (basesink, pad,
2981             GST_MINI_OBJECT_CAST (event), FALSE);
2982       } else {
2983         if (bclass->event)
2984           bclass->event (basesink, event);
2985         gst_event_unref (event);
2986       }
2987       break;
2988   }
2989 done:
2990   gst_object_unref (basesink);
2991
2992   return result;
2993
2994   /* ERRORS */
2995 flushing:
2996   {
2997     GST_DEBUG_OBJECT (basesink, "we are flushing");
2998     GST_PAD_PREROLL_UNLOCK (pad);
2999     result = FALSE;
3000     gst_event_unref (event);
3001     goto done;
3002   }
3003 }
3004
3005 /* default implementation to calculate the start and end
3006  * timestamps on a buffer, subclasses can override
3007  */
3008 static void
3009 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
3010     GstClockTime * start, GstClockTime * end)
3011 {
3012   GstClockTime timestamp, duration;
3013
3014   timestamp = GST_BUFFER_TIMESTAMP (buffer);
3015   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
3016
3017     /* get duration to calculate end time */
3018     duration = GST_BUFFER_DURATION (buffer);
3019     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3020       *end = timestamp + duration;
3021     }
3022     *start = timestamp;
3023   }
3024 }
3025
3026 /* must be called with PREROLL_LOCK */
3027 static gboolean
3028 gst_base_sink_needs_preroll (GstBaseSink * basesink)
3029 {
3030   gboolean is_prerolled, res;
3031
3032   /* we have 2 cases where the PREROLL_LOCK is released:
3033    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
3034    *  2) we are syncing on the clock
3035    */
3036   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
3037   res = !is_prerolled;
3038
3039   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
3040       basesink->have_preroll, basesink->priv->received_eos, res);
3041
3042   return res;
3043 }
3044
3045 /* with STREAM_LOCK, PREROLL_LOCK 
3046  *
3047  * Takes a buffer and compare the timestamps with the last segment.
3048  * If the buffer falls outside of the segment boundaries, drop it.
3049  * Else queue the buffer for preroll and rendering.
3050  *
3051  * This function takes ownership of the buffer.
3052  */
3053 static GstFlowReturn
3054 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
3055     GstBuffer * buf)
3056 {
3057   GstBaseSinkClass *bclass;
3058   GstFlowReturn result;
3059   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
3060   GstSegment *clip_segment;
3061
3062   if (G_UNLIKELY (basesink->flushing))
3063     goto flushing;
3064
3065   if (G_UNLIKELY (basesink->priv->received_eos))
3066     goto was_eos;
3067
3068   /* for code clarity */
3069   clip_segment = basesink->abidata.ABI.clip_segment;
3070
3071   if (G_UNLIKELY (!basesink->have_newsegment)) {
3072     gboolean sync;
3073
3074     sync = gst_base_sink_get_sync (basesink);
3075     if (sync) {
3076       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
3077           (_("Internal data flow problem.")),
3078           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
3079     }
3080
3081     /* this means this sink will assume timestamps start from 0 */
3082     GST_OBJECT_LOCK (basesink);
3083     clip_segment->start = 0;
3084     clip_segment->stop = -1;
3085     basesink->segment.start = 0;
3086     basesink->segment.stop = -1;
3087     basesink->have_newsegment = TRUE;
3088     GST_OBJECT_UNLOCK (basesink);
3089   }
3090
3091   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3092
3093   /* check if the buffer needs to be dropped, we first ask the subclass for the
3094    * start and end */
3095   if (bclass->get_times)
3096     bclass->get_times (basesink, buf, &start, &end);
3097
3098   if (start == -1) {
3099     /* if the subclass does not want sync, we use our own values so that we at
3100      * least clip the buffer to the segment */
3101     gst_base_sink_get_times (basesink, buf, &start, &end);
3102   }
3103
3104   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
3105       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
3106
3107   /* a dropped buffer does not participate in anything */
3108   if (GST_CLOCK_TIME_IS_VALID (start) &&
3109       (clip_segment->format == GST_FORMAT_TIME)) {
3110     if (G_UNLIKELY (!gst_segment_clip (clip_segment,
3111                 GST_FORMAT_TIME, (gint64) start, (gint64) end, NULL, NULL)))
3112       goto out_of_segment;
3113   }
3114
3115   /* now we can process the buffer in the queue, this function takes ownership
3116    * of the buffer */
3117   result = gst_base_sink_queue_object_unlocked (basesink, pad,
3118       GST_MINI_OBJECT_CAST (buf), TRUE);
3119
3120   return result;
3121
3122   /* ERRORS */
3123 flushing:
3124   {
3125     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3126     gst_buffer_unref (buf);
3127     return GST_FLOW_WRONG_STATE;
3128   }
3129 was_eos:
3130   {
3131     GST_DEBUG_OBJECT (basesink,
3132         "we are EOS, dropping object, return UNEXPECTED");
3133     gst_buffer_unref (buf);
3134     return GST_FLOW_UNEXPECTED;
3135   }
3136 out_of_segment:
3137   {
3138     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
3139     gst_buffer_unref (buf);
3140     return GST_FLOW_OK;
3141   }
3142 }
3143
3144 /* with STREAM_LOCK
3145  */
3146 static GstFlowReturn
3147 gst_base_sink_chain (GstPad * pad, GstBuffer * buf)
3148 {
3149   GstBaseSink *basesink;
3150   GstFlowReturn result;
3151
3152   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3153
3154   if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH))
3155     goto wrong_mode;
3156
3157   GST_PAD_PREROLL_LOCK (pad);
3158   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
3159   GST_PAD_PREROLL_UNLOCK (pad);
3160
3161 done:
3162   return result;
3163
3164   /* ERRORS */
3165 wrong_mode:
3166   {
3167     GST_OBJECT_LOCK (pad);
3168     GST_WARNING_OBJECT (basesink,
3169         "Push on pad %s:%s, but it was not activated in push mode",
3170         GST_DEBUG_PAD_NAME (pad));
3171     GST_OBJECT_UNLOCK (pad);
3172     gst_buffer_unref (buf);
3173     /* we don't post an error message this will signal to the peer
3174      * pushing that EOS is reached. */
3175     result = GST_FLOW_UNEXPECTED;
3176     goto done;
3177   }
3178 }
3179
3180 static gboolean
3181 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
3182 {
3183   gboolean res = TRUE;
3184
3185   /* update our offset if the start/stop position was updated */
3186   if (segment->format == GST_FORMAT_BYTES) {
3187     segment->time = segment->start;
3188   } else if (segment->start == 0) {
3189     /* seek to start, we can implement a default for this. */
3190     segment->time = 0;
3191   } else {
3192     res = FALSE;
3193     GST_INFO_OBJECT (sink, "Can't do a default seek");
3194   }
3195
3196   return res;
3197 }
3198
3199 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
3200
3201 static gboolean
3202 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3203     GstEvent * event, GstSegment * segment)
3204 {
3205   /* By default, we try one of 2 things:
3206    *   - For absolute seek positions, convert the requested position to our 
3207    *     configured processing format and place it in the output segment \
3208    *   - For relative seek positions, convert our current (input) values to the
3209    *     seek format, adjust by the relative seek offset and then convert back to
3210    *     the processing format
3211    */
3212   GstSeekType cur_type, stop_type;
3213   gint64 cur, stop;
3214   GstSeekFlags flags;
3215   GstFormat seek_format, dest_format;
3216   gdouble rate;
3217   gboolean update;
3218   gboolean res = TRUE;
3219
3220   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3221       &cur_type, &cur, &stop_type, &stop);
3222   dest_format = segment->format;
3223
3224   if (seek_format == dest_format) {
3225     gst_segment_set_seek (segment, rate, seek_format, flags,
3226         cur_type, cur, stop_type, stop, &update);
3227     return TRUE;
3228   }
3229
3230   if (cur_type != GST_SEEK_TYPE_NONE) {
3231     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3232     res =
3233         gst_pad_query_convert (sink->sinkpad, seek_format, cur, &dest_format,
3234         &cur);
3235     cur_type = GST_SEEK_TYPE_SET;
3236   }
3237
3238   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3239     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3240     res =
3241         gst_pad_query_convert (sink->sinkpad, seek_format, stop, &dest_format,
3242         &stop);
3243     stop_type = GST_SEEK_TYPE_SET;
3244   }
3245
3246   /* And finally, configure our output segment in the desired format */
3247   gst_segment_set_seek (segment, rate, dest_format, flags, cur_type, cur,
3248       stop_type, stop, &update);
3249
3250   if (!res)
3251     goto no_format;
3252
3253   return res;
3254
3255 no_format:
3256   {
3257     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3258     return FALSE;
3259   }
3260 }
3261
3262 /* perform a seek, only executed in pull mode */
3263 static gboolean
3264 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3265 {
3266   gboolean flush;
3267   gdouble rate;
3268   GstFormat seek_format, dest_format;
3269   GstSeekFlags flags;
3270   GstSeekType cur_type, stop_type;
3271   gboolean seekseg_configured = FALSE;
3272   gint64 cur, stop;
3273   gboolean update, res = TRUE;
3274   GstSegment seeksegment;
3275
3276   dest_format = sink->segment.format;
3277
3278   if (event) {
3279     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3280     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3281         &cur_type, &cur, &stop_type, &stop);
3282
3283     flush = flags & GST_SEEK_FLAG_FLUSH;
3284   } else {
3285     GST_DEBUG_OBJECT (sink, "performing seek without event");
3286     flush = FALSE;
3287   }
3288
3289   if (flush) {
3290     GST_DEBUG_OBJECT (sink, "flushing upstream");
3291     gst_pad_push_event (pad, gst_event_new_flush_start ());
3292     gst_base_sink_flush_start (sink, pad);
3293   } else {
3294     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3295   }
3296
3297   GST_PAD_STREAM_LOCK (pad);
3298
3299   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3300    * copy the current segment info into the temp segment that we can actually
3301    * attempt the seek with. We only update the real segment if the seek suceeds. */
3302   if (!seekseg_configured) {
3303     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3304
3305     /* now configure the final seek segment */
3306     if (event) {
3307       if (sink->segment.format != seek_format) {
3308         /* OK, here's where we give the subclass a chance to convert the relative
3309          * seek into an absolute one in the processing format. We set up any
3310          * absolute seek above, before taking the stream lock. */
3311         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3312                 &seeksegment)) {
3313           GST_DEBUG_OBJECT (sink,
3314               "Preparing the seek failed after flushing. " "Aborting seek");
3315           res = FALSE;
3316         }
3317       } else {
3318         /* The seek format matches our processing format, no need to ask the
3319          * the subclass to configure the segment. */
3320         gst_segment_set_seek (&seeksegment, rate, seek_format, flags,
3321             cur_type, cur, stop_type, stop, &update);
3322       }
3323     }
3324     /* Else, no seek event passed, so we're just (re)starting the 
3325        current segment. */
3326   }
3327
3328   if (res) {
3329     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3330         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3331         seeksegment.start, seeksegment.stop, seeksegment.last_stop);
3332
3333     /* do the seek, segment.last_stop contains the new position. */
3334     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3335   }
3336
3337
3338   if (flush) {
3339     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3340     gst_pad_push_event (pad, gst_event_new_flush_stop ());
3341     gst_base_sink_flush_stop (sink, pad);
3342   } else if (res && sink->abidata.ABI.running) {
3343     /* we are running the current segment and doing a non-flushing seek, 
3344      * close the segment first based on the last_stop. */
3345     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3346         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.last_stop);
3347   }
3348
3349   /* The subclass must have converted the segment to the processing format 
3350    * by now */
3351   if (res && seeksegment.format != dest_format) {
3352     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3353         "in the correct format. Aborting seek.");
3354     res = FALSE;
3355   }
3356
3357   /* if successfull seek, we update our real segment and push
3358    * out the new segment. */
3359   if (res) {
3360     memcpy (&sink->segment, &seeksegment, sizeof (GstSegment));
3361
3362     if (sink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3363       gst_element_post_message (GST_ELEMENT (sink),
3364           gst_message_new_segment_start (GST_OBJECT (sink),
3365               sink->segment.format, sink->segment.last_stop));
3366     }
3367   }
3368
3369   sink->priv->discont = TRUE;
3370   sink->abidata.ABI.running = TRUE;
3371
3372   GST_PAD_STREAM_UNLOCK (pad);
3373
3374   return res;
3375 }
3376
3377 static gboolean
3378 gst_base_sink_perform_step (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3379 {
3380   GstBaseSinkPrivate *priv;
3381   GstBaseSinkClass *bclass;
3382   gboolean flush, intermediate;
3383   gdouble rate;
3384   GstFormat format;
3385   guint64 amount;
3386   guint seqnum;
3387
3388   bclass = GST_BASE_SINK_GET_CLASS (sink);
3389   priv = sink->priv;
3390
3391   GST_DEBUG_OBJECT (sink, "performing step with event %p", event);
3392
3393   gst_event_parse_step (event, &format, &amount, &rate, &flush, &intermediate);
3394   seqnum = gst_event_get_seqnum (event);
3395
3396   if (flush) {
3397     /* we need to call ::unlock before locking PREROLL_LOCK
3398      * since we lock it before going into ::render */
3399     if (bclass->unlock)
3400       bclass->unlock (sink);
3401
3402     GST_PAD_PREROLL_LOCK (sink->sinkpad);
3403     /* update the segment */
3404     priv->pending_step.seqnum = seqnum;
3405     priv->pending_step.format = format;
3406     priv->pending_step.amount = amount;
3407     priv->pending_step.position = 0;
3408     priv->pending_step.rate = rate;
3409     priv->pending_step.flush = flush;
3410     priv->pending_step.intermediate = intermediate;
3411     priv->pending_step.valid = TRUE;
3412
3413     /* now that we have the PREROLL lock, clear our unlock request */
3414     if (bclass->unlock_stop)
3415       bclass->unlock_stop (sink);
3416
3417     if (sink->priv->async_enabled) {
3418       /* and we need to commit our state again on the next
3419        * prerolled buffer */
3420       sink->playing_async = TRUE;
3421       priv->pending_step.need_preroll = TRUE;
3422       sink->need_preroll = FALSE;
3423       gst_element_lost_state_full (GST_ELEMENT_CAST (sink), FALSE);
3424     } else {
3425       sink->priv->have_latency = TRUE;
3426       sink->need_preroll = FALSE;
3427     }
3428     priv->call_preroll = TRUE;
3429     gst_base_sink_set_last_buffer (sink, NULL);
3430     gst_base_sink_reset_qos (sink);
3431
3432     if (sink->clock_id) {
3433       gst_clock_id_unschedule (sink->clock_id);
3434     }
3435
3436     GST_DEBUG_OBJECT (sink, "signal waiter");
3437     GST_PAD_PREROLL_SIGNAL (sink->sinkpad);
3438
3439     GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
3440   }
3441
3442   return TRUE;
3443 }
3444
3445 /* with STREAM_LOCK
3446  */
3447 static void
3448 gst_base_sink_loop (GstPad * pad)
3449 {
3450   GstBaseSink *basesink;
3451   GstBuffer *buf = NULL;
3452   GstFlowReturn result;
3453   guint blocksize;
3454   guint64 offset;
3455
3456   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3457
3458   g_assert (basesink->pad_mode == GST_ACTIVATE_PULL);
3459
3460   if ((blocksize = basesink->priv->blocksize) == 0)
3461     blocksize = -1;
3462
3463   offset = basesink->segment.last_stop;
3464
3465   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
3466       offset, blocksize);
3467
3468   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
3469   if (G_UNLIKELY (result != GST_FLOW_OK))
3470     goto paused;
3471
3472   if (G_UNLIKELY (buf == NULL))
3473     goto no_buffer;
3474
3475   offset += GST_BUFFER_SIZE (buf);
3476
3477   gst_segment_set_last_stop (&basesink->segment, GST_FORMAT_BYTES, offset);
3478
3479   GST_PAD_PREROLL_LOCK (pad);
3480   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
3481   GST_PAD_PREROLL_UNLOCK (pad);
3482   if (G_UNLIKELY (result != GST_FLOW_OK))
3483     goto paused;
3484
3485   return;
3486
3487   /* ERRORS */
3488 paused:
3489   {
3490     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
3491         gst_flow_get_name (result));
3492     gst_pad_pause_task (pad);
3493     /* fatal errors and NOT_LINKED cause EOS */
3494     if (GST_FLOW_IS_FATAL (result) || result == GST_FLOW_NOT_LINKED) {
3495       if (result == GST_FLOW_UNEXPECTED) {
3496         /* perform EOS logic */
3497         if (basesink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3498           gst_element_post_message (GST_ELEMENT_CAST (basesink),
3499               gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
3500                   basesink->segment.format, basesink->segment.last_stop));
3501         } else {
3502           gst_base_sink_event (pad, gst_event_new_eos ());
3503         }
3504       } else {
3505         /* for fatal errors we post an error message, post the error
3506          * first so the app knows about the error first. */
3507         GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3508             (_("Internal data stream error.")),
3509             ("stream stopped, reason %s", gst_flow_get_name (result)));
3510         gst_base_sink_event (pad, gst_event_new_eos ());
3511       }
3512     }
3513     return;
3514   }
3515 no_buffer:
3516   {
3517     GST_LOG_OBJECT (basesink, "no buffer, pausing");
3518     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3519         (_("Internal data flow error.")), ("element returned NULL buffer"));
3520     result = GST_FLOW_ERROR;
3521     goto paused;
3522   }
3523 }
3524
3525 static gboolean
3526 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
3527     gboolean flushing)
3528 {
3529   GstBaseSinkClass *bclass;
3530
3531   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3532
3533   if (flushing) {
3534     /* unlock any subclasses, we need to do this before grabbing the
3535      * PREROLL_LOCK since we hold this lock before going into ::render. */
3536     if (bclass->unlock)
3537       bclass->unlock (basesink);
3538   }
3539
3540   GST_PAD_PREROLL_LOCK (pad);
3541   basesink->flushing = flushing;
3542   if (flushing) {
3543     /* step 1, now that we have the PREROLL lock, clear our unlock request */
3544     if (bclass->unlock_stop)
3545       bclass->unlock_stop (basesink);
3546
3547     /* set need_preroll before we unblock the clock. If the clock is unblocked
3548      * before timing out, we can reuse the buffer for preroll. */
3549     basesink->need_preroll = TRUE;
3550
3551     /* step 2, unblock clock sync (if any) or any other blocking thing */
3552     if (basesink->clock_id) {
3553       gst_clock_id_unschedule (basesink->clock_id);
3554     }
3555
3556     /* flush out the data thread if it's locked in finish_preroll, this will
3557      * also flush out the EOS state */
3558     GST_DEBUG_OBJECT (basesink,
3559         "flushing out data thread, need preroll to TRUE");
3560     gst_base_sink_preroll_queue_flush (basesink, pad);
3561   }
3562   GST_PAD_PREROLL_UNLOCK (pad);
3563
3564   return TRUE;
3565 }
3566
3567 static gboolean
3568 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
3569 {
3570   gboolean result;
3571
3572   if (active) {
3573     /* start task */
3574     result = gst_pad_start_task (basesink->sinkpad,
3575         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad);
3576   } else {
3577     /* step 2, make sure streaming finishes */
3578     result = gst_pad_stop_task (basesink->sinkpad);
3579   }
3580
3581   return result;
3582 }
3583
3584 static gboolean
3585 gst_base_sink_pad_activate (GstPad * pad)
3586 {
3587   gboolean result = FALSE;
3588   GstBaseSink *basesink;
3589
3590   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3591
3592   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
3593
3594   gst_base_sink_set_flushing (basesink, pad, FALSE);
3595
3596   /* we need to have the pull mode enabled */
3597   if (!basesink->can_activate_pull) {
3598     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
3599     goto fallback;
3600   }
3601
3602   /* check if downstreams supports pull mode at all */
3603   if (!gst_pad_check_pull_range (pad)) {
3604     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
3605     goto fallback;
3606   }
3607
3608   /* set the pad mode before starting the task so that it's in the
3609    * correct state for the new thread. also the sink set_caps and get_caps
3610    * function checks this */
3611   basesink->pad_mode = GST_ACTIVATE_PULL;
3612
3613   /* we first try to negotiate a format so that when we try to activate
3614    * downstream, it knows about our format */
3615   if (!gst_base_sink_negotiate_pull (basesink)) {
3616     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
3617     goto fallback;
3618   }
3619
3620   /* ok activate now */
3621   if (!gst_pad_activate_pull (pad, TRUE)) {
3622     /* clear any pending caps */
3623     GST_OBJECT_LOCK (basesink);
3624     gst_caps_replace (&basesink->priv->pull_caps, NULL);
3625     GST_OBJECT_UNLOCK (basesink);
3626     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
3627     goto fallback;
3628   }
3629
3630   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
3631   result = TRUE;
3632   goto done;
3633
3634   /* push mode fallback */
3635 fallback:
3636   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
3637   if ((result = gst_pad_activate_push (pad, TRUE))) {
3638     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
3639   }
3640
3641 done:
3642   if (!result) {
3643     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
3644     gst_base_sink_set_flushing (basesink, pad, TRUE);
3645   }
3646
3647   gst_object_unref (basesink);
3648
3649   return result;
3650 }
3651
3652 static gboolean
3653 gst_base_sink_pad_activate_push (GstPad * pad, gboolean active)
3654 {
3655   gboolean result;
3656   GstBaseSink *basesink;
3657
3658   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3659
3660   if (active) {
3661     if (!basesink->can_activate_push) {
3662       result = FALSE;
3663       basesink->pad_mode = GST_ACTIVATE_NONE;
3664     } else {
3665       result = TRUE;
3666       basesink->pad_mode = GST_ACTIVATE_PUSH;
3667     }
3668   } else {
3669     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH)) {
3670       g_warning ("Internal GStreamer activation error!!!");
3671       result = FALSE;
3672     } else {
3673       gst_base_sink_set_flushing (basesink, pad, TRUE);
3674       result = TRUE;
3675       basesink->pad_mode = GST_ACTIVATE_NONE;
3676     }
3677   }
3678
3679   gst_object_unref (basesink);
3680
3681   return result;
3682 }
3683
3684 static gboolean
3685 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
3686 {
3687   GstCaps *caps;
3688   gboolean result;
3689
3690   result = FALSE;
3691
3692   /* this returns the intersection between our caps and the peer caps. If there
3693    * is no peer, it returns NULL and we can't operate in pull mode so we can
3694    * fail the negotiation. */
3695   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
3696   if (caps == NULL || gst_caps_is_empty (caps))
3697     goto no_caps_possible;
3698
3699   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
3700
3701   caps = gst_caps_make_writable (caps);
3702   /* get the first (prefered) format */
3703   gst_caps_truncate (caps);
3704   /* try to fixate */
3705   gst_pad_fixate_caps (GST_BASE_SINK_PAD (basesink), caps);
3706
3707   GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
3708
3709   if (gst_caps_is_any (caps)) {
3710     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
3711         "allowing pull()");
3712     /* neither side has template caps in this case, so they are prepared for
3713        pull() without setcaps() */
3714     result = TRUE;
3715   } else if (gst_caps_is_fixed (caps)) {
3716     if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
3717       goto could_not_set_caps;
3718
3719     GST_OBJECT_LOCK (basesink);
3720     gst_caps_replace (&basesink->priv->pull_caps, caps);
3721     GST_OBJECT_UNLOCK (basesink);
3722
3723     result = TRUE;
3724   }
3725
3726   gst_caps_unref (caps);
3727
3728   return result;
3729
3730 no_caps_possible:
3731   {
3732     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
3733     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
3734     if (caps)
3735       gst_caps_unref (caps);
3736     return FALSE;
3737   }
3738 could_not_set_caps:
3739   {
3740     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
3741     gst_caps_unref (caps);
3742     return FALSE;
3743   }
3744 }
3745
3746 /* this won't get called until we implement an activate function */
3747 static gboolean
3748 gst_base_sink_pad_activate_pull (GstPad * pad, gboolean active)
3749 {
3750   gboolean result = FALSE;
3751   GstBaseSink *basesink;
3752   GstBaseSinkClass *bclass;
3753
3754   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3755   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3756
3757   if (active) {
3758     GstFormat format;
3759     gint64 duration;
3760
3761     /* we mark we have a newsegment here because pull based
3762      * mode works just fine without having a newsegment before the
3763      * first buffer */
3764     format = GST_FORMAT_BYTES;
3765
3766     gst_segment_init (&basesink->segment, format);
3767     gst_segment_init (basesink->abidata.ABI.clip_segment, format);
3768     GST_OBJECT_LOCK (basesink);
3769     basesink->have_newsegment = TRUE;
3770     GST_OBJECT_UNLOCK (basesink);
3771
3772     /* get the peer duration in bytes */
3773     result = gst_pad_query_peer_duration (pad, &format, &duration);
3774     if (result) {
3775       GST_DEBUG_OBJECT (basesink,
3776           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
3777       gst_segment_set_duration (basesink->abidata.ABI.clip_segment, format,
3778           duration);
3779       gst_segment_set_duration (&basesink->segment, format, duration);
3780     } else {
3781       GST_DEBUG_OBJECT (basesink, "unknown duration");
3782     }
3783
3784     if (bclass->activate_pull)
3785       result = bclass->activate_pull (basesink, TRUE);
3786     else
3787       result = FALSE;
3788
3789     if (!result)
3790       goto activate_failed;
3791
3792   } else {
3793     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PULL)) {
3794       g_warning ("Internal GStreamer activation error!!!");
3795       result = FALSE;
3796     } else {
3797       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
3798       if (bclass->activate_pull)
3799         result &= bclass->activate_pull (basesink, FALSE);
3800       basesink->pad_mode = GST_ACTIVATE_NONE;
3801       /* clear any pending caps */
3802       GST_OBJECT_LOCK (basesink);
3803       gst_caps_replace (&basesink->priv->pull_caps, NULL);
3804       GST_OBJECT_UNLOCK (basesink);
3805     }
3806   }
3807   gst_object_unref (basesink);
3808
3809   return result;
3810
3811   /* ERRORS */
3812 activate_failed:
3813   {
3814     /* reset, as starting the thread failed */
3815     basesink->pad_mode = GST_ACTIVATE_NONE;
3816
3817     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
3818     return FALSE;
3819   }
3820 }
3821
3822 /* send an event to our sinkpad peer. */
3823 static gboolean
3824 gst_base_sink_send_event (GstElement * element, GstEvent * event)
3825 {
3826   GstPad *pad;
3827   GstBaseSink *basesink = GST_BASE_SINK (element);
3828   gboolean forward, result = TRUE;
3829   GstActivateMode mode;
3830
3831   GST_OBJECT_LOCK (element);
3832   /* get the pad and the scheduling mode */
3833   pad = gst_object_ref (basesink->sinkpad);
3834   mode = basesink->pad_mode;
3835   GST_OBJECT_UNLOCK (element);
3836
3837   /* only push UPSTREAM events upstream */
3838   forward = GST_EVENT_IS_UPSTREAM (event);
3839
3840   switch (GST_EVENT_TYPE (event)) {
3841     case GST_EVENT_LATENCY:
3842     {
3843       GstClockTime latency;
3844
3845       gst_event_parse_latency (event, &latency);
3846
3847       /* store the latency. We use this to adjust the running_time before syncing
3848        * it to the clock. */
3849       GST_OBJECT_LOCK (element);
3850       basesink->priv->latency = latency;
3851       if (!basesink->priv->have_latency)
3852         forward = FALSE;
3853       GST_OBJECT_UNLOCK (element);
3854       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
3855           GST_TIME_ARGS (latency));
3856
3857       /* We forward this event so that all elements know about the global pipeline
3858        * latency. This is interesting for an element when it wants to figure out
3859        * when a particular piece of data will be rendered. */
3860       break;
3861     }
3862     case GST_EVENT_SEEK:
3863       /* in pull mode we will execute the seek */
3864       if (mode == GST_ACTIVATE_PULL)
3865         result = gst_base_sink_perform_seek (basesink, pad, event);
3866       break;
3867     case GST_EVENT_STEP:
3868       result = gst_base_sink_perform_step (basesink, pad, event);
3869       forward = FALSE;
3870       break;
3871     default:
3872       break;
3873   }
3874
3875   if (forward) {
3876     result = gst_pad_push_event (pad, event);
3877   } else {
3878     /* not forwarded, unref the event */
3879     gst_event_unref (event);
3880   }
3881
3882   gst_object_unref (pad);
3883   return result;
3884 }
3885
3886 static gboolean
3887 gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query)
3888 {
3889   GstPad *peer;
3890   gboolean res = FALSE;
3891
3892   if ((peer = gst_pad_get_peer (sink->sinkpad))) {
3893     res = gst_pad_query (peer, query);
3894     gst_object_unref (peer);
3895   }
3896   return res;
3897 }
3898
3899 /* get the end position of the last seen object, this is used
3900  * for EOS and for making sure that we don't report a position we
3901  * have not reached yet. With LOCK. */
3902 static gboolean
3903 gst_base_sink_get_position_last (GstBaseSink * basesink, GstFormat format,
3904     gint64 * cur)
3905 {
3906   GstFormat oformat;
3907   GstSegment *segment;
3908   gboolean ret = TRUE;
3909
3910   segment = &basesink->segment;
3911   oformat = segment->format;
3912
3913   if (oformat == GST_FORMAT_TIME) {
3914     /* return last observed stream time, we keep the stream time around in the
3915      * time format. */
3916     *cur = basesink->priv->current_sstop;
3917   } else {
3918     /* convert last stop to stream time */
3919     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3920   }
3921
3922   if (*cur != -1 && oformat != format) {
3923     GST_OBJECT_UNLOCK (basesink);
3924     /* convert to the target format if we need to, release lock first */
3925     ret =
3926         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3927     if (!ret)
3928       *cur = -1;
3929     GST_OBJECT_LOCK (basesink);
3930   }
3931
3932   GST_DEBUG_OBJECT (basesink, "POSITION: %" GST_TIME_FORMAT,
3933       GST_TIME_ARGS (*cur));
3934
3935   return ret;
3936 }
3937
3938 /* get the position when we are PAUSED, this is the stream time of the buffer
3939  * that prerolled. If no buffer is prerolled (we are still flushing), this
3940  * value will be -1. With LOCK. */
3941 static gboolean
3942 gst_base_sink_get_position_paused (GstBaseSink * basesink, GstFormat format,
3943     gint64 * cur)
3944 {
3945   gboolean res;
3946   gint64 time;
3947   GstSegment *segment;
3948   GstFormat oformat;
3949
3950   /* we don't use the clip segment in pull mode, when seeking we update the
3951    * main segment directly with the new segment values without it having to be
3952    * activated by the rendering after preroll */
3953   if (basesink->pad_mode == GST_ACTIVATE_PUSH)
3954     segment = basesink->abidata.ABI.clip_segment;
3955   else
3956     segment = &basesink->segment;
3957   oformat = segment->format;
3958
3959   if (oformat == GST_FORMAT_TIME) {
3960     *cur = basesink->priv->current_sstart;
3961   } else {
3962     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3963   }
3964
3965   time = segment->time;
3966
3967   if (*cur != -1) {
3968     *cur = MAX (*cur, time);
3969     GST_DEBUG_OBJECT (basesink, "POSITION as max: %" GST_TIME_FORMAT
3970         ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (*cur), GST_TIME_ARGS (time));
3971   } else {
3972     /* we have no buffer, use the segment times. */
3973     if (segment->rate >= 0.0) {
3974       /* forward, next position is always the time of the segment */
3975       *cur = time;
3976       GST_DEBUG_OBJECT (basesink, "POSITION as time: %" GST_TIME_FORMAT,
3977           GST_TIME_ARGS (*cur));
3978     } else {
3979       /* reverse, next expected timestamp is segment->stop. We use the function
3980        * to get things right for negative applied_rates. */
3981       *cur = gst_segment_to_stream_time (segment, oformat, segment->stop);
3982       GST_DEBUG_OBJECT (basesink, "reverse POSITION: %" GST_TIME_FORMAT,
3983           GST_TIME_ARGS (*cur));
3984     }
3985   }
3986
3987   res = (*cur != -1);
3988   if (res && oformat != format) {
3989     GST_OBJECT_UNLOCK (basesink);
3990     res =
3991         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3992     if (!res)
3993       *cur = -1;
3994     GST_OBJECT_LOCK (basesink);
3995   }
3996
3997   return res;
3998 }
3999
4000 static gboolean
4001 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
4002     gint64 * cur, gboolean * upstream)
4003 {
4004   GstClock *clock;
4005   gboolean res = FALSE;
4006   GstFormat oformat, tformat;
4007   GstClockTime now, base, latency;
4008   gint64 time, accum, duration;
4009   gdouble rate;
4010   gint64 last;
4011
4012   GST_OBJECT_LOCK (basesink);
4013   /* our intermediate time format */
4014   tformat = GST_FORMAT_TIME;
4015   /* get the format in the segment */
4016   oformat = basesink->segment.format;
4017
4018   /* can only give answer based on the clock if not EOS */
4019   if (G_UNLIKELY (basesink->eos))
4020     goto in_eos;
4021
4022   /* we can only get the segment when we are not NULL or READY */
4023   if (!basesink->have_newsegment)
4024     goto wrong_state;
4025
4026   /* when not in PLAYING or when we're busy with a state change, we
4027    * cannot read from the clock so we report time based on the
4028    * last seen timestamp. */
4029   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
4030       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING)
4031     goto in_pause;
4032
4033   /* we need to sync on the clock. */
4034   if (basesink->sync == FALSE)
4035     goto no_sync;
4036
4037   /* and we need a clock */
4038   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
4039     goto no_sync;
4040
4041   /* collect all data we need holding the lock */
4042   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.time))
4043     time = basesink->segment.time;
4044   else
4045     time = 0;
4046
4047   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.stop))
4048     duration = basesink->segment.stop - basesink->segment.start;
4049   else
4050     duration = 0;
4051
4052   base = GST_ELEMENT_CAST (basesink)->base_time;
4053   accum = basesink->segment.accum;
4054   rate = basesink->segment.rate * basesink->segment.applied_rate;
4055   latency = basesink->priv->latency;
4056
4057   gst_object_ref (clock);
4058
4059   /* this function might release the LOCK */
4060   gst_base_sink_get_position_last (basesink, format, &last);
4061
4062   /* need to release the object lock before we can get the time, 
4063    * a clock might take the LOCK of the provider, which could be
4064    * a basesink subclass. */
4065   GST_OBJECT_UNLOCK (basesink);
4066
4067   now = gst_clock_get_time (clock);
4068
4069   if (oformat != tformat) {
4070     /* convert accum, time and duration to time */
4071     if (!gst_pad_query_convert (basesink->sinkpad, oformat, accum, &tformat,
4072             &accum))
4073       goto convert_failed;
4074     if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration, &tformat,
4075             &duration))
4076       goto convert_failed;
4077     if (!gst_pad_query_convert (basesink->sinkpad, oformat, time, &tformat,
4078             &time))
4079       goto convert_failed;
4080   }
4081
4082   /* subtract base time and accumulated time from the clock time. 
4083    * Make sure we don't go negative. This is the current time in
4084    * the segment which we need to scale with the combined 
4085    * rate and applied rate. */
4086   base += accum;
4087   base += latency;
4088   base = MIN (now, base);
4089
4090   /* for negative rates we need to count back from from the segment
4091    * duration. */
4092   if (rate < 0.0)
4093     time += duration;
4094
4095   *cur = time + gst_guint64_to_gdouble (now - base) * rate;
4096
4097   /* never report more than last seen position */
4098   if (last != -1)
4099     *cur = MIN (last, *cur);
4100
4101   gst_object_unref (clock);
4102
4103   GST_DEBUG_OBJECT (basesink,
4104       "now %" GST_TIME_FORMAT " - base %" GST_TIME_FORMAT " - accum %"
4105       GST_TIME_FORMAT " + time %" GST_TIME_FORMAT,
4106       GST_TIME_ARGS (now), GST_TIME_ARGS (base),
4107       GST_TIME_ARGS (accum), GST_TIME_ARGS (time));
4108
4109   if (oformat != format) {
4110     /* convert time to final format */
4111     if (!gst_pad_query_convert (basesink->sinkpad, tformat, *cur, &format, cur))
4112       goto convert_failed;
4113   }
4114
4115   res = TRUE;
4116
4117 done:
4118   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
4119       res, GST_TIME_ARGS (*cur));
4120   return res;
4121
4122   /* special cases */
4123 in_eos:
4124   {
4125     GST_DEBUG_OBJECT (basesink, "position in EOS");
4126     res = gst_base_sink_get_position_last (basesink, format, cur);
4127     GST_OBJECT_UNLOCK (basesink);
4128     goto done;
4129   }
4130 in_pause:
4131   {
4132     GST_DEBUG_OBJECT (basesink, "position in PAUSED");
4133     res = gst_base_sink_get_position_paused (basesink, format, cur);
4134     GST_OBJECT_UNLOCK (basesink);
4135     goto done;
4136   }
4137 wrong_state:
4138   {
4139     /* in NULL or READY we always return FALSE and -1 */
4140     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
4141     res = FALSE;
4142     *cur = -1;
4143     GST_OBJECT_UNLOCK (basesink);
4144     goto done;
4145   }
4146 no_sync:
4147   {
4148     /* report last seen timestamp if any, else ask upstream to answer */
4149     if ((*cur = basesink->priv->current_sstart) != -1)
4150       res = TRUE;
4151     else
4152       *upstream = TRUE;
4153
4154     GST_DEBUG_OBJECT (basesink, "no sync, res %d, POSITION %" GST_TIME_FORMAT,
4155         res, GST_TIME_ARGS (*cur));
4156     GST_OBJECT_UNLOCK (basesink);
4157     return res;
4158   }
4159 convert_failed:
4160   {
4161     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
4162     *upstream = TRUE;
4163     return FALSE;
4164   }
4165 }
4166
4167 static gboolean
4168 gst_base_sink_query (GstElement * element, GstQuery * query)
4169 {
4170   gboolean res = FALSE;
4171
4172   GstBaseSink *basesink = GST_BASE_SINK (element);
4173
4174   switch (GST_QUERY_TYPE (query)) {
4175     case GST_QUERY_POSITION:
4176     {
4177       gint64 cur = 0;
4178       GstFormat format;
4179       gboolean upstream = FALSE;
4180
4181       gst_query_parse_position (query, &format, NULL);
4182
4183       GST_DEBUG_OBJECT (basesink, "position format %d", format);
4184
4185       /* first try to get the position based on the clock */
4186       if ((res =
4187               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
4188         gst_query_set_position (query, format, cur);
4189       } else if (upstream) {
4190         /* fallback to peer query */
4191         res = gst_base_sink_peer_query (basesink, query);
4192       }
4193       break;
4194     }
4195     case GST_QUERY_DURATION:
4196     {
4197       GstFormat format, uformat;
4198       gint64 duration, uduration;
4199
4200       gst_query_parse_duration (query, &format, NULL);
4201
4202       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
4203           gst_format_get_name (format));
4204
4205       if (basesink->pad_mode == GST_ACTIVATE_PULL) {
4206         uformat = GST_FORMAT_BYTES;
4207
4208         /* get the duration in bytes, in pull mode that's all we are sure to
4209          * know. We have to explicitly get this value from upstream instead of
4210          * using our cached value because it might change. Duration caching
4211          * should be done at a higher level. */
4212         res = gst_pad_query_peer_duration (basesink->sinkpad, &uformat,
4213             &uduration);
4214         if (res) {
4215           gst_segment_set_duration (&basesink->segment, uformat, uduration);
4216           if (format != uformat) {
4217             /* convert to the requested format */
4218             res = gst_pad_query_convert (basesink->sinkpad, uformat, uduration,
4219                 &format, &duration);
4220           } else {
4221             duration = uduration;
4222           }
4223           if (res) {
4224             /* set the result */
4225             gst_query_set_duration (query, format, duration);
4226           }
4227         }
4228       } else {
4229         /* in push mode we simply forward upstream */
4230         res = gst_base_sink_peer_query (basesink, query);
4231       }
4232       break;
4233     }
4234     case GST_QUERY_LATENCY:
4235     {
4236       gboolean live, us_live;
4237       GstClockTime min, max;
4238
4239       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
4240                   &max))) {
4241         gst_query_set_latency (query, live, min, max);
4242       }
4243       break;
4244     }
4245     case GST_QUERY_JITTER:
4246       break;
4247     case GST_QUERY_RATE:
4248       /* gst_query_set_rate (query, basesink->segment_rate); */
4249       res = TRUE;
4250       break;
4251     case GST_QUERY_SEGMENT:
4252     {
4253       /* FIXME, bring start/stop to stream time */
4254       gst_query_set_segment (query, basesink->segment.rate,
4255           GST_FORMAT_TIME, basesink->segment.start, basesink->segment.stop);
4256       break;
4257     }
4258     case GST_QUERY_SEEKING:
4259     case GST_QUERY_CONVERT:
4260     case GST_QUERY_FORMATS:
4261     default:
4262       res = gst_base_sink_peer_query (basesink, query);
4263       break;
4264   }
4265   return res;
4266 }
4267
4268 static GstStateChangeReturn
4269 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
4270 {
4271   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
4272   GstBaseSink *basesink = GST_BASE_SINK (element);
4273   GstBaseSinkClass *bclass;
4274   GstBaseSinkPrivate *priv;
4275
4276   priv = basesink->priv;
4277
4278   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4279
4280   switch (transition) {
4281     case GST_STATE_CHANGE_NULL_TO_READY:
4282       if (bclass->start)
4283         if (!bclass->start (basesink))
4284           goto start_failed;
4285       break;
4286     case GST_STATE_CHANGE_READY_TO_PAUSED:
4287       /* need to complete preroll before this state change completes, there
4288        * is no data flow in READY so we can safely assume we need to preroll. */
4289       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4290       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
4291       basesink->have_newsegment = FALSE;
4292       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
4293       gst_segment_init (basesink->abidata.ABI.clip_segment,
4294           GST_FORMAT_UNDEFINED);
4295       basesink->offset = 0;
4296       basesink->have_preroll = FALSE;
4297       basesink->need_preroll = TRUE;
4298       basesink->playing_async = TRUE;
4299       priv->current_sstart = -1;
4300       priv->current_sstop = -1;
4301       priv->eos_rtime = -1;
4302       priv->latency = 0;
4303       basesink->eos = FALSE;
4304       priv->received_eos = FALSE;
4305       gst_base_sink_reset_qos (basesink);
4306       priv->commited = FALSE;
4307       priv->call_preroll = TRUE;
4308       priv->current_step.valid = FALSE;
4309       priv->pending_step.valid = FALSE;
4310       if (priv->async_enabled) {
4311         GST_DEBUG_OBJECT (basesink, "doing async state change");
4312         /* when async enabled, post async-start message and return ASYNC from
4313          * the state change function */
4314         ret = GST_STATE_CHANGE_ASYNC;
4315         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4316             gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4317       } else {
4318         priv->have_latency = TRUE;
4319       }
4320       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4321       break;
4322     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4323       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4324       if (!gst_base_sink_needs_preroll (basesink)) {
4325         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
4326         /* no preroll needed anymore now. */
4327         basesink->playing_async = FALSE;
4328         basesink->need_preroll = FALSE;
4329         if (basesink->eos) {
4330           GstMessage *message;
4331
4332           /* need to post EOS message here */
4333           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
4334           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
4335           gst_message_set_seqnum (message, basesink->priv->seqnum);
4336           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
4337         } else {
4338           GST_DEBUG_OBJECT (basesink, "signal preroll");
4339           GST_PAD_PREROLL_SIGNAL (basesink->sinkpad);
4340         }
4341       } else {
4342         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
4343         basesink->need_preroll = TRUE;
4344         basesink->playing_async = TRUE;
4345         priv->call_preroll = TRUE;
4346         priv->commited = FALSE;
4347         if (priv->async_enabled) {
4348           GST_DEBUG_OBJECT (basesink, "doing async state change");
4349           ret = GST_STATE_CHANGE_ASYNC;
4350           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4351               gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4352         }
4353       }
4354       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4355       break;
4356     default:
4357       break;
4358   }
4359
4360   {
4361     GstStateChangeReturn bret;
4362
4363     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4364     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
4365       goto activate_failed;
4366   }
4367
4368   switch (transition) {
4369     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4370       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
4371       /* FIXME, make sure we cannot enter _render first */
4372
4373       /* we need to call ::unlock before locking PREROLL_LOCK
4374        * since we lock it before going into ::render */
4375       if (bclass->unlock)
4376         bclass->unlock (basesink);
4377
4378       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4379       /* now that we have the PREROLL lock, clear our unlock request */
4380       if (bclass->unlock_stop)
4381         bclass->unlock_stop (basesink);
4382
4383       /* we need preroll again and we set the flag before unlocking the clockid
4384        * because if the clockid is unlocked before a current buffer expired, we
4385        * can use that buffer to preroll with */
4386       basesink->need_preroll = TRUE;
4387
4388       if (basesink->clock_id) {
4389         gst_clock_id_unschedule (basesink->clock_id);
4390       }
4391
4392       /* if we don't have a preroll buffer we need to wait for a preroll and
4393        * return ASYNC. */
4394       if (!gst_base_sink_needs_preroll (basesink)) {
4395         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
4396         basesink->playing_async = FALSE;
4397       } else {
4398         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
4399           ret = GST_STATE_CHANGE_SUCCESS;
4400         } else {
4401           GST_DEBUG_OBJECT (basesink,
4402               "PLAYING to PAUSED, we are not prerolled");
4403           basesink->playing_async = TRUE;
4404           priv->commited = FALSE;
4405           priv->call_preroll = TRUE;
4406           if (priv->async_enabled) {
4407             GST_DEBUG_OBJECT (basesink, "doing async state change");
4408             ret = GST_STATE_CHANGE_ASYNC;
4409             gst_element_post_message (GST_ELEMENT_CAST (basesink),
4410                 gst_message_new_async_start (GST_OBJECT_CAST (basesink),
4411                     FALSE));
4412           }
4413         }
4414       }
4415       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
4416           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
4417
4418       gst_base_sink_reset_qos (basesink);
4419       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4420       break;
4421     case GST_STATE_CHANGE_PAUSED_TO_READY:
4422       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4423       /* start by reseting our position state with the object lock so that the
4424        * position query gets the right idea. We do this before we post the
4425        * messages so that the message handlers pick this up. */
4426       GST_OBJECT_LOCK (basesink);
4427       basesink->have_newsegment = FALSE;
4428       priv->current_sstart = -1;
4429       priv->current_sstop = -1;
4430       priv->have_latency = FALSE;
4431       GST_OBJECT_UNLOCK (basesink);
4432
4433       gst_base_sink_set_last_buffer (basesink, NULL);
4434       priv->call_preroll = FALSE;
4435
4436       if (!priv->commited) {
4437         if (priv->async_enabled) {
4438           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
4439
4440           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4441               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
4442                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
4443
4444           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4445               gst_message_new_async_done (GST_OBJECT_CAST (basesink)));
4446         }
4447         priv->commited = TRUE;
4448       } else {
4449         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
4450       }
4451       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4452       break;
4453     case GST_STATE_CHANGE_READY_TO_NULL:
4454       if (bclass->stop) {
4455         if (!bclass->stop (basesink)) {
4456           GST_WARNING_OBJECT (basesink, "failed to stop");
4457         }
4458       }
4459       gst_base_sink_set_last_buffer (basesink, NULL);
4460       priv->call_preroll = FALSE;
4461       break;
4462     default:
4463       break;
4464   }
4465
4466   return ret;
4467
4468   /* ERRORS */
4469 start_failed:
4470   {
4471     GST_DEBUG_OBJECT (basesink, "failed to start");
4472     return GST_STATE_CHANGE_FAILURE;
4473   }
4474 activate_failed:
4475   {
4476     GST_DEBUG_OBJECT (basesink,
4477         "element failed to change states -- activation problem?");
4478     return GST_STATE_CHANGE_FAILURE;
4479   }
4480 }