basesink: clip stepping boundaries
[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         if (segment->stop == *cstop)
1650           *rstop = *rstart + current->amount;
1651
1652         first = *rstart;
1653         last = *rstop;
1654       } else {
1655         if (segment->start == *cstart)
1656           *rstart = *rstop + current->amount;
1657
1658         first = *rstop;
1659         last = *rstart;
1660       }
1661
1662       end = current->start + current->amount;
1663       current->position = first - current->start;
1664
1665       if (G_UNLIKELY (segment->abs_rate != 1.0))
1666         current->position /= segment->abs_rate;
1667
1668       GST_DEBUG_OBJECT (sink,
1669           "buffer: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1670           GST_TIME_ARGS (first), GST_TIME_ARGS (last));
1671       GST_DEBUG_OBJECT (sink,
1672           "got time step %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT "/%"
1673           GST_TIME_FORMAT, GST_TIME_ARGS (current->position),
1674           GST_TIME_ARGS (last - current->start),
1675           GST_TIME_ARGS (current->amount));
1676
1677       if ((current->flush && current->position >= current->amount)
1678           || last >= end) {
1679         GST_DEBUG_OBJECT (sink, "step ended, we need clipping");
1680         step_end = TRUE;
1681         if (segment->rate > 0.0) {
1682           *rstart = end;
1683           *cstart = gst_segment_to_position (segment, GST_FORMAT_TIME, end);
1684         } else {
1685           *rstop = end;
1686           *cstop = gst_segment_to_position (segment, GST_FORMAT_TIME, end);
1687         }
1688       }
1689       GST_DEBUG_OBJECT (sink,
1690           "cstart %" GST_TIME_FORMAT ", rstart %" GST_TIME_FORMAT,
1691           GST_TIME_ARGS (*cstart), GST_TIME_ARGS (*rstart));
1692       GST_DEBUG_OBJECT (sink,
1693           "cstop %" GST_TIME_FORMAT ", rstop %" GST_TIME_FORMAT,
1694           GST_TIME_ARGS (*cstop), GST_TIME_ARGS (*rstop));
1695       break;
1696     }
1697     case GST_FORMAT_BUFFERS:
1698       GST_DEBUG_OBJECT (sink,
1699           "got default step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1700           current->position, current->amount);
1701
1702       if (current->position < current->amount) {
1703         current->position++;
1704       } else {
1705         step_end = TRUE;
1706       }
1707       break;
1708     case GST_FORMAT_DEFAULT:
1709     default:
1710       GST_DEBUG_OBJECT (sink,
1711           "got unknown step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1712           current->position, current->amount);
1713       break;
1714   }
1715   return step_end;
1716 }
1717
1718 /* with STREAM_LOCK, PREROLL_LOCK
1719  *
1720  * Returns TRUE if the object needs synchronisation and takes therefore
1721  * part in prerolling.
1722  *
1723  * rsstart/rsstop contain the start/stop in stream time.
1724  * rrstart/rrstop contain the start/stop in running time.
1725  */
1726 static gboolean
1727 gst_base_sink_get_sync_times (GstBaseSink * basesink, GstMiniObject * obj,
1728     GstClockTime * rsstart, GstClockTime * rsstop,
1729     GstClockTime * rrstart, GstClockTime * rrstop, gboolean * do_sync,
1730     gboolean * stepped, GstSegment * segment, GstStepInfo * step,
1731     gboolean * step_end)
1732 {
1733   GstBaseSinkClass *bclass;
1734   GstBuffer *buffer;
1735   GstClockTime start, stop;     /* raw start/stop timestamps */
1736   gint64 cstart, cstop;         /* clipped raw timestamps */
1737   gint64 rstart, rstop;         /* clipped timestamps converted to running time */
1738   GstClockTime sstart, sstop;   /* clipped timestamps converted to stream time */
1739   GstFormat format;
1740   GstBaseSinkPrivate *priv;
1741   gboolean eos;
1742
1743   priv = basesink->priv;
1744
1745   /* start with nothing */
1746   start = stop = GST_CLOCK_TIME_NONE;
1747
1748   if (G_UNLIKELY (GST_IS_EVENT (obj))) {
1749     GstEvent *event = GST_EVENT_CAST (obj);
1750
1751     switch (GST_EVENT_TYPE (event)) {
1752         /* EOS event needs syncing */
1753       case GST_EVENT_EOS:
1754       {
1755         if (basesink->segment.rate >= 0.0) {
1756           sstart = sstop = priv->current_sstop;
1757           if (!GST_CLOCK_TIME_IS_VALID (sstart)) {
1758             /* we have not seen a buffer yet, use the segment values */
1759             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1760                 basesink->segment.format, basesink->segment.stop);
1761           }
1762         } else {
1763           sstart = sstop = priv->current_sstart;
1764           if (!GST_CLOCK_TIME_IS_VALID (sstart)) {
1765             /* we have not seen a buffer yet, use the segment values */
1766             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1767                 basesink->segment.format, basesink->segment.start);
1768           }
1769         }
1770
1771         rstart = rstop = priv->eos_rtime;
1772         *do_sync = rstart != -1;
1773         GST_DEBUG_OBJECT (basesink, "sync times for EOS %" GST_TIME_FORMAT,
1774             GST_TIME_ARGS (rstart));
1775         /* if we are stepping, we end now */
1776         *step_end = step->valid;
1777         eos = TRUE;
1778         goto eos_done;
1779       }
1780       default:
1781         /* other events do not need syncing */
1782         /* FIXME, maybe NEWSEGMENT might need synchronisation
1783          * since the POSITION query depends on accumulated times and
1784          * we cannot accumulate the current segment before the previous
1785          * one completed.
1786          */
1787         return FALSE;
1788     }
1789   }
1790
1791   eos = FALSE;
1792
1793   /* else do buffer sync code */
1794   buffer = GST_BUFFER_CAST (obj);
1795
1796   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1797
1798   /* just get the times to see if we need syncing, if the start returns -1 we
1799    * don't sync. */
1800   if (bclass->get_times)
1801     bclass->get_times (basesink, buffer, &start, &stop);
1802
1803   if (!GST_CLOCK_TIME_IS_VALID (start)) {
1804     /* we don't need to sync but we still want to get the timestamps for
1805      * tracking the position */
1806     gst_base_sink_get_times (basesink, buffer, &start, &stop);
1807     *do_sync = FALSE;
1808   } else {
1809     *do_sync = TRUE;
1810   }
1811
1812   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
1813       ", stop: %" GST_TIME_FORMAT ", do_sync %d", GST_TIME_ARGS (start),
1814       GST_TIME_ARGS (stop), *do_sync);
1815
1816   /* collect segment and format for code clarity */
1817   format = segment->format;
1818
1819   /* no timestamp clipping if we did not get a TIME segment format */
1820   if (G_UNLIKELY (format != GST_FORMAT_TIME)) {
1821     cstart = start;
1822     cstop = stop;
1823     /* do running and stream time in TIME format */
1824     format = GST_FORMAT_TIME;
1825     GST_LOG_OBJECT (basesink, "not time format, don't clip");
1826     goto do_times;
1827   }
1828
1829   /* clip, only when we know about time */
1830   if (G_UNLIKELY (!gst_segment_clip (segment, GST_FORMAT_TIME,
1831               (gint64) start, (gint64) stop, &cstart, &cstop))) {
1832     if (step->valid) {
1833       GST_DEBUG_OBJECT (basesink, "step out of segment");
1834       /* when we are stepping, pretend we're at the end of the segment */
1835       if (segment->rate > 0.0) {
1836         cstart = segment->stop;
1837         cstop = segment->stop;
1838       } else {
1839         cstart = segment->start;
1840         cstop = segment->start;
1841       }
1842       goto do_times;
1843     }
1844     goto out_of_segment;
1845   }
1846
1847   if (G_UNLIKELY (start != cstart || stop != cstop)) {
1848     GST_DEBUG_OBJECT (basesink, "clipped to: start %" GST_TIME_FORMAT
1849         ", stop: %" GST_TIME_FORMAT, GST_TIME_ARGS (cstart),
1850         GST_TIME_ARGS (cstop));
1851   }
1852
1853   /* set last stop position */
1854   if (G_LIKELY (cstop != GST_CLOCK_TIME_NONE))
1855     gst_segment_set_last_stop (segment, GST_FORMAT_TIME, cstop);
1856   else
1857     gst_segment_set_last_stop (segment, GST_FORMAT_TIME, cstart);
1858
1859 do_times:
1860   rstart = gst_segment_to_running_time (segment, format, cstart);
1861   rstop = gst_segment_to_running_time (segment, format, cstop);
1862
1863   if (G_UNLIKELY (step->valid)) {
1864     if (!(*step_end = handle_stepping (basesink, segment, step, &cstart, &cstop,
1865                 &rstart, &rstop))) {
1866       /* step is still busy, we discard data when we are flushing */
1867       *stepped = step->flush;
1868       GST_DEBUG_OBJECT (basesink, "stepping busy");
1869     }
1870   }
1871   /* this can produce wrong values if we accumulated non-TIME segments. If this happens,
1872    * upstream is behaving very badly */
1873   sstart = gst_segment_to_stream_time (segment, format, cstart);
1874   sstop = gst_segment_to_stream_time (segment, format, cstop);
1875
1876 eos_done:
1877   /* eos_done label only called when doing EOS, we also stop stepping then */
1878   if (*step_end && step->flush) {
1879     GST_DEBUG_OBJECT (basesink, "flushing step ended");
1880     stop_stepping (basesink, segment, step, rstart, rstop, eos);
1881     *step_end = FALSE;
1882   }
1883
1884   /* save times */
1885   *rsstart = sstart;
1886   *rsstop = sstop;
1887   *rrstart = rstart;
1888   *rrstop = rstop;
1889
1890   /* buffers and EOS always need syncing and preroll */
1891   return TRUE;
1892
1893   /* special cases */
1894 out_of_segment:
1895   {
1896     /* we usually clip in the chain function already but stepping could cause
1897      * the segment to be updated later. we return FALSE so that we don't try
1898      * to sync on it. */
1899     GST_LOG_OBJECT (basesink, "buffer skipped, not in segment");
1900     return FALSE;
1901   }
1902 }
1903
1904 /* with STREAM_LOCK, PREROLL_LOCK, LOCK
1905  * adjust a timestamp with the latency and timestamp offset */
1906 static GstClockTime
1907 gst_base_sink_adjust_time (GstBaseSink * basesink, GstClockTime time)
1908 {
1909   GstClockTimeDiff ts_offset;
1910
1911   /* don't do anything funny with invalid timestamps */
1912   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1913     return time;
1914
1915   time += basesink->priv->latency;
1916
1917   /* apply offset, be carefull for underflows */
1918   ts_offset = basesink->priv->ts_offset;
1919   if (ts_offset < 0) {
1920     ts_offset = -ts_offset;
1921     if (ts_offset < time)
1922       time -= ts_offset;
1923     else
1924       time = 0;
1925   } else
1926     time += ts_offset;
1927
1928   return time;
1929 }
1930
1931 /**
1932  * gst_base_sink_wait_clock:
1933  * @sink: the sink
1934  * @time: the running_time to be reached
1935  * @jitter: the jitter to be filled with time diff (can be NULL)
1936  *
1937  * This function will block until @time is reached. It is usually called by
1938  * subclasses that use their own internal synchronisation.
1939  *
1940  * If @time is not valid, no sycnhronisation is done and #GST_CLOCK_BADTIME is
1941  * returned. Likewise, if synchronisation is disabled in the element or there
1942  * is no clock, no synchronisation is done and #GST_CLOCK_BADTIME is returned.
1943  *
1944  * This function should only be called with the PREROLL_LOCK held, like when
1945  * receiving an EOS event in the #GstBaseSinkClass.event() vmethod or when
1946  * receiving a buffer in
1947  * the #GstBaseSinkClass.render() vmethod.
1948  *
1949  * The @time argument should be the running_time of when this method should
1950  * return and is not adjusted with any latency or offset configured in the
1951  * sink.
1952  *
1953  * Since 0.10.20
1954  *
1955  * Returns: #GstClockReturn
1956  */
1957 GstClockReturn
1958 gst_base_sink_wait_clock (GstBaseSink * sink, GstClockTime time,
1959     GstClockTimeDiff * jitter)
1960 {
1961   GstClockID id;
1962   GstClockReturn ret;
1963   GstClock *clock;
1964
1965   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1966     goto invalid_time;
1967
1968   GST_OBJECT_LOCK (sink);
1969   if (G_UNLIKELY (!sink->sync))
1970     goto no_sync;
1971
1972   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (sink)) == NULL))
1973     goto no_clock;
1974
1975   /* add base_time to running_time to get the time against the clock */
1976   time += GST_ELEMENT_CAST (sink)->base_time;
1977
1978   id = gst_clock_new_single_shot_id (clock, time);
1979   GST_OBJECT_UNLOCK (sink);
1980
1981   /* A blocking wait is performed on the clock. We save the ClockID
1982    * so we can unlock the entry at any time. While we are blocking, we
1983    * release the PREROLL_LOCK so that other threads can interrupt the
1984    * entry. */
1985   sink->clock_id = id;
1986   /* release the preroll lock while waiting */
1987   GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
1988
1989   ret = gst_clock_id_wait (id, jitter);
1990
1991   GST_PAD_PREROLL_LOCK (sink->sinkpad);
1992   gst_clock_id_unref (id);
1993   sink->clock_id = NULL;
1994
1995   return ret;
1996
1997   /* no syncing needed */
1998 invalid_time:
1999   {
2000     GST_DEBUG_OBJECT (sink, "time not valid, no sync needed");
2001     return GST_CLOCK_BADTIME;
2002   }
2003 no_sync:
2004   {
2005     GST_DEBUG_OBJECT (sink, "sync disabled");
2006     GST_OBJECT_UNLOCK (sink);
2007     return GST_CLOCK_BADTIME;
2008   }
2009 no_clock:
2010   {
2011     GST_DEBUG_OBJECT (sink, "no clock, can't sync");
2012     GST_OBJECT_UNLOCK (sink);
2013     return GST_CLOCK_BADTIME;
2014   }
2015 }
2016
2017 /**
2018  * gst_base_sink_wait_preroll:
2019  * @sink: the sink
2020  *
2021  * If the #GstBaseSinkClass.render() method performs its own synchronisation
2022  * against the clock it must unblock when going from PLAYING to the PAUSED state
2023  * and call this method before continuing to render the remaining data.
2024  *
2025  * This function will block until a state change to PLAYING happens (in which
2026  * case this function returns #GST_FLOW_OK) or the processing must be stopped due
2027  * to a state change to READY or a FLUSH event (in which case this function
2028  * returns #GST_FLOW_WRONG_STATE).
2029  *
2030  * This function should only be called with the PREROLL_LOCK held, like in the
2031  * render function.
2032  *
2033  * Since: 0.10.11
2034  *
2035  * Returns: #GST_FLOW_OK if the preroll completed and processing can
2036  * continue. Any other return value should be returned from the render vmethod.
2037  */
2038 GstFlowReturn
2039 gst_base_sink_wait_preroll (GstBaseSink * sink)
2040 {
2041   sink->have_preroll = TRUE;
2042   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
2043   /* block until the state changes, or we get a flush, or something */
2044   GST_PAD_PREROLL_WAIT (sink->sinkpad);
2045   sink->have_preroll = FALSE;
2046   if (G_UNLIKELY (sink->flushing))
2047     goto stopping;
2048   if (G_UNLIKELY (sink->priv->step_unlock))
2049     goto step_unlocked;
2050   GST_DEBUG_OBJECT (sink, "continue after preroll");
2051
2052   return GST_FLOW_OK;
2053
2054   /* ERRORS */
2055 stopping:
2056   {
2057     GST_DEBUG_OBJECT (sink, "preroll interrupted because of flush");
2058     return GST_FLOW_WRONG_STATE;
2059   }
2060 step_unlocked:
2061   {
2062     sink->priv->step_unlock = FALSE;
2063     GST_DEBUG_OBJECT (sink, "preroll interrupted because of step");
2064     return GST_FLOW_STEP;
2065   }
2066 }
2067
2068 /**
2069  * gst_base_sink_do_preroll:
2070  * @sink: the sink
2071  * @obj: the object that caused the preroll
2072  *
2073  * If the @sink spawns its own thread for pulling buffers from upstream it
2074  * should call this method after it has pulled a buffer. If the element needed
2075  * to preroll, this function will perform the preroll and will then block
2076  * until the element state is changed.
2077  *
2078  * This function should be called with the PREROLL_LOCK held.
2079  *
2080  * Since 0.10.22
2081  *
2082  * Returns: #GST_FLOW_OK if the preroll completed and processing can
2083  * continue. Any other return value should be returned from the render vmethod.
2084  */
2085 GstFlowReturn
2086 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
2087 {
2088   GstFlowReturn ret;
2089
2090   while (G_UNLIKELY (sink->need_preroll)) {
2091     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
2092
2093     ret = gst_base_sink_preroll_object (sink, FALSE, obj);
2094     if (ret != GST_FLOW_OK)
2095       goto preroll_failed;
2096
2097     /* need to recheck here because the commit state could have
2098      * made us not need the preroll anymore */
2099     if (G_LIKELY (sink->need_preroll)) {
2100       /* block until the state changes, or we get a flush, or something */
2101       ret = gst_base_sink_wait_preroll (sink);
2102       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2103         goto preroll_failed;
2104     }
2105   }
2106   return GST_FLOW_OK;
2107
2108   /* ERRORS */
2109 preroll_failed:
2110   {
2111     GST_DEBUG_OBJECT (sink, "preroll failed %d", ret);
2112     return ret;
2113   }
2114 }
2115
2116 /**
2117  * gst_base_sink_wait_eos:
2118  * @sink: the sink
2119  * @time: the running_time to be reached
2120  * @jitter: the jitter to be filled with time diff (can be NULL)
2121  *
2122  * This function will block until @time is reached. It is usually called by
2123  * subclasses that use their own internal synchronisation but want to let the
2124  * EOS be handled by the base class.
2125  *
2126  * This function should only be called with the PREROLL_LOCK held, like when
2127  * receiving an EOS event in the ::event vmethod.
2128  *
2129  * The @time argument should be the running_time of when the EOS should happen
2130  * and will be adjusted with any latency and offset configured in the sink.
2131  *
2132  * Since 0.10.15
2133  *
2134  * Returns: #GstFlowReturn
2135  */
2136 GstFlowReturn
2137 gst_base_sink_wait_eos (GstBaseSink * sink, GstClockTime time,
2138     GstClockTimeDiff * jitter)
2139 {
2140   GstClockReturn status;
2141   GstFlowReturn ret;
2142
2143   do {
2144     GstClockTime stime;
2145
2146     GST_DEBUG_OBJECT (sink, "checking preroll");
2147
2148     /* first wait for the playing state before we can continue */
2149     if (G_UNLIKELY (sink->need_preroll)) {
2150       ret = gst_base_sink_wait_preroll (sink);
2151       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2152         goto flushing;
2153     }
2154
2155     /* preroll done, we can sync since we are in PLAYING now. */
2156     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
2157         GST_TIME_FORMAT, GST_TIME_ARGS (time));
2158
2159     /* compensate for latency and ts_offset. We don't adjust for render delay
2160      * because we don't interact with the device on EOS normally. */
2161     stime = gst_base_sink_adjust_time (sink, time);
2162
2163     /* wait for the clock, this can be interrupted because we got shut down or
2164      * we PAUSED. */
2165     status = gst_base_sink_wait_clock (sink, stime, jitter);
2166
2167     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
2168
2169     /* invalid time, no clock or sync disabled, just continue then */
2170     if (status == GST_CLOCK_BADTIME)
2171       break;
2172
2173     /* waiting could have been interrupted and we can be flushing now */
2174     if (G_UNLIKELY (sink->flushing))
2175       goto flushing;
2176
2177     /* retry if we got unscheduled, which means we did not reach the timeout
2178      * yet. if some other error occures, we continue. */
2179   } while (status == GST_CLOCK_UNSCHEDULED);
2180
2181   GST_DEBUG_OBJECT (sink, "end of stream");
2182
2183   return GST_FLOW_OK;
2184
2185   /* ERRORS */
2186 flushing:
2187   {
2188     GST_DEBUG_OBJECT (sink, "we are flushing");
2189     return GST_FLOW_WRONG_STATE;
2190   }
2191 }
2192
2193 /* with STREAM_LOCK, PREROLL_LOCK
2194  *
2195  * Make sure we are in PLAYING and synchronize an object to the clock.
2196  *
2197  * If we need preroll, we are not in PLAYING. We try to commit the state
2198  * if needed and then block if we still are not PLAYING.
2199  *
2200  * We start waiting on the clock in PLAYING. If we got interrupted, we
2201  * immediatly try to re-preroll.
2202  *
2203  * Some objects do not need synchronisation (most events) and so this function
2204  * immediatly returns GST_FLOW_OK.
2205  *
2206  * for objects that arrive later than max-lateness to be synchronized to the
2207  * clock have the @late boolean set to TRUE.
2208  *
2209  * This function keeps a running average of the jitter (the diff between the
2210  * clock time and the requested sync time). The jitter is negative for
2211  * objects that arrive in time and positive for late buffers.
2212  *
2213  * does not take ownership of obj.
2214  */
2215 static GstFlowReturn
2216 gst_base_sink_do_sync (GstBaseSink * basesink, GstPad * pad,
2217     GstMiniObject * obj, gboolean * late, gboolean * step_end)
2218 {
2219   GstClockTimeDiff jitter;
2220   gboolean syncable;
2221   GstClockReturn status = GST_CLOCK_OK;
2222   GstClockTime rstart, rstop, sstart, sstop, stime;
2223   gboolean do_sync;
2224   GstBaseSinkPrivate *priv;
2225   GstFlowReturn ret;
2226   GstStepInfo *current, *pending;
2227   gboolean stepped;
2228
2229   priv = basesink->priv;
2230
2231 do_step:
2232   sstart = sstop = rstart = rstop = GST_CLOCK_TIME_NONE;
2233   do_sync = TRUE;
2234   stepped = FALSE;
2235
2236   priv->current_rstart = GST_CLOCK_TIME_NONE;
2237
2238   /* get stepping info */
2239   current = &priv->current_step;
2240   pending = &priv->pending_step;
2241
2242   /* get timing information for this object against the render segment */
2243   syncable = gst_base_sink_get_sync_times (basesink, obj,
2244       &sstart, &sstop, &rstart, &rstop, &do_sync, &stepped, &basesink->segment,
2245       current, step_end);
2246
2247   if (G_UNLIKELY (stepped))
2248     goto step_skipped;
2249
2250   /* a syncable object needs to participate in preroll and
2251    * clocking. All buffers and EOS are syncable. */
2252   if (G_UNLIKELY (!syncable))
2253     goto not_syncable;
2254
2255   /* store timing info for current object */
2256   priv->current_rstart = rstart;
2257   priv->current_rstop = (GST_CLOCK_TIME_IS_VALID (rstop) ? rstop : rstart);
2258
2259   /* save sync time for eos when the previous object needed sync */
2260   priv->eos_rtime = (do_sync ? priv->current_rstop : GST_CLOCK_TIME_NONE);
2261
2262 again:
2263   /* first do preroll, this makes sure we commit our state
2264    * to PAUSED and can continue to PLAYING. We cannot perform
2265    * any clock sync in PAUSED because there is no clock. */
2266   ret = gst_base_sink_do_preroll (basesink, obj);
2267   if (G_UNLIKELY (ret != GST_FLOW_OK))
2268     goto preroll_failed;
2269
2270   /* update the segment with a pending step if the current one is invalid and we
2271    * have a new pending one. We only accept new step updates after a preroll */
2272   if (G_UNLIKELY (pending->valid && !current->valid)) {
2273     start_stepping (basesink, &basesink->segment, pending, current);
2274     goto do_step;
2275   }
2276
2277   /* After rendering we store the position of the last buffer so that we can use
2278    * it to report the position. We need to take the lock here. */
2279   GST_OBJECT_LOCK (basesink);
2280   priv->current_sstart = sstart;
2281   priv->current_sstop = (GST_CLOCK_TIME_IS_VALID (sstop) ? sstop : sstart);
2282   GST_OBJECT_UNLOCK (basesink);
2283
2284   if (!do_sync)
2285     goto done;
2286
2287   /* adjust for latency */
2288   stime = gst_base_sink_adjust_time (basesink, rstart);
2289
2290   /* adjust for render-delay, avoid underflows */
2291   if (GST_CLOCK_TIME_IS_VALID (stime)) {
2292     if (stime > priv->render_delay)
2293       stime -= priv->render_delay;
2294     else
2295       stime = 0;
2296   }
2297
2298   /* preroll done, we can sync since we are in PLAYING now. */
2299   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
2300       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
2301       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
2302
2303   /* This function will return immediatly if start == -1, no clock
2304    * or sync is disabled with GST_CLOCK_BADTIME. */
2305   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
2306
2307   GST_DEBUG_OBJECT (basesink, "clock returned %d", status);
2308
2309   /* invalid time, no clock or sync disabled, just render */
2310   if (status == GST_CLOCK_BADTIME)
2311     goto done;
2312
2313   /* waiting could have been interrupted and we can be flushing now */
2314   if (G_UNLIKELY (basesink->flushing))
2315     goto flushing;
2316
2317   /* check for unlocked by a state change, we are not flushing so
2318    * we can try to preroll on the current buffer. */
2319   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
2320     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
2321     priv->call_preroll = TRUE;
2322     goto again;
2323   }
2324
2325   /* successful syncing done, record observation */
2326   priv->current_jitter = jitter;
2327
2328   /* check if the object should be dropped */
2329   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
2330       status, jitter);
2331
2332 done:
2333   return GST_FLOW_OK;
2334
2335   /* ERRORS */
2336 step_skipped:
2337   {
2338     GST_DEBUG_OBJECT (basesink, "skipped stepped object %p", obj);
2339     *late = TRUE;
2340     return GST_FLOW_OK;
2341   }
2342 not_syncable:
2343   {
2344     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2345     return GST_FLOW_OK;
2346   }
2347 flushing:
2348   {
2349     GST_DEBUG_OBJECT (basesink, "we are flushing");
2350     return GST_FLOW_WRONG_STATE;
2351   }
2352 preroll_failed:
2353   {
2354     GST_DEBUG_OBJECT (basesink, "preroll failed");
2355     *step_end = FALSE;
2356     return ret;
2357   }
2358 }
2359
2360 static gboolean
2361 gst_base_sink_send_qos (GstBaseSink * basesink,
2362     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2363 {
2364   GstEvent *event;
2365   gboolean res;
2366
2367   /* generate Quality-of-Service event */
2368   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2369       "qos: proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2370       GST_TIME_FORMAT, proportion, diff, GST_TIME_ARGS (time));
2371
2372   event = gst_event_new_qos (proportion, diff, time);
2373
2374   /* send upstream */
2375   res = gst_pad_push_event (basesink->sinkpad, event);
2376
2377   return res;
2378 }
2379
2380 static void
2381 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2382 {
2383   GstBaseSinkPrivate *priv;
2384   GstClockTime start, stop;
2385   GstClockTimeDiff jitter;
2386   GstClockTime pt, entered, left;
2387   GstClockTime duration;
2388   gdouble rate;
2389
2390   priv = sink->priv;
2391
2392   start = priv->current_rstart;
2393
2394   if (priv->current_step.valid)
2395     return;
2396
2397   /* if Quality-of-Service disabled, do nothing */
2398   if (!g_atomic_int_get (&priv->qos_enabled) ||
2399       !GST_CLOCK_TIME_IS_VALID (start))
2400     return;
2401
2402   stop = priv->current_rstop;
2403   jitter = priv->current_jitter;
2404
2405   if (jitter < 0) {
2406     /* this is the time the buffer entered the sink */
2407     if (start < -jitter)
2408       entered = 0;
2409     else
2410       entered = start + jitter;
2411     left = start;
2412   } else {
2413     /* this is the time the buffer entered the sink */
2414     entered = start + jitter;
2415     /* this is the time the buffer left the sink */
2416     left = start + jitter;
2417   }
2418
2419   /* calculate duration of the buffer */
2420   if (GST_CLOCK_TIME_IS_VALID (stop))
2421     duration = stop - start;
2422   else
2423     duration = GST_CLOCK_TIME_NONE;
2424
2425   /* if we have the time when the last buffer left us, calculate
2426    * processing time */
2427   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2428     if (entered > priv->last_left) {
2429       pt = entered - priv->last_left;
2430     } else {
2431       pt = 0;
2432     }
2433   } else {
2434     pt = priv->avg_pt;
2435   }
2436
2437   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2438       ", entered %" GST_TIME_FORMAT ", left %" GST_TIME_FORMAT ", pt: %"
2439       GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT ",jitter %"
2440       G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (entered),
2441       GST_TIME_ARGS (left), GST_TIME_ARGS (pt), GST_TIME_ARGS (duration),
2442       jitter);
2443
2444   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "avg_duration: %" GST_TIME_FORMAT
2445       ", avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2446       GST_TIME_ARGS (priv->avg_duration), GST_TIME_ARGS (priv->avg_pt),
2447       priv->avg_rate);
2448
2449   /* collect running averages. for first observations, we copy the
2450    * values */
2451   if (!GST_CLOCK_TIME_IS_VALID (priv->avg_duration))
2452     priv->avg_duration = duration;
2453   else
2454     priv->avg_duration = UPDATE_RUNNING_AVG (priv->avg_duration, duration);
2455
2456   if (!GST_CLOCK_TIME_IS_VALID (priv->avg_pt))
2457     priv->avg_pt = pt;
2458   else
2459     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2460
2461   if (priv->avg_duration != 0)
2462     rate =
2463         gst_guint64_to_gdouble (priv->avg_pt) /
2464         gst_guint64_to_gdouble (priv->avg_duration);
2465   else
2466     rate = 0.0;
2467
2468   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2469     if (dropped || priv->avg_rate < 0.0) {
2470       priv->avg_rate = rate;
2471     } else {
2472       if (rate > 1.0)
2473         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2474       else
2475         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2476     }
2477   }
2478
2479   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2480       "updated: avg_duration: %" GST_TIME_FORMAT ", avg_pt: %" GST_TIME_FORMAT
2481       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_duration),
2482       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2483
2484
2485   if (priv->avg_rate >= 0.0) {
2486     /* if we have a valid rate, start sending QoS messages */
2487     if (priv->current_jitter < 0) {
2488       /* make sure we never go below 0 when adding the jitter to the
2489        * timestamp. */
2490       if (priv->current_rstart < -priv->current_jitter)
2491         priv->current_jitter = -priv->current_rstart;
2492     }
2493     gst_base_sink_send_qos (sink, priv->avg_rate, priv->current_rstart,
2494         priv->current_jitter);
2495   }
2496
2497   /* record when this buffer will leave us */
2498   priv->last_left = left;
2499 }
2500
2501 /* reset all qos measuring */
2502 static void
2503 gst_base_sink_reset_qos (GstBaseSink * sink)
2504 {
2505   GstBaseSinkPrivate *priv;
2506
2507   priv = sink->priv;
2508
2509   priv->last_in_time = GST_CLOCK_TIME_NONE;
2510   priv->last_left = GST_CLOCK_TIME_NONE;
2511   priv->avg_duration = GST_CLOCK_TIME_NONE;
2512   priv->avg_pt = GST_CLOCK_TIME_NONE;
2513   priv->avg_rate = -1.0;
2514   priv->avg_render = GST_CLOCK_TIME_NONE;
2515   priv->rendered = 0;
2516   priv->dropped = 0;
2517
2518 }
2519
2520 /* Checks if the object was scheduled too late.
2521  *
2522  * start/stop contain the raw timestamp start and stop values
2523  * of the object.
2524  *
2525  * status and jitter contain the return values from the clock wait.
2526  *
2527  * returns TRUE if the buffer was too late.
2528  */
2529 static gboolean
2530 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2531     GstClockTime start, GstClockTime stop,
2532     GstClockReturn status, GstClockTimeDiff jitter)
2533 {
2534   gboolean late;
2535   gint64 max_lateness;
2536   GstBaseSinkPrivate *priv;
2537
2538   priv = basesink->priv;
2539
2540   late = FALSE;
2541
2542   /* only for objects that were too late */
2543   if (G_LIKELY (status != GST_CLOCK_EARLY))
2544     goto in_time;
2545
2546   max_lateness = basesink->abidata.ABI.max_lateness;
2547
2548   /* check if frame dropping is enabled */
2549   if (max_lateness == -1)
2550     goto no_drop;
2551
2552   /* only check for buffers */
2553   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2554     goto not_buffer;
2555
2556   /* can't do check if we don't have a timestamp */
2557   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (start)))
2558     goto no_timestamp;
2559
2560   /* we can add a valid stop time */
2561   if (GST_CLOCK_TIME_IS_VALID (stop))
2562     max_lateness += stop;
2563   else
2564     max_lateness += start;
2565
2566   /* if the jitter bigger than duration and lateness we are too late */
2567   if ((late = start + jitter > max_lateness)) {
2568     GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2569         "buffer is too late %" GST_TIME_FORMAT
2570         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (start + jitter),
2571         GST_TIME_ARGS (max_lateness));
2572     /* !!emergency!!, if we did not receive anything valid for more than a
2573      * second, render it anyway so the user sees something */
2574     if (GST_CLOCK_TIME_IS_VALID (priv->last_in_time) &&
2575         start - priv->last_in_time > GST_SECOND) {
2576       late = FALSE;
2577       GST_ELEMENT_WARNING (basesink, CORE, CLOCK,
2578           (_("A lot of buffers are being dropped.")),
2579           ("There may be a timestamping problem, or this computer is too slow."));
2580       GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2581           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
2582           GST_TIME_ARGS (priv->last_in_time));
2583     }
2584   }
2585
2586 done:
2587   if (!late) {
2588     priv->last_in_time = start;
2589   }
2590   return late;
2591
2592   /* all is fine */
2593 in_time:
2594   {
2595     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
2596     goto done;
2597   }
2598 no_drop:
2599   {
2600     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
2601     goto done;
2602   }
2603 not_buffer:
2604   {
2605     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
2606     return FALSE;
2607   }
2608 no_timestamp:
2609   {
2610     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
2611     return FALSE;
2612   }
2613 }
2614
2615 /* called before and after calling the render vmethod. It keeps track of how
2616  * much time was spent in the render method and is used to check if we are
2617  * flooded */
2618 static void
2619 gst_base_sink_do_render_stats (GstBaseSink * basesink, gboolean start)
2620 {
2621   GstBaseSinkPrivate *priv;
2622
2623   priv = basesink->priv;
2624
2625   if (start) {
2626     priv->start = gst_util_get_timestamp ();
2627   } else {
2628     GstClockTime elapsed;
2629
2630     priv->stop = gst_util_get_timestamp ();
2631
2632     elapsed = GST_CLOCK_DIFF (priv->start, priv->stop);
2633
2634     if (!GST_CLOCK_TIME_IS_VALID (priv->avg_render))
2635       priv->avg_render = elapsed;
2636     else
2637       priv->avg_render = UPDATE_RUNNING_AVG (priv->avg_render, elapsed);
2638
2639     GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2640         "avg_render: %" GST_TIME_FORMAT, GST_TIME_ARGS (priv->avg_render));
2641   }
2642 }
2643
2644 /* with STREAM_LOCK, PREROLL_LOCK,
2645  *
2646  * Synchronize the object on the clock and then render it.
2647  *
2648  * takes ownership of obj.
2649  */
2650 static GstFlowReturn
2651 gst_base_sink_render_object (GstBaseSink * basesink, GstPad * pad,
2652     gboolean is_list, gpointer obj)
2653 {
2654   GstFlowReturn ret;
2655   GstBaseSinkClass *bclass;
2656   gboolean late, step_end;
2657   gpointer sync_obj;
2658
2659   GstBaseSinkPrivate *priv;
2660
2661   priv = basesink->priv;
2662
2663   if (is_list) {
2664     /*
2665      * If buffer list, use the first group buffer within the list
2666      * for syncing
2667      */
2668     sync_obj = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0, 0);
2669     g_assert (NULL != sync_obj);
2670   } else {
2671     sync_obj = obj;
2672   }
2673
2674 again:
2675   late = FALSE;
2676   step_end = FALSE;
2677
2678   /* synchronize this object, non syncable objects return OK
2679    * immediatly. */
2680   ret = gst_base_sink_do_sync (basesink, pad, sync_obj, &late, &step_end);
2681   if (G_UNLIKELY (ret != GST_FLOW_OK))
2682     goto sync_failed;
2683
2684   /* and now render, event or buffer/buffer list. */
2685   if (G_LIKELY (is_list || GST_IS_BUFFER (obj))) {
2686     /* drop late buffers unconditionally, let's hope it's unlikely */
2687     if (G_UNLIKELY (late))
2688       goto dropped;
2689
2690     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2691
2692     if (G_LIKELY ((is_list && bclass->render_list) ||
2693             (!is_list && bclass->render))) {
2694       gint do_qos;
2695
2696       /* read once, to get same value before and after */
2697       do_qos = g_atomic_int_get (&priv->qos_enabled);
2698
2699       GST_DEBUG_OBJECT (basesink, "rendering object %p", obj);
2700
2701       /* record rendering time for QoS and stats */
2702       if (do_qos)
2703         gst_base_sink_do_render_stats (basesink, TRUE);
2704
2705       if (!is_list) {
2706         GstBuffer *buf;
2707
2708         /* For buffer lists do not set last buffer. Creating buffer
2709          * with meaningful data can be done only with memcpy which will
2710          * significantly affect performance */
2711         buf = GST_BUFFER_CAST (obj);
2712         gst_base_sink_set_last_buffer (basesink, buf);
2713
2714         ret = bclass->render (basesink, buf);
2715       } else {
2716         GstBufferList *buflist;
2717
2718         buflist = GST_BUFFER_LIST_CAST (obj);
2719
2720         ret = bclass->render_list (basesink, buflist);
2721       }
2722
2723       if (do_qos)
2724         gst_base_sink_do_render_stats (basesink, FALSE);
2725
2726       if (ret == GST_FLOW_STEP)
2727         goto again;
2728
2729       if (G_UNLIKELY (basesink->flushing))
2730         goto flushing;
2731
2732       priv->rendered++;
2733     }
2734   } else {
2735     GstEvent *event = GST_EVENT_CAST (obj);
2736     gboolean event_res = TRUE;
2737     GstEventType type;
2738
2739     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2740
2741     type = GST_EVENT_TYPE (event);
2742
2743     GST_DEBUG_OBJECT (basesink, "rendering event %p, type %s", obj,
2744         gst_event_type_get_name (type));
2745
2746     if (bclass->event)
2747       event_res = bclass->event (basesink, event);
2748
2749     /* when we get here we could be flushing again when the event handler calls
2750      * _wait_eos(). We have to ignore this object in that case. */
2751     if (G_UNLIKELY (basesink->flushing))
2752       goto flushing;
2753
2754     if (G_LIKELY (event_res)) {
2755       guint32 seqnum;
2756
2757       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
2758       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
2759
2760       switch (type) {
2761         case GST_EVENT_EOS:
2762         {
2763           GstMessage *message;
2764
2765           /* the EOS event is completely handled so we mark
2766            * ourselves as being in the EOS state. eos is also
2767            * protected by the object lock so we can read it when
2768            * answering the POSITION query. */
2769           GST_OBJECT_LOCK (basesink);
2770           basesink->eos = TRUE;
2771           GST_OBJECT_UNLOCK (basesink);
2772
2773           /* ok, now we can post the message */
2774           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
2775
2776           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
2777           gst_message_set_seqnum (message, seqnum);
2778           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
2779           break;
2780         }
2781         case GST_EVENT_NEWSEGMENT:
2782           /* configure the segment */
2783           gst_base_sink_configure_segment (basesink, pad, event,
2784               &basesink->segment);
2785           break;
2786         case GST_EVENT_SINK_MESSAGE:{
2787           GstMessage *msg = NULL;
2788
2789           gst_event_parse_sink_message (event, &msg);
2790
2791           if (msg)
2792             gst_element_post_message (GST_ELEMENT_CAST (basesink), msg);
2793         }
2794         default:
2795           break;
2796       }
2797     }
2798   }
2799
2800 done:
2801   if (step_end) {
2802     /* the step ended, check if we need to activate a new step */
2803     GST_DEBUG_OBJECT (basesink, "step ended");
2804     stop_stepping (basesink, &basesink->segment, &priv->current_step,
2805         priv->current_rstart, priv->current_rstop, basesink->eos);
2806     goto again;
2807   }
2808
2809   gst_base_sink_perform_qos (basesink, late);
2810
2811   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
2812   gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
2813   return ret;
2814
2815   /* ERRORS */
2816 sync_failed:
2817   {
2818     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
2819     goto done;
2820   }
2821 dropped:
2822   {
2823     priv->dropped++;
2824     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
2825     goto done;
2826   }
2827 flushing:
2828   {
2829     GST_DEBUG_OBJECT (basesink, "we are flushing, ignore object");
2830     gst_mini_object_unref (obj);
2831     return GST_FLOW_WRONG_STATE;
2832   }
2833 }
2834
2835 /* with STREAM_LOCK, PREROLL_LOCK
2836  *
2837  * Perform preroll on the given object. For buffers this means
2838  * calling the preroll subclass method.
2839  * If that succeeds, the state will be commited.
2840  *
2841  * function does not take ownership of obj.
2842  */
2843 static GstFlowReturn
2844 gst_base_sink_preroll_object (GstBaseSink * basesink, gboolean is_list,
2845     GstMiniObject * obj)
2846 {
2847   GstFlowReturn ret;
2848
2849   GST_DEBUG_OBJECT (basesink, "prerolling object %p", obj);
2850
2851   /* if it's a buffer, we need to call the preroll method */
2852   if (G_LIKELY (is_list || GST_IS_BUFFER (obj)) && basesink->priv->call_preroll) {
2853     GstBaseSinkClass *bclass;
2854     GstBuffer *buf;
2855     GstClockTime timestamp;
2856
2857     if (is_list) {
2858       buf = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0, 0);
2859       g_assert (NULL != buf);
2860     } else {
2861       buf = GST_BUFFER_CAST (obj);
2862     }
2863
2864     timestamp = GST_BUFFER_TIMESTAMP (buf);
2865
2866     GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
2867         GST_TIME_ARGS (timestamp));
2868
2869     /*
2870      * For buffer lists do not set last buffer. Creating buffer
2871      * with meaningful data can be done only with memcpy which will
2872      * significantly affect performance
2873      */
2874     if (!is_list) {
2875       gst_base_sink_set_last_buffer (basesink, buf);
2876     }
2877
2878     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2879     if (bclass->preroll)
2880       if ((ret = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
2881         goto preroll_failed;
2882
2883     basesink->priv->call_preroll = FALSE;
2884   }
2885
2886   /* commit state */
2887   if (G_LIKELY (basesink->playing_async)) {
2888     if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
2889       goto stopping;
2890   }
2891
2892   return GST_FLOW_OK;
2893
2894   /* ERRORS */
2895 preroll_failed:
2896   {
2897     GST_DEBUG_OBJECT (basesink, "preroll failed, abort state");
2898     gst_element_abort_state (GST_ELEMENT_CAST (basesink));
2899     return ret;
2900   }
2901 stopping:
2902   {
2903     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
2904     return GST_FLOW_WRONG_STATE;
2905   }
2906 }
2907
2908 /* with STREAM_LOCK, PREROLL_LOCK
2909  *
2910  * Queue an object for rendering.
2911  * The first prerollable object queued will complete the preroll. If the
2912  * preroll queue if filled, we render all the objects in the queue.
2913  *
2914  * This function takes ownership of the object.
2915  */
2916 static GstFlowReturn
2917 gst_base_sink_queue_object_unlocked (GstBaseSink * basesink, GstPad * pad,
2918     gboolean is_list, gpointer obj, gboolean prerollable)
2919 {
2920   GstFlowReturn ret = GST_FLOW_OK;
2921   gint length;
2922   GQueue *q;
2923
2924   if (G_UNLIKELY (basesink->need_preroll)) {
2925     if (G_LIKELY (prerollable))
2926       basesink->preroll_queued++;
2927
2928     length = basesink->preroll_queued;
2929
2930     GST_DEBUG_OBJECT (basesink, "now %d prerolled items", length);
2931
2932     /* first prerollable item needs to finish the preroll */
2933     if (length == 1) {
2934       ret = gst_base_sink_preroll_object (basesink, is_list, obj);
2935       if (G_UNLIKELY (ret != GST_FLOW_OK))
2936         goto preroll_failed;
2937     }
2938     /* need to recheck if we need preroll, commmit state during preroll
2939      * could have made us not need more preroll. */
2940     if (G_UNLIKELY (basesink->need_preroll)) {
2941       /* see if we can render now, if we can't add the object to the preroll
2942        * queue. */
2943       if (G_UNLIKELY (length <= basesink->preroll_queue_max_len))
2944         goto more_preroll;
2945     }
2946   }
2947   /* we can start rendering (or blocking) the queued object
2948    * if any. */
2949   q = basesink->preroll_queue;
2950   while (G_UNLIKELY (!g_queue_is_empty (q))) {
2951     GstMiniObject *o;
2952
2953     o = g_queue_pop_head (q);
2954     GST_DEBUG_OBJECT (basesink, "rendering queued object %p", o);
2955
2956     /* do something with the return value */
2957     ret = gst_base_sink_render_object (basesink, pad, FALSE, o);
2958     if (ret != GST_FLOW_OK)
2959       goto dequeue_failed;
2960   }
2961
2962   /* now render the object */
2963   ret = gst_base_sink_render_object (basesink, pad, is_list, obj);
2964   basesink->preroll_queued = 0;
2965
2966   return ret;
2967
2968   /* special cases */
2969 preroll_failed:
2970   {
2971     GST_DEBUG_OBJECT (basesink, "preroll failed, reason %s",
2972         gst_flow_get_name (ret));
2973     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
2974     return ret;
2975   }
2976 more_preroll:
2977   {
2978     /* add object to the queue and return */
2979     GST_DEBUG_OBJECT (basesink, "need more preroll data %d <= %d",
2980         length, basesink->preroll_queue_max_len);
2981     g_queue_push_tail (basesink->preroll_queue, obj);
2982     return GST_FLOW_OK;
2983   }
2984 dequeue_failed:
2985   {
2986     GST_DEBUG_OBJECT (basesink, "rendering queued objects failed, reason %s",
2987         gst_flow_get_name (ret));
2988     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
2989     return ret;
2990   }
2991 }
2992
2993 /* with STREAM_LOCK
2994  *
2995  * This function grabs the PREROLL_LOCK and adds the object to
2996  * the queue.
2997  *
2998  * This function takes ownership of obj.
2999  */
3000 static GstFlowReturn
3001 gst_base_sink_queue_object (GstBaseSink * basesink, GstPad * pad,
3002     GstMiniObject * obj, gboolean prerollable)
3003 {
3004   GstFlowReturn ret;
3005
3006   GST_PAD_PREROLL_LOCK (pad);
3007   if (G_UNLIKELY (basesink->flushing))
3008     goto flushing;
3009
3010   if (G_UNLIKELY (basesink->priv->received_eos))
3011     goto was_eos;
3012
3013   ret =
3014       gst_base_sink_queue_object_unlocked (basesink, pad, FALSE, obj,
3015       prerollable);
3016   GST_PAD_PREROLL_UNLOCK (pad);
3017
3018   return ret;
3019
3020   /* ERRORS */
3021 flushing:
3022   {
3023     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3024     GST_PAD_PREROLL_UNLOCK (pad);
3025     gst_mini_object_unref (obj);
3026     return GST_FLOW_WRONG_STATE;
3027   }
3028 was_eos:
3029   {
3030     GST_DEBUG_OBJECT (basesink,
3031         "we are EOS, dropping object, return UNEXPECTED");
3032     GST_PAD_PREROLL_UNLOCK (pad);
3033     gst_mini_object_unref (obj);
3034     return GST_FLOW_UNEXPECTED;
3035   }
3036 }
3037
3038 static void
3039 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
3040 {
3041   /* make sure we are not blocked on the clock also clear any pending
3042    * eos state. */
3043   gst_base_sink_set_flushing (basesink, pad, TRUE);
3044
3045   /* we grab the stream lock but that is not needed since setting the
3046    * sink to flushing would make sure no state commit is being done
3047    * anymore */
3048   GST_PAD_STREAM_LOCK (pad);
3049   gst_base_sink_reset_qos (basesink);
3050   if (basesink->priv->async_enabled) {
3051     /* and we need to commit our state again on the next
3052      * prerolled buffer */
3053     basesink->playing_async = TRUE;
3054     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
3055   } else {
3056     basesink->priv->have_latency = TRUE;
3057     basesink->need_preroll = FALSE;
3058   }
3059   gst_base_sink_set_last_buffer (basesink, NULL);
3060   GST_PAD_STREAM_UNLOCK (pad);
3061 }
3062
3063 static void
3064 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad)
3065 {
3066   /* unset flushing so we can accept new data, this also flushes out any EOS
3067    * event. */
3068   gst_base_sink_set_flushing (basesink, pad, FALSE);
3069
3070   /* for position reporting */
3071   GST_OBJECT_LOCK (basesink);
3072   basesink->priv->current_sstart = GST_CLOCK_TIME_NONE;
3073   basesink->priv->current_sstop = GST_CLOCK_TIME_NONE;
3074   basesink->priv->eos_rtime = GST_CLOCK_TIME_NONE;
3075   basesink->priv->call_preroll = TRUE;
3076   basesink->priv->current_step.valid = FALSE;
3077   basesink->priv->pending_step.valid = FALSE;
3078   if (basesink->pad_mode == GST_ACTIVATE_PUSH) {
3079     /* we need new segment info after the flush. */
3080     basesink->have_newsegment = FALSE;
3081     gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
3082     gst_segment_init (basesink->abidata.ABI.clip_segment, GST_FORMAT_UNDEFINED);
3083   }
3084   GST_OBJECT_UNLOCK (basesink);
3085 }
3086
3087 static gboolean
3088 gst_base_sink_event (GstPad * pad, GstEvent * event)
3089 {
3090   GstBaseSink *basesink;
3091   gboolean result = TRUE;
3092   GstBaseSinkClass *bclass;
3093
3094   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3095
3096   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3097
3098   GST_DEBUG_OBJECT (basesink, "event %p (%s)", event,
3099       GST_EVENT_TYPE_NAME (event));
3100
3101   switch (GST_EVENT_TYPE (event)) {
3102     case GST_EVENT_EOS:
3103     {
3104       GstFlowReturn ret;
3105
3106       GST_PAD_PREROLL_LOCK (pad);
3107       if (G_UNLIKELY (basesink->flushing))
3108         goto flushing;
3109
3110       if (G_UNLIKELY (basesink->priv->received_eos)) {
3111         /* we can't accept anything when we are EOS */
3112         result = FALSE;
3113         gst_event_unref (event);
3114       } else {
3115         /* we set the received EOS flag here so that we can use it when testing if
3116          * we are prerolled and to refuse more buffers. */
3117         basesink->priv->received_eos = TRUE;
3118
3119         /* EOS is a prerollable object, we call the unlocked version because it
3120          * does not check the received_eos flag. */
3121         ret = gst_base_sink_queue_object_unlocked (basesink, pad,
3122             FALSE, GST_MINI_OBJECT_CAST (event), TRUE);
3123         if (G_UNLIKELY (ret != GST_FLOW_OK))
3124           result = FALSE;
3125       }
3126       GST_PAD_PREROLL_UNLOCK (pad);
3127       break;
3128     }
3129     case GST_EVENT_NEWSEGMENT:
3130     {
3131       GstFlowReturn ret;
3132
3133       GST_DEBUG_OBJECT (basesink, "newsegment %p", event);
3134
3135       GST_PAD_PREROLL_LOCK (pad);
3136       if (G_UNLIKELY (basesink->flushing))
3137         goto flushing;
3138
3139       if (G_UNLIKELY (basesink->priv->received_eos)) {
3140         /* we can't accept anything when we are EOS */
3141         result = FALSE;
3142         gst_event_unref (event);
3143       } else {
3144         /* the new segment is a non prerollable item and does not block anything,
3145          * we need to configure the current clipping segment and insert the event
3146          * in the queue to serialize it with the buffers for rendering. */
3147         gst_base_sink_configure_segment (basesink, pad, event,
3148             basesink->abidata.ABI.clip_segment);
3149
3150         ret =
3151             gst_base_sink_queue_object_unlocked (basesink, pad,
3152             FALSE, GST_MINI_OBJECT_CAST (event), FALSE);
3153         if (G_UNLIKELY (ret != GST_FLOW_OK))
3154           result = FALSE;
3155         else {
3156           GST_OBJECT_LOCK (basesink);
3157           basesink->have_newsegment = TRUE;
3158           GST_OBJECT_UNLOCK (basesink);
3159         }
3160       }
3161       GST_PAD_PREROLL_UNLOCK (pad);
3162       break;
3163     }
3164     case GST_EVENT_FLUSH_START:
3165       if (bclass->event)
3166         bclass->event (basesink, event);
3167
3168       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
3169
3170       gst_base_sink_flush_start (basesink, pad);
3171
3172       gst_event_unref (event);
3173       break;
3174     case GST_EVENT_FLUSH_STOP:
3175       if (bclass->event)
3176         bclass->event (basesink, event);
3177
3178       GST_DEBUG_OBJECT (basesink, "flush-stop %p", event);
3179
3180       gst_base_sink_flush_stop (basesink, pad);
3181
3182       gst_event_unref (event);
3183       break;
3184     default:
3185       /* other events are sent to queue or subclass depending on if they
3186        * are serialized. */
3187       if (GST_EVENT_IS_SERIALIZED (event)) {
3188         gst_base_sink_queue_object (basesink, pad,
3189             GST_MINI_OBJECT_CAST (event), FALSE);
3190       } else {
3191         if (bclass->event)
3192           bclass->event (basesink, event);
3193         gst_event_unref (event);
3194       }
3195       break;
3196   }
3197 done:
3198   gst_object_unref (basesink);
3199
3200   return result;
3201
3202   /* ERRORS */
3203 flushing:
3204   {
3205     GST_DEBUG_OBJECT (basesink, "we are flushing");
3206     GST_PAD_PREROLL_UNLOCK (pad);
3207     result = FALSE;
3208     gst_event_unref (event);
3209     goto done;
3210   }
3211 }
3212
3213 /* default implementation to calculate the start and end
3214  * timestamps on a buffer, subclasses can override
3215  */
3216 static void
3217 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
3218     GstClockTime * start, GstClockTime * end)
3219 {
3220   GstClockTime timestamp, duration;
3221
3222   timestamp = GST_BUFFER_TIMESTAMP (buffer);
3223   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
3224
3225     /* get duration to calculate end time */
3226     duration = GST_BUFFER_DURATION (buffer);
3227     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3228       *end = timestamp + duration;
3229     }
3230     *start = timestamp;
3231   }
3232 }
3233
3234 /* must be called with PREROLL_LOCK */
3235 static gboolean
3236 gst_base_sink_needs_preroll (GstBaseSink * basesink)
3237 {
3238   gboolean is_prerolled, res;
3239
3240   /* we have 2 cases where the PREROLL_LOCK is released:
3241    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
3242    *  2) we are syncing on the clock
3243    */
3244   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
3245   res = !is_prerolled;
3246
3247   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
3248       basesink->have_preroll, basesink->priv->received_eos, res);
3249
3250   return res;
3251 }
3252
3253 /* with STREAM_LOCK, PREROLL_LOCK
3254  *
3255  * Takes a buffer and compare the timestamps with the last segment.
3256  * If the buffer falls outside of the segment boundaries, drop it.
3257  * Else queue the buffer for preroll and rendering.
3258  *
3259  * This function takes ownership of the buffer.
3260  */
3261 static GstFlowReturn
3262 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
3263     gboolean is_list, gpointer obj)
3264 {
3265   GstBaseSinkClass *bclass;
3266   GstFlowReturn result;
3267   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
3268   GstSegment *clip_segment;
3269   GstBuffer *time_buf;
3270
3271   if (G_UNLIKELY (basesink->flushing))
3272     goto flushing;
3273
3274   if (G_UNLIKELY (basesink->priv->received_eos))
3275     goto was_eos;
3276
3277   if (is_list) {
3278     time_buf = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0, 0);
3279     g_assert (NULL != time_buf);
3280   } else {
3281     time_buf = GST_BUFFER_CAST (obj);
3282   }
3283
3284   /* for code clarity */
3285   clip_segment = basesink->abidata.ABI.clip_segment;
3286
3287   if (G_UNLIKELY (!basesink->have_newsegment)) {
3288     gboolean sync;
3289
3290     sync = gst_base_sink_get_sync (basesink);
3291     if (sync) {
3292       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
3293           (_("Internal data flow problem.")),
3294           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
3295     }
3296
3297     /* this means this sink will assume timestamps start from 0 */
3298     GST_OBJECT_LOCK (basesink);
3299     clip_segment->start = 0;
3300     clip_segment->stop = -1;
3301     basesink->segment.start = 0;
3302     basesink->segment.stop = -1;
3303     basesink->have_newsegment = TRUE;
3304     GST_OBJECT_UNLOCK (basesink);
3305   }
3306
3307   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3308
3309   /* check if the buffer needs to be dropped, we first ask the subclass for the
3310    * start and end */
3311   if (bclass->get_times)
3312     bclass->get_times (basesink, time_buf, &start, &end);
3313
3314   if (!GST_CLOCK_TIME_IS_VALID (start)) {
3315     /* if the subclass does not want sync, we use our own values so that we at
3316      * least clip the buffer to the segment */
3317     gst_base_sink_get_times (basesink, time_buf, &start, &end);
3318   }
3319
3320   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
3321       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
3322
3323   /* a dropped buffer does not participate in anything */
3324   if (GST_CLOCK_TIME_IS_VALID (start) &&
3325       (clip_segment->format == GST_FORMAT_TIME)) {
3326     if (G_UNLIKELY (!gst_segment_clip (clip_segment,
3327                 GST_FORMAT_TIME, (gint64) start, (gint64) end, NULL, NULL)))
3328       goto out_of_segment;
3329   }
3330
3331   /* now we can process the buffer in the queue, this function takes ownership
3332    * of the buffer */
3333   result = gst_base_sink_queue_object_unlocked (basesink, pad,
3334       is_list, obj, TRUE);
3335   return result;
3336
3337   /* ERRORS */
3338 flushing:
3339   {
3340     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3341     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3342     return GST_FLOW_WRONG_STATE;
3343   }
3344 was_eos:
3345   {
3346     GST_DEBUG_OBJECT (basesink,
3347         "we are EOS, dropping object, return UNEXPECTED");
3348     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3349     return GST_FLOW_UNEXPECTED;
3350   }
3351 out_of_segment:
3352   {
3353     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
3354     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3355     return GST_FLOW_OK;
3356   }
3357 }
3358
3359 /* with STREAM_LOCK
3360  */
3361 static GstFlowReturn
3362 gst_base_sink_chain_main (GstBaseSink * basesink, GstPad * pad,
3363     gboolean is_list, gpointer obj)
3364 {
3365   GstFlowReturn result;
3366
3367   if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH))
3368     goto wrong_mode;
3369
3370   GST_PAD_PREROLL_LOCK (pad);
3371   result = gst_base_sink_chain_unlocked (basesink, pad, is_list, obj);
3372   GST_PAD_PREROLL_UNLOCK (pad);
3373
3374 done:
3375   return result;
3376
3377   /* ERRORS */
3378 wrong_mode:
3379   {
3380     GST_OBJECT_LOCK (pad);
3381     GST_WARNING_OBJECT (basesink,
3382         "Push on pad %s:%s, but it was not activated in push mode",
3383         GST_DEBUG_PAD_NAME (pad));
3384     GST_OBJECT_UNLOCK (pad);
3385     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3386     /* we don't post an error message this will signal to the peer
3387      * pushing that EOS is reached. */
3388     result = GST_FLOW_UNEXPECTED;
3389     goto done;
3390   }
3391 }
3392
3393 static GstFlowReturn
3394 gst_base_sink_chain (GstPad * pad, GstBuffer * buf)
3395 {
3396   GstBaseSink *basesink;
3397
3398   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3399
3400   return gst_base_sink_chain_main (basesink, pad, FALSE, buf);
3401 }
3402
3403 static GstFlowReturn
3404 gst_base_sink_chain_list (GstPad * pad, GstBufferList * list)
3405 {
3406   GstBaseSink *basesink;
3407   GstBaseSinkClass *bclass;
3408   GstFlowReturn result;
3409
3410   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3411   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3412
3413   if (G_LIKELY (bclass->render_list)) {
3414     result = gst_base_sink_chain_main (basesink, pad, TRUE, list);
3415   } else {
3416     GstBufferListIterator *it;
3417     GstBuffer *group;
3418
3419     GST_INFO_OBJECT (pad, "chaining each group in list as a merged buffer");
3420
3421     it = gst_buffer_list_iterate (list);
3422
3423     if (gst_buffer_list_iterator_next_group (it)) {
3424       do {
3425         group = gst_buffer_list_iterator_merge_group (it);
3426         if (group == NULL) {
3427           group = gst_buffer_new ();
3428           GST_CAT_INFO_OBJECT (GST_CAT_SCHEDULING, pad, "chaining empty group");
3429         } else {
3430           GST_CAT_INFO_OBJECT (GST_CAT_SCHEDULING, pad, "chaining group");
3431         }
3432         result = gst_base_sink_chain_main (basesink, pad, FALSE, group);
3433       } while (result == GST_FLOW_OK
3434           && gst_buffer_list_iterator_next_group (it));
3435     } else {
3436       GST_CAT_INFO_OBJECT (GST_CAT_SCHEDULING, pad, "chaining empty group");
3437       result =
3438           gst_base_sink_chain_main (basesink, pad, FALSE, gst_buffer_new ());
3439     }
3440     gst_buffer_list_iterator_free (it);
3441     gst_buffer_list_unref (list);
3442   }
3443   return result;
3444 }
3445
3446
3447 static gboolean
3448 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
3449 {
3450   gboolean res = TRUE;
3451
3452   /* update our offset if the start/stop position was updated */
3453   if (segment->format == GST_FORMAT_BYTES) {
3454     segment->time = segment->start;
3455   } else if (segment->start == 0) {
3456     /* seek to start, we can implement a default for this. */
3457     segment->time = 0;
3458   } else {
3459     res = FALSE;
3460     GST_INFO_OBJECT (sink, "Can't do a default seek");
3461   }
3462
3463   return res;
3464 }
3465
3466 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
3467
3468 static gboolean
3469 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3470     GstEvent * event, GstSegment * segment)
3471 {
3472   /* By default, we try one of 2 things:
3473    *   - For absolute seek positions, convert the requested position to our
3474    *     configured processing format and place it in the output segment \
3475    *   - For relative seek positions, convert our current (input) values to the
3476    *     seek format, adjust by the relative seek offset and then convert back to
3477    *     the processing format
3478    */
3479   GstSeekType cur_type, stop_type;
3480   gint64 cur, stop;
3481   GstSeekFlags flags;
3482   GstFormat seek_format, dest_format;
3483   gdouble rate;
3484   gboolean update;
3485   gboolean res = TRUE;
3486
3487   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3488       &cur_type, &cur, &stop_type, &stop);
3489   dest_format = segment->format;
3490
3491   if (seek_format == dest_format) {
3492     gst_segment_set_seek (segment, rate, seek_format, flags,
3493         cur_type, cur, stop_type, stop, &update);
3494     return TRUE;
3495   }
3496
3497   if (cur_type != GST_SEEK_TYPE_NONE) {
3498     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3499     res =
3500         gst_pad_query_convert (sink->sinkpad, seek_format, cur, &dest_format,
3501         &cur);
3502     cur_type = GST_SEEK_TYPE_SET;
3503   }
3504
3505   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3506     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3507     res =
3508         gst_pad_query_convert (sink->sinkpad, seek_format, stop, &dest_format,
3509         &stop);
3510     stop_type = GST_SEEK_TYPE_SET;
3511   }
3512
3513   /* And finally, configure our output segment in the desired format */
3514   gst_segment_set_seek (segment, rate, dest_format, flags, cur_type, cur,
3515       stop_type, stop, &update);
3516
3517   if (!res)
3518     goto no_format;
3519
3520   return res;
3521
3522 no_format:
3523   {
3524     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3525     return FALSE;
3526   }
3527 }
3528
3529 /* perform a seek, only executed in pull mode */
3530 static gboolean
3531 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3532 {
3533   gboolean flush;
3534   gdouble rate;
3535   GstFormat seek_format, dest_format;
3536   GstSeekFlags flags;
3537   GstSeekType cur_type, stop_type;
3538   gboolean seekseg_configured = FALSE;
3539   gint64 cur, stop;
3540   gboolean update, res = TRUE;
3541   GstSegment seeksegment;
3542
3543   dest_format = sink->segment.format;
3544
3545   if (event) {
3546     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3547     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3548         &cur_type, &cur, &stop_type, &stop);
3549
3550     flush = flags & GST_SEEK_FLAG_FLUSH;
3551   } else {
3552     GST_DEBUG_OBJECT (sink, "performing seek without event");
3553     flush = FALSE;
3554   }
3555
3556   if (flush) {
3557     GST_DEBUG_OBJECT (sink, "flushing upstream");
3558     gst_pad_push_event (pad, gst_event_new_flush_start ());
3559     gst_base_sink_flush_start (sink, pad);
3560   } else {
3561     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3562   }
3563
3564   GST_PAD_STREAM_LOCK (pad);
3565
3566   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3567    * copy the current segment info into the temp segment that we can actually
3568    * attempt the seek with. We only update the real segment if the seek suceeds. */
3569   if (!seekseg_configured) {
3570     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3571
3572     /* now configure the final seek segment */
3573     if (event) {
3574       if (sink->segment.format != seek_format) {
3575         /* OK, here's where we give the subclass a chance to convert the relative
3576          * seek into an absolute one in the processing format. We set up any
3577          * absolute seek above, before taking the stream lock. */
3578         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3579                 &seeksegment)) {
3580           GST_DEBUG_OBJECT (sink,
3581               "Preparing the seek failed after flushing. " "Aborting seek");
3582           res = FALSE;
3583         }
3584       } else {
3585         /* The seek format matches our processing format, no need to ask the
3586          * the subclass to configure the segment. */
3587         gst_segment_set_seek (&seeksegment, rate, seek_format, flags,
3588             cur_type, cur, stop_type, stop, &update);
3589       }
3590     }
3591     /* Else, no seek event passed, so we're just (re)starting the
3592        current segment. */
3593   }
3594
3595   if (res) {
3596     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3597         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3598         seeksegment.start, seeksegment.stop, seeksegment.last_stop);
3599
3600     /* do the seek, segment.last_stop contains the new position. */
3601     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3602   }
3603
3604
3605   if (flush) {
3606     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3607     gst_pad_push_event (pad, gst_event_new_flush_stop ());
3608     gst_base_sink_flush_stop (sink, pad);
3609   } else if (res && sink->abidata.ABI.running) {
3610     /* we are running the current segment and doing a non-flushing seek,
3611      * close the segment first based on the last_stop. */
3612     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3613         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.last_stop);
3614   }
3615
3616   /* The subclass must have converted the segment to the processing format
3617    * by now */
3618   if (res && seeksegment.format != dest_format) {
3619     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3620         "in the correct format. Aborting seek.");
3621     res = FALSE;
3622   }
3623
3624   /* if successfull seek, we update our real segment and push
3625    * out the new segment. */
3626   if (res) {
3627     memcpy (&sink->segment, &seeksegment, sizeof (GstSegment));
3628
3629     if (sink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3630       gst_element_post_message (GST_ELEMENT (sink),
3631           gst_message_new_segment_start (GST_OBJECT (sink),
3632               sink->segment.format, sink->segment.last_stop));
3633     }
3634   }
3635
3636   sink->priv->discont = TRUE;
3637   sink->abidata.ABI.running = TRUE;
3638
3639   GST_PAD_STREAM_UNLOCK (pad);
3640
3641   return res;
3642 }
3643
3644 static void
3645 set_step_info (GstBaseSink * sink, GstStepInfo * current, GstStepInfo * pending,
3646     guint seqnum, GstFormat format, guint64 amount, gdouble rate,
3647     gboolean flush, gboolean intermediate)
3648 {
3649   GST_OBJECT_LOCK (sink);
3650   pending->seqnum = seqnum;
3651   pending->format = format;
3652   pending->amount = amount;
3653   pending->position = 0;
3654   pending->rate = rate;
3655   pending->flush = flush;
3656   pending->intermediate = intermediate;
3657   pending->valid = TRUE;
3658   /* flush invalidates the current stepping segment */
3659   if (flush)
3660     current->valid = FALSE;
3661   GST_OBJECT_UNLOCK (sink);
3662 }
3663
3664 static gboolean
3665 gst_base_sink_perform_step (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3666 {
3667   GstBaseSinkPrivate *priv;
3668   GstBaseSinkClass *bclass;
3669   gboolean flush, intermediate;
3670   gdouble rate;
3671   GstFormat format;
3672   guint64 amount;
3673   guint seqnum;
3674   GstStepInfo *pending, *current;
3675   GstMessage *message;
3676
3677   bclass = GST_BASE_SINK_GET_CLASS (sink);
3678   priv = sink->priv;
3679
3680   GST_DEBUG_OBJECT (sink, "performing step with event %p", event);
3681
3682   gst_event_parse_step (event, &format, &amount, &rate, &flush, &intermediate);
3683   seqnum = gst_event_get_seqnum (event);
3684
3685   pending = &priv->pending_step;
3686   current = &priv->current_step;
3687
3688   /* post message first */
3689   message = gst_message_new_step_start (GST_OBJECT (sink), FALSE, format,
3690       amount, rate, flush, intermediate);
3691   gst_message_set_seqnum (message, seqnum);
3692   gst_element_post_message (GST_ELEMENT (sink), message);
3693
3694   if (flush) {
3695     /* we need to call ::unlock before locking PREROLL_LOCK
3696      * since we lock it before going into ::render */
3697     if (bclass->unlock)
3698       bclass->unlock (sink);
3699
3700     GST_PAD_PREROLL_LOCK (sink->sinkpad);
3701     /* now that we have the PREROLL lock, clear our unlock request */
3702     if (bclass->unlock_stop)
3703       bclass->unlock_stop (sink);
3704
3705     /* update the stepinfo and make it valid */
3706     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
3707         intermediate);
3708
3709     if (sink->priv->async_enabled) {
3710       /* and we need to commit our state again on the next
3711        * prerolled buffer */
3712       sink->playing_async = TRUE;
3713       priv->pending_step.need_preroll = TRUE;
3714       sink->need_preroll = FALSE;
3715       gst_element_lost_state_full (GST_ELEMENT_CAST (sink), FALSE);
3716     } else {
3717       sink->priv->have_latency = TRUE;
3718       sink->need_preroll = FALSE;
3719     }
3720     priv->current_sstart = GST_CLOCK_TIME_NONE;
3721     priv->current_sstop = GST_CLOCK_TIME_NONE;
3722     priv->eos_rtime = GST_CLOCK_TIME_NONE;
3723     priv->call_preroll = TRUE;
3724     gst_base_sink_set_last_buffer (sink, NULL);
3725     gst_base_sink_reset_qos (sink);
3726
3727     if (sink->clock_id) {
3728       gst_clock_id_unschedule (sink->clock_id);
3729     }
3730
3731     if (sink->have_preroll) {
3732       GST_DEBUG_OBJECT (sink, "signal waiter");
3733       priv->step_unlock = TRUE;
3734       GST_PAD_PREROLL_SIGNAL (sink->sinkpad);
3735     }
3736     GST_PAD_PREROLL_UNLOCK (sink->sinkpad);
3737   } else {
3738     /* update the stepinfo and make it valid */
3739     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
3740         intermediate);
3741   }
3742
3743   return TRUE;
3744 }
3745
3746 /* with STREAM_LOCK
3747  */
3748 static void
3749 gst_base_sink_loop (GstPad * pad)
3750 {
3751   GstBaseSink *basesink;
3752   GstBuffer *buf = NULL;
3753   GstFlowReturn result;
3754   guint blocksize;
3755   guint64 offset;
3756
3757   basesink = GST_BASE_SINK (GST_OBJECT_PARENT (pad));
3758
3759   g_assert (basesink->pad_mode == GST_ACTIVATE_PULL);
3760
3761   if ((blocksize = basesink->priv->blocksize) == 0)
3762     blocksize = -1;
3763
3764   offset = basesink->segment.last_stop;
3765
3766   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
3767       offset, blocksize);
3768
3769   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
3770   if (G_UNLIKELY (result != GST_FLOW_OK))
3771     goto paused;
3772
3773   if (G_UNLIKELY (buf == NULL))
3774     goto no_buffer;
3775
3776   offset += GST_BUFFER_SIZE (buf);
3777
3778   gst_segment_set_last_stop (&basesink->segment, GST_FORMAT_BYTES, offset);
3779
3780   GST_PAD_PREROLL_LOCK (pad);
3781   result = gst_base_sink_chain_unlocked (basesink, pad, FALSE, buf);
3782   GST_PAD_PREROLL_UNLOCK (pad);
3783   if (G_UNLIKELY (result != GST_FLOW_OK))
3784     goto paused;
3785
3786   return;
3787
3788   /* ERRORS */
3789 paused:
3790   {
3791     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
3792         gst_flow_get_name (result));
3793     gst_pad_pause_task (pad);
3794     /* fatal errors and NOT_LINKED cause EOS */
3795     if (GST_FLOW_IS_FATAL (result) || result == GST_FLOW_NOT_LINKED) {
3796       if (result == GST_FLOW_UNEXPECTED) {
3797         /* perform EOS logic */
3798         if (basesink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3799           gst_element_post_message (GST_ELEMENT_CAST (basesink),
3800               gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
3801                   basesink->segment.format, basesink->segment.last_stop));
3802         } else {
3803           gst_base_sink_event (pad, gst_event_new_eos ());
3804         }
3805       } else {
3806         /* for fatal errors we post an error message, post the error
3807          * first so the app knows about the error first. */
3808         GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3809             (_("Internal data stream error.")),
3810             ("stream stopped, reason %s", gst_flow_get_name (result)));
3811         gst_base_sink_event (pad, gst_event_new_eos ());
3812       }
3813     }
3814     return;
3815   }
3816 no_buffer:
3817   {
3818     GST_LOG_OBJECT (basesink, "no buffer, pausing");
3819     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3820         (_("Internal data flow error.")), ("element returned NULL buffer"));
3821     result = GST_FLOW_ERROR;
3822     goto paused;
3823   }
3824 }
3825
3826 static gboolean
3827 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
3828     gboolean flushing)
3829 {
3830   GstBaseSinkClass *bclass;
3831
3832   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3833
3834   if (flushing) {
3835     /* unlock any subclasses, we need to do this before grabbing the
3836      * PREROLL_LOCK since we hold this lock before going into ::render. */
3837     if (bclass->unlock)
3838       bclass->unlock (basesink);
3839   }
3840
3841   GST_PAD_PREROLL_LOCK (pad);
3842   basesink->flushing = flushing;
3843   if (flushing) {
3844     /* step 1, now that we have the PREROLL lock, clear our unlock request */
3845     if (bclass->unlock_stop)
3846       bclass->unlock_stop (basesink);
3847
3848     /* set need_preroll before we unblock the clock. If the clock is unblocked
3849      * before timing out, we can reuse the buffer for preroll. */
3850     basesink->need_preroll = TRUE;
3851
3852     /* step 2, unblock clock sync (if any) or any other blocking thing */
3853     if (basesink->clock_id) {
3854       gst_clock_id_unschedule (basesink->clock_id);
3855     }
3856
3857     /* flush out the data thread if it's locked in finish_preroll, this will
3858      * also flush out the EOS state */
3859     GST_DEBUG_OBJECT (basesink,
3860         "flushing out data thread, need preroll to TRUE");
3861     gst_base_sink_preroll_queue_flush (basesink, pad);
3862   }
3863   GST_PAD_PREROLL_UNLOCK (pad);
3864
3865   return TRUE;
3866 }
3867
3868 static gboolean
3869 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
3870 {
3871   gboolean result;
3872
3873   if (active) {
3874     /* start task */
3875     result = gst_pad_start_task (basesink->sinkpad,
3876         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad);
3877   } else {
3878     /* step 2, make sure streaming finishes */
3879     result = gst_pad_stop_task (basesink->sinkpad);
3880   }
3881
3882   return result;
3883 }
3884
3885 static gboolean
3886 gst_base_sink_pad_activate (GstPad * pad)
3887 {
3888   gboolean result = FALSE;
3889   GstBaseSink *basesink;
3890
3891   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3892
3893   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
3894
3895   gst_base_sink_set_flushing (basesink, pad, FALSE);
3896
3897   /* we need to have the pull mode enabled */
3898   if (!basesink->can_activate_pull) {
3899     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
3900     goto fallback;
3901   }
3902
3903   /* check if downstreams supports pull mode at all */
3904   if (!gst_pad_check_pull_range (pad)) {
3905     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
3906     goto fallback;
3907   }
3908
3909   /* set the pad mode before starting the task so that it's in the
3910    * correct state for the new thread. also the sink set_caps and get_caps
3911    * function checks this */
3912   basesink->pad_mode = GST_ACTIVATE_PULL;
3913
3914   /* we first try to negotiate a format so that when we try to activate
3915    * downstream, it knows about our format */
3916   if (!gst_base_sink_negotiate_pull (basesink)) {
3917     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
3918     goto fallback;
3919   }
3920
3921   /* ok activate now */
3922   if (!gst_pad_activate_pull (pad, TRUE)) {
3923     /* clear any pending caps */
3924     GST_OBJECT_LOCK (basesink);
3925     gst_caps_replace (&basesink->priv->pull_caps, NULL);
3926     GST_OBJECT_UNLOCK (basesink);
3927     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
3928     goto fallback;
3929   }
3930
3931   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
3932   result = TRUE;
3933   goto done;
3934
3935   /* push mode fallback */
3936 fallback:
3937   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
3938   if ((result = gst_pad_activate_push (pad, TRUE))) {
3939     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
3940   }
3941
3942 done:
3943   if (!result) {
3944     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
3945     gst_base_sink_set_flushing (basesink, pad, TRUE);
3946   }
3947
3948   gst_object_unref (basesink);
3949
3950   return result;
3951 }
3952
3953 static gboolean
3954 gst_base_sink_pad_activate_push (GstPad * pad, gboolean active)
3955 {
3956   gboolean result;
3957   GstBaseSink *basesink;
3958
3959   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
3960
3961   if (active) {
3962     if (!basesink->can_activate_push) {
3963       result = FALSE;
3964       basesink->pad_mode = GST_ACTIVATE_NONE;
3965     } else {
3966       result = TRUE;
3967       basesink->pad_mode = GST_ACTIVATE_PUSH;
3968     }
3969   } else {
3970     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH)) {
3971       g_warning ("Internal GStreamer activation error!!!");
3972       result = FALSE;
3973     } else {
3974       gst_base_sink_set_flushing (basesink, pad, TRUE);
3975       result = TRUE;
3976       basesink->pad_mode = GST_ACTIVATE_NONE;
3977     }
3978   }
3979
3980   gst_object_unref (basesink);
3981
3982   return result;
3983 }
3984
3985 static gboolean
3986 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
3987 {
3988   GstCaps *caps;
3989   gboolean result;
3990
3991   result = FALSE;
3992
3993   /* this returns the intersection between our caps and the peer caps. If there
3994    * is no peer, it returns NULL and we can't operate in pull mode so we can
3995    * fail the negotiation. */
3996   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
3997   if (caps == NULL || gst_caps_is_empty (caps))
3998     goto no_caps_possible;
3999
4000   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
4001
4002   caps = gst_caps_make_writable (caps);
4003   /* get the first (prefered) format */
4004   gst_caps_truncate (caps);
4005   /* try to fixate */
4006   gst_pad_fixate_caps (GST_BASE_SINK_PAD (basesink), caps);
4007
4008   GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
4009
4010   if (gst_caps_is_any (caps)) {
4011     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
4012         "allowing pull()");
4013     /* neither side has template caps in this case, so they are prepared for
4014        pull() without setcaps() */
4015     result = TRUE;
4016   } else if (gst_caps_is_fixed (caps)) {
4017     if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
4018       goto could_not_set_caps;
4019
4020     GST_OBJECT_LOCK (basesink);
4021     gst_caps_replace (&basesink->priv->pull_caps, caps);
4022     GST_OBJECT_UNLOCK (basesink);
4023
4024     result = TRUE;
4025   }
4026
4027   gst_caps_unref (caps);
4028
4029   return result;
4030
4031 no_caps_possible:
4032   {
4033     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
4034     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
4035     if (caps)
4036       gst_caps_unref (caps);
4037     return FALSE;
4038   }
4039 could_not_set_caps:
4040   {
4041     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
4042     gst_caps_unref (caps);
4043     return FALSE;
4044   }
4045 }
4046
4047 /* this won't get called until we implement an activate function */
4048 static gboolean
4049 gst_base_sink_pad_activate_pull (GstPad * pad, gboolean active)
4050 {
4051   gboolean result = FALSE;
4052   GstBaseSink *basesink;
4053   GstBaseSinkClass *bclass;
4054
4055   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
4056   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4057
4058   if (active) {
4059     GstFormat format;
4060     gint64 duration;
4061
4062     /* we mark we have a newsegment here because pull based
4063      * mode works just fine without having a newsegment before the
4064      * first buffer */
4065     format = GST_FORMAT_BYTES;
4066
4067     gst_segment_init (&basesink->segment, format);
4068     gst_segment_init (basesink->abidata.ABI.clip_segment, format);
4069     GST_OBJECT_LOCK (basesink);
4070     basesink->have_newsegment = TRUE;
4071     GST_OBJECT_UNLOCK (basesink);
4072
4073     /* get the peer duration in bytes */
4074     result = gst_pad_query_peer_duration (pad, &format, &duration);
4075     if (result) {
4076       GST_DEBUG_OBJECT (basesink,
4077           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
4078       gst_segment_set_duration (basesink->abidata.ABI.clip_segment, format,
4079           duration);
4080       gst_segment_set_duration (&basesink->segment, format, duration);
4081     } else {
4082       GST_DEBUG_OBJECT (basesink, "unknown duration");
4083     }
4084
4085     if (bclass->activate_pull)
4086       result = bclass->activate_pull (basesink, TRUE);
4087     else
4088       result = FALSE;
4089
4090     if (!result)
4091       goto activate_failed;
4092
4093   } else {
4094     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PULL)) {
4095       g_warning ("Internal GStreamer activation error!!!");
4096       result = FALSE;
4097     } else {
4098       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
4099       if (bclass->activate_pull)
4100         result &= bclass->activate_pull (basesink, FALSE);
4101       basesink->pad_mode = GST_ACTIVATE_NONE;
4102       /* clear any pending caps */
4103       GST_OBJECT_LOCK (basesink);
4104       gst_caps_replace (&basesink->priv->pull_caps, NULL);
4105       GST_OBJECT_UNLOCK (basesink);
4106     }
4107   }
4108   gst_object_unref (basesink);
4109
4110   return result;
4111
4112   /* ERRORS */
4113 activate_failed:
4114   {
4115     /* reset, as starting the thread failed */
4116     basesink->pad_mode = GST_ACTIVATE_NONE;
4117
4118     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
4119     return FALSE;
4120   }
4121 }
4122
4123 /* send an event to our sinkpad peer. */
4124 static gboolean
4125 gst_base_sink_send_event (GstElement * element, GstEvent * event)
4126 {
4127   GstPad *pad;
4128   GstBaseSink *basesink = GST_BASE_SINK (element);
4129   gboolean forward, result = TRUE;
4130   GstActivateMode mode;
4131
4132   GST_OBJECT_LOCK (element);
4133   /* get the pad and the scheduling mode */
4134   pad = gst_object_ref (basesink->sinkpad);
4135   mode = basesink->pad_mode;
4136   GST_OBJECT_UNLOCK (element);
4137
4138   /* only push UPSTREAM events upstream */
4139   forward = GST_EVENT_IS_UPSTREAM (event);
4140
4141   switch (GST_EVENT_TYPE (event)) {
4142     case GST_EVENT_LATENCY:
4143     {
4144       GstClockTime latency;
4145
4146       gst_event_parse_latency (event, &latency);
4147
4148       /* store the latency. We use this to adjust the running_time before syncing
4149        * it to the clock. */
4150       GST_OBJECT_LOCK (element);
4151       basesink->priv->latency = latency;
4152       if (!basesink->priv->have_latency)
4153         forward = FALSE;
4154       GST_OBJECT_UNLOCK (element);
4155       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
4156           GST_TIME_ARGS (latency));
4157
4158       /* We forward this event so that all elements know about the global pipeline
4159        * latency. This is interesting for an element when it wants to figure out
4160        * when a particular piece of data will be rendered. */
4161       break;
4162     }
4163     case GST_EVENT_SEEK:
4164       /* in pull mode we will execute the seek */
4165       if (mode == GST_ACTIVATE_PULL)
4166         result = gst_base_sink_perform_seek (basesink, pad, event);
4167       break;
4168     case GST_EVENT_STEP:
4169       result = gst_base_sink_perform_step (basesink, pad, event);
4170       forward = FALSE;
4171       break;
4172     default:
4173       break;
4174   }
4175
4176   if (forward) {
4177     result = gst_pad_push_event (pad, event);
4178   } else {
4179     /* not forwarded, unref the event */
4180     gst_event_unref (event);
4181   }
4182
4183   gst_object_unref (pad);
4184   return result;
4185 }
4186
4187 static gboolean
4188 gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query)
4189 {
4190   GstPad *peer;
4191   gboolean res = FALSE;
4192
4193   if ((peer = gst_pad_get_peer (sink->sinkpad))) {
4194     res = gst_pad_query (peer, query);
4195     gst_object_unref (peer);
4196   }
4197   return res;
4198 }
4199
4200 /* get the end position of the last seen object, this is used
4201  * for EOS and for making sure that we don't report a position we
4202  * have not reached yet. With LOCK. */
4203 static gboolean
4204 gst_base_sink_get_position_last (GstBaseSink * basesink, GstFormat format,
4205     gint64 * cur, gboolean * upstream)
4206 {
4207   GstFormat oformat;
4208   GstSegment *segment;
4209   gboolean ret = TRUE;
4210
4211   segment = &basesink->segment;
4212   oformat = segment->format;
4213
4214   if (oformat == GST_FORMAT_TIME) {
4215     /* return last observed stream time, we keep the stream time around in the
4216      * time format. */
4217     *cur = basesink->priv->current_sstop;
4218   } else {
4219     /* convert last stop to stream time */
4220     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
4221   }
4222
4223   if (*cur != -1 && oformat != format) {
4224     GST_OBJECT_UNLOCK (basesink);
4225     /* convert to the target format if we need to, release lock first */
4226     ret =
4227         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
4228     if (!ret) {
4229       *cur = -1;
4230       *upstream = TRUE;
4231     }
4232     GST_OBJECT_LOCK (basesink);
4233   }
4234
4235   GST_DEBUG_OBJECT (basesink, "POSITION: %" GST_TIME_FORMAT,
4236       GST_TIME_ARGS (*cur));
4237
4238   return ret;
4239 }
4240
4241 /* get the position when we are PAUSED, this is the stream time of the buffer
4242  * that prerolled. If no buffer is prerolled (we are still flushing), this
4243  * value will be -1. With LOCK. */
4244 static gboolean
4245 gst_base_sink_get_position_paused (GstBaseSink * basesink, GstFormat format,
4246     gint64 * cur, gboolean * upstream)
4247 {
4248   gboolean res;
4249   gint64 time;
4250   GstSegment *segment;
4251   GstFormat oformat;
4252
4253   /* we don't use the clip segment in pull mode, when seeking we update the
4254    * main segment directly with the new segment values without it having to be
4255    * activated by the rendering after preroll */
4256   if (basesink->pad_mode == GST_ACTIVATE_PUSH)
4257     segment = basesink->abidata.ABI.clip_segment;
4258   else
4259     segment = &basesink->segment;
4260   oformat = segment->format;
4261
4262   if (oformat == GST_FORMAT_TIME) {
4263     *cur = basesink->priv->current_sstart;
4264     if (segment->rate < 0.0 &&
4265         GST_CLOCK_TIME_IS_VALID (basesink->priv->current_sstop)) {
4266       /* for reverse playback we prefer the stream time stop position if we have
4267        * one */
4268       *cur = basesink->priv->current_sstop;
4269     }
4270   } else {
4271     *cur = gst_segment_to_stream_time (segment, oformat, segment->last_stop);
4272   }
4273
4274   time = segment->time;
4275
4276   if (*cur != -1) {
4277     *cur = MAX (*cur, time);
4278     GST_DEBUG_OBJECT (basesink, "POSITION as max: %" GST_TIME_FORMAT
4279         ", time %" GST_TIME_FORMAT, GST_TIME_ARGS (*cur), GST_TIME_ARGS (time));
4280   } else {
4281     /* we have no buffer, use the segment times. */
4282     if (segment->rate >= 0.0) {
4283       /* forward, next position is always the time of the segment */
4284       *cur = time;
4285       GST_DEBUG_OBJECT (basesink, "POSITION as time: %" GST_TIME_FORMAT,
4286           GST_TIME_ARGS (*cur));
4287     } else {
4288       /* reverse, next expected timestamp is segment->stop. We use the function
4289        * to get things right for negative applied_rates. */
4290       *cur = gst_segment_to_stream_time (segment, oformat, segment->stop);
4291       GST_DEBUG_OBJECT (basesink, "reverse POSITION: %" GST_TIME_FORMAT,
4292           GST_TIME_ARGS (*cur));
4293     }
4294   }
4295
4296   res = (*cur != -1);
4297   if (res && oformat != format) {
4298     GST_OBJECT_UNLOCK (basesink);
4299     res =
4300         gst_pad_query_convert (basesink->sinkpad, oformat, *cur, &format, cur);
4301     if (!res) {
4302       *cur = -1;
4303       *upstream = TRUE;
4304     }
4305     GST_OBJECT_LOCK (basesink);
4306   }
4307
4308   return res;
4309 }
4310
4311 static gboolean
4312 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
4313     gint64 * cur, gboolean * upstream)
4314 {
4315   GstClock *clock;
4316   gboolean res = FALSE;
4317   GstFormat oformat, tformat;
4318   GstClockTime now, latency;
4319   GstClockTimeDiff base;
4320   gint64 time, accum, duration;
4321   gdouble rate;
4322   gint64 last;
4323
4324   GST_OBJECT_LOCK (basesink);
4325   /* our intermediate time format */
4326   tformat = GST_FORMAT_TIME;
4327   /* get the format in the segment */
4328   oformat = basesink->segment.format;
4329
4330   /* can only give answer based on the clock if not EOS */
4331   if (G_UNLIKELY (basesink->eos))
4332     goto in_eos;
4333
4334   /* we can only get the segment when we are not NULL or READY */
4335   if (!basesink->have_newsegment)
4336     goto wrong_state;
4337
4338   /* when not in PLAYING or when we're busy with a state change, we
4339    * cannot read from the clock so we report time based on the
4340    * last seen timestamp. */
4341   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
4342       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING)
4343     goto in_pause;
4344
4345   /* we need to sync on the clock. */
4346   if (basesink->sync == FALSE)
4347     goto no_sync;
4348
4349   /* and we need a clock */
4350   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
4351     goto no_sync;
4352
4353   /* collect all data we need holding the lock */
4354   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.time))
4355     time = basesink->segment.time;
4356   else
4357     time = 0;
4358
4359   if (GST_CLOCK_TIME_IS_VALID (basesink->segment.stop))
4360     duration = basesink->segment.stop - basesink->segment.start;
4361   else
4362     duration = 0;
4363
4364   base = GST_ELEMENT_CAST (basesink)->base_time;
4365   accum = basesink->segment.accum;
4366   rate = basesink->segment.rate * basesink->segment.applied_rate;
4367   latency = basesink->priv->latency;
4368
4369   gst_object_ref (clock);
4370
4371   /* this function might release the LOCK */
4372   gst_base_sink_get_position_last (basesink, format, &last, upstream);
4373
4374   /* need to release the object lock before we can get the time,
4375    * a clock might take the LOCK of the provider, which could be
4376    * a basesink subclass. */
4377   GST_OBJECT_UNLOCK (basesink);
4378
4379   now = gst_clock_get_time (clock);
4380
4381   if (oformat != tformat) {
4382     /* convert accum, time and duration to time */
4383     if (!gst_pad_query_convert (basesink->sinkpad, oformat, accum, &tformat,
4384             &accum))
4385       goto convert_failed;
4386     if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration, &tformat,
4387             &duration))
4388       goto convert_failed;
4389     if (!gst_pad_query_convert (basesink->sinkpad, oformat, time, &tformat,
4390             &time))
4391       goto convert_failed;
4392   }
4393
4394   /* subtract base time and accumulated time from the clock time.
4395    * Make sure we don't go negative. This is the current time in
4396    * the segment which we need to scale with the combined
4397    * rate and applied rate. */
4398   base += accum;
4399   base += latency;
4400   if (GST_CLOCK_DIFF (base, now) < 0)
4401     base = now;
4402
4403   /* for negative rates we need to count back from the segment
4404    * duration. */
4405   if (rate < 0.0)
4406     time += duration;
4407
4408   *cur = time + gst_guint64_to_gdouble (now - base) * rate;
4409
4410   /* never report more than last seen position */
4411   if (last != -1)
4412     *cur = MIN (last, *cur);
4413
4414   gst_object_unref (clock);
4415
4416   GST_DEBUG_OBJECT (basesink,
4417       "now %" GST_TIME_FORMAT " - base %" GST_TIME_FORMAT " - accum %"
4418       GST_TIME_FORMAT " + time %" GST_TIME_FORMAT,
4419       GST_TIME_ARGS (now), GST_TIME_ARGS (base),
4420       GST_TIME_ARGS (accum), GST_TIME_ARGS (time));
4421
4422   if (oformat != format) {
4423     /* convert time to final format */
4424     if (!gst_pad_query_convert (basesink->sinkpad, tformat, *cur, &format, cur))
4425       goto convert_failed;
4426   }
4427
4428   res = TRUE;
4429
4430 done:
4431   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
4432       res, GST_TIME_ARGS (*cur));
4433   return res;
4434
4435   /* special cases */
4436 in_eos:
4437   {
4438     GST_DEBUG_OBJECT (basesink, "position in EOS");
4439     res = gst_base_sink_get_position_last (basesink, format, cur, upstream);
4440     GST_OBJECT_UNLOCK (basesink);
4441     goto done;
4442   }
4443 in_pause:
4444   {
4445     GST_DEBUG_OBJECT (basesink, "position in PAUSED");
4446     res = gst_base_sink_get_position_paused (basesink, format, cur, upstream);
4447     GST_OBJECT_UNLOCK (basesink);
4448     goto done;
4449   }
4450 wrong_state:
4451   {
4452     /* in NULL or READY we always return FALSE and -1 */
4453     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
4454     res = FALSE;
4455     *cur = -1;
4456     GST_OBJECT_UNLOCK (basesink);
4457     goto done;
4458   }
4459 no_sync:
4460   {
4461     /* report last seen timestamp if any, else ask upstream to answer */
4462     if ((*cur = basesink->priv->current_sstart) != -1)
4463       res = TRUE;
4464     else
4465       *upstream = TRUE;
4466
4467     GST_DEBUG_OBJECT (basesink, "no sync, res %d, POSITION %" GST_TIME_FORMAT,
4468         res, GST_TIME_ARGS (*cur));
4469     GST_OBJECT_UNLOCK (basesink);
4470     return res;
4471   }
4472 convert_failed:
4473   {
4474     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
4475     *upstream = TRUE;
4476     return FALSE;
4477   }
4478 }
4479
4480 static gboolean
4481 gst_base_sink_query (GstElement * element, GstQuery * query)
4482 {
4483   gboolean res = FALSE;
4484
4485   GstBaseSink *basesink = GST_BASE_SINK (element);
4486
4487   switch (GST_QUERY_TYPE (query)) {
4488     case GST_QUERY_POSITION:
4489     {
4490       gint64 cur = 0;
4491       GstFormat format;
4492       gboolean upstream = FALSE;
4493
4494       gst_query_parse_position (query, &format, NULL);
4495
4496       GST_DEBUG_OBJECT (basesink, "position format %d", format);
4497
4498       /* first try to get the position based on the clock */
4499       if ((res =
4500               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
4501         gst_query_set_position (query, format, cur);
4502       } else if (upstream) {
4503         /* fallback to peer query */
4504         res = gst_base_sink_peer_query (basesink, query);
4505       }
4506       break;
4507     }
4508     case GST_QUERY_DURATION:
4509     {
4510       GstFormat format, uformat;
4511       gint64 duration, uduration;
4512
4513       gst_query_parse_duration (query, &format, NULL);
4514
4515       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
4516           gst_format_get_name (format));
4517
4518       if (basesink->pad_mode == GST_ACTIVATE_PULL) {
4519         uformat = GST_FORMAT_BYTES;
4520
4521         /* get the duration in bytes, in pull mode that's all we are sure to
4522          * know. We have to explicitly get this value from upstream instead of
4523          * using our cached value because it might change. Duration caching
4524          * should be done at a higher level. */
4525         res = gst_pad_query_peer_duration (basesink->sinkpad, &uformat,
4526             &uduration);
4527         if (res) {
4528           gst_segment_set_duration (&basesink->segment, uformat, uduration);
4529           if (format != uformat) {
4530             /* convert to the requested format */
4531             res = gst_pad_query_convert (basesink->sinkpad, uformat, uduration,
4532                 &format, &duration);
4533           } else {
4534             duration = uduration;
4535           }
4536           if (res) {
4537             /* set the result */
4538             gst_query_set_duration (query, format, duration);
4539           }
4540         }
4541       } else {
4542         /* in push mode we simply forward upstream */
4543         res = gst_base_sink_peer_query (basesink, query);
4544       }
4545       break;
4546     }
4547     case GST_QUERY_LATENCY:
4548     {
4549       gboolean live, us_live;
4550       GstClockTime min, max;
4551
4552       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
4553                   &max))) {
4554         gst_query_set_latency (query, live, min, max);
4555       }
4556       break;
4557     }
4558     case GST_QUERY_JITTER:
4559       break;
4560     case GST_QUERY_RATE:
4561       /* gst_query_set_rate (query, basesink->segment_rate); */
4562       res = TRUE;
4563       break;
4564     case GST_QUERY_SEGMENT:
4565     {
4566       /* FIXME, bring start/stop to stream time */
4567       gst_query_set_segment (query, basesink->segment.rate,
4568           GST_FORMAT_TIME, basesink->segment.start, basesink->segment.stop);
4569       break;
4570     }
4571     case GST_QUERY_SEEKING:
4572     case GST_QUERY_CONVERT:
4573     case GST_QUERY_FORMATS:
4574     default:
4575       res = gst_base_sink_peer_query (basesink, query);
4576       break;
4577   }
4578   return res;
4579 }
4580
4581 static GstStateChangeReturn
4582 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
4583 {
4584   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
4585   GstBaseSink *basesink = GST_BASE_SINK (element);
4586   GstBaseSinkClass *bclass;
4587   GstBaseSinkPrivate *priv;
4588
4589   priv = basesink->priv;
4590
4591   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4592
4593   switch (transition) {
4594     case GST_STATE_CHANGE_NULL_TO_READY:
4595       if (bclass->start)
4596         if (!bclass->start (basesink))
4597           goto start_failed;
4598       break;
4599     case GST_STATE_CHANGE_READY_TO_PAUSED:
4600       /* need to complete preroll before this state change completes, there
4601        * is no data flow in READY so we can safely assume we need to preroll. */
4602       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4603       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
4604       basesink->have_newsegment = FALSE;
4605       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
4606       gst_segment_init (basesink->abidata.ABI.clip_segment,
4607           GST_FORMAT_UNDEFINED);
4608       basesink->offset = 0;
4609       basesink->have_preroll = FALSE;
4610       priv->step_unlock = FALSE;
4611       basesink->need_preroll = TRUE;
4612       basesink->playing_async = TRUE;
4613       priv->current_sstart = GST_CLOCK_TIME_NONE;
4614       priv->current_sstop = GST_CLOCK_TIME_NONE;
4615       priv->eos_rtime = GST_CLOCK_TIME_NONE;
4616       priv->latency = 0;
4617       basesink->eos = FALSE;
4618       priv->received_eos = FALSE;
4619       gst_base_sink_reset_qos (basesink);
4620       priv->commited = FALSE;
4621       priv->call_preroll = TRUE;
4622       priv->current_step.valid = FALSE;
4623       priv->pending_step.valid = FALSE;
4624       if (priv->async_enabled) {
4625         GST_DEBUG_OBJECT (basesink, "doing async state change");
4626         /* when async enabled, post async-start message and return ASYNC from
4627          * the state change function */
4628         ret = GST_STATE_CHANGE_ASYNC;
4629         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4630             gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4631       } else {
4632         priv->have_latency = TRUE;
4633       }
4634       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4635       break;
4636     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4637       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4638       if (!gst_base_sink_needs_preroll (basesink)) {
4639         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
4640         /* no preroll needed anymore now. */
4641         basesink->playing_async = FALSE;
4642         basesink->need_preroll = FALSE;
4643         if (basesink->eos) {
4644           GstMessage *message;
4645
4646           /* need to post EOS message here */
4647           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
4648           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
4649           gst_message_set_seqnum (message, basesink->priv->seqnum);
4650           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
4651         } else {
4652           GST_DEBUG_OBJECT (basesink, "signal preroll");
4653           GST_PAD_PREROLL_SIGNAL (basesink->sinkpad);
4654         }
4655       } else {
4656         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
4657         basesink->need_preroll = TRUE;
4658         basesink->playing_async = TRUE;
4659         priv->call_preroll = TRUE;
4660         priv->commited = FALSE;
4661         if (priv->async_enabled) {
4662           GST_DEBUG_OBJECT (basesink, "doing async state change");
4663           ret = GST_STATE_CHANGE_ASYNC;
4664           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4665               gst_message_new_async_start (GST_OBJECT_CAST (basesink), FALSE));
4666         }
4667       }
4668       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4669       break;
4670     default:
4671       break;
4672   }
4673
4674   {
4675     GstStateChangeReturn bret;
4676
4677     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4678     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
4679       goto activate_failed;
4680   }
4681
4682   switch (transition) {
4683     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4684       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
4685       /* FIXME, make sure we cannot enter _render first */
4686
4687       /* we need to call ::unlock before locking PREROLL_LOCK
4688        * since we lock it before going into ::render */
4689       if (bclass->unlock)
4690         bclass->unlock (basesink);
4691
4692       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4693       GST_DEBUG_OBJECT (basesink, "got preroll lock");
4694       /* now that we have the PREROLL lock, clear our unlock request */
4695       if (bclass->unlock_stop)
4696         bclass->unlock_stop (basesink);
4697
4698       /* we need preroll again and we set the flag before unlocking the clockid
4699        * because if the clockid is unlocked before a current buffer expired, we
4700        * can use that buffer to preroll with */
4701       basesink->need_preroll = TRUE;
4702
4703       if (basesink->clock_id) {
4704         GST_DEBUG_OBJECT (basesink, "unschedule clock");
4705         gst_clock_id_unschedule (basesink->clock_id);
4706       }
4707
4708       /* if we don't have a preroll buffer we need to wait for a preroll and
4709        * return ASYNC. */
4710       if (!gst_base_sink_needs_preroll (basesink)) {
4711         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
4712         basesink->playing_async = FALSE;
4713       } else {
4714         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
4715           GST_DEBUG_OBJECT (basesink, "element is <= READY");
4716           ret = GST_STATE_CHANGE_SUCCESS;
4717         } else {
4718           GST_DEBUG_OBJECT (basesink,
4719               "PLAYING to PAUSED, we are not prerolled");
4720           basesink->playing_async = TRUE;
4721           priv->commited = FALSE;
4722           priv->call_preroll = TRUE;
4723           if (priv->async_enabled) {
4724             GST_DEBUG_OBJECT (basesink, "doing async state change");
4725             ret = GST_STATE_CHANGE_ASYNC;
4726             gst_element_post_message (GST_ELEMENT_CAST (basesink),
4727                 gst_message_new_async_start (GST_OBJECT_CAST (basesink),
4728                     FALSE));
4729           }
4730         }
4731       }
4732       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
4733           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
4734
4735       gst_base_sink_reset_qos (basesink);
4736       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4737       break;
4738     case GST_STATE_CHANGE_PAUSED_TO_READY:
4739       GST_PAD_PREROLL_LOCK (basesink->sinkpad);
4740       /* start by reseting our position state with the object lock so that the
4741        * position query gets the right idea. We do this before we post the
4742        * messages so that the message handlers pick this up. */
4743       GST_OBJECT_LOCK (basesink);
4744       basesink->have_newsegment = FALSE;
4745       priv->current_sstart = GST_CLOCK_TIME_NONE;
4746       priv->current_sstop = GST_CLOCK_TIME_NONE;
4747       priv->have_latency = FALSE;
4748       GST_OBJECT_UNLOCK (basesink);
4749
4750       gst_base_sink_set_last_buffer (basesink, NULL);
4751       priv->call_preroll = FALSE;
4752
4753       if (!priv->commited) {
4754         if (priv->async_enabled) {
4755           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
4756
4757           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4758               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
4759                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
4760
4761           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4762               gst_message_new_async_done (GST_OBJECT_CAST (basesink)));
4763         }
4764         priv->commited = TRUE;
4765       } else {
4766         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
4767       }
4768       GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
4769       break;
4770     case GST_STATE_CHANGE_READY_TO_NULL:
4771       if (bclass->stop) {
4772         if (!bclass->stop (basesink)) {
4773           GST_WARNING_OBJECT (basesink, "failed to stop");
4774         }
4775       }
4776       gst_base_sink_set_last_buffer (basesink, NULL);
4777       priv->call_preroll = FALSE;
4778       break;
4779     default:
4780       break;
4781   }
4782
4783   return ret;
4784
4785   /* ERRORS */
4786 start_failed:
4787   {
4788     GST_DEBUG_OBJECT (basesink, "failed to start");
4789     return GST_STATE_CHANGE_FAILURE;
4790   }
4791 activate_failed:
4792   {
4793     GST_DEBUG_OBJECT (basesink,
4794         "element failed to change states -- activation problem?");
4795     return GST_STATE_CHANGE_FAILURE;
4796   }
4797 }