libs/gst/base/gstbasesink.c: Turn comment into gtk-doc comment.
[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 /**
1603  * gst_base_sink_wait_clock:
1604  * @sink: the sink
1605  * @time: the running_time to be reached
1606  * @jitter: the jitter to be filled with time diff (can be NULL)
1607  *
1608  * This function will block until @time is reached. It is usually called by
1609  * subclasses that use their own internal synchronisation.
1610  *
1611  * If @time is not valid, no sycnhronisation is done and #GST_CLOCK_BADTIME is
1612  * returned. Likewise, if synchronisation is disabled in the element or there
1613  * is no clock, no synchronisation is done and #GST_CLOCK_BADTIME is returned.
1614  *
1615  * This function should only be called with the PREROLL_LOCK held, like when
1616  * receiving an EOS event in the ::event vmethod or when receiving a buffer in
1617  * the ::render vmethod.
1618  *
1619  * The @time argument should be the running_time of when this method should
1620  * return and is not adjusted with any latency or offset configured in the
1621  * sink.
1622  *
1623  * Since 0.10.20
1624  *
1625  * Returns: #GstClockReturn
1626  */
1627 GstClockReturn
1628 gst_base_sink_wait_clock (GstBaseSink * basesink, GstClockTime time,
1629     GstClockTimeDiff * jitter)
1630 {
1631   GstClockID id;
1632   GstClockReturn ret;
1633   GstClock *clock;
1634
1635   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1636     goto invalid_time;
1637
1638   GST_OBJECT_LOCK (basesink);
1639   if (G_UNLIKELY (!basesink->sync))
1640     goto no_sync;
1641
1642   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
1643     goto no_clock;
1644
1645   /* add base_time to running_time to get the time against the clock */
1646   time += GST_ELEMENT_CAST (basesink)->base_time;
1647
1648   id = gst_clock_new_single_shot_id (clock, time);
1649   GST_OBJECT_UNLOCK (basesink);
1650
1651   /* A blocking wait is performed on the clock. We save the ClockID
1652    * so we can unlock the entry at any time. While we are blocking, we 
1653    * release the PREROLL_LOCK so that other threads can interrupt the
1654    * entry. */
1655   basesink->clock_id = id;
1656   /* release the preroll lock while waiting */
1657   GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1658
1659   ret = gst_clock_id_wait (id, jitter);
1660
1661   GST_PAD_PREROLL_LOCK (basesink->sinkpad);
1662   gst_clock_id_unref (id);
1663   basesink->clock_id = NULL;
1664
1665   return ret;
1666
1667   /* no syncing needed */
1668 invalid_time:
1669   {
1670     GST_DEBUG_OBJECT (basesink, "time not valid, no sync needed");
1671     return GST_CLOCK_BADTIME;
1672   }
1673 no_sync:
1674   {
1675     GST_DEBUG_OBJECT (basesink, "sync disabled");
1676     GST_OBJECT_UNLOCK (basesink);
1677     return GST_CLOCK_BADTIME;
1678   }
1679 no_clock:
1680   {
1681     GST_DEBUG_OBJECT (basesink, "no clock, can't sync");
1682     GST_OBJECT_UNLOCK (basesink);
1683     return GST_CLOCK_BADTIME;
1684   }
1685 }
1686
1687 /**
1688  * gst_base_sink_wait_preroll:
1689  * @sink: the sink
1690  *
1691  * If the #GstBaseSinkClass::render method performs its own synchronisation against
1692  * the clock it must unblock when going from PLAYING to the PAUSED state and call
1693  * this method before continuing to render the remaining data.
1694  *
1695  * This function will block until a state change to PLAYING happens (in which
1696  * case this function returns #GST_FLOW_OK) or the processing must be stopped due
1697  * to a state change to READY or a FLUSH event (in which case this function
1698  * returns #GST_FLOW_WRONG_STATE).
1699  *
1700  * This function should only be called with the PREROLL_LOCK held, like in the
1701  * render function.
1702  *
1703  * Since: 0.10.11
1704  *
1705  * Returns: #GST_FLOW_OK if the preroll completed and processing can
1706  * continue. Any other return value should be returned from the render vmethod.
1707  */
1708 GstFlowReturn
1709 gst_base_sink_wait_preroll (GstBaseSink * sink)
1710 {
1711   sink->have_preroll = TRUE;
1712   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
1713   /* block until the state changes, or we get a flush, or something */
1714   GST_PAD_PREROLL_WAIT (sink->sinkpad);
1715   sink->have_preroll = FALSE;
1716   if (G_UNLIKELY (sink->flushing))
1717     goto stopping;
1718   GST_DEBUG_OBJECT (sink, "continue after preroll");
1719
1720   return GST_FLOW_OK;
1721
1722   /* ERRORS */
1723 stopping:
1724   {
1725     GST_DEBUG_OBJECT (sink, "preroll interrupted");
1726     return GST_FLOW_WRONG_STATE;
1727   }
1728 }
1729
1730 /**
1731  * gst_base_sink_do_preroll:
1732  * @sink: the sink
1733  * @obj: the object that caused the preroll
1734  *
1735  * If the @sink spawns its own thread for pulling buffers from upstream it
1736  * should call this method after it has pulled a buffer. If the element needed
1737  * to preroll, this function will perform the preroll and will then block
1738  * until the element state is changed.
1739  *
1740  * This function should be called with the PREROLL_LOCK held.
1741  *
1742  * Since 0.10.22
1743  *
1744  * Returns: #GST_FLOW_OK if the preroll completed and processing can
1745  * continue. Any other return value should be returned from the render vmethod.
1746  */
1747 GstFlowReturn
1748 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
1749 {
1750   GstFlowReturn ret;
1751
1752   while (G_UNLIKELY (sink->need_preroll)) {
1753     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
1754
1755     if (G_LIKELY (sink->playing_async)) {
1756       /* commit state */
1757       if (G_UNLIKELY (!gst_base_sink_commit_state (sink)))
1758         goto stopping;
1759     }
1760
1761     /* need to recheck here because the commit state could have
1762      * made us not need the preroll anymore */
1763     if (G_LIKELY (sink->need_preroll)) {
1764       /* block until the state changes, or we get a flush, or something */
1765       ret = gst_base_sink_wait_preroll (sink);
1766       if (ret != GST_FLOW_OK)
1767         goto flushing;
1768     }
1769   }
1770   return GST_FLOW_OK;
1771
1772   /* ERRORS */
1773 flushing:
1774   {
1775     GST_DEBUG_OBJECT (sink, "we are flushing");
1776     return ret;
1777   }
1778 stopping:
1779   {
1780     GST_DEBUG_OBJECT (sink, "stopping while commiting state");
1781     return GST_FLOW_WRONG_STATE;
1782   }
1783 }
1784
1785 /**
1786  * gst_base_sink_wait_eos:
1787  * @sink: the sink
1788  * @time: the running_time to be reached
1789  * @jitter: the jitter to be filled with time diff (can be NULL)
1790  *
1791  * This function will block until @time is reached. It is usually called by
1792  * subclasses that use their own internal synchronisation but want to let the
1793  * EOS be handled by the base class.
1794  *
1795  * This function should only be called with the PREROLL_LOCK held, like when
1796  * receiving an EOS event in the ::event vmethod.
1797  *
1798  * The @time argument should be the running_time of when the EOS should happen
1799  * and will be adjusted with any latency and offset configured in the sink.
1800  *
1801  * Since 0.10.15
1802  *
1803  * Returns: #GstFlowReturn
1804  */
1805 GstFlowReturn
1806 gst_base_sink_wait_eos (GstBaseSink * sink, GstClockTime time,
1807     GstClockTimeDiff * jitter)
1808 {
1809   GstClockReturn status;
1810   GstFlowReturn ret;
1811
1812   do {
1813     GstClockTime stime;
1814
1815     GST_DEBUG_OBJECT (sink, "checking preroll");
1816
1817     /* first wait for the playing state before we can continue */
1818     if (G_UNLIKELY (sink->need_preroll)) {
1819       ret = gst_base_sink_wait_preroll (sink);
1820       if (ret != GST_FLOW_OK)
1821         goto flushing;
1822     }
1823
1824     /* preroll done, we can sync since we are in PLAYING now. */
1825     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
1826         GST_TIME_FORMAT, GST_TIME_ARGS (time));
1827
1828     /* compensate for latency and ts_offset. We don't adjust for render delay
1829      * because we don't interact with the device on EOS normally. */
1830     stime = gst_base_sink_adjust_time (sink, time);
1831
1832     /* wait for the clock, this can be interrupted because we got shut down or 
1833      * we PAUSED. */
1834     status = gst_base_sink_wait_clock (sink, stime, jitter);
1835
1836     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
1837
1838     /* invalid time, no clock or sync disabled, just continue then */
1839     if (status == GST_CLOCK_BADTIME)
1840       break;
1841
1842     /* waiting could have been interrupted and we can be flushing now */
1843     if (G_UNLIKELY (sink->flushing))
1844       goto flushing;
1845
1846     /* retry if we got unscheduled, which means we did not reach the timeout
1847      * yet. if some other error occures, we continue. */
1848   } while (status == GST_CLOCK_UNSCHEDULED);
1849
1850   GST_DEBUG_OBJECT (sink, "end of stream");
1851
1852   return GST_FLOW_OK;
1853
1854   /* ERRORS */
1855 flushing:
1856   {
1857     GST_DEBUG_OBJECT (sink, "we are flushing");
1858     return GST_FLOW_WRONG_STATE;
1859   }
1860 }
1861
1862 /* with STREAM_LOCK, PREROLL_LOCK
1863  *
1864  * Make sure we are in PLAYING and synchronize an object to the clock.
1865  *
1866  * If we need preroll, we are not in PLAYING. We try to commit the state
1867  * if needed and then block if we still are not PLAYING.
1868  *
1869  * We start waiting on the clock in PLAYING. If we got interrupted, we
1870  * immediatly try to re-preroll.
1871  *
1872  * Some objects do not need synchronisation (most events) and so this function
1873  * immediatly returns GST_FLOW_OK.
1874  *
1875  * for objects that arrive later than max-lateness to be synchronized to the 
1876  * clock have the @late boolean set to TRUE.
1877  *
1878  * This function keeps a running average of the jitter (the diff between the
1879  * clock time and the requested sync time). The jitter is negative for
1880  * objects that arrive in time and positive for late buffers.
1881  *
1882  * does not take ownership of obj.
1883  */
1884 static GstFlowReturn
1885 gst_base_sink_do_sync (GstBaseSink * basesink, GstPad * pad,
1886     GstMiniObject * obj, gboolean * late)
1887 {
1888   GstClockTimeDiff jitter;
1889   gboolean syncable;
1890   GstClockReturn status = GST_CLOCK_OK;
1891   GstClockTime rstart, rstop, sstart, sstop, stime;
1892   gboolean do_sync;
1893   GstBaseSinkPrivate *priv;
1894
1895   priv = basesink->priv;
1896
1897   sstart = sstop = rstart = rstop = -1;
1898   do_sync = TRUE;
1899
1900   priv->current_rstart = -1;
1901
1902   /* get timing information for this object against the render segment */
1903   syncable = gst_base_sink_get_sync_times (basesink, obj,
1904       &sstart, &sstop, &rstart, &rstop, &do_sync, &basesink->segment);
1905
1906   /* a syncable object needs to participate in preroll and
1907    * clocking. All buffers and EOS are syncable. */
1908   if (G_UNLIKELY (!syncable))
1909     goto not_syncable;
1910
1911   /* store timing info for current object */
1912   priv->current_rstart = rstart;
1913   priv->current_rstop = (rstop != -1 ? rstop : rstart);
1914   /* save sync time for eos when the previous object needed sync */
1915   priv->eos_rtime = (do_sync ? priv->current_rstop : -1);
1916
1917 again:
1918   /* first do preroll, this makes sure we commit our state
1919    * to PAUSED and can continue to PLAYING. We cannot perform
1920    * any clock sync in PAUSED because there is no clock. 
1921    */
1922   while (G_UNLIKELY (basesink->need_preroll)) {
1923     GST_DEBUG_OBJECT (basesink, "prerolling object %p", obj);
1924
1925     if (G_LIKELY (basesink->playing_async)) {
1926       /* commit state */
1927       if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
1928         goto stopping;
1929     }
1930
1931     /* need to recheck here because the commit state could have
1932      * made us not need the preroll anymore */
1933     if (G_LIKELY (basesink->need_preroll)) {
1934       /* block until the state changes, or we get a flush, or something */
1935       if (gst_base_sink_wait_preroll (basesink) != GST_FLOW_OK)
1936         goto flushing;
1937     }
1938   }
1939
1940   /* After rendering we store the position of the last buffer so that we can use
1941    * it to report the position. We need to take the lock here. */
1942   GST_OBJECT_LOCK (basesink);
1943   priv->current_sstart = sstart;
1944   priv->current_sstop = (sstop != -1 ? sstop : sstart);
1945   GST_OBJECT_UNLOCK (basesink);
1946
1947   if (!do_sync)
1948     goto done;
1949
1950   /* adjust for latency */
1951   stime = gst_base_sink_adjust_time (basesink, rstart);
1952
1953   /* adjust for render-delay, avoid underflows */
1954   if (stime != -1) {
1955     if (stime > priv->render_delay)
1956       stime -= priv->render_delay;
1957     else
1958       stime = 0;
1959   }
1960
1961   /* preroll done, we can sync since we are in PLAYING now. */
1962   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
1963       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
1964       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
1965
1966   /* This function will return immediatly if start == -1, no clock
1967    * or sync is disabled with GST_CLOCK_BADTIME. */
1968   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
1969
1970   GST_DEBUG_OBJECT (basesink, "clock returned %d", status);
1971
1972   /* invalid time, no clock or sync disabled, just render */
1973   if (status == GST_CLOCK_BADTIME)
1974     goto done;
1975
1976   /* waiting could have been interrupted and we can be flushing now */
1977   if (G_UNLIKELY (basesink->flushing))
1978     goto flushing;
1979
1980   /* check for unlocked by a state change, we are not flushing so
1981    * we can try to preroll on the current buffer. */
1982   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1983     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
1984     goto again;
1985   }
1986
1987   /* successful syncing done, record observation */
1988   priv->current_jitter = jitter;
1989
1990   /* check if the object should be dropped */
1991   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
1992       status, jitter);
1993
1994 done:
1995   return GST_FLOW_OK;
1996
1997   /* ERRORS */
1998 not_syncable:
1999   {
2000     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2001     return GST_FLOW_OK;
2002   }
2003 flushing:
2004   {
2005     GST_DEBUG_OBJECT (basesink, "we are flushing");
2006     return GST_FLOW_WRONG_STATE;
2007   }
2008 stopping:
2009   {
2010     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
2011     return GST_FLOW_WRONG_STATE;
2012   }
2013 }
2014
2015 static gboolean
2016 gst_base_sink_send_qos (GstBaseSink * basesink,
2017     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2018 {
2019   GstEvent *event;
2020   gboolean res;
2021
2022   /* generate Quality-of-Service event */
2023   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2024       "qos: proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2025       GST_TIME_FORMAT, proportion, diff, GST_TIME_ARGS (time));
2026
2027   event = gst_event_new_qos (proportion, diff, time);
2028
2029   /* send upstream */
2030   res = gst_pad_push_event (basesink->sinkpad, event);
2031
2032   return res;
2033 }
2034
2035 static void
2036 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2037 {
2038   GstBaseSinkPrivate *priv;
2039   GstClockTime start, stop;
2040   GstClockTimeDiff jitter;
2041   GstClockTime pt, entered, left;
2042   GstClockTime duration;
2043   gdouble rate;
2044
2045   priv = sink->priv;
2046
2047   start = priv->current_rstart;
2048
2049   /* if Quality-of-Service disabled, do nothing */
2050   if (!g_atomic_int_get (&priv->qos_enabled) || start == -1)
2051     return;
2052
2053   stop = priv->current_rstop;
2054   jitter = priv->current_jitter;
2055
2056   if (jitter < 0) {
2057     /* this is the time the buffer entered the sink */
2058     if (start < -jitter)
2059       entered = 0;
2060     else
2061       entered = start + jitter;
2062     left = start;
2063   } else {
2064     /* this is the time the buffer entered the sink */
2065     entered = start + jitter;
2066     /* this is the time the buffer left the sink */
2067     left = start + jitter;
2068   }
2069
2070   /* calculate duration of the buffer */
2071   if (stop != -1)
2072     duration = stop - start;
2073   else
2074     duration = -1;
2075
2076   /* if we have the time when the last buffer left us, calculate
2077    * processing time */
2078   if (priv->last_left != -1) {
2079     if (entered > priv->last_left) {
2080       pt = entered - priv->last_left;
2081     } else {
2082       pt = 0;
2083     }
2084   } else {
2085     pt = priv->avg_pt;
2086   }
2087
2088   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2089       ", entered %" GST_TIME_FORMAT ", left %" GST_TIME_FORMAT ", pt: %"
2090       GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT ",jitter %"
2091       G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (entered),
2092       GST_TIME_ARGS (left), GST_TIME_ARGS (pt), GST_TIME_ARGS (duration),
2093       jitter);
2094
2095   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "avg_duration: %" GST_TIME_FORMAT
2096       ", avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2097       GST_TIME_ARGS (priv->avg_duration), GST_TIME_ARGS (priv->avg_pt),
2098       priv->avg_rate);
2099
2100   /* collect running averages. for first observations, we copy the
2101    * values */
2102   if (priv->avg_duration == -1)
2103     priv->avg_duration = duration;
2104   else
2105     priv->avg_duration = UPDATE_RUNNING_AVG (priv->avg_duration, duration);
2106
2107   if (priv->avg_pt == -1)
2108     priv->avg_pt = pt;
2109   else
2110     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2111
2112   if (priv->avg_duration != 0)
2113     rate =
2114         gst_guint64_to_gdouble (priv->avg_pt) /
2115         gst_guint64_to_gdouble (priv->avg_duration);
2116   else
2117     rate = 0.0;
2118
2119   if (priv->last_left != -1) {
2120     if (dropped || priv->avg_rate < 0.0) {
2121       priv->avg_rate = rate;
2122     } else {
2123       if (rate > 1.0)
2124         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2125       else
2126         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2127     }
2128   }
2129
2130   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2131       "updated: avg_duration: %" GST_TIME_FORMAT ", avg_pt: %" GST_TIME_FORMAT
2132       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_duration),
2133       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2134
2135
2136   if (priv->avg_rate >= 0.0) {
2137     /* if we have a valid rate, start sending QoS messages */
2138     if (priv->current_jitter < 0) {
2139       /* make sure we never go below 0 when adding the jitter to the
2140        * timestamp. */
2141       if (priv->current_rstart < -priv->current_jitter)
2142         priv->current_jitter = -priv->current_rstart;
2143     }
2144     gst_base_sink_send_qos (sink, priv->avg_rate, priv->current_rstart,
2145         priv->current_jitter);
2146   }
2147
2148   /* record when this buffer will leave us */
2149   priv->last_left = left;
2150 }
2151
2152 /* reset all qos measuring */
2153 static void
2154 gst_base_sink_reset_qos (GstBaseSink * sink)
2155 {
2156   GstBaseSinkPrivate *priv;
2157
2158   priv = sink->priv;
2159
2160   priv->last_in_time = -1;
2161   priv->last_left = -1;
2162   priv->avg_duration = -1;
2163   priv->avg_pt = -1;
2164   priv->avg_rate = -1.0;
2165   priv->avg_render = -1;
2166   priv->rendered = 0;
2167   priv->dropped = 0;
2168
2169 }
2170
2171 /* Checks if the object was scheduled too late.
2172  *
2173  * start/stop contain the raw timestamp start and stop values
2174  * of the object.
2175  *
2176  * status and jitter contain the return values from the clock wait.
2177  *
2178  * returns TRUE if the buffer was too late.
2179  */
2180 static gboolean
2181 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2182     GstClockTime start, GstClockTime stop,
2183     GstClockReturn status, GstClockTimeDiff jitter)
2184 {
2185   gboolean late;
2186   gint64 max_lateness;
2187   GstBaseSinkPrivate *priv;
2188
2189   priv = basesink->priv;
2190
2191   late = FALSE;
2192
2193   /* only for objects that were too late */
2194   if (G_LIKELY (status != GST_CLOCK_EARLY))
2195     goto in_time;
2196
2197   max_lateness = basesink->abidata.ABI.max_lateness;
2198
2199   /* check if frame dropping is enabled */
2200   if (max_lateness == -1)
2201     goto no_drop;
2202
2203   /* only check for buffers */
2204   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2205     goto not_buffer;
2206
2207   /* can't do check if we don't have a timestamp */
2208   if (G_UNLIKELY (start == -1))
2209     goto no_timestamp;
2210
2211   /* we can add a valid stop time */
2212   if (stop != -1)
2213     max_lateness += stop;
2214   else
2215     max_lateness += start;
2216
2217   /* if the jitter bigger than duration and lateness we are too late */
2218   if ((late = start + jitter > max_lateness)) {
2219     GST_DEBUG_OBJECT (basesink, "buffer is too late %" GST_TIME_FORMAT
2220         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (start + jitter),
2221         GST_TIME_ARGS (max_lateness));
2222     /* !!emergency!!, if we did not receive anything valid for more than a 
2223      * second, render it anyway so the user sees something */
2224     if (priv->last_in_time && start - priv->last_in_time > GST_SECOND) {
2225       late = FALSE;
2226       GST_DEBUG_OBJECT (basesink,
2227           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
2228           GST_TIME_ARGS (priv->last_in_time));
2229     }
2230   }
2231
2232 done:
2233   if (!late) {
2234     priv->last_in_time = start;
2235   }
2236   return late;
2237
2238   /* all is fine */
2239 in_time:
2240   {
2241     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
2242     goto done;
2243   }
2244 no_drop:
2245   {
2246     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
2247     goto done;
2248   }
2249 not_buffer:
2250   {
2251     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
2252     return FALSE;
2253   }
2254 no_timestamp:
2255   {
2256     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
2257     return FALSE;
2258   }
2259 }
2260
2261 /* called before and after calling the render vmethod. It keeps track of how
2262  * much time was spent in the render method and is used to check if we are
2263  * flooded */
2264 static void
2265 gst_base_sink_do_render_stats (GstBaseSink * basesink, gboolean start)
2266 {
2267   GstBaseSinkPrivate *priv;
2268
2269   priv = basesink->priv;
2270
2271   if (start) {
2272     priv->start = gst_util_get_timestamp ();
2273   } else {
2274     GstClockTime elapsed;
2275
2276     priv->stop = gst_util_get_timestamp ();
2277
2278     elapsed = GST_CLOCK_DIFF (priv->start, priv->stop);
2279
2280     if (priv->avg_render == -1)
2281       priv->avg_render = elapsed;
2282     else
2283       priv->avg_render = UPDATE_RUNNING_AVG (priv->avg_render, elapsed);
2284
2285     GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2286         "avg_render: %" GST_TIME_FORMAT, GST_TIME_ARGS (priv->avg_render));
2287   }
2288 }
2289
2290 /* with STREAM_LOCK, PREROLL_LOCK,
2291  *
2292  * Synchronize the object on the clock and then render it.
2293  *
2294  * takes ownership of obj.
2295  */
2296 static GstFlowReturn
2297 gst_base_sink_render_object (GstBaseSink * basesink, GstPad * pad,
2298     GstMiniObject * obj)
2299 {
2300   GstFlowReturn ret = GST_FLOW_OK;
2301   GstBaseSinkClass *bclass;
2302   gboolean late = FALSE;
2303   GstBaseSinkPrivate *priv;
2304
2305   priv = basesink->priv;
2306
2307   /* synchronize this object, non syncable objects return OK
2308    * immediatly. */
2309   ret = gst_base_sink_do_sync (basesink, pad, obj, &late);
2310   if (G_UNLIKELY (ret != GST_FLOW_OK))
2311     goto sync_failed;
2312
2313   /* and now render, event or buffer. */
2314   if (G_LIKELY (GST_IS_BUFFER (obj))) {
2315     GstBuffer *buf;
2316
2317     /* drop late buffers unconditionally, let's hope it's unlikely */
2318     if (G_UNLIKELY (late))
2319       goto dropped;
2320
2321     buf = GST_BUFFER_CAST (obj);
2322
2323     gst_base_sink_set_last_buffer (basesink, buf);
2324
2325     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2326
2327     if (G_LIKELY (bclass->render)) {
2328       gint do_qos;
2329
2330       /* read once, to get same value before and after */
2331       do_qos = g_atomic_int_get (&priv->qos_enabled);
2332
2333       GST_DEBUG_OBJECT (basesink, "rendering buffer %p", obj);
2334
2335       /* record rendering time for QoS and stats */
2336       if (do_qos)
2337         gst_base_sink_do_render_stats (basesink, TRUE);
2338
2339       ret = bclass->render (basesink, buf);
2340
2341       priv->rendered++;
2342
2343       if (do_qos)
2344         gst_base_sink_do_render_stats (basesink, FALSE);
2345     }
2346   } else {
2347     GstEvent *event = GST_EVENT_CAST (obj);
2348     gboolean event_res = TRUE;
2349     GstEventType type;
2350
2351     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2352
2353     type = GST_EVENT_TYPE (event);
2354
2355     GST_DEBUG_OBJECT (basesink, "rendering event %p, type %s", obj,
2356         gst_event_type_get_name (type));
2357
2358     if (bclass->event)
2359       event_res = bclass->event (basesink, event);
2360
2361     /* when we get here we could be flushing again when the event handler calls
2362      * _wait_eos(). We have to ignore this object in that case. */
2363     if (G_UNLIKELY (basesink->flushing))
2364       goto flushing;
2365
2366     if (G_LIKELY (event_res)) {
2367       guint32 seqnum;
2368
2369       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
2370       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
2371
2372       switch (type) {
2373         case GST_EVENT_EOS:
2374         {
2375           GstMessage *message;
2376
2377           /* the EOS event is completely handled so we mark
2378            * ourselves as being in the EOS state. eos is also 
2379            * protected by the object lock so we can read it when 
2380            * answering the POSITION query. */
2381           GST_OBJECT_LOCK (basesink);
2382           basesink->eos = TRUE;
2383           GST_OBJECT_UNLOCK (basesink);
2384
2385           /* ok, now we can post the message */
2386           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
2387
2388           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
2389           gst_message_set_seqnum (message, seqnum);
2390           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
2391           break;
2392         }
2393         case GST_EVENT_NEWSEGMENT:
2394           /* configure the segment */
2395           gst_base_sink_configure_segment (basesink, pad, event,
2396               &basesink->segment);
2397           break;
2398         default:
2399           break;
2400       }
2401     }
2402   }
2403
2404 done:
2405   gst_base_sink_perform_qos (basesink, late);
2406
2407   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
2408   gst_mini_object_unref (obj);
2409
2410   return ret;
2411
2412   /* ERRORS */
2413 sync_failed:
2414   {
2415     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
2416     goto done;
2417   }
2418 dropped:
2419   {
2420     priv->dropped++;
2421     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
2422     goto done;
2423   }
2424 flushing:
2425   {
2426     GST_DEBUG_OBJECT (basesink, "we are flushing, ignore object");
2427     gst_mini_object_unref (obj);
2428     return GST_FLOW_WRONG_STATE;
2429   }
2430 }
2431
2432 /* with STREAM_LOCK, PREROLL_LOCK
2433  *
2434  * Perform preroll on the given object. For buffers this means 
2435  * calling the preroll subclass method. 
2436  * If that succeeds, the state will be commited.
2437  *
2438  * function does not take ownership of obj.
2439  */
2440 static GstFlowReturn
2441 gst_base_sink_preroll_object (GstBaseSink * basesink, GstPad * pad,
2442     GstMiniObject * obj)
2443 {
2444   GstFlowReturn ret;
2445
2446   GST_DEBUG_OBJECT (basesink, "do preroll %p", obj);
2447
2448   /* if it's a buffer, we need to call the preroll method */
2449   if (G_LIKELY (GST_IS_BUFFER (obj))) {
2450     GstBaseSinkClass *bclass;
2451     GstBuffer *buf;
2452     GstClockTime timestamp;
2453
2454     buf = GST_BUFFER_CAST (obj);
2455     timestamp = GST_BUFFER_TIMESTAMP (buf);
2456
2457     GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
2458         GST_TIME_ARGS (timestamp));
2459
2460     gst_base_sink_set_last_buffer (basesink, buf);
2461
2462     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2463     if (bclass->preroll)
2464       if ((ret = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
2465         goto preroll_failed;
2466   }
2467
2468   /* commit state */
2469   if (G_LIKELY (basesink->playing_async)) {
2470     if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
2471       goto stopping;
2472   }
2473
2474   return GST_FLOW_OK;
2475
2476   /* ERRORS */
2477 preroll_failed:
2478   {
2479     GST_DEBUG_OBJECT (basesink, "preroll failed, abort state");
2480     gst_element_abort_state (GST_ELEMENT_CAST (basesink));
2481     return ret;
2482   }
2483 stopping:
2484   {
2485     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
2486     return GST_FLOW_WRONG_STATE;
2487   }
2488 }
2489
2490 /* with STREAM_LOCK, PREROLL_LOCK 
2491  *
2492  * Queue an object for rendering.
2493  * The first prerollable object queued will complete the preroll. If the
2494  * preroll queue if filled, we render all the objects in the queue.
2495  *
2496  * This function takes ownership of the object.
2497  */
2498 static GstFlowReturn
2499 gst_base_sink_queue_object_unlocked (GstBaseSink * basesink, GstPad * pad,
2500     GstMiniObject * obj, gboolean prerollable)
2501 {
2502   GstFlowReturn ret = GST_FLOW_OK;
2503   gint length;
2504   GQueue *q;
2505
2506   if (G_UNLIKELY (basesink->need_preroll)) {
2507     if (G_LIKELY (prerollable))
2508       basesink->preroll_queued++;
2509
2510     length = basesink->preroll_queued;
2511
2512     GST_DEBUG_OBJECT (basesink, "now %d prerolled items", length);
2513
2514     /* first prerollable item needs to finish the preroll */
2515     if (length == 1) {
2516       ret = gst_base_sink_preroll_object (basesink, pad, obj);
2517       if (G_UNLIKELY (ret != GST_FLOW_OK))
2518         goto preroll_failed;
2519     }
2520     /* need to recheck if we need preroll, commmit state during preroll 
2521      * could have made us not need more preroll. */
2522     if (G_UNLIKELY (basesink->need_preroll)) {
2523       /* see if we can render now, if we can't add the object to the preroll
2524        * queue. */
2525       if (G_UNLIKELY (length <= basesink->preroll_queue_max_len))
2526         goto more_preroll;
2527     }
2528   }
2529
2530   /* we can start rendering (or blocking) the queued object
2531    * if any. */
2532   q = basesink->preroll_queue;
2533   while (G_UNLIKELY (!g_queue_is_empty (q))) {
2534     GstMiniObject *o;
2535
2536     o = g_queue_pop_head (q);
2537     GST_DEBUG_OBJECT (basesink, "rendering queued object %p", o);
2538
2539     /* do something with the return value */
2540     ret = gst_base_sink_render_object (basesink, pad, o);
2541     if (ret != GST_FLOW_OK)
2542       goto dequeue_failed;
2543   }
2544
2545   /* now render the object */
2546   ret = gst_base_sink_render_object (basesink, pad, obj);
2547   basesink->preroll_queued = 0;
2548
2549   return ret;
2550
2551   /* special cases */
2552 preroll_failed:
2553   {
2554     GST_DEBUG_OBJECT (basesink, "preroll failed, reason %s",
2555         gst_flow_get_name (ret));
2556     gst_mini_object_unref (obj);
2557     return ret;
2558   }
2559 more_preroll:
2560   {
2561     /* add object to the queue and return */
2562     GST_DEBUG_OBJECT (basesink, "need more preroll data %d <= %d",
2563         length, basesink->preroll_queue_max_len);
2564     g_queue_push_tail (basesink->preroll_queue, obj);
2565     return GST_FLOW_OK;
2566   }
2567 dequeue_failed:
2568   {
2569     GST_DEBUG_OBJECT (basesink, "rendering queued objects failed, reason %s",
2570         gst_flow_get_name (ret));
2571     gst_mini_object_unref (obj);
2572     return ret;
2573   }
2574 }
2575
2576 /* with STREAM_LOCK
2577  *
2578  * This function grabs the PREROLL_LOCK and adds the object to
2579  * the queue.
2580  *
2581  * This function takes ownership of obj.
2582  */
2583 static GstFlowReturn
2584 gst_base_sink_queue_object (GstBaseSink * basesink, GstPad * pad,
2585     GstMiniObject * obj, gboolean prerollable)
2586 {
2587   GstFlowReturn ret;
2588
2589   GST_PAD_PREROLL_LOCK (pad);
2590   if (G_UNLIKELY (basesink->flushing))
2591     goto flushing;
2592
2593   if (G_UNLIKELY (basesink->priv->received_eos))
2594     goto was_eos;
2595
2596   ret = gst_base_sink_queue_object_unlocked (basesink, pad, obj, prerollable);
2597   GST_PAD_PREROLL_UNLOCK (pad);
2598
2599   return ret;
2600
2601   /* ERRORS */
2602 flushing:
2603   {
2604     GST_DEBUG_OBJECT (basesink, "sink is flushing");
2605     GST_PAD_PREROLL_UNLOCK (pad);
2606     gst_mini_object_unref (obj);
2607     return GST_FLOW_WRONG_STATE;
2608   }
2609 was_eos:
2610   {
2611     GST_DEBUG_OBJECT (basesink,
2612         "we are EOS, dropping object, return UNEXPECTED");
2613     GST_PAD_PREROLL_UNLOCK (pad);
2614     gst_mini_object_unref (obj);
2615     return GST_FLOW_UNEXPECTED;
2616   }
2617 }
2618
2619 static void
2620 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
2621 {
2622   /* make sure we are not blocked on the clock also clear any pending
2623    * eos state. */
2624   gst_base_sink_set_flushing (basesink, pad, TRUE);
2625
2626   /* we grab the stream lock but that is not needed since setting the
2627    * sink to flushing would make sure no state commit is being done
2628    * anymore */
2629   GST_PAD_STREAM_LOCK (pad);
2630   gst_base_sink_reset_qos (basesink);
2631   if (basesink->priv->async_enabled) {
2632     /* and we need to commit our state again on the next
2633      * prerolled buffer */
2634     basesink->playing_async = TRUE;
2635     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
2636   } else {
2637     basesink->priv->have_latency = TRUE;
2638     basesink->need_preroll = FALSE;
2639   }
2640   gst_base_sink_set_last_buffer (basesink, NULL);
2641   GST_PAD_STREAM_UNLOCK (pad);
2642 }
2643
2644 static void
2645 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad)
2646 {
2647   /* unset flushing so we can accept new data, this also flushes out any EOS
2648    * event. */
2649   gst_base_sink_set_flushing (basesink, pad, FALSE);
2650
2651   /* for position reporting */
2652   GST_OBJECT_LOCK (basesink);
2653   basesink->priv->current_sstart = -1;
2654   basesink->priv->current_sstop = -1;
2655   basesink->priv->eos_rtime = -1;
2656   if (basesink->pad_mode == GST_ACTIVATE_PUSH) {
2657     /* we need new segment info after the flush. */
2658     basesink->have_newsegment = FALSE;
2659     gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
2660     gst_segment_init (basesink->abidata.ABI.clip_segment, GST_FORMAT_UNDEFINED);
2661   }
2662   GST_OBJECT_UNLOCK (basesink);
2663 }
2664
2665 static gboolean
2666 gst_base_sink_event (GstPad * pad, GstEvent * event)
2667 {
2668   GstBaseSink *basesink;
2669   gboolean result = TRUE;
2670   GstBaseSinkClass *bclass;
2671
2672   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
2673
2674   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2675
2676   GST_DEBUG_OBJECT (basesink, "event %p (%s)", event,
2677       GST_EVENT_TYPE_NAME (event));
2678
2679   switch (GST_EVENT_TYPE (event)) {
2680     case GST_EVENT_EOS:
2681     {
2682       GstFlowReturn ret;
2683
2684       GST_PAD_PREROLL_LOCK (pad);
2685       if (G_UNLIKELY (basesink->flushing))
2686         goto flushing;
2687
2688       if (G_UNLIKELY (basesink->priv->received_eos)) {
2689         /* we can't accept anything when we are EOS */
2690         result = FALSE;
2691         gst_event_unref (event);
2692       } else {
2693         /* we set the received EOS flag here so that we can use it when testing if
2694          * we are prerolled and to refuse more buffers. */
2695         basesink->priv->received_eos = TRUE;
2696
2697         /* EOS is a prerollable object, we call the unlocked version because it
2698          * does not check the received_eos flag. */
2699         ret = gst_base_sink_queue_object_unlocked (basesink, pad,
2700             GST_MINI_OBJECT_CAST (event), TRUE);
2701         if (G_UNLIKELY (ret != GST_FLOW_OK))
2702           result = FALSE;
2703       }
2704       GST_PAD_PREROLL_UNLOCK (pad);
2705       break;
2706     }
2707     case GST_EVENT_NEWSEGMENT:
2708     {
2709       GstFlowReturn ret;
2710
2711       GST_DEBUG_OBJECT (basesink, "newsegment %p", event);
2712
2713       GST_PAD_PREROLL_LOCK (pad);
2714       if (G_UNLIKELY (basesink->flushing))
2715         goto flushing;
2716
2717       if (G_UNLIKELY (basesink->priv->received_eos)) {
2718         /* we can't accept anything when we are EOS */
2719         result = FALSE;
2720         gst_event_unref (event);
2721       } else {
2722         /* the new segment is a non prerollable item and does not block anything,
2723          * we need to configure the current clipping segment and insert the event 
2724          * in the queue to serialize it with the buffers for rendering. */
2725         gst_base_sink_configure_segment (basesink, pad, event,
2726             basesink->abidata.ABI.clip_segment);
2727
2728         ret =
2729             gst_base_sink_queue_object_unlocked (basesink, pad,
2730             GST_MINI_OBJECT_CAST (event), FALSE);
2731         if (G_UNLIKELY (ret != GST_FLOW_OK))
2732           result = FALSE;
2733         else {
2734           GST_OBJECT_LOCK (basesink);
2735           basesink->have_newsegment = TRUE;
2736           GST_OBJECT_UNLOCK (basesink);
2737         }
2738       }
2739       GST_PAD_PREROLL_UNLOCK (pad);
2740       break;
2741     }
2742     case GST_EVENT_FLUSH_START:
2743       if (bclass->event)
2744         bclass->event (basesink, event);
2745
2746       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
2747
2748       gst_base_sink_flush_start (basesink, pad);
2749
2750       gst_event_unref (event);
2751       break;
2752     case GST_EVENT_FLUSH_STOP:
2753       if (bclass->event)
2754         bclass->event (basesink, event);
2755
2756       GST_DEBUG_OBJECT (basesink, "flush-stop %p", event);
2757
2758       gst_base_sink_flush_stop (basesink, pad);
2759
2760       gst_event_unref (event);
2761       break;
2762     default:
2763       /* other events are sent to queue or subclass depending on if they
2764        * are serialized. */
2765       if (GST_EVENT_IS_SERIALIZED (event)) {
2766         gst_base_sink_queue_object (basesink, pad,
2767             GST_MINI_OBJECT_CAST (event), FALSE);
2768       } else {
2769         if (bclass->event)
2770           bclass->event (basesink, event);
2771         gst_event_unref (event);
2772       }
2773       break;
2774   }
2775 done:
2776   gst_object_unref (basesink);
2777
2778   return result;
2779
2780   /* ERRORS */
2781 flushing:
2782   {
2783     GST_DEBUG_OBJECT (basesink, "we are flushing");
2784     GST_PAD_PREROLL_UNLOCK (pad);
2785     result = FALSE;
2786     gst_event_unref (event);
2787     goto done;
2788   }
2789 }
2790
2791 /* default implementation to calculate the start and end
2792  * timestamps on a buffer, subclasses can override
2793  */
2794 static void
2795 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
2796     GstClockTime * start, GstClockTime * end)
2797 {
2798   GstClockTime timestamp, duration;
2799
2800   timestamp = GST_BUFFER_TIMESTAMP (buffer);
2801   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
2802
2803     /* get duration to calculate end time */
2804     duration = GST_BUFFER_DURATION (buffer);
2805     if (GST_CLOCK_TIME_IS_VALID (duration)) {
2806       *end = timestamp + duration;
2807     }
2808     *start = timestamp;
2809   }
2810 }
2811
2812 /* must be called with PREROLL_LOCK */
2813 static gboolean
2814 gst_base_sink_needs_preroll (GstBaseSink * basesink)
2815 {
2816   gboolean is_prerolled, res;
2817
2818   /* we have 2 cases where the PREROLL_LOCK is released:
2819    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
2820    *  2) we are syncing on the clock
2821    */
2822   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
2823   res = !is_prerolled;
2824
2825   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
2826       basesink->have_preroll, basesink->priv->received_eos, res);
2827
2828   return res;
2829 }
2830
2831 /* with STREAM_LOCK, PREROLL_LOCK 
2832  *
2833  * Takes a buffer and compare the timestamps with the last segment.
2834  * If the buffer falls outside of the segment boundaries, drop it.
2835  * Else queue the buffer for preroll and rendering.
2836  *
2837  * This function takes ownership of the buffer.
2838  */
2839 static GstFlowReturn
2840 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
2841     GstBuffer * buf)
2842 {
2843   GstBaseSinkClass *bclass;
2844   GstFlowReturn result;
2845   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
2846   GstSegment *clip_segment;
2847
2848   if (G_UNLIKELY (basesink->flushing))
2849     goto flushing;
2850
2851   if (G_UNLIKELY (basesink->priv->received_eos))
2852     goto was_eos;
2853
2854   /* for code clarity */
2855   clip_segment = basesink->abidata.ABI.clip_segment;
2856
2857   if (G_UNLIKELY (!basesink->have_newsegment)) {
2858     gboolean sync;
2859
2860     sync = gst_base_sink_get_sync (basesink);
2861     if (sync) {
2862       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
2863           (_("Internal data flow problem.")),
2864           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
2865     }
2866
2867     /* this means this sink will assume timestamps start from 0 */
2868     GST_OBJECT_LOCK (basesink);
2869     clip_segment->start = 0;
2870     clip_segment->stop = -1;
2871     basesink->segment.start = 0;
2872     basesink->segment.stop = -1;
2873     basesink->have_newsegment = TRUE;
2874     GST_OBJECT_UNLOCK (basesink);
2875   }
2876
2877   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2878
2879   /* check if the buffer needs to be dropped, we first ask the subclass for the
2880    * start and end */
2881   if (bclass->get_times)
2882     bclass->get_times (basesink, buf, &start, &end);
2883
2884   if (start == -1) {
2885     /* if the subclass does not want sync, we use our own values so that we at
2886      * least clip the buffer to the segment */
2887     gst_base_sink_get_times (basesink, buf, &start, &end);
2888   }
2889
2890   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
2891       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
2892
2893   /* a dropped buffer does not participate in anything */
2894   if (GST_CLOCK_TIME_IS_VALID (start) &&
2895       (clip_segment->format == GST_FORMAT_TIME)) {
2896     if (G_UNLIKELY (!gst_segment_clip (clip_segment,
2897                 GST_FORMAT_TIME, (gint64) start, (gint64) end, NULL, NULL)))
2898       goto out_of_segment;
2899   }
2900
2901   /* now we can process the buffer in the queue, this function takes ownership
2902    * of the buffer */
2903   result = gst_base_sink_queue_object_unlocked (basesink, pad,
2904       GST_MINI_OBJECT_CAST (buf), TRUE);
2905
2906   return result;
2907
2908   /* ERRORS */
2909 flushing:
2910   {
2911     GST_DEBUG_OBJECT (basesink, "sink is flushing");
2912     gst_buffer_unref (buf);
2913     return GST_FLOW_WRONG_STATE;
2914   }
2915 was_eos:
2916   {
2917     GST_DEBUG_OBJECT (basesink,
2918         "we are EOS, dropping object, return UNEXPECTED");
2919     gst_buffer_unref (buf);
2920     return GST_FLOW_UNEXPECTED;
2921   }
2922 out_of_segment:
2923   {
2924     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
2925     gst_buffer_unref (buf);
2926     return GST_FLOW_OK;
2927   }
2928 }
2929
2930 /* with STREAM_LOCK
2931  */
2932 static GstFlowReturn
2933 gst_base_sink_chain (GstPad * pad, GstBuffer * buf)
2934 {
2935   GstBaseSink *basesink;
2936   GstFlowReturn result;
2937
2938   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
2939
2940   if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH))
2941     goto wrong_mode;
2942
2943   GST_PAD_PREROLL_LOCK (pad);
2944   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
2945   GST_PAD_PREROLL_UNLOCK (pad);
2946
2947 done:
2948   return result;
2949
2950   /* ERRORS */
2951 wrong_mode:
2952   {
2953     GST_OBJECT_LOCK (pad);
2954     GST_WARNING_OBJECT (basesink,
2955         "Push on pad %s:%s, but it was not activated in push mode",
2956         GST_DEBUG_PAD_NAME (pad));
2957     GST_OBJECT_UNLOCK (pad);
2958     gst_buffer_unref (buf);
2959     /* we don't post an error message this will signal to the peer
2960      * pushing that EOS is reached. */
2961     result = GST_FLOW_UNEXPECTED;
2962     goto done;
2963   }
2964 }
2965
2966 static gboolean
2967 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
2968 {
2969   gboolean res = TRUE;
2970
2971   /* update our offset if the start/stop position was updated */
2972   if (segment->format == GST_FORMAT_BYTES) {
2973     segment->time = segment->start;
2974   } else if (segment->start == 0) {
2975     /* seek to start, we can implement a default for this. */
2976     segment->time = 0;
2977   } else {
2978     res = FALSE;
2979     GST_INFO_OBJECT (sink, "Can't do a default seek");
2980   }
2981
2982   return res;
2983 }
2984
2985 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
2986
2987 static gboolean
2988 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
2989     GstEvent * event, GstSegment * segment)
2990 {
2991   /* By default, we try one of 2 things:
2992    *   - For absolute seek positions, convert the requested position to our 
2993    *     configured processing format and place it in the output segment \
2994    *   - For relative seek positions, convert our current (input) values to the
2995    *     seek format, adjust by the relative seek offset and then convert back to
2996    *     the processing format
2997    */
2998   GstSeekType cur_type, stop_type;
2999   gint64 cur, stop;
3000   GstSeekFlags flags;
3001   GstFormat seek_format, dest_format;
3002   gdouble rate;
3003   gboolean update;
3004   gboolean res = TRUE;
3005
3006   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3007       &cur_type, &cur, &stop_type, &stop);
3008   dest_format = segment->format;
3009
3010   if (seek_format == dest_format) {
3011     gst_segment_set_seek (segment, rate, seek_format, flags,
3012         cur_type, cur, stop_type, stop, &update);
3013     return TRUE;
3014   }
3015
3016   if (cur_type != GST_SEEK_TYPE_NONE) {
3017     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3018     res =
3019         gst_pad_query_convert (sink->sinkpad, seek_format, cur, &dest_format,
3020         &cur);
3021     cur_type = GST_SEEK_TYPE_SET;
3022   }
3023
3024   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3025     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3026     res =
3027         gst_pad_query_convert (sink->sinkpad, seek_format, stop, &dest_format,
3028         &stop);
3029     stop_type = GST_SEEK_TYPE_SET;
3030   }
3031
3032   /* And finally, configure our output segment in the desired format */
3033   gst_segment_set_seek (segment, rate, dest_format, flags, cur_type, cur,
3034       stop_type, stop, &update);
3035
3036   if (!res)
3037     goto no_format;
3038
3039   return res;
3040
3041 no_format:
3042   {
3043     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3044     return FALSE;
3045   }
3046 }
3047
3048 /* perform a seek, only executed in pull mode */
3049 static gboolean
3050 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3051 {
3052   gboolean flush;
3053   gdouble rate;
3054   GstFormat seek_format, dest_format;
3055   GstSeekFlags flags;
3056   GstSeekType cur_type, stop_type;
3057   gboolean seekseg_configured = FALSE;
3058   gint64 cur, stop;
3059   gboolean update, res = TRUE;
3060   GstSegment seeksegment;
3061
3062   dest_format = sink->segment.format;
3063
3064   if (event) {
3065     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3066     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3067         &cur_type, &cur, &stop_type, &stop);
3068
3069     flush = flags & GST_SEEK_FLAG_FLUSH;
3070   } else {
3071     GST_DEBUG_OBJECT (sink, "performing seek without event");
3072     flush = FALSE;
3073   }
3074
3075   if (flush) {
3076     GST_DEBUG_OBJECT (sink, "flushing upstream");
3077     gst_pad_push_event (pad, gst_event_new_flush_start ());
3078     gst_base_sink_flush_start (sink, pad);
3079   } else {
3080     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3081   }
3082
3083   GST_PAD_STREAM_LOCK (pad);
3084
3085   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3086    * copy the current segment info into the temp segment that we can actually
3087    * attempt the seek with. We only update the real segment if the seek suceeds. */
3088   if (!seekseg_configured) {
3089     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3090
3091     /* now configure the final seek segment */
3092     if (event) {
3093       if (sink->segment.format != seek_format) {
3094         /* OK, here's where we give the subclass a chance to convert the relative
3095          * seek into an absolute one in the processing format. We set up any
3096          * absolute seek above, before taking the stream lock. */
3097         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3098                 &seeksegment)) {
3099           GST_DEBUG_OBJECT (sink,
3100               "Preparing the seek failed after flushing. " "Aborting seek");
3101           res = FALSE;
3102         }
3103       } else {
3104         /* The seek format matches our processing format, no need to ask the
3105          * the subclass to configure the segment. */
3106         gst_segment_set_seek (&seeksegment, rate, seek_format, flags,
3107             cur_type, cur, stop_type, stop, &update);
3108       }
3109     }
3110     /* Else, no seek event passed, so we're just (re)starting the 
3111        current segment. */
3112   }
3113
3114   if (res) {
3115     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3116         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3117         seeksegment.start, seeksegment.stop, seeksegment.last_stop);
3118
3119     /* do the seek, segment.last_stop contains the new position. */
3120     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3121   }
3122
3123
3124   if (flush) {
3125     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3126     gst_pad_push_event (pad, gst_event_new_flush_stop ());
3127     gst_base_sink_flush_stop (sink, pad);
3128   } else if (res && sink->abidata.ABI.running) {
3129     /* we are running the current segment and doing a non-flushing seek, 
3130      * close the segment first based on the last_stop. */
3131     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3132         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.last_stop);
3133   }
3134
3135   /* The subclass must have converted the segment to the processing format 
3136    * by now */
3137   if (res && seeksegment.format != dest_format) {
3138     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3139         "in the correct format. Aborting seek.");
3140     res = FALSE;
3141   }
3142
3143   /* if successfull seek, we update our real segment and push
3144    * out the new segment. */
3145   if (res) {
3146     memcpy (&sink->segment, &seeksegment, sizeof (GstSegment));
3147
3148     if (sink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3149       gst_element_post_message (GST_ELEMENT (sink),
3150           gst_message_new_segment_start (GST_OBJECT (sink),
3151               sink->segment.format, sink->segment.last_stop));
3152     }
3153   }
3154
3155   sink->priv->discont = TRUE;
3156   sink->abidata.ABI.running = TRUE;
3157
3158   GST_PAD_STREAM_UNLOCK (pad);
3159
3160   return res;
3161 }
3162
3163 /* with STREAM_LOCK
3164  */
3165 static void
3166 gst_base_sink_loop (GstPad * pad)
3167 {
3168   GstBaseSink *basesink;
3169   GstBuffer *buf = NULL;
3170   GstFlowReturn result;
3171   guint blocksize;
3172   guint64 offset;
3173
3174   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3175
3176   g_assert (basesink->pad_mode == GST_ACTIVATE_PULL);
3177
3178   if ((blocksize = basesink->priv->blocksize) == 0)
3179     blocksize = -1;
3180
3181   offset = basesink->segment.last_stop;
3182
3183   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
3184       offset, blocksize);
3185
3186   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
3187   if (G_UNLIKELY (result != GST_FLOW_OK))
3188     goto paused;
3189
3190   if (G_UNLIKELY (buf == NULL))
3191     goto no_buffer;
3192
3193   offset += GST_BUFFER_SIZE (buf);
3194
3195   gst_segment_set_last_stop (&basesink->segment, GST_FORMAT_BYTES, offset);
3196
3197   GST_PAD_PREROLL_LOCK (pad);
3198   result = gst_base_sink_chain_unlocked (basesink, pad, buf);
3199   GST_PAD_PREROLL_UNLOCK (pad);
3200   if (G_UNLIKELY (result != GST_FLOW_OK))
3201     goto paused;
3202
3203   return;
3204
3205   /* ERRORS */
3206 paused:
3207   {
3208     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
3209         gst_flow_get_name (result));
3210     gst_pad_pause_task (pad);
3211     /* fatal errors and NOT_LINKED cause EOS */
3212     if (GST_FLOW_IS_FATAL (result) || result == GST_FLOW_NOT_LINKED) {
3213       if (result == GST_FLOW_UNEXPECTED) {
3214         /* perform EOS logic */
3215         if (basesink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3216           gst_element_post_message (GST_ELEMENT_CAST (basesink),
3217               gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
3218                   basesink->segment.format, basesink->segment.last_stop));
3219         } else {
3220           gst_base_sink_event (pad, gst_event_new_eos ());
3221         }
3222       } else {
3223         /* for fatal errors we post an error message, post the error
3224          * first so the app knows about the error first. */
3225         GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3226             (_("Internal data stream error.")),
3227             ("stream stopped, reason %s", gst_flow_get_name (result)));
3228         gst_base_sink_event (pad, gst_event_new_eos ());
3229       }
3230     }
3231     return;
3232   }
3233 no_buffer:
3234   {
3235     GST_LOG_OBJECT (basesink, "no buffer, pausing");
3236     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3237         (_("Internal data flow error.")), ("element returned NULL buffer"));
3238     result = GST_FLOW_ERROR;
3239     goto paused;
3240   }
3241 }
3242
3243 static gboolean
3244 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
3245     gboolean flushing)
3246 {
3247   GstBaseSinkClass *bclass;
3248
3249   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3250
3251   if (flushing) {
3252     /* unlock any subclasses, we need to do this before grabbing the
3253      * PREROLL_LOCK since we hold this lock before going into ::render. */
3254     if (bclass->unlock)
3255       bclass->unlock (basesink);
3256   }
3257
3258   GST_PAD_PREROLL_LOCK (pad);
3259   basesink->flushing = flushing;
3260   if (flushing) {
3261     /* step 1, now that we have the PREROLL lock, clear our unlock request */
3262     if (bclass->unlock_stop)
3263       bclass->unlock_stop (basesink);
3264
3265     /* set need_preroll before we unblock the clock. If the clock is unblocked
3266      * before timing out, we can reuse the buffer for preroll. */
3267     basesink->need_preroll = TRUE;
3268
3269     /* step 2, unblock clock sync (if any) or any other blocking thing */
3270     if (basesink->clock_id) {
3271       gst_clock_id_unschedule (basesink->clock_id);
3272     }
3273
3274     /* flush out the data thread if it's locked in finish_preroll, this will
3275      * also flush out the EOS state */
3276     GST_DEBUG_OBJECT (basesink,
3277         "flushing out data thread, need preroll to TRUE");
3278     gst_base_sink_preroll_queue_flush (basesink, pad);
3279   }
3280   GST_PAD_PREROLL_UNLOCK (pad);
3281
3282   return TRUE;
3283 }
3284
3285 static gboolean
3286 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
3287 {
3288   gboolean result;
3289
3290   if (active) {
3291     /* start task */
3292     result = gst_pad_start_task (basesink->sinkpad,
3293         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad);
3294   } else {
3295     /* step 2, make sure streaming finishes */
3296     result = gst_pad_stop_task (basesink->sinkpad);
3297   }
3298
3299   return result;
3300 }
3301
3302 static gboolean
3303 gst_base_sink_pad_activate (GstPad * pad)
3304 {
3305   gboolean result = FALSE;
3306   GstBaseSink *basesink;
3307
3308   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3309
3310   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
3311
3312   gst_base_sink_set_flushing (basesink, pad, FALSE);
3313
3314   /* we need to have the pull mode enabled */
3315   if (!basesink->can_activate_pull) {
3316     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
3317     goto fallback;
3318   }
3319
3320   /* check if downstreams supports pull mode at all */
3321   if (!gst_pad_check_pull_range (pad)) {
3322     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
3323     goto fallback;
3324   }
3325
3326   /* set the pad mode before starting the task so that it's in the
3327    * correct state for the new thread. also the sink set_caps and get_caps
3328    * function checks this */
3329   basesink->pad_mode = GST_ACTIVATE_PULL;
3330
3331   /* we first try to negotiate a format so that when we try to activate
3332    * downstream, it knows about our format */
3333   if (!gst_base_sink_negotiate_pull (basesink)) {
3334     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
3335     goto fallback;
3336   }
3337
3338   /* ok activate now */
3339   if (!gst_pad_activate_pull (pad, TRUE)) {
3340     /* clear any pending caps */
3341     GST_OBJECT_LOCK (basesink);
3342     gst_caps_replace (&basesink->priv->pull_caps, NULL);
3343     GST_OBJECT_UNLOCK (basesink);
3344     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
3345     goto fallback;
3346   }
3347
3348   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
3349   result = TRUE;
3350   goto done;
3351
3352   /* push mode fallback */
3353 fallback:
3354   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
3355   if ((result = gst_pad_activate_push (pad, TRUE))) {
3356     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
3357   }
3358
3359 done:
3360   if (!result) {
3361     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
3362     gst_base_sink_set_flushing (basesink, pad, TRUE);
3363   }
3364
3365   gst_object_unref (basesink);
3366
3367   return result;
3368 }
3369
3370 static gboolean
3371 gst_base_sink_pad_activate_push (GstPad * pad, gboolean active)
3372 {
3373   gboolean result;
3374   GstBaseSink *basesink;
3375
3376   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3377
3378   if (active) {
3379     if (!basesink->can_activate_push) {
3380       result = FALSE;
3381       basesink->pad_mode = GST_ACTIVATE_NONE;
3382     } else {
3383       result = TRUE;
3384       basesink->pad_mode = GST_ACTIVATE_PUSH;
3385     }
3386   } else {
3387     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH)) {
3388       g_warning ("Internal GStreamer activation error!!!");
3389       result = FALSE;
3390     } else {
3391       gst_base_sink_set_flushing (basesink, pad, TRUE);
3392       result = TRUE;
3393       basesink->pad_mode = GST_ACTIVATE_NONE;
3394     }
3395   }
3396
3397   gst_object_unref (basesink);
3398
3399   return result;
3400 }
3401
3402 static gboolean
3403 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
3404 {
3405   GstCaps *caps;
3406   gboolean result;
3407
3408   result = FALSE;
3409
3410   /* this returns the intersection between our caps and the peer caps. If there
3411    * is no peer, it returns NULL and we can't operate in pull mode so we can
3412    * fail the negotiation. */
3413   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
3414   if (caps == NULL || gst_caps_is_empty (caps))
3415     goto no_caps_possible;
3416
3417   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
3418
3419   caps = gst_caps_make_writable (caps);
3420   /* get the first (prefered) format */
3421   gst_caps_truncate (caps);
3422   /* try to fixate */
3423   gst_pad_fixate_caps (GST_BASE_SINK_PAD (basesink), caps);
3424
3425   GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
3426
3427   if (gst_caps_is_any (caps)) {
3428     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
3429         "allowing pull()");
3430     /* neither side has template caps in this case, so they are prepared for
3431        pull() without setcaps() */
3432     result = TRUE;
3433   } else if (gst_caps_is_fixed (caps)) {
3434     if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
3435       goto could_not_set_caps;
3436
3437     GST_OBJECT_LOCK (basesink);
3438     gst_caps_replace (&basesink->priv->pull_caps, caps);
3439     GST_OBJECT_UNLOCK (basesink);
3440
3441     result = TRUE;
3442   }
3443
3444   gst_caps_unref (caps);
3445
3446   return result;
3447
3448 no_caps_possible:
3449   {
3450     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
3451     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
3452     if (caps)
3453       gst_caps_unref (caps);
3454     return FALSE;
3455   }
3456 could_not_set_caps:
3457   {
3458     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
3459     gst_caps_unref (caps);
3460     return FALSE;
3461   }
3462 }
3463
3464 /* this won't get called until we implement an activate function */
3465 static gboolean
3466 gst_base_sink_pad_activate_pull (GstPad * pad, gboolean active)
3467 {
3468   gboolean result = FALSE;
3469   GstBaseSink *basesink;
3470   GstBaseSinkClass *bclass;
3471
3472   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3473   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3474
3475   if (active) {
3476     GstFormat format;
3477     gint64 duration;
3478
3479     /* we mark we have a newsegment here because pull based
3480      * mode works just fine without having a newsegment before the
3481      * first buffer */
3482     format = GST_FORMAT_BYTES;
3483
3484     gst_segment_init (&basesink->segment, format);
3485     gst_segment_init (basesink->abidata.ABI.clip_segment, format);
3486     GST_OBJECT_LOCK (basesink);
3487     basesink->have_newsegment = TRUE;
3488     GST_OBJECT_UNLOCK (basesink);
3489
3490     /* get the peer duration in bytes */
3491     result = gst_pad_query_peer_duration (pad, &format, &duration);
3492     if (result) {
3493       GST_DEBUG_OBJECT (basesink,
3494           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
3495       gst_segment_set_duration (basesink->abidata.ABI.clip_segment, format,
3496           duration);
3497       gst_segment_set_duration (&basesink->segment, format, duration);
3498     } else {
3499       GST_DEBUG_OBJECT (basesink, "unknown duration");
3500     }
3501
3502     if (bclass->activate_pull)
3503       result = bclass->activate_pull (basesink, TRUE);
3504     else
3505       result = FALSE;
3506
3507     if (!result)
3508       goto activate_failed;
3509
3510     /* but if starting the thread fails, set it back */
3511     if (!result)
3512       basesink->pad_mode = GST_ACTIVATE_NONE;
3513   } else {
3514     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PULL)) {
3515       g_warning ("Internal GStreamer activation error!!!");
3516       result = FALSE;
3517     } else {
3518       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
3519       if (bclass->activate_pull)
3520         result &= bclass->activate_pull (basesink, FALSE);
3521       basesink->pad_mode = GST_ACTIVATE_NONE;
3522       /* clear any pending caps */
3523       GST_OBJECT_LOCK (basesink);
3524       gst_caps_replace (&basesink->priv->pull_caps, NULL);
3525       GST_OBJECT_UNLOCK (basesink);
3526     }
3527   }
3528   gst_object_unref (basesink);
3529
3530   return result;
3531
3532   /* ERRORS */
3533 activate_failed:
3534   {
3535     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
3536     return FALSE;
3537   }
3538 }
3539
3540 /* send an event to our sinkpad peer. */
3541 static gboolean
3542 gst_base_sink_send_event (GstElement * element, GstEvent * event)
3543 {
3544   GstPad *pad;
3545   GstBaseSink *basesink = GST_BASE_SINK (element);
3546   gboolean forward, result = TRUE;
3547   GstActivateMode mode;
3548
3549   GST_OBJECT_LOCK (element);
3550   /* get the pad and the scheduling mode */
3551   pad = gst_object_ref (basesink->sinkpad);
3552   mode = basesink->pad_mode;
3553   GST_OBJECT_UNLOCK (element);
3554
3555   /* only push UPSTREAM events upstream and if we are in push mode */
3556   forward = GST_EVENT_IS_UPSTREAM (event) && (mode == GST_ACTIVATE_PUSH);
3557
3558   switch (GST_EVENT_TYPE (event)) {
3559     case GST_EVENT_LATENCY:
3560     {
3561       GstClockTime latency;
3562
3563       gst_event_parse_latency (event, &latency);
3564
3565       /* store the latency. We use this to adjust the running_time before syncing
3566        * it to the clock. */
3567       GST_OBJECT_LOCK (element);
3568       basesink->priv->latency = latency;
3569       GST_OBJECT_UNLOCK (element);
3570       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
3571           GST_TIME_ARGS (latency));
3572
3573       /* We forward this event so that all elements know about the global pipeline
3574        * latency. This is interesting for an element when it wants to figure out
3575        * when a particular piece of data will be rendered. */
3576       break;
3577     }
3578     case GST_EVENT_SEEK:
3579       /* in pull mode we will execute the seek */
3580       if (mode == GST_ACTIVATE_PULL)
3581         result = gst_base_sink_perform_seek (basesink, pad, event);
3582       break;
3583     default:
3584       break;
3585   }
3586
3587   if (forward) {
3588     result = gst_pad_push_event (pad, event);
3589   } else {
3590     /* not forwarded, unref the event */
3591     gst_event_unref (event);
3592   }
3593
3594   gst_object_unref (pad);
3595   return result;
3596 }
3597
3598 static gboolean
3599 gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query)
3600 {
3601   GstPad *peer;
3602   gboolean res = FALSE;
3603
3604   if ((peer = gst_pad_get_peer (sink->sinkpad))) {
3605     res = gst_pad_query (peer, query);
3606     gst_object_unref (peer);
3607   }
3608   return res;
3609 }
3610
3611 /* get the end position of the last seen object, this is used
3612  * for EOS and for making sure that we don't report a position we
3613  * have not reached yet. */
3614 static gboolean
3615 gst_base_sink_get_position_last (GstBaseSink * basesink, GstFormat format,
3616     gint64 * cur)
3617 {
3618   GstFormat oformat;
3619   GstSegment *segment;
3620   gboolean ret = TRUE;
3621
3622   segment = &basesink->segment;
3623   oformat = segment->format;
3624
3625   if (oformat == GST_FORMAT_TIME) {
3626     /* return last observed stream time, we keep the stream time around in the
3627      * time format. */
3628     *cur = basesink->priv->current_sstop;
3629   } else {
3630     /* convert last stop to stream time */
3631     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3632   }
3633
3634   if (*cur != -1 && oformat != format) {
3635     /* convert to the target format if we need to */
3636     ret =
3637         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3638   }
3639
3640   GST_DEBUG_OBJECT (basesink, "POSITION: %" GST_TIME_FORMAT,
3641       GST_TIME_ARGS (*cur));
3642
3643   return ret;
3644 }
3645
3646 /* get the position when we are PAUSED, this is the stream time of the buffer
3647  * that prerolled. If no buffer is prerolled (we are still flushing), this
3648  * value will be -1. */
3649 static gboolean
3650 gst_base_sink_get_position_paused (GstBaseSink * basesink, GstFormat format,
3651     gint64 * cur)
3652 {
3653   gboolean res;
3654   gint64 time;
3655   GstSegment *segment;
3656   GstFormat oformat;
3657
3658   /* we don't use the clip segment in pull mode, when seeking we update the
3659    * main segment directly with the new segment values without it having to be
3660    * activated by the rendering after preroll */
3661   if (basesink->pad_mode == GST_ACTIVATE_PUSH)
3662     segment = basesink->abidata.ABI.clip_segment;
3663   else
3664     segment = &basesink->segment;
3665   oformat = segment->format;
3666
3667   if (oformat == GST_FORMAT_TIME) {
3668     *cur = basesink->priv->current_sstart;
3669   } else {
3670     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
3671   }
3672
3673   time = segment->time;
3674
3675   if (*cur != -1) {
3676     *cur = MAX (*cur, time);
3677     GST_DEBUG_OBJECT (basesink, "POSITION as max: %" GST_TIME_FORMAT
3678         ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (*cur), GST_TIME_ARGS (time));
3679   } else {
3680     /* we have no buffer, use the segment times. */
3681     if (segment->rate >= 0.0) {
3682       /* forward, next position is always the time of the segment */
3683       *cur = time;
3684       GST_DEBUG_OBJECT (basesink, "POSITION as time: %" GST_TIME_FORMAT,
3685           GST_TIME_ARGS (*cur));
3686     } else {
3687       /* reverse, next expected timestamp is segment->stop. We use the function
3688        * to get things right for negative applied_rates. */
3689       *cur = gst_segment_to_stream_time (segment, oformat, segment->stop);
3690       GST_DEBUG_OBJECT (basesink, "reverse POSITION: %" GST_TIME_FORMAT,
3691           GST_TIME_ARGS (*cur));
3692     }
3693   }
3694   res = (*cur != -1);
3695   if (res && oformat != format) {
3696     res =
3697         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
3698   }
3699
3700   return res;
3701 }
3702
3703 static gboolean
3704 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
3705     gint64 * cur, gboolean * upstream)
3706 {
3707   GstClock *clock;
3708   gboolean res = FALSE;
3709   GstFormat oformat, tformat;
3710   GstClockTime now, base, latency;
3711   gint64 time, accum, duration;
3712   gdouble rate;
3713   gint64 last;
3714
3715   GST_OBJECT_LOCK (basesink);
3716   /* our intermediate time format */
3717   tformat = GST_FORMAT_TIME;
3718   /* get the format in the segment */
3719   oformat = basesink->segment.format;
3720
3721   /* can only give answer based on the clock if not EOS */
3722   if (G_UNLIKELY (basesink->eos))
3723     goto in_eos;
3724
3725   /* we can only get the segment when we are not NULL or READY */
3726   if (!basesink->have_newsegment)
3727     goto wrong_state;
3728
3729   /* when not in PLAYING or when we're busy with a state change, we
3730    * cannot read from the clock so we report time based on the
3731    * last seen timestamp. */
3732   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
3733       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING)
3734     goto in_pause;
3735
3736   /* we need to sync on the clock. */
3737   if (basesink->sync == FALSE)
3738     goto no_sync;
3739
3740   /* and we need a clock */
3741   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
3742     goto no_sync;
3743
3744   /* collect all data we need holding the lock */
3745   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.time))
3746     time = basesink->segment.time;
3747   else
3748     time = 0;
3749
3750   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.stop))
3751     duration = basesink->segment.stop - basesink->segment.start;
3752   else
3753     duration = 0;
3754
3755   base = GST_ELEMENT_CAST (basesink)->base_time;
3756   accum = basesink->segment.accum;
3757   rate = basesink->segment.rate * basesink->segment.applied_rate;
3758   gst_base_sink_get_position_last (basesink, format, &last);
3759   latency = basesink->priv->latency;
3760
3761   gst_object_ref (clock);
3762   /* need to release the object lock before we can get the time, 
3763    * a clock might take the LOCK of the provider, which could be
3764    * a basesink subclass. */
3765   GST_OBJECT_UNLOCK (basesink);
3766
3767   now = gst_clock_get_time (clock);
3768
3769   if (oformat != tformat) {
3770     /* convert accum, time and duration to time */
3771     if (!gst_pad_query_convert (basesink->sinkpad, oformat, accum, &tformat,
3772             &accum))
3773       goto convert_failed;
3774     if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration, &tformat,
3775             &duration))
3776       goto convert_failed;
3777     if (!gst_pad_query_convert (basesink->sinkpad, oformat, time, &tformat,
3778             &time))
3779       goto convert_failed;
3780   }
3781
3782   /* subtract base time and accumulated time from the clock time. 
3783    * Make sure we don't go negative. This is the current time in
3784    * the segment which we need to scale with the combined 
3785    * rate and applied rate. */
3786   base += accum;
3787   base += latency;
3788   base = MIN (now, base);
3789
3790   /* for negative rates we need to count back from from the segment
3791    * duration. */
3792   if (rate < 0.0)
3793     time += duration;
3794
3795   *cur = time + gst_guint64_to_gdouble (now - base) * rate;
3796
3797   /* never report more than last seen position */
3798   if (last != -1)
3799     *cur = MIN (last, *cur);
3800
3801   gst_object_unref (clock);
3802
3803   GST_DEBUG_OBJECT (basesink,
3804       "now %" GST_TIME_FORMAT " - base %" GST_TIME_FORMAT " - accum %"
3805       GST_TIME_FORMAT " + time %" GST_TIME_FORMAT,
3806       GST_TIME_ARGS (now), GST_TIME_ARGS (base),
3807       GST_TIME_ARGS (accum), GST_TIME_ARGS (time));
3808
3809   if (oformat != format) {
3810     /* convert time to final format */
3811     if (!gst_pad_query_convert (basesink->sinkpad, tformat, *cur, &format, cur))
3812       goto convert_failed;
3813   }
3814
3815   res = TRUE;
3816
3817 done:
3818   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
3819       res, GST_TIME_ARGS (*cur));
3820   return res;
3821
3822   /* special cases */
3823 in_eos:
3824   {
3825     GST_DEBUG_OBJECT (basesink, "position in EOS");
3826     res = gst_base_sink_get_position_last (basesink, format, cur);
3827     GST_OBJECT_UNLOCK (basesink);
3828     goto done;
3829   }
3830 in_pause:
3831   {
3832     GST_DEBUG_OBJECT (basesink, "position in PAUSED");
3833     res = gst_base_sink_get_position_paused (basesink, format, cur);
3834     GST_OBJECT_UNLOCK (basesink);
3835     goto done;
3836   }
3837 wrong_state:
3838   {
3839     /* in NULL or READY we always return FALSE and -1 */
3840     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
3841     res = FALSE;
3842     *cur = -1;
3843     GST_OBJECT_UNLOCK (basesink);
3844     goto done;
3845   }
3846 no_sync:
3847   {
3848     /* report last seen timestamp if any, else ask upstream to answer */
3849     if ((*cur = basesink->priv->current_sstart) != -1)
3850       res = TRUE;
3851     else
3852       *upstream = TRUE;
3853
3854     GST_DEBUG_OBJECT (basesink, "no sync, res %d, POSITION %" GST_TIME_FORMAT,
3855         res, GST_TIME_ARGS (*cur));
3856     GST_OBJECT_UNLOCK (basesink);
3857     return res;
3858   }
3859 convert_failed:
3860   {
3861     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
3862     *upstream = TRUE;
3863     return FALSE;
3864   }
3865 }
3866
3867 static gboolean
3868 gst_base_sink_query (GstElement * element, GstQuery * query)
3869 {
3870   gboolean res = FALSE;
3871
3872   GstBaseSink *basesink = GST_BASE_SINK (element);
3873
3874   switch (GST_QUERY_TYPE (query)) {
3875     case GST_QUERY_POSITION:
3876     {
3877       gint64 cur = 0;
3878       GstFormat format;
3879       gboolean upstream = FALSE;
3880
3881       gst_query_parse_position (query, &format, NULL);
3882
3883       GST_DEBUG_OBJECT (basesink, "position format %d", format);
3884
3885       /* first try to get the position based on the clock */
3886       if ((res =
3887               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
3888         gst_query_set_position (query, format, cur);
3889       } else if (upstream) {
3890         /* fallback to peer query */
3891         res = gst_base_sink_peer_query (basesink, query);
3892       }
3893       break;
3894     }
3895     case GST_QUERY_DURATION:
3896     {
3897       GstFormat format, uformat;
3898       gint64 duration, uduration;
3899
3900       gst_query_parse_duration (query, &format, NULL);
3901
3902       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
3903           gst_format_get_name (format));
3904
3905       if (basesink->pad_mode == GST_ACTIVATE_PULL) {
3906         uformat = GST_FORMAT_BYTES;
3907
3908         /* get the duration in bytes, in pull mode that's all we are sure to
3909          * know. We have to explicitly get this value from upstream instead of
3910          * using our cached value because it might change. Duration caching
3911          * should be done at a higher level. */
3912         res = gst_pad_query_peer_duration (basesink->sinkpad, &uformat,
3913             &uduration);
3914         if (res) {
3915           gst_segment_set_duration (&basesink->segment, uformat, uduration);
3916           if (format != uformat) {
3917             /* convert to the requested format */
3918             res = gst_pad_query_convert (basesink->sinkpad, uformat, uduration,
3919                 &format, &duration);
3920           } else {
3921             duration = uduration;
3922           }
3923           if (res) {
3924             /* set the result */
3925             gst_query_set_duration (query, format, duration);
3926           }
3927         }
3928       } else {
3929         /* in push mode we simply forward upstream */
3930         res = gst_base_sink_peer_query (basesink, query);
3931       }
3932       break;
3933     }
3934     case GST_QUERY_LATENCY:
3935     {
3936       gboolean live, us_live;
3937       GstClockTime min, max;
3938
3939       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
3940                   &max))) {
3941         gst_query_set_latency (query, live, min, max);
3942       }
3943       break;
3944     }
3945     case GST_QUERY_JITTER:
3946       break;
3947     case GST_QUERY_RATE:
3948       /* gst_query_set_rate (query, basesink->segment_rate); */
3949       res = TRUE;
3950       break;
3951     case GST_QUERY_SEGMENT:
3952     {
3953       /* FIXME, bring start/stop to stream time */
3954       gst_query_set_segment (query, basesink->segment.rate,
3955           GST_FORMAT_TIME, basesink->segment.start, basesink->segment.stop);
3956       break;
3957     }
3958     case GST_QUERY_SEEKING:
3959     case GST_QUERY_CONVERT:
3960     case GST_QUERY_FORMATS:
3961     default:
3962       res = gst_base_sink_peer_query (basesink, query);
3963       break;
3964   }
3965   return res;
3966 }
3967
3968 static GstStateChangeReturn
3969 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
3970 {
3971   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3972   GstBaseSink *basesink = GST_BASE_SINK (element);
3973   GstBaseSinkClass *bclass;
3974   GstBaseSinkPrivate *priv;
3975
3976   priv = basesink->priv;
3977
3978   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3979
3980   switch (transition) {
3981     case GST_STATE_CHANGE_NULL_TO_READY:
3982       if (bclass->start)
3983         if (!bclass->start (basesink))
3984           goto start_failed;
3985       break;
3986     case GST_STATE_CHANGE_READY_TO_PAUSED:
3987       /* need to complete preroll before this state change completes, there
3988        * is no data flow in READY so we can safely assume we need to preroll. */
3989       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
3990       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
3991       basesink->have_newsegment = FALSE;
3992       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
3993       gst_segment_init (basesink->abidata.ABI.clip_segment,
3994           GST_FORMAT_UNDEFINED);
3995       basesink->offset = 0;
3996       basesink->have_preroll = FALSE;
3997       basesink->need_preroll = TRUE;
3998       basesink->playing_async = TRUE;
3999       priv->current_sstart = -1;
4000       priv->current_sstop = -1;
4001       priv->eos_rtime = -1;
4002       priv->latency = 0;
4003       basesink->eos = FALSE;
4004       priv->received_eos = FALSE;
4005       gst_base_sink_reset_qos (basesink);
4006       priv->commited = FALSE;
4007       if (priv->async_enabled) {
4008         GST_DEBUG_OBJECT (basesink, "doing async state change");
4009         /* when async enabled, post async-start message and return ASYNC from
4010          * the state change function */
4011         ret = GST_STATE_CHANGE_ASYNC;
4012         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4013             gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4014       } else {
4015         priv->have_latency = TRUE;
4016       }
4017       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4018       break;
4019     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4020       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4021       if (!gst_base_sink_needs_preroll (basesink)) {
4022         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
4023         /* no preroll needed anymore now. */
4024         basesink->playing_async = FALSE;
4025         basesink->need_preroll = FALSE;
4026         if (basesink->eos) {
4027           GstMessage *message;
4028
4029           /* need to post EOS message here */
4030           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
4031           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
4032           gst_message_set_seqnum (message, basesink->priv->seqnum);
4033           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
4034         } else {
4035           GST_DEBUG_OBJECT (basesink, "signal preroll");
4036           GST_PAD_PREROLL_SIGNAL (basesink->sinkpad);
4037         }
4038       } else {
4039         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
4040         basesink->need_preroll = TRUE;
4041         basesink->playing_async = TRUE;
4042         priv->commited = FALSE;
4043         if (priv->async_enabled) {
4044           GST_DEBUG_OBJECT (basesink, "doing async state change");
4045           ret = GST_STATE_CHANGE_ASYNC;
4046           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4047               gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4048         }
4049       }
4050       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4051       break;
4052     default:
4053       break;
4054   }
4055
4056   {
4057     GstStateChangeReturn bret;
4058
4059     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4060     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
4061       goto activate_failed;
4062   }
4063
4064   switch (transition) {
4065     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4066       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
4067       /* FIXME, make sure we cannot enter _render first */
4068
4069       /* we need to call ::unlock before locking PREROLL_LOCK
4070        * since we lock it before going into ::render */
4071       if (bclass->unlock)
4072         bclass->unlock (basesink);
4073
4074       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4075       /* now that we have the PREROLL lock, clear our unlock request */
4076       if (bclass->unlock_stop)
4077         bclass->unlock_stop (basesink);
4078
4079       /* we need preroll again and we set the flag before unlocking the clockid
4080        * because if the clockid is unlocked before a current buffer expired, we
4081        * can use that buffer to preroll with */
4082       basesink->need_preroll = TRUE;
4083
4084       if (basesink->clock_id) {
4085         gst_clock_id_unschedule (basesink->clock_id);
4086       }
4087
4088       /* if we don't have a preroll buffer we need to wait for a preroll and
4089        * return ASYNC. */
4090       if (!gst_base_sink_needs_preroll (basesink)) {
4091         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
4092         basesink->playing_async = FALSE;
4093       } else {
4094         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
4095           ret = GST_STATE_CHANGE_SUCCESS;
4096         } else {
4097           GST_DEBUG_OBJECT (basesink,
4098               "PLAYING to PAUSED, we are not prerolled");
4099           basesink->playing_async = TRUE;
4100           priv->commited = FALSE;
4101           if (priv->async_enabled) {
4102             GST_DEBUG_OBJECT (basesink, "doing async state change");
4103             ret = GST_STATE_CHANGE_ASYNC;
4104             gst_element_post_message (GST_ELEMENT_CAST (basesink),
4105                 gst_message_new_async_start (GST_OBJECT_CAST (basesink),
4106                     FALSE));
4107           }
4108         }
4109       }
4110       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
4111           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
4112
4113       gst_base_sink_reset_qos (basesink);
4114       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4115       break;
4116     case GST_STATE_CHANGE_PAUSED_TO_READY:
4117       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4118       /* start by reseting our position state with the object lock so that the
4119        * position query gets the right idea. We do this before we post the
4120        * messages so that the message handlers pick this up. */
4121       GST_OBJECT_LOCK (basesink);
4122       basesink->have_newsegment = FALSE;
4123       priv->current_sstart = -1;
4124       priv->current_sstop = -1;
4125       priv->have_latency = FALSE;
4126       GST_OBJECT_UNLOCK (basesink);
4127
4128       gst_base_sink_set_last_buffer (basesink, NULL);
4129
4130       if (!priv->commited) {
4131         if (priv->async_enabled) {
4132           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
4133
4134           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4135               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
4136                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
4137
4138           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4139               gst_message_new_async_done (GST_OBJECT_CAST (basesink)));
4140         }
4141         priv->commited = TRUE;
4142       } else {
4143         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
4144       }
4145       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4146       break;
4147     case GST_STATE_CHANGE_READY_TO_NULL:
4148       if (bclass->stop) {
4149         if (!bclass->stop (basesink)) {
4150           GST_WARNING_OBJECT (basesink, "failed to stop");
4151         }
4152       }
4153       gst_base_sink_set_last_buffer (basesink, NULL);
4154       break;
4155     default:
4156       break;
4157   }
4158
4159   return ret;
4160
4161   /* ERRORS */
4162 start_failed:
4163   {
4164     GST_DEBUG_OBJECT (basesink, "failed to start");
4165     return GST_STATE_CHANGE_FAILURE;
4166   }
4167 activate_failed:
4168   {
4169     GST_DEBUG_OBJECT (basesink,
4170         "element failed to change states -- activation problem?");
4171     return GST_STATE_CHANGE_FAILURE;
4172   }
4173 }