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