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