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