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