dccf3ce1b8e4eb5aa1c9159ac98354b712846b79
[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  * If the #GstBaseSinkClass.render() method can block on something else than
2243  * the clock, it must also be ready to unblock immediately on
2244  * the #GstBaseSinkClass.unlock() method and cause the
2245  * #GstBaseSinkClass.render() method to immediately call this function.
2246  * In this case, the subclass must be prepared to continue rendering where it
2247  * left off if this function returns %GST_FLOW_OK.
2248  *
2249  * This function will block until a state change to PLAYING happens (in which
2250  * case this function returns %GST_FLOW_OK) or the processing must be stopped due
2251  * to a state change to READY or a FLUSH event (in which case this function
2252  * returns %GST_FLOW_FLUSHING).
2253  *
2254  * This function should only be called with the PREROLL_LOCK held, like in the
2255  * render function.
2256  *
2257  * Returns: %GST_FLOW_OK if the preroll completed and processing can
2258  * continue. Any other return value should be returned from the render vmethod.
2259  */
2260 GstFlowReturn
2261 gst_base_sink_wait_preroll (GstBaseSink * sink)
2262 {
2263   sink->have_preroll = TRUE;
2264   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
2265   /* block until the state changes, or we get a flush, or something */
2266   GST_BASE_SINK_PREROLL_WAIT (sink);
2267   sink->have_preroll = FALSE;
2268   if (G_UNLIKELY (sink->flushing))
2269     goto stopping;
2270   if (G_UNLIKELY (sink->priv->step_unlock))
2271     goto step_unlocked;
2272   GST_DEBUG_OBJECT (sink, "continue after preroll");
2273
2274   return GST_FLOW_OK;
2275
2276   /* ERRORS */
2277 stopping:
2278   {
2279     GST_DEBUG_OBJECT (sink, "preroll interrupted because of flush");
2280     return GST_FLOW_FLUSHING;
2281   }
2282 step_unlocked:
2283   {
2284     sink->priv->step_unlock = FALSE;
2285     GST_DEBUG_OBJECT (sink, "preroll interrupted because of step");
2286     return GST_FLOW_STEP;
2287   }
2288 }
2289
2290 /**
2291  * gst_base_sink_do_preroll:
2292  * @sink: the sink
2293  * @obj: (transfer none): the mini object that caused the preroll
2294  *
2295  * If the @sink spawns its own thread for pulling buffers from upstream it
2296  * should call this method after it has pulled a buffer. If the element needed
2297  * to preroll, this function will perform the preroll and will then block
2298  * until the element state is changed.
2299  *
2300  * This function should be called with the PREROLL_LOCK held.
2301  *
2302  * Returns: %GST_FLOW_OK if the preroll completed and processing can
2303  * continue. Any other return value should be returned from the render vmethod.
2304  */
2305 GstFlowReturn
2306 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
2307 {
2308   GstFlowReturn ret;
2309
2310   while (G_UNLIKELY (sink->need_preroll)) {
2311     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
2312
2313     /* if it's a buffer, we need to call the preroll method */
2314     if (sink->priv->call_preroll) {
2315       GstBaseSinkClass *bclass;
2316       GstBuffer *buf;
2317
2318       if (GST_IS_BUFFER_LIST (obj)) {
2319         buf = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0);
2320         gst_base_sink_set_last_buffer (sink, buf);
2321         gst_base_sink_set_last_buffer_list (sink, GST_BUFFER_LIST_CAST (obj));
2322         g_assert (NULL != buf);
2323       } else if (GST_IS_BUFFER (obj)) {
2324         buf = GST_BUFFER_CAST (obj);
2325         /* For buffer lists do not set last buffer for now */
2326         gst_base_sink_set_last_buffer (sink, buf);
2327         gst_base_sink_set_last_buffer_list (sink, NULL);
2328       } else {
2329         buf = NULL;
2330       }
2331
2332       if (buf) {
2333         GST_DEBUG_OBJECT (sink, "preroll buffer %" GST_TIME_FORMAT,
2334             GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2335
2336         bclass = GST_BASE_SINK_GET_CLASS (sink);
2337
2338         if (bclass->prepare)
2339           if ((ret = bclass->prepare (sink, buf)) != GST_FLOW_OK)
2340             goto prepare_canceled;
2341
2342         if (bclass->preroll)
2343           if ((ret = bclass->preroll (sink, buf)) != GST_FLOW_OK)
2344             goto preroll_canceled;
2345
2346         sink->priv->call_preroll = FALSE;
2347       }
2348     }
2349
2350     /* commit state */
2351     if (G_LIKELY (sink->playing_async)) {
2352       if (G_UNLIKELY (!gst_base_sink_commit_state (sink)))
2353         goto stopping;
2354     }
2355
2356     /* need to recheck here because the commit state could have
2357      * made us not need the preroll anymore */
2358     if (G_LIKELY (sink->need_preroll)) {
2359       /* block until the state changes, or we get a flush, or something */
2360       ret = gst_base_sink_wait_preroll (sink);
2361       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2362         goto preroll_failed;
2363     }
2364   }
2365   return GST_FLOW_OK;
2366
2367   /* ERRORS */
2368 prepare_canceled:
2369   {
2370     GST_DEBUG_OBJECT (sink, "prepare failed, abort state");
2371     gst_element_abort_state (GST_ELEMENT_CAST (sink));
2372     return ret;
2373   }
2374 preroll_canceled:
2375   {
2376     GST_DEBUG_OBJECT (sink, "preroll failed, abort state");
2377     gst_element_abort_state (GST_ELEMENT_CAST (sink));
2378     return ret;
2379   }
2380 stopping:
2381   {
2382     GST_DEBUG_OBJECT (sink, "stopping while commiting state");
2383     return GST_FLOW_FLUSHING;
2384   }
2385 preroll_failed:
2386   {
2387     GST_DEBUG_OBJECT (sink, "preroll failed: %s", gst_flow_get_name (ret));
2388     return ret;
2389   }
2390 }
2391
2392 /**
2393  * gst_base_sink_wait:
2394  * @sink: the sink
2395  * @time: the running_time to be reached
2396  * @jitter: (out) (allow-none): the jitter to be filled with time diff, or %NULL
2397  *
2398  * This function will wait for preroll to complete and will then block until @time
2399  * is reached. It is usually called by subclasses that use their own internal
2400  * synchronisation but want to let some synchronization (like EOS) be handled
2401  * by the base class.
2402  *
2403  * This function should only be called with the PREROLL_LOCK held (like when
2404  * receiving an EOS event in the ::event vmethod or when handling buffers in
2405  * ::render).
2406  *
2407  * The @time argument should be the running_time of when the timeout should happen
2408  * and will be adjusted with any latency and offset configured in the sink.
2409  *
2410  * Returns: #GstFlowReturn
2411  */
2412 GstFlowReturn
2413 gst_base_sink_wait (GstBaseSink * sink, GstClockTime time,
2414     GstClockTimeDiff * jitter)
2415 {
2416   GstClockReturn status;
2417   GstFlowReturn ret;
2418
2419   do {
2420     GstClockTime stime;
2421
2422     GST_DEBUG_OBJECT (sink, "checking preroll");
2423
2424     /* first wait for the playing state before we can continue */
2425     while (G_UNLIKELY (sink->need_preroll)) {
2426       ret = gst_base_sink_wait_preroll (sink);
2427       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2428         goto flushing;
2429     }
2430
2431     /* preroll done, we can sync since we are in PLAYING now. */
2432     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
2433         GST_TIME_FORMAT, GST_TIME_ARGS (time));
2434
2435     /* compensate for latency, ts_offset and render delay */
2436     stime = gst_base_sink_adjust_time (sink, time);
2437
2438     /* wait for the clock, this can be interrupted because we got shut down or
2439      * we PAUSED. */
2440     status = gst_base_sink_wait_clock (sink, stime, jitter);
2441
2442     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
2443
2444     /* invalid time, no clock or sync disabled, just continue then */
2445     if (status == GST_CLOCK_BADTIME)
2446       break;
2447
2448     /* waiting could have been interrupted and we can be flushing now */
2449     if (G_UNLIKELY (sink->flushing))
2450       goto flushing;
2451
2452     /* retry if we got unscheduled, which means we did not reach the timeout
2453      * yet. if some other error occures, we continue. */
2454   } while (status == GST_CLOCK_UNSCHEDULED);
2455
2456   GST_DEBUG_OBJECT (sink, "end of stream");
2457
2458   return GST_FLOW_OK;
2459
2460   /* ERRORS */
2461 flushing:
2462   {
2463     GST_DEBUG_OBJECT (sink, "we are flushing");
2464     return GST_FLOW_FLUSHING;
2465   }
2466 }
2467
2468 /* with STREAM_LOCK, PREROLL_LOCK
2469  *
2470  * Make sure we are in PLAYING and synchronize an object to the clock.
2471  *
2472  * If we need preroll, we are not in PLAYING. We try to commit the state
2473  * if needed and then block if we still are not PLAYING.
2474  *
2475  * We start waiting on the clock in PLAYING. If we got interrupted, we
2476  * immediately try to re-preroll.
2477  *
2478  * Some objects do not need synchronisation (most events) and so this function
2479  * immediately returns GST_FLOW_OK.
2480  *
2481  * for objects that arrive later than max-lateness to be synchronized to the
2482  * clock have the @late boolean set to %TRUE.
2483  *
2484  * This function keeps a running average of the jitter (the diff between the
2485  * clock time and the requested sync time). The jitter is negative for
2486  * objects that arrive in time and positive for late buffers.
2487  *
2488  * does not take ownership of obj.
2489  */
2490 static GstFlowReturn
2491 gst_base_sink_do_sync (GstBaseSink * basesink,
2492     GstMiniObject * obj, gboolean * late, gboolean * step_end)
2493 {
2494   GstClockTimeDiff jitter = 0;
2495   gboolean syncable;
2496   GstClockReturn status = GST_CLOCK_OK;
2497   GstClockTime rstart, rstop, rnext, sstart, sstop, stime;
2498   gboolean do_sync;
2499   GstBaseSinkPrivate *priv;
2500   GstFlowReturn ret;
2501   GstStepInfo *current, *pending;
2502   gboolean stepped;
2503
2504   priv = basesink->priv;
2505
2506 do_step:
2507   sstart = sstop = rstart = rstop = rnext = GST_CLOCK_TIME_NONE;
2508   do_sync = TRUE;
2509   stepped = FALSE;
2510
2511   priv->current_rstart = GST_CLOCK_TIME_NONE;
2512
2513   /* get stepping info */
2514   current = &priv->current_step;
2515   pending = &priv->pending_step;
2516
2517   /* get timing information for this object against the render segment */
2518   syncable = gst_base_sink_get_sync_times (basesink, obj,
2519       &sstart, &sstop, &rstart, &rstop, &rnext, &do_sync, &stepped, current,
2520       step_end);
2521
2522   if (G_UNLIKELY (stepped))
2523     goto step_skipped;
2524
2525   /* a syncable object needs to participate in preroll and
2526    * clocking. All buffers and EOS are syncable. */
2527   if (G_UNLIKELY (!syncable))
2528     goto not_syncable;
2529
2530   /* store timing info for current object */
2531   priv->current_rstart = rstart;
2532   priv->current_rstop = (GST_CLOCK_TIME_IS_VALID (rstop) ? rstop : rstart);
2533
2534   /* save sync time for eos when the previous object needed sync */
2535   priv->eos_rtime = (do_sync ? rnext : GST_CLOCK_TIME_NONE);
2536
2537   /* calculate inter frame spacing */
2538   if (G_UNLIKELY (priv->prev_rstart != -1 && priv->prev_rstart < rstart)) {
2539     GstClockTime in_diff;
2540
2541     in_diff = rstart - priv->prev_rstart;
2542
2543     if (priv->avg_in_diff == -1)
2544       priv->avg_in_diff = in_diff;
2545     else
2546       priv->avg_in_diff = UPDATE_RUNNING_AVG (priv->avg_in_diff, in_diff);
2547
2548     GST_LOG_OBJECT (basesink, "avg frame diff %" GST_TIME_FORMAT,
2549         GST_TIME_ARGS (priv->avg_in_diff));
2550
2551   }
2552   priv->prev_rstart = rstart;
2553
2554   if (G_UNLIKELY (priv->earliest_in_time != -1
2555           && rstart < priv->earliest_in_time))
2556     goto qos_dropped;
2557
2558 again:
2559   /* first do preroll, this makes sure we commit our state
2560    * to PAUSED and can continue to PLAYING. We cannot perform
2561    * any clock sync in PAUSED because there is no clock. */
2562   ret = gst_base_sink_do_preroll (basesink, obj);
2563   if (G_UNLIKELY (ret != GST_FLOW_OK))
2564     goto preroll_failed;
2565
2566   /* update the segment with a pending step if the current one is invalid and we
2567    * have a new pending one. We only accept new step updates after a preroll */
2568   if (G_UNLIKELY (pending->valid && !current->valid)) {
2569     start_stepping (basesink, &basesink->segment, pending, current);
2570     goto do_step;
2571   }
2572
2573   /* After rendering we store the position of the last buffer so that we can use
2574    * it to report the position. We need to take the lock here. */
2575   GST_OBJECT_LOCK (basesink);
2576   priv->current_sstart = sstart;
2577   priv->current_sstop = (GST_CLOCK_TIME_IS_VALID (sstop) ? sstop : sstart);
2578   GST_OBJECT_UNLOCK (basesink);
2579
2580   if (!do_sync)
2581     goto done;
2582
2583   /* adjust for latency */
2584   stime = gst_base_sink_adjust_time (basesink, rstart);
2585
2586   /* adjust for rate control */
2587   if (priv->rc_next == -1 || (stime != -1 && stime >= priv->rc_next)) {
2588     GST_DEBUG_OBJECT (basesink, "reset rc_time to time %" GST_TIME_FORMAT,
2589         GST_TIME_ARGS (stime));
2590     priv->rc_time = stime;
2591     priv->rc_accumulated = 0;
2592   } else {
2593     GST_DEBUG_OBJECT (basesink, "rate control next %" GST_TIME_FORMAT,
2594         GST_TIME_ARGS (priv->rc_next));
2595     stime = priv->rc_next;
2596   }
2597
2598   /* preroll done, we can sync since we are in PLAYING now. */
2599   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
2600       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
2601       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
2602
2603   /* This function will return immediately if start == -1, no clock
2604    * or sync is disabled with GST_CLOCK_BADTIME. */
2605   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
2606
2607   GST_DEBUG_OBJECT (basesink, "clock returned %d, jitter %c%" GST_TIME_FORMAT,
2608       status, (jitter < 0 ? '-' : ' '), GST_TIME_ARGS (ABS (jitter)));
2609
2610   /* invalid time, no clock or sync disabled, just render */
2611   if (status == GST_CLOCK_BADTIME)
2612     goto done;
2613
2614   /* waiting could have been interrupted and we can be flushing now */
2615   if (G_UNLIKELY (basesink->flushing))
2616     goto flushing;
2617
2618   /* check for unlocked by a state change, we are not flushing so
2619    * we can try to preroll on the current buffer. */
2620   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
2621     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
2622     priv->call_preroll = TRUE;
2623     goto again;
2624   }
2625
2626   /* successful syncing done, record observation */
2627   priv->current_jitter = jitter;
2628
2629   /* check if the object should be dropped */
2630   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
2631       status, jitter, TRUE);
2632
2633 done:
2634   return GST_FLOW_OK;
2635
2636   /* ERRORS */
2637 step_skipped:
2638   {
2639     GST_DEBUG_OBJECT (basesink, "skipped stepped object %p", obj);
2640     *late = TRUE;
2641     return GST_FLOW_OK;
2642   }
2643 not_syncable:
2644   {
2645     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2646     return GST_FLOW_OK;
2647   }
2648 qos_dropped:
2649   {
2650     GST_DEBUG_OBJECT (basesink, "dropped because of QoS %p", obj);
2651     *late = TRUE;
2652     return GST_FLOW_OK;
2653   }
2654 flushing:
2655   {
2656     GST_DEBUG_OBJECT (basesink, "we are flushing");
2657     return GST_FLOW_FLUSHING;
2658   }
2659 preroll_failed:
2660   {
2661     GST_DEBUG_OBJECT (basesink, "preroll failed");
2662     *step_end = FALSE;
2663     return ret;
2664   }
2665 }
2666
2667 static gboolean
2668 gst_base_sink_send_qos (GstBaseSink * basesink, GstQOSType type,
2669     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2670 {
2671   GstEvent *event;
2672   gboolean res;
2673
2674   /* generate Quality-of-Service event */
2675   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2676       "qos: type %d, proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2677       GST_TIME_FORMAT, type, proportion, diff, GST_TIME_ARGS (time));
2678
2679   event = gst_event_new_qos (type, proportion, diff, time);
2680
2681   /* send upstream */
2682   res = gst_pad_push_event (basesink->sinkpad, event);
2683
2684   return res;
2685 }
2686
2687 static void
2688 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2689 {
2690   GstBaseSinkPrivate *priv;
2691   GstClockTime start, stop;
2692   GstClockTimeDiff jitter;
2693   GstClockTime pt, entered, left;
2694   GstClockTime duration;
2695   gdouble rate;
2696
2697   priv = sink->priv;
2698
2699   start = priv->current_rstart;
2700
2701   if (priv->current_step.valid)
2702     return;
2703
2704   /* if Quality-of-Service disabled, do nothing */
2705   if (!g_atomic_int_get (&priv->qos_enabled) ||
2706       !GST_CLOCK_TIME_IS_VALID (start))
2707     return;
2708
2709   stop = priv->current_rstop;
2710   jitter = priv->current_jitter;
2711
2712   if (jitter < 0) {
2713     /* this is the time the buffer entered the sink */
2714     if (start < -jitter)
2715       entered = 0;
2716     else
2717       entered = start + jitter;
2718     left = start;
2719   } else {
2720     /* this is the time the buffer entered the sink */
2721     entered = start + jitter;
2722     /* this is the time the buffer left the sink */
2723     left = start + jitter;
2724   }
2725
2726   /* calculate duration of the buffer, only use buffer durations if not in
2727    * trick mode or key-unit mode. Otherwise the buffer durations will be
2728    * meaningless as frames are being dropped in-between without updating the
2729    * durations. */
2730   duration = priv->avg_in_diff;
2731
2732   /* if we have the time when the last buffer left us, calculate
2733    * processing time */
2734   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2735     if (entered > priv->last_left) {
2736       pt = entered - priv->last_left;
2737     } else {
2738       pt = 0;
2739     }
2740   } else {
2741     pt = priv->avg_pt;
2742   }
2743
2744   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2745       ", stop %" GST_TIME_FORMAT ", entered %" GST_TIME_FORMAT ", left %"
2746       GST_TIME_FORMAT ", pt: %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2747       ",jitter %" G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
2748       GST_TIME_ARGS (entered), GST_TIME_ARGS (left), GST_TIME_ARGS (pt),
2749       GST_TIME_ARGS (duration), jitter);
2750
2751   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2752       "avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2753       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2754
2755   /* collect running averages. for first observations, we copy the
2756    * values */
2757   if (!GST_CLOCK_TIME_IS_VALID (priv->avg_pt))
2758     priv->avg_pt = pt;
2759   else
2760     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2761
2762   if (duration != -1 && duration != 0) {
2763     rate =
2764         gst_guint64_to_gdouble (priv->avg_pt) /
2765         gst_guint64_to_gdouble (duration);
2766   } else {
2767     rate = 1.0;
2768   }
2769
2770   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2771     if (dropped || priv->avg_rate < 0.0) {
2772       priv->avg_rate = rate;
2773     } else {
2774       if (rate > 1.0)
2775         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2776       else
2777         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2778     }
2779   }
2780
2781   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2782       "updated: avg_pt: %" GST_TIME_FORMAT
2783       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2784
2785
2786   if (priv->avg_rate >= 0.0) {
2787     GstQOSType type;
2788     GstClockTimeDiff diff;
2789
2790     /* if we have a valid rate, start sending QoS messages */
2791     if (priv->current_jitter < 0) {
2792       /* make sure we never go below 0 when adding the jitter to the
2793        * timestamp. */
2794       if (priv->current_rstart < -priv->current_jitter)
2795         priv->current_jitter = -priv->current_rstart;
2796     }
2797
2798     if (priv->throttle_time > 0) {
2799       diff = priv->throttle_time;
2800       type = GST_QOS_TYPE_THROTTLE;
2801     } else {
2802       diff = priv->current_jitter;
2803       if (diff <= 0)
2804         type = GST_QOS_TYPE_OVERFLOW;
2805       else
2806         type = GST_QOS_TYPE_UNDERFLOW;
2807     }
2808
2809     gst_base_sink_send_qos (sink, type, priv->avg_rate, priv->current_rstart,
2810         diff);
2811   }
2812
2813   /* record when this buffer will leave us */
2814   priv->last_left = left;
2815 }
2816
2817 /* reset all qos measuring */
2818 static void
2819 gst_base_sink_reset_qos (GstBaseSink * sink)
2820 {
2821   GstBaseSinkPrivate *priv;
2822
2823   priv = sink->priv;
2824
2825   priv->last_render_time = GST_CLOCK_TIME_NONE;
2826   priv->prev_rstart = GST_CLOCK_TIME_NONE;
2827   priv->earliest_in_time = GST_CLOCK_TIME_NONE;
2828   priv->last_left = GST_CLOCK_TIME_NONE;
2829   priv->avg_pt = GST_CLOCK_TIME_NONE;
2830   priv->avg_rate = -1.0;
2831   priv->avg_in_diff = GST_CLOCK_TIME_NONE;
2832   priv->rendered = 0;
2833   priv->dropped = 0;
2834
2835 }
2836
2837 /* Checks if the object was scheduled too late.
2838  *
2839  * rstart/rstop contain the running_time start and stop values
2840  * of the object.
2841  *
2842  * status and jitter contain the return values from the clock wait.
2843  *
2844  * returns %TRUE if the buffer was too late.
2845  */
2846 static gboolean
2847 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2848     GstClockTime rstart, GstClockTime rstop,
2849     GstClockReturn status, GstClockTimeDiff jitter, gboolean render)
2850 {
2851   gboolean late;
2852   guint64 max_lateness;
2853   GstBaseSinkPrivate *priv;
2854
2855   priv = basesink->priv;
2856
2857   late = FALSE;
2858
2859   /* only for objects that were too late */
2860   if (G_LIKELY (status != GST_CLOCK_EARLY))
2861     goto in_time;
2862
2863   max_lateness = basesink->max_lateness;
2864
2865   /* check if frame dropping is enabled */
2866   if (max_lateness == -1)
2867     goto no_drop;
2868
2869   /* only check for buffers */
2870   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2871     goto not_buffer;
2872
2873   /* can't do check if we don't have a timestamp */
2874   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (rstart)))
2875     goto no_timestamp;
2876
2877   /* we can add a valid stop time */
2878   if (GST_CLOCK_TIME_IS_VALID (rstop))
2879     max_lateness += rstop;
2880   else {
2881     max_lateness += rstart;
2882     /* no stop time, use avg frame diff */
2883     if (priv->avg_in_diff != -1)
2884       max_lateness += priv->avg_in_diff;
2885   }
2886
2887   /* if the jitter bigger than duration and lateness we are too late */
2888   if ((late = rstart + jitter > max_lateness)) {
2889     GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2890         "buffer is too late %" GST_TIME_FORMAT
2891         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (rstart + jitter),
2892         GST_TIME_ARGS (max_lateness));
2893     /* !!emergency!!, if we did not receive anything valid for more than a
2894      * second, render it anyway so the user sees something */
2895     if (GST_CLOCK_TIME_IS_VALID (priv->last_render_time) &&
2896         rstart - priv->last_render_time > GST_SECOND) {
2897       late = FALSE;
2898       GST_ELEMENT_WARNING (basesink, CORE, CLOCK,
2899           (_("A lot of buffers are being dropped.")),
2900           ("There may be a timestamping problem, or this computer is too slow."));
2901       GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2902           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
2903           GST_TIME_ARGS (priv->last_render_time));
2904     }
2905   }
2906
2907 done:
2908   if (render && (!late || !GST_CLOCK_TIME_IS_VALID (priv->last_render_time))) {
2909     priv->last_render_time = rstart;
2910     /* the next allowed input timestamp */
2911     if (priv->throttle_time > 0)
2912       priv->earliest_in_time = rstart + priv->throttle_time;
2913   }
2914   return late;
2915
2916   /* all is fine */
2917 in_time:
2918   {
2919     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
2920     goto done;
2921   }
2922 no_drop:
2923   {
2924     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
2925     goto done;
2926   }
2927 not_buffer:
2928   {
2929     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
2930     return FALSE;
2931   }
2932 no_timestamp:
2933   {
2934     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
2935     return FALSE;
2936   }
2937 }
2938
2939 static void
2940 gst_base_sink_update_start_time (GstBaseSink * basesink)
2941 {
2942   GstClock *clock;
2943
2944   GST_OBJECT_LOCK (basesink);
2945   if (GST_STATE (basesink) == GST_STATE_PLAYING
2946       && (clock = GST_ELEMENT_CLOCK (basesink))) {
2947     GstClockTime now;
2948
2949     gst_object_ref (clock);
2950     GST_OBJECT_UNLOCK (basesink);
2951
2952     /* calculate the time when we stopped */
2953     now = gst_clock_get_time (clock);
2954     gst_object_unref (clock);
2955
2956     GST_OBJECT_LOCK (basesink);
2957     /* store the current running time */
2958     if (GST_ELEMENT_START_TIME (basesink) != GST_CLOCK_TIME_NONE) {
2959       if (now != GST_CLOCK_TIME_NONE)
2960         GST_ELEMENT_START_TIME (basesink) =
2961             now - GST_ELEMENT_CAST (basesink)->base_time;
2962       else
2963         GST_WARNING_OBJECT (basesink,
2964             "Clock %s returned invalid time, can't calculate "
2965             "running_time when going to the PAUSED state",
2966             GST_OBJECT_NAME (clock));
2967     }
2968     GST_DEBUG_OBJECT (basesink,
2969         "start_time=%" GST_TIME_FORMAT ", now=%" GST_TIME_FORMAT
2970         ", base_time %" GST_TIME_FORMAT,
2971         GST_TIME_ARGS (GST_ELEMENT_START_TIME (basesink)),
2972         GST_TIME_ARGS (now),
2973         GST_TIME_ARGS (GST_ELEMENT_CAST (basesink)->base_time));
2974   }
2975   GST_OBJECT_UNLOCK (basesink);
2976 }
2977
2978 static void
2979 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
2980 {
2981   /* make sure we are not blocked on the clock also clear any pending
2982    * eos state. */
2983   gst_base_sink_set_flushing (basesink, pad, TRUE);
2984
2985   /* we grab the stream lock but that is not needed since setting the
2986    * sink to flushing would make sure no state commit is being done
2987    * anymore */
2988   GST_PAD_STREAM_LOCK (pad);
2989   gst_base_sink_reset_qos (basesink);
2990   /* and we need to commit our state again on the next
2991    * prerolled buffer */
2992   basesink->playing_async = TRUE;
2993   if (basesink->priv->async_enabled) {
2994     gst_base_sink_update_start_time (basesink);
2995     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
2996   } else {
2997     /* start time reset in above case as well;
2998      * arranges for a.o. proper position reporting when flushing in PAUSED */
2999     gst_element_set_start_time (GST_ELEMENT_CAST (basesink), 0);
3000     basesink->priv->have_latency = TRUE;
3001   }
3002   gst_base_sink_set_last_buffer (basesink, NULL);
3003   gst_base_sink_set_last_buffer_list (basesink, NULL);
3004   GST_PAD_STREAM_UNLOCK (pad);
3005 }
3006
3007 static void
3008 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad,
3009     gboolean reset_time)
3010 {
3011   /* unset flushing so we can accept new data, this also flushes out any EOS
3012    * event. */
3013   gst_base_sink_set_flushing (basesink, pad, FALSE);
3014
3015   /* for position reporting */
3016   GST_OBJECT_LOCK (basesink);
3017   basesink->priv->current_sstart = GST_CLOCK_TIME_NONE;
3018   basesink->priv->current_sstop = GST_CLOCK_TIME_NONE;
3019   basesink->priv->eos_rtime = GST_CLOCK_TIME_NONE;
3020   basesink->priv->call_preroll = TRUE;
3021   basesink->priv->current_step.valid = FALSE;
3022   basesink->priv->pending_step.valid = FALSE;
3023   if (basesink->pad_mode == GST_PAD_MODE_PUSH) {
3024     /* we need new segment info after the flush. */
3025     basesink->have_newsegment = FALSE;
3026     if (reset_time) {
3027       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
3028       GST_ELEMENT_START_TIME (basesink) = 0;
3029     }
3030   }
3031   GST_OBJECT_UNLOCK (basesink);
3032
3033   if (reset_time) {
3034     GST_DEBUG_OBJECT (basesink, "posting reset-time message");
3035     gst_element_post_message (GST_ELEMENT_CAST (basesink),
3036         gst_message_new_reset_time (GST_OBJECT_CAST (basesink), 0));
3037   }
3038 }
3039
3040 static GstFlowReturn
3041 gst_base_sink_default_wait_event (GstBaseSink * basesink, GstEvent * event)
3042 {
3043   GstFlowReturn ret;
3044   gboolean late, step_end = FALSE;
3045
3046   ret = gst_base_sink_do_sync (basesink, GST_MINI_OBJECT_CAST (event),
3047       &late, &step_end);
3048
3049   return ret;
3050 }
3051
3052 static GstFlowReturn
3053 gst_base_sink_wait_event (GstBaseSink * basesink, GstEvent * event)
3054 {
3055   GstFlowReturn ret;
3056   GstBaseSinkClass *bclass;
3057
3058   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3059
3060   if (G_LIKELY (bclass->wait_event))
3061     ret = bclass->wait_event (basesink, event);
3062   else
3063     ret = GST_FLOW_NOT_SUPPORTED;
3064
3065   return ret;
3066 }
3067
3068 static gboolean
3069 gst_base_sink_default_event (GstBaseSink * basesink, GstEvent * event)
3070 {
3071   gboolean result = TRUE;
3072   GstBaseSinkClass *bclass;
3073
3074   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3075
3076   switch (GST_EVENT_TYPE (event)) {
3077     case GST_EVENT_FLUSH_START:
3078     {
3079       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
3080       gst_base_sink_flush_start (basesink, basesink->sinkpad);
3081       break;
3082     }
3083     case GST_EVENT_FLUSH_STOP:
3084     {
3085       gboolean reset_time;
3086
3087       gst_event_parse_flush_stop (event, &reset_time);
3088       GST_DEBUG_OBJECT (basesink, "flush-stop %p, reset_time: %d", event,
3089           reset_time);
3090       gst_base_sink_flush_stop (basesink, basesink->sinkpad, reset_time);
3091       break;
3092     }
3093     case GST_EVENT_EOS:
3094     {
3095       GstMessage *message;
3096       guint32 seqnum;
3097
3098       /* we set the received EOS flag here so that we can use it when testing if
3099        * we are prerolled and to refuse more buffers. */
3100       basesink->priv->received_eos = TRUE;
3101
3102       /* wait for EOS */
3103       if (G_UNLIKELY (gst_base_sink_wait_event (basesink,
3104                   event) != GST_FLOW_OK)) {
3105         result = FALSE;
3106         goto done;
3107       }
3108
3109       /* the EOS event is completely handled so we mark
3110        * ourselves as being in the EOS state. eos is also
3111        * protected by the object lock so we can read it when
3112        * answering the POSITION query. */
3113       GST_OBJECT_LOCK (basesink);
3114       basesink->eos = TRUE;
3115       GST_OBJECT_UNLOCK (basesink);
3116
3117       /* ok, now we can post the message */
3118       GST_DEBUG_OBJECT (basesink, "Now posting EOS");
3119
3120       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
3121       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
3122
3123       message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
3124       gst_message_set_seqnum (message, seqnum);
3125       gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
3126       break;
3127     }
3128     case GST_EVENT_STREAM_START:
3129     {
3130       GstMessage *message;
3131       guint32 seqnum;
3132       guint group_id;
3133
3134       seqnum = gst_event_get_seqnum (event);
3135       GST_DEBUG_OBJECT (basesink, "Now posting STREAM_START (seqnum:%d)",
3136           seqnum);
3137       message = gst_message_new_stream_start (GST_OBJECT_CAST (basesink));
3138       if (gst_event_parse_group_id (event, &group_id)) {
3139         gst_message_set_group_id (message, group_id);
3140       } else {
3141         GST_FIXME_OBJECT (basesink, "stream-start event without group-id. "
3142             "Consider implementing group-id handling in the upstream "
3143             "elements");
3144       }
3145       gst_message_set_seqnum (message, seqnum);
3146       gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
3147       break;
3148     }
3149     case GST_EVENT_CAPS:
3150     {
3151       GstCaps *caps, *current_caps;
3152
3153       GST_DEBUG_OBJECT (basesink, "caps %p", event);
3154
3155       gst_event_parse_caps (event, &caps);
3156       current_caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (basesink));
3157
3158       if (current_caps && gst_caps_is_equal (current_caps, caps)) {
3159         GST_DEBUG_OBJECT (basesink,
3160             "New caps equal to old ones: %" GST_PTR_FORMAT, caps);
3161       } else {
3162         if (bclass->set_caps)
3163           result = bclass->set_caps (basesink, caps);
3164
3165         if (result) {
3166           GST_OBJECT_LOCK (basesink);
3167           gst_caps_replace (&basesink->priv->caps, caps);
3168           GST_OBJECT_UNLOCK (basesink);
3169         }
3170       }
3171       if (current_caps)
3172         gst_caps_unref (current_caps);
3173       break;
3174     }
3175     case GST_EVENT_SEGMENT:
3176       /* configure the segment */
3177       /* The segment is protected with both the STREAM_LOCK and the OBJECT_LOCK.
3178        * We protect with the OBJECT_LOCK so that we can use the values to
3179        * safely answer a POSITION query. */
3180       GST_OBJECT_LOCK (basesink);
3181       /* the newsegment event is needed to bring the buffer timestamps to the
3182        * stream time and to drop samples outside of the playback segment. */
3183       gst_event_copy_segment (event, &basesink->segment);
3184       GST_DEBUG_OBJECT (basesink, "configured segment %" GST_SEGMENT_FORMAT,
3185           &basesink->segment);
3186       basesink->have_newsegment = TRUE;
3187       gst_base_sink_reset_qos (basesink);
3188       GST_OBJECT_UNLOCK (basesink);
3189       break;
3190     case GST_EVENT_GAP:
3191     {
3192       if (G_UNLIKELY (gst_base_sink_wait_event (basesink,
3193                   event) != GST_FLOW_OK))
3194         result = FALSE;
3195       break;
3196     }
3197     case GST_EVENT_TAG:
3198     {
3199       GstTagList *taglist;
3200
3201       gst_event_parse_tag (event, &taglist);
3202
3203       gst_element_post_message (GST_ELEMENT_CAST (basesink),
3204           gst_message_new_tag (GST_OBJECT_CAST (basesink),
3205               gst_tag_list_copy (taglist)));
3206       break;
3207     }
3208     case GST_EVENT_TOC:
3209     {
3210       GstToc *toc;
3211       gboolean updated;
3212
3213       gst_event_parse_toc (event, &toc, &updated);
3214
3215       gst_element_post_message (GST_ELEMENT_CAST (basesink),
3216           gst_message_new_toc (GST_OBJECT_CAST (basesink), toc, updated));
3217
3218       gst_toc_unref (toc);
3219       break;
3220     }
3221     case GST_EVENT_SINK_MESSAGE:
3222     {
3223       GstMessage *msg = NULL;
3224
3225       gst_event_parse_sink_message (event, &msg);
3226       if (msg)
3227         gst_element_post_message (GST_ELEMENT_CAST (basesink), msg);
3228       break;
3229     }
3230     default:
3231       break;
3232   }
3233 done:
3234   gst_event_unref (event);
3235
3236   return result;
3237 }
3238
3239 static gboolean
3240 gst_base_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
3241 {
3242   GstBaseSink *basesink;
3243   gboolean result = TRUE;
3244   GstBaseSinkClass *bclass;
3245
3246   basesink = GST_BASE_SINK_CAST (parent);
3247   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3248
3249   GST_DEBUG_OBJECT (basesink, "received event %p %" GST_PTR_FORMAT, event,
3250       event);
3251
3252   switch (GST_EVENT_TYPE (event)) {
3253     case GST_EVENT_FLUSH_STOP:
3254       /* special case for this serialized event because we don't want to grab
3255        * the PREROLL lock or check if we were flushing */
3256       if (bclass->event)
3257         result = bclass->event (basesink, event);
3258       break;
3259     default:
3260       if (GST_EVENT_IS_SERIALIZED (event)) {
3261         GST_BASE_SINK_PREROLL_LOCK (basesink);
3262         if (G_UNLIKELY (basesink->flushing))
3263           goto flushing;
3264
3265         if (G_UNLIKELY (basesink->priv->received_eos))
3266           goto after_eos;
3267
3268         if (bclass->event)
3269           result = bclass->event (basesink, event);
3270
3271         GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3272       } else {
3273         if (bclass->event)
3274           result = bclass->event (basesink, event);
3275       }
3276       break;
3277   }
3278 done:
3279   return result;
3280
3281   /* ERRORS */
3282 flushing:
3283   {
3284     GST_DEBUG_OBJECT (basesink, "we are flushing");
3285     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3286     gst_event_unref (event);
3287     result = FALSE;
3288     goto done;
3289   }
3290
3291 after_eos:
3292   {
3293     GST_DEBUG_OBJECT (basesink, "Event received after EOS, dropping");
3294     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3295     gst_event_unref (event);
3296     result = FALSE;
3297     goto done;
3298   }
3299 }
3300
3301 /* default implementation to calculate the start and end
3302  * timestamps on a buffer, subclasses can override
3303  */
3304 static void
3305 gst_base_sink_default_get_times (GstBaseSink * basesink, GstBuffer * buffer,
3306     GstClockTime * start, GstClockTime * end)
3307 {
3308   GstClockTime timestamp, duration;
3309
3310   /* first sync on DTS, else use PTS */
3311   timestamp = GST_BUFFER_DTS (buffer);
3312   if (!GST_CLOCK_TIME_IS_VALID (timestamp))
3313     timestamp = GST_BUFFER_PTS (buffer);
3314
3315   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
3316     /* get duration to calculate end time */
3317     duration = GST_BUFFER_DURATION (buffer);
3318     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3319       *end = timestamp + duration;
3320     }
3321     *start = timestamp;
3322   }
3323 }
3324
3325 /* must be called with PREROLL_LOCK */
3326 static gboolean
3327 gst_base_sink_needs_preroll (GstBaseSink * basesink)
3328 {
3329   gboolean is_prerolled, res;
3330
3331   /* we have 2 cases where the PREROLL_LOCK is released:
3332    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
3333    *  2) we are syncing on the clock
3334    */
3335   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
3336   res = !is_prerolled;
3337
3338   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
3339       basesink->have_preroll, basesink->priv->received_eos, res);
3340
3341   return res;
3342 }
3343
3344 static gboolean
3345 count_list_bytes (GstBuffer ** buffer, guint idx, GstBaseSinkPrivate * priv)
3346 {
3347   priv->rc_accumulated += gst_buffer_get_size (*buffer);
3348   return TRUE;
3349 }
3350
3351 /* with STREAM_LOCK, PREROLL_LOCK
3352  *
3353  * Takes a buffer and compare the timestamps with the last segment.
3354  * If the buffer falls outside of the segment boundaries, drop it.
3355  * Else send the buffer for preroll and rendering.
3356  *
3357  * This function takes ownership of the buffer.
3358  */
3359 static GstFlowReturn
3360 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
3361     gpointer obj, gboolean is_list)
3362 {
3363   GstBaseSinkClass *bclass;
3364   GstBaseSinkPrivate *priv = basesink->priv;
3365   GstFlowReturn ret = GST_FLOW_OK;
3366   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
3367   GstSegment *segment;
3368   GstBuffer *sync_buf;
3369   gboolean late, step_end, prepared = FALSE;
3370
3371   if (G_UNLIKELY (basesink->flushing))
3372     goto flushing;
3373
3374   if (G_UNLIKELY (priv->received_eos))
3375     goto was_eos;
3376
3377   if (is_list) {
3378     GstBufferList *buffer_list = GST_BUFFER_LIST_CAST (obj);
3379
3380     if (gst_buffer_list_length (buffer_list) == 0)
3381       goto empty_list;
3382
3383     sync_buf = gst_buffer_list_get (buffer_list, 0);
3384     g_assert (NULL != sync_buf);
3385   } else {
3386     sync_buf = GST_BUFFER_CAST (obj);
3387   }
3388
3389   /* for code clarity */
3390   segment = &basesink->segment;
3391
3392   if (G_UNLIKELY (!basesink->have_newsegment)) {
3393     gboolean sync;
3394
3395     sync = gst_base_sink_get_sync (basesink);
3396     if (sync) {
3397       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
3398           (_("Internal data flow problem.")),
3399           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
3400     }
3401
3402     /* this means this sink will assume timestamps start from 0 */
3403     GST_OBJECT_LOCK (basesink);
3404     segment->start = 0;
3405     segment->stop = -1;
3406     basesink->segment.start = 0;
3407     basesink->segment.stop = -1;
3408     basesink->have_newsegment = TRUE;
3409     GST_OBJECT_UNLOCK (basesink);
3410   }
3411
3412   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3413
3414   /* check if the buffer needs to be dropped, we first ask the subclass for the
3415    * start and end */
3416   if (bclass->get_times)
3417     bclass->get_times (basesink, sync_buf, &start, &end);
3418
3419   if (!GST_CLOCK_TIME_IS_VALID (start)) {
3420     /* if the subclass does not want sync, we use our own values so that we at
3421      * least clip the buffer to the segment */
3422     gst_base_sink_default_get_times (basesink, sync_buf, &start, &end);
3423   }
3424
3425   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
3426       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
3427
3428   /* a dropped buffer does not participate in anything. Buffer can only be
3429    * dropped if their PTS falls completly outside the segment, while we sync
3430    * preferably on DTS */
3431   if (GST_CLOCK_TIME_IS_VALID (start) && (segment->format == GST_FORMAT_TIME)) {
3432     GstClockTime pts = GST_BUFFER_PTS (sync_buf);
3433     GstClockTime pts_end = GST_CLOCK_TIME_NONE;
3434
3435     if (!GST_CLOCK_TIME_IS_VALID (pts))
3436       pts = start;
3437
3438     if (GST_CLOCK_TIME_IS_VALID (end))
3439       pts_end = pts + (end - start);
3440
3441     if (G_UNLIKELY (!gst_segment_clip (segment,
3442                 GST_FORMAT_TIME, pts, pts_end, NULL, NULL)
3443             && priv->drop_out_of_segment))
3444       goto out_of_segment;
3445   }
3446
3447   if (bclass->prepare || bclass->prepare_list) {
3448     gboolean do_sync = TRUE, stepped = FALSE, syncable = TRUE;
3449     GstClockTime sstart, sstop, rstart, rstop, rnext;
3450     GstStepInfo *current;
3451
3452     late = FALSE;
3453     step_end = FALSE;
3454
3455     current = &priv->current_step;
3456     syncable =
3457         gst_base_sink_get_sync_times (basesink, obj, &sstart, &sstop, &rstart,
3458         &rstop, &rnext, &do_sync, &stepped, current, &step_end);
3459
3460     if (G_UNLIKELY (stepped))
3461       goto dropped;
3462
3463     if (syncable && do_sync && gst_base_sink_get_sync (basesink)) {
3464       GstClock *clock;
3465
3466       GST_OBJECT_LOCK (basesink);
3467       clock = GST_ELEMENT_CLOCK (basesink);
3468       if (clock && GST_STATE (basesink) == GST_STATE_PLAYING) {
3469         GstClockTime base_time;
3470         GstClockTime stime;
3471         GstClockTime now;
3472
3473         base_time = GST_ELEMENT_CAST (basesink)->base_time;
3474         stime = base_time + gst_base_sink_adjust_time (basesink, rstart);
3475         now = gst_clock_get_time (clock);
3476         GST_OBJECT_UNLOCK (basesink);
3477
3478         late =
3479             gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
3480             GST_CLOCK_EARLY, GST_CLOCK_DIFF (stime, now), FALSE);
3481       } else {
3482         GST_OBJECT_UNLOCK (basesink);
3483       }
3484     }
3485
3486     /* We are about to prepare the first frame, make sure we have prerolled
3487      * already. This prevent nesting prepare/render calls. */
3488     ret = gst_base_sink_do_preroll (basesink, obj);
3489     if (G_UNLIKELY (ret != GST_FLOW_OK))
3490       goto preroll_failed;
3491
3492     if (G_UNLIKELY (late))
3493       goto dropped;
3494
3495     if (!is_list) {
3496       if (bclass->prepare) {
3497         ret = bclass->prepare (basesink, GST_BUFFER_CAST (obj));
3498         if (G_UNLIKELY (ret != GST_FLOW_OK))
3499           goto prepare_failed;
3500       }
3501     } else {
3502       if (bclass->prepare_list) {
3503         ret = bclass->prepare_list (basesink, GST_BUFFER_LIST_CAST (obj));
3504         if (G_UNLIKELY (ret != GST_FLOW_OK))
3505           goto prepare_failed;
3506       }
3507     }
3508
3509     prepared = TRUE;
3510   }
3511
3512 again:
3513   late = FALSE;
3514   step_end = FALSE;
3515
3516   /* synchronize this object, non syncable objects return OK
3517    * immediately. */
3518   ret = gst_base_sink_do_sync (basesink, GST_MINI_OBJECT_CAST (sync_buf),
3519       &late, &step_end);
3520   if (G_UNLIKELY (ret != GST_FLOW_OK))
3521     goto sync_failed;
3522
3523   /* Don't skip if prepare() was called on time */
3524   late = late && !prepared;
3525
3526   /* drop late buffers unconditionally, let's hope it's unlikely */
3527   if (G_UNLIKELY (late))
3528     goto dropped;
3529
3530   if (priv->max_bitrate) {
3531     if (is_list) {
3532       gst_buffer_list_foreach (GST_BUFFER_LIST_CAST (obj),
3533           (GstBufferListFunc) count_list_bytes, priv);
3534     } else {
3535       priv->rc_accumulated += gst_buffer_get_size (GST_BUFFER_CAST (obj));
3536     }
3537     priv->rc_next = priv->rc_time + gst_util_uint64_scale (priv->rc_accumulated,
3538         8 * GST_SECOND, priv->max_bitrate);
3539   }
3540
3541   GST_DEBUG_OBJECT (basesink, "rendering object %p", obj);
3542
3543   if (!is_list) {
3544     /* For buffer lists do not set last buffer for now. */
3545     gst_base_sink_set_last_buffer (basesink, GST_BUFFER_CAST (obj));
3546     gst_base_sink_set_last_buffer_list (basesink, NULL);
3547
3548     if (bclass->render)
3549       ret = bclass->render (basesink, GST_BUFFER_CAST (obj));
3550   } else {
3551     GstBufferList *buffer_list = GST_BUFFER_LIST_CAST (obj);
3552
3553     if (bclass->render_list)
3554       ret = bclass->render_list (basesink, buffer_list);
3555
3556     /* Set the first buffer and buffer list to be included in last sample */
3557     gst_base_sink_set_last_buffer (basesink, sync_buf);
3558     gst_base_sink_set_last_buffer_list (basesink, buffer_list);
3559   }
3560
3561   if (ret == GST_FLOW_STEP)
3562     goto again;
3563
3564   if (G_UNLIKELY (basesink->flushing))
3565     goto flushing;
3566
3567   priv->rendered++;
3568
3569 done:
3570   if (step_end) {
3571     /* the step ended, check if we need to activate a new step */
3572     GST_DEBUG_OBJECT (basesink, "step ended");
3573     stop_stepping (basesink, &basesink->segment, &priv->current_step,
3574         priv->current_rstart, priv->current_rstop, basesink->eos);
3575     goto again;
3576   }
3577
3578   gst_base_sink_perform_qos (basesink, late);
3579
3580   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
3581   gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3582
3583   return ret;
3584
3585   /* ERRORS */
3586 flushing:
3587   {
3588     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3589     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3590     return GST_FLOW_FLUSHING;
3591   }
3592 was_eos:
3593   {
3594     GST_DEBUG_OBJECT (basesink, "we are EOS, dropping object, return EOS");
3595     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3596     return GST_FLOW_EOS;
3597   }
3598 empty_list:
3599   {
3600     GST_DEBUG_OBJECT (basesink, "buffer list with no buffers");
3601     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3602     return GST_FLOW_OK;
3603   }
3604 out_of_segment:
3605   {
3606     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
3607     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3608     return GST_FLOW_OK;
3609   }
3610 prepare_failed:
3611   {
3612     GST_DEBUG_OBJECT (basesink, "prepare buffer failed %s",
3613         gst_flow_get_name (ret));
3614     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3615     return ret;
3616   }
3617 sync_failed:
3618   {
3619     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
3620     goto done;
3621   }
3622 dropped:
3623   {
3624     priv->dropped++;
3625     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
3626
3627     if (g_atomic_int_get (&priv->qos_enabled)) {
3628       GstMessage *qos_msg;
3629       GstClockTime timestamp, duration;
3630
3631       timestamp = GST_BUFFER_TIMESTAMP (GST_BUFFER_CAST (sync_buf));
3632       duration = GST_BUFFER_DURATION (GST_BUFFER_CAST (sync_buf));
3633
3634       GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
3635           "qos: dropped buffer rt %" GST_TIME_FORMAT ", st %" GST_TIME_FORMAT
3636           ", ts %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
3637           GST_TIME_ARGS (priv->current_rstart),
3638           GST_TIME_ARGS (priv->current_sstart), GST_TIME_ARGS (timestamp),
3639           GST_TIME_ARGS (duration));
3640       GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
3641           "qos: rendered %" G_GUINT64_FORMAT ", dropped %" G_GUINT64_FORMAT,
3642           priv->rendered, priv->dropped);
3643
3644       qos_msg =
3645           gst_message_new_qos (GST_OBJECT_CAST (basesink), basesink->sync,
3646           priv->current_rstart, priv->current_sstart, timestamp, duration);
3647       gst_message_set_qos_values (qos_msg, priv->current_jitter, priv->avg_rate,
3648           1000000);
3649       gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS, priv->rendered,
3650           priv->dropped);
3651       gst_element_post_message (GST_ELEMENT_CAST (basesink), qos_msg);
3652     }
3653     goto done;
3654   }
3655 preroll_failed:
3656   {
3657     GST_DEBUG_OBJECT (basesink, "preroll failed: %s", gst_flow_get_name (ret));
3658     return ret;
3659   }
3660 }
3661
3662 /* with STREAM_LOCK
3663  */
3664 static GstFlowReturn
3665 gst_base_sink_chain_main (GstBaseSink * basesink, GstPad * pad, gpointer obj,
3666     gboolean is_list)
3667 {
3668   GstFlowReturn result;
3669
3670   if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PUSH))
3671     goto wrong_mode;
3672
3673   GST_BASE_SINK_PREROLL_LOCK (basesink);
3674   result = gst_base_sink_chain_unlocked (basesink, pad, obj, is_list);
3675   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3676
3677 done:
3678   return result;
3679
3680   /* ERRORS */
3681 wrong_mode:
3682   {
3683     GST_OBJECT_LOCK (pad);
3684     GST_WARNING_OBJECT (basesink,
3685         "Push on pad %s:%s, but it was not activated in push mode",
3686         GST_DEBUG_PAD_NAME (pad));
3687     GST_OBJECT_UNLOCK (pad);
3688     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3689     /* we don't post an error message this will signal to the peer
3690      * pushing that EOS is reached. */
3691     result = GST_FLOW_EOS;
3692     goto done;
3693   }
3694 }
3695
3696 static GstFlowReturn
3697 gst_base_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
3698 {
3699   GstBaseSink *basesink;
3700
3701   basesink = GST_BASE_SINK (parent);
3702
3703   return gst_base_sink_chain_main (basesink, pad, buf, FALSE);
3704 }
3705
3706 static GstFlowReturn
3707 gst_base_sink_chain_list (GstPad * pad, GstObject * parent,
3708     GstBufferList * list)
3709 {
3710   GstBaseSink *basesink;
3711   GstBaseSinkClass *bclass;
3712   GstFlowReturn result;
3713
3714   basesink = GST_BASE_SINK (parent);
3715   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3716
3717   if (G_LIKELY (bclass->render_list)) {
3718     result = gst_base_sink_chain_main (basesink, pad, list, TRUE);
3719   } else {
3720     guint i, len;
3721     GstBuffer *buffer;
3722
3723     GST_LOG_OBJECT (pad, "chaining each buffer in list");
3724
3725     len = gst_buffer_list_length (list);
3726
3727     result = GST_FLOW_OK;
3728     for (i = 0; i < len; i++) {
3729       buffer = gst_buffer_list_get (list, i);
3730       result = gst_base_sink_chain_main (basesink, pad,
3731           gst_buffer_ref (buffer), FALSE);
3732       if (result != GST_FLOW_OK)
3733         break;
3734     }
3735     gst_buffer_list_unref (list);
3736   }
3737   return result;
3738 }
3739
3740
3741 static gboolean
3742 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
3743 {
3744   gboolean res = TRUE;
3745
3746   /* update our offset if the start/stop position was updated */
3747   if (segment->format == GST_FORMAT_BYTES) {
3748     segment->time = segment->start;
3749   } else if (segment->start == 0) {
3750     /* seek to start, we can implement a default for this. */
3751     segment->time = 0;
3752   } else {
3753     res = FALSE;
3754     GST_INFO_OBJECT (sink, "Can't do a default seek");
3755   }
3756
3757   return res;
3758 }
3759
3760 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
3761
3762 static gboolean
3763 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3764     GstEvent * event, GstSegment * segment)
3765 {
3766   /* By default, we try one of 2 things:
3767    *   - For absolute seek positions, convert the requested position to our
3768    *     configured processing format and place it in the output segment \
3769    *   - For relative seek positions, convert our current (input) values to the
3770    *     seek format, adjust by the relative seek offset and then convert back to
3771    *     the processing format
3772    */
3773   GstSeekType start_type, stop_type;
3774   gint64 start, stop;
3775   GstSeekFlags flags;
3776   GstFormat seek_format;
3777   gdouble rate;
3778   gboolean update;
3779   gboolean res = TRUE;
3780
3781   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3782       &start_type, &start, &stop_type, &stop);
3783
3784   if (seek_format == segment->format) {
3785     gst_segment_do_seek (segment, rate, seek_format, flags,
3786         start_type, start, stop_type, stop, &update);
3787     return TRUE;
3788   }
3789
3790   if (start_type != GST_SEEK_TYPE_NONE) {
3791     /* FIXME: Handle seek_end by converting the input segment vals */
3792     res =
3793         gst_pad_query_convert (sink->sinkpad, seek_format, start,
3794         segment->format, &start);
3795     start_type = GST_SEEK_TYPE_SET;
3796   }
3797
3798   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3799     /* FIXME: Handle seek_end by converting the input segment vals */
3800     res =
3801         gst_pad_query_convert (sink->sinkpad, seek_format, stop,
3802         segment->format, &stop);
3803     stop_type = GST_SEEK_TYPE_SET;
3804   }
3805
3806   /* And finally, configure our output segment in the desired format */
3807   gst_segment_do_seek (segment, rate, segment->format, flags, start_type, start,
3808       stop_type, stop, &update);
3809
3810   if (!res)
3811     goto no_format;
3812
3813   return res;
3814
3815 no_format:
3816   {
3817     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3818     return FALSE;
3819   }
3820 }
3821
3822 /* perform a seek, only executed in pull mode */
3823 static gboolean
3824 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3825 {
3826   gboolean flush;
3827   gdouble rate;
3828   GstFormat seek_format, dest_format;
3829   GstSeekFlags flags;
3830   GstSeekType start_type, stop_type;
3831   gboolean seekseg_configured = FALSE;
3832   gint64 start, stop;
3833   gboolean update, res = TRUE;
3834   GstSegment seeksegment;
3835
3836   dest_format = sink->segment.format;
3837
3838   if (event) {
3839     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3840     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3841         &start_type, &start, &stop_type, &stop);
3842
3843     flush = flags & GST_SEEK_FLAG_FLUSH;
3844   } else {
3845     GST_DEBUG_OBJECT (sink, "performing seek without event");
3846     flush = FALSE;
3847   }
3848
3849   if (flush) {
3850     GST_DEBUG_OBJECT (sink, "flushing upstream");
3851     gst_pad_push_event (pad, gst_event_new_flush_start ());
3852     gst_base_sink_flush_start (sink, pad);
3853   } else {
3854     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3855   }
3856
3857   GST_PAD_STREAM_LOCK (pad);
3858
3859   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3860    * copy the current segment info into the temp segment that we can actually
3861    * attempt the seek with. We only update the real segment if the seek succeeds. */
3862   if (!seekseg_configured) {
3863     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3864
3865     /* now configure the final seek segment */
3866     if (event) {
3867       if (sink->segment.format != seek_format) {
3868         /* OK, here's where we give the subclass a chance to convert the relative
3869          * seek into an absolute one in the processing format. We set up any
3870          * absolute seek above, before taking the stream lock. */
3871         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3872                 &seeksegment)) {
3873           GST_DEBUG_OBJECT (sink,
3874               "Preparing the seek failed after flushing. " "Aborting seek");
3875           res = FALSE;
3876         }
3877       } else {
3878         /* The seek format matches our processing format, no need to ask the
3879          * the subclass to configure the segment. */
3880         gst_segment_do_seek (&seeksegment, rate, seek_format, flags,
3881             start_type, start, stop_type, stop, &update);
3882       }
3883     }
3884     /* Else, no seek event passed, so we're just (re)starting the
3885        current segment. */
3886   }
3887
3888   if (res) {
3889     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3890         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3891         seeksegment.start, seeksegment.stop, seeksegment.position);
3892
3893     /* do the seek, segment.position contains the new position. */
3894     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3895   }
3896
3897   if (flush) {
3898     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
3899     gst_pad_push_event (pad, gst_event_new_flush_stop (TRUE));
3900     gst_base_sink_flush_stop (sink, pad, TRUE);
3901   } else if (res && sink->running) {
3902     /* we are running the current segment and doing a non-flushing seek,
3903      * close the segment first based on the position. */
3904     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
3905         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.position);
3906   }
3907
3908   /* The subclass must have converted the segment to the processing format
3909    * by now */
3910   if (res && seeksegment.format != dest_format) {
3911     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
3912         "in the correct format. Aborting seek.");
3913     res = FALSE;
3914   }
3915
3916   GST_INFO_OBJECT (sink, "seeking done %d: %" GST_SEGMENT_FORMAT, res,
3917       &seeksegment);
3918
3919   /* if successful seek, we update our real segment and push
3920    * out the new segment. */
3921   if (res) {
3922     gst_segment_copy_into (&seeksegment, &sink->segment);
3923
3924     if (sink->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
3925       gst_element_post_message (GST_ELEMENT (sink),
3926           gst_message_new_segment_start (GST_OBJECT (sink),
3927               sink->segment.format, sink->segment.position));
3928     }
3929   }
3930
3931   sink->priv->discont = TRUE;
3932   sink->running = TRUE;
3933
3934   GST_PAD_STREAM_UNLOCK (pad);
3935
3936   return res;
3937 }
3938
3939 static void
3940 set_step_info (GstBaseSink * sink, GstStepInfo * current, GstStepInfo * pending,
3941     guint seqnum, GstFormat format, guint64 amount, gdouble rate,
3942     gboolean flush, gboolean intermediate)
3943 {
3944   GST_OBJECT_LOCK (sink);
3945   pending->seqnum = seqnum;
3946   pending->format = format;
3947   pending->amount = amount;
3948   pending->position = 0;
3949   pending->rate = rate;
3950   pending->flush = flush;
3951   pending->intermediate = intermediate;
3952   pending->valid = TRUE;
3953   /* flush invalidates the current stepping segment */
3954   if (flush)
3955     current->valid = FALSE;
3956   GST_OBJECT_UNLOCK (sink);
3957 }
3958
3959 static gboolean
3960 gst_base_sink_perform_step (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3961 {
3962   GstBaseSinkPrivate *priv;
3963   GstBaseSinkClass *bclass;
3964   gboolean flush, intermediate;
3965   gdouble rate;
3966   GstFormat format;
3967   guint64 amount;
3968   guint seqnum;
3969   GstStepInfo *pending, *current;
3970   GstMessage *message;
3971
3972   bclass = GST_BASE_SINK_GET_CLASS (sink);
3973   priv = sink->priv;
3974
3975   GST_DEBUG_OBJECT (sink, "performing step with event %p", event);
3976
3977   gst_event_parse_step (event, &format, &amount, &rate, &flush, &intermediate);
3978   seqnum = gst_event_get_seqnum (event);
3979
3980   pending = &priv->pending_step;
3981   current = &priv->current_step;
3982
3983   /* post message first */
3984   message = gst_message_new_step_start (GST_OBJECT (sink), FALSE, format,
3985       amount, rate, flush, intermediate);
3986   gst_message_set_seqnum (message, seqnum);
3987   gst_element_post_message (GST_ELEMENT (sink), message);
3988
3989   if (flush) {
3990     /* we need to call ::unlock before locking PREROLL_LOCK
3991      * since we lock it before going into ::render */
3992     if (bclass->unlock)
3993       bclass->unlock (sink);
3994
3995     GST_BASE_SINK_PREROLL_LOCK (sink);
3996     /* now that we have the PREROLL lock, clear our unlock request */
3997     if (bclass->unlock_stop)
3998       bclass->unlock_stop (sink);
3999
4000     /* update the stepinfo and make it valid */
4001     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
4002         intermediate);
4003
4004     if (sink->priv->async_enabled) {
4005       /* and we need to commit our state again on the next
4006        * prerolled buffer */
4007       sink->playing_async = TRUE;
4008       priv->pending_step.need_preroll = TRUE;
4009       sink->need_preroll = FALSE;
4010       gst_base_sink_update_start_time (sink);
4011       gst_element_lost_state (GST_ELEMENT_CAST (sink));
4012     } else {
4013       sink->priv->have_latency = TRUE;
4014       sink->need_preroll = FALSE;
4015     }
4016     priv->current_sstart = GST_CLOCK_TIME_NONE;
4017     priv->current_sstop = GST_CLOCK_TIME_NONE;
4018     priv->eos_rtime = GST_CLOCK_TIME_NONE;
4019     priv->call_preroll = TRUE;
4020     gst_base_sink_set_last_buffer (sink, NULL);
4021     gst_base_sink_set_last_buffer_list (sink, NULL);
4022     gst_base_sink_reset_qos (sink);
4023
4024     if (sink->clock_id) {
4025       gst_clock_id_unschedule (sink->clock_id);
4026     }
4027
4028     if (sink->have_preroll) {
4029       GST_DEBUG_OBJECT (sink, "signal waiter");
4030       priv->step_unlock = TRUE;
4031       GST_BASE_SINK_PREROLL_SIGNAL (sink);
4032     }
4033     GST_BASE_SINK_PREROLL_UNLOCK (sink);
4034   } else {
4035     /* update the stepinfo and make it valid */
4036     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
4037         intermediate);
4038   }
4039
4040   return TRUE;
4041 }
4042
4043 /* with STREAM_LOCK
4044  */
4045 static void
4046 gst_base_sink_loop (GstPad * pad)
4047 {
4048   GstObject *parent;
4049   GstBaseSink *basesink;
4050   GstBuffer *buf = NULL;
4051   GstFlowReturn result;
4052   guint blocksize;
4053   guint64 offset;
4054
4055   parent = GST_OBJECT_PARENT (pad);
4056   basesink = GST_BASE_SINK (parent);
4057
4058   g_assert (basesink->pad_mode == GST_PAD_MODE_PULL);
4059
4060   if ((blocksize = basesink->priv->blocksize) == 0)
4061     blocksize = -1;
4062
4063   offset = basesink->segment.position;
4064
4065   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
4066       offset, blocksize);
4067
4068   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
4069   if (G_UNLIKELY (result != GST_FLOW_OK))
4070     goto paused;
4071
4072   if (G_UNLIKELY (buf == NULL))
4073     goto no_buffer;
4074
4075   offset += gst_buffer_get_size (buf);
4076
4077   basesink->segment.position = offset;
4078
4079   GST_BASE_SINK_PREROLL_LOCK (basesink);
4080   result = gst_base_sink_chain_unlocked (basesink, pad, buf, FALSE);
4081   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4082   if (G_UNLIKELY (result != GST_FLOW_OK))
4083     goto paused;
4084
4085   return;
4086
4087   /* ERRORS */
4088 paused:
4089   {
4090     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
4091         gst_flow_get_name (result));
4092     gst_pad_pause_task (pad);
4093     if (result == GST_FLOW_EOS) {
4094       /* perform EOS logic */
4095       if (basesink->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
4096         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4097             gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
4098                 basesink->segment.format, basesink->segment.position));
4099         gst_base_sink_event (pad, parent,
4100             gst_event_new_segment_done (basesink->segment.format,
4101                 basesink->segment.position));
4102       } else {
4103         gst_base_sink_event (pad, parent, gst_event_new_eos ());
4104       }
4105     } else if (result == GST_FLOW_NOT_LINKED || result <= GST_FLOW_EOS) {
4106       /* for fatal errors we post an error message, post the error
4107        * first so the app knows about the error first. 
4108        * wrong-state is not a fatal error because it happens due to
4109        * flushing and posting an error message in that case is the
4110        * wrong thing to do, e.g. when basesrc is doing a flushing
4111        * seek. */
4112       GST_ELEMENT_FLOW_ERROR (basesink, result);
4113       gst_base_sink_event (pad, parent, gst_event_new_eos ());
4114     }
4115     return;
4116   }
4117 no_buffer:
4118   {
4119     GST_LOG_OBJECT (basesink, "no buffer, pausing");
4120     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
4121         (_("Internal data flow error.")), ("element returned NULL buffer"));
4122     result = GST_FLOW_ERROR;
4123     goto paused;
4124   }
4125 }
4126
4127 static gboolean
4128 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
4129     gboolean flushing)
4130 {
4131   GstBaseSinkClass *bclass;
4132
4133   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4134
4135   if (flushing) {
4136     /* unlock any subclasses, we need to do this before grabbing the
4137      * PREROLL_LOCK since we hold this lock before going into ::render. */
4138     if (bclass->unlock)
4139       bclass->unlock (basesink);
4140   }
4141
4142   GST_BASE_SINK_PREROLL_LOCK (basesink);
4143   basesink->flushing = flushing;
4144   if (flushing) {
4145     /* step 1, now that we have the PREROLL lock, clear our unlock request */
4146     if (bclass->unlock_stop)
4147       bclass->unlock_stop (basesink);
4148
4149     /* set need_preroll before we unblock the clock. If the clock is unblocked
4150      * before timing out, we can reuse the buffer for preroll. */
4151     basesink->need_preroll = TRUE;
4152
4153     /* step 2, unblock clock sync (if any) or any other blocking thing */
4154     if (basesink->clock_id) {
4155       gst_clock_id_unschedule (basesink->clock_id);
4156     }
4157
4158     /* flush out the data thread if it's locked in finish_preroll, this will
4159      * also flush out the EOS state */
4160     GST_DEBUG_OBJECT (basesink,
4161         "flushing out data thread, need preroll to TRUE");
4162
4163     /* we can't have EOS anymore now */
4164     basesink->eos = FALSE;
4165     basesink->priv->received_eos = FALSE;
4166     basesink->have_preroll = FALSE;
4167     basesink->priv->step_unlock = FALSE;
4168     /* can't report latency anymore until we preroll again */
4169     if (basesink->priv->async_enabled) {
4170       GST_OBJECT_LOCK (basesink);
4171       basesink->priv->have_latency = FALSE;
4172       GST_OBJECT_UNLOCK (basesink);
4173     }
4174     /* and signal any waiters now */
4175     GST_BASE_SINK_PREROLL_SIGNAL (basesink);
4176   }
4177   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4178
4179   return TRUE;
4180 }
4181
4182 static gboolean
4183 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
4184 {
4185   gboolean result;
4186
4187   if (active) {
4188     /* start task */
4189     result = gst_pad_start_task (basesink->sinkpad,
4190         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad, NULL);
4191   } else {
4192     /* step 2, make sure streaming finishes */
4193     result = gst_pad_stop_task (basesink->sinkpad);
4194   }
4195
4196   return result;
4197 }
4198
4199 static gboolean
4200 gst_base_sink_pad_activate (GstPad * pad, GstObject * parent)
4201 {
4202   gboolean result = FALSE;
4203   GstBaseSink *basesink;
4204   GstQuery *query;
4205   gboolean pull_mode;
4206
4207   basesink = GST_BASE_SINK (parent);
4208
4209   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
4210
4211   gst_base_sink_set_flushing (basesink, pad, FALSE);
4212
4213   /* we need to have the pull mode enabled */
4214   if (!basesink->can_activate_pull) {
4215     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
4216     goto fallback;
4217   }
4218
4219   /* check if downstreams supports pull mode at all */
4220   query = gst_query_new_scheduling ();
4221
4222   if (!gst_pad_peer_query (pad, query)) {
4223     gst_query_unref (query);
4224     GST_DEBUG_OBJECT (basesink, "peer query faild, no pull mode");
4225     goto fallback;
4226   }
4227
4228   /* parse result of the query */
4229   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
4230   gst_query_unref (query);
4231
4232   if (!pull_mode) {
4233     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
4234     goto fallback;
4235   }
4236
4237   /* set the pad mode before starting the task so that it's in the
4238    * correct state for the new thread. also the sink set_caps and get_caps
4239    * function checks this */
4240   basesink->pad_mode = GST_PAD_MODE_PULL;
4241
4242   /* we first try to negotiate a format so that when we try to activate
4243    * downstream, it knows about our format */
4244   if (!gst_base_sink_negotiate_pull (basesink)) {
4245     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
4246     goto fallback;
4247   }
4248
4249   /* ok activate now */
4250   if (!gst_pad_activate_mode (pad, GST_PAD_MODE_PULL, TRUE)) {
4251     /* clear any pending caps */
4252     GST_OBJECT_LOCK (basesink);
4253     gst_caps_replace (&basesink->priv->caps, NULL);
4254     GST_OBJECT_UNLOCK (basesink);
4255     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
4256     goto fallback;
4257   }
4258
4259   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
4260   result = TRUE;
4261   goto done;
4262
4263   /* push mode fallback */
4264 fallback:
4265   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
4266   if ((result = gst_pad_activate_mode (pad, GST_PAD_MODE_PUSH, TRUE))) {
4267     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
4268   }
4269
4270 done:
4271   if (!result) {
4272     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
4273     gst_base_sink_set_flushing (basesink, pad, TRUE);
4274   }
4275
4276   return result;
4277 }
4278
4279 static gboolean
4280 gst_base_sink_pad_activate_push (GstPad * pad, GstObject * parent,
4281     gboolean active)
4282 {
4283   gboolean result;
4284   GstBaseSink *basesink;
4285
4286   basesink = GST_BASE_SINK (parent);
4287
4288   if (active) {
4289     if (!basesink->can_activate_push) {
4290       result = FALSE;
4291       basesink->pad_mode = GST_PAD_MODE_NONE;
4292     } else {
4293       result = TRUE;
4294       basesink->pad_mode = GST_PAD_MODE_PUSH;
4295     }
4296   } else {
4297     if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PUSH)) {
4298       g_warning ("Internal GStreamer activation error!!!");
4299       result = FALSE;
4300     } else {
4301       gst_base_sink_set_flushing (basesink, pad, TRUE);
4302       result = TRUE;
4303       basesink->pad_mode = GST_PAD_MODE_NONE;
4304     }
4305   }
4306
4307   return result;
4308 }
4309
4310 static gboolean
4311 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
4312 {
4313   GstCaps *caps;
4314   gboolean result;
4315
4316   result = FALSE;
4317
4318   /* this returns the intersection between our caps and the peer caps. If there
4319    * is no peer, it returns %NULL and we can't operate in pull mode so we can
4320    * fail the negotiation. */
4321   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
4322   if (caps == NULL || gst_caps_is_empty (caps))
4323     goto no_caps_possible;
4324
4325   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
4326
4327   if (gst_caps_is_any (caps)) {
4328     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
4329         "allowing pull()");
4330     /* neither side has template caps in this case, so they are prepared for
4331        pull() without setcaps() */
4332     result = TRUE;
4333   } else {
4334     /* try to fixate */
4335     caps = gst_base_sink_fixate (basesink, caps);
4336     GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
4337
4338     if (gst_caps_is_fixed (caps)) {
4339       if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
4340         goto could_not_set_caps;
4341
4342       result = TRUE;
4343     }
4344   }
4345
4346   gst_caps_unref (caps);
4347
4348   return result;
4349
4350 no_caps_possible:
4351   {
4352     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
4353     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
4354     if (caps)
4355       gst_caps_unref (caps);
4356     return FALSE;
4357   }
4358 could_not_set_caps:
4359   {
4360     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
4361     gst_caps_unref (caps);
4362     return FALSE;
4363   }
4364 }
4365
4366 /* this won't get called until we implement an activate function */
4367 static gboolean
4368 gst_base_sink_pad_activate_pull (GstPad * pad, GstObject * parent,
4369     gboolean active)
4370 {
4371   gboolean result = FALSE;
4372   GstBaseSink *basesink;
4373   GstBaseSinkClass *bclass;
4374
4375   basesink = GST_BASE_SINK (parent);
4376   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4377
4378   if (active) {
4379     gint64 duration;
4380
4381     /* we mark we have a newsegment here because pull based
4382      * mode works just fine without having a newsegment before the
4383      * first buffer */
4384     gst_segment_init (&basesink->segment, GST_FORMAT_BYTES);
4385     GST_OBJECT_LOCK (basesink);
4386     basesink->have_newsegment = TRUE;
4387     GST_OBJECT_UNLOCK (basesink);
4388
4389     /* get the peer duration in bytes */
4390     result = gst_pad_peer_query_duration (pad, GST_FORMAT_BYTES, &duration);
4391     if (result) {
4392       GST_DEBUG_OBJECT (basesink,
4393           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
4394       basesink->segment.duration = duration;
4395     } else {
4396       GST_DEBUG_OBJECT (basesink, "unknown duration");
4397     }
4398
4399     if (bclass->activate_pull)
4400       result = bclass->activate_pull (basesink, TRUE);
4401     else
4402       result = FALSE;
4403
4404     if (!result)
4405       goto activate_failed;
4406
4407   } else {
4408     if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PULL)) {
4409       g_warning ("Internal GStreamer activation error!!!");
4410       result = FALSE;
4411     } else {
4412       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
4413       if (bclass->activate_pull)
4414         result &= bclass->activate_pull (basesink, FALSE);
4415       basesink->pad_mode = GST_PAD_MODE_NONE;
4416     }
4417   }
4418
4419   return result;
4420
4421   /* ERRORS */
4422 activate_failed:
4423   {
4424     /* reset, as starting the thread failed */
4425     basesink->pad_mode = GST_PAD_MODE_NONE;
4426
4427     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
4428     return FALSE;
4429   }
4430 }
4431
4432 static gboolean
4433 gst_base_sink_pad_activate_mode (GstPad * pad, GstObject * parent,
4434     GstPadMode mode, gboolean active)
4435 {
4436   gboolean res;
4437
4438   switch (mode) {
4439     case GST_PAD_MODE_PULL:
4440       res = gst_base_sink_pad_activate_pull (pad, parent, active);
4441       break;
4442     case GST_PAD_MODE_PUSH:
4443       res = gst_base_sink_pad_activate_push (pad, parent, active);
4444       break;
4445     default:
4446       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
4447       res = FALSE;
4448       break;
4449   }
4450   return res;
4451 }
4452
4453 /* send an event to our sinkpad peer. */
4454 static gboolean
4455 gst_base_sink_send_event (GstElement * element, GstEvent * event)
4456 {
4457   GstPad *pad;
4458   GstBaseSink *basesink = GST_BASE_SINK (element);
4459   gboolean forward, result = TRUE;
4460   GstPadMode mode;
4461
4462   GST_OBJECT_LOCK (element);
4463   /* get the pad and the scheduling mode */
4464   pad = gst_object_ref (basesink->sinkpad);
4465   mode = basesink->pad_mode;
4466   GST_OBJECT_UNLOCK (element);
4467
4468   /* only push UPSTREAM events upstream */
4469   forward = GST_EVENT_IS_UPSTREAM (event);
4470
4471   GST_DEBUG_OBJECT (basesink, "handling event %p %" GST_PTR_FORMAT, event,
4472       event);
4473
4474   switch (GST_EVENT_TYPE (event)) {
4475     case GST_EVENT_LATENCY:
4476     {
4477       GstClockTime latency;
4478
4479       gst_event_parse_latency (event, &latency);
4480
4481       /* store the latency. We use this to adjust the running_time before syncing
4482        * it to the clock. */
4483       GST_OBJECT_LOCK (element);
4484       basesink->priv->latency = latency;
4485       if (!basesink->priv->have_latency)
4486         forward = FALSE;
4487       GST_OBJECT_UNLOCK (element);
4488       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
4489           GST_TIME_ARGS (latency));
4490
4491       /* We forward this event so that all elements know about the global pipeline
4492        * latency. This is interesting for an element when it wants to figure out
4493        * when a particular piece of data will be rendered. */
4494       break;
4495     }
4496     case GST_EVENT_SEEK:
4497       /* in pull mode we will execute the seek */
4498       if (mode == GST_PAD_MODE_PULL)
4499         result = gst_base_sink_perform_seek (basesink, pad, event);
4500       break;
4501     case GST_EVENT_STEP:
4502       result = gst_base_sink_perform_step (basesink, pad, event);
4503       forward = FALSE;
4504       break;
4505     default:
4506       break;
4507   }
4508
4509   if (forward) {
4510     GST_DEBUG_OBJECT (basesink, "sending event %p %" GST_PTR_FORMAT, event,
4511         event);
4512     result = gst_pad_push_event (pad, event);
4513   } else {
4514     /* not forwarded, unref the event */
4515     gst_event_unref (event);
4516   }
4517
4518   gst_object_unref (pad);
4519
4520   GST_DEBUG_OBJECT (basesink, "handled event: %d", result);
4521
4522   return result;
4523 }
4524
4525 static gboolean
4526 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
4527     gint64 * cur, gboolean * upstream)
4528 {
4529   GstClock *clock = NULL;
4530   gboolean res = FALSE;
4531   GstFormat oformat;
4532   GstSegment *segment;
4533   GstClockTime now, latency;
4534   GstClockTimeDiff base_time;
4535   gint64 time, base, duration;
4536   gdouble rate;
4537   gint64 last;
4538   gboolean last_seen, with_clock, in_paused;
4539
4540   GST_OBJECT_LOCK (basesink);
4541   /* we can only get the segment when we are not NULL or READY */
4542   if (!basesink->have_newsegment)
4543     goto wrong_state;
4544
4545   in_paused = FALSE;
4546   /* when not in PLAYING or when we're busy with a state change, we
4547    * cannot read from the clock so we report time based on the
4548    * last seen timestamp. */
4549   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
4550       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING) {
4551     in_paused = TRUE;
4552   }
4553
4554   segment = &basesink->segment;
4555
4556   /* get the format in the segment */
4557   oformat = segment->format;
4558
4559   /* report with last seen position when EOS */
4560   last_seen = basesink->eos;
4561
4562   /* assume we will use the clock for getting the current position */
4563   with_clock = TRUE;
4564   if (!basesink->sync)
4565     with_clock = FALSE;
4566
4567   /* and we need a clock */
4568   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
4569     with_clock = FALSE;
4570   else
4571     gst_object_ref (clock);
4572
4573   /* mainloop might be querying position when going to playing async,
4574    * while (audio) rendering might be quickly advancing stream position,
4575    * so use clock asap rather than last reported position */
4576   if (in_paused && with_clock && g_atomic_int_get (&basesink->priv->to_playing)) {
4577     GST_DEBUG_OBJECT (basesink, "going to PLAYING, so not PAUSED");
4578     in_paused = FALSE;
4579   }
4580
4581   /* collect all data we need holding the lock */
4582   if (GST_CLOCK_TIME_IS_VALID (segment->time))
4583     time = segment->time;
4584   else
4585     time = 0;
4586
4587   if (GST_CLOCK_TIME_IS_VALID (segment->stop))
4588     duration = segment->stop - segment->start;
4589   else
4590     duration = 0;
4591
4592   base = segment->base;
4593   rate = segment->rate * segment->applied_rate;
4594   latency = basesink->priv->latency;
4595
4596   if (in_paused) {
4597     /* in paused, use start_time */
4598     base_time = GST_ELEMENT_START_TIME (basesink);
4599     GST_DEBUG_OBJECT (basesink, "in paused, using start time %" GST_TIME_FORMAT,
4600         GST_TIME_ARGS (base_time));
4601   } else if (with_clock) {
4602     /* else use clock when needed */
4603     base_time = GST_ELEMENT_CAST (basesink)->base_time;
4604     GST_DEBUG_OBJECT (basesink, "using clock and base time %" GST_TIME_FORMAT,
4605         GST_TIME_ARGS (base_time));
4606   } else {
4607     /* else, no sync or clock -> no base time */
4608     GST_DEBUG_OBJECT (basesink, "no sync or no clock");
4609     base_time = -1;
4610   }
4611
4612   /* no base_time, we can't calculate running_time, use last seem timestamp to report
4613    * time */
4614   if (base_time == -1)
4615     last_seen = TRUE;
4616
4617   if (oformat == GST_FORMAT_TIME) {
4618     gint64 start, stop;
4619
4620     start = basesink->priv->current_sstart;
4621     stop = basesink->priv->current_sstop;
4622
4623     if (last_seen) {
4624       /* when we don't use the clock, we use the last position as a lower bound */
4625       if (stop == -1 || segment->rate > 0.0)
4626         last = start;
4627       else
4628         last = stop;
4629
4630       GST_DEBUG_OBJECT (basesink, "in PAUSED using last %" GST_TIME_FORMAT,
4631           GST_TIME_ARGS (last));
4632     } else {
4633       /* in playing and paused, use last stop time as upper bound */
4634       if (start == -1 || segment->rate > 0.0)
4635         last = stop;
4636       else
4637         last = start;
4638
4639       GST_DEBUG_OBJECT (basesink, "in PLAYING using last %" GST_TIME_FORMAT,
4640           GST_TIME_ARGS (last));
4641     }
4642   } else {
4643     /* convert position to stream time */
4644     last = gst_segment_to_stream_time (segment, oformat, segment->position);
4645
4646     GST_DEBUG_OBJECT (basesink, "in using last %" G_GINT64_FORMAT, last);
4647   }
4648
4649   /* need to release the object lock before we can get the time,
4650    * a clock might take the LOCK of the provider, which could be
4651    * a basesink subclass. */
4652   GST_OBJECT_UNLOCK (basesink);
4653
4654   if (last_seen) {
4655     /* in EOS or when no valid stream_time, report the value of last seen
4656      * timestamp */
4657     if (last == -1) {
4658       /* no timestamp, we need to ask upstream */
4659       GST_DEBUG_OBJECT (basesink, "no last seen timestamp, asking upstream");
4660       res = FALSE;
4661       *upstream = TRUE;
4662       goto done;
4663     }
4664     GST_DEBUG_OBJECT (basesink, "using last seen timestamp %" GST_TIME_FORMAT,
4665         GST_TIME_ARGS (last));
4666     *cur = last;
4667   } else {
4668     if (oformat != GST_FORMAT_TIME) {
4669       /* convert base, time and duration to time */
4670       if (!gst_pad_query_convert (basesink->sinkpad, oformat, base,
4671               GST_FORMAT_TIME, &base))
4672         goto convert_failed;
4673       if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration,
4674               GST_FORMAT_TIME, &duration))
4675         goto convert_failed;
4676       if (!gst_pad_query_convert (basesink->sinkpad, oformat, time,
4677               GST_FORMAT_TIME, &time))
4678         goto convert_failed;
4679       if (!gst_pad_query_convert (basesink->sinkpad, oformat, last,
4680               GST_FORMAT_TIME, &last))
4681         goto convert_failed;
4682
4683       /* assume time format from now on */
4684       oformat = GST_FORMAT_TIME;
4685     }
4686
4687     if (!in_paused && with_clock) {
4688       now = gst_clock_get_time (clock);
4689     } else {
4690       now = base_time;
4691       base_time = 0;
4692     }
4693
4694     /* subtract base time and base time from the clock time.
4695      * Make sure we don't go negative. This is the current time in
4696      * the segment which we need to scale with the combined
4697      * rate and applied rate. */
4698     base_time += base;
4699     base_time += latency;
4700     if (GST_CLOCK_DIFF (base_time, now) < 0)
4701       base_time = now;
4702
4703     /* for negative rates we need to count back from the segment
4704      * duration. */
4705     if (rate < 0.0)
4706       time += duration;
4707
4708     *cur = time + gst_guint64_to_gdouble (now - base_time) * rate;
4709
4710     /* never report more than last seen position */
4711     if (last != -1) {
4712       if (rate > 0.0)
4713         *cur = MIN (last, *cur);
4714       else
4715         *cur = MAX (last, *cur);
4716     }
4717
4718     GST_DEBUG_OBJECT (basesink,
4719         "now %" GST_TIME_FORMAT " - base_time %" GST_TIME_FORMAT " - base %"
4720         GST_TIME_FORMAT " + time %" GST_TIME_FORMAT "  last %" GST_TIME_FORMAT,
4721         GST_TIME_ARGS (now), GST_TIME_ARGS (base_time), GST_TIME_ARGS (base),
4722         GST_TIME_ARGS (time), GST_TIME_ARGS (last));
4723   }
4724
4725   if (oformat != format) {
4726     /* convert to final format */
4727     if (!gst_pad_query_convert (basesink->sinkpad, oformat, *cur, format, cur))
4728       goto convert_failed;
4729   }
4730
4731   res = TRUE;
4732
4733 done:
4734   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
4735       res, GST_TIME_ARGS (*cur));
4736
4737   if (clock)
4738     gst_object_unref (clock);
4739
4740   return res;
4741
4742   /* special cases */
4743 wrong_state:
4744   {
4745     /* in NULL or READY we always return FALSE and -1 */
4746     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
4747     res = FALSE;
4748     *cur = -1;
4749     GST_OBJECT_UNLOCK (basesink);
4750     goto done;
4751   }
4752 convert_failed:
4753   {
4754     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
4755     *upstream = TRUE;
4756     res = FALSE;
4757     goto done;
4758   }
4759 }
4760
4761 static gboolean
4762 gst_base_sink_get_duration (GstBaseSink * basesink, GstFormat format,
4763     gint64 * dur, gboolean * upstream)
4764 {
4765   gboolean res = FALSE;
4766
4767   if (basesink->pad_mode == GST_PAD_MODE_PULL) {
4768     gint64 uduration;
4769
4770     /* get the duration in bytes, in pull mode that's all we are sure to
4771      * know. We have to explicitly get this value from upstream instead of
4772      * using our cached value because it might change. Duration caching
4773      * should be done at a higher level. */
4774     res =
4775         gst_pad_peer_query_duration (basesink->sinkpad, GST_FORMAT_BYTES,
4776         &uduration);
4777     if (res) {
4778       basesink->segment.duration = uduration;
4779       if (format != GST_FORMAT_BYTES) {
4780         /* convert to the requested format */
4781         res =
4782             gst_pad_query_convert (basesink->sinkpad, GST_FORMAT_BYTES,
4783             uduration, format, dur);
4784       } else {
4785         *dur = uduration;
4786       }
4787     }
4788     *upstream = FALSE;
4789   } else {
4790     *upstream = TRUE;
4791   }
4792
4793   return res;
4794 }
4795
4796 static gboolean
4797 default_element_query (GstElement * element, GstQuery * query)
4798 {
4799   gboolean res = FALSE;
4800
4801   GstBaseSink *basesink = GST_BASE_SINK (element);
4802
4803   switch (GST_QUERY_TYPE (query)) {
4804     case GST_QUERY_POSITION:
4805     {
4806       gint64 cur = 0;
4807       GstFormat format;
4808       gboolean upstream = FALSE;
4809
4810       gst_query_parse_position (query, &format, NULL);
4811
4812       GST_DEBUG_OBJECT (basesink, "position query in format %s",
4813           gst_format_get_name (format));
4814
4815       /* first try to get the position based on the clock */
4816       if ((res =
4817               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
4818         gst_query_set_position (query, format, cur);
4819       } else if (upstream) {
4820         /* fallback to peer query */
4821         res = gst_pad_peer_query (basesink->sinkpad, query);
4822       }
4823       if (!res) {
4824         /* we can handle a few things if upstream failed */
4825         if (format == GST_FORMAT_PERCENT) {
4826           gint64 dur = 0;
4827
4828           res = gst_base_sink_get_position (basesink, GST_FORMAT_TIME, &cur,
4829               &upstream);
4830           if (!res && upstream) {
4831             res =
4832                 gst_pad_peer_query_position (basesink->sinkpad, GST_FORMAT_TIME,
4833                 &cur);
4834           }
4835           if (res) {
4836             res = gst_base_sink_get_duration (basesink, GST_FORMAT_TIME, &dur,
4837                 &upstream);
4838             if (!res && upstream) {
4839               res =
4840                   gst_pad_peer_query_duration (basesink->sinkpad,
4841                   GST_FORMAT_TIME, &dur);
4842             }
4843           }
4844           if (res) {
4845             gint64 pos;
4846
4847             pos = gst_util_uint64_scale (100 * GST_FORMAT_PERCENT_SCALE, cur,
4848                 dur);
4849             gst_query_set_position (query, GST_FORMAT_PERCENT, pos);
4850           }
4851         }
4852       }
4853       break;
4854     }
4855     case GST_QUERY_DURATION:
4856     {
4857       gint64 dur = 0;
4858       GstFormat format;
4859       gboolean upstream = FALSE;
4860
4861       gst_query_parse_duration (query, &format, NULL);
4862
4863       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
4864           gst_format_get_name (format));
4865
4866       if ((res =
4867               gst_base_sink_get_duration (basesink, format, &dur, &upstream))) {
4868         gst_query_set_duration (query, format, dur);
4869       } else if (upstream) {
4870         /* fallback to peer query */
4871         res = gst_pad_peer_query (basesink->sinkpad, query);
4872       }
4873       if (!res) {
4874         /* we can handle a few things if upstream failed */
4875         if (format == GST_FORMAT_PERCENT) {
4876           gst_query_set_duration (query, GST_FORMAT_PERCENT,
4877               GST_FORMAT_PERCENT_MAX);
4878           res = TRUE;
4879         }
4880       }
4881       break;
4882     }
4883     case GST_QUERY_LATENCY:
4884     {
4885       gboolean live, us_live;
4886       GstClockTime min, max;
4887
4888       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
4889                   &max))) {
4890         gst_query_set_latency (query, live, min, max);
4891       }
4892       break;
4893     }
4894     case GST_QUERY_JITTER:
4895       break;
4896     case GST_QUERY_RATE:
4897       /* gst_query_set_rate (query, basesink->segment_rate); */
4898       res = TRUE;
4899       break;
4900     case GST_QUERY_SEGMENT:
4901     {
4902       if (basesink->pad_mode == GST_PAD_MODE_PULL) {
4903         GstFormat format;
4904         gint64 start, stop;
4905
4906         format = basesink->segment.format;
4907
4908         start =
4909             gst_segment_to_stream_time (&basesink->segment, format,
4910             basesink->segment.start);
4911         if ((stop = basesink->segment.stop) == -1)
4912           stop = basesink->segment.duration;
4913         else
4914           stop = gst_segment_to_stream_time (&basesink->segment, format, stop);
4915
4916         gst_query_set_segment (query, basesink->segment.rate, format, start,
4917             stop);
4918         res = TRUE;
4919       } else {
4920         res = gst_pad_peer_query (basesink->sinkpad, query);
4921       }
4922       break;
4923     }
4924     case GST_QUERY_SEEKING:
4925     case GST_QUERY_CONVERT:
4926     case GST_QUERY_FORMATS:
4927     default:
4928       res = gst_pad_peer_query (basesink->sinkpad, query);
4929       break;
4930   }
4931   GST_DEBUG_OBJECT (basesink, "query %s returns %d",
4932       GST_QUERY_TYPE_NAME (query), res);
4933   return res;
4934 }
4935
4936 static void
4937 gst_base_sink_drain (GstBaseSink * basesink)
4938 {
4939   GstBuffer *old;
4940   GstBufferList *old_list;
4941
4942   GST_OBJECT_LOCK (basesink);
4943   if ((old = basesink->priv->last_buffer))
4944     basesink->priv->last_buffer = gst_buffer_copy_deep (old);
4945
4946   if ((old_list = basesink->priv->last_buffer_list))
4947     basesink->priv->last_buffer_list = gst_buffer_list_copy_deep (old_list);
4948   GST_OBJECT_UNLOCK (basesink);
4949
4950   if (old)
4951     gst_buffer_unref (old);
4952   if (old_list)
4953     gst_mini_object_unref (GST_MINI_OBJECT_CAST (old_list));
4954 }
4955
4956 static gboolean
4957 gst_base_sink_default_query (GstBaseSink * basesink, GstQuery * query)
4958 {
4959   gboolean res;
4960   GstBaseSinkClass *bclass;
4961
4962   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4963
4964   switch (GST_QUERY_TYPE (query)) {
4965     case GST_QUERY_ALLOCATION:
4966     {
4967       gst_base_sink_drain (basesink);
4968       if (bclass->propose_allocation)
4969         res = bclass->propose_allocation (basesink, query);
4970       else
4971         res = FALSE;
4972       break;
4973     }
4974     case GST_QUERY_CAPS:
4975     {
4976       GstCaps *caps, *filter;
4977
4978       gst_query_parse_caps (query, &filter);
4979       caps = gst_base_sink_query_caps (basesink, basesink->sinkpad, filter);
4980       gst_query_set_caps_result (query, caps);
4981       gst_caps_unref (caps);
4982       res = TRUE;
4983       break;
4984     }
4985     case GST_QUERY_ACCEPT_CAPS:
4986     {
4987       GstCaps *caps, *allowed;
4988       gboolean subset;
4989
4990       /* slightly faster than the default implementation */
4991       gst_query_parse_accept_caps (query, &caps);
4992       allowed = gst_base_sink_query_caps (basesink, basesink->sinkpad, NULL);
4993       subset = gst_caps_is_subset (caps, allowed);
4994       GST_DEBUG_OBJECT (basesink, "Checking if requested caps %" GST_PTR_FORMAT
4995           " are a subset of pad caps %" GST_PTR_FORMAT " result %d", caps,
4996           allowed, subset);
4997       gst_caps_unref (allowed);
4998       gst_query_set_accept_caps_result (query, subset);
4999       res = TRUE;
5000       break;
5001     }
5002     case GST_QUERY_DRAIN:
5003     {
5004       gst_base_sink_drain (basesink);
5005       res = TRUE;
5006       break;
5007     }
5008     case GST_QUERY_POSITION:
5009     {
5010       res = default_element_query (GST_ELEMENT (basesink), query);
5011       break;
5012     }
5013     default:
5014       res =
5015           gst_pad_query_default (basesink->sinkpad, GST_OBJECT_CAST (basesink),
5016           query);
5017       break;
5018   }
5019   return res;
5020 }
5021
5022 static gboolean
5023 gst_base_sink_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
5024 {
5025   GstBaseSink *basesink;
5026   GstBaseSinkClass *bclass;
5027   gboolean res;
5028
5029   basesink = GST_BASE_SINK_CAST (parent);
5030   bclass = GST_BASE_SINK_GET_CLASS (basesink);
5031
5032   if (bclass->query)
5033     res = bclass->query (basesink, query);
5034   else
5035     res = FALSE;
5036
5037   return res;
5038 }
5039
5040 static GstStateChangeReturn
5041 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
5042 {
5043   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
5044   GstBaseSink *basesink = GST_BASE_SINK (element);
5045   GstBaseSinkClass *bclass;
5046   GstBaseSinkPrivate *priv;
5047
5048   priv = basesink->priv;
5049
5050   bclass = GST_BASE_SINK_GET_CLASS (basesink);
5051
5052   switch (transition) {
5053     case GST_STATE_CHANGE_NULL_TO_READY:
5054       if (bclass->start)
5055         if (!bclass->start (basesink))
5056           goto start_failed;
5057       break;
5058     case GST_STATE_CHANGE_READY_TO_PAUSED:
5059       /* need to complete preroll before this state change completes, there
5060        * is no data flow in READY so we can safely assume we need to preroll. */
5061       GST_BASE_SINK_PREROLL_LOCK (basesink);
5062       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
5063       basesink->have_newsegment = FALSE;
5064       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
5065       basesink->offset = 0;
5066       basesink->have_preroll = FALSE;
5067       priv->step_unlock = FALSE;
5068       basesink->need_preroll = TRUE;
5069       basesink->playing_async = TRUE;
5070       priv->current_sstart = GST_CLOCK_TIME_NONE;
5071       priv->current_sstop = GST_CLOCK_TIME_NONE;
5072       priv->eos_rtime = GST_CLOCK_TIME_NONE;
5073       priv->latency = 0;
5074       basesink->eos = FALSE;
5075       priv->received_eos = FALSE;
5076       gst_base_sink_reset_qos (basesink);
5077       priv->rc_next = -1;
5078       priv->commited = FALSE;
5079       priv->call_preroll = TRUE;
5080       priv->current_step.valid = FALSE;
5081       priv->pending_step.valid = FALSE;
5082       if (priv->async_enabled) {
5083         GST_DEBUG_OBJECT (basesink, "doing async state change");
5084         /* when async enabled, post async-start message and return ASYNC from
5085          * the state change function */
5086         ret = GST_STATE_CHANGE_ASYNC;
5087         gst_element_post_message (GST_ELEMENT_CAST (basesink),
5088             gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
5089       } else {
5090         priv->have_latency = TRUE;
5091       }
5092       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5093       break;
5094     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
5095       GST_BASE_SINK_PREROLL_LOCK (basesink);
5096       g_atomic_int_set (&basesink->priv->to_playing, TRUE);
5097       if (!gst_base_sink_needs_preroll (basesink)) {
5098         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
5099         /* no preroll needed anymore now. */
5100         basesink->playing_async = FALSE;
5101         basesink->need_preroll = FALSE;
5102         if (basesink->eos) {
5103           GstMessage *message;
5104
5105           /* need to post EOS message here */
5106           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
5107           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
5108           gst_message_set_seqnum (message, basesink->priv->seqnum);
5109           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
5110         } else {
5111           GST_DEBUG_OBJECT (basesink, "signal preroll");
5112           GST_BASE_SINK_PREROLL_SIGNAL (basesink);
5113         }
5114       } else {
5115         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
5116         basesink->need_preroll = TRUE;
5117         basesink->playing_async = TRUE;
5118         priv->call_preroll = TRUE;
5119         priv->commited = FALSE;
5120         if (priv->async_enabled) {
5121           GST_DEBUG_OBJECT (basesink, "doing async state change");
5122           ret = GST_STATE_CHANGE_ASYNC;
5123           gst_element_post_message (GST_ELEMENT_CAST (basesink),
5124               gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
5125         }
5126       }
5127       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5128       break;
5129     default:
5130       break;
5131   }
5132
5133   {
5134     GstStateChangeReturn bret;
5135
5136     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5137     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
5138       goto activate_failed;
5139   }
5140
5141   switch (transition) {
5142     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
5143       /* completed transition, so need not be marked any longer
5144        * And it should be unmarked, since e.g. losing our position upon flush
5145        * does not really change state to PAUSED ... */
5146       g_atomic_int_set (&basesink->priv->to_playing, FALSE);
5147       break;
5148     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
5149       g_atomic_int_set (&basesink->priv->to_playing, FALSE);
5150       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
5151       /* FIXME, make sure we cannot enter _render first */
5152
5153       /* we need to call ::unlock before locking PREROLL_LOCK
5154        * since we lock it before going into ::render */
5155       if (bclass->unlock)
5156         bclass->unlock (basesink);
5157
5158       GST_BASE_SINK_PREROLL_LOCK (basesink);
5159       GST_DEBUG_OBJECT (basesink, "got preroll lock");
5160       /* now that we have the PREROLL lock, clear our unlock request */
5161       if (bclass->unlock_stop)
5162         bclass->unlock_stop (basesink);
5163
5164       if (basesink->clock_id) {
5165         GST_DEBUG_OBJECT (basesink, "unschedule clock");
5166         gst_clock_id_unschedule (basesink->clock_id);
5167       }
5168
5169       /* if we don't have a preroll buffer we need to wait for a preroll and
5170        * return ASYNC. */
5171       if (!gst_base_sink_needs_preroll (basesink)) {
5172         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
5173         basesink->playing_async = FALSE;
5174         basesink->need_preroll = FALSE;
5175       } else {
5176         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
5177           GST_DEBUG_OBJECT (basesink, "element is <= READY");
5178           ret = GST_STATE_CHANGE_SUCCESS;
5179         } else {
5180           GST_DEBUG_OBJECT (basesink,
5181               "PLAYING to PAUSED, we are not prerolled");
5182           basesink->playing_async = TRUE;
5183           basesink->need_preroll = TRUE;
5184           priv->commited = FALSE;
5185           priv->call_preroll = TRUE;
5186           if (priv->async_enabled) {
5187             GST_DEBUG_OBJECT (basesink, "doing async state change");
5188             ret = GST_STATE_CHANGE_ASYNC;
5189             gst_element_post_message (GST_ELEMENT_CAST (basesink),
5190                 gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
5191           }
5192         }
5193       }
5194       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
5195           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
5196
5197       gst_base_sink_reset_qos (basesink);
5198       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5199       break;
5200     case GST_STATE_CHANGE_PAUSED_TO_READY:
5201       GST_BASE_SINK_PREROLL_LOCK (basesink);
5202       /* start by resetting our position state with the object lock so that the
5203        * position query gets the right idea. We do this before we post the
5204        * messages so that the message handlers pick this up. */
5205       GST_OBJECT_LOCK (basesink);
5206       basesink->have_newsegment = FALSE;
5207       priv->current_sstart = GST_CLOCK_TIME_NONE;
5208       priv->current_sstop = GST_CLOCK_TIME_NONE;
5209       priv->have_latency = FALSE;
5210       if (priv->cached_clock_id) {
5211         gst_clock_id_unref (priv->cached_clock_id);
5212         priv->cached_clock_id = NULL;
5213       }
5214       gst_caps_replace (&basesink->priv->caps, NULL);
5215       GST_OBJECT_UNLOCK (basesink);
5216
5217       gst_base_sink_set_last_buffer (basesink, NULL);
5218       gst_base_sink_set_last_buffer_list (basesink, NULL);
5219       priv->call_preroll = FALSE;
5220
5221       if (!priv->commited) {
5222         if (priv->async_enabled) {
5223           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
5224
5225           gst_element_post_message (GST_ELEMENT_CAST (basesink),
5226               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
5227                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
5228
5229           gst_element_post_message (GST_ELEMENT_CAST (basesink),
5230               gst_message_new_async_done (GST_OBJECT_CAST (basesink),
5231                   GST_CLOCK_TIME_NONE));
5232         }
5233         priv->commited = TRUE;
5234       } else {
5235         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
5236       }
5237       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5238       break;
5239     case GST_STATE_CHANGE_READY_TO_NULL:
5240       if (bclass->stop) {
5241         if (!bclass->stop (basesink)) {
5242           GST_WARNING_OBJECT (basesink, "failed to stop");
5243         }
5244       }
5245       gst_base_sink_set_last_buffer (basesink, NULL);
5246       gst_base_sink_set_last_buffer_list (basesink, NULL);
5247       priv->call_preroll = FALSE;
5248       break;
5249     default:
5250       break;
5251   }
5252
5253   return ret;
5254
5255   /* ERRORS */
5256 start_failed:
5257   {
5258     GST_DEBUG_OBJECT (basesink, "failed to start");
5259     /* subclass is supposed to post a message but we post one as a fallback
5260      * just in case */
5261     GST_ELEMENT_ERROR (basesink, CORE, STATE_CHANGE, (NULL),
5262         ("Failed to start"));
5263     return GST_STATE_CHANGE_FAILURE;
5264   }
5265 activate_failed:
5266   {
5267     GST_DEBUG_OBJECT (basesink,
5268         "element failed to change states -- activation problem?");
5269     return GST_STATE_CHANGE_FAILURE;
5270   }
5271 }