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