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