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