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