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