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