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