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