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