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