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