basesink: small cleanups
[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;
2513   GstBaseSinkClass *bclass;
2514   gboolean late;
2515
2516   GstBaseSinkPrivate *priv;
2517
2518   priv = basesink->priv;
2519
2520   late = FALSE;
2521   ret = GST_FLOW_OK;
2522
2523   /* synchronize this object, non syncable objects return OK
2524    * immediatly. */
2525   ret = gst_base_sink_do_sync (basesink, pad, obj, &late);
2526   if (G_UNLIKELY (ret != GST_FLOW_OK))
2527     goto sync_failed;
2528
2529   /* and now render, event or buffer. */
2530   if (G_LIKELY (GST_IS_BUFFER (obj))) {
2531     GstBuffer *buf;
2532
2533     /* drop late buffers unconditionally, let's hope it's unlikely */
2534     if (G_UNLIKELY (late))
2535       goto dropped;
2536
2537     buf = GST_BUFFER_CAST (obj);
2538
2539     gst_base_sink_set_last_buffer (basesink, buf);
2540
2541     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2542
2543     if (G_LIKELY (bclass->render)) {
2544       gint do_qos;
2545
2546       /* read once, to get same value before and after */
2547       do_qos = g_atomic_int_get (&priv->qos_enabled);
2548
2549       GST_DEBUG_OBJECT (basesink, "rendering buffer %p", obj);
2550
2551       /* record rendering time for QoS and stats */
2552       if (do_qos)
2553         gst_base_sink_do_render_stats (basesink, TRUE);
2554
2555       ret = bclass->render (basesink, buf);
2556
2557       priv->rendered++;
2558
2559       if (do_qos)
2560         gst_base_sink_do_render_stats (basesink, FALSE);
2561     }
2562   } else {
2563     GstEvent *event = GST_EVENT_CAST (obj);
2564     gboolean event_res = TRUE;
2565     GstEventType type;
2566
2567     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2568
2569     type = GST_EVENT_TYPE (event);
2570
2571     GST_DEBUG_OBJECT (basesink, "rendering event %p, type %s", obj,
2572         gst_event_type_get_name (type));
2573
2574     if (bclass->event)
2575       event_res = bclass->event (basesink, event);
2576
2577     /* when we get here we could be flushing again when the event handler calls
2578      * _wait_eos(). We have to ignore this object in that case. */
2579     if (G_UNLIKELY (basesink->flushing))
2580       goto flushing;
2581
2582     if (G_LIKELY (event_res)) {
2583       guint32 seqnum;
2584
2585       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
2586       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
2587
2588       switch (type) {
2589         case GST_EVENT_EOS:
2590         {
2591           GstMessage *message;
2592
2593           /* the EOS event is completely handled so we mark
2594            * ourselves as being in the EOS state. eos is also 
2595            * protected by the object lock so we can read it when 
2596            * answering the POSITION query. */
2597           GST_OBJECT_LOCK (basesink);
2598           basesink->eos = TRUE;
2599           GST_OBJECT_UNLOCK (basesink);
2600
2601           /* ok, now we can post the message */
2602           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
2603
2604           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
2605           gst_message_set_seqnum (message, seqnum);
2606           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
2607           break;
2608         }
2609         case GST_EVENT_NEWSEGMENT:
2610           /* configure the segment */
2611           gst_base_sink_configure_segment (basesink, pad, event,
2612               &basesink->segment);
2613           break;
2614         default:
2615           break;
2616       }
2617     }
2618   }
2619
2620 done:
2621   gst_base_sink_perform_qos (basesink, late);
2622
2623   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
2624   gst_mini_object_unref (obj);
2625
2626   return ret;
2627
2628   /* ERRORS */
2629 sync_failed:
2630   {
2631     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
2632     goto done;
2633   }
2634 dropped:
2635   {
2636     priv->dropped++;
2637     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
2638     goto done;
2639   }
2640 flushing:
2641   {
2642     GST_DEBUG_OBJECT (basesink, "we are flushing, ignore object");
2643     gst_mini_object_unref (obj);
2644     return GST_FLOW_WRONG_STATE;
2645   }
2646 }
2647
2648 /* with STREAM_LOCK, PREROLL_LOCK
2649  *
2650  * Perform preroll on the given object. For buffers this means 
2651  * calling the preroll subclass method. 
2652  * If that succeeds, the state will be commited.
2653  *
2654  * function does not take ownership of obj.
2655  */
2656 static GstFlowReturn
2657 gst_base_sink_preroll_object (GstBaseSink * basesink, GstMiniObject * obj)
2658 {
2659   GstFlowReturn ret;
2660
2661   GST_DEBUG_OBJECT (basesink, "prerolling object %p", obj);
2662
2663   /* if it's a buffer, we need to call the preroll method */
2664   if (G_LIKELY (GST_IS_BUFFER (obj)) && basesink->priv->call_preroll) {
2665     GstBaseSinkClass *bclass;
2666     GstBuffer *buf;
2667     GstClockTime timestamp;
2668
2669     buf = GST_BUFFER_CAST (obj);
2670     timestamp = GST_BUFFER_TIMESTAMP (buf);
2671
2672     GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
2673         GST_TIME_ARGS (timestamp));
2674
2675     gst_base_sink_set_last_buffer (basesink, buf);
2676
2677     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2678     if (bclass->preroll)
2679       if ((ret = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
2680         goto preroll_failed;
2681
2682     basesink->priv->call_preroll = FALSE;
2683   }
2684
2685   /* commit state */
2686   if (G_LIKELY (basesink->playing_async)) {
2687     if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
2688       goto stopping;
2689   }
2690
2691   return GST_FLOW_OK;
2692
2693   /* ERRORS */
2694 preroll_failed:
2695   {
2696     GST_DEBUG_OBJECT (basesink, "preroll failed, abort state");
2697     gst_element_abort_state (GST_ELEMENT_CAST (basesink));
2698     return ret;
2699   }
2700 stopping:
2701   {
2702     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
2703     return GST_FLOW_WRONG_STATE;
2704   }
2705 }
2706
2707 /* with STREAM_LOCK, PREROLL_LOCK 
2708  *
2709  * Queue an object for rendering.
2710  * The first prerollable object queued will complete the preroll. If the
2711  * preroll queue if filled, we render all the objects in the queue.
2712  *
2713  * This function takes ownership of the object.
2714  */
2715 static GstFlowReturn
2716 gst_base_sink_queue_object_unlocked (GstBaseSink * basesink, GstPad * pad,
2717     GstMiniObject * obj, gboolean prerollable)
2718 {
2719   GstFlowReturn ret = GST_FLOW_OK;
2720   gint length;
2721   GQueue *q;
2722
2723   if (G_UNLIKELY (basesink->need_preroll)) {
2724     if (G_LIKELY (prerollable))
2725       basesink->preroll_queued++;
2726
2727     length = basesink->preroll_queued;
2728
2729     GST_DEBUG_OBJECT (basesink, "now %d prerolled items", length);
2730
2731     /* first prerollable item needs to finish the preroll */
2732     if (length == 1) {
2733       ret = gst_base_sink_preroll_object (basesink, obj);
2734       if (G_UNLIKELY (ret != GST_FLOW_OK))
2735         goto preroll_failed;
2736     }
2737     /* need to recheck if we need preroll, commmit state during preroll 
2738      * could have made us not need more preroll. */
2739     if (G_UNLIKELY (basesink->need_preroll)) {
2740       /* see if we can render now, if we can't add the object to the preroll
2741        * queue. */
2742       if (G_UNLIKELY (length <= basesink->preroll_queue_max_len))
2743         goto more_preroll;
2744     }
2745   }
2746
2747   /* we can start rendering (or blocking) the queued object
2748    * if any. */
2749   q = basesink->preroll_queue;
2750   while (G_UNLIKELY (!g_queue_is_empty (q))) {
2751     GstMiniObject *o;
2752
2753     o = g_queue_pop_head (q);
2754     GST_DEBUG_OBJECT (basesink, "rendering queued object %p", o);
2755
2756     /* do something with the return value */
2757     ret = gst_base_sink_render_object (basesink, pad, o);
2758     if (ret != GST_FLOW_OK)
2759       goto dequeue_failed;
2760   }
2761
2762   /* now render the object */
2763   ret = gst_base_sink_render_object (basesink, pad, obj);
2764   basesink->preroll_queued = 0;
2765
2766   return ret;
2767
2768   /* special cases */
2769 preroll_failed:
2770   {
2771     GST_DEBUG_OBJECT (basesink, "preroll failed, reason %s",
2772         gst_flow_get_name (ret));
2773     gst_mini_object_unref (obj);
2774     return ret;
2775   }
2776 more_preroll:
2777   {
2778     /* add object to the queue and return */
2779     GST_DEBUG_OBJECT (basesink, "need more preroll data %d <= %d",
2780         length, basesink->preroll_queue_max_len);
2781     g_queue_push_tail (basesink->preroll_queue, obj);
2782     return GST_FLOW_OK;
2783   }
2784 dequeue_failed:
2785   {
2786     GST_DEBUG_OBJECT (basesink, "rendering queued objects failed, reason %s",
2787         gst_flow_get_name (ret));
2788     gst_mini_object_unref (obj);
2789     return ret;
2790   }
2791 }
2792
2793 /* with STREAM_LOCK
2794  *
2795  * This function grabs the PREROLL_LOCK and adds the object to
2796  * the queue.
2797  *
2798  * This function takes ownership of obj.
2799  */
2800 static GstFlowReturn
2801 gst_base_sink_queue_object (GstBaseSink * basesink, GstPad * pad,
2802     GstMiniObject * obj, gboolean prerollable)
2803 {
2804   GstFlowReturn ret;
2805
2806   GST_PAD_PREROLL_LOCK (pad);
2807   if (G_UNLIKELY (basesink->flushing))
2808     goto flushing;
2809
2810   if (G_UNLIKELY (basesink->priv->received_eos))
2811     goto was_eos;
2812
2813   ret = gst_base_sink_queue_object_unlocked (basesink, pad, obj, prerollable);
2814   GST_PAD_PREROLL_UNLOCK (pad);
2815
2816   return ret;
2817
2818   /* ERRORS */
2819 flushing:
2820   {
2821     GST_DEBUG_OBJECT (basesink, "sink is flushing");
2822     GST_PAD_PREROLL_UNLOCK (pad);
2823     gst_mini_object_unref (obj);
2824     return GST_FLOW_WRONG_STATE;
2825   }
2826 was_eos:
2827   {
2828     GST_DEBUG_OBJECT (basesink,
2829         "we are EOS, dropping object, return UNEXPECTED");
2830     GST_PAD_PREROLL_UNLOCK (pad);
2831     gst_mini_object_unref (obj);
2832     return GST_FLOW_UNEXPECTED;
2833   }
2834 }
2835
2836 static void
2837 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
2838 {
2839   /* make sure we are not blocked on the clock also clear any pending
2840    * eos state. */
2841   gst_base_sink_set_flushing (basesink, pad, TRUE);
2842
2843   /* we grab the stream lock but that is not needed since setting the
2844    * sink to flushing would make sure no state commit is being done
2845    * anymore */
2846   GST_PAD_STREAM_LOCK (pad);
2847   gst_base_sink_reset_qos (basesink);
2848   if (basesink->priv->async_enabled) {
2849     /* and we need to commit our state again on the next
2850      * prerolled buffer */
2851     basesink->playing_async = TRUE;
2852     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
2853   } else {
2854     basesink->priv->have_latency = TRUE;
2855     basesink->need_preroll = FALSE;
2856   }
2857   gst_base_sink_set_last_buffer (basesink, NULL);
2858   GST_PAD_STREAM_UNLOCK (pad);
2859 }
2860
2861 static void
2862 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad)
2863 {
2864   /* unset flushing so we can accept new data, this also flushes out any EOS
2865    * event. */
2866   gst_base_sink_set_flushing (basesink, pad, FALSE);
2867
2868   /* for position reporting */
2869   GST_OBJECT_LOCK (basesink);
2870   basesink->priv->current_sstart = -1;
2871   basesink->priv->current_sstop = -1;
2872   basesink->priv->eos_rtime = -1;
2873   basesink->priv->call_preroll = TRUE;
2874   if (basesink->pad_mode == GST_ACTIVATE_PUSH) {
2875     /* we need new segment info after the flush. */
2876     basesink->have_newsegment = FALSE;
2877     gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
2878     gst_segment_init (basesink->abidata.ABI.clip_segment, GST_FORMAT_UNDEFINED);
2879   }
2880   GST_OBJECT_UNLOCK (basesink);
2881 }
2882
2883 static gboolean
2884 gst_base_sink_event (GstPad * pad, GstEvent * event)
2885 {
2886   GstBaseSink *basesink;
2887   gboolean result = TRUE;
2888   GstBaseSinkClass *bclass;
2889
2890   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
2891
2892   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2893
2894   GST_DEBUG_OBJECT (basesink, "event %p (%s)", event,
2895       GST_EVENT_TYPE_NAME (event));
2896
2897   switch (GST_EVENT_TYPE (event)) {
2898     case GST_EVENT_EOS:
2899     {
2900       GstFlowReturn ret;
2901
2902       GST_PAD_PREROLL_LOCK (pad);
2903       if (G_UNLIKELY (basesink->flushing))
2904         goto flushing;
2905
2906       if (G_UNLIKELY (basesink->priv->received_eos)) {
2907         /* we can't accept anything when we are EOS */
2908         result = FALSE;
2909         gst_event_unref (event);
2910       } else {
2911         /* we set the received EOS flag here so that we can use it when testing if
2912          * we are prerolled and to refuse more buffers. */
2913         basesink->priv->received_eos = TRUE;
2914
2915         /* EOS is a prerollable object, we call the unlocked version because it
2916          * does not check the received_eos flag. */
2917         ret = gst_base_sink_queue_object_unlocked (basesink, pad,
2918             GST_MINI_OBJECT_CAST (event), TRUE);
2919         if (G_UNLIKELY (ret != GST_FLOW_OK))
2920           result = FALSE;
2921       }
2922       GST_PAD_PREROLL_UNLOCK (pad);
2923       break;
2924     }
2925     case GST_EVENT_NEWSEGMENT:
2926     {
2927       GstFlowReturn ret;
2928
2929       GST_DEBUG_OBJECT (basesink, "newsegment %p", event);
2930
2931       GST_PAD_PREROLL_LOCK (pad);
2932       if (G_UNLIKELY (basesink->flushing))
2933         goto flushing;
2934
2935       if (G_UNLIKELY (basesink->priv->received_eos)) {
2936         /* we can't accept anything when we are EOS */
2937         result = FALSE;
2938         gst_event_unref (event);
2939       } else {
2940         /* the new segment is a non prerollable item and does not block anything,
2941          * we need to configure the current clipping segment and insert the event 
2942          * in the queue to serialize it with the buffers for rendering. */
2943         gst_base_sink_configure_segment (basesink, pad, event,
2944             basesink->abidata.ABI.clip_segment);
2945
2946         ret =
2947             gst_base_sink_queue_object_unlocked (basesink, pad,
2948             GST_MINI_OBJECT_CAST (event), FALSE);
2949         if (G_UNLIKELY (ret != GST_FLOW_OK))
2950           result = FALSE;
2951         else {
2952           GST_OBJECT_LOCK (basesink);
2953           basesink->have_newsegment = TRUE;
2954           GST_OBJECT_UNLOCK (basesink);
2955         }
2956       }
2957       GST_PAD_PREROLL_UNLOCK (pad);
2958       break;
2959     }
2960     case GST_EVENT_FLUSH_START:
2961       if (bclass->event)
2962         bclass->event (basesink, event);
2963
2964       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
2965
2966       gst_base_sink_flush_start (basesink, pad);
2967
2968       gst_event_unref (event);
2969       break;
2970     case GST_EVENT_FLUSH_STOP:
2971       if (bclass->event)
2972         bclass->event (basesink, event);
2973
2974       GST_DEBUG_OBJECT (basesink, "flush-stop %p", event);
2975
2976       gst_base_sink_flush_stop (basesink, pad);
2977
2978       gst_event_unref (event);
2979       break;
2980     default:
2981       /* other events are sent to queue or subclass depending on if they
2982        * are serialized. */
2983       if (GST_EVENT_IS_SERIALIZED (event)) {
2984         gst_base_sink_queue_object (basesink, pad,
2985             GST_MINI_OBJECT_CAST (event), FALSE);
2986       } else {
2987         if (bclass->event)
2988           bclass->event (basesink, event);
2989         gst_event_unref (event);
2990       }
2991       break;
2992   }
2993 done:
2994   gst_object_unref (basesink);
2995
2996   return result;
2997
2998   /* ERRORS */
2999 flushing:
3000   {
3001     GST_DEBUG_OBJECT (basesink, "we are flushing");
3002     GST_PAD_PREROLL_UNLOCK (pad);
3003     result = FALSE;
3004     gst_event_unref (event);
3005     goto done;
3006   }
3007 }
3008
3009 /* default implementation to calculate the start and end
3010  * timestamps on a buffer, subclasses can override
3011  */
3012 static void
3013 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
3014     GstClockTime * start, GstClockTime * end)
3015 {
3016   GstClockTime timestamp, duration;
3017
3018   timestamp = GST_BUFFER_TIMESTAMP (buffer);
3019   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
3020
3021     /* get duration to calculate end time */
3022     duration = GST_BUFFER_DURATION (buffer);
3023     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3024       *end = timestamp + duration;
3025     }
3026     *start = timestamp;
3027   }
3028 }
3029
3030 /* must be called with PREROLL_LOCK */
3031 static gboolean
3032 gst_base_sink_needs_preroll (GstBaseSink * basesink)
3033 {
3034   gboolean is_prerolled, res;
3035
3036   /* we have 2 cases where the PREROLL_LOCK is released:
3037    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
3038    *  2) we are syncing on the clock
3039    */
3040   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
3041   res = !is_prerolled;
3042
3043   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
3044       basesink->have_preroll, basesink->priv->received_eos, res);
3045
3046   return res;
3047 }
3048
3049 /* with STREAM_LOCK, PREROLL_LOCK 
3050  *
3051  * Takes a buffer and compare the timestamps with the last segment.
3052  * If the buffer falls outside of the segment boundaries, drop it.
3053  * Else queue the buffer for preroll and rendering.
3054  *
3055  * This function takes ownership of the buffer.
3056  */
3057 static GstFlowReturn
3058 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
3059     GstBuffer * buf)
3060 {
3061   GstBaseSinkClass *bclass;
3062   GstFlowReturn result;
3063   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
3064   GstSegment *clip_segment;
3065
3066   if (G_UNLIKELY (basesink->flushing))
3067     goto flushing;
3068
3069   if (G_UNLIKELY (basesink->priv->received_eos))
3070     goto was_eos;
3071
3072   /* for code clarity */
3073   clip_segment = basesink->abidata.ABI.clip_segment;
3074
3075   if (G_UNLIKELY (!basesink->have_newsegment)) {
3076     gboolean sync;
3077
3078     sync = gst_base_sink_get_sync (basesink);
3079     if (sync) {
3080       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
3081           (_("Internal data flow problem.")),
3082           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
3083     }
3084
3085     /* this means this sink will assume timestamps start from 0 */
3086     GST_OBJECT_LOCK (basesink);
3087     clip_segment->start = 0;
3088     clip_segment->stop = -1;
3089     basesink->segment.start = 0;
3090     basesink->segment.stop = -1;
3091     basesink->have_newsegment = TRUE;
3092     GST_OBJECT_UNLOCK (basesink);
3093   }
3094
3095   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3096
3097   /* check if the buffer needs to be dropped, we first ask the subclass for the
3098    * start and end */
3099   if (bclass->get_times)
3100     bclass->get_times (basesink, buf, &start, &end);
3101
3102   if (start == -1) {
3103     /* if the subclass does not want sync, we use our own values so that we at
3104      * least clip the buffer to the segment */
3105     gst_base_sink_get_times (basesink, buf, &start, &end);
3106   }
3107
3108   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
3109       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
3110
3111   /* a dropped buffer does not participate in anything */
3112   if (GST_CLOCK_TIME_IS_VALID (start) &&
3113       (clip_segment->format == GST_FORMAT_TIME)) {
3114     if (G_UNLIKELY (!gst_segment_clip (clip_segment,
3115                 GST_FORMAT_TIME, (gint64) start, (gint64) end, NULL, NULL)))
3116       goto out_of_segment;
3117   }
3118
3119   /* now we can process the buffer in the queue, this function takes ownership
3120    * of the buffer */
3121   result = gst_base_sink_queue_object_unlocked (basesink, pad,
3122       GST_MINI_OBJECT_CAST (buf), TRUE);
3123
3124   return result;
3125
3126   /* ERRORS */
3127 flushing:
3128   {
3129     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3130     gst_buffer_unref (buf);
3131     return GST_FLOW_WRONG_STATE;
3132   }
3133 was_eos:
3134   {
3135     GST_DEBUG_OBJECT (basesink,
3136         "we are EOS, dropping object, return UNEXPECTED");
3137     gst_buffer_unref (buf);
3138     return GST_FLOW_UNEXPECTED;
3139   }
3140 out_of_segment:
3141   {
3142     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
3143     gst_buffer_unref (buf);
3144     return GST_FLOW_OK;
3145   }
3146 }
3147
3148 /* with STREAM_LOCK
3149  */
3150 static GstFlowReturn
3151 gst_base_sink_chain (GstPad * pad, GstBuffer * buf)
3152 {
3153   GstBaseSink *basesink;
3154   GstFlowReturn result;
3155
3156   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3157
3158   if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH))
3159     goto wrong_mode;
3160
3161   GST_PAD_PREROLL_LOCK (pad);
3162   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
3163   GST_PAD_PREROLL_UNLOCK (pad);
3164
3165 done:
3166   return result;
3167
3168   /* ERRORS */
3169 wrong_mode:
3170   {
3171     GST_OBJECT_LOCK (pad);
3172     GST_WARNING_OBJECT (basesink,
3173         "Push on pad %s:%s, but it was not activated in push mode",
3174         GST_DEBUG_PAD_NAME (pad));
3175     GST_OBJECT_UNLOCK (pad);
3176     gst_buffer_unref (buf);
3177     /* we don't post an error message this will signal to the peer
3178      * pushing that EOS is reached. */
3179     result = GST_FLOW_UNEXPECTED;
3180     goto done;
3181   }
3182 }
3183
3184 static gboolean
3185 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
3186 {
3187   gboolean res = TRUE;
3188
3189   /* update our offset if the start/stop position was updated */
3190   if (segment->format == GST_FORMAT_BYTES) {
3191     segment->time = segment->start;
3192   } else if (segment->start == 0) {
3193     /* seek to start, we can implement a default for this. */
3194     segment->time = 0;
3195   } else {
3196     res = FALSE;
3197     GST_INFO_OBJECT (sink, "Can't do a default seek");
3198   }
3199
3200   return res;
3201 }
3202
3203 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
3204
3205 static gboolean
3206 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3207     GstEvent * event, GstSegment * segment)
3208 {
3209   /* By default, we try one of 2 things:
3210    *   - For absolute seek positions, convert the requested position to our 
3211    *     configured processing format and place it in the output segment \
3212    *   - For relative seek positions, convert our current (input) values to the
3213    *     seek format, adjust by the relative seek offset and then convert back to
3214    *     the processing format
3215    */
3216   GstSeekType cur_type, stop_type;
3217   gint64 cur, stop;
3218   GstSeekFlags flags;
3219   GstFormat seek_format, dest_format;
3220   gdouble rate;
3221   gboolean update;
3222   gboolean res = TRUE;
3223
3224   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3225       &cur_type, &cur, &stop_type, &stop);
3226   dest_format = segment->format;
3227
3228   if (seek_format == dest_format) {
3229     gst_segment_set_seek (segment, rate, seek_format, flags,
3230         cur_type, cur, stop_type, stop, &update);
3231     return TRUE;
3232   }
3233
3234   if (cur_type != GST_SEEK_TYPE_NONE) {
3235     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3236     res =
3237         gst_pad_query_convert (sink->sinkpad, seek_format, cur, &dest_format,
3238         &cur);
3239     cur_type = GST_SEEK_TYPE_SET;
3240   }
3241
3242   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3243     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3244     res =
3245         gst_pad_query_convert (sink->sinkpad, seek_format, stop, &dest_format,
3246         &stop);
3247     stop_type = GST_SEEK_TYPE_SET;
3248   }
3249
3250   /* And finally, configure our output segment in the desired format */
3251   gst_segment_set_seek (segment, rate, dest_format, flags, cur_type, cur,
3252       stop_type, stop, &update);
3253
3254   if (!res)
3255     goto no_format;
3256
3257   return res;
3258
3259 no_format:
3260   {
3261     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3262     return FALSE;
3263   }
3264 }
3265
3266 /* perform a seek, only executed in pull mode */
3267 static gboolean
3268 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3269 {
3270   gboolean flush;
3271   gdouble rate;
3272   GstFormat seek_format, dest_format;
3273   GstSeekFlags flags;
3274   GstSeekType cur_type, stop_type;
3275   gboolean seekseg_configured = FALSE;
3276   gint64 cur, stop;
3277   gboolean update, res = TRUE;
3278   GstSegment seeksegment;
3279
3280   dest_format = sink->segment.format;
3281
3282   if (event) {
3283     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3284     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3285         &cur_type, &cur, &stop_type, &stop);
3286
3287     flush = flags & GST_SEEK_FLAG_FLUSH;
3288   } else {
3289     GST_DEBUG_OBJECT (sink, "performing seek without event");
3290     flush = FALSE;
3291   }
3292
3293   if (flush) {
3294     GST_DEBUG_OBJECT (sink, "flushing upstream");
3295     gst_pad_push_event (pad, gst_event_new_flush_start ());
3296     gst_base_sink_flush_start (sink, pad);
3297   } else {
3298     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3299   }
3300
3301   GST_PAD_STREAM_LOCK (pad);
3302
3303   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3304    * copy the current segment info into the temp segment that we can actually
3305    * attempt the seek with. We only update the real segment if the seek suceeds. */
3306   if (!seekseg_configured) {
3307     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3308
3309     /* now configure the final seek segment */
3310     if (event) {
3311       if (sink->segment.format != seek_format) {
3312         /* OK, here's where we give the subclass a chance to convert the relative
3313          * seek into an absolute one in the processing format. We set up any
3314          * absolute seek above, before taking the stream lock. */
3315         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3316                 &seeksegment)) {
3317           GST_DEBUG_OBJECT (sink,
3318               "Preparing the seek failed after flushing. " "Aborting seek");
3319           res = FALSE;
3320         }
3321       } else {
3322         /* The seek format matches our processing format, no need to ask the
3323          * the subclass to configure the segment. */
3324         gst_segment_set_seek (&seeksegment, rate, seek_format, flags,
3325             cur_type, cur, stop_type, stop, &update);
3326       }
3327     }
3328     /* Else, no seek event passed, so we're just (re)starting the 
3329        current segment. */
3330   }
3331
3332   if (res) {
3333     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3334         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3335         seeksegment.start, seeksegment.stop, seeksegment.last_stop);
3336
3337     /* do the seek, segment.last_stop contains the new position. */
3338     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3339   }
3340
3341
3342   if (flush) {
3343     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3344     gst_pad_push_event (pad, gst_event_new_flush_stop ());
3345     gst_base_sink_flush_stop (sink, pad);
3346   } else if (res && sink->abidata.ABI.running) {
3347     /* we are running the current segment and doing a non-flushing seek, 
3348      * close the segment first based on the last_stop. */
3349     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3350         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.last_stop);
3351   }
3352
3353   /* The subclass must have converted the segment to the processing format 
3354    * by now */
3355   if (res && seeksegment.format != dest_format) {
3356     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3357         "in the correct format. Aborting seek.");
3358     res = FALSE;
3359   }
3360
3361   /* if successfull seek, we update our real segment and push
3362    * out the new segment. */
3363   if (res) {
3364     memcpy (&sink->segment, &seeksegment, sizeof (GstSegment));
3365
3366     if (sink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3367       gst_element_post_message (GST_ELEMENT (sink),
3368           gst_message_new_segment_start (GST_OBJECT (sink),
3369               sink->segment.format, sink->segment.last_stop));
3370     }
3371   }
3372
3373   sink->priv->discont = TRUE;
3374   sink->abidata.ABI.running = TRUE;
3375
3376   GST_PAD_STREAM_UNLOCK (pad);
3377
3378   return res;
3379 }
3380
3381 static gboolean
3382 gst_base_sink_perform_step (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3383 {
3384   GstBaseSinkPrivate *priv;
3385   GstBaseSinkClass *bclass;
3386   gboolean flush, intermediate;
3387   gdouble rate;
3388   GstFormat format;
3389   guint64 amount;
3390   guint seqnum;
3391   GstStepInfo *pending;
3392
3393   bclass = GST_BASE_SINK_GET_CLASS (sink);
3394   priv = sink->priv;
3395
3396   GST_DEBUG_OBJECT (sink, "performing step with event %p", event);
3397
3398   gst_event_parse_step (event, &format, &amount, &rate, &flush, &intermediate);
3399   seqnum = gst_event_get_seqnum (event);
3400
3401   pending = &priv->pending_step;
3402
3403   if (flush) {
3404     /* we need to call ::unlock before locking PREROLL_LOCK
3405      * since we lock it before going into ::render */
3406     if (bclass->unlock)
3407       bclass->unlock (sink);
3408
3409     GST_PAD_PREROLL_LOCK (sink->sinkpad);
3410     /* update the segment */
3411     pending->seqnum = seqnum;
3412     pending->format = format;
3413     pending->amount = amount;
3414     pending->position = 0;
3415     pending->rate = rate;
3416     pending->flush = flush;
3417     pending->intermediate = intermediate;
3418     pending->valid = TRUE;
3419
3420     /* now that we have the PREROLL lock, clear our unlock request */
3421     if (bclass->unlock_stop)
3422       bclass->unlock_stop (sink);
3423
3424     if (sink->priv->async_enabled) {
3425       /* and we need to commit our state again on the next
3426        * prerolled buffer */
3427       sink->playing_async = TRUE;
3428       priv->pending_step.need_preroll = TRUE;
3429       sink->need_preroll = FALSE;
3430       gst_element_lost_state_full (GST_ELEMENT_CAST (sink), FALSE);
3431     } else {
3432       sink->priv->have_latency = TRUE;
3433       sink->need_preroll = FALSE;
3434     }
3435     priv->call_preroll = TRUE;
3436     gst_base_sink_set_last_buffer (sink, NULL);
3437     gst_base_sink_reset_qos (sink);
3438
3439     if (sink->clock_id) {
3440       gst_clock_id_unschedule (sink->clock_id);
3441     }
3442
3443     GST_DEBUG_OBJECT (sink, "signal waiter");
3444     GST_PAD_PREROLL_SIGNAL (sink->sinkpad);
3445
3446     GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
3447   }
3448
3449   return TRUE;
3450 }
3451
3452 /* with STREAM_LOCK
3453  */
3454 static void
3455 gst_base_sink_loop (GstPad * pad)
3456 {
3457   GstBaseSink *basesink;
3458   GstBuffer *buf = NULL;
3459   GstFlowReturn result;
3460   guint blocksize;
3461   guint64 offset;
3462
3463   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3464
3465   g_assert (basesink->pad_mode == GST_ACTIVATE_PULL);
3466
3467   if ((blocksize = basesink->priv->blocksize) == 0)
3468     blocksize = -1;
3469
3470   offset = basesink->segment.last_stop;
3471
3472   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
3473       offset, blocksize);
3474
3475   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
3476   if (G_UNLIKELY (result != GST_FLOW_OK))
3477     goto paused;
3478
3479   if (G_UNLIKELY (buf == NULL))
3480     goto no_buffer;
3481
3482   offset += GST_BUFFER_SIZE (buf);
3483
3484   gst_segment_set_last_stop (&basesink->segment, GST_FORMAT_BYTES, offset);
3485
3486   GST_PAD_PREROLL_LOCK (pad);
3487   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
3488   GST_PAD_PREROLL_UNLOCK (pad);
3489   if (G_UNLIKELY (result != GST_FLOW_OK))
3490     goto paused;
3491
3492   return;
3493
3494   /* ERRORS */
3495 paused:
3496   {
3497     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
3498         gst_flow_get_name (result));
3499     gst_pad_pause_task (pad);
3500     /* fatal errors and NOT_LINKED cause EOS */
3501     if (GST_FLOW_IS_FATAL (result) || result == GST_FLOW_NOT_LINKED) {
3502       if (result == GST_FLOW_UNEXPECTED) {
3503         /* perform EOS logic */
3504         if (basesink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3505           gst_element_post_message (GST_ELEMENT_CAST (basesink),
3506               gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
3507                   basesink->segment.format, basesink->segment.last_stop));
3508         } else {
3509           gst_base_sink_event (pad, gst_event_new_eos ());
3510         }
3511       } else {
3512         /* for fatal errors we post an error message, post the error
3513          * first so the app knows about the error first. */
3514         GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3515             (_("Internal data stream error.")),
3516             ("stream stopped, reason %s", gst_flow_get_name (result)));
3517         gst_base_sink_event (pad, gst_event_new_eos ());
3518       }
3519     }
3520     return;
3521   }
3522 no_buffer:
3523   {
3524     GST_LOG_OBJECT (basesink, "no buffer, pausing");
3525     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3526         (_("Internal data flow error.")), ("element returned NULL buffer"));
3527     result = GST_FLOW_ERROR;
3528     goto paused;
3529   }
3530 }
3531
3532 static gboolean
3533 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
3534     gboolean flushing)
3535 {
3536   GstBaseSinkClass *bclass;
3537
3538   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3539
3540   if (flushing) {
3541     /* unlock any subclasses, we need to do this before grabbing the
3542      * PREROLL_LOCK since we hold this lock before going into ::render. */
3543     if (bclass->unlock)
3544       bclass->unlock (basesink);
3545   }
3546
3547   GST_PAD_PREROLL_LOCK (pad);
3548   basesink->flushing = flushing;
3549   if (flushing) {
3550     /* step 1, now that we have the PREROLL lock, clear our unlock request */
3551     if (bclass->unlock_stop)
3552       bclass->unlock_stop (basesink);
3553
3554     /* set need_preroll before we unblock the clock. If the clock is unblocked
3555      * before timing out, we can reuse the buffer for preroll. */
3556     basesink->need_preroll = TRUE;
3557
3558     /* step 2, unblock clock sync (if any) or any other blocking thing */
3559     if (basesink->clock_id) {
3560       gst_clock_id_unschedule (basesink->clock_id);
3561     }
3562
3563     /* flush out the data thread if it's locked in finish_preroll, this will
3564      * also flush out the EOS state */
3565     GST_DEBUG_OBJECT (basesink,
3566         "flushing out data thread, need preroll to TRUE");
3567     gst_base_sink_preroll_queue_flush (basesink, pad);
3568   }
3569   GST_PAD_PREROLL_UNLOCK (pad);
3570
3571   return TRUE;
3572 }
3573
3574 static gboolean
3575 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
3576 {
3577   gboolean result;
3578
3579   if (active) {
3580     /* start task */
3581     result = gst_pad_start_task (basesink->sinkpad,
3582         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad);
3583   } else {
3584     /* step 2, make sure streaming finishes */
3585     result = gst_pad_stop_task (basesink->sinkpad);
3586   }
3587
3588   return result;
3589 }
3590
3591 static gboolean
3592 gst_base_sink_pad_activate (GstPad * pad)
3593 {
3594   gboolean result = FALSE;
3595   GstBaseSink *basesink;
3596
3597   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3598
3599   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
3600
3601   gst_base_sink_set_flushing (basesink, pad, FALSE);
3602
3603   /* we need to have the pull mode enabled */
3604   if (!basesink->can_activate_pull) {
3605     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
3606     goto fallback;
3607   }
3608
3609   /* check if downstreams supports pull mode at all */
3610   if (!gst_pad_check_pull_range (pad)) {
3611     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
3612     goto fallback;
3613   }
3614
3615   /* set the pad mode before starting the task so that it's in the
3616    * correct state for the new thread. also the sink set_caps and get_caps
3617    * function checks this */
3618   basesink->pad_mode = GST_ACTIVATE_PULL;
3619
3620   /* we first try to negotiate a format so that when we try to activate
3621    * downstream, it knows about our format */
3622   if (!gst_base_sink_negotiate_pull (basesink)) {
3623     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
3624     goto fallback;
3625   }
3626
3627   /* ok activate now */
3628   if (!gst_pad_activate_pull (pad, TRUE)) {
3629     /* clear any pending caps */
3630     GST_OBJECT_LOCK (basesink);
3631     gst_caps_replace (&basesink->priv->pull_caps, NULL);
3632     GST_OBJECT_UNLOCK (basesink);
3633     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
3634     goto fallback;
3635   }
3636
3637   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
3638   result = TRUE;
3639   goto done;
3640
3641   /* push mode fallback */
3642 fallback:
3643   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
3644   if ((result = gst_pad_activate_push (pad, TRUE))) {
3645     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
3646   }
3647
3648 done:
3649   if (!result) {
3650     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
3651     gst_base_sink_set_flushing (basesink, pad, TRUE);
3652   }
3653
3654   gst_object_unref (basesink);
3655
3656   return result;
3657 }
3658
3659 static gboolean
3660 gst_base_sink_pad_activate_push (GstPad * pad, gboolean active)
3661 {
3662   gboolean result;
3663   GstBaseSink *basesink;
3664
3665   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3666
3667   if (active) {
3668     if (!basesink->can_activate_push) {
3669       result = FALSE;
3670       basesink->pad_mode = GST_ACTIVATE_NONE;
3671     } else {
3672       result = TRUE;
3673       basesink->pad_mode = GST_ACTIVATE_PUSH;
3674     }
3675   } else {
3676     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH)) {
3677       g_warning ("Internal GStreamer activation error!!!");
3678       result = FALSE;
3679     } else {
3680       gst_base_sink_set_flushing (basesink, pad, TRUE);
3681       result = TRUE;
3682       basesink->pad_mode = GST_ACTIVATE_NONE;
3683     }
3684   }
3685
3686   gst_object_unref (basesink);
3687
3688   return result;
3689 }
3690
3691 static gboolean
3692 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
3693 {
3694   GstCaps *caps;
3695   gboolean result;
3696
3697   result = FALSE;
3698
3699   /* this returns the intersection between our caps and the peer caps. If there
3700    * is no peer, it returns NULL and we can't operate in pull mode so we can
3701    * fail the negotiation. */
3702   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
3703   if (caps == NULL || gst_caps_is_empty (caps))
3704     goto no_caps_possible;
3705
3706   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
3707
3708   caps = gst_caps_make_writable (caps);
3709   /* get the first (prefered) format */
3710   gst_caps_truncate (caps);
3711   /* try to fixate */
3712   gst_pad_fixate_caps (GST_BASE_SINK_PAD (basesink), caps);
3713
3714   GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
3715
3716   if (gst_caps_is_any (caps)) {
3717     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
3718         "allowing pull()");
3719     /* neither side has template caps in this case, so they are prepared for
3720        pull() without setcaps() */
3721     result = TRUE;
3722   } else if (gst_caps_is_fixed (caps)) {
3723     if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
3724       goto could_not_set_caps;
3725
3726     GST_OBJECT_LOCK (basesink);
3727     gst_caps_replace (&basesink->priv->pull_caps, caps);
3728     GST_OBJECT_UNLOCK (basesink);
3729
3730     result = TRUE;
3731   }
3732
3733   gst_caps_unref (caps);
3734
3735   return result;
3736
3737 no_caps_possible:
3738   {
3739     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
3740     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
3741     if (caps)
3742       gst_caps_unref (caps);
3743     return FALSE;
3744   }
3745 could_not_set_caps:
3746   {
3747     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
3748     gst_caps_unref (caps);
3749     return FALSE;
3750   }
3751 }
3752
3753 /* this won't get called until we implement an activate function */
3754 static gboolean
3755 gst_base_sink_pad_activate_pull (GstPad * pad, gboolean active)
3756 {
3757   gboolean result = FALSE;
3758   GstBaseSink *basesink;
3759   GstBaseSinkClass *bclass;
3760
3761   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3762   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3763
3764   if (active) {
3765     GstFormat format;
3766     gint64 duration;
3767
3768     /* we mark we have a newsegment here because pull based
3769      * mode works just fine without having a newsegment before the
3770      * first buffer */
3771     format = GST_FORMAT_BYTES;
3772
3773     gst_segment_init (&basesink->segment, format);
3774     gst_segment_init (basesink->abidata.ABI.clip_segment, format);
3775     GST_OBJECT_LOCK (basesink);
3776     basesink->have_newsegment = TRUE;
3777     GST_OBJECT_UNLOCK (basesink);
3778
3779     /* get the peer duration in bytes */
3780     result = gst_pad_query_peer_duration (pad, &format, &duration);
3781     if (result) {
3782       GST_DEBUG_OBJECT (basesink,
3783           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
3784       gst_segment_set_duration (basesink->abidata.ABI.clip_segment, format,
3785           duration);
3786       gst_segment_set_duration (&basesink->segment, format, duration);
3787     } else {
3788       GST_DEBUG_OBJECT (basesink, "unknown duration");
3789     }
3790
3791     if (bclass->activate_pull)
3792       result = bclass->activate_pull (basesink, TRUE);
3793     else
3794       result = FALSE;
3795
3796     if (!result)
3797       goto activate_failed;
3798
3799   } else {
3800     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PULL)) {
3801       g_warning ("Internal GStreamer activation error!!!");
3802       result = FALSE;
3803     } else {
3804       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
3805       if (bclass->activate_pull)
3806         result &= bclass->activate_pull (basesink, FALSE);
3807       basesink->pad_mode = GST_ACTIVATE_NONE;
3808       /* clear any pending caps */
3809       GST_OBJECT_LOCK (basesink);
3810       gst_caps_replace (&basesink->priv->pull_caps, NULL);
3811       GST_OBJECT_UNLOCK (basesink);
3812     }
3813   }
3814   gst_object_unref (basesink);
3815
3816   return result;
3817
3818   /* ERRORS */
3819 activate_failed:
3820   {
3821     /* reset, as starting the thread failed */
3822     basesink->pad_mode = GST_ACTIVATE_NONE;
3823
3824     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
3825     return FALSE;
3826   }
3827 }
3828
3829 /* send an event to our sinkpad peer. */
3830 static gboolean
3831 gst_base_sink_send_event (GstElement * element, GstEvent * event)
3832 {
3833   GstPad *pad;
3834   GstBaseSink *basesink = GST_BASE_SINK (element);
3835   gboolean forward, result = TRUE;
3836   GstActivateMode mode;
3837
3838   GST_OBJECT_LOCK (element);
3839   /* get the pad and the scheduling mode */
3840   pad = gst_object_ref (basesink->sinkpad);
3841   mode = basesink->pad_mode;
3842   GST_OBJECT_UNLOCK (element);
3843
3844   /* only push UPSTREAM events upstream */
3845   forward = GST_EVENT_IS_UPSTREAM (event);
3846
3847   switch (GST_EVENT_TYPE (event)) {
3848     case GST_EVENT_LATENCY:
3849     {
3850       GstClockTime latency;
3851
3852       gst_event_parse_latency (event, &latency);
3853
3854       /* store the latency. We use this to adjust the running_time before syncing
3855        * it to the clock. */
3856       GST_OBJECT_LOCK (element);
3857       basesink->priv->latency = latency;
3858       if (!basesink->priv->have_latency)
3859         forward = FALSE;
3860       GST_OBJECT_UNLOCK (element);
3861       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
3862           GST_TIME_ARGS (latency));
3863
3864       /* We forward this event so that all elements know about the global pipeline
3865        * latency. This is interesting for an element when it wants to figure out
3866        * when a particular piece of data will be rendered. */
3867       break;
3868     }
3869     case GST_EVENT_SEEK:
3870       /* in pull mode we will execute the seek */
3871       if (mode == GST_ACTIVATE_PULL)
3872         result = gst_base_sink_perform_seek (basesink, pad, event);
3873       break;
3874     case GST_EVENT_STEP:
3875       result = gst_base_sink_perform_step (basesink, pad, event);
3876       forward = FALSE;
3877       break;
3878     default:
3879       break;
3880   }
3881
3882   if (forward) {
3883     result = gst_pad_push_event (pad, event);
3884   } else {
3885     /* not forwarded, unref the event */
3886     gst_event_unref (event);
3887   }
3888
3889   gst_object_unref (pad);
3890   return result;
3891 }
3892
3893 static gboolean
3894 gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query)
3895 {
3896   GstPad *peer;
3897   gboolean res = FALSE;
3898
3899   if ((peer = gst_pad_get_peer (sink->sinkpad))) {
3900     res = gst_pad_query (peer, query);
3901     gst_object_unref (peer);
3902   }
3903   return res;
3904 }
3905
3906 /* get the end position of the last seen object, this is used
3907  * for EOS and for making sure that we don't report a position we
3908  * have not reached yet. With LOCK. */
3909 static gboolean
3910 gst_base_sink_get_position_last (GstBaseSink * basesink, GstFormat format,
3911     gint64 * cur)
3912 {
3913   GstFormat oformat;
3914   GstSegment *segment;
3915   gboolean ret = TRUE;
3916
3917   segment = &basesink->segment;
3918   oformat = segment->format;
3919
3920   if (oformat == GST_FORMAT_TIME) {
3921     /* return last observed stream time, we keep the stream time around in the
3922      * time format. */
3923     *cur = basesink->priv->current_sstop;
3924   } else {
3925     /* convert last stop to stream time */
3926     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3927   }
3928
3929   if (*cur != -1 && oformat != format) {
3930     GST_OBJECT_UNLOCK (basesink);
3931     /* convert to the target format if we need to, release lock first */
3932     ret =
3933         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3934     if (!ret)
3935       *cur = -1;
3936     GST_OBJECT_LOCK (basesink);
3937   }
3938
3939   GST_DEBUG_OBJECT (basesink, "POSITION: %" GST_TIME_FORMAT,
3940       GST_TIME_ARGS (*cur));
3941
3942   return ret;
3943 }
3944
3945 /* get the position when we are PAUSED, this is the stream time of the buffer
3946  * that prerolled. If no buffer is prerolled (we are still flushing), this
3947  * value will be -1. With LOCK. */
3948 static gboolean
3949 gst_base_sink_get_position_paused (GstBaseSink * basesink, GstFormat format,
3950     gint64 * cur)
3951 {
3952   gboolean res;
3953   gint64 time;
3954   GstSegment *segment;
3955   GstFormat oformat;
3956
3957   /* we don't use the clip segment in pull mode, when seeking we update the
3958    * main segment directly with the new segment values without it having to be
3959    * activated by the rendering after preroll */
3960   if (basesink->pad_mode == GST_ACTIVATE_PUSH)
3961     segment = basesink->abidata.ABI.clip_segment;
3962   else
3963     segment = &basesink->segment;
3964   oformat = segment->format;
3965
3966   if (oformat == GST_FORMAT_TIME) {
3967     *cur = basesink->priv->current_sstart;
3968   } else {
3969     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3970   }
3971
3972   time = segment->time;
3973
3974   if (*cur != -1) {
3975     *cur = MAX (*cur, time);
3976     GST_DEBUG_OBJECT (basesink, "POSITION as max: %" GST_TIME_FORMAT
3977         ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (*cur), GST_TIME_ARGS (time));
3978   } else {
3979     /* we have no buffer, use the segment times. */
3980     if (segment->rate >= 0.0) {
3981       /* forward, next position is always the time of the segment */
3982       *cur = time;
3983       GST_DEBUG_OBJECT (basesink, "POSITION as time: %" GST_TIME_FORMAT,
3984           GST_TIME_ARGS (*cur));
3985     } else {
3986       /* reverse, next expected timestamp is segment->stop. We use the function
3987        * to get things right for negative applied_rates. */
3988       *cur = gst_segment_to_stream_time (segment, oformat, segment->stop);
3989       GST_DEBUG_OBJECT (basesink, "reverse POSITION: %" GST_TIME_FORMAT,
3990           GST_TIME_ARGS (*cur));
3991     }
3992   }
3993
3994   res = (*cur != -1);
3995   if (res && oformat != format) {
3996     GST_OBJECT_UNLOCK (basesink);
3997     res =
3998         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3999     if (!res)
4000       *cur = -1;
4001     GST_OBJECT_LOCK (basesink);
4002   }
4003
4004   return res;
4005 }
4006
4007 static gboolean
4008 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
4009     gint64 * cur, gboolean * upstream)
4010 {
4011   GstClock *clock;
4012   gboolean res = FALSE;
4013   GstFormat oformat, tformat;
4014   GstClockTime now, base, latency;
4015   gint64 time, accum, duration;
4016   gdouble rate;
4017   gint64 last;
4018
4019   GST_OBJECT_LOCK (basesink);
4020   /* our intermediate time format */
4021   tformat = GST_FORMAT_TIME;
4022   /* get the format in the segment */
4023   oformat = basesink->segment.format;
4024
4025   /* can only give answer based on the clock if not EOS */
4026   if (G_UNLIKELY (basesink->eos))
4027     goto in_eos;
4028
4029   /* we can only get the segment when we are not NULL or READY */
4030   if (!basesink->have_newsegment)
4031     goto wrong_state;
4032
4033   /* when not in PLAYING or when we're busy with a state change, we
4034    * cannot read from the clock so we report time based on the
4035    * last seen timestamp. */
4036   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
4037       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING)
4038     goto in_pause;
4039
4040   /* we need to sync on the clock. */
4041   if (basesink->sync == FALSE)
4042     goto no_sync;
4043
4044   /* and we need a clock */
4045   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
4046     goto no_sync;
4047
4048   /* collect all data we need holding the lock */
4049   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.time))
4050     time = basesink->segment.time;
4051   else
4052     time = 0;
4053
4054   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.stop))
4055     duration = basesink->segment.stop - basesink->segment.start;
4056   else
4057     duration = 0;
4058
4059   base = GST_ELEMENT_CAST (basesink)->base_time;
4060   accum = basesink->segment.accum;
4061   rate = basesink->segment.rate * basesink->segment.applied_rate;
4062   latency = basesink->priv->latency;
4063
4064   gst_object_ref (clock);
4065
4066   /* this function might release the LOCK */
4067   gst_base_sink_get_position_last (basesink, format, &last);
4068
4069   /* need to release the object lock before we can get the time, 
4070    * a clock might take the LOCK of the provider, which could be
4071    * a basesink subclass. */
4072   GST_OBJECT_UNLOCK (basesink);
4073
4074   now = gst_clock_get_time (clock);
4075
4076   if (oformat != tformat) {
4077     /* convert accum, time and duration to time */
4078     if (!gst_pad_query_convert (basesink->sinkpad, oformat, accum, &tformat,
4079             &accum))
4080       goto convert_failed;
4081     if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration, &tformat,
4082             &duration))
4083       goto convert_failed;
4084     if (!gst_pad_query_convert (basesink->sinkpad, oformat, time, &tformat,
4085             &time))
4086       goto convert_failed;
4087   }
4088
4089   /* subtract base time and accumulated time from the clock time. 
4090    * Make sure we don't go negative. This is the current time in
4091    * the segment which we need to scale with the combined 
4092    * rate and applied rate. */
4093   base += accum;
4094   base += latency;
4095   base = MIN (now, base);
4096
4097   /* for negative rates we need to count back from from the segment
4098    * duration. */
4099   if (rate < 0.0)
4100     time += duration;
4101
4102   *cur = time + gst_guint64_to_gdouble (now - base) * rate;
4103
4104   /* never report more than last seen position */
4105   if (last != -1)
4106     *cur = MIN (last, *cur);
4107
4108   gst_object_unref (clock);
4109
4110   GST_DEBUG_OBJECT (basesink,
4111       "now %" GST_TIME_FORMAT " - base %" GST_TIME_FORMAT " - accum %"
4112       GST_TIME_FORMAT " + time %" GST_TIME_FORMAT,
4113       GST_TIME_ARGS (now), GST_TIME_ARGS (base),
4114       GST_TIME_ARGS (accum), GST_TIME_ARGS (time));
4115
4116   if (oformat != format) {
4117     /* convert time to final format */
4118     if (!gst_pad_query_convert (basesink->sinkpad, tformat, *cur, &format, cur))
4119       goto convert_failed;
4120   }
4121
4122   res = TRUE;
4123
4124 done:
4125   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
4126       res, GST_TIME_ARGS (*cur));
4127   return res;
4128
4129   /* special cases */
4130 in_eos:
4131   {
4132     GST_DEBUG_OBJECT (basesink, "position in EOS");
4133     res = gst_base_sink_get_position_last (basesink, format, cur);
4134     GST_OBJECT_UNLOCK (basesink);
4135     goto done;
4136   }
4137 in_pause:
4138   {
4139     GST_DEBUG_OBJECT (basesink, "position in PAUSED");
4140     res = gst_base_sink_get_position_paused (basesink, format, cur);
4141     GST_OBJECT_UNLOCK (basesink);
4142     goto done;
4143   }
4144 wrong_state:
4145   {
4146     /* in NULL or READY we always return FALSE and -1 */
4147     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
4148     res = FALSE;
4149     *cur = -1;
4150     GST_OBJECT_UNLOCK (basesink);
4151     goto done;
4152   }
4153 no_sync:
4154   {
4155     /* report last seen timestamp if any, else ask upstream to answer */
4156     if ((*cur = basesink->priv->current_sstart) != -1)
4157       res = TRUE;
4158     else
4159       *upstream = TRUE;
4160
4161     GST_DEBUG_OBJECT (basesink, "no sync, res %d, POSITION %" GST_TIME_FORMAT,
4162         res, GST_TIME_ARGS (*cur));
4163     GST_OBJECT_UNLOCK (basesink);
4164     return res;
4165   }
4166 convert_failed:
4167   {
4168     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
4169     *upstream = TRUE;
4170     return FALSE;
4171   }
4172 }
4173
4174 static gboolean
4175 gst_base_sink_query (GstElement * element, GstQuery * query)
4176 {
4177   gboolean res = FALSE;
4178
4179   GstBaseSink *basesink = GST_BASE_SINK (element);
4180
4181   switch (GST_QUERY_TYPE (query)) {
4182     case GST_QUERY_POSITION:
4183     {
4184       gint64 cur = 0;
4185       GstFormat format;
4186       gboolean upstream = FALSE;
4187
4188       gst_query_parse_position (query, &format, NULL);
4189
4190       GST_DEBUG_OBJECT (basesink, "position format %d", format);
4191
4192       /* first try to get the position based on the clock */
4193       if ((res =
4194               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
4195         gst_query_set_position (query, format, cur);
4196       } else if (upstream) {
4197         /* fallback to peer query */
4198         res = gst_base_sink_peer_query (basesink, query);
4199       }
4200       break;
4201     }
4202     case GST_QUERY_DURATION:
4203     {
4204       GstFormat format, uformat;
4205       gint64 duration, uduration;
4206
4207       gst_query_parse_duration (query, &format, NULL);
4208
4209       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
4210           gst_format_get_name (format));
4211
4212       if (basesink->pad_mode == GST_ACTIVATE_PULL) {
4213         uformat = GST_FORMAT_BYTES;
4214
4215         /* get the duration in bytes, in pull mode that's all we are sure to
4216          * know. We have to explicitly get this value from upstream instead of
4217          * using our cached value because it might change. Duration caching
4218          * should be done at a higher level. */
4219         res = gst_pad_query_peer_duration (basesink->sinkpad, &uformat,
4220             &uduration);
4221         if (res) {
4222           gst_segment_set_duration (&basesink->segment, uformat, uduration);
4223           if (format != uformat) {
4224             /* convert to the requested format */
4225             res = gst_pad_query_convert (basesink->sinkpad, uformat, uduration,
4226                 &format, &duration);
4227           } else {
4228             duration = uduration;
4229           }
4230           if (res) {
4231             /* set the result */
4232             gst_query_set_duration (query, format, duration);
4233           }
4234         }
4235       } else {
4236         /* in push mode we simply forward upstream */
4237         res = gst_base_sink_peer_query (basesink, query);
4238       }
4239       break;
4240     }
4241     case GST_QUERY_LATENCY:
4242     {
4243       gboolean live, us_live;
4244       GstClockTime min, max;
4245
4246       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
4247                   &max))) {
4248         gst_query_set_latency (query, live, min, max);
4249       }
4250       break;
4251     }
4252     case GST_QUERY_JITTER:
4253       break;
4254     case GST_QUERY_RATE:
4255       /* gst_query_set_rate (query, basesink->segment_rate); */
4256       res = TRUE;
4257       break;
4258     case GST_QUERY_SEGMENT:
4259     {
4260       /* FIXME, bring start/stop to stream time */
4261       gst_query_set_segment (query, basesink->segment.rate,
4262           GST_FORMAT_TIME, basesink->segment.start, basesink->segment.stop);
4263       break;
4264     }
4265     case GST_QUERY_SEEKING:
4266     case GST_QUERY_CONVERT:
4267     case GST_QUERY_FORMATS:
4268     default:
4269       res = gst_base_sink_peer_query (basesink, query);
4270       break;
4271   }
4272   return res;
4273 }
4274
4275 static GstStateChangeReturn
4276 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
4277 {
4278   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
4279   GstBaseSink *basesink = GST_BASE_SINK (element);
4280   GstBaseSinkClass *bclass;
4281   GstBaseSinkPrivate *priv;
4282
4283   priv = basesink->priv;
4284
4285   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4286
4287   switch (transition) {
4288     case GST_STATE_CHANGE_NULL_TO_READY:
4289       if (bclass->start)
4290         if (!bclass->start (basesink))
4291           goto start_failed;
4292       break;
4293     case GST_STATE_CHANGE_READY_TO_PAUSED:
4294       /* need to complete preroll before this state change completes, there
4295        * is no data flow in READY so we can safely assume we need to preroll. */
4296       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4297       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
4298       basesink->have_newsegment = FALSE;
4299       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
4300       gst_segment_init (basesink->abidata.ABI.clip_segment,
4301           GST_FORMAT_UNDEFINED);
4302       basesink->offset = 0;
4303       basesink->have_preroll = FALSE;
4304       basesink->need_preroll = TRUE;
4305       basesink->playing_async = TRUE;
4306       priv->current_sstart = -1;
4307       priv->current_sstop = -1;
4308       priv->eos_rtime = -1;
4309       priv->latency = 0;
4310       basesink->eos = FALSE;
4311       priv->received_eos = FALSE;
4312       gst_base_sink_reset_qos (basesink);
4313       priv->commited = FALSE;
4314       priv->call_preroll = TRUE;
4315       priv->current_step.valid = FALSE;
4316       priv->pending_step.valid = FALSE;
4317       if (priv->async_enabled) {
4318         GST_DEBUG_OBJECT (basesink, "doing async state change");
4319         /* when async enabled, post async-start message and return ASYNC from
4320          * the state change function */
4321         ret = GST_STATE_CHANGE_ASYNC;
4322         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4323             gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4324       } else {
4325         priv->have_latency = TRUE;
4326       }
4327       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4328       break;
4329     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4330       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4331       if (!gst_base_sink_needs_preroll (basesink)) {
4332         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
4333         /* no preroll needed anymore now. */
4334         basesink->playing_async = FALSE;
4335         basesink->need_preroll = FALSE;
4336         if (basesink->eos) {
4337           GstMessage *message;
4338
4339           /* need to post EOS message here */
4340           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
4341           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
4342           gst_message_set_seqnum (message, basesink->priv->seqnum);
4343           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
4344         } else {
4345           GST_DEBUG_OBJECT (basesink, "signal preroll");
4346           GST_PAD_PREROLL_SIGNAL (basesink->sinkpad);
4347         }
4348       } else {
4349         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
4350         basesink->need_preroll = TRUE;
4351         basesink->playing_async = TRUE;
4352         priv->call_preroll = TRUE;
4353         priv->commited = FALSE;
4354         if (priv->async_enabled) {
4355           GST_DEBUG_OBJECT (basesink, "doing async state change");
4356           ret = GST_STATE_CHANGE_ASYNC;
4357           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4358               gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4359         }
4360       }
4361       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4362       break;
4363     default:
4364       break;
4365   }
4366
4367   {
4368     GstStateChangeReturn bret;
4369
4370     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4371     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
4372       goto activate_failed;
4373   }
4374
4375   switch (transition) {
4376     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4377       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
4378       /* FIXME, make sure we cannot enter _render first */
4379
4380       /* we need to call ::unlock before locking PREROLL_LOCK
4381        * since we lock it before going into ::render */
4382       if (bclass->unlock)
4383         bclass->unlock (basesink);
4384
4385       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4386       /* now that we have the PREROLL lock, clear our unlock request */
4387       if (bclass->unlock_stop)
4388         bclass->unlock_stop (basesink);
4389
4390       /* we need preroll again and we set the flag before unlocking the clockid
4391        * because if the clockid is unlocked before a current buffer expired, we
4392        * can use that buffer to preroll with */
4393       basesink->need_preroll = TRUE;
4394
4395       if (basesink->clock_id) {
4396         gst_clock_id_unschedule (basesink->clock_id);
4397       }
4398
4399       /* if we don't have a preroll buffer we need to wait for a preroll and
4400        * return ASYNC. */
4401       if (!gst_base_sink_needs_preroll (basesink)) {
4402         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
4403         basesink->playing_async = FALSE;
4404       } else {
4405         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
4406           ret = GST_STATE_CHANGE_SUCCESS;
4407         } else {
4408           GST_DEBUG_OBJECT (basesink,
4409               "PLAYING to PAUSED, we are not prerolled");
4410           basesink->playing_async = TRUE;
4411           priv->commited = FALSE;
4412           priv->call_preroll = TRUE;
4413           if (priv->async_enabled) {
4414             GST_DEBUG_OBJECT (basesink, "doing async state change");
4415             ret = GST_STATE_CHANGE_ASYNC;
4416             gst_element_post_message (GST_ELEMENT_CAST (basesink),
4417                 gst_message_new_async_start (GST_OBJECT_CAST (basesink),
4418                     FALSE));
4419           }
4420         }
4421       }
4422       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
4423           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
4424
4425       gst_base_sink_reset_qos (basesink);
4426       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4427       break;
4428     case GST_STATE_CHANGE_PAUSED_TO_READY:
4429       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4430       /* start by reseting our position state with the object lock so that the
4431        * position query gets the right idea. We do this before we post the
4432        * messages so that the message handlers pick this up. */
4433       GST_OBJECT_LOCK (basesink);
4434       basesink->have_newsegment = FALSE;
4435       priv->current_sstart = -1;
4436       priv->current_sstop = -1;
4437       priv->have_latency = FALSE;
4438       GST_OBJECT_UNLOCK (basesink);
4439
4440       gst_base_sink_set_last_buffer (basesink, NULL);
4441       priv->call_preroll = FALSE;
4442
4443       if (!priv->commited) {
4444         if (priv->async_enabled) {
4445           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
4446
4447           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4448               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
4449                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
4450
4451           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4452               gst_message_new_async_done (GST_OBJECT_CAST (basesink)));
4453         }
4454         priv->commited = TRUE;
4455       } else {
4456         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
4457       }
4458       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4459       break;
4460     case GST_STATE_CHANGE_READY_TO_NULL:
4461       if (bclass->stop) {
4462         if (!bclass->stop (basesink)) {
4463           GST_WARNING_OBJECT (basesink, "failed to stop");
4464         }
4465       }
4466       gst_base_sink_set_last_buffer (basesink, NULL);
4467       priv->call_preroll = FALSE;
4468       break;
4469     default:
4470       break;
4471   }
4472
4473   return ret;
4474
4475   /* ERRORS */
4476 start_failed:
4477   {
4478     GST_DEBUG_OBJECT (basesink, "failed to start");
4479     return GST_STATE_CHANGE_FAILURE;
4480   }
4481 activate_failed:
4482   {
4483     GST_DEBUG_OBJECT (basesink,
4484         "element failed to change states -- activation problem?");
4485     return GST_STATE_CHANGE_FAILURE;
4486   }
4487 }