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