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