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