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