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