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