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