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