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