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