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