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