basesink: more cleanups
[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 STREAM_LOCK, configures given segment with the event information. */
1407 static void
1408 gst_base_sink_configure_segment (GstBaseSink * basesink, GstPad * pad,
1409     GstEvent * event, GstSegment * segment)
1410 {
1411   /* The segment is protected with both the STREAM_LOCK and the OBJECT_LOCK.
1412    * We protect with the OBJECT_LOCK so that we can use the values to
1413    * safely answer a POSITION query. */
1414   GST_OBJECT_LOCK (basesink);
1415   /* the newsegment event is needed to bring the buffer timestamps to the
1416    * stream time and to drop samples outside of the playback segment. */
1417   gst_event_copy_segment (event, segment);
1418   GST_DEBUG_OBJECT (basesink, "configured SEGMENT %" GST_SEGMENT_FORMAT,
1419       segment);
1420   GST_OBJECT_UNLOCK (basesink);
1421 }
1422
1423 /* with PREROLL_LOCK, STREAM_LOCK */
1424 static gboolean
1425 gst_base_sink_commit_state (GstBaseSink * basesink)
1426 {
1427   /* commit state and proceed to next pending state */
1428   GstState current, next, pending, post_pending;
1429   gboolean post_paused = FALSE;
1430   gboolean post_async_done = FALSE;
1431   gboolean post_playing = FALSE;
1432   gboolean reset_time;
1433
1434   /* we are certainly not playing async anymore now */
1435   basesink->playing_async = FALSE;
1436
1437   GST_OBJECT_LOCK (basesink);
1438   current = GST_STATE (basesink);
1439   next = GST_STATE_NEXT (basesink);
1440   pending = GST_STATE_PENDING (basesink);
1441   post_pending = pending;
1442   reset_time = basesink->priv->reset_time;
1443   basesink->priv->reset_time = FALSE;
1444
1445   switch (pending) {
1446     case GST_STATE_PLAYING:
1447     {
1448       GST_DEBUG_OBJECT (basesink, "commiting state to PLAYING");
1449
1450       basesink->need_preroll = FALSE;
1451       post_async_done = TRUE;
1452       basesink->priv->commited = TRUE;
1453       post_playing = TRUE;
1454       /* post PAUSED too when we were READY */
1455       if (current == GST_STATE_READY) {
1456         post_paused = TRUE;
1457       }
1458       break;
1459     }
1460     case GST_STATE_PAUSED:
1461       GST_DEBUG_OBJECT (basesink, "commiting state to PAUSED");
1462       post_paused = TRUE;
1463       post_async_done = TRUE;
1464       basesink->priv->commited = TRUE;
1465       post_pending = GST_STATE_VOID_PENDING;
1466       break;
1467     case GST_STATE_READY:
1468     case GST_STATE_NULL:
1469       goto stopping;
1470     case GST_STATE_VOID_PENDING:
1471       goto nothing_pending;
1472     default:
1473       break;
1474   }
1475
1476   /* we can report latency queries now */
1477   basesink->priv->have_latency = TRUE;
1478
1479   GST_STATE (basesink) = pending;
1480   GST_STATE_NEXT (basesink) = GST_STATE_VOID_PENDING;
1481   GST_STATE_PENDING (basesink) = GST_STATE_VOID_PENDING;
1482   GST_STATE_RETURN (basesink) = GST_STATE_CHANGE_SUCCESS;
1483   GST_OBJECT_UNLOCK (basesink);
1484
1485   if (post_paused) {
1486     GST_DEBUG_OBJECT (basesink, "posting PAUSED state change message");
1487     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1488         gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
1489             current, next, post_pending));
1490   }
1491   if (post_async_done) {
1492     GST_DEBUG_OBJECT (basesink, "posting async-done message");
1493     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1494         gst_message_new_async_done (GST_OBJECT_CAST (basesink), reset_time));
1495   }
1496   if (post_playing) {
1497     GST_DEBUG_OBJECT (basesink, "posting PLAYING state change message");
1498     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1499         gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
1500             next, pending, GST_STATE_VOID_PENDING));
1501   }
1502
1503   GST_STATE_BROADCAST (basesink);
1504
1505   return TRUE;
1506
1507 nothing_pending:
1508   {
1509     /* Depending on the state, set our vars. We get in this situation when the
1510      * state change function got a change to update the state vars before the
1511      * streaming thread did. This is fine but we need to make sure that we
1512      * update the need_preroll var since it was TRUE when we got here and might
1513      * become FALSE if we got to PLAYING. */
1514     GST_DEBUG_OBJECT (basesink, "nothing to commit, now in %s",
1515         gst_element_state_get_name (current));
1516     switch (current) {
1517       case GST_STATE_PLAYING:
1518         basesink->need_preroll = FALSE;
1519         break;
1520       case GST_STATE_PAUSED:
1521         basesink->need_preroll = TRUE;
1522         break;
1523       default:
1524         basesink->need_preroll = FALSE;
1525         basesink->flushing = TRUE;
1526         break;
1527     }
1528     /* we can report latency queries now */
1529     basesink->priv->have_latency = TRUE;
1530     GST_OBJECT_UNLOCK (basesink);
1531     return TRUE;
1532   }
1533 stopping:
1534   {
1535     /* app is going to READY */
1536     GST_DEBUG_OBJECT (basesink, "stopping");
1537     basesink->need_preroll = FALSE;
1538     basesink->flushing = TRUE;
1539     GST_OBJECT_UNLOCK (basesink);
1540     return FALSE;
1541   }
1542 }
1543
1544 static void
1545 start_stepping (GstBaseSink * sink, GstSegment * segment,
1546     GstStepInfo * pending, GstStepInfo * current)
1547 {
1548   gint64 end;
1549   GstMessage *message;
1550
1551   GST_DEBUG_OBJECT (sink, "update pending step");
1552
1553   GST_OBJECT_LOCK (sink);
1554   memcpy (current, pending, sizeof (GstStepInfo));
1555   pending->valid = FALSE;
1556   GST_OBJECT_UNLOCK (sink);
1557
1558   /* post message first */
1559   message =
1560       gst_message_new_step_start (GST_OBJECT (sink), TRUE, current->format,
1561       current->amount, current->rate, current->flush, current->intermediate);
1562   gst_message_set_seqnum (message, current->seqnum);
1563   gst_element_post_message (GST_ELEMENT (sink), message);
1564
1565   /* get the running time of where we paused and remember it */
1566   current->start = gst_element_get_start_time (GST_ELEMENT_CAST (sink));
1567   gst_segment_set_running_time (segment, GST_FORMAT_TIME, current->start);
1568
1569   /* set the new rate for the remainder of the segment */
1570   current->start_rate = segment->rate;
1571   segment->rate *= current->rate;
1572
1573   /* save values */
1574   if (segment->rate > 0.0)
1575     current->start_stop = segment->stop;
1576   else
1577     current->start_start = segment->start;
1578
1579   if (current->format == GST_FORMAT_TIME) {
1580     end = current->start + current->amount;
1581     if (!current->flush) {
1582       /* update the segment clipping regions for non-flushing seeks */
1583       if (segment->rate > 0.0) {
1584         segment->stop = gst_segment_to_position (segment, GST_FORMAT_TIME, end);
1585         segment->position = segment->stop;
1586       } else {
1587         gint64 position;
1588
1589         position = gst_segment_to_position (segment, GST_FORMAT_TIME, end);
1590         segment->time = position;
1591         segment->start = position;
1592         segment->position = position;
1593       }
1594     }
1595   }
1596
1597   GST_DEBUG_OBJECT (sink, "segment now %" GST_SEGMENT_FORMAT, segment);
1598   GST_DEBUG_OBJECT (sink, "step started at running_time %" GST_TIME_FORMAT,
1599       GST_TIME_ARGS (current->start));
1600
1601   if (current->amount == -1) {
1602     GST_DEBUG_OBJECT (sink, "step amount == -1, stop stepping");
1603     current->valid = FALSE;
1604   } else {
1605     GST_DEBUG_OBJECT (sink, "step amount: %" G_GUINT64_FORMAT ", format: %s, "
1606         "rate: %f", current->amount, gst_format_get_name (current->format),
1607         current->rate);
1608   }
1609 }
1610
1611 static void
1612 stop_stepping (GstBaseSink * sink, GstSegment * segment,
1613     GstStepInfo * current, gint64 rstart, gint64 rstop, gboolean eos)
1614 {
1615   gint64 stop, position;
1616   GstMessage *message;
1617
1618   GST_DEBUG_OBJECT (sink, "step complete");
1619
1620   if (segment->rate > 0.0)
1621     stop = rstart;
1622   else
1623     stop = rstop;
1624
1625   GST_DEBUG_OBJECT (sink,
1626       "step stop at running_time %" GST_TIME_FORMAT, GST_TIME_ARGS (stop));
1627
1628   if (stop == -1)
1629     current->duration = current->position;
1630   else
1631     current->duration = stop - current->start;
1632
1633   GST_DEBUG_OBJECT (sink, "step elapsed running_time %" GST_TIME_FORMAT,
1634       GST_TIME_ARGS (current->duration));
1635
1636   position = current->start + current->duration;
1637
1638   /* now move the segment to the new running time */
1639   gst_segment_set_running_time (segment, GST_FORMAT_TIME, position);
1640
1641   if (current->flush) {
1642     /* and remove the time we flushed, start time did not change */
1643     segment->base = current->start;
1644   } else {
1645     /* start time is now the stepped position */
1646     gst_element_set_start_time (GST_ELEMENT_CAST (sink), position);
1647   }
1648
1649   /* restore the previous rate */
1650   segment->rate = current->start_rate;
1651
1652   if (segment->rate > 0.0)
1653     segment->stop = current->start_stop;
1654   else
1655     segment->start = current->start_start;
1656
1657   /* the clip segment is used for position report in paused... */
1658   gst_segment_copy_into (segment, &sink->clip_segment);
1659
1660   /* post the step done when we know the stepped duration in TIME */
1661   message =
1662       gst_message_new_step_done (GST_OBJECT_CAST (sink), current->format,
1663       current->amount, current->rate, current->flush, current->intermediate,
1664       current->duration, eos);
1665   gst_message_set_seqnum (message, current->seqnum);
1666   gst_element_post_message (GST_ELEMENT_CAST (sink), message);
1667
1668   if (!current->intermediate)
1669     sink->need_preroll = current->need_preroll;
1670
1671   /* and the current step info finished and becomes invalid */
1672   current->valid = FALSE;
1673 }
1674
1675 static gboolean
1676 handle_stepping (GstBaseSink * sink, GstSegment * segment,
1677     GstStepInfo * current, guint64 * cstart, guint64 * cstop, guint64 * rstart,
1678     guint64 * rstop)
1679 {
1680   gboolean step_end = FALSE;
1681
1682   /* see if we need to skip this buffer because of stepping */
1683   switch (current->format) {
1684     case GST_FORMAT_TIME:
1685     {
1686       guint64 end;
1687       guint64 first, last;
1688       gdouble abs_rate;
1689
1690       if (segment->rate > 0.0) {
1691         if (segment->stop == *cstop)
1692           *rstop = *rstart + current->amount;
1693
1694         first = *rstart;
1695         last = *rstop;
1696       } else {
1697         if (segment->start == *cstart)
1698           *rstart = *rstop + current->amount;
1699
1700         first = *rstop;
1701         last = *rstart;
1702       }
1703
1704       end = current->start + current->amount;
1705       current->position = first - current->start;
1706
1707       abs_rate = ABS (segment->rate);
1708       if (G_UNLIKELY (abs_rate != 1.0))
1709         current->position /= abs_rate;
1710
1711       GST_DEBUG_OBJECT (sink,
1712           "buffer: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1713           GST_TIME_ARGS (first), GST_TIME_ARGS (last));
1714       GST_DEBUG_OBJECT (sink,
1715           "got time step %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT "/%"
1716           GST_TIME_FORMAT, GST_TIME_ARGS (current->position),
1717           GST_TIME_ARGS (last - current->start),
1718           GST_TIME_ARGS (current->amount));
1719
1720       if ((current->flush && current->position >= current->amount)
1721           || last >= end) {
1722         GST_DEBUG_OBJECT (sink, "step ended, we need clipping");
1723         step_end = TRUE;
1724         if (segment->rate > 0.0) {
1725           *rstart = end;
1726           *cstart = gst_segment_to_position (segment, GST_FORMAT_TIME, end);
1727         } else {
1728           *rstop = end;
1729           *cstop = gst_segment_to_position (segment, GST_FORMAT_TIME, end);
1730         }
1731       }
1732       GST_DEBUG_OBJECT (sink,
1733           "cstart %" GST_TIME_FORMAT ", rstart %" GST_TIME_FORMAT,
1734           GST_TIME_ARGS (*cstart), GST_TIME_ARGS (*rstart));
1735       GST_DEBUG_OBJECT (sink,
1736           "cstop %" GST_TIME_FORMAT ", rstop %" GST_TIME_FORMAT,
1737           GST_TIME_ARGS (*cstop), GST_TIME_ARGS (*rstop));
1738       break;
1739     }
1740     case GST_FORMAT_BUFFERS:
1741       GST_DEBUG_OBJECT (sink,
1742           "got default step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1743           current->position, current->amount);
1744
1745       if (current->position < current->amount) {
1746         current->position++;
1747       } else {
1748         step_end = TRUE;
1749       }
1750       break;
1751     case GST_FORMAT_DEFAULT:
1752     default:
1753       GST_DEBUG_OBJECT (sink,
1754           "got unknown step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1755           current->position, current->amount);
1756       break;
1757   }
1758   return step_end;
1759 }
1760
1761 /* with STREAM_LOCK, PREROLL_LOCK
1762  *
1763  * Returns TRUE if the object needs synchronisation and takes therefore
1764  * part in prerolling.
1765  *
1766  * rsstart/rsstop contain the start/stop in stream time.
1767  * rrstart/rrstop contain the start/stop in running time.
1768  */
1769 static gboolean
1770 gst_base_sink_get_sync_times (GstBaseSink * basesink, GstMiniObject * obj,
1771     GstClockTime * rsstart, GstClockTime * rsstop,
1772     GstClockTime * rrstart, GstClockTime * rrstop, gboolean * do_sync,
1773     gboolean * stepped, GstSegment * segment, GstStepInfo * step,
1774     gboolean * step_end, guint8 obj_type)
1775 {
1776   GstBaseSinkClass *bclass;
1777   GstBuffer *buffer;
1778   GstClockTime start, stop;     /* raw start/stop timestamps */
1779   guint64 cstart, cstop;        /* clipped raw timestamps */
1780   guint64 rstart, rstop;        /* clipped timestamps converted to running time */
1781   GstClockTime sstart, sstop;   /* clipped timestamps converted to stream time */
1782   GstFormat format;
1783   GstBaseSinkPrivate *priv;
1784   gboolean eos;
1785
1786   priv = basesink->priv;
1787
1788   /* start with nothing */
1789   start = stop = GST_CLOCK_TIME_NONE;
1790
1791   if (G_UNLIKELY (OBJ_IS_EVENT (obj_type))) {
1792     GstEvent *event = GST_EVENT_CAST (obj);
1793
1794     switch (GST_EVENT_TYPE (event)) {
1795         /* EOS event needs syncing */
1796       case GST_EVENT_EOS:
1797       {
1798         if (basesink->segment.rate >= 0.0) {
1799           sstart = sstop = priv->current_sstop;
1800           if (!GST_CLOCK_TIME_IS_VALID (sstart)) {
1801             /* we have not seen a buffer yet, use the segment values */
1802             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1803                 basesink->segment.format, basesink->segment.stop);
1804           }
1805         } else {
1806           sstart = sstop = priv->current_sstart;
1807           if (!GST_CLOCK_TIME_IS_VALID (sstart)) {
1808             /* we have not seen a buffer yet, use the segment values */
1809             sstart = sstop = gst_segment_to_stream_time (&basesink->segment,
1810                 basesink->segment.format, basesink->segment.start);
1811           }
1812         }
1813
1814         rstart = rstop = priv->eos_rtime;
1815         *do_sync = rstart != -1;
1816         GST_DEBUG_OBJECT (basesink, "sync times for EOS %" GST_TIME_FORMAT,
1817             GST_TIME_ARGS (rstart));
1818         /* if we are stepping, we end now */
1819         *step_end = step->valid;
1820         eos = TRUE;
1821         goto eos_done;
1822       }
1823       default:
1824         /* other events do not need syncing */
1825         return FALSE;
1826     }
1827   }
1828
1829   eos = FALSE;
1830
1831 again:
1832   /* else do buffer sync code */
1833   buffer = GST_BUFFER_CAST (obj);
1834
1835   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1836
1837   /* just get the times to see if we need syncing, if the start returns -1 we
1838    * don't sync. */
1839   if (bclass->get_times)
1840     bclass->get_times (basesink, buffer, &start, &stop);
1841
1842   if (!GST_CLOCK_TIME_IS_VALID (start)) {
1843     /* we don't need to sync but we still want to get the timestamps for
1844      * tracking the position */
1845     gst_base_sink_get_times (basesink, buffer, &start, &stop);
1846     *do_sync = FALSE;
1847   } else {
1848     *do_sync = TRUE;
1849   }
1850
1851   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
1852       ", stop: %" GST_TIME_FORMAT ", do_sync %d", GST_TIME_ARGS (start),
1853       GST_TIME_ARGS (stop), *do_sync);
1854
1855   /* collect segment and format for code clarity */
1856   format = segment->format;
1857
1858   /* clip */
1859   if (G_UNLIKELY (!gst_segment_clip (segment, format,
1860               start, stop, &cstart, &cstop))) {
1861     if (step->valid) {
1862       GST_DEBUG_OBJECT (basesink, "step out of segment");
1863       /* when we are stepping, pretend we're at the end of the segment */
1864       if (segment->rate > 0.0) {
1865         cstart = segment->stop;
1866         cstop = segment->stop;
1867       } else {
1868         cstart = segment->start;
1869         cstop = segment->start;
1870       }
1871       goto do_times;
1872     }
1873     goto out_of_segment;
1874   }
1875
1876   if (G_UNLIKELY (start != cstart || stop != cstop)) {
1877     GST_DEBUG_OBJECT (basesink, "clipped to: start %" GST_TIME_FORMAT
1878         ", stop: %" GST_TIME_FORMAT, GST_TIME_ARGS (cstart),
1879         GST_TIME_ARGS (cstop));
1880   }
1881
1882   /* set last stop position */
1883   if (G_LIKELY (stop != GST_CLOCK_TIME_NONE && cstop != GST_CLOCK_TIME_NONE))
1884     segment->position = cstop;
1885   else
1886     segment->position = cstart;
1887
1888 do_times:
1889   rstart = gst_segment_to_running_time (segment, format, cstart);
1890   rstop = gst_segment_to_running_time (segment, format, cstop);
1891
1892   if (G_UNLIKELY (step->valid)) {
1893     if (!(*step_end = handle_stepping (basesink, segment, step, &cstart, &cstop,
1894                 &rstart, &rstop))) {
1895       /* step is still busy, we discard data when we are flushing */
1896       *stepped = step->flush;
1897       GST_DEBUG_OBJECT (basesink, "stepping busy");
1898     }
1899   }
1900   /* this can produce wrong values if we accumulated non-TIME segments. If this happens,
1901    * upstream is behaving very badly */
1902   sstart = gst_segment_to_stream_time (segment, format, cstart);
1903   sstop = gst_segment_to_stream_time (segment, format, cstop);
1904
1905 eos_done:
1906   /* eos_done label only called when doing EOS, we also stop stepping then */
1907   if (*step_end && step->flush) {
1908     GST_DEBUG_OBJECT (basesink, "flushing step ended");
1909     stop_stepping (basesink, segment, step, rstart, rstop, eos);
1910     *step_end = FALSE;
1911     /* re-determine running start times for adjusted segment
1912      * (which has a flushed amount of running/accumulated time removed) */
1913     if (!GST_IS_EVENT (obj)) {
1914       GST_DEBUG_OBJECT (basesink, "refresh sync times");
1915       goto again;
1916     }
1917   }
1918
1919   /* save times */
1920   *rsstart = sstart;
1921   *rsstop = sstop;
1922   *rrstart = rstart;
1923   *rrstop = rstop;
1924
1925   /* buffers and EOS always need syncing and preroll */
1926   return TRUE;
1927
1928   /* special cases */
1929 out_of_segment:
1930   {
1931     /* we usually clip in the chain function already but stepping could cause
1932      * the segment to be updated later. we return FALSE so that we don't try
1933      * to sync on it. */
1934     GST_LOG_OBJECT (basesink, "buffer skipped, not in segment");
1935     return FALSE;
1936   }
1937 }
1938
1939 /* with STREAM_LOCK, PREROLL_LOCK, LOCK
1940  * adjust a timestamp with the latency and timestamp offset. This function does
1941  * not adjust for the render delay. */
1942 static GstClockTime
1943 gst_base_sink_adjust_time (GstBaseSink * basesink, GstClockTime time)
1944 {
1945   GstClockTimeDiff ts_offset;
1946
1947   /* don't do anything funny with invalid timestamps */
1948   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
1949     return time;
1950
1951   time += basesink->priv->latency;
1952
1953   /* apply offset, be carefull for underflows */
1954   ts_offset = basesink->priv->ts_offset;
1955   if (ts_offset < 0) {
1956     ts_offset = -ts_offset;
1957     if (ts_offset < time)
1958       time -= ts_offset;
1959     else
1960       time = 0;
1961   } else
1962     time += ts_offset;
1963
1964   /* subtract the render delay again, which was included in the latency */
1965   if (time > basesink->priv->render_delay)
1966     time -= basesink->priv->render_delay;
1967   else
1968     time = 0;
1969
1970   return time;
1971 }
1972
1973 /**
1974  * gst_base_sink_wait_clock:
1975  * @sink: the sink
1976  * @time: the running_time to be reached
1977  * @jitter: (out) (allow-none): the jitter to be filled with time diff, or NULL
1978  *
1979  * This function will block until @time is reached. It is usually called by
1980  * subclasses that use their own internal synchronisation.
1981  *
1982  * If @time is not valid, no sycnhronisation is done and #GST_CLOCK_BADTIME is
1983  * returned. Likewise, if synchronisation is disabled in the element or there
1984  * is no clock, no synchronisation is done and #GST_CLOCK_BADTIME is returned.
1985  *
1986  * This function should only be called with the PREROLL_LOCK held, like when
1987  * receiving an EOS event in the #GstBaseSinkClass.event() vmethod or when
1988  * receiving a buffer in
1989  * the #GstBaseSinkClass.render() vmethod.
1990  *
1991  * The @time argument should be the running_time of when this method should
1992  * return and is not adjusted with any latency or offset configured in the
1993  * sink.
1994  *
1995  * Since: 0.10.20
1996  *
1997  * Returns: #GstClockReturn
1998  */
1999 GstClockReturn
2000 gst_base_sink_wait_clock (GstBaseSink * sink, GstClockTime time,
2001     GstClockTimeDiff * jitter)
2002 {
2003   GstClockReturn ret;
2004   GstClock *clock;
2005   GstClockTime base_time;
2006
2007   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
2008     goto invalid_time;
2009
2010   GST_OBJECT_LOCK (sink);
2011   if (G_UNLIKELY (!sink->sync))
2012     goto no_sync;
2013
2014   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (sink)) == NULL))
2015     goto no_clock;
2016
2017   base_time = GST_ELEMENT_CAST (sink)->base_time;
2018   GST_LOG_OBJECT (sink,
2019       "time %" GST_TIME_FORMAT ", base_time %" GST_TIME_FORMAT,
2020       GST_TIME_ARGS (time), GST_TIME_ARGS (base_time));
2021
2022   /* add base_time to running_time to get the time against the clock */
2023   time += base_time;
2024
2025   /* Re-use existing clockid if available */
2026   /* FIXME: Casting to GstClockEntry only works because the types
2027    * are the same */
2028   if (G_LIKELY (sink->priv->cached_clock_id != NULL
2029           && GST_CLOCK_ENTRY_CLOCK ((GstClockEntry *) sink->
2030               priv->cached_clock_id) == clock)) {
2031     if (!gst_clock_single_shot_id_reinit (clock, sink->priv->cached_clock_id,
2032             time)) {
2033       gst_clock_id_unref (sink->priv->cached_clock_id);
2034       sink->priv->cached_clock_id = gst_clock_new_single_shot_id (clock, time);
2035     }
2036   } else {
2037     if (sink->priv->cached_clock_id != NULL)
2038       gst_clock_id_unref (sink->priv->cached_clock_id);
2039     sink->priv->cached_clock_id = gst_clock_new_single_shot_id (clock, time);
2040   }
2041   GST_OBJECT_UNLOCK (sink);
2042
2043   /* A blocking wait is performed on the clock. We save the ClockID
2044    * so we can unlock the entry at any time. While we are blocking, we
2045    * release the PREROLL_LOCK so that other threads can interrupt the
2046    * entry. */
2047   sink->clock_id = sink->priv->cached_clock_id;
2048   /* release the preroll lock while waiting */
2049   GST_BASE_SINK_PREROLL_UNLOCK (sink);
2050
2051   ret = gst_clock_id_wait (sink->priv->cached_clock_id, jitter);
2052
2053   GST_BASE_SINK_PREROLL_LOCK (sink);
2054   sink->clock_id = NULL;
2055
2056   return ret;
2057
2058   /* no syncing needed */
2059 invalid_time:
2060   {
2061     GST_DEBUG_OBJECT (sink, "time not valid, no sync needed");
2062     return GST_CLOCK_BADTIME;
2063   }
2064 no_sync:
2065   {
2066     GST_DEBUG_OBJECT (sink, "sync disabled");
2067     GST_OBJECT_UNLOCK (sink);
2068     return GST_CLOCK_BADTIME;
2069   }
2070 no_clock:
2071   {
2072     GST_DEBUG_OBJECT (sink, "no clock, can't sync");
2073     GST_OBJECT_UNLOCK (sink);
2074     return GST_CLOCK_BADTIME;
2075   }
2076 }
2077
2078 /**
2079  * gst_base_sink_wait_preroll:
2080  * @sink: the sink
2081  *
2082  * If the #GstBaseSinkClass.render() method performs its own synchronisation
2083  * against the clock it must unblock when going from PLAYING to the PAUSED state
2084  * and call this method before continuing to render the remaining data.
2085  *
2086  * This function will block until a state change to PLAYING happens (in which
2087  * case this function returns #GST_FLOW_OK) or the processing must be stopped due
2088  * to a state change to READY or a FLUSH event (in which case this function
2089  * returns #GST_FLOW_WRONG_STATE).
2090  *
2091  * This function should only be called with the PREROLL_LOCK held, like in the
2092  * render function.
2093  *
2094  * Returns: #GST_FLOW_OK if the preroll completed and processing can
2095  * continue. Any other return value should be returned from the render vmethod.
2096  *
2097  * Since: 0.10.11
2098  */
2099 GstFlowReturn
2100 gst_base_sink_wait_preroll (GstBaseSink * sink)
2101 {
2102   sink->have_preroll = TRUE;
2103   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
2104   /* block until the state changes, or we get a flush, or something */
2105   GST_BASE_SINK_PREROLL_WAIT (sink);
2106   sink->have_preroll = FALSE;
2107   if (G_UNLIKELY (sink->flushing))
2108     goto stopping;
2109   if (G_UNLIKELY (sink->priv->step_unlock))
2110     goto step_unlocked;
2111   GST_DEBUG_OBJECT (sink, "continue after preroll");
2112
2113   return GST_FLOW_OK;
2114
2115   /* ERRORS */
2116 stopping:
2117   {
2118     GST_DEBUG_OBJECT (sink, "preroll interrupted because of flush");
2119     return GST_FLOW_WRONG_STATE;
2120   }
2121 step_unlocked:
2122   {
2123     sink->priv->step_unlock = FALSE;
2124     GST_DEBUG_OBJECT (sink, "preroll interrupted because of step");
2125     return GST_FLOW_STEP;
2126   }
2127 }
2128
2129 static inline guint8
2130 get_object_type (GstMiniObject * obj)
2131 {
2132   guint8 obj_type;
2133
2134   if (G_LIKELY (GST_IS_BUFFER (obj)))
2135     obj_type = _PR_IS_BUFFER;
2136   else if (GST_IS_EVENT (obj))
2137     obj_type = _PR_IS_EVENT;
2138   else if (GST_IS_BUFFER_LIST (obj))
2139     obj_type = _PR_IS_BUFFERLIST;
2140   else
2141     obj_type = _PR_IS_NOTHING;
2142
2143   return obj_type;
2144 }
2145
2146 /**
2147  * gst_base_sink_do_preroll:
2148  * @sink: the sink
2149  * @obj: (transfer none): the mini object that caused the preroll
2150  *
2151  * If the @sink spawns its own thread for pulling buffers from upstream it
2152  * should call this method after it has pulled a buffer. If the element needed
2153  * to preroll, this function will perform the preroll and will then block
2154  * until the element state is changed.
2155  *
2156  * This function should be called with the PREROLL_LOCK held.
2157  *
2158  * Returns: #GST_FLOW_OK if the preroll completed and processing can
2159  * continue. Any other return value should be returned from the render vmethod.
2160  *
2161  * Since: 0.10.22
2162  */
2163 GstFlowReturn
2164 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
2165 {
2166   GstFlowReturn ret;
2167
2168   while (G_UNLIKELY (sink->need_preroll)) {
2169     guint8 obj_type;
2170     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
2171
2172     obj_type = get_object_type (obj);
2173
2174     ret = gst_base_sink_preroll_object (sink, obj_type, obj);
2175     if (ret != GST_FLOW_OK)
2176       goto preroll_failed;
2177
2178     /* need to recheck here because the commit state could have
2179      * made us not need the preroll anymore */
2180     if (G_LIKELY (sink->need_preroll)) {
2181       /* block until the state changes, or we get a flush, or something */
2182       ret = gst_base_sink_wait_preroll (sink);
2183       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2184         goto preroll_failed;
2185     }
2186   }
2187   return GST_FLOW_OK;
2188
2189   /* ERRORS */
2190 preroll_failed:
2191   {
2192     GST_DEBUG_OBJECT (sink, "preroll failed: %s", gst_flow_get_name (ret));
2193     return ret;
2194   }
2195 }
2196
2197 /**
2198  * gst_base_sink_wait_eos:
2199  * @sink: the sink
2200  * @time: the running_time to be reached
2201  * @jitter: (out) (allow-none): the jitter to be filled with time diff, or NULL
2202  *
2203  * This function will block until @time is reached. It is usually called by
2204  * subclasses that use their own internal synchronisation but want to let the
2205  * EOS be handled by the base class.
2206  *
2207  * This function should only be called with the PREROLL_LOCK held, like when
2208  * receiving an EOS event in the ::event vmethod.
2209  *
2210  * The @time argument should be the running_time of when the EOS should happen
2211  * and will be adjusted with any latency and offset configured in the sink.
2212  *
2213  * Returns: #GstFlowReturn
2214  *
2215  * Since: 0.10.15
2216  */
2217 GstFlowReturn
2218 gst_base_sink_wait_eos (GstBaseSink * sink, GstClockTime time,
2219     GstClockTimeDiff * jitter)
2220 {
2221   GstClockReturn status;
2222   GstFlowReturn ret;
2223
2224   do {
2225     GstClockTime stime;
2226
2227     GST_DEBUG_OBJECT (sink, "checking preroll");
2228
2229     /* first wait for the playing state before we can continue */
2230     while (G_UNLIKELY (sink->need_preroll)) {
2231       ret = gst_base_sink_wait_preroll (sink);
2232       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2233         goto flushing;
2234     }
2235
2236     /* preroll done, we can sync since we are in PLAYING now. */
2237     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
2238         GST_TIME_FORMAT, GST_TIME_ARGS (time));
2239
2240     /* compensate for latency and ts_offset. We don't adjust for render delay
2241      * because we don't interact with the device on EOS normally. */
2242     stime = gst_base_sink_adjust_time (sink, time);
2243
2244     /* wait for the clock, this can be interrupted because we got shut down or
2245      * we PAUSED. */
2246     status = gst_base_sink_wait_clock (sink, stime, jitter);
2247
2248     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
2249
2250     /* invalid time, no clock or sync disabled, just continue then */
2251     if (status == GST_CLOCK_BADTIME)
2252       break;
2253
2254     /* waiting could have been interrupted and we can be flushing now */
2255     if (G_UNLIKELY (sink->flushing))
2256       goto flushing;
2257
2258     /* retry if we got unscheduled, which means we did not reach the timeout
2259      * yet. if some other error occures, we continue. */
2260   } while (status == GST_CLOCK_UNSCHEDULED);
2261
2262   GST_DEBUG_OBJECT (sink, "end of stream");
2263
2264   return GST_FLOW_OK;
2265
2266   /* ERRORS */
2267 flushing:
2268   {
2269     GST_DEBUG_OBJECT (sink, "we are flushing");
2270     return GST_FLOW_WRONG_STATE;
2271   }
2272 }
2273
2274 /* with STREAM_LOCK, PREROLL_LOCK
2275  *
2276  * Make sure we are in PLAYING and synchronize an object to the clock.
2277  *
2278  * If we need preroll, we are not in PLAYING. We try to commit the state
2279  * if needed and then block if we still are not PLAYING.
2280  *
2281  * We start waiting on the clock in PLAYING. If we got interrupted, we
2282  * immediately try to re-preroll.
2283  *
2284  * Some objects do not need synchronisation (most events) and so this function
2285  * immediately returns GST_FLOW_OK.
2286  *
2287  * for objects that arrive later than max-lateness to be synchronized to the
2288  * clock have the @late boolean set to TRUE.
2289  *
2290  * This function keeps a running average of the jitter (the diff between the
2291  * clock time and the requested sync time). The jitter is negative for
2292  * objects that arrive in time and positive for late buffers.
2293  *
2294  * does not take ownership of obj.
2295  */
2296 static GstFlowReturn
2297 gst_base_sink_do_sync (GstBaseSink * basesink, GstPad * pad,
2298     GstMiniObject * obj, gboolean * late, gboolean * step_end, guint8 obj_type)
2299 {
2300   GstClockTimeDiff jitter = 0;
2301   gboolean syncable;
2302   GstClockReturn status = GST_CLOCK_OK;
2303   GstClockTime rstart, rstop, sstart, sstop, stime;
2304   gboolean do_sync;
2305   GstBaseSinkPrivate *priv;
2306   GstFlowReturn ret;
2307   GstStepInfo *current, *pending;
2308   gboolean stepped;
2309
2310   priv = basesink->priv;
2311
2312 do_step:
2313   sstart = sstop = rstart = rstop = GST_CLOCK_TIME_NONE;
2314   do_sync = TRUE;
2315   stepped = FALSE;
2316
2317   priv->current_rstart = GST_CLOCK_TIME_NONE;
2318
2319   /* get stepping info */
2320   current = &priv->current_step;
2321   pending = &priv->pending_step;
2322
2323   /* get timing information for this object against the render segment */
2324   syncable = gst_base_sink_get_sync_times (basesink, obj,
2325       &sstart, &sstop, &rstart, &rstop, &do_sync, &stepped, &basesink->segment,
2326       current, step_end, obj_type);
2327
2328   if (G_UNLIKELY (stepped))
2329     goto step_skipped;
2330
2331   /* a syncable object needs to participate in preroll and
2332    * clocking. All buffers and EOS are syncable. */
2333   if (G_UNLIKELY (!syncable))
2334     goto not_syncable;
2335
2336   /* store timing info for current object */
2337   priv->current_rstart = rstart;
2338   priv->current_rstop = (GST_CLOCK_TIME_IS_VALID (rstop) ? rstop : rstart);
2339
2340   /* save sync time for eos when the previous object needed sync */
2341   priv->eos_rtime = (do_sync ? priv->current_rstop : GST_CLOCK_TIME_NONE);
2342
2343   /* calculate inter frame spacing */
2344   if (G_UNLIKELY (priv->prev_rstart != -1 && priv->prev_rstart < rstart)) {
2345     GstClockTime in_diff;
2346
2347     in_diff = rstart - priv->prev_rstart;
2348
2349     if (priv->avg_in_diff == -1)
2350       priv->avg_in_diff = in_diff;
2351     else
2352       priv->avg_in_diff = UPDATE_RUNNING_AVG (priv->avg_in_diff, in_diff);
2353
2354     GST_LOG_OBJECT (basesink, "avg frame diff %" GST_TIME_FORMAT,
2355         GST_TIME_ARGS (priv->avg_in_diff));
2356
2357   }
2358   priv->prev_rstart = rstart;
2359
2360   if (G_UNLIKELY (priv->earliest_in_time != -1
2361           && rstart < priv->earliest_in_time))
2362     goto qos_dropped;
2363
2364 again:
2365   /* first do preroll, this makes sure we commit our state
2366    * to PAUSED and can continue to PLAYING. We cannot perform
2367    * any clock sync in PAUSED because there is no clock. */
2368   ret = gst_base_sink_do_preroll (basesink, obj);
2369   if (G_UNLIKELY (ret != GST_FLOW_OK))
2370     goto preroll_failed;
2371
2372   /* update the segment with a pending step if the current one is invalid and we
2373    * have a new pending one. We only accept new step updates after a preroll */
2374   if (G_UNLIKELY (pending->valid && !current->valid)) {
2375     start_stepping (basesink, &basesink->segment, pending, current);
2376     goto do_step;
2377   }
2378
2379   /* After rendering we store the position of the last buffer so that we can use
2380    * it to report the position. We need to take the lock here. */
2381   GST_OBJECT_LOCK (basesink);
2382   priv->current_sstart = sstart;
2383   priv->current_sstop = (GST_CLOCK_TIME_IS_VALID (sstop) ? sstop : sstart);
2384   GST_OBJECT_UNLOCK (basesink);
2385
2386   if (!do_sync)
2387     goto done;
2388
2389   /* adjust for latency */
2390   stime = gst_base_sink_adjust_time (basesink, rstart);
2391
2392   /* adjust for render-delay, avoid underflows */
2393   if (GST_CLOCK_TIME_IS_VALID (stime)) {
2394     if (stime > priv->render_delay)
2395       stime -= priv->render_delay;
2396     else
2397       stime = 0;
2398   }
2399
2400   /* preroll done, we can sync since we are in PLAYING now. */
2401   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
2402       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
2403       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
2404
2405   /* This function will return immediately if start == -1, no clock
2406    * or sync is disabled with GST_CLOCK_BADTIME. */
2407   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
2408
2409   GST_DEBUG_OBJECT (basesink, "clock returned %d, jitter %c%" GST_TIME_FORMAT,
2410       status, (jitter < 0 ? '-' : ' '), GST_TIME_ARGS (ABS (jitter)));
2411
2412   /* invalid time, no clock or sync disabled, just render */
2413   if (status == GST_CLOCK_BADTIME)
2414     goto done;
2415
2416   /* waiting could have been interrupted and we can be flushing now */
2417   if (G_UNLIKELY (basesink->flushing))
2418     goto flushing;
2419
2420   /* check for unlocked by a state change, we are not flushing so
2421    * we can try to preroll on the current buffer. */
2422   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
2423     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
2424     priv->call_preroll = TRUE;
2425     goto again;
2426   }
2427
2428   /* successful syncing done, record observation */
2429   priv->current_jitter = jitter;
2430
2431   /* check if the object should be dropped */
2432   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
2433       status, jitter);
2434
2435 done:
2436   return GST_FLOW_OK;
2437
2438   /* ERRORS */
2439 step_skipped:
2440   {
2441     GST_DEBUG_OBJECT (basesink, "skipped stepped object %p", obj);
2442     *late = TRUE;
2443     return GST_FLOW_OK;
2444   }
2445 not_syncable:
2446   {
2447     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2448     return GST_FLOW_OK;
2449   }
2450 qos_dropped:
2451   {
2452     GST_DEBUG_OBJECT (basesink, "dropped because of QoS %p", obj);
2453     *late = TRUE;
2454     return GST_FLOW_OK;
2455   }
2456 flushing:
2457   {
2458     GST_DEBUG_OBJECT (basesink, "we are flushing");
2459     return GST_FLOW_WRONG_STATE;
2460   }
2461 preroll_failed:
2462   {
2463     GST_DEBUG_OBJECT (basesink, "preroll failed");
2464     *step_end = FALSE;
2465     return ret;
2466   }
2467 }
2468
2469 static gboolean
2470 gst_base_sink_send_qos (GstBaseSink * basesink, GstQOSType type,
2471     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2472 {
2473   GstEvent *event;
2474   gboolean res;
2475
2476   /* generate Quality-of-Service event */
2477   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2478       "qos: type %d, proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2479       GST_TIME_FORMAT, type, proportion, diff, GST_TIME_ARGS (time));
2480
2481   event = gst_event_new_qos (type, proportion, diff, time);
2482
2483   /* send upstream */
2484   res = gst_pad_push_event (basesink->sinkpad, event);
2485
2486   return res;
2487 }
2488
2489 static void
2490 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2491 {
2492   GstBaseSinkPrivate *priv;
2493   GstClockTime start, stop;
2494   GstClockTimeDiff jitter;
2495   GstClockTime pt, entered, left;
2496   GstClockTime duration;
2497   gdouble rate;
2498
2499   priv = sink->priv;
2500
2501   start = priv->current_rstart;
2502
2503   if (priv->current_step.valid)
2504     return;
2505
2506   /* if Quality-of-Service disabled, do nothing */
2507   if (!g_atomic_int_get (&priv->qos_enabled) ||
2508       !GST_CLOCK_TIME_IS_VALID (start))
2509     return;
2510
2511   stop = priv->current_rstop;
2512   jitter = priv->current_jitter;
2513
2514   if (jitter < 0) {
2515     /* this is the time the buffer entered the sink */
2516     if (start < -jitter)
2517       entered = 0;
2518     else
2519       entered = start + jitter;
2520     left = start;
2521   } else {
2522     /* this is the time the buffer entered the sink */
2523     entered = start + jitter;
2524     /* this is the time the buffer left the sink */
2525     left = start + jitter;
2526   }
2527
2528   /* calculate duration of the buffer */
2529   if (GST_CLOCK_TIME_IS_VALID (stop) && stop != start)
2530     duration = stop - start;
2531   else
2532     duration = priv->avg_in_diff;
2533
2534   /* if we have the time when the last buffer left us, calculate
2535    * processing time */
2536   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2537     if (entered > priv->last_left) {
2538       pt = entered - priv->last_left;
2539     } else {
2540       pt = 0;
2541     }
2542   } else {
2543     pt = priv->avg_pt;
2544   }
2545
2546   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2547       ", stop %" GST_TIME_FORMAT ", entered %" GST_TIME_FORMAT ", left %"
2548       GST_TIME_FORMAT ", pt: %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2549       ",jitter %" G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
2550       GST_TIME_ARGS (entered), GST_TIME_ARGS (left), GST_TIME_ARGS (pt),
2551       GST_TIME_ARGS (duration), jitter);
2552
2553   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "avg_duration: %" GST_TIME_FORMAT
2554       ", avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2555       GST_TIME_ARGS (priv->avg_duration), GST_TIME_ARGS (priv->avg_pt),
2556       priv->avg_rate);
2557
2558   /* collect running averages. for first observations, we copy the
2559    * values */
2560   if (!GST_CLOCK_TIME_IS_VALID (priv->avg_duration))
2561     priv->avg_duration = duration;
2562   else
2563     priv->avg_duration = UPDATE_RUNNING_AVG (priv->avg_duration, duration);
2564
2565   if (!GST_CLOCK_TIME_IS_VALID (priv->avg_pt))
2566     priv->avg_pt = pt;
2567   else
2568     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2569
2570   if (priv->avg_duration != 0)
2571     rate =
2572         gst_guint64_to_gdouble (priv->avg_pt) /
2573         gst_guint64_to_gdouble (priv->avg_duration);
2574   else
2575     rate = 1.0;
2576
2577   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2578     if (dropped || priv->avg_rate < 0.0) {
2579       priv->avg_rate = rate;
2580     } else {
2581       if (rate > 1.0)
2582         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2583       else
2584         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2585     }
2586   }
2587
2588   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2589       "updated: avg_duration: %" GST_TIME_FORMAT ", avg_pt: %" GST_TIME_FORMAT
2590       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_duration),
2591       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2592
2593
2594   if (priv->avg_rate >= 0.0) {
2595     GstQOSType type;
2596     GstClockTimeDiff diff;
2597
2598     /* if we have a valid rate, start sending QoS messages */
2599     if (priv->current_jitter < 0) {
2600       /* make sure we never go below 0 when adding the jitter to the
2601        * timestamp. */
2602       if (priv->current_rstart < -priv->current_jitter)
2603         priv->current_jitter = -priv->current_rstart;
2604     }
2605
2606     if (priv->throttle_time > 0) {
2607       diff = priv->throttle_time;
2608       type = GST_QOS_TYPE_THROTTLE;
2609     } else {
2610       diff = priv->current_jitter;
2611       if (diff <= 0)
2612         type = GST_QOS_TYPE_OVERFLOW;
2613       else
2614         type = GST_QOS_TYPE_UNDERFLOW;
2615     }
2616
2617     gst_base_sink_send_qos (sink, type, priv->avg_rate, priv->current_rstart,
2618         diff);
2619   }
2620
2621   /* record when this buffer will leave us */
2622   priv->last_left = left;
2623 }
2624
2625 /* reset all qos measuring */
2626 static void
2627 gst_base_sink_reset_qos (GstBaseSink * sink)
2628 {
2629   GstBaseSinkPrivate *priv;
2630
2631   priv = sink->priv;
2632
2633   priv->last_render_time = GST_CLOCK_TIME_NONE;
2634   priv->prev_rstart = GST_CLOCK_TIME_NONE;
2635   priv->earliest_in_time = GST_CLOCK_TIME_NONE;
2636   priv->last_left = GST_CLOCK_TIME_NONE;
2637   priv->avg_duration = GST_CLOCK_TIME_NONE;
2638   priv->avg_pt = GST_CLOCK_TIME_NONE;
2639   priv->avg_rate = -1.0;
2640   priv->avg_render = GST_CLOCK_TIME_NONE;
2641   priv->avg_in_diff = GST_CLOCK_TIME_NONE;
2642   priv->rendered = 0;
2643   priv->dropped = 0;
2644
2645 }
2646
2647 /* Checks if the object was scheduled too late.
2648  *
2649  * rstart/rstop contain the running_time start and stop values
2650  * of the object.
2651  *
2652  * status and jitter contain the return values from the clock wait.
2653  *
2654  * returns TRUE if the buffer was too late.
2655  */
2656 static gboolean
2657 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2658     GstClockTime rstart, GstClockTime rstop,
2659     GstClockReturn status, GstClockTimeDiff jitter)
2660 {
2661   gboolean late;
2662   guint64 max_lateness;
2663   GstBaseSinkPrivate *priv;
2664
2665   priv = basesink->priv;
2666
2667   late = FALSE;
2668
2669   /* only for objects that were too late */
2670   if (G_LIKELY (status != GST_CLOCK_EARLY))
2671     goto in_time;
2672
2673   max_lateness = basesink->max_lateness;
2674
2675   /* check if frame dropping is enabled */
2676   if (max_lateness == -1)
2677     goto no_drop;
2678
2679   /* only check for buffers */
2680   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2681     goto not_buffer;
2682
2683   /* can't do check if we don't have a timestamp */
2684   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (rstart)))
2685     goto no_timestamp;
2686
2687   /* we can add a valid stop time */
2688   if (GST_CLOCK_TIME_IS_VALID (rstop))
2689     max_lateness += rstop;
2690   else {
2691     max_lateness += rstart;
2692     /* no stop time, use avg frame diff */
2693     if (priv->avg_in_diff != -1)
2694       max_lateness += priv->avg_in_diff;
2695   }
2696
2697   /* if the jitter bigger than duration and lateness we are too late */
2698   if ((late = rstart + jitter > max_lateness)) {
2699     GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2700         "buffer is too late %" GST_TIME_FORMAT
2701         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (rstart + jitter),
2702         GST_TIME_ARGS (max_lateness));
2703     /* !!emergency!!, if we did not receive anything valid for more than a
2704      * second, render it anyway so the user sees something */
2705     if (GST_CLOCK_TIME_IS_VALID (priv->last_render_time) &&
2706         rstart - priv->last_render_time > GST_SECOND) {
2707       late = FALSE;
2708       GST_ELEMENT_WARNING (basesink, CORE, CLOCK,
2709           (_("A lot of buffers are being dropped.")),
2710           ("There may be a timestamping problem, or this computer is too slow."));
2711       GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2712           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
2713           GST_TIME_ARGS (priv->last_render_time));
2714     }
2715   }
2716
2717 done:
2718   if (!late || !GST_CLOCK_TIME_IS_VALID (priv->last_render_time)) {
2719     priv->last_render_time = rstart;
2720     /* the next allowed input timestamp */
2721     if (priv->throttle_time > 0)
2722       priv->earliest_in_time = rstart + priv->throttle_time;
2723   }
2724   return late;
2725
2726   /* all is fine */
2727 in_time:
2728   {
2729     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
2730     goto done;
2731   }
2732 no_drop:
2733   {
2734     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
2735     goto done;
2736   }
2737 not_buffer:
2738   {
2739     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
2740     return FALSE;
2741   }
2742 no_timestamp:
2743   {
2744     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
2745     return FALSE;
2746   }
2747 }
2748
2749 /* called before and after calling the render vmethod. It keeps track of how
2750  * much time was spent in the render method and is used to check if we are
2751  * flooded */
2752 static void
2753 gst_base_sink_do_render_stats (GstBaseSink * basesink, gboolean start)
2754 {
2755   GstBaseSinkPrivate *priv;
2756
2757   priv = basesink->priv;
2758
2759   if (start) {
2760     priv->start = gst_util_get_timestamp ();
2761   } else {
2762     GstClockTime elapsed;
2763
2764     priv->stop = gst_util_get_timestamp ();
2765
2766     elapsed = GST_CLOCK_DIFF (priv->start, priv->stop);
2767
2768     if (!GST_CLOCK_TIME_IS_VALID (priv->avg_render))
2769       priv->avg_render = elapsed;
2770     else
2771       priv->avg_render = UPDATE_RUNNING_AVG (priv->avg_render, elapsed);
2772
2773     GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2774         "avg_render: %" GST_TIME_FORMAT, GST_TIME_ARGS (priv->avg_render));
2775   }
2776 }
2777
2778 /* with STREAM_LOCK, PREROLL_LOCK,
2779  *
2780  * Synchronize the object on the clock and then render it.
2781  *
2782  * takes ownership of obj.
2783  */
2784 static GstFlowReturn
2785 gst_base_sink_render_object (GstBaseSink * basesink, GstPad * pad,
2786     guint8 obj_type, gpointer obj)
2787 {
2788   GstFlowReturn ret;
2789   GstBaseSinkClass *bclass;
2790   gboolean late, step_end;
2791   gpointer sync_obj;
2792   GstBaseSinkPrivate *priv;
2793
2794   priv = basesink->priv;
2795
2796   if (OBJ_IS_BUFFERLIST (obj_type)) {
2797     /*
2798      * If buffer list, use the first group buffer within the list
2799      * for syncing
2800      */
2801     sync_obj = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0);
2802     g_assert (NULL != sync_obj);
2803   } else {
2804     sync_obj = obj;
2805   }
2806
2807 again:
2808   late = FALSE;
2809   step_end = FALSE;
2810
2811   /* synchronize this object, non syncable objects return OK
2812    * immediately. */
2813   ret =
2814       gst_base_sink_do_sync (basesink, pad, sync_obj, &late, &step_end,
2815       obj_type);
2816   if (G_UNLIKELY (ret != GST_FLOW_OK))
2817     goto sync_failed;
2818
2819   /* and now render, event or buffer/buffer list. */
2820   if (G_LIKELY (OBJ_IS_BUFFERFULL (obj_type))) {
2821     /* drop late buffers unconditionally, let's hope it's unlikely */
2822     if (G_UNLIKELY (late))
2823       goto dropped;
2824
2825     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2826
2827     if (G_LIKELY ((OBJ_IS_BUFFERLIST (obj_type) && bclass->render_list) ||
2828             (!OBJ_IS_BUFFERLIST (obj_type) && bclass->render))) {
2829       gint do_qos;
2830
2831       /* read once, to get same value before and after */
2832       do_qos = g_atomic_int_get (&priv->qos_enabled);
2833
2834       GST_DEBUG_OBJECT (basesink, "rendering object %p", obj);
2835
2836       /* record rendering time for QoS and stats */
2837       if (do_qos)
2838         gst_base_sink_do_render_stats (basesink, TRUE);
2839
2840       if (!OBJ_IS_BUFFERLIST (obj_type)) {
2841         GstBuffer *buf;
2842
2843         /* For buffer lists do not set last buffer. Creating buffer
2844          * with meaningful data can be done only with memcpy which will
2845          * significantly affect performance */
2846         buf = GST_BUFFER_CAST (obj);
2847         gst_base_sink_set_last_buffer (basesink, buf);
2848
2849         ret = bclass->render (basesink, buf);
2850       } else {
2851         GstBufferList *buflist;
2852
2853         buflist = GST_BUFFER_LIST_CAST (obj);
2854
2855         ret = bclass->render_list (basesink, buflist);
2856       }
2857
2858       if (do_qos)
2859         gst_base_sink_do_render_stats (basesink, FALSE);
2860
2861       if (ret == GST_FLOW_STEP)
2862         goto again;
2863
2864       if (G_UNLIKELY (basesink->flushing))
2865         goto flushing;
2866
2867       priv->rendered++;
2868     }
2869   } else if (G_LIKELY (OBJ_IS_EVENT (obj_type))) {
2870     GstEvent *event = GST_EVENT_CAST (obj);
2871     gboolean event_res = TRUE;
2872     GstEventType type;
2873
2874     bclass = GST_BASE_SINK_GET_CLASS (basesink);
2875
2876     type = GST_EVENT_TYPE (event);
2877
2878     GST_DEBUG_OBJECT (basesink, "rendering event %p, type %s", obj,
2879         gst_event_type_get_name (type));
2880
2881     if (bclass->event)
2882       event_res = bclass->event (basesink, event);
2883
2884     /* when we get here we could be flushing again when the event handler calls
2885      * _wait_eos(). We have to ignore this object in that case. */
2886     if (G_UNLIKELY (basesink->flushing))
2887       goto flushing;
2888
2889     if (G_LIKELY (event_res)) {
2890       guint32 seqnum;
2891
2892       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
2893       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
2894
2895       switch (type) {
2896         case GST_EVENT_EOS:
2897         {
2898           GstMessage *message;
2899
2900           /* the EOS event is completely handled so we mark
2901            * ourselves as being in the EOS state. eos is also
2902            * protected by the object lock so we can read it when
2903            * answering the POSITION query. */
2904           GST_OBJECT_LOCK (basesink);
2905           basesink->eos = TRUE;
2906           GST_OBJECT_UNLOCK (basesink);
2907
2908           /* ok, now we can post the message */
2909           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
2910
2911           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
2912           gst_message_set_seqnum (message, seqnum);
2913           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
2914           break;
2915         }
2916         case GST_EVENT_SEGMENT:
2917           /* configure the segment */
2918           gst_base_sink_configure_segment (basesink, pad, event,
2919               &basesink->segment);
2920           break;
2921         case GST_EVENT_TAG:
2922         {
2923           GstTagList *taglist;
2924
2925           gst_event_parse_tag (event, &taglist);
2926
2927           gst_element_post_message (GST_ELEMENT_CAST (basesink),
2928               gst_message_new_tag (GST_OBJECT_CAST (basesink),
2929                   gst_tag_list_copy (taglist)));
2930           break;
2931         }
2932         case GST_EVENT_SINK_MESSAGE:
2933         {
2934           GstMessage *msg = NULL;
2935
2936           gst_event_parse_sink_message (event, &msg);
2937
2938           if (msg)
2939             gst_element_post_message (GST_ELEMENT_CAST (basesink), msg);
2940         }
2941         default:
2942           break;
2943       }
2944     }
2945   } else {
2946     g_return_val_if_reached (GST_FLOW_ERROR);
2947   }
2948
2949 done:
2950   if (step_end) {
2951     /* the step ended, check if we need to activate a new step */
2952     GST_DEBUG_OBJECT (basesink, "step ended");
2953     stop_stepping (basesink, &basesink->segment, &priv->current_step,
2954         priv->current_rstart, priv->current_rstop, basesink->eos);
2955     goto again;
2956   }
2957
2958   gst_base_sink_perform_qos (basesink, late);
2959
2960   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
2961   gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
2962   return ret;
2963
2964   /* ERRORS */
2965 sync_failed:
2966   {
2967     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
2968     goto done;
2969   }
2970 dropped:
2971   {
2972     priv->dropped++;
2973     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
2974
2975     if (g_atomic_int_get (&priv->qos_enabled)) {
2976       GstMessage *qos_msg;
2977       GstClockTime timestamp, duration;
2978
2979       timestamp = GST_BUFFER_TIMESTAMP (GST_BUFFER_CAST (sync_obj));
2980       duration = GST_BUFFER_DURATION (GST_BUFFER_CAST (sync_obj));
2981
2982       GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2983           "qos: dropped buffer rt %" GST_TIME_FORMAT ", st %" GST_TIME_FORMAT
2984           ", ts %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
2985           GST_TIME_ARGS (priv->current_rstart),
2986           GST_TIME_ARGS (priv->current_sstart), GST_TIME_ARGS (timestamp),
2987           GST_TIME_ARGS (duration));
2988       GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2989           "qos: rendered %" G_GUINT64_FORMAT ", dropped %" G_GUINT64_FORMAT,
2990           priv->rendered, priv->dropped);
2991
2992       qos_msg =
2993           gst_message_new_qos (GST_OBJECT_CAST (basesink), basesink->sync,
2994           priv->current_rstart, priv->current_sstart, timestamp, duration);
2995       gst_message_set_qos_values (qos_msg, priv->current_jitter, priv->avg_rate,
2996           1000000);
2997       gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS, priv->rendered,
2998           priv->dropped);
2999       gst_element_post_message (GST_ELEMENT_CAST (basesink), qos_msg);
3000     }
3001     goto done;
3002   }
3003 flushing:
3004   {
3005     GST_DEBUG_OBJECT (basesink, "we are flushing, ignore object");
3006     gst_mini_object_unref (obj);
3007     return GST_FLOW_WRONG_STATE;
3008   }
3009 }
3010
3011 /* with STREAM_LOCK, PREROLL_LOCK
3012  *
3013  * Perform preroll on the given object. For buffers this means
3014  * calling the preroll subclass method.
3015  * If that succeeds, the state will be commited.
3016  *
3017  * function does not take ownership of obj.
3018  */
3019 static GstFlowReturn
3020 gst_base_sink_preroll_object (GstBaseSink * basesink, guint8 obj_type,
3021     GstMiniObject * obj)
3022 {
3023   GstFlowReturn ret;
3024
3025   GST_DEBUG_OBJECT (basesink, "prerolling object %p", obj);
3026
3027   /* if it's a buffer, we need to call the preroll method */
3028   if (G_LIKELY (OBJ_IS_BUFFERFULL (obj_type) && basesink->priv->call_preroll)) {
3029     GstBaseSinkClass *bclass;
3030     GstBuffer *buf;
3031
3032     if (OBJ_IS_BUFFERLIST (obj_type)) {
3033       buf = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0);
3034       g_assert (NULL != buf);
3035     } else {
3036       buf = GST_BUFFER_CAST (obj);
3037     }
3038
3039     GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
3040         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
3041
3042     /*
3043      * For buffer lists do not set last buffer. Creating buffer
3044      * with meaningful data can be done only with memcpy which will
3045      * significantly affect performance
3046      */
3047     if (!OBJ_IS_BUFFERLIST (obj_type)) {
3048       gst_base_sink_set_last_buffer (basesink, buf);
3049     }
3050
3051     bclass = GST_BASE_SINK_GET_CLASS (basesink);
3052     if (bclass->preroll)
3053       if ((ret = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
3054         goto preroll_failed;
3055
3056     basesink->priv->call_preroll = FALSE;
3057   }
3058
3059   /* commit state */
3060   if (G_LIKELY (basesink->playing_async)) {
3061     if (G_UNLIKELY (!gst_base_sink_commit_state (basesink)))
3062       goto stopping;
3063   }
3064
3065   return GST_FLOW_OK;
3066
3067   /* ERRORS */
3068 preroll_failed:
3069   {
3070     GST_DEBUG_OBJECT (basesink, "preroll failed, abort state");
3071     gst_element_abort_state (GST_ELEMENT_CAST (basesink));
3072     return ret;
3073   }
3074 stopping:
3075   {
3076     GST_DEBUG_OBJECT (basesink, "stopping while commiting state");
3077     return GST_FLOW_WRONG_STATE;
3078   }
3079 }
3080
3081 static void
3082 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
3083 {
3084   /* make sure we are not blocked on the clock also clear any pending
3085    * eos state. */
3086   gst_base_sink_set_flushing (basesink, pad, TRUE);
3087
3088   /* we grab the stream lock but that is not needed since setting the
3089    * sink to flushing would make sure no state commit is being done
3090    * anymore */
3091   GST_PAD_STREAM_LOCK (pad);
3092   gst_base_sink_reset_qos (basesink);
3093   /* and we need to commit our state again on the next
3094    * prerolled buffer */
3095   basesink->playing_async = TRUE;
3096   if (basesink->priv->async_enabled) {
3097     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
3098   } else {
3099     /* start time reset in above case as well;
3100      * arranges for a.o. proper position reporting when flushing in PAUSED */
3101     gst_element_set_start_time (GST_ELEMENT_CAST (basesink), 0);
3102     basesink->priv->have_latency = TRUE;
3103   }
3104   gst_base_sink_set_last_buffer (basesink, NULL);
3105   GST_PAD_STREAM_UNLOCK (pad);
3106 }
3107
3108 static void
3109 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad,
3110     gboolean reset_time)
3111 {
3112   /* unset flushing so we can accept new data, this also flushes out any EOS
3113    * event. */
3114   gst_base_sink_set_flushing (basesink, pad, FALSE);
3115
3116   /* for position reporting */
3117   GST_OBJECT_LOCK (basesink);
3118   basesink->priv->current_sstart = GST_CLOCK_TIME_NONE;
3119   basesink->priv->current_sstop = GST_CLOCK_TIME_NONE;
3120   basesink->priv->eos_rtime = GST_CLOCK_TIME_NONE;
3121   basesink->priv->call_preroll = TRUE;
3122   basesink->priv->current_step.valid = FALSE;
3123   basesink->priv->pending_step.valid = FALSE;
3124   if (basesink->pad_mode == GST_PAD_MODE_PUSH) {
3125     /* we need new segment info after the flush. */
3126     basesink->have_newsegment = FALSE;
3127     if (reset_time) {
3128       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
3129       gst_segment_init (&basesink->clip_segment, GST_FORMAT_UNDEFINED);
3130     }
3131   }
3132   basesink->priv->reset_time = reset_time;
3133   GST_OBJECT_UNLOCK (basesink);
3134 }
3135
3136 static gboolean
3137 gst_base_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
3138 {
3139   GstBaseSink *basesink;
3140   gboolean result = TRUE;
3141   GstBaseSinkClass *bclass;
3142
3143   basesink = GST_BASE_SINK (parent);
3144   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3145
3146   GST_DEBUG_OBJECT (basesink, "received event %p %" GST_PTR_FORMAT, event,
3147       event);
3148
3149   switch (GST_EVENT_TYPE (event)) {
3150     case GST_EVENT_EOS:
3151     {
3152       GstFlowReturn ret;
3153
3154       GST_BASE_SINK_PREROLL_LOCK (basesink);
3155       if (G_UNLIKELY (basesink->flushing))
3156         goto flushing;
3157
3158       if (G_UNLIKELY (basesink->priv->received_eos))
3159         goto after_eos;
3160
3161       /* we set the received EOS flag here so that we can use it when testing if
3162        * we are prerolled and to refuse more buffers. */
3163       basesink->priv->received_eos = TRUE;
3164
3165       /* EOS is a prerollable object, we call the unlocked version because it
3166        * does not check the received_eos flag. */
3167       ret = gst_base_sink_render_object (basesink, pad,
3168           _PR_IS_EVENT, GST_MINI_OBJECT_CAST (event));
3169       if (G_UNLIKELY (ret != GST_FLOW_OK))
3170         result = FALSE;
3171
3172       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3173       break;
3174     }
3175     case GST_EVENT_CAPS:
3176     {
3177       GstCaps *caps;
3178
3179       GST_DEBUG_OBJECT (basesink, "caps %p", event);
3180
3181       gst_event_parse_caps (event, &caps);
3182       if (bclass->set_caps)
3183         result = bclass->set_caps (basesink, caps);
3184
3185       if (result) {
3186         GST_OBJECT_LOCK (basesink);
3187         gst_caps_replace (&basesink->priv->caps, caps);
3188         GST_OBJECT_UNLOCK (basesink);
3189       }
3190       gst_event_unref (event);
3191       break;
3192     }
3193     case GST_EVENT_SEGMENT:
3194     {
3195       GstFlowReturn ret;
3196
3197       GST_DEBUG_OBJECT (basesink, "segment %p", event);
3198
3199       GST_BASE_SINK_PREROLL_LOCK (basesink);
3200       if (G_UNLIKELY (basesink->flushing))
3201         goto flushing;
3202
3203       if (G_UNLIKELY (basesink->priv->received_eos))
3204         goto after_eos;
3205
3206       /* the new segment is a non prerollable item and does not block anything,
3207        * we need to configure the current clipping segment and insert the event
3208        * in the queue to serialize it with the buffers for rendering. */
3209       gst_base_sink_configure_segment (basesink, pad, event,
3210           &basesink->clip_segment);
3211
3212       ret =
3213           gst_base_sink_render_object (basesink, pad,
3214           _PR_IS_EVENT, GST_MINI_OBJECT_CAST (event));
3215       if (G_UNLIKELY (ret != GST_FLOW_OK))
3216         result = FALSE;
3217       else {
3218         GST_OBJECT_LOCK (basesink);
3219         basesink->have_newsegment = TRUE;
3220         GST_OBJECT_UNLOCK (basesink);
3221       }
3222       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3223       break;
3224     }
3225     case GST_EVENT_FLUSH_START:
3226       if (bclass->event)
3227         bclass->event (basesink, event);
3228
3229       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
3230
3231       gst_base_sink_flush_start (basesink, pad);
3232
3233       gst_event_unref (event);
3234       break;
3235     case GST_EVENT_FLUSH_STOP:
3236     {
3237       gboolean reset_time;
3238
3239       if (bclass->event)
3240         bclass->event (basesink, event);
3241
3242       gst_event_parse_flush_stop (event, &reset_time);
3243       GST_DEBUG_OBJECT (basesink, "flush-stop %p, reset_time: %d", event,
3244           reset_time);
3245
3246       gst_base_sink_flush_stop (basesink, pad, reset_time);
3247
3248       gst_event_unref (event);
3249       break;
3250     }
3251     default:
3252       /* other events are sent to queue or subclass depending on if they
3253        * are serialized. */
3254       if (GST_EVENT_IS_SERIALIZED (event)) {
3255         GstFlowReturn ret;
3256
3257         GST_BASE_SINK_PREROLL_LOCK (basesink);
3258         if (G_UNLIKELY (basesink->flushing))
3259           goto flushing;
3260
3261         if (G_UNLIKELY (basesink->priv->received_eos))
3262           goto after_eos;
3263
3264         ret = gst_base_sink_render_object (basesink, pad, _PR_IS_EVENT,
3265             GST_MINI_OBJECT_CAST (event));
3266         if (G_UNLIKELY (ret != GST_FLOW_OK))
3267           result = FALSE;
3268
3269         GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3270       } else {
3271         if (bclass->event)
3272           bclass->event (basesink, event);
3273         gst_event_unref (event);
3274       }
3275       break;
3276   }
3277 done:
3278   return result;
3279
3280   /* ERRORS */
3281 flushing:
3282   {
3283     GST_DEBUG_OBJECT (basesink, "we are flushing");
3284     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3285     result = FALSE;
3286     gst_event_unref (event);
3287     goto done;
3288   }
3289
3290 after_eos:
3291   {
3292     GST_DEBUG_OBJECT (basesink, "Event received after EOS, dropping");
3293     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3294     result = FALSE;
3295     gst_event_unref (event);
3296     goto done;
3297   }
3298 }
3299
3300 /* default implementation to calculate the start and end
3301  * timestamps on a buffer, subclasses can override
3302  */
3303 static void
3304 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
3305     GstClockTime * start, GstClockTime * end)
3306 {
3307   GstClockTime timestamp, duration;
3308
3309   timestamp = GST_BUFFER_TIMESTAMP (buffer);
3310   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
3311
3312     /* get duration to calculate end time */
3313     duration = GST_BUFFER_DURATION (buffer);
3314     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3315       *end = timestamp + duration;
3316     }
3317     *start = timestamp;
3318   }
3319 }
3320
3321 /* must be called with PREROLL_LOCK */
3322 static gboolean
3323 gst_base_sink_needs_preroll (GstBaseSink * basesink)
3324 {
3325   gboolean is_prerolled, res;
3326
3327   /* we have 2 cases where the PREROLL_LOCK is released:
3328    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
3329    *  2) we are syncing on the clock
3330    */
3331   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
3332   res = !is_prerolled;
3333
3334   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
3335       basesink->have_preroll, basesink->priv->received_eos, res);
3336
3337   return res;
3338 }
3339
3340 /* with STREAM_LOCK, PREROLL_LOCK
3341  *
3342  * Takes a buffer and compare the timestamps with the last segment.
3343  * If the buffer falls outside of the segment boundaries, drop it.
3344  * Else queue the buffer for preroll and rendering.
3345  *
3346  * This function takes ownership of the buffer.
3347  */
3348 static GstFlowReturn
3349 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
3350     guint8 obj_type, gpointer obj)
3351 {
3352   GstBaseSinkClass *bclass;
3353   GstFlowReturn result;
3354   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
3355   GstSegment *clip_segment;
3356   GstBuffer *time_buf;
3357
3358   if (G_UNLIKELY (basesink->flushing))
3359     goto flushing;
3360
3361   if (G_UNLIKELY (basesink->priv->received_eos))
3362     goto was_eos;
3363
3364   if (OBJ_IS_BUFFERLIST (obj_type)) {
3365     time_buf = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0);
3366     g_assert (NULL != time_buf);
3367   } else {
3368     time_buf = GST_BUFFER_CAST (obj);
3369   }
3370
3371   /* for code clarity */
3372   clip_segment = &basesink->clip_segment;
3373
3374   if (G_UNLIKELY (!basesink->have_newsegment)) {
3375     gboolean sync;
3376
3377     sync = gst_base_sink_get_sync (basesink);
3378     if (sync) {
3379       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
3380           (_("Internal data flow problem.")),
3381           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
3382     }
3383
3384     /* this means this sink will assume timestamps start from 0 */
3385     GST_OBJECT_LOCK (basesink);
3386     clip_segment->start = 0;
3387     clip_segment->stop = -1;
3388     basesink->segment.start = 0;
3389     basesink->segment.stop = -1;
3390     basesink->have_newsegment = TRUE;
3391     GST_OBJECT_UNLOCK (basesink);
3392   }
3393
3394   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3395
3396   /* check if the buffer needs to be dropped, we first ask the subclass for the
3397    * start and end */
3398   if (bclass->get_times)
3399     bclass->get_times (basesink, time_buf, &start, &end);
3400
3401   if (!GST_CLOCK_TIME_IS_VALID (start)) {
3402     /* if the subclass does not want sync, we use our own values so that we at
3403      * least clip the buffer to the segment */
3404     gst_base_sink_get_times (basesink, time_buf, &start, &end);
3405   }
3406
3407   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
3408       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
3409
3410   /* a dropped buffer does not participate in anything */
3411   if (GST_CLOCK_TIME_IS_VALID (start) &&
3412       (clip_segment->format == GST_FORMAT_TIME)) {
3413     if (G_UNLIKELY (!gst_segment_clip (clip_segment,
3414                 GST_FORMAT_TIME, start, end, NULL, NULL)))
3415       goto out_of_segment;
3416   }
3417
3418   /* now we can process the buffer in the queue, this function takes ownership
3419    * of the buffer */
3420   result = gst_base_sink_render_object (basesink, pad, obj_type, obj);
3421   return result;
3422
3423   /* ERRORS */
3424 flushing:
3425   {
3426     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3427     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3428     return GST_FLOW_WRONG_STATE;
3429   }
3430 was_eos:
3431   {
3432     GST_DEBUG_OBJECT (basesink, "we are EOS, dropping object, return EOS");
3433     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3434     return GST_FLOW_EOS;
3435   }
3436 out_of_segment:
3437   {
3438     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
3439     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3440     return GST_FLOW_OK;
3441   }
3442 }
3443
3444 /* with STREAM_LOCK
3445  */
3446 static GstFlowReturn
3447 gst_base_sink_chain_main (GstBaseSink * basesink, GstPad * pad,
3448     guint8 obj_type, gpointer obj)
3449 {
3450   GstFlowReturn result;
3451
3452   if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PUSH))
3453     goto wrong_mode;
3454
3455   GST_BASE_SINK_PREROLL_LOCK (basesink);
3456   result = gst_base_sink_chain_unlocked (basesink, pad, obj_type, obj);
3457   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3458
3459 done:
3460   return result;
3461
3462   /* ERRORS */
3463 wrong_mode:
3464   {
3465     GST_OBJECT_LOCK (pad);
3466     GST_WARNING_OBJECT (basesink,
3467         "Push on pad %s:%s, but it was not activated in push mode",
3468         GST_DEBUG_PAD_NAME (pad));
3469     GST_OBJECT_UNLOCK (pad);
3470     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3471     /* we don't post an error message this will signal to the peer
3472      * pushing that EOS is reached. */
3473     result = GST_FLOW_EOS;
3474     goto done;
3475   }
3476 }
3477
3478 static GstFlowReturn
3479 gst_base_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
3480 {
3481   GstBaseSink *basesink;
3482
3483   basesink = GST_BASE_SINK (parent);
3484
3485   return gst_base_sink_chain_main (basesink, pad, _PR_IS_BUFFER, buf);
3486 }
3487
3488 static GstFlowReturn
3489 gst_base_sink_chain_list (GstPad * pad, GstObject * parent,
3490     GstBufferList * list)
3491 {
3492   GstBaseSink *basesink;
3493   GstBaseSinkClass *bclass;
3494   GstFlowReturn result;
3495
3496   basesink = GST_BASE_SINK (parent);
3497   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3498
3499   if (G_LIKELY (bclass->render_list)) {
3500     result = gst_base_sink_chain_main (basesink, pad, _PR_IS_BUFFERLIST, list);
3501   } else {
3502     guint i, len;
3503     GstBuffer *buffer;
3504
3505     GST_INFO_OBJECT (pad, "chaining each group in list as a merged buffer");
3506
3507     len = gst_buffer_list_length (list);
3508
3509     result = GST_FLOW_OK;
3510     for (i = 0; i < len; i++) {
3511       buffer = gst_buffer_list_get (list, 0);
3512       result = gst_base_sink_chain_main (basesink, pad, _PR_IS_BUFFER,
3513           gst_buffer_ref (buffer));
3514       if (result != GST_FLOW_OK)
3515         break;
3516     }
3517     gst_buffer_list_unref (list);
3518   }
3519   return result;
3520 }
3521
3522
3523 static gboolean
3524 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
3525 {
3526   gboolean res = TRUE;
3527
3528   /* update our offset if the start/stop position was updated */
3529   if (segment->format == GST_FORMAT_BYTES) {
3530     segment->time = segment->start;
3531   } else if (segment->start == 0) {
3532     /* seek to start, we can implement a default for this. */
3533     segment->time = 0;
3534   } else {
3535     res = FALSE;
3536     GST_INFO_OBJECT (sink, "Can't do a default seek");
3537   }
3538
3539   return res;
3540 }
3541
3542 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
3543
3544 static gboolean
3545 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3546     GstEvent * event, GstSegment * segment)
3547 {
3548   /* By default, we try one of 2 things:
3549    *   - For absolute seek positions, convert the requested position to our
3550    *     configured processing format and place it in the output segment \
3551    *   - For relative seek positions, convert our current (input) values to the
3552    *     seek format, adjust by the relative seek offset and then convert back to
3553    *     the processing format
3554    */
3555   GstSeekType cur_type, stop_type;
3556   gint64 cur, stop;
3557   GstSeekFlags flags;
3558   GstFormat seek_format;
3559   gdouble rate;
3560   gboolean update;
3561   gboolean res = TRUE;
3562
3563   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3564       &cur_type, &cur, &stop_type, &stop);
3565
3566   if (seek_format == segment->format) {
3567     gst_segment_do_seek (segment, rate, seek_format, flags,
3568         cur_type, cur, stop_type, stop, &update);
3569     return TRUE;
3570   }
3571
3572   if (cur_type != GST_SEEK_TYPE_NONE) {
3573     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3574     res =
3575         gst_pad_query_convert (sink->sinkpad, seek_format, cur, segment->format,
3576         &cur);
3577     cur_type = GST_SEEK_TYPE_SET;
3578   }
3579
3580   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3581     /* FIXME: Handle seek_cur & seek_end by converting the input segment vals */
3582     res =
3583         gst_pad_query_convert (sink->sinkpad, seek_format, stop,
3584         segment->format, &stop);
3585     stop_type = GST_SEEK_TYPE_SET;
3586   }
3587
3588   /* And finally, configure our output segment in the desired format */
3589   gst_segment_do_seek (segment, rate, segment->format, flags, cur_type, cur,
3590       stop_type, stop, &update);
3591
3592   if (!res)
3593     goto no_format;
3594
3595   return res;
3596
3597 no_format:
3598   {
3599     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3600     return FALSE;
3601   }
3602 }
3603
3604 /* perform a seek, only executed in pull mode */
3605 static gboolean
3606 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3607 {
3608   gboolean flush;
3609   gdouble rate;
3610   GstFormat seek_format, dest_format;
3611   GstSeekFlags flags;
3612   GstSeekType cur_type, stop_type;
3613   gboolean seekseg_configured = FALSE;
3614   gint64 cur, stop;
3615   gboolean update, res = TRUE;
3616   GstSegment seeksegment;
3617
3618   dest_format = sink->segment.format;
3619
3620   if (event) {
3621     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3622     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3623         &cur_type, &cur, &stop_type, &stop);
3624
3625     flush = flags & GST_SEEK_FLAG_FLUSH;
3626   } else {
3627     GST_DEBUG_OBJECT (sink, "performing seek without event");
3628     flush = FALSE;
3629   }
3630
3631   if (flush) {
3632     GST_DEBUG_OBJECT (sink, "flushing upstream");
3633     gst_pad_push_event (pad, gst_event_new_flush_start ());
3634     gst_base_sink_flush_start (sink, pad);
3635   } else {
3636     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3637   }
3638
3639   GST_PAD_STREAM_LOCK (pad);
3640
3641   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3642    * copy the current segment info into the temp segment that we can actually
3643    * attempt the seek with. We only update the real segment if the seek succeeds. */
3644   if (!seekseg_configured) {
3645     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3646
3647     /* now configure the final seek segment */
3648     if (event) {
3649       if (sink->segment.format != seek_format) {
3650         /* OK, here's where we give the subclass a chance to convert the relative
3651          * seek into an absolute one in the processing format. We set up any
3652          * absolute seek above, before taking the stream lock. */
3653         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3654                 &seeksegment)) {
3655           GST_DEBUG_OBJECT (sink,
3656               "Preparing the seek failed after flushing. " "Aborting seek");
3657           res = FALSE;
3658         }
3659       } else {
3660         /* The seek format matches our processing format, no need to ask the
3661          * the subclass to configure the segment. */
3662         gst_segment_do_seek (&seeksegment, rate, seek_format, flags,
3663             cur_type, cur, stop_type, stop, &update);
3664       }
3665     }
3666     /* Else, no seek event passed, so we're just (re)starting the
3667        current segment. */
3668   }
3669
3670   if (res) {
3671     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3672         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3673         seeksegment.start, seeksegment.stop, seeksegment.position);
3674
3675     /* do the seek, segment.position contains the new position. */
3676     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3677   }
3678
3679
3680   if (flush) {
3681     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3682     gst_pad_push_event (pad, gst_event_new_flush_stop (TRUE));
3683     gst_base_sink_flush_stop (sink, pad, TRUE);
3684   } else if (res && sink->running) {
3685     /* we are running the current segment and doing a non-flushing seek,
3686      * close the segment first based on the position. */
3687     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3688         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.position);
3689   }
3690
3691   /* The subclass must have converted the segment to the processing format
3692    * by now */
3693   if (res && seeksegment.format != dest_format) {
3694     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3695         "in the correct format. Aborting seek.");
3696     res = FALSE;
3697   }
3698
3699   /* if successful seek, we update our real segment and push
3700    * out the new segment. */
3701   if (res) {
3702     gst_segment_copy_into (&seeksegment, &sink->segment);
3703
3704     if (sink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3705       gst_element_post_message (GST_ELEMENT (sink),
3706           gst_message_new_segment_start (GST_OBJECT (sink),
3707               sink->segment.format, sink->segment.position));
3708     }
3709   }
3710
3711   sink->priv->discont = TRUE;
3712   sink->running = TRUE;
3713
3714   GST_PAD_STREAM_UNLOCK (pad);
3715
3716   return res;
3717 }
3718
3719 static void
3720 set_step_info (GstBaseSink * sink, GstStepInfo * current, GstStepInfo * pending,
3721     guint seqnum, GstFormat format, guint64 amount, gdouble rate,
3722     gboolean flush, gboolean intermediate)
3723 {
3724   GST_OBJECT_LOCK (sink);
3725   pending->seqnum = seqnum;
3726   pending->format = format;
3727   pending->amount = amount;
3728   pending->position = 0;
3729   pending->rate = rate;
3730   pending->flush = flush;
3731   pending->intermediate = intermediate;
3732   pending->valid = TRUE;
3733   /* flush invalidates the current stepping segment */
3734   if (flush)
3735     current->valid = FALSE;
3736   GST_OBJECT_UNLOCK (sink);
3737 }
3738
3739 static gboolean
3740 gst_base_sink_perform_step (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3741 {
3742   GstBaseSinkPrivate *priv;
3743   GstBaseSinkClass *bclass;
3744   gboolean flush, intermediate;
3745   gdouble rate;
3746   GstFormat format;
3747   guint64 amount;
3748   guint seqnum;
3749   GstStepInfo *pending, *current;
3750   GstMessage *message;
3751
3752   bclass = GST_BASE_SINK_GET_CLASS (sink);
3753   priv = sink->priv;
3754
3755   GST_DEBUG_OBJECT (sink, "performing step with event %p", event);
3756
3757   gst_event_parse_step (event, &format, &amount, &rate, &flush, &intermediate);
3758   seqnum = gst_event_get_seqnum (event);
3759
3760   pending = &priv->pending_step;
3761   current = &priv->current_step;
3762
3763   /* post message first */
3764   message = gst_message_new_step_start (GST_OBJECT (sink), FALSE, format,
3765       amount, rate, flush, intermediate);
3766   gst_message_set_seqnum (message, seqnum);
3767   gst_element_post_message (GST_ELEMENT (sink), message);
3768
3769   if (flush) {
3770     /* we need to call ::unlock before locking PREROLL_LOCK
3771      * since we lock it before going into ::render */
3772     if (bclass->unlock)
3773       bclass->unlock (sink);
3774
3775     GST_BASE_SINK_PREROLL_LOCK (sink);
3776     /* now that we have the PREROLL lock, clear our unlock request */
3777     if (bclass->unlock_stop)
3778       bclass->unlock_stop (sink);
3779
3780     /* update the stepinfo and make it valid */
3781     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
3782         intermediate);
3783
3784     if (sink->priv->async_enabled) {
3785       /* and we need to commit our state again on the next
3786        * prerolled buffer */
3787       sink->playing_async = TRUE;
3788       priv->pending_step.need_preroll = TRUE;
3789       sink->need_preroll = FALSE;
3790       gst_element_lost_state (GST_ELEMENT_CAST (sink));
3791     } else {
3792       sink->priv->have_latency = TRUE;
3793       sink->need_preroll = FALSE;
3794     }
3795     priv->current_sstart = GST_CLOCK_TIME_NONE;
3796     priv->current_sstop = GST_CLOCK_TIME_NONE;
3797     priv->eos_rtime = GST_CLOCK_TIME_NONE;
3798     priv->call_preroll = TRUE;
3799     gst_base_sink_set_last_buffer (sink, NULL);
3800     gst_base_sink_reset_qos (sink);
3801
3802     if (sink->clock_id) {
3803       gst_clock_id_unschedule (sink->clock_id);
3804     }
3805
3806     if (sink->have_preroll) {
3807       GST_DEBUG_OBJECT (sink, "signal waiter");
3808       priv->step_unlock = TRUE;
3809       GST_BASE_SINK_PREROLL_SIGNAL (sink);
3810     }
3811     GST_BASE_SINK_PREROLL_UNLOCK (sink);
3812   } else {
3813     /* update the stepinfo and make it valid */
3814     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
3815         intermediate);
3816   }
3817
3818   return TRUE;
3819 }
3820
3821 /* with STREAM_LOCK
3822  */
3823 static void
3824 gst_base_sink_loop (GstPad * pad)
3825 {
3826   GstObject *parent;
3827   GstBaseSink *basesink;
3828   GstBuffer *buf = NULL;
3829   GstFlowReturn result;
3830   guint blocksize;
3831   guint64 offset;
3832
3833   parent = GST_OBJECT_PARENT (pad);
3834   basesink = GST_BASE_SINK (parent);
3835
3836   g_assert (basesink->pad_mode == GST_PAD_MODE_PULL);
3837
3838   if ((blocksize = basesink->priv->blocksize) == 0)
3839     blocksize = -1;
3840
3841   offset = basesink->segment.position;
3842
3843   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
3844       offset, blocksize);
3845
3846   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
3847   if (G_UNLIKELY (result != GST_FLOW_OK))
3848     goto paused;
3849
3850   if (G_UNLIKELY (buf == NULL))
3851     goto no_buffer;
3852
3853   offset += gst_buffer_get_size (buf);
3854
3855   basesink->segment.position = offset;
3856
3857   GST_BASE_SINK_PREROLL_LOCK (basesink);
3858   result = gst_base_sink_chain_unlocked (basesink, pad, _PR_IS_BUFFER, buf);
3859   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3860   if (G_UNLIKELY (result != GST_FLOW_OK))
3861     goto paused;
3862
3863   return;
3864
3865   /* ERRORS */
3866 paused:
3867   {
3868     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
3869         gst_flow_get_name (result));
3870     gst_pad_pause_task (pad);
3871     if (result == GST_FLOW_EOS) {
3872       /* perform EOS logic */
3873       if (basesink->segment.flags & GST_SEEK_FLAG_SEGMENT) {
3874         gst_element_post_message (GST_ELEMENT_CAST (basesink),
3875             gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
3876                 basesink->segment.format, basesink->segment.position));
3877       } else {
3878         gst_base_sink_event (pad, parent, gst_event_new_eos ());
3879       }
3880     } else if (result == GST_FLOW_NOT_LINKED || result <= GST_FLOW_EOS) {
3881       /* for fatal errors we post an error message, post the error
3882        * first so the app knows about the error first. 
3883        * wrong-state is not a fatal error because it happens due to
3884        * flushing and posting an error message in that case is the
3885        * wrong thing to do, e.g. when basesrc is doing a flushing
3886        * seek. */
3887       GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3888           (_("Internal data stream error.")),
3889           ("stream stopped, reason %s", gst_flow_get_name (result)));
3890       gst_base_sink_event (pad, parent, gst_event_new_eos ());
3891     }
3892     return;
3893   }
3894 no_buffer:
3895   {
3896     GST_LOG_OBJECT (basesink, "no buffer, pausing");
3897     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
3898         (_("Internal data flow error.")), ("element returned NULL buffer"));
3899     result = GST_FLOW_ERROR;
3900     goto paused;
3901   }
3902 }
3903
3904 static gboolean
3905 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
3906     gboolean flushing)
3907 {
3908   GstBaseSinkClass *bclass;
3909
3910   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3911
3912   if (flushing) {
3913     /* unlock any subclasses, we need to do this before grabbing the
3914      * PREROLL_LOCK since we hold this lock before going into ::render. */
3915     if (bclass->unlock)
3916       bclass->unlock (basesink);
3917   }
3918
3919   GST_BASE_SINK_PREROLL_LOCK (basesink);
3920   basesink->flushing = flushing;
3921   if (flushing) {
3922     /* step 1, now that we have the PREROLL lock, clear our unlock request */
3923     if (bclass->unlock_stop)
3924       bclass->unlock_stop (basesink);
3925
3926     /* set need_preroll before we unblock the clock. If the clock is unblocked
3927      * before timing out, we can reuse the buffer for preroll. */
3928     basesink->need_preroll = TRUE;
3929
3930     /* step 2, unblock clock sync (if any) or any other blocking thing */
3931     if (basesink->clock_id) {
3932       gst_clock_id_unschedule (basesink->clock_id);
3933     }
3934
3935     /* flush out the data thread if it's locked in finish_preroll, this will
3936      * also flush out the EOS state */
3937     GST_DEBUG_OBJECT (basesink,
3938         "flushing out data thread, need preroll to TRUE");
3939
3940     /* we can't have EOS anymore now */
3941     basesink->eos = FALSE;
3942     basesink->priv->received_eos = FALSE;
3943     basesink->have_preroll = FALSE;
3944     basesink->priv->step_unlock = FALSE;
3945     /* can't report latency anymore until we preroll again */
3946     if (basesink->priv->async_enabled) {
3947       GST_OBJECT_LOCK (basesink);
3948       basesink->priv->have_latency = FALSE;
3949       GST_OBJECT_UNLOCK (basesink);
3950     }
3951     /* and signal any waiters now */
3952     GST_BASE_SINK_PREROLL_SIGNAL (basesink);
3953   }
3954   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3955
3956   return TRUE;
3957 }
3958
3959 static gboolean
3960 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
3961 {
3962   gboolean result;
3963
3964   if (active) {
3965     /* start task */
3966     result = gst_pad_start_task (basesink->sinkpad,
3967         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad);
3968   } else {
3969     /* step 2, make sure streaming finishes */
3970     result = gst_pad_stop_task (basesink->sinkpad);
3971   }
3972
3973   return result;
3974 }
3975
3976 static gboolean
3977 gst_base_sink_pad_activate (GstPad * pad, GstObject * parent)
3978 {
3979   gboolean result = FALSE;
3980   GstBaseSink *basesink;
3981   GstQuery *query;
3982   gboolean pull_mode;
3983
3984   basesink = GST_BASE_SINK (parent);
3985
3986   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
3987
3988   gst_base_sink_set_flushing (basesink, pad, FALSE);
3989
3990   /* we need to have the pull mode enabled */
3991   if (!basesink->can_activate_pull) {
3992     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
3993     goto fallback;
3994   }
3995
3996   /* check if downstreams supports pull mode at all */
3997   query = gst_query_new_scheduling ();
3998
3999   if (!gst_pad_peer_query (pad, query)) {
4000     gst_query_unref (query);
4001     GST_DEBUG_OBJECT (basesink, "peer query faild, no pull mode");
4002     goto fallback;
4003   }
4004
4005   /* parse result of the query */
4006   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
4007   gst_query_unref (query);
4008
4009   if (!pull_mode) {
4010     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
4011     goto fallback;
4012   }
4013
4014   /* set the pad mode before starting the task so that it's in the
4015    * correct state for the new thread. also the sink set_caps and get_caps
4016    * function checks this */
4017   basesink->pad_mode = GST_PAD_MODE_PULL;
4018
4019   /* we first try to negotiate a format so that when we try to activate
4020    * downstream, it knows about our format */
4021   if (!gst_base_sink_negotiate_pull (basesink)) {
4022     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
4023     goto fallback;
4024   }
4025
4026   /* ok activate now */
4027   if (!gst_pad_activate_mode (pad, GST_PAD_MODE_PULL, TRUE)) {
4028     /* clear any pending caps */
4029     GST_OBJECT_LOCK (basesink);
4030     gst_caps_replace (&basesink->priv->caps, NULL);
4031     GST_OBJECT_UNLOCK (basesink);
4032     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
4033     goto fallback;
4034   }
4035
4036   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
4037   result = TRUE;
4038   goto done;
4039
4040   /* push mode fallback */
4041 fallback:
4042   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
4043   if ((result = gst_pad_activate_mode (pad, GST_PAD_MODE_PUSH, TRUE))) {
4044     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
4045   }
4046
4047 done:
4048   if (!result) {
4049     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
4050     gst_base_sink_set_flushing (basesink, pad, TRUE);
4051   }
4052
4053   return result;
4054 }
4055
4056 static gboolean
4057 gst_base_sink_pad_activate_push (GstPad * pad, GstObject * parent,
4058     gboolean active)
4059 {
4060   gboolean result;
4061   GstBaseSink *basesink;
4062
4063   basesink = GST_BASE_SINK (parent);
4064
4065   if (active) {
4066     if (!basesink->can_activate_push) {
4067       result = FALSE;
4068       basesink->pad_mode = GST_PAD_MODE_NONE;
4069     } else {
4070       result = TRUE;
4071       basesink->pad_mode = GST_PAD_MODE_PUSH;
4072     }
4073   } else {
4074     if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PUSH)) {
4075       g_warning ("Internal GStreamer activation error!!!");
4076       result = FALSE;
4077     } else {
4078       gst_base_sink_set_flushing (basesink, pad, TRUE);
4079       result = TRUE;
4080       basesink->pad_mode = GST_PAD_MODE_NONE;
4081     }
4082   }
4083
4084   return result;
4085 }
4086
4087 static gboolean
4088 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
4089 {
4090   GstCaps *caps;
4091   gboolean result;
4092
4093   result = FALSE;
4094
4095   /* this returns the intersection between our caps and the peer caps. If there
4096    * is no peer, it returns NULL and we can't operate in pull mode so we can
4097    * fail the negotiation. */
4098   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
4099   if (caps == NULL || gst_caps_is_empty (caps))
4100     goto no_caps_possible;
4101
4102   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
4103
4104   if (gst_caps_is_any (caps)) {
4105     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
4106         "allowing pull()");
4107     /* neither side has template caps in this case, so they are prepared for
4108        pull() without setcaps() */
4109     result = TRUE;
4110   } else {
4111     caps = gst_caps_make_writable (caps);
4112     /* try to fixate */
4113     gst_base_sink_fixate (basesink, caps);
4114     GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
4115
4116     if (gst_caps_is_fixed (caps)) {
4117       if (!gst_pad_send_event (GST_BASE_SINK_PAD (basesink),
4118               gst_event_new_caps (caps)))
4119         goto could_not_set_caps;
4120
4121       result = TRUE;
4122     }
4123   }
4124
4125   gst_caps_unref (caps);
4126
4127   return result;
4128
4129 no_caps_possible:
4130   {
4131     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
4132     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
4133     if (caps)
4134       gst_caps_unref (caps);
4135     return FALSE;
4136   }
4137 could_not_set_caps:
4138   {
4139     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
4140     gst_caps_unref (caps);
4141     return FALSE;
4142   }
4143 }
4144
4145 /* this won't get called until we implement an activate function */
4146 static gboolean
4147 gst_base_sink_pad_activate_pull (GstPad * pad, GstObject * parent,
4148     gboolean active)
4149 {
4150   gboolean result = FALSE;
4151   GstBaseSink *basesink;
4152   GstBaseSinkClass *bclass;
4153
4154   basesink = GST_BASE_SINK (parent);
4155   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4156
4157   if (active) {
4158     gint64 duration;
4159
4160     /* we mark we have a newsegment here because pull based
4161      * mode works just fine without having a newsegment before the
4162      * first buffer */
4163     gst_segment_init (&basesink->segment, GST_FORMAT_BYTES);
4164     gst_segment_init (&basesink->clip_segment, GST_FORMAT_BYTES);
4165     GST_OBJECT_LOCK (basesink);
4166     basesink->have_newsegment = TRUE;
4167     GST_OBJECT_UNLOCK (basesink);
4168
4169     /* get the peer duration in bytes */
4170     result = gst_pad_peer_query_duration (pad, GST_FORMAT_BYTES, &duration);
4171     if (result) {
4172       GST_DEBUG_OBJECT (basesink,
4173           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
4174       basesink->clip_segment.duration = duration;
4175       basesink->segment.duration = duration;
4176     } else {
4177       GST_DEBUG_OBJECT (basesink, "unknown duration");
4178     }
4179
4180     if (bclass->activate_pull)
4181       result = bclass->activate_pull (basesink, TRUE);
4182     else
4183       result = FALSE;
4184
4185     if (!result)
4186       goto activate_failed;
4187
4188   } else {
4189     if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PULL)) {
4190       g_warning ("Internal GStreamer activation error!!!");
4191       result = FALSE;
4192     } else {
4193       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
4194       if (bclass->activate_pull)
4195         result &= bclass->activate_pull (basesink, FALSE);
4196       basesink->pad_mode = GST_PAD_MODE_NONE;
4197     }
4198   }
4199
4200   return result;
4201
4202   /* ERRORS */
4203 activate_failed:
4204   {
4205     /* reset, as starting the thread failed */
4206     basesink->pad_mode = GST_PAD_MODE_NONE;
4207
4208     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
4209     return FALSE;
4210   }
4211 }
4212
4213 static gboolean
4214 gst_base_sink_pad_activate_mode (GstPad * pad, GstObject * parent,
4215     GstPadMode mode, gboolean active)
4216 {
4217   gboolean res;
4218
4219   switch (mode) {
4220     case GST_PAD_MODE_PULL:
4221       res = gst_base_sink_pad_activate_pull (pad, parent, active);
4222       break;
4223     case GST_PAD_MODE_PUSH:
4224       res = gst_base_sink_pad_activate_push (pad, parent, active);
4225       break;
4226     default:
4227       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
4228       res = FALSE;
4229       break;
4230   }
4231   return res;
4232 }
4233
4234 /* send an event to our sinkpad peer. */
4235 static gboolean
4236 gst_base_sink_send_event (GstElement * element, GstEvent * event)
4237 {
4238   GstPad *pad;
4239   GstBaseSink *basesink = GST_BASE_SINK (element);
4240   gboolean forward, result = TRUE;
4241   GstPadMode mode;
4242
4243   GST_OBJECT_LOCK (element);
4244   /* get the pad and the scheduling mode */
4245   pad = gst_object_ref (basesink->sinkpad);
4246   mode = basesink->pad_mode;
4247   GST_OBJECT_UNLOCK (element);
4248
4249   /* only push UPSTREAM events upstream */
4250   forward = GST_EVENT_IS_UPSTREAM (event);
4251
4252   GST_DEBUG_OBJECT (basesink, "handling event %p %" GST_PTR_FORMAT, event,
4253       event);
4254
4255   switch (GST_EVENT_TYPE (event)) {
4256     case GST_EVENT_LATENCY:
4257     {
4258       GstClockTime latency;
4259
4260       gst_event_parse_latency (event, &latency);
4261
4262       /* store the latency. We use this to adjust the running_time before syncing
4263        * it to the clock. */
4264       GST_OBJECT_LOCK (element);
4265       basesink->priv->latency = latency;
4266       if (!basesink->priv->have_latency)
4267         forward = FALSE;
4268       GST_OBJECT_UNLOCK (element);
4269       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
4270           GST_TIME_ARGS (latency));
4271
4272       /* We forward this event so that all elements know about the global pipeline
4273        * latency. This is interesting for an element when it wants to figure out
4274        * when a particular piece of data will be rendered. */
4275       break;
4276     }
4277     case GST_EVENT_SEEK:
4278       /* in pull mode we will execute the seek */
4279       if (mode == GST_PAD_MODE_PULL)
4280         result = gst_base_sink_perform_seek (basesink, pad, event);
4281       break;
4282     case GST_EVENT_STEP:
4283       result = gst_base_sink_perform_step (basesink, pad, event);
4284       forward = FALSE;
4285       break;
4286     default:
4287       break;
4288   }
4289
4290   if (forward) {
4291     result = gst_pad_push_event (pad, event);
4292   } else {
4293     /* not forwarded, unref the event */
4294     gst_event_unref (event);
4295   }
4296
4297   gst_object_unref (pad);
4298
4299   GST_DEBUG_OBJECT (basesink, "handled event %p %" GST_PTR_FORMAT ": %d", event,
4300       event, result);
4301
4302   return result;
4303 }
4304
4305 static gboolean
4306 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
4307     gint64 * cur, gboolean * upstream)
4308 {
4309   GstClock *clock = NULL;
4310   gboolean res = FALSE;
4311   GstFormat oformat;
4312   GstSegment *segment;
4313   GstClockTime now, latency;
4314   GstClockTimeDiff base_time;
4315   gint64 time, base, duration;
4316   gdouble rate;
4317   gint64 last;
4318   gboolean last_seen, with_clock, in_paused;
4319
4320   GST_OBJECT_LOCK (basesink);
4321   /* we can only get the segment when we are not NULL or READY */
4322   if (!basesink->have_newsegment)
4323     goto wrong_state;
4324
4325   in_paused = FALSE;
4326   /* when not in PLAYING or when we're busy with a state change, we
4327    * cannot read from the clock so we report time based on the
4328    * last seen timestamp. */
4329   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
4330       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING) {
4331     in_paused = TRUE;
4332   }
4333
4334   /* we don't use the clip segment in pull mode, when seeking we update the
4335    * main segment directly with the new segment values without it having to be
4336    * activated by the rendering after preroll */
4337   if (basesink->pad_mode == GST_PAD_MODE_PUSH)
4338     segment = &basesink->clip_segment;
4339   else
4340     segment = &basesink->segment;
4341
4342   /* get the format in the segment */
4343   oformat = segment->format;
4344
4345   /* report with last seen position when EOS */
4346   last_seen = basesink->eos;
4347
4348   /* assume we will use the clock for getting the current position */
4349   with_clock = TRUE;
4350   if (basesink->sync == FALSE)
4351     with_clock = FALSE;
4352
4353   /* and we need a clock */
4354   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
4355     with_clock = FALSE;
4356   else
4357     gst_object_ref (clock);
4358
4359   /* mainloop might be querying position when going to playing async,
4360    * while (audio) rendering might be quickly advancing stream position,
4361    * so use clock asap rather than last reported position */
4362   if (in_paused && with_clock && g_atomic_int_get (&basesink->priv->to_playing)) {
4363     GST_DEBUG_OBJECT (basesink, "going to PLAYING, so not PAUSED");
4364     in_paused = FALSE;
4365   }
4366
4367   /* collect all data we need holding the lock */
4368   if (GST_CLOCK_TIME_IS_VALID (segment->time))
4369     time = segment->time;
4370   else
4371     time = 0;
4372
4373   if (GST_CLOCK_TIME_IS_VALID (segment->stop))
4374     duration = segment->stop - segment->start;
4375   else
4376     duration = 0;
4377
4378   base = segment->base;
4379   rate = segment->rate * segment->applied_rate;
4380   latency = basesink->priv->latency;
4381
4382   if (oformat == GST_FORMAT_TIME) {
4383     gint64 start, stop;
4384
4385     start = basesink->priv->current_sstart;
4386     stop = basesink->priv->current_sstop;
4387
4388     if (in_paused) {
4389       /* in paused we use the last position as a lower bound */
4390       if (stop == -1 || segment->rate > 0.0)
4391         last = start;
4392       else
4393         last = stop;
4394     } else {
4395       /* in playing, use last stop time as upper bound */
4396       if (start == -1 || segment->rate > 0.0)
4397         last = stop;
4398       else
4399         last = start;
4400     }
4401   } else {
4402     /* convert last stop to stream time */
4403     last = gst_segment_to_stream_time (segment, oformat, segment->position);
4404   }
4405
4406   if (in_paused) {
4407     /* in paused, use start_time */
4408     base_time = GST_ELEMENT_START_TIME (basesink);
4409     GST_DEBUG_OBJECT (basesink, "in paused, using start time %" GST_TIME_FORMAT,
4410         GST_TIME_ARGS (base_time));
4411   } else if (with_clock) {
4412     /* else use clock when needed */
4413     base_time = GST_ELEMENT_CAST (basesink)->base_time;
4414     GST_DEBUG_OBJECT (basesink, "using clock and base time %" GST_TIME_FORMAT,
4415         GST_TIME_ARGS (base_time));
4416   } else {
4417     /* else, no sync or clock -> no base time */
4418     GST_DEBUG_OBJECT (basesink, "no sync or no clock");
4419     base_time = -1;
4420   }
4421
4422   /* no base_time, we can't calculate running_time, use last seem timestamp to report
4423    * time */
4424   if (base_time == -1)
4425     last_seen = TRUE;
4426
4427   /* need to release the object lock before we can get the time,
4428    * a clock might take the LOCK of the provider, which could be
4429    * a basesink subclass. */
4430   GST_OBJECT_UNLOCK (basesink);
4431
4432   if (last_seen) {
4433     /* in EOS or when no valid stream_time, report the value of last seen
4434      * timestamp */
4435     if (last == -1) {
4436       /* no timestamp, we need to ask upstream */
4437       GST_DEBUG_OBJECT (basesink, "no last seen timestamp, asking upstream");
4438       res = FALSE;
4439       *upstream = TRUE;
4440       goto done;
4441     }
4442     GST_DEBUG_OBJECT (basesink, "using last seen timestamp %" GST_TIME_FORMAT,
4443         GST_TIME_ARGS (last));
4444     *cur = last;
4445   } else {
4446     if (oformat != GST_FORMAT_TIME) {
4447       /* convert base, time and duration to time */
4448       if (!gst_pad_query_convert (basesink->sinkpad, oformat, base,
4449               GST_FORMAT_TIME, &base))
4450         goto convert_failed;
4451       if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration,
4452               GST_FORMAT_TIME, &duration))
4453         goto convert_failed;
4454       if (!gst_pad_query_convert (basesink->sinkpad, oformat, time,
4455               GST_FORMAT_TIME, &time))
4456         goto convert_failed;
4457       if (!gst_pad_query_convert (basesink->sinkpad, oformat, last,
4458               GST_FORMAT_TIME, &last))
4459         goto convert_failed;
4460
4461       /* assume time format from now on */
4462       oformat = GST_FORMAT_TIME;
4463     }
4464
4465     if (!in_paused && with_clock) {
4466       now = gst_clock_get_time (clock);
4467     } else {
4468       now = base_time;
4469       base_time = 0;
4470     }
4471
4472     /* subtract base time and base time from the clock time.
4473      * Make sure we don't go negative. This is the current time in
4474      * the segment which we need to scale with the combined
4475      * rate and applied rate. */
4476     base_time += base;
4477     base_time += latency;
4478     if (GST_CLOCK_DIFF (base_time, now) < 0)
4479       base_time = now;
4480
4481     /* for negative rates we need to count back from the segment
4482      * duration. */
4483     if (rate < 0.0)
4484       time += duration;
4485
4486     *cur = time + gst_guint64_to_gdouble (now - base_time) * rate;
4487
4488     if (in_paused) {
4489       /* never report less than segment values in paused */
4490       if (last != -1)
4491         *cur = MAX (last, *cur);
4492     } else {
4493       /* never report more than last seen position in playing */
4494       if (last != -1)
4495         *cur = MIN (last, *cur);
4496     }
4497
4498     GST_DEBUG_OBJECT (basesink,
4499         "now %" GST_TIME_FORMAT " - base_time %" GST_TIME_FORMAT " - base %"
4500         GST_TIME_FORMAT " + time %" GST_TIME_FORMAT "  last %" GST_TIME_FORMAT,
4501         GST_TIME_ARGS (now), GST_TIME_ARGS (base_time), GST_TIME_ARGS (base),
4502         GST_TIME_ARGS (time), GST_TIME_ARGS (last));
4503   }
4504
4505   if (oformat != format) {
4506     /* convert to final format */
4507     if (!gst_pad_query_convert (basesink->sinkpad, oformat, *cur, format, cur))
4508       goto convert_failed;
4509   }
4510
4511   res = TRUE;
4512
4513 done:
4514   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
4515       res, GST_TIME_ARGS (*cur));
4516
4517   if (clock)
4518     gst_object_unref (clock);
4519
4520   return res;
4521
4522   /* special cases */
4523 wrong_state:
4524   {
4525     /* in NULL or READY we always return FALSE and -1 */
4526     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
4527     res = FALSE;
4528     *cur = -1;
4529     GST_OBJECT_UNLOCK (basesink);
4530     goto done;
4531   }
4532 convert_failed:
4533   {
4534     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
4535     *upstream = TRUE;
4536     res = FALSE;
4537     goto done;
4538   }
4539 }
4540
4541 static gboolean
4542 gst_base_sink_get_duration (GstBaseSink * basesink, GstFormat format,
4543     gint64 * dur, gboolean * upstream)
4544 {
4545   gboolean res = FALSE;
4546
4547   if (basesink->pad_mode == GST_PAD_MODE_PULL) {
4548     gint64 uduration;
4549
4550     /* get the duration in bytes, in pull mode that's all we are sure to
4551      * know. We have to explicitly get this value from upstream instead of
4552      * using our cached value because it might change. Duration caching
4553      * should be done at a higher level. */
4554     res =
4555         gst_pad_peer_query_duration (basesink->sinkpad, GST_FORMAT_BYTES,
4556         &uduration);
4557     if (res) {
4558       basesink->segment.duration = uduration;
4559       if (format != GST_FORMAT_BYTES) {
4560         /* convert to the requested format */
4561         res =
4562             gst_pad_query_convert (basesink->sinkpad, GST_FORMAT_BYTES,
4563             uduration, format, dur);
4564       } else {
4565         *dur = uduration;
4566       }
4567     }
4568     *upstream = FALSE;
4569   } else {
4570     *upstream = TRUE;
4571   }
4572
4573   return res;
4574 }
4575
4576 static gboolean
4577 default_element_query (GstElement * element, GstQuery * query)
4578 {
4579   gboolean res = FALSE;
4580
4581   GstBaseSink *basesink = GST_BASE_SINK (element);
4582
4583   switch (GST_QUERY_TYPE (query)) {
4584     case GST_QUERY_POSITION:
4585     {
4586       gint64 cur = 0;
4587       GstFormat format;
4588       gboolean upstream = FALSE;
4589
4590       gst_query_parse_position (query, &format, NULL);
4591
4592       GST_DEBUG_OBJECT (basesink, "position query in format %s",
4593           gst_format_get_name (format));
4594
4595       /* first try to get the position based on the clock */
4596       if ((res =
4597               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
4598         gst_query_set_position (query, format, cur);
4599       } else if (upstream) {
4600         /* fallback to peer query */
4601         res = gst_pad_peer_query (basesink->sinkpad, query);
4602       }
4603       if (!res) {
4604         /* we can handle a few things if upstream failed */
4605         if (format == GST_FORMAT_PERCENT) {
4606           gint64 dur = 0;
4607
4608           res = gst_base_sink_get_position (basesink, GST_FORMAT_TIME, &cur,
4609               &upstream);
4610           if (!res && upstream) {
4611             res =
4612                 gst_pad_peer_query_position (basesink->sinkpad, GST_FORMAT_TIME,
4613                 &cur);
4614           }
4615           if (res) {
4616             res = gst_base_sink_get_duration (basesink, GST_FORMAT_TIME, &dur,
4617                 &upstream);
4618             if (!res && upstream) {
4619               res =
4620                   gst_pad_peer_query_duration (basesink->sinkpad,
4621                   GST_FORMAT_TIME, &dur);
4622             }
4623           }
4624           if (res) {
4625             gint64 pos;
4626
4627             pos = gst_util_uint64_scale (100 * GST_FORMAT_PERCENT_SCALE, cur,
4628                 dur);
4629             gst_query_set_position (query, GST_FORMAT_PERCENT, pos);
4630           }
4631         }
4632       }
4633       break;
4634     }
4635     case GST_QUERY_DURATION:
4636     {
4637       gint64 dur = 0;
4638       GstFormat format;
4639       gboolean upstream = FALSE;
4640
4641       gst_query_parse_duration (query, &format, NULL);
4642
4643       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
4644           gst_format_get_name (format));
4645
4646       if ((res =
4647               gst_base_sink_get_duration (basesink, format, &dur, &upstream))) {
4648         gst_query_set_duration (query, format, dur);
4649       } else if (upstream) {
4650         /* fallback to peer query */
4651         res = gst_pad_peer_query (basesink->sinkpad, query);
4652       }
4653       if (!res) {
4654         /* we can handle a few things if upstream failed */
4655         if (format == GST_FORMAT_PERCENT) {
4656           gst_query_set_duration (query, GST_FORMAT_PERCENT,
4657               GST_FORMAT_PERCENT_MAX);
4658           res = TRUE;
4659         }
4660       }
4661       break;
4662     }
4663     case GST_QUERY_LATENCY:
4664     {
4665       gboolean live, us_live;
4666       GstClockTime min, max;
4667
4668       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
4669                   &max))) {
4670         gst_query_set_latency (query, live, min, max);
4671       }
4672       break;
4673     }
4674     case GST_QUERY_JITTER:
4675       break;
4676     case GST_QUERY_RATE:
4677       /* gst_query_set_rate (query, basesink->segment_rate); */
4678       res = TRUE;
4679       break;
4680     case GST_QUERY_SEGMENT:
4681     {
4682       if (basesink->pad_mode == GST_PAD_MODE_PULL) {
4683         gst_query_set_segment (query, basesink->segment.rate,
4684             GST_FORMAT_TIME, basesink->segment.start, basesink->segment.stop);
4685         res = TRUE;
4686       } else {
4687         res = gst_pad_peer_query (basesink->sinkpad, query);
4688       }
4689       break;
4690     }
4691     case GST_QUERY_SEEKING:
4692     case GST_QUERY_CONVERT:
4693     case GST_QUERY_FORMATS:
4694     default:
4695       res = gst_pad_peer_query (basesink->sinkpad, query);
4696       break;
4697   }
4698   GST_DEBUG_OBJECT (basesink, "query %s returns %d",
4699       GST_QUERY_TYPE_NAME (query), res);
4700   return res;
4701 }
4702
4703
4704 static gboolean
4705 default_sink_query (GstBaseSink * basesink, GstQuery * query)
4706 {
4707   gboolean res;
4708   GstBaseSinkClass *bclass;
4709
4710   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4711
4712   switch (GST_QUERY_TYPE (query)) {
4713     case GST_QUERY_ALLOCATION:
4714     {
4715       if (bclass->propose_allocation)
4716         res = bclass->propose_allocation (basesink, query);
4717       else
4718         res = FALSE;
4719       break;
4720     }
4721     case GST_QUERY_CAPS:
4722     {
4723       GstCaps *caps, *filter;
4724
4725       gst_query_parse_caps (query, &filter);
4726       caps = gst_base_sink_query_caps (basesink, basesink->sinkpad, filter);
4727       gst_query_set_caps_result (query, caps);
4728       gst_caps_unref (caps);
4729       res = TRUE;
4730       break;
4731     }
4732     default:
4733       res =
4734           gst_pad_query_default (basesink->sinkpad, GST_OBJECT_CAST (basesink),
4735           query);
4736       break;
4737   }
4738   return res;
4739 }
4740
4741 static gboolean
4742 gst_base_sink_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
4743 {
4744   GstBaseSink *basesink;
4745   GstBaseSinkClass *bclass;
4746   gboolean res;
4747
4748   basesink = GST_BASE_SINK_CAST (parent);
4749   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4750
4751   if (bclass->query)
4752     res = bclass->query (basesink, query);
4753   else
4754     res = FALSE;
4755
4756   return res;
4757 }
4758
4759 static GstStateChangeReturn
4760 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
4761 {
4762   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
4763   GstBaseSink *basesink = GST_BASE_SINK (element);
4764   GstBaseSinkClass *bclass;
4765   GstBaseSinkPrivate *priv;
4766
4767   priv = basesink->priv;
4768
4769   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4770
4771   switch (transition) {
4772     case GST_STATE_CHANGE_NULL_TO_READY:
4773       if (bclass->start)
4774         if (!bclass->start (basesink))
4775           goto start_failed;
4776       break;
4777     case GST_STATE_CHANGE_READY_TO_PAUSED:
4778       /* need to complete preroll before this state change completes, there
4779        * is no data flow in READY so we can safely assume we need to preroll. */
4780       GST_BASE_SINK_PREROLL_LOCK (basesink);
4781       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
4782       basesink->have_newsegment = FALSE;
4783       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
4784       gst_segment_init (&basesink->clip_segment, GST_FORMAT_UNDEFINED);
4785       basesink->offset = 0;
4786       basesink->have_preroll = FALSE;
4787       priv->step_unlock = FALSE;
4788       basesink->need_preroll = TRUE;
4789       basesink->playing_async = TRUE;
4790       basesink->priv->reset_time = FALSE;
4791       priv->current_sstart = GST_CLOCK_TIME_NONE;
4792       priv->current_sstop = GST_CLOCK_TIME_NONE;
4793       priv->eos_rtime = GST_CLOCK_TIME_NONE;
4794       priv->latency = 0;
4795       basesink->eos = FALSE;
4796       priv->received_eos = FALSE;
4797       gst_base_sink_reset_qos (basesink);
4798       priv->commited = FALSE;
4799       priv->call_preroll = TRUE;
4800       priv->current_step.valid = FALSE;
4801       priv->pending_step.valid = FALSE;
4802       if (priv->async_enabled) {
4803         GST_DEBUG_OBJECT (basesink, "doing async state change");
4804         /* when async enabled, post async-start message and return ASYNC from
4805          * the state change function */
4806         ret = GST_STATE_CHANGE_ASYNC;
4807         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4808             gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
4809       } else {
4810         priv->have_latency = TRUE;
4811       }
4812       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4813       break;
4814     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4815       GST_BASE_SINK_PREROLL_LOCK (basesink);
4816       g_atomic_int_set (&basesink->priv->to_playing, TRUE);
4817       if (!gst_base_sink_needs_preroll (basesink)) {
4818         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
4819         /* no preroll needed anymore now. */
4820         basesink->playing_async = FALSE;
4821         basesink->need_preroll = FALSE;
4822         if (basesink->eos) {
4823           GstMessage *message;
4824
4825           /* need to post EOS message here */
4826           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
4827           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
4828           gst_message_set_seqnum (message, basesink->priv->seqnum);
4829           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
4830         } else {
4831           GST_DEBUG_OBJECT (basesink, "signal preroll");
4832           GST_BASE_SINK_PREROLL_SIGNAL (basesink);
4833         }
4834       } else {
4835         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
4836         basesink->need_preroll = TRUE;
4837         basesink->playing_async = TRUE;
4838         priv->call_preroll = TRUE;
4839         priv->commited = FALSE;
4840         if (priv->async_enabled) {
4841           GST_DEBUG_OBJECT (basesink, "doing async state change");
4842           ret = GST_STATE_CHANGE_ASYNC;
4843           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4844               gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
4845         }
4846       }
4847       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4848       break;
4849     default:
4850       break;
4851   }
4852
4853   {
4854     GstStateChangeReturn bret;
4855
4856     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4857     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
4858       goto activate_failed;
4859   }
4860
4861   switch (transition) {
4862     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
4863       /* completed transition, so need not be marked any longer
4864        * And it should be unmarked, since e.g. losing our position upon flush
4865        * does not really change state to PAUSED ... */
4866       g_atomic_int_set (&basesink->priv->to_playing, FALSE);
4867       break;
4868     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
4869       g_atomic_int_set (&basesink->priv->to_playing, FALSE);
4870       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
4871       /* FIXME, make sure we cannot enter _render first */
4872
4873       /* we need to call ::unlock before locking PREROLL_LOCK
4874        * since we lock it before going into ::render */
4875       if (bclass->unlock)
4876         bclass->unlock (basesink);
4877
4878       GST_BASE_SINK_PREROLL_LOCK (basesink);
4879       GST_DEBUG_OBJECT (basesink, "got preroll lock");
4880       /* now that we have the PREROLL lock, clear our unlock request */
4881       if (bclass->unlock_stop)
4882         bclass->unlock_stop (basesink);
4883
4884       /* we need preroll again and we set the flag before unlocking the clockid
4885        * because if the clockid is unlocked before a current buffer expired, we
4886        * can use that buffer to preroll with */
4887       basesink->need_preroll = TRUE;
4888
4889       if (basesink->clock_id) {
4890         GST_DEBUG_OBJECT (basesink, "unschedule clock");
4891         gst_clock_id_unschedule (basesink->clock_id);
4892       }
4893
4894       /* if we don't have a preroll buffer we need to wait for a preroll and
4895        * return ASYNC. */
4896       if (!gst_base_sink_needs_preroll (basesink)) {
4897         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
4898         basesink->playing_async = FALSE;
4899       } else {
4900         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
4901           GST_DEBUG_OBJECT (basesink, "element is <= READY");
4902           ret = GST_STATE_CHANGE_SUCCESS;
4903         } else {
4904           GST_DEBUG_OBJECT (basesink,
4905               "PLAYING to PAUSED, we are not prerolled");
4906           basesink->playing_async = TRUE;
4907           priv->commited = FALSE;
4908           priv->call_preroll = TRUE;
4909           if (priv->async_enabled) {
4910             GST_DEBUG_OBJECT (basesink, "doing async state change");
4911             ret = GST_STATE_CHANGE_ASYNC;
4912             gst_element_post_message (GST_ELEMENT_CAST (basesink),
4913                 gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
4914           }
4915         }
4916       }
4917       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
4918           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
4919
4920       gst_base_sink_reset_qos (basesink);
4921       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4922       break;
4923     case GST_STATE_CHANGE_PAUSED_TO_READY:
4924       GST_BASE_SINK_PREROLL_LOCK (basesink);
4925       /* start by resetting our position state with the object lock so that the
4926        * position query gets the right idea. We do this before we post the
4927        * messages so that the message handlers pick this up. */
4928       GST_OBJECT_LOCK (basesink);
4929       basesink->have_newsegment = FALSE;
4930       priv->current_sstart = GST_CLOCK_TIME_NONE;
4931       priv->current_sstop = GST_CLOCK_TIME_NONE;
4932       priv->have_latency = FALSE;
4933       if (priv->cached_clock_id) {
4934         gst_clock_id_unref (priv->cached_clock_id);
4935         priv->cached_clock_id = NULL;
4936       }
4937       gst_caps_replace (&basesink->priv->caps, NULL);
4938       GST_OBJECT_UNLOCK (basesink);
4939
4940       gst_base_sink_set_last_buffer (basesink, NULL);
4941       priv->call_preroll = FALSE;
4942
4943       if (!priv->commited) {
4944         if (priv->async_enabled) {
4945           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
4946
4947           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4948               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
4949                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
4950
4951           gst_element_post_message (GST_ELEMENT_CAST (basesink),
4952               gst_message_new_async_done (GST_OBJECT_CAST (basesink), FALSE));
4953         }
4954         priv->commited = TRUE;
4955       } else {
4956         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
4957       }
4958       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4959       break;
4960     case GST_STATE_CHANGE_READY_TO_NULL:
4961       if (bclass->stop) {
4962         if (!bclass->stop (basesink)) {
4963           GST_WARNING_OBJECT (basesink, "failed to stop");
4964         }
4965       }
4966       gst_base_sink_set_last_buffer (basesink, NULL);
4967       priv->call_preroll = FALSE;
4968       break;
4969     default:
4970       break;
4971   }
4972
4973   return ret;
4974
4975   /* ERRORS */
4976 start_failed:
4977   {
4978     GST_DEBUG_OBJECT (basesink, "failed to start");
4979     return GST_STATE_CHANGE_FAILURE;
4980   }
4981 activate_failed:
4982   {
4983     GST_DEBUG_OBJECT (basesink,
4984         "element failed to change states -- activation problem?");
4985     return GST_STATE_CHANGE_FAILURE;
4986   }
4987 }