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