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