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