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