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