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