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