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