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