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