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