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