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