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