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