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