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