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