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