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