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