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