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