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