basesink: Minor GI warning fix.
[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         /* we need to add the render delay if we are live */
1207         min += render_delay;
1208         if (max != -1)
1209           max += render_delay;
1210
1211         if (max == -1 || min + processing_deadline <= max)
1212           min += processing_deadline;
1213         else {
1214           GST_ELEMENT_WARNING (sink, CORE, CLOCK,
1215               (_("Pipeline construction is invalid, please add queues.")),
1216               ("Not enough buffering available for "
1217                   " the processing deadline of %" GST_TIME_FORMAT
1218                   ", add enough queues to buffer  %" GST_TIME_FORMAT
1219                   " additional data. Shortening processing latency to %"
1220                   GST_TIME_FORMAT ".",
1221                   GST_TIME_ARGS (processing_deadline),
1222                   GST_TIME_ARGS (min + processing_deadline - max),
1223                   GST_TIME_ARGS (max - min)));
1224           min = max;
1225         }
1226       }
1227     }
1228     gst_query_unref (query);
1229   } else {
1230     GST_DEBUG_OBJECT (sink, "we are not yet ready for LATENCY query");
1231     res = FALSE;
1232   }
1233
1234   /* not live, we tried to do the query, if it failed we return TRUE anyway */
1235   if (!res) {
1236     if (!l) {
1237       res = TRUE;
1238       GST_DEBUG_OBJECT (sink, "latency query failed but we are not live");
1239     } else {
1240       GST_DEBUG_OBJECT (sink, "latency query failed and we are live");
1241     }
1242   }
1243
1244   if (res) {
1245     GST_DEBUG_OBJECT (sink, "latency query: live: %d, have_latency %d,"
1246         " upstream: %d, min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT, l,
1247         have_latency, us_live, GST_TIME_ARGS (min), GST_TIME_ARGS (max));
1248
1249     if (live)
1250       *live = l;
1251     if (upstream_live)
1252       *upstream_live = us_live;
1253     if (min_latency)
1254       *min_latency = min;
1255     if (max_latency)
1256       *max_latency = max;
1257   }
1258   return res;
1259 }
1260
1261 /**
1262  * gst_base_sink_set_render_delay:
1263  * @sink: a #GstBaseSink
1264  * @delay: the new delay
1265  *
1266  * Set the render delay in @sink to @delay. The render delay is the time
1267  * between actual rendering of a buffer and its synchronisation time. Some
1268  * devices might delay media rendering which can be compensated for with this
1269  * function.
1270  *
1271  * After calling this function, this sink will report additional latency and
1272  * other sinks will adjust their latency to delay the rendering of their media.
1273  *
1274  * This function is usually called by subclasses.
1275  */
1276 void
1277 gst_base_sink_set_render_delay (GstBaseSink * sink, GstClockTime delay)
1278 {
1279   GstClockTime old_render_delay;
1280
1281   g_return_if_fail (GST_IS_BASE_SINK (sink));
1282
1283   GST_OBJECT_LOCK (sink);
1284   old_render_delay = sink->priv->render_delay;
1285   sink->priv->render_delay = delay;
1286   GST_LOG_OBJECT (sink, "set render delay to %" GST_TIME_FORMAT,
1287       GST_TIME_ARGS (delay));
1288   GST_OBJECT_UNLOCK (sink);
1289
1290   if (delay != old_render_delay) {
1291     GST_DEBUG_OBJECT (sink, "posting latency changed");
1292     gst_element_post_message (GST_ELEMENT_CAST (sink),
1293         gst_message_new_latency (GST_OBJECT_CAST (sink)));
1294   }
1295 }
1296
1297 /**
1298  * gst_base_sink_get_render_delay:
1299  * @sink: a #GstBaseSink
1300  *
1301  * Get the render delay of @sink. see gst_base_sink_set_render_delay() for more
1302  * information about the render delay.
1303  *
1304  * Returns: the render delay of @sink.
1305  */
1306 GstClockTime
1307 gst_base_sink_get_render_delay (GstBaseSink * sink)
1308 {
1309   GstClockTimeDiff res;
1310
1311   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1312
1313   GST_OBJECT_LOCK (sink);
1314   res = sink->priv->render_delay;
1315   GST_OBJECT_UNLOCK (sink);
1316
1317   return res;
1318 }
1319
1320 /**
1321  * gst_base_sink_set_blocksize:
1322  * @sink: a #GstBaseSink
1323  * @blocksize: the blocksize in bytes
1324  *
1325  * Set the number of bytes that the sink will pull when it is operating in pull
1326  * mode.
1327  */
1328 /* FIXME 2.0: blocksize property should be int, otherwise min>max.. */
1329 void
1330 gst_base_sink_set_blocksize (GstBaseSink * sink, guint blocksize)
1331 {
1332   g_return_if_fail (GST_IS_BASE_SINK (sink));
1333
1334   GST_OBJECT_LOCK (sink);
1335   sink->priv->blocksize = blocksize;
1336   GST_LOG_OBJECT (sink, "set blocksize to %u", blocksize);
1337   GST_OBJECT_UNLOCK (sink);
1338 }
1339
1340 /**
1341  * gst_base_sink_get_blocksize:
1342  * @sink: a #GstBaseSink
1343  *
1344  * Get the number of bytes that the sink will pull when it is operating in pull
1345  * mode.
1346  *
1347  * Returns: the number of bytes @sink will pull in pull mode.
1348  */
1349 /* FIXME 2.0: blocksize property should be int, otherwise min>max.. */
1350 guint
1351 gst_base_sink_get_blocksize (GstBaseSink * sink)
1352 {
1353   guint res;
1354
1355   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1356
1357   GST_OBJECT_LOCK (sink);
1358   res = sink->priv->blocksize;
1359   GST_OBJECT_UNLOCK (sink);
1360
1361   return res;
1362 }
1363
1364 /**
1365  * gst_base_sink_set_throttle_time:
1366  * @sink: a #GstBaseSink
1367  * @throttle: the throttle time in nanoseconds
1368  *
1369  * Set the time that will be inserted between rendered buffers. This
1370  * can be used to control the maximum buffers per second that the sink
1371  * will render.
1372  */
1373 void
1374 gst_base_sink_set_throttle_time (GstBaseSink * sink, guint64 throttle)
1375 {
1376   g_return_if_fail (GST_IS_BASE_SINK (sink));
1377
1378   GST_OBJECT_LOCK (sink);
1379   sink->priv->throttle_time = throttle;
1380   GST_LOG_OBJECT (sink, "set throttle_time to %" G_GUINT64_FORMAT, throttle);
1381   GST_OBJECT_UNLOCK (sink);
1382 }
1383
1384 /**
1385  * gst_base_sink_get_throttle_time:
1386  * @sink: a #GstBaseSink
1387  *
1388  * Get the time that will be inserted between frames to control the
1389  * maximum buffers per second.
1390  *
1391  * Returns: the number of nanoseconds @sink will put between frames.
1392  */
1393 guint64
1394 gst_base_sink_get_throttle_time (GstBaseSink * sink)
1395 {
1396   guint64 res;
1397
1398   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1399
1400   GST_OBJECT_LOCK (sink);
1401   res = sink->priv->throttle_time;
1402   GST_OBJECT_UNLOCK (sink);
1403
1404   return res;
1405 }
1406
1407 /**
1408  * gst_base_sink_set_max_bitrate:
1409  * @sink: a #GstBaseSink
1410  * @max_bitrate: the max_bitrate in bits per second
1411  *
1412  * Set the maximum amount of bits per second that the sink will render.
1413  *
1414  * Since: 1.2
1415  */
1416 void
1417 gst_base_sink_set_max_bitrate (GstBaseSink * sink, guint64 max_bitrate)
1418 {
1419   g_return_if_fail (GST_IS_BASE_SINK (sink));
1420
1421   GST_OBJECT_LOCK (sink);
1422   sink->priv->max_bitrate = max_bitrate;
1423   GST_LOG_OBJECT (sink, "set max_bitrate to %" G_GUINT64_FORMAT, max_bitrate);
1424   GST_OBJECT_UNLOCK (sink);
1425 }
1426
1427 /**
1428  * gst_base_sink_get_max_bitrate:
1429  * @sink: a #GstBaseSink
1430  *
1431  * Get the maximum amount of bits per second that the sink will render.
1432  *
1433  * Returns: the maximum number of bits per second @sink will render.
1434  *
1435  * Since: 1.2
1436  */
1437 guint64
1438 gst_base_sink_get_max_bitrate (GstBaseSink * sink)
1439 {
1440   guint64 res;
1441
1442   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1443
1444   GST_OBJECT_LOCK (sink);
1445   res = sink->priv->max_bitrate;
1446   GST_OBJECT_UNLOCK (sink);
1447
1448   return res;
1449 }
1450
1451 /**
1452  * gst_base_sink_set_processing_deadline:
1453  * @sink: a #GstBaseSink
1454  * @processing_deadline: the new processing deadline in nanoseconds.
1455  *
1456  * Maximum amount of time (in nanoseconds) that the pipeline can take
1457  * for processing the buffer. This is added to the latency of live
1458  * pipelines.
1459  *
1460  * This function is usually called by subclasses.
1461  *
1462  * Since: 1.16
1463  */
1464 void
1465 gst_base_sink_set_processing_deadline (GstBaseSink * sink,
1466     GstClockTime processing_deadline)
1467 {
1468   GstClockTime old_processing_deadline;
1469
1470   g_return_if_fail (GST_IS_BASE_SINK (sink));
1471
1472   GST_OBJECT_LOCK (sink);
1473   old_processing_deadline = sink->priv->processing_deadline;
1474   sink->priv->processing_deadline = processing_deadline;
1475   GST_LOG_OBJECT (sink, "set render processing_deadline to %" GST_TIME_FORMAT,
1476       GST_TIME_ARGS (processing_deadline));
1477   GST_OBJECT_UNLOCK (sink);
1478
1479   if (processing_deadline != old_processing_deadline) {
1480     GST_DEBUG_OBJECT (sink, "posting latency changed");
1481     gst_element_post_message (GST_ELEMENT_CAST (sink),
1482         gst_message_new_latency (GST_OBJECT_CAST (sink)));
1483   }
1484 }
1485
1486 /**
1487  * gst_base_sink_get_processing_deadline:
1488  * @sink: a #GstBaseSink
1489  *
1490  * Get the processing deadline of @sink. see
1491  * gst_base_sink_set_processing_deadline() for more information about
1492  * the processing deadline.
1493  *
1494  * Returns: the processing deadline
1495  *
1496  * Since: 1.16
1497  */
1498 GstClockTime
1499 gst_base_sink_get_processing_deadline (GstBaseSink * sink)
1500 {
1501   GstClockTimeDiff res;
1502
1503   g_return_val_if_fail (GST_IS_BASE_SINK (sink), 0);
1504
1505   GST_OBJECT_LOCK (sink);
1506   res = sink->priv->processing_deadline;
1507   GST_OBJECT_UNLOCK (sink);
1508
1509   return res;
1510 }
1511
1512 static void
1513 gst_base_sink_set_property (GObject * object, guint prop_id,
1514     const GValue * value, GParamSpec * pspec)
1515 {
1516   GstBaseSink *sink = GST_BASE_SINK (object);
1517
1518   switch (prop_id) {
1519     case PROP_SYNC:
1520       gst_base_sink_set_sync (sink, g_value_get_boolean (value));
1521       break;
1522     case PROP_MAX_LATENESS:
1523       gst_base_sink_set_max_lateness (sink, g_value_get_int64 (value));
1524       break;
1525     case PROP_QOS:
1526       gst_base_sink_set_qos_enabled (sink, g_value_get_boolean (value));
1527       break;
1528     case PROP_ASYNC:
1529       gst_base_sink_set_async_enabled (sink, g_value_get_boolean (value));
1530       break;
1531     case PROP_TS_OFFSET:
1532       gst_base_sink_set_ts_offset (sink, g_value_get_int64 (value));
1533       break;
1534     case PROP_BLOCKSIZE:
1535       gst_base_sink_set_blocksize (sink, g_value_get_uint (value));
1536       break;
1537     case PROP_RENDER_DELAY:
1538       gst_base_sink_set_render_delay (sink, g_value_get_uint64 (value));
1539       break;
1540     case PROP_ENABLE_LAST_SAMPLE:
1541       gst_base_sink_set_last_sample_enabled (sink, g_value_get_boolean (value));
1542       break;
1543     case PROP_THROTTLE_TIME:
1544       gst_base_sink_set_throttle_time (sink, g_value_get_uint64 (value));
1545       break;
1546     case PROP_MAX_BITRATE:
1547       gst_base_sink_set_max_bitrate (sink, g_value_get_uint64 (value));
1548       break;
1549     case PROP_PROCESSING_DEADLINE:
1550       gst_base_sink_set_processing_deadline (sink, g_value_get_uint64 (value));
1551       break;
1552     default:
1553       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1554       break;
1555   }
1556 }
1557
1558 static void
1559 gst_base_sink_get_property (GObject * object, guint prop_id, GValue * value,
1560     GParamSpec * pspec)
1561 {
1562   GstBaseSink *sink = GST_BASE_SINK (object);
1563
1564   switch (prop_id) {
1565     case PROP_SYNC:
1566       g_value_set_boolean (value, gst_base_sink_get_sync (sink));
1567       break;
1568     case PROP_MAX_LATENESS:
1569       g_value_set_int64 (value, gst_base_sink_get_max_lateness (sink));
1570       break;
1571     case PROP_QOS:
1572       g_value_set_boolean (value, gst_base_sink_is_qos_enabled (sink));
1573       break;
1574     case PROP_ASYNC:
1575       g_value_set_boolean (value, gst_base_sink_is_async_enabled (sink));
1576       break;
1577     case PROP_TS_OFFSET:
1578       g_value_set_int64 (value, gst_base_sink_get_ts_offset (sink));
1579       break;
1580     case PROP_LAST_SAMPLE:
1581       gst_value_take_sample (value, gst_base_sink_get_last_sample (sink));
1582       break;
1583     case PROP_ENABLE_LAST_SAMPLE:
1584       g_value_set_boolean (value, gst_base_sink_is_last_sample_enabled (sink));
1585       break;
1586     case PROP_BLOCKSIZE:
1587       g_value_set_uint (value, gst_base_sink_get_blocksize (sink));
1588       break;
1589     case PROP_RENDER_DELAY:
1590       g_value_set_uint64 (value, gst_base_sink_get_render_delay (sink));
1591       break;
1592     case PROP_THROTTLE_TIME:
1593       g_value_set_uint64 (value, gst_base_sink_get_throttle_time (sink));
1594       break;
1595     case PROP_MAX_BITRATE:
1596       g_value_set_uint64 (value, gst_base_sink_get_max_bitrate (sink));
1597       break;
1598     case PROP_PROCESSING_DEADLINE:
1599       g_value_set_uint64 (value, gst_base_sink_get_processing_deadline (sink));
1600       break;
1601     default:
1602       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1603       break;
1604   }
1605 }
1606
1607
1608 static GstCaps *
1609 gst_base_sink_default_get_caps (GstBaseSink * sink, GstCaps * filter)
1610 {
1611   return NULL;
1612 }
1613
1614 static gboolean
1615 gst_base_sink_default_set_caps (GstBaseSink * sink, GstCaps * caps)
1616 {
1617   return TRUE;
1618 }
1619
1620 /* with PREROLL_LOCK, STREAM_LOCK */
1621 static gboolean
1622 gst_base_sink_commit_state (GstBaseSink * basesink)
1623 {
1624   /* commit state and proceed to next pending state */
1625   GstState current, next, pending, post_pending;
1626   gboolean post_paused = FALSE;
1627   gboolean post_async_done = FALSE;
1628   gboolean post_playing = FALSE;
1629
1630   /* we are certainly not playing async anymore now */
1631   basesink->playing_async = FALSE;
1632
1633   GST_OBJECT_LOCK (basesink);
1634   current = GST_STATE (basesink);
1635   next = GST_STATE_NEXT (basesink);
1636   pending = GST_STATE_PENDING (basesink);
1637   post_pending = pending;
1638
1639   switch (pending) {
1640     case GST_STATE_PLAYING:
1641     {
1642       GST_DEBUG_OBJECT (basesink, "committing state to PLAYING");
1643
1644       basesink->need_preroll = FALSE;
1645       post_async_done = TRUE;
1646       basesink->priv->committed = TRUE;
1647       post_playing = TRUE;
1648       /* post PAUSED too when we were READY */
1649       if (current == GST_STATE_READY) {
1650         post_paused = TRUE;
1651       }
1652       break;
1653     }
1654     case GST_STATE_PAUSED:
1655       GST_DEBUG_OBJECT (basesink, "committing state to PAUSED");
1656       post_paused = TRUE;
1657       post_async_done = TRUE;
1658       basesink->priv->committed = TRUE;
1659       post_pending = GST_STATE_VOID_PENDING;
1660       break;
1661     case GST_STATE_READY:
1662     case GST_STATE_NULL:
1663       goto stopping;
1664     case GST_STATE_VOID_PENDING:
1665       goto nothing_pending;
1666     default:
1667       break;
1668   }
1669
1670   /* we can report latency queries now */
1671   basesink->priv->have_latency = TRUE;
1672
1673   GST_STATE (basesink) = pending;
1674   GST_STATE_NEXT (basesink) = GST_STATE_VOID_PENDING;
1675   GST_STATE_PENDING (basesink) = GST_STATE_VOID_PENDING;
1676   GST_STATE_RETURN (basesink) = GST_STATE_CHANGE_SUCCESS;
1677   GST_OBJECT_UNLOCK (basesink);
1678
1679   if (post_paused) {
1680     GST_DEBUG_OBJECT (basesink, "posting PAUSED state change message");
1681     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1682         gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
1683             current, next, post_pending));
1684   }
1685   if (post_async_done) {
1686     GST_DEBUG_OBJECT (basesink, "posting async-done message");
1687     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1688         gst_message_new_async_done (GST_OBJECT_CAST (basesink),
1689             GST_CLOCK_TIME_NONE));
1690   }
1691   if (post_playing) {
1692     if (post_paused) {
1693       GstElementClass *klass;
1694
1695       klass = GST_ELEMENT_GET_CLASS (basesink);
1696       basesink->have_preroll = TRUE;
1697       /* after releasing this lock, the state change function
1698        * can execute concurrently with this thread. There is nothing we do to
1699        * prevent this for now. subclasses should be prepared to handle it. */
1700       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
1701
1702       if (klass->change_state)
1703         klass->change_state (GST_ELEMENT_CAST (basesink),
1704             GST_STATE_CHANGE_PAUSED_TO_PLAYING);
1705
1706       GST_BASE_SINK_PREROLL_LOCK (basesink);
1707       /* state change function could have been executed and we could be
1708        * flushing now */
1709       if (G_UNLIKELY (basesink->flushing))
1710         goto stopping_unlocked;
1711     }
1712     GST_DEBUG_OBJECT (basesink, "posting PLAYING state change message");
1713     /* FIXME, we released the PREROLL lock above, it's possible that this
1714      * message is not correct anymore when the element went back to PAUSED */
1715     gst_element_post_message (GST_ELEMENT_CAST (basesink),
1716         gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
1717             next, pending, GST_STATE_VOID_PENDING));
1718   }
1719
1720   GST_STATE_BROADCAST (basesink);
1721
1722   return TRUE;
1723
1724 nothing_pending:
1725   {
1726     /* Depending on the state, set our vars. We get in this situation when the
1727      * state change function got a change to update the state vars before the
1728      * streaming thread did. This is fine but we need to make sure that we
1729      * update the need_preroll var since it was %TRUE when we got here and might
1730      * become %FALSE if we got to PLAYING. */
1731     GST_DEBUG_OBJECT (basesink, "nothing to commit, now in %s",
1732         gst_element_state_get_name (current));
1733     switch (current) {
1734       case GST_STATE_PLAYING:
1735         basesink->need_preroll = FALSE;
1736         break;
1737       case GST_STATE_PAUSED:
1738         basesink->need_preroll = TRUE;
1739         break;
1740       default:
1741         basesink->need_preroll = FALSE;
1742         basesink->flushing = TRUE;
1743         break;
1744     }
1745     /* we can report latency queries now */
1746     basesink->priv->have_latency = TRUE;
1747     GST_OBJECT_UNLOCK (basesink);
1748     return TRUE;
1749   }
1750 stopping_unlocked:
1751   {
1752     GST_OBJECT_LOCK (basesink);
1753     goto stopping;
1754   }
1755 stopping:
1756   {
1757     /* app is going to READY */
1758     GST_DEBUG_OBJECT (basesink, "stopping");
1759     basesink->need_preroll = FALSE;
1760     basesink->flushing = TRUE;
1761     GST_OBJECT_UNLOCK (basesink);
1762     return FALSE;
1763   }
1764 }
1765
1766 static void
1767 start_stepping (GstBaseSink * sink, GstSegment * segment,
1768     GstStepInfo * pending, GstStepInfo * current)
1769 {
1770   gint64 end;
1771   GstMessage *message;
1772
1773   GST_DEBUG_OBJECT (sink, "update pending step");
1774
1775   GST_OBJECT_LOCK (sink);
1776   memcpy (current, pending, sizeof (GstStepInfo));
1777   pending->valid = FALSE;
1778   GST_OBJECT_UNLOCK (sink);
1779
1780   /* post message first */
1781   message =
1782       gst_message_new_step_start (GST_OBJECT (sink), TRUE, current->format,
1783       current->amount, current->rate, current->flush, current->intermediate);
1784   gst_message_set_seqnum (message, current->seqnum);
1785   gst_element_post_message (GST_ELEMENT (sink), message);
1786
1787   /* get the running time of where we paused and remember it */
1788   current->start = gst_element_get_start_time (GST_ELEMENT_CAST (sink));
1789   gst_segment_set_running_time (segment, GST_FORMAT_TIME, current->start);
1790
1791   /* set the new rate for the remainder of the segment */
1792   current->start_rate = segment->rate;
1793   segment->rate *= current->rate;
1794
1795   /* save values */
1796   if (segment->rate > 0.0)
1797     current->start_stop = segment->stop;
1798   else
1799     current->start_start = segment->start;
1800
1801   if (current->format == GST_FORMAT_TIME) {
1802     /* calculate the running-time when the step operation should stop */
1803     if (current->amount != -1)
1804       end = current->start + current->amount;
1805     else
1806       end = -1;
1807
1808     if (!current->flush) {
1809       gint64 position;
1810
1811       /* update the segment clipping regions for non-flushing seeks */
1812       if (segment->rate > 0.0) {
1813         if (end != -1)
1814           position =
1815               gst_segment_position_from_running_time (segment, GST_FORMAT_TIME,
1816               end);
1817         else
1818           position = segment->stop;
1819
1820         segment->stop = position;
1821         segment->position = position;
1822       } else {
1823         if (end != -1)
1824           position =
1825               gst_segment_position_from_running_time (segment, GST_FORMAT_TIME,
1826               end);
1827         else
1828           position = segment->start;
1829
1830         segment->time = position;
1831         segment->start = position;
1832         segment->position = position;
1833       }
1834     }
1835   }
1836
1837   GST_DEBUG_OBJECT (sink, "segment now %" GST_SEGMENT_FORMAT, segment);
1838   GST_DEBUG_OBJECT (sink, "step started at running_time %" GST_TIME_FORMAT,
1839       GST_TIME_ARGS (current->start));
1840
1841   GST_DEBUG_OBJECT (sink, "step amount: %" G_GUINT64_FORMAT ", format: %s, "
1842       "rate: %f", current->amount, gst_format_get_name (current->format),
1843       current->rate);
1844 }
1845
1846 static void
1847 stop_stepping (GstBaseSink * sink, GstSegment * segment,
1848     GstStepInfo * current, gint64 rstart, gint64 rstop, gboolean eos)
1849 {
1850   gint64 stop, position;
1851   GstMessage *message;
1852
1853   GST_DEBUG_OBJECT (sink, "step complete");
1854
1855   if (segment->rate > 0.0)
1856     stop = rstart;
1857   else
1858     stop = rstop;
1859
1860   GST_DEBUG_OBJECT (sink,
1861       "step stop at running_time %" GST_TIME_FORMAT, GST_TIME_ARGS (stop));
1862
1863   if (stop == -1)
1864     current->duration = current->position;
1865   else
1866     current->duration = stop - current->start;
1867
1868   GST_DEBUG_OBJECT (sink, "step elapsed running_time %" GST_TIME_FORMAT,
1869       GST_TIME_ARGS (current->duration));
1870
1871   position = current->start + current->duration;
1872
1873   /* now move the segment to the new running time */
1874   gst_segment_set_running_time (segment, GST_FORMAT_TIME, position);
1875
1876   if (current->flush) {
1877     /* and remove the time we flushed, start time did not change */
1878     segment->base = current->start;
1879   } else {
1880     /* start time is now the stepped position */
1881     gst_element_set_start_time (GST_ELEMENT_CAST (sink), position);
1882   }
1883
1884   /* restore the previous rate */
1885   segment->rate = current->start_rate;
1886
1887   if (segment->rate > 0.0)
1888     segment->stop = current->start_stop;
1889   else
1890     segment->start = current->start_start;
1891
1892   /* post the step done when we know the stepped duration in TIME */
1893   message =
1894       gst_message_new_step_done (GST_OBJECT_CAST (sink), current->format,
1895       current->amount, current->rate, current->flush, current->intermediate,
1896       current->duration, eos);
1897   gst_message_set_seqnum (message, current->seqnum);
1898   gst_element_post_message (GST_ELEMENT_CAST (sink), message);
1899
1900   if (!current->intermediate)
1901     sink->need_preroll = current->need_preroll;
1902
1903   /* and the current step info finished and becomes invalid */
1904   current->valid = FALSE;
1905 }
1906
1907 static gboolean
1908 handle_stepping (GstBaseSink * sink, GstSegment * segment,
1909     GstStepInfo * current, guint64 * cstart, guint64 * cstop, guint64 * rstart,
1910     guint64 * rstop)
1911 {
1912   gboolean step_end = FALSE;
1913
1914   /* stepping never stops */
1915   if (current->amount == -1)
1916     return FALSE;
1917
1918   /* see if we need to skip this buffer because of stepping */
1919   switch (current->format) {
1920     case GST_FORMAT_TIME:
1921     {
1922       guint64 end;
1923       guint64 first, last;
1924       gdouble abs_rate;
1925
1926       if (segment->rate > 0.0) {
1927         if (segment->stop == *cstop)
1928           *rstop = *rstart + current->amount;
1929
1930         first = *rstart;
1931         last = *rstop;
1932       } else {
1933         if (segment->start == *cstart)
1934           *rstart = *rstop + current->amount;
1935
1936         first = *rstop;
1937         last = *rstart;
1938       }
1939
1940       end = current->start + current->amount;
1941       current->position = first - current->start;
1942
1943       abs_rate = ABS (segment->rate);
1944       if (G_UNLIKELY (abs_rate != 1.0))
1945         current->position /= abs_rate;
1946
1947       GST_DEBUG_OBJECT (sink,
1948           "buffer: %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
1949           GST_TIME_ARGS (first), GST_TIME_ARGS (last));
1950       GST_DEBUG_OBJECT (sink,
1951           "got time step %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT "/%"
1952           GST_TIME_FORMAT, GST_TIME_ARGS (current->position),
1953           GST_TIME_ARGS (last - current->start),
1954           GST_TIME_ARGS (current->amount));
1955
1956       if ((current->flush && current->position >= current->amount)
1957           || last >= end) {
1958         GST_DEBUG_OBJECT (sink, "step ended, we need clipping");
1959         step_end = TRUE;
1960         if (segment->rate > 0.0) {
1961           *rstart = end;
1962           *cstart =
1963               gst_segment_position_from_running_time (segment, GST_FORMAT_TIME,
1964               end);
1965         } else {
1966           *rstop = end;
1967           *cstop =
1968               gst_segment_position_from_running_time (segment, GST_FORMAT_TIME,
1969               end);
1970         }
1971       }
1972       GST_DEBUG_OBJECT (sink,
1973           "cstart %" GST_TIME_FORMAT ", rstart %" GST_TIME_FORMAT,
1974           GST_TIME_ARGS (*cstart), GST_TIME_ARGS (*rstart));
1975       GST_DEBUG_OBJECT (sink,
1976           "cstop %" GST_TIME_FORMAT ", rstop %" GST_TIME_FORMAT,
1977           GST_TIME_ARGS (*cstop), GST_TIME_ARGS (*rstop));
1978       break;
1979     }
1980     case GST_FORMAT_BUFFERS:
1981       GST_DEBUG_OBJECT (sink,
1982           "got default step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1983           current->position, current->amount);
1984
1985       if (current->position < current->amount) {
1986         current->position++;
1987       } else {
1988         step_end = TRUE;
1989       }
1990       break;
1991     case GST_FORMAT_DEFAULT:
1992     default:
1993       GST_DEBUG_OBJECT (sink,
1994           "got unknown step %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT,
1995           current->position, current->amount);
1996       break;
1997   }
1998   return step_end;
1999 }
2000
2001 /* with STREAM_LOCK, PREROLL_LOCK
2002  *
2003  * Returns %TRUE if the object needs synchronisation and takes therefore
2004  * part in prerolling.
2005  *
2006  * rsstart/rsstop contain the start/stop in stream time.
2007  * rrstart/rrstop contain the start/stop in running time.
2008  */
2009 static gboolean
2010 gst_base_sink_get_sync_times (GstBaseSink * basesink, GstMiniObject * obj,
2011     GstClockTime * rsstart, GstClockTime * rsstop,
2012     GstClockTime * rrstart, GstClockTime * rrstop, GstClockTime * rrnext,
2013     gboolean * do_sync, gboolean * stepped, GstStepInfo * step,
2014     gboolean * step_end)
2015 {
2016   GstBaseSinkClass *bclass;
2017   GstClockTime start, stop;     /* raw start/stop timestamps */
2018   guint64 cstart, cstop;        /* clipped raw timestamps */
2019   guint64 rstart, rstop, rnext; /* clipped timestamps converted to running time */
2020   GstClockTime sstart, sstop;   /* clipped timestamps converted to stream time */
2021   GstFormat format;
2022   GstBaseSinkPrivate *priv;
2023   GstSegment *segment;
2024   gboolean eos;
2025
2026   priv = basesink->priv;
2027   segment = &basesink->segment;
2028
2029   bclass = GST_BASE_SINK_GET_CLASS (basesink);
2030
2031 again:
2032   /* start with nothing */
2033   start = stop = GST_CLOCK_TIME_NONE;
2034   eos = FALSE;
2035
2036   if (G_UNLIKELY (GST_IS_EVENT (obj))) {
2037     GstEvent *event = GST_EVENT_CAST (obj);
2038
2039     switch (GST_EVENT_TYPE (event)) {
2040         /* EOS event needs syncing */
2041       case GST_EVENT_EOS:
2042       {
2043         if (segment->rate >= 0.0) {
2044           sstart = sstop = priv->current_sstop;
2045           if (!GST_CLOCK_TIME_IS_VALID (sstart)) {
2046             /* we have not seen a buffer yet, use the segment values */
2047             sstart = sstop = gst_segment_to_stream_time (segment,
2048                 segment->format, segment->stop);
2049           }
2050         } else {
2051           sstart = sstop = priv->current_sstart;
2052           if (!GST_CLOCK_TIME_IS_VALID (sstart)) {
2053             /* we have not seen a buffer yet, use the segment values */
2054             sstart = sstop = gst_segment_to_stream_time (segment,
2055                 segment->format, segment->start);
2056           }
2057         }
2058
2059         rstart = rstop = rnext = priv->eos_rtime;
2060         *do_sync = GST_CLOCK_TIME_IS_VALID (rstart);
2061         GST_DEBUG_OBJECT (basesink, "sync times for EOS %" GST_TIME_FORMAT,
2062             GST_TIME_ARGS (rstart));
2063         /* if we are stepping, we end now */
2064         *step_end = step->valid;
2065         eos = TRUE;
2066         goto eos_done;
2067       }
2068       case GST_EVENT_GAP:
2069       {
2070         GstClockTime timestamp, duration;
2071         gst_event_parse_gap (event, &timestamp, &duration);
2072
2073         GST_DEBUG_OBJECT (basesink, "Got Gap time %" GST_TIME_FORMAT
2074             " duration %" GST_TIME_FORMAT,
2075             GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
2076
2077         if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
2078           start = timestamp;
2079           if (GST_CLOCK_TIME_IS_VALID (duration))
2080             stop = start + duration;
2081         }
2082         *do_sync = TRUE;
2083         break;
2084       }
2085       default:
2086         /* other events do not need syncing */
2087         return FALSE;
2088     }
2089   } else {
2090     /* else do buffer sync code */
2091     GstBuffer *buffer = GST_BUFFER_CAST (obj);
2092
2093     /* just get the times to see if we need syncing, if the retuned start is -1
2094      * we don't sync. */
2095     if (bclass->get_times)
2096       bclass->get_times (basesink, buffer, &start, &stop);
2097
2098     if (!GST_CLOCK_TIME_IS_VALID (start)) {
2099       /* we don't need to sync but we still want to get the timestamps for
2100        * tracking the position */
2101       gst_base_sink_default_get_times (basesink, buffer, &start, &stop);
2102       *do_sync = FALSE;
2103     } else {
2104       *do_sync = TRUE;
2105     }
2106   }
2107
2108   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
2109       ", stop: %" GST_TIME_FORMAT ", do_sync %d", GST_TIME_ARGS (start),
2110       GST_TIME_ARGS (stop), *do_sync);
2111
2112   /* collect segment and format for code clarity */
2113   format = segment->format;
2114
2115   /* clip */
2116   if (G_UNLIKELY (!gst_segment_clip (segment, format,
2117               start, stop, &cstart, &cstop))) {
2118     if (step->valid) {
2119       GST_DEBUG_OBJECT (basesink, "step out of segment");
2120       /* when we are stepping, pretend we're at the end of the segment */
2121       if (segment->rate > 0.0) {
2122         cstart = segment->stop;
2123         cstop = segment->stop;
2124       } else {
2125         cstart = segment->start;
2126         cstop = segment->start;
2127       }
2128       goto do_times;
2129     }
2130     goto out_of_segment;
2131   }
2132
2133   if (G_UNLIKELY (start != cstart || stop != cstop)) {
2134     GST_DEBUG_OBJECT (basesink, "clipped to: start %" GST_TIME_FORMAT
2135         ", stop: %" GST_TIME_FORMAT, GST_TIME_ARGS (cstart),
2136         GST_TIME_ARGS (cstop));
2137   }
2138
2139   /* set last stop position */
2140   if (G_LIKELY (stop != GST_CLOCK_TIME_NONE && cstop != GST_CLOCK_TIME_NONE))
2141     segment->position = cstop;
2142   else
2143     segment->position = cstart;
2144
2145 do_times:
2146   rstart = gst_segment_to_running_time (segment, format, cstart);
2147   rstop = gst_segment_to_running_time (segment, format, cstop);
2148
2149   if (GST_CLOCK_TIME_IS_VALID (stop))
2150     rnext = rstop;
2151   else
2152     rnext = rstart;
2153
2154   if (G_UNLIKELY (step->valid)) {
2155     if (!(*step_end = handle_stepping (basesink, segment, step, &cstart, &cstop,
2156                 &rstart, &rstop))) {
2157       /* step is still busy, we discard data when we are flushing */
2158       *stepped = step->flush;
2159       GST_DEBUG_OBJECT (basesink, "stepping busy");
2160     }
2161   }
2162   /* this can produce wrong values if we accumulated non-TIME segments. If this happens,
2163    * upstream is behaving very badly */
2164   sstart = gst_segment_to_stream_time (segment, format, cstart);
2165   sstop = gst_segment_to_stream_time (segment, format, cstop);
2166
2167 eos_done:
2168   /* eos_done label only called when doing EOS, we also stop stepping then */
2169   if (*step_end && step->flush) {
2170     GST_DEBUG_OBJECT (basesink, "flushing step ended");
2171     stop_stepping (basesink, segment, step, rstart, rstop, eos);
2172     *step_end = FALSE;
2173     /* re-determine running start times for adjusted segment
2174      * (which has a flushed amount of running/accumulated time removed) */
2175     if (!GST_IS_EVENT (obj)) {
2176       GST_DEBUG_OBJECT (basesink, "refresh sync times");
2177       goto again;
2178     }
2179   }
2180
2181   /* save times */
2182   *rsstart = sstart;
2183   *rsstop = sstop;
2184   *rrstart = rstart;
2185   *rrstop = rstop;
2186   *rrnext = rnext;
2187
2188   /* buffers and EOS always need syncing and preroll */
2189   return TRUE;
2190
2191   /* special cases */
2192 out_of_segment:
2193   {
2194     /* we usually clip in the chain function already but stepping could cause
2195      * the segment to be updated later. we return %FALSE so that we don't try
2196      * to sync on it. */
2197     GST_LOG_OBJECT (basesink, "buffer skipped, not in segment");
2198     return FALSE;
2199   }
2200 }
2201
2202 /* with STREAM_LOCK, PREROLL_LOCK, LOCK
2203  * adjust a timestamp with the latency and timestamp offset. This function does
2204  * not adjust for the render delay. */
2205 static GstClockTime
2206 gst_base_sink_adjust_time (GstBaseSink * basesink, GstClockTime time)
2207 {
2208   GstClockTimeDiff ts_offset;
2209
2210   /* don't do anything funny with invalid timestamps */
2211   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
2212     return time;
2213
2214   time += basesink->priv->latency;
2215
2216   /* apply offset, be careful for underflows */
2217   ts_offset = basesink->priv->ts_offset;
2218   if (ts_offset < 0) {
2219     ts_offset = -ts_offset;
2220     if (ts_offset < time)
2221       time -= ts_offset;
2222     else
2223       time = 0;
2224   } else
2225     time += ts_offset;
2226
2227   /* subtract the render delay again, which was included in the latency */
2228   if (time > basesink->priv->render_delay)
2229     time -= basesink->priv->render_delay;
2230   else
2231     time = 0;
2232
2233   return time;
2234 }
2235
2236 /**
2237  * gst_base_sink_wait_clock:
2238  * @sink: the sink
2239  * @time: the running_time to be reached
2240  * @jitter: (out) (allow-none): the jitter to be filled with time diff, or %NULL
2241  *
2242  * This function will block until @time is reached. It is usually called by
2243  * subclasses that use their own internal synchronisation.
2244  *
2245  * If @time is not valid, no synchronisation is done and %GST_CLOCK_BADTIME is
2246  * returned. Likewise, if synchronisation is disabled in the element or there
2247  * is no clock, no synchronisation is done and %GST_CLOCK_BADTIME is returned.
2248  *
2249  * This function should only be called with the PREROLL_LOCK held, like when
2250  * receiving an EOS event in the #GstBaseSinkClass.event() vmethod or when
2251  * receiving a buffer in
2252  * the #GstBaseSinkClass.render() vmethod.
2253  *
2254  * The @time argument should be the running_time of when this method should
2255  * return and is not adjusted with any latency or offset configured in the
2256  * sink.
2257  *
2258  * Returns: #GstClockReturn
2259  */
2260 GstClockReturn
2261 gst_base_sink_wait_clock (GstBaseSink * sink, GstClockTime time,
2262     GstClockTimeDiff * jitter)
2263 {
2264   GstClockReturn ret;
2265   GstClock *clock;
2266   GstClockTime base_time;
2267
2268   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (time)))
2269     goto invalid_time;
2270
2271   GST_OBJECT_LOCK (sink);
2272   if (G_UNLIKELY (!sink->sync))
2273     goto no_sync;
2274
2275   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (sink)) == NULL))
2276     goto no_clock;
2277
2278   base_time = GST_ELEMENT_CAST (sink)->base_time;
2279   GST_LOG_OBJECT (sink,
2280       "time %" GST_TIME_FORMAT ", base_time %" GST_TIME_FORMAT,
2281       GST_TIME_ARGS (time), GST_TIME_ARGS (base_time));
2282
2283   /* add base_time to running_time to get the time against the clock */
2284   time += base_time;
2285
2286   /* Re-use existing clockid if available */
2287   /* FIXME: Casting to GstClockEntry only works because the types
2288    * are the same */
2289   if (G_LIKELY (sink->priv->cached_clock_id != NULL
2290           && GST_CLOCK_ENTRY_CLOCK ((GstClockEntry *) sink->
2291               priv->cached_clock_id) == clock)) {
2292     if (!gst_clock_single_shot_id_reinit (clock, sink->priv->cached_clock_id,
2293             time)) {
2294       gst_clock_id_unref (sink->priv->cached_clock_id);
2295       sink->priv->cached_clock_id = gst_clock_new_single_shot_id (clock, time);
2296     }
2297   } else {
2298     if (sink->priv->cached_clock_id != NULL)
2299       gst_clock_id_unref (sink->priv->cached_clock_id);
2300     sink->priv->cached_clock_id = gst_clock_new_single_shot_id (clock, time);
2301   }
2302   GST_OBJECT_UNLOCK (sink);
2303
2304   /* A blocking wait is performed on the clock. We save the ClockID
2305    * so we can unlock the entry at any time. While we are blocking, we
2306    * release the PREROLL_LOCK so that other threads can interrupt the
2307    * entry. */
2308   sink->clock_id = sink->priv->cached_clock_id;
2309   /* release the preroll lock while waiting */
2310   GST_BASE_SINK_PREROLL_UNLOCK (sink);
2311
2312   ret = gst_clock_id_wait (sink->priv->cached_clock_id, jitter);
2313
2314   GST_BASE_SINK_PREROLL_LOCK (sink);
2315   sink->clock_id = NULL;
2316
2317   return ret;
2318
2319   /* no syncing needed */
2320 invalid_time:
2321   {
2322     GST_DEBUG_OBJECT (sink, "time not valid, no sync needed");
2323     return GST_CLOCK_BADTIME;
2324   }
2325 no_sync:
2326   {
2327     GST_DEBUG_OBJECT (sink, "sync disabled");
2328     GST_OBJECT_UNLOCK (sink);
2329     return GST_CLOCK_BADTIME;
2330   }
2331 no_clock:
2332   {
2333     GST_DEBUG_OBJECT (sink, "no clock, can't sync");
2334     GST_OBJECT_UNLOCK (sink);
2335     return GST_CLOCK_BADTIME;
2336   }
2337 }
2338
2339 /**
2340  * gst_base_sink_wait_preroll:
2341  * @sink: the sink
2342  *
2343  * If the #GstBaseSinkClass.render() method performs its own synchronisation
2344  * against the clock it must unblock when going from PLAYING to the PAUSED state
2345  * and call this method before continuing to render the remaining data.
2346  *
2347  * If the #GstBaseSinkClass.render() method can block on something else than
2348  * the clock, it must also be ready to unblock immediately on
2349  * the #GstBaseSinkClass.unlock() method and cause the
2350  * #GstBaseSinkClass.render() method to immediately call this function.
2351  * In this case, the subclass must be prepared to continue rendering where it
2352  * left off if this function returns %GST_FLOW_OK.
2353  *
2354  * This function will block until a state change to PLAYING happens (in which
2355  * case this function returns %GST_FLOW_OK) or the processing must be stopped due
2356  * to a state change to READY or a FLUSH event (in which case this function
2357  * returns %GST_FLOW_FLUSHING).
2358  *
2359  * This function should only be called with the PREROLL_LOCK held, like in the
2360  * render function.
2361  *
2362  * Returns: %GST_FLOW_OK if the preroll completed and processing can
2363  * continue. Any other return value should be returned from the render vmethod.
2364  */
2365 GstFlowReturn
2366 gst_base_sink_wait_preroll (GstBaseSink * sink)
2367 {
2368   sink->have_preroll = TRUE;
2369   GST_DEBUG_OBJECT (sink, "waiting in preroll for flush or PLAYING");
2370   /* block until the state changes, or we get a flush, or something */
2371   GST_BASE_SINK_PREROLL_WAIT (sink);
2372   sink->have_preroll = FALSE;
2373   if (G_UNLIKELY (sink->flushing))
2374     goto stopping;
2375   if (G_UNLIKELY (sink->priv->step_unlock))
2376     goto step_unlocked;
2377   GST_DEBUG_OBJECT (sink, "continue after preroll");
2378
2379   return GST_FLOW_OK;
2380
2381   /* ERRORS */
2382 stopping:
2383   {
2384     GST_DEBUG_OBJECT (sink, "preroll interrupted because of flush");
2385     return GST_FLOW_FLUSHING;
2386   }
2387 step_unlocked:
2388   {
2389     sink->priv->step_unlock = FALSE;
2390     GST_DEBUG_OBJECT (sink, "preroll interrupted because of step");
2391     return GST_FLOW_STEP;
2392   }
2393 }
2394
2395 /**
2396  * gst_base_sink_do_preroll:
2397  * @sink: the sink
2398  * @obj: (transfer none): the mini object that caused the preroll
2399  *
2400  * If the @sink spawns its own thread for pulling buffers from upstream it
2401  * should call this method after it has pulled a buffer. If the element needed
2402  * to preroll, this function will perform the preroll and will then block
2403  * until the element state is changed.
2404  *
2405  * This function should be called with the PREROLL_LOCK held.
2406  *
2407  * Returns: %GST_FLOW_OK if the preroll completed and processing can
2408  * continue. Any other return value should be returned from the render vmethod.
2409  */
2410 GstFlowReturn
2411 gst_base_sink_do_preroll (GstBaseSink * sink, GstMiniObject * obj)
2412 {
2413   GstFlowReturn ret;
2414
2415   while (G_UNLIKELY (sink->need_preroll)) {
2416     GST_DEBUG_OBJECT (sink, "prerolling object %p", obj);
2417
2418     /* if it's a buffer, we need to call the preroll method */
2419     if (sink->priv->call_preroll) {
2420       GstBaseSinkClass *bclass;
2421       GstBuffer *buf;
2422
2423       if (GST_IS_BUFFER_LIST (obj)) {
2424         buf = gst_buffer_list_get (GST_BUFFER_LIST_CAST (obj), 0);
2425         gst_base_sink_set_last_buffer (sink, buf);
2426         gst_base_sink_set_last_buffer_list (sink, GST_BUFFER_LIST_CAST (obj));
2427         g_assert (NULL != buf);
2428       } else if (GST_IS_BUFFER (obj)) {
2429         buf = GST_BUFFER_CAST (obj);
2430         /* For buffer lists do not set last buffer for now */
2431         gst_base_sink_set_last_buffer (sink, buf);
2432         gst_base_sink_set_last_buffer_list (sink, NULL);
2433       } else {
2434         buf = NULL;
2435       }
2436
2437       if (buf) {
2438         GST_DEBUG_OBJECT (sink, "preroll buffer %" GST_TIME_FORMAT,
2439             GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
2440
2441         bclass = GST_BASE_SINK_GET_CLASS (sink);
2442
2443         if (bclass->prepare)
2444           if ((ret = bclass->prepare (sink, buf)) != GST_FLOW_OK)
2445             goto prepare_canceled;
2446
2447         if (bclass->preroll)
2448           if ((ret = bclass->preroll (sink, buf)) != GST_FLOW_OK)
2449             goto preroll_canceled;
2450
2451         sink->priv->call_preroll = FALSE;
2452       }
2453     }
2454
2455     /* commit state */
2456     if (G_LIKELY (sink->playing_async)) {
2457       if (G_UNLIKELY (!gst_base_sink_commit_state (sink)))
2458         goto stopping;
2459     }
2460
2461     /* need to recheck here because the commit state could have
2462      * made us not need the preroll anymore */
2463     if (G_LIKELY (sink->need_preroll)) {
2464       /* block until the state changes, or we get a flush, or something */
2465       ret = gst_base_sink_wait_preroll (sink);
2466       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2467         goto preroll_failed;
2468     }
2469   }
2470   return GST_FLOW_OK;
2471
2472   /* ERRORS */
2473 prepare_canceled:
2474   {
2475     GST_DEBUG_OBJECT (sink, "prepare failed, abort state");
2476     gst_element_abort_state (GST_ELEMENT_CAST (sink));
2477     return ret;
2478   }
2479 preroll_canceled:
2480   {
2481     GST_DEBUG_OBJECT (sink, "preroll failed, abort state");
2482     gst_element_abort_state (GST_ELEMENT_CAST (sink));
2483     return ret;
2484   }
2485 stopping:
2486   {
2487     GST_DEBUG_OBJECT (sink, "stopping while committing state");
2488     return GST_FLOW_FLUSHING;
2489   }
2490 preroll_failed:
2491   {
2492     GST_DEBUG_OBJECT (sink, "preroll failed: %s", gst_flow_get_name (ret));
2493     return ret;
2494   }
2495 }
2496
2497 /**
2498  * gst_base_sink_wait:
2499  * @sink: the sink
2500  * @time: the running_time to be reached
2501  * @jitter: (out) (allow-none): the jitter to be filled with time diff, or %NULL
2502  *
2503  * This function will wait for preroll to complete and will then block until @time
2504  * is reached. It is usually called by subclasses that use their own internal
2505  * synchronisation but want to let some synchronization (like EOS) be handled
2506  * by the base class.
2507  *
2508  * This function should only be called with the PREROLL_LOCK held (like when
2509  * receiving an EOS event in the ::event vmethod or when handling buffers in
2510  * ::render).
2511  *
2512  * The @time argument should be the running_time of when the timeout should happen
2513  * and will be adjusted with any latency and offset configured in the sink.
2514  *
2515  * Returns: #GstFlowReturn
2516  */
2517 GstFlowReturn
2518 gst_base_sink_wait (GstBaseSink * sink, GstClockTime time,
2519     GstClockTimeDiff * jitter)
2520 {
2521   GstClockReturn status;
2522   GstFlowReturn ret;
2523
2524   do {
2525     GstClockTime stime;
2526
2527     GST_DEBUG_OBJECT (sink, "checking preroll");
2528
2529     /* first wait for the playing state before we can continue */
2530     while (G_UNLIKELY (sink->need_preroll)) {
2531       ret = gst_base_sink_wait_preroll (sink);
2532       if ((ret != GST_FLOW_OK) && (ret != GST_FLOW_STEP))
2533         goto flushing;
2534     }
2535
2536     /* preroll done, we can sync since we are in PLAYING now. */
2537     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
2538         GST_TIME_FORMAT, GST_TIME_ARGS (time));
2539
2540     /* compensate for latency, ts_offset and render delay */
2541     stime = gst_base_sink_adjust_time (sink, time);
2542
2543     /* wait for the clock, this can be interrupted because we got shut down or
2544      * we PAUSED. */
2545     status = gst_base_sink_wait_clock (sink, stime, jitter);
2546
2547     GST_DEBUG_OBJECT (sink, "clock returned %d", status);
2548
2549     /* invalid time, no clock or sync disabled, just continue then */
2550     if (status == GST_CLOCK_BADTIME)
2551       break;
2552
2553     /* waiting could have been interrupted and we can be flushing now */
2554     if (G_UNLIKELY (sink->flushing))
2555       goto flushing;
2556
2557     /* retry if we got unscheduled, which means we did not reach the timeout
2558      * yet. if some other error occurs, we continue. */
2559   } while (status == GST_CLOCK_UNSCHEDULED);
2560
2561   GST_DEBUG_OBJECT (sink, "end of stream");
2562
2563   return GST_FLOW_OK;
2564
2565   /* ERRORS */
2566 flushing:
2567   {
2568     GST_DEBUG_OBJECT (sink, "we are flushing");
2569     return GST_FLOW_FLUSHING;
2570   }
2571 }
2572
2573 /* with STREAM_LOCK, PREROLL_LOCK
2574  *
2575  * Make sure we are in PLAYING and synchronize an object to the clock.
2576  *
2577  * If we need preroll, we are not in PLAYING. We try to commit the state
2578  * if needed and then block if we still are not PLAYING.
2579  *
2580  * We start waiting on the clock in PLAYING. If we got interrupted, we
2581  * immediately try to re-preroll.
2582  *
2583  * Some objects do not need synchronisation (most events) and so this function
2584  * immediately returns GST_FLOW_OK.
2585  *
2586  * for objects that arrive later than max-lateness to be synchronized to the
2587  * clock have the @late boolean set to %TRUE.
2588  *
2589  * This function keeps a running average of the jitter (the diff between the
2590  * clock time and the requested sync time). The jitter is negative for
2591  * objects that arrive in time and positive for late buffers.
2592  *
2593  * does not take ownership of obj.
2594  */
2595 static GstFlowReturn
2596 gst_base_sink_do_sync (GstBaseSink * basesink,
2597     GstMiniObject * obj, gboolean * late, gboolean * step_end)
2598 {
2599   GstClockTimeDiff jitter = 0;
2600   gboolean syncable;
2601   GstClockReturn status = GST_CLOCK_OK;
2602   GstClockTime rstart, rstop, rnext, sstart, sstop, stime;
2603   gboolean do_sync;
2604   GstBaseSinkPrivate *priv;
2605   GstFlowReturn ret;
2606   GstStepInfo *current, *pending;
2607   gboolean stepped;
2608
2609   priv = basesink->priv;
2610
2611 do_step:
2612   sstart = sstop = rstart = rstop = rnext = GST_CLOCK_TIME_NONE;
2613   do_sync = TRUE;
2614   stepped = FALSE;
2615
2616   priv->current_rstart = GST_CLOCK_TIME_NONE;
2617
2618   /* get stepping info */
2619   current = &priv->current_step;
2620   pending = &priv->pending_step;
2621
2622   /* get timing information for this object against the render segment */
2623   syncable = gst_base_sink_get_sync_times (basesink, obj,
2624       &sstart, &sstop, &rstart, &rstop, &rnext, &do_sync, &stepped, current,
2625       step_end);
2626
2627   if (G_UNLIKELY (stepped))
2628     goto step_skipped;
2629
2630   /* a syncable object needs to participate in preroll and
2631    * clocking. All buffers and EOS are syncable. */
2632   if (G_UNLIKELY (!syncable))
2633     goto not_syncable;
2634
2635   /* store timing info for current object */
2636   priv->current_rstart = rstart;
2637   priv->current_rstop = (GST_CLOCK_TIME_IS_VALID (rstop) ? rstop : rstart);
2638
2639   /* save sync time for eos when the previous object needed sync */
2640   priv->eos_rtime = (do_sync ? rnext : GST_CLOCK_TIME_NONE);
2641
2642   /* calculate inter frame spacing */
2643   if (G_UNLIKELY (GST_CLOCK_TIME_IS_VALID (priv->prev_rstart) &&
2644           priv->prev_rstart < rstart)) {
2645     GstClockTime in_diff;
2646
2647     in_diff = rstart - priv->prev_rstart;
2648
2649     if (priv->avg_in_diff == -1)
2650       priv->avg_in_diff = in_diff;
2651     else
2652       priv->avg_in_diff = UPDATE_RUNNING_AVG (priv->avg_in_diff, in_diff);
2653
2654     GST_LOG_OBJECT (basesink, "avg frame diff %" GST_TIME_FORMAT,
2655         GST_TIME_ARGS (priv->avg_in_diff));
2656
2657   }
2658   priv->prev_rstart = rstart;
2659
2660   if (G_UNLIKELY (GST_CLOCK_TIME_IS_VALID (priv->earliest_in_time) &&
2661           rstart < priv->earliest_in_time))
2662     goto qos_dropped;
2663
2664 again:
2665   /* first do preroll, this makes sure we commit our state
2666    * to PAUSED and can continue to PLAYING. We cannot perform
2667    * any clock sync in PAUSED because there is no clock. */
2668   ret = gst_base_sink_do_preroll (basesink, obj);
2669   if (G_UNLIKELY (ret != GST_FLOW_OK))
2670     goto preroll_failed;
2671
2672   /* update the segment with a pending step if the current one is invalid and we
2673    * have a new pending one. We only accept new step updates after a preroll */
2674   if (G_UNLIKELY (pending->valid && !current->valid)) {
2675     start_stepping (basesink, &basesink->segment, pending, current);
2676     goto do_step;
2677   }
2678
2679   /* After rendering we store the position of the last buffer so that we can use
2680    * it to report the position. We need to take the lock here. */
2681   GST_OBJECT_LOCK (basesink);
2682   priv->current_sstart = sstart;
2683   priv->current_sstop = (GST_CLOCK_TIME_IS_VALID (sstop) ? sstop : sstart);
2684   GST_OBJECT_UNLOCK (basesink);
2685
2686   if (!do_sync)
2687     goto done;
2688
2689   /* adjust for latency */
2690   stime = gst_base_sink_adjust_time (basesink, rstart);
2691
2692   /* adjust for rate control */
2693   if (priv->rc_next == -1 || (stime != -1 && stime >= priv->rc_next)) {
2694     GST_DEBUG_OBJECT (basesink, "reset rc_time to time %" GST_TIME_FORMAT,
2695         GST_TIME_ARGS (stime));
2696     priv->rc_time = stime;
2697     priv->rc_accumulated = 0;
2698   } else {
2699     GST_DEBUG_OBJECT (basesink, "rate control next %" GST_TIME_FORMAT,
2700         GST_TIME_ARGS (priv->rc_next));
2701     stime = priv->rc_next;
2702   }
2703
2704   /* preroll done, we can sync since we are in PLAYING now. */
2705   GST_DEBUG_OBJECT (basesink, "possibly waiting for clock to reach %"
2706       GST_TIME_FORMAT ", adjusted %" GST_TIME_FORMAT,
2707       GST_TIME_ARGS (rstart), GST_TIME_ARGS (stime));
2708
2709   /* This function will return immediately if start == -1, no clock
2710    * or sync is disabled with GST_CLOCK_BADTIME. */
2711   status = gst_base_sink_wait_clock (basesink, stime, &jitter);
2712
2713   GST_DEBUG_OBJECT (basesink, "clock returned %d, jitter %c%" GST_TIME_FORMAT,
2714       status, (jitter < 0 ? '-' : ' '), GST_TIME_ARGS (ABS (jitter)));
2715
2716   /* invalid time, no clock or sync disabled, just render */
2717   if (status == GST_CLOCK_BADTIME)
2718     goto done;
2719
2720   /* waiting could have been interrupted and we can be flushing now */
2721   if (G_UNLIKELY (basesink->flushing))
2722     goto flushing;
2723
2724   /* check for unlocked by a state change, we are not flushing so
2725    * we can try to preroll on the current buffer. */
2726   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
2727     GST_DEBUG_OBJECT (basesink, "unscheduled, waiting some more");
2728     priv->call_preroll = TRUE;
2729     goto again;
2730   }
2731
2732   /* successful syncing done, record observation */
2733   priv->current_jitter = jitter;
2734
2735   /* check if the object should be dropped */
2736   *late = gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
2737       status, jitter, TRUE);
2738
2739 done:
2740   return GST_FLOW_OK;
2741
2742   /* ERRORS */
2743 step_skipped:
2744   {
2745     GST_DEBUG_OBJECT (basesink, "skipped stepped object %p", obj);
2746     *late = TRUE;
2747     return GST_FLOW_OK;
2748   }
2749 not_syncable:
2750   {
2751     GST_DEBUG_OBJECT (basesink, "non syncable object %p", obj);
2752     return GST_FLOW_OK;
2753   }
2754 qos_dropped:
2755   {
2756     GST_DEBUG_OBJECT (basesink, "dropped because of QoS %p", obj);
2757     *late = TRUE;
2758     return GST_FLOW_OK;
2759   }
2760 flushing:
2761   {
2762     GST_DEBUG_OBJECT (basesink, "we are flushing");
2763     return GST_FLOW_FLUSHING;
2764   }
2765 preroll_failed:
2766   {
2767     GST_DEBUG_OBJECT (basesink, "preroll failed");
2768     *step_end = FALSE;
2769     return ret;
2770   }
2771 }
2772
2773 static gboolean
2774 gst_base_sink_send_qos (GstBaseSink * basesink, GstQOSType type,
2775     gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
2776 {
2777   GstEvent *event;
2778   gboolean res;
2779
2780   /* generate Quality-of-Service event */
2781   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
2782       "qos: type %d, proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
2783       GST_TIME_FORMAT, type, proportion, diff, GST_TIME_ARGS (time));
2784
2785   event = gst_event_new_qos (type, proportion, diff, time);
2786
2787   /* send upstream */
2788   res = gst_pad_push_event (basesink->sinkpad, event);
2789
2790   return res;
2791 }
2792
2793 static void
2794 gst_base_sink_perform_qos (GstBaseSink * sink, gboolean dropped)
2795 {
2796   GstBaseSinkPrivate *priv;
2797   GstClockTime start, stop;
2798   GstClockTimeDiff jitter;
2799   GstClockTime pt, entered, left;
2800   GstClockTime duration;
2801   gdouble rate;
2802
2803   priv = sink->priv;
2804
2805   start = priv->current_rstart;
2806
2807   if (priv->current_step.valid)
2808     return;
2809
2810   /* if Quality-of-Service disabled, do nothing */
2811   if (!g_atomic_int_get (&priv->qos_enabled) ||
2812       !GST_CLOCK_TIME_IS_VALID (start))
2813     return;
2814
2815   stop = priv->current_rstop;
2816   jitter = priv->current_jitter;
2817
2818   if (jitter < 0) {
2819     /* this is the time the buffer entered the sink */
2820     if (start < -jitter)
2821       entered = 0;
2822     else
2823       entered = start + jitter;
2824     left = start;
2825   } else {
2826     /* this is the time the buffer entered the sink */
2827     entered = start + jitter;
2828     /* this is the time the buffer left the sink */
2829     left = start + jitter;
2830   }
2831
2832   /* calculate duration of the buffer, only use buffer durations if not in
2833    * trick mode or key-unit mode. Otherwise the buffer durations will be
2834    * meaningless as frames are being dropped in-between without updating the
2835    * durations. */
2836   duration = priv->avg_in_diff;
2837
2838   /* if we have the time when the last buffer left us, calculate
2839    * processing time */
2840   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2841     if (entered > priv->last_left) {
2842       pt = entered - priv->last_left;
2843     } else {
2844       pt = 0;
2845     }
2846   } else {
2847     pt = priv->avg_pt;
2848   }
2849
2850   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink, "start: %" GST_TIME_FORMAT
2851       ", stop %" GST_TIME_FORMAT ", entered %" GST_TIME_FORMAT ", left %"
2852       GST_TIME_FORMAT ", pt: %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2853       ",jitter %" G_GINT64_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
2854       GST_TIME_ARGS (entered), GST_TIME_ARGS (left), GST_TIME_ARGS (pt),
2855       GST_TIME_ARGS (duration), jitter);
2856
2857   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2858       "avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
2859       GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2860
2861   /* collect running averages. for first observations, we copy the
2862    * values */
2863   if (!GST_CLOCK_TIME_IS_VALID (priv->avg_pt))
2864     priv->avg_pt = pt;
2865   else
2866     priv->avg_pt = UPDATE_RUNNING_AVG (priv->avg_pt, pt);
2867
2868   if (duration != -1 && duration != 0) {
2869     rate =
2870         gst_guint64_to_gdouble (priv->avg_pt) /
2871         gst_guint64_to_gdouble (duration);
2872   } else {
2873     rate = 1.0;
2874   }
2875
2876   if (GST_CLOCK_TIME_IS_VALID (priv->last_left)) {
2877     if (dropped || priv->avg_rate < 0.0) {
2878       priv->avg_rate = rate;
2879     } else {
2880       if (rate > 1.0)
2881         priv->avg_rate = UPDATE_RUNNING_AVG_N (priv->avg_rate, rate);
2882       else
2883         priv->avg_rate = UPDATE_RUNNING_AVG_P (priv->avg_rate, rate);
2884     }
2885   }
2886
2887   GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, sink,
2888       "updated: avg_pt: %" GST_TIME_FORMAT
2889       ", avg_rate: %g", GST_TIME_ARGS (priv->avg_pt), priv->avg_rate);
2890
2891
2892   if (priv->avg_rate >= 0.0) {
2893     GstQOSType type;
2894     GstClockTimeDiff diff;
2895
2896     /* if we have a valid rate, start sending QoS messages */
2897     if (priv->current_jitter < 0) {
2898       /* make sure we never go below 0 when adding the jitter to the
2899        * timestamp. */
2900       if (priv->current_rstart < -priv->current_jitter)
2901         priv->current_jitter = -priv->current_rstart;
2902     }
2903
2904     if (priv->throttle_time > 0) {
2905       diff = priv->throttle_time;
2906       type = GST_QOS_TYPE_THROTTLE;
2907     } else {
2908       diff = priv->current_jitter;
2909       if (diff <= 0)
2910         type = GST_QOS_TYPE_OVERFLOW;
2911       else
2912         type = GST_QOS_TYPE_UNDERFLOW;
2913     }
2914
2915     gst_base_sink_send_qos (sink, type, priv->avg_rate, priv->current_rstart,
2916         diff);
2917   }
2918
2919   /* record when this buffer will leave us */
2920   priv->last_left = left;
2921 }
2922
2923 /* reset all qos measuring */
2924 static void
2925 gst_base_sink_reset_qos (GstBaseSink * sink)
2926 {
2927   GstBaseSinkPrivate *priv;
2928
2929   priv = sink->priv;
2930
2931   priv->last_render_time = GST_CLOCK_TIME_NONE;
2932   priv->prev_rstart = GST_CLOCK_TIME_NONE;
2933   priv->earliest_in_time = GST_CLOCK_TIME_NONE;
2934   priv->last_left = GST_CLOCK_TIME_NONE;
2935   priv->avg_pt = GST_CLOCK_TIME_NONE;
2936   priv->avg_rate = -1.0;
2937   priv->avg_in_diff = GST_CLOCK_TIME_NONE;
2938   priv->rendered = 0;
2939   priv->dropped = 0;
2940
2941 }
2942
2943 /* Checks if the object was scheduled too late.
2944  *
2945  * rstart/rstop contain the running_time start and stop values
2946  * of the object.
2947  *
2948  * status and jitter contain the return values from the clock wait.
2949  *
2950  * returns %TRUE if the buffer was too late.
2951  */
2952 static gboolean
2953 gst_base_sink_is_too_late (GstBaseSink * basesink, GstMiniObject * obj,
2954     GstClockTime rstart, GstClockTime rstop,
2955     GstClockReturn status, GstClockTimeDiff jitter, gboolean render)
2956 {
2957   gboolean late;
2958   guint64 max_lateness;
2959   GstBaseSinkPrivate *priv;
2960
2961   priv = basesink->priv;
2962
2963   late = FALSE;
2964
2965   /* only for objects that were too late */
2966   if (G_LIKELY (status != GST_CLOCK_EARLY))
2967     goto in_time;
2968
2969   max_lateness = basesink->max_lateness;
2970
2971   /* check if frame dropping is enabled */
2972   if (max_lateness == -1)
2973     goto no_drop;
2974
2975   /* only check for buffers */
2976   if (G_UNLIKELY (!GST_IS_BUFFER (obj)))
2977     goto not_buffer;
2978
2979   /* can't do check if we don't have a timestamp */
2980   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (rstart)))
2981     goto no_timestamp;
2982
2983   /* we can add a valid stop time */
2984   if (GST_CLOCK_TIME_IS_VALID (rstop))
2985     max_lateness += rstop;
2986   else {
2987     max_lateness += rstart;
2988     /* no stop time, use avg frame diff */
2989     if (priv->avg_in_diff != -1)
2990       max_lateness += priv->avg_in_diff;
2991   }
2992
2993   /* if the jitter bigger than duration and lateness we are too late */
2994   if ((late = rstart + jitter > max_lateness)) {
2995     GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
2996         "buffer is too late %" GST_TIME_FORMAT
2997         " > %" GST_TIME_FORMAT, GST_TIME_ARGS (rstart + jitter),
2998         GST_TIME_ARGS (max_lateness));
2999     /* !!emergency!!, if we did not receive anything valid for more than a
3000      * second, render it anyway so the user sees something */
3001     if (GST_CLOCK_TIME_IS_VALID (priv->last_render_time) &&
3002         rstart - priv->last_render_time > GST_SECOND) {
3003       late = FALSE;
3004       GST_ELEMENT_WARNING (basesink, CORE, CLOCK,
3005           (_("A lot of buffers are being dropped.")),
3006           ("There may be a timestamping problem, or this computer is too slow."));
3007       GST_CAT_DEBUG_OBJECT (GST_CAT_PERFORMANCE, basesink,
3008           "**emergency** last buffer at %" GST_TIME_FORMAT " > GST_SECOND",
3009           GST_TIME_ARGS (priv->last_render_time));
3010     }
3011   }
3012
3013 done:
3014   if (render && (!late || !GST_CLOCK_TIME_IS_VALID (priv->last_render_time))) {
3015     priv->last_render_time = rstart;
3016     /* the next allowed input timestamp */
3017     if (priv->throttle_time > 0)
3018       priv->earliest_in_time = rstart + priv->throttle_time;
3019   }
3020   return late;
3021
3022   /* all is fine */
3023 in_time:
3024   {
3025     GST_DEBUG_OBJECT (basesink, "object was scheduled in time");
3026     goto done;
3027   }
3028 no_drop:
3029   {
3030     GST_DEBUG_OBJECT (basesink, "frame dropping disabled");
3031     goto done;
3032   }
3033 not_buffer:
3034   {
3035     GST_DEBUG_OBJECT (basesink, "object is not a buffer");
3036     return FALSE;
3037   }
3038 no_timestamp:
3039   {
3040     GST_DEBUG_OBJECT (basesink, "buffer has no timestamp");
3041     return FALSE;
3042   }
3043 }
3044
3045 static void
3046 gst_base_sink_update_start_time (GstBaseSink * basesink)
3047 {
3048   GstClock *clock;
3049
3050   GST_OBJECT_LOCK (basesink);
3051   if (GST_STATE (basesink) == GST_STATE_PLAYING
3052       && (clock = GST_ELEMENT_CLOCK (basesink))) {
3053     GstClockTime now;
3054
3055     gst_object_ref (clock);
3056     GST_OBJECT_UNLOCK (basesink);
3057
3058     /* calculate the time when we stopped */
3059     now = gst_clock_get_time (clock);
3060     gst_object_unref (clock);
3061
3062     GST_OBJECT_LOCK (basesink);
3063     /* store the current running time */
3064     if (GST_ELEMENT_START_TIME (basesink) != GST_CLOCK_TIME_NONE) {
3065       if (now != GST_CLOCK_TIME_NONE)
3066         GST_ELEMENT_START_TIME (basesink) =
3067             now - GST_ELEMENT_CAST (basesink)->base_time;
3068       else
3069         GST_WARNING_OBJECT (basesink,
3070             "Clock %s returned invalid time, can't calculate "
3071             "running_time when going to the PAUSED state",
3072             GST_OBJECT_NAME (clock));
3073     }
3074     GST_DEBUG_OBJECT (basesink,
3075         "start_time=%" GST_TIME_FORMAT ", now=%" GST_TIME_FORMAT
3076         ", base_time %" GST_TIME_FORMAT,
3077         GST_TIME_ARGS (GST_ELEMENT_START_TIME (basesink)),
3078         GST_TIME_ARGS (now),
3079         GST_TIME_ARGS (GST_ELEMENT_CAST (basesink)->base_time));
3080   }
3081   GST_OBJECT_UNLOCK (basesink);
3082 }
3083
3084 static void
3085 gst_base_sink_flush_start (GstBaseSink * basesink, GstPad * pad)
3086 {
3087   /* make sure we are not blocked on the clock also clear any pending
3088    * eos state. */
3089   gst_base_sink_set_flushing (basesink, pad, TRUE);
3090
3091   /* we grab the stream lock but that is not needed since setting the
3092    * sink to flushing would make sure no state commit is being done
3093    * anymore */
3094   GST_PAD_STREAM_LOCK (pad);
3095   gst_base_sink_reset_qos (basesink);
3096   /* and we need to commit our state again on the next
3097    * prerolled buffer */
3098   basesink->playing_async = TRUE;
3099   if (basesink->priv->async_enabled) {
3100     gst_base_sink_update_start_time (basesink);
3101     gst_element_lost_state (GST_ELEMENT_CAST (basesink));
3102   } else {
3103     /* start time reset in above case as well;
3104      * arranges for a.o. proper position reporting when flushing in PAUSED */
3105     gst_element_set_start_time (GST_ELEMENT_CAST (basesink), 0);
3106     basesink->priv->have_latency = TRUE;
3107   }
3108   gst_base_sink_set_last_buffer (basesink, NULL);
3109   gst_base_sink_set_last_buffer_list (basesink, NULL);
3110   GST_PAD_STREAM_UNLOCK (pad);
3111 }
3112
3113 static void
3114 gst_base_sink_flush_stop (GstBaseSink * basesink, GstPad * pad,
3115     gboolean reset_time)
3116 {
3117   /* unset flushing so we can accept new data, this also flushes out any EOS
3118    * event. */
3119   gst_base_sink_set_flushing (basesink, pad, FALSE);
3120
3121   /* for position reporting */
3122   GST_OBJECT_LOCK (basesink);
3123   basesink->priv->current_sstart = GST_CLOCK_TIME_NONE;
3124   basesink->priv->current_sstop = GST_CLOCK_TIME_NONE;
3125   basesink->priv->eos_rtime = GST_CLOCK_TIME_NONE;
3126   basesink->priv->call_preroll = TRUE;
3127   basesink->priv->current_step.valid = FALSE;
3128   basesink->priv->pending_step.valid = FALSE;
3129   if (basesink->pad_mode == GST_PAD_MODE_PUSH) {
3130     /* we need new segment info after the flush. */
3131     basesink->have_newsegment = FALSE;
3132     if (reset_time) {
3133       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
3134       GST_ELEMENT_START_TIME (basesink) = 0;
3135     }
3136   }
3137   GST_OBJECT_UNLOCK (basesink);
3138
3139   if (reset_time) {
3140     GST_DEBUG_OBJECT (basesink, "posting reset-time message");
3141     gst_element_post_message (GST_ELEMENT_CAST (basesink),
3142         gst_message_new_reset_time (GST_OBJECT_CAST (basesink), 0));
3143   }
3144 }
3145
3146 static GstFlowReturn
3147 gst_base_sink_default_wait_event (GstBaseSink * basesink, GstEvent * event)
3148 {
3149   GstFlowReturn ret;
3150   gboolean late, step_end = FALSE;
3151
3152   ret = gst_base_sink_do_sync (basesink, GST_MINI_OBJECT_CAST (event),
3153       &late, &step_end);
3154
3155   return ret;
3156 }
3157
3158 static GstFlowReturn
3159 gst_base_sink_wait_event (GstBaseSink * basesink, GstEvent * event)
3160 {
3161   GstFlowReturn ret;
3162   GstBaseSinkClass *bclass;
3163
3164   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3165
3166   if (G_LIKELY (bclass->wait_event))
3167     ret = bclass->wait_event (basesink, event);
3168   else
3169     ret = GST_FLOW_NOT_SUPPORTED;
3170
3171   return ret;
3172 }
3173
3174 static gboolean
3175 gst_base_sink_default_event (GstBaseSink * basesink, GstEvent * event)
3176 {
3177   gboolean result = TRUE;
3178   GstBaseSinkClass *bclass;
3179
3180   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3181
3182   switch (GST_EVENT_TYPE (event)) {
3183     case GST_EVENT_FLUSH_START:
3184     {
3185       GST_DEBUG_OBJECT (basesink, "flush-start %p", event);
3186       gst_base_sink_flush_start (basesink, basesink->sinkpad);
3187       break;
3188     }
3189     case GST_EVENT_FLUSH_STOP:
3190     {
3191       gboolean reset_time;
3192
3193       gst_event_parse_flush_stop (event, &reset_time);
3194       GST_DEBUG_OBJECT (basesink, "flush-stop %p, reset_time: %d", event,
3195           reset_time);
3196       gst_base_sink_flush_stop (basesink, basesink->sinkpad, reset_time);
3197       break;
3198     }
3199     case GST_EVENT_EOS:
3200     {
3201       GstMessage *message;
3202       guint32 seqnum;
3203
3204       /* we set the received EOS flag here so that we can use it when testing if
3205        * we are prerolled and to refuse more buffers. */
3206       basesink->priv->received_eos = TRUE;
3207
3208       /* wait for EOS */
3209       if (G_UNLIKELY (gst_base_sink_wait_event (basesink,
3210                   event) != GST_FLOW_OK)) {
3211         result = FALSE;
3212         goto done;
3213       }
3214
3215       /* the EOS event is completely handled so we mark
3216        * ourselves as being in the EOS state. eos is also
3217        * protected by the object lock so we can read it when
3218        * answering the POSITION query. */
3219       GST_OBJECT_LOCK (basesink);
3220       basesink->eos = TRUE;
3221       GST_OBJECT_UNLOCK (basesink);
3222
3223       /* ok, now we can post the message */
3224       GST_DEBUG_OBJECT (basesink, "Now posting EOS");
3225
3226       seqnum = basesink->priv->seqnum = gst_event_get_seqnum (event);
3227       GST_DEBUG_OBJECT (basesink, "Got seqnum #%" G_GUINT32_FORMAT, seqnum);
3228
3229       message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
3230       gst_message_set_seqnum (message, seqnum);
3231       gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
3232       break;
3233     }
3234     case GST_EVENT_STREAM_START:
3235     {
3236       GstMessage *message;
3237       guint32 seqnum;
3238       guint group_id;
3239
3240       seqnum = gst_event_get_seqnum (event);
3241       GST_DEBUG_OBJECT (basesink, "Now posting STREAM_START (seqnum:%d)",
3242           seqnum);
3243       message = gst_message_new_stream_start (GST_OBJECT_CAST (basesink));
3244       if (gst_event_parse_group_id (event, &group_id)) {
3245         gst_message_set_group_id (message, group_id);
3246       } else {
3247         GST_FIXME_OBJECT (basesink, "stream-start event without group-id. "
3248             "Consider implementing group-id handling in the upstream "
3249             "elements");
3250       }
3251       gst_message_set_seqnum (message, seqnum);
3252       gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
3253       break;
3254     }
3255     case GST_EVENT_CAPS:
3256     {
3257       GstCaps *caps, *current_caps;
3258
3259       GST_DEBUG_OBJECT (basesink, "caps %p", event);
3260
3261       gst_event_parse_caps (event, &caps);
3262       current_caps = gst_pad_get_current_caps (GST_BASE_SINK_PAD (basesink));
3263
3264       if (current_caps && gst_caps_is_equal (current_caps, caps)) {
3265         GST_DEBUG_OBJECT (basesink,
3266             "New caps equal to old ones: %" GST_PTR_FORMAT, caps);
3267       } else {
3268         if (bclass->set_caps)
3269           result = bclass->set_caps (basesink, caps);
3270
3271         if (result) {
3272           GST_OBJECT_LOCK (basesink);
3273           gst_caps_replace (&basesink->priv->caps, caps);
3274           GST_OBJECT_UNLOCK (basesink);
3275         }
3276       }
3277       if (current_caps)
3278         gst_caps_unref (current_caps);
3279       break;
3280     }
3281     case GST_EVENT_SEGMENT:
3282       /* configure the segment */
3283       /* The segment is protected with both the STREAM_LOCK and the OBJECT_LOCK.
3284        * We protect with the OBJECT_LOCK so that we can use the values to
3285        * safely answer a POSITION query. */
3286       GST_OBJECT_LOCK (basesink);
3287       /* the newsegment event is needed to bring the buffer timestamps to the
3288        * stream time and to drop samples outside of the playback segment. */
3289       gst_event_copy_segment (event, &basesink->segment);
3290       GST_DEBUG_OBJECT (basesink, "configured segment %" GST_SEGMENT_FORMAT,
3291           &basesink->segment);
3292       basesink->have_newsegment = TRUE;
3293       gst_base_sink_reset_qos (basesink);
3294       GST_OBJECT_UNLOCK (basesink);
3295       break;
3296     case GST_EVENT_GAP:
3297     {
3298       if (G_UNLIKELY (gst_base_sink_wait_event (basesink,
3299                   event) != GST_FLOW_OK))
3300         result = FALSE;
3301       break;
3302     }
3303     case GST_EVENT_TAG:
3304     {
3305       GstTagList *taglist;
3306
3307       gst_event_parse_tag (event, &taglist);
3308
3309       gst_element_post_message (GST_ELEMENT_CAST (basesink),
3310           gst_message_new_tag (GST_OBJECT_CAST (basesink),
3311               gst_tag_list_copy (taglist)));
3312       break;
3313     }
3314     case GST_EVENT_TOC:
3315     {
3316       GstToc *toc;
3317       gboolean updated;
3318
3319       gst_event_parse_toc (event, &toc, &updated);
3320
3321       gst_element_post_message (GST_ELEMENT_CAST (basesink),
3322           gst_message_new_toc (GST_OBJECT_CAST (basesink), toc, updated));
3323
3324       gst_toc_unref (toc);
3325       break;
3326     }
3327     case GST_EVENT_SINK_MESSAGE:
3328     {
3329       GstMessage *msg = NULL;
3330
3331       gst_event_parse_sink_message (event, &msg);
3332       if (msg)
3333         gst_element_post_message (GST_ELEMENT_CAST (basesink), msg);
3334       break;
3335     }
3336     default:
3337       break;
3338   }
3339 done:
3340   gst_event_unref (event);
3341
3342   return result;
3343 }
3344
3345 static gboolean
3346 gst_base_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
3347 {
3348   GstBaseSink *basesink;
3349   gboolean result = TRUE;
3350   GstBaseSinkClass *bclass;
3351
3352   basesink = GST_BASE_SINK_CAST (parent);
3353   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3354
3355   GST_DEBUG_OBJECT (basesink, "received event %p %" GST_PTR_FORMAT, event,
3356       event);
3357
3358   switch (GST_EVENT_TYPE (event)) {
3359     case GST_EVENT_FLUSH_STOP:
3360       /* special case for this serialized event because we don't want to grab
3361        * the PREROLL lock or check if we were flushing */
3362       if (bclass->event)
3363         result = bclass->event (basesink, event);
3364       break;
3365     default:
3366       if (GST_EVENT_IS_SERIALIZED (event)) {
3367         GST_BASE_SINK_PREROLL_LOCK (basesink);
3368         if (G_UNLIKELY (basesink->flushing))
3369           goto flushing;
3370
3371         if (G_UNLIKELY (basesink->priv->received_eos))
3372           goto after_eos;
3373
3374         if (bclass->event)
3375           result = bclass->event (basesink, event);
3376
3377         GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3378       } else {
3379         if (bclass->event)
3380           result = bclass->event (basesink, event);
3381       }
3382       break;
3383   }
3384 done:
3385   return result;
3386
3387   /* ERRORS */
3388 flushing:
3389   {
3390     GST_DEBUG_OBJECT (basesink, "we are flushing");
3391     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3392     gst_event_unref (event);
3393     result = FALSE;
3394     goto done;
3395   }
3396
3397 after_eos:
3398   {
3399     GST_DEBUG_OBJECT (basesink, "Event received after EOS, dropping");
3400     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3401     gst_event_unref (event);
3402     result = FALSE;
3403     goto done;
3404   }
3405 }
3406
3407 /* default implementation to calculate the start and end
3408  * timestamps on a buffer, subclasses can override
3409  */
3410 static void
3411 gst_base_sink_default_get_times (GstBaseSink * basesink, GstBuffer * buffer,
3412     GstClockTime * start, GstClockTime * end)
3413 {
3414   GstClockTime timestamp, duration;
3415
3416   /* first sync on DTS, else use PTS */
3417   timestamp = GST_BUFFER_DTS (buffer);
3418   if (!GST_CLOCK_TIME_IS_VALID (timestamp))
3419     timestamp = GST_BUFFER_PTS (buffer);
3420
3421   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
3422     /* get duration to calculate end time */
3423     duration = GST_BUFFER_DURATION (buffer);
3424     if (GST_CLOCK_TIME_IS_VALID (duration)) {
3425       *end = timestamp + duration;
3426     }
3427     *start = timestamp;
3428   }
3429 }
3430
3431 /* must be called with PREROLL_LOCK */
3432 static gboolean
3433 gst_base_sink_needs_preroll (GstBaseSink * basesink)
3434 {
3435   gboolean is_prerolled, res;
3436
3437   /* we have 2 cases where the PREROLL_LOCK is released:
3438    *  1) we are blocking in the PREROLL_LOCK and thus are prerolled.
3439    *  2) we are syncing on the clock
3440    */
3441   is_prerolled = basesink->have_preroll || basesink->priv->received_eos;
3442   res = !is_prerolled;
3443
3444   GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d => needs preroll: %d",
3445       basesink->have_preroll, basesink->priv->received_eos, res);
3446
3447   return res;
3448 }
3449
3450 /* with STREAM_LOCK, PREROLL_LOCK
3451  *
3452  * Takes a buffer and compare the timestamps with the last segment.
3453  * If the buffer falls outside of the segment boundaries, drop it.
3454  * Else send the buffer for preroll and rendering.
3455  *
3456  * This function takes ownership of the buffer.
3457  */
3458 static GstFlowReturn
3459 gst_base_sink_chain_unlocked (GstBaseSink * basesink, GstPad * pad,
3460     gpointer obj, gboolean is_list)
3461 {
3462   GstBaseSinkClass *bclass;
3463   GstBaseSinkPrivate *priv = basesink->priv;
3464   GstFlowReturn ret = GST_FLOW_OK;
3465   GstClockTime start = GST_CLOCK_TIME_NONE, end = GST_CLOCK_TIME_NONE;
3466   GstSegment *segment;
3467   GstBuffer *sync_buf;
3468   gboolean late, step_end, prepared = FALSE;
3469
3470   if (G_UNLIKELY (basesink->flushing))
3471     goto flushing;
3472
3473   if (G_UNLIKELY (priv->received_eos))
3474     goto was_eos;
3475
3476   if (is_list) {
3477     GstBufferList *buffer_list = GST_BUFFER_LIST_CAST (obj);
3478
3479     if (gst_buffer_list_length (buffer_list) == 0)
3480       goto empty_list;
3481
3482     sync_buf = gst_buffer_list_get (buffer_list, 0);
3483     g_assert (NULL != sync_buf);
3484   } else {
3485     sync_buf = GST_BUFFER_CAST (obj);
3486   }
3487
3488   /* for code clarity */
3489   segment = &basesink->segment;
3490
3491   if (G_UNLIKELY (!basesink->have_newsegment)) {
3492     gboolean sync;
3493
3494     sync = gst_base_sink_get_sync (basesink);
3495     if (sync) {
3496       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
3497           (_("Internal data flow problem.")),
3498           ("Received buffer without a new-segment. Assuming timestamps start from 0."));
3499     }
3500
3501     /* this means this sink will assume timestamps start from 0 */
3502     GST_OBJECT_LOCK (basesink);
3503     segment->start = 0;
3504     segment->stop = -1;
3505     basesink->segment.start = 0;
3506     basesink->segment.stop = -1;
3507     basesink->have_newsegment = TRUE;
3508     GST_OBJECT_UNLOCK (basesink);
3509   }
3510
3511   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3512
3513   /* check if the buffer needs to be dropped, we first ask the subclass for the
3514    * start and end */
3515   if (bclass->get_times)
3516     bclass->get_times (basesink, sync_buf, &start, &end);
3517
3518   if (!GST_CLOCK_TIME_IS_VALID (start)) {
3519     /* if the subclass does not want sync, we use our own values so that we at
3520      * least clip the buffer to the segment */
3521     gst_base_sink_default_get_times (basesink, sync_buf, &start, &end);
3522   }
3523
3524   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
3525       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
3526
3527   /* a dropped buffer does not participate in anything. Buffer can only be
3528    * dropped if their PTS falls completely outside the segment, while we sync
3529    * preferably on DTS */
3530   if (GST_CLOCK_TIME_IS_VALID (start) && (segment->format == GST_FORMAT_TIME)) {
3531     GstClockTime pts = GST_BUFFER_PTS (sync_buf);
3532     GstClockTime pts_end = GST_CLOCK_TIME_NONE;
3533
3534     if (!GST_CLOCK_TIME_IS_VALID (pts))
3535       pts = start;
3536
3537     if (GST_CLOCK_TIME_IS_VALID (end))
3538       pts_end = pts + (end - start);
3539
3540     if (G_UNLIKELY (!gst_segment_clip (segment,
3541                 GST_FORMAT_TIME, pts, pts_end, NULL, NULL)
3542             && priv->drop_out_of_segment))
3543       goto out_of_segment;
3544   }
3545
3546   if (bclass->prepare || bclass->prepare_list) {
3547     gboolean do_sync = TRUE, stepped = FALSE, syncable = TRUE;
3548     GstClockTime sstart, sstop, rstart, rstop, rnext;
3549     GstStepInfo *current;
3550
3551     late = FALSE;
3552     step_end = FALSE;
3553
3554     current = &priv->current_step;
3555     syncable =
3556         gst_base_sink_get_sync_times (basesink, obj, &sstart, &sstop, &rstart,
3557         &rstop, &rnext, &do_sync, &stepped, current, &step_end);
3558
3559     if (G_UNLIKELY (stepped))
3560       goto dropped;
3561
3562     if (syncable && do_sync && gst_base_sink_get_sync (basesink)) {
3563       GstClock *clock;
3564
3565       GST_OBJECT_LOCK (basesink);
3566       clock = GST_ELEMENT_CLOCK (basesink);
3567       if (clock && GST_STATE (basesink) == GST_STATE_PLAYING) {
3568         GstClockTime base_time;
3569         GstClockTime stime;
3570         GstClockTime now;
3571
3572         base_time = GST_ELEMENT_CAST (basesink)->base_time;
3573         stime = base_time + gst_base_sink_adjust_time (basesink, rstart);
3574         now = gst_clock_get_time (clock);
3575         GST_OBJECT_UNLOCK (basesink);
3576
3577         late =
3578             gst_base_sink_is_too_late (basesink, obj, rstart, rstop,
3579             GST_CLOCK_EARLY, GST_CLOCK_DIFF (stime, now), FALSE);
3580       } else {
3581         GST_OBJECT_UNLOCK (basesink);
3582       }
3583     }
3584
3585     /* We are about to prepare the first frame, make sure we have prerolled
3586      * already. This prevent nesting prepare/render calls. */
3587     ret = gst_base_sink_do_preroll (basesink, obj);
3588     if (G_UNLIKELY (ret != GST_FLOW_OK))
3589       goto preroll_failed;
3590
3591     if (G_UNLIKELY (late))
3592       goto dropped;
3593
3594     if (!is_list) {
3595       if (bclass->prepare) {
3596         ret = bclass->prepare (basesink, GST_BUFFER_CAST (obj));
3597         if (G_UNLIKELY (ret != GST_FLOW_OK))
3598           goto prepare_failed;
3599       }
3600     } else {
3601       if (bclass->prepare_list) {
3602         ret = bclass->prepare_list (basesink, GST_BUFFER_LIST_CAST (obj));
3603         if (G_UNLIKELY (ret != GST_FLOW_OK))
3604           goto prepare_failed;
3605       }
3606     }
3607
3608     prepared = TRUE;
3609   }
3610
3611 again:
3612   late = FALSE;
3613   step_end = FALSE;
3614
3615   /* synchronize this object, non syncable objects return OK
3616    * immediately. */
3617   ret = gst_base_sink_do_sync (basesink, GST_MINI_OBJECT_CAST (sync_buf),
3618       &late, &step_end);
3619   if (G_UNLIKELY (ret != GST_FLOW_OK))
3620     goto sync_failed;
3621
3622   /* Don't skip if prepare() was called on time */
3623   late = late && !prepared;
3624
3625   /* drop late buffers unconditionally, let's hope it's unlikely */
3626   if (G_UNLIKELY (late))
3627     goto dropped;
3628
3629   if (priv->max_bitrate) {
3630     gsize size;
3631
3632     if (is_list)
3633       size = gst_buffer_list_calculate_size (GST_BUFFER_LIST_CAST (obj));
3634     else
3635       size = gst_buffer_get_size (GST_BUFFER_CAST (obj));
3636
3637     priv->rc_accumulated += size;
3638     priv->rc_next = priv->rc_time + gst_util_uint64_scale (priv->rc_accumulated,
3639         8 * GST_SECOND, priv->max_bitrate);
3640   }
3641
3642   GST_DEBUG_OBJECT (basesink, "rendering object %p", obj);
3643
3644   if (!is_list) {
3645     /* For buffer lists do not set last buffer for now. */
3646     gst_base_sink_set_last_buffer (basesink, GST_BUFFER_CAST (obj));
3647     gst_base_sink_set_last_buffer_list (basesink, NULL);
3648
3649     if (bclass->render)
3650       ret = bclass->render (basesink, GST_BUFFER_CAST (obj));
3651   } else {
3652     GstBufferList *buffer_list = GST_BUFFER_LIST_CAST (obj);
3653
3654     if (bclass->render_list)
3655       ret = bclass->render_list (basesink, buffer_list);
3656
3657     /* Set the first buffer and buffer list to be included in last sample */
3658     gst_base_sink_set_last_buffer (basesink, sync_buf);
3659     gst_base_sink_set_last_buffer_list (basesink, buffer_list);
3660   }
3661
3662   if (ret == GST_FLOW_STEP)
3663     goto again;
3664
3665   if (G_UNLIKELY (basesink->flushing))
3666     goto flushing;
3667
3668   priv->rendered++;
3669
3670 done:
3671   if (step_end) {
3672     /* the step ended, check if we need to activate a new step */
3673     GST_DEBUG_OBJECT (basesink, "step ended");
3674     stop_stepping (basesink, &basesink->segment, &priv->current_step,
3675         priv->current_rstart, priv->current_rstop, basesink->eos);
3676     goto again;
3677   }
3678
3679   gst_base_sink_perform_qos (basesink, late);
3680
3681   GST_DEBUG_OBJECT (basesink, "object unref after render %p", obj);
3682   gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3683
3684   return ret;
3685
3686   /* ERRORS */
3687 flushing:
3688   {
3689     GST_DEBUG_OBJECT (basesink, "sink is flushing");
3690     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3691     return GST_FLOW_FLUSHING;
3692   }
3693 was_eos:
3694   {
3695     GST_DEBUG_OBJECT (basesink, "we are EOS, dropping object, return EOS");
3696     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3697     return GST_FLOW_EOS;
3698   }
3699 empty_list:
3700   {
3701     GST_DEBUG_OBJECT (basesink, "buffer list with no buffers");
3702     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3703     return GST_FLOW_OK;
3704   }
3705 out_of_segment:
3706   {
3707     GST_DEBUG_OBJECT (basesink, "dropping buffer, out of clipping segment");
3708     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3709     return GST_FLOW_OK;
3710   }
3711 prepare_failed:
3712   {
3713     GST_DEBUG_OBJECT (basesink, "prepare buffer failed %s",
3714         gst_flow_get_name (ret));
3715     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3716     return ret;
3717   }
3718 sync_failed:
3719   {
3720     GST_DEBUG_OBJECT (basesink, "do_sync returned %s", gst_flow_get_name (ret));
3721     goto done;
3722   }
3723 dropped:
3724   {
3725     priv->dropped++;
3726     GST_DEBUG_OBJECT (basesink, "buffer late, dropping");
3727
3728     if (g_atomic_int_get (&priv->qos_enabled)) {
3729       GstMessage *qos_msg;
3730       GstClockTime timestamp, duration;
3731
3732       timestamp = GST_BUFFER_TIMESTAMP (GST_BUFFER_CAST (sync_buf));
3733       duration = GST_BUFFER_DURATION (GST_BUFFER_CAST (sync_buf));
3734
3735       GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
3736           "qos: dropped buffer rt %" GST_TIME_FORMAT ", st %" GST_TIME_FORMAT
3737           ", ts %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT,
3738           GST_TIME_ARGS (priv->current_rstart),
3739           GST_TIME_ARGS (priv->current_sstart), GST_TIME_ARGS (timestamp),
3740           GST_TIME_ARGS (duration));
3741       GST_CAT_DEBUG_OBJECT (GST_CAT_QOS, basesink,
3742           "qos: rendered %" G_GUINT64_FORMAT ", dropped %" G_GUINT64_FORMAT,
3743           priv->rendered, priv->dropped);
3744
3745       qos_msg =
3746           gst_message_new_qos (GST_OBJECT_CAST (basesink), basesink->sync,
3747           priv->current_rstart, priv->current_sstart, timestamp, duration);
3748       gst_message_set_qos_values (qos_msg, priv->current_jitter, priv->avg_rate,
3749           1000000);
3750       gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS, priv->rendered,
3751           priv->dropped);
3752       gst_element_post_message (GST_ELEMENT_CAST (basesink), qos_msg);
3753     }
3754     goto done;
3755   }
3756 preroll_failed:
3757   {
3758     GST_DEBUG_OBJECT (basesink, "preroll failed: %s", gst_flow_get_name (ret));
3759     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3760     return ret;
3761   }
3762 }
3763
3764 /* with STREAM_LOCK
3765  */
3766 static GstFlowReturn
3767 gst_base_sink_chain_main (GstBaseSink * basesink, GstPad * pad, gpointer obj,
3768     gboolean is_list)
3769 {
3770   GstFlowReturn result;
3771
3772   if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PUSH))
3773     goto wrong_mode;
3774
3775   GST_BASE_SINK_PREROLL_LOCK (basesink);
3776   result = gst_base_sink_chain_unlocked (basesink, pad, obj, is_list);
3777   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
3778
3779 done:
3780   return result;
3781
3782   /* ERRORS */
3783 wrong_mode:
3784   {
3785     GST_OBJECT_LOCK (pad);
3786     GST_WARNING_OBJECT (basesink,
3787         "Push on pad %s:%s, but it was not activated in push mode",
3788         GST_DEBUG_PAD_NAME (pad));
3789     GST_OBJECT_UNLOCK (pad);
3790     gst_mini_object_unref (GST_MINI_OBJECT_CAST (obj));
3791     /* we don't post an error message this will signal to the peer
3792      * pushing that EOS is reached. */
3793     result = GST_FLOW_EOS;
3794     goto done;
3795   }
3796 }
3797
3798 static GstFlowReturn
3799 gst_base_sink_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
3800 {
3801   GstBaseSink *basesink;
3802
3803   basesink = GST_BASE_SINK (parent);
3804
3805   return gst_base_sink_chain_main (basesink, pad, buf, FALSE);
3806 }
3807
3808 static GstFlowReturn
3809 gst_base_sink_chain_list (GstPad * pad, GstObject * parent,
3810     GstBufferList * list)
3811 {
3812   GstBaseSink *basesink;
3813   GstBaseSinkClass *bclass;
3814   GstFlowReturn result;
3815
3816   basesink = GST_BASE_SINK (parent);
3817   bclass = GST_BASE_SINK_GET_CLASS (basesink);
3818
3819   if (G_LIKELY (bclass->render_list)) {
3820     result = gst_base_sink_chain_main (basesink, pad, list, TRUE);
3821   } else {
3822     guint i, len;
3823     GstBuffer *buffer;
3824
3825     GST_LOG_OBJECT (pad, "chaining each buffer in list");
3826
3827     len = gst_buffer_list_length (list);
3828
3829     result = GST_FLOW_OK;
3830     for (i = 0; i < len; i++) {
3831       buffer = gst_buffer_list_get (list, i);
3832       result = gst_base_sink_chain_main (basesink, pad,
3833           gst_buffer_ref (buffer), FALSE);
3834       if (result != GST_FLOW_OK)
3835         break;
3836     }
3837     gst_buffer_list_unref (list);
3838   }
3839   return result;
3840 }
3841
3842
3843 static gboolean
3844 gst_base_sink_default_do_seek (GstBaseSink * sink, GstSegment * segment)
3845 {
3846   gboolean res = TRUE;
3847
3848   /* update our offset if the start/stop position was updated */
3849   if (segment->format == GST_FORMAT_BYTES) {
3850     segment->time = segment->start;
3851   } else if (segment->start == 0) {
3852     /* seek to start, we can implement a default for this. */
3853     segment->time = 0;
3854   } else {
3855     res = FALSE;
3856     GST_INFO_OBJECT (sink, "Can't do a default seek");
3857   }
3858
3859   return res;
3860 }
3861
3862 #define SEEK_TYPE_IS_RELATIVE(t) (((t) != GST_SEEK_TYPE_NONE) && ((t) != GST_SEEK_TYPE_SET))
3863
3864 static gboolean
3865 gst_base_sink_default_prepare_seek_segment (GstBaseSink * sink,
3866     GstEvent * event, GstSegment * segment)
3867 {
3868   /* By default, we try one of 2 things:
3869    *   - For absolute seek positions, convert the requested position to our
3870    *     configured processing format and place it in the output segment \
3871    *   - For relative seek positions, convert our current (input) values to the
3872    *     seek format, adjust by the relative seek offset and then convert back to
3873    *     the processing format
3874    */
3875   GstSeekType start_type, stop_type;
3876   gint64 start, stop;
3877   GstSeekFlags flags;
3878   GstFormat seek_format;
3879   gdouble rate;
3880   gboolean update;
3881   gboolean res = TRUE;
3882
3883   gst_event_parse_seek (event, &rate, &seek_format, &flags,
3884       &start_type, &start, &stop_type, &stop);
3885
3886   if (seek_format == segment->format) {
3887     gst_segment_do_seek (segment, rate, seek_format, flags,
3888         start_type, start, stop_type, stop, &update);
3889     return TRUE;
3890   }
3891
3892   if (start_type != GST_SEEK_TYPE_NONE) {
3893     /* FIXME: Handle seek_end by converting the input segment vals */
3894     res =
3895         gst_pad_query_convert (sink->sinkpad, seek_format, start,
3896         segment->format, &start);
3897     start_type = GST_SEEK_TYPE_SET;
3898   }
3899
3900   if (res && stop_type != GST_SEEK_TYPE_NONE) {
3901     /* FIXME: Handle seek_end by converting the input segment vals */
3902     res =
3903         gst_pad_query_convert (sink->sinkpad, seek_format, stop,
3904         segment->format, &stop);
3905     stop_type = GST_SEEK_TYPE_SET;
3906   }
3907
3908   /* And finally, configure our output segment in the desired format */
3909   gst_segment_do_seek (segment, rate, segment->format, flags, start_type, start,
3910       stop_type, stop, &update);
3911
3912   if (!res)
3913     goto no_format;
3914
3915   return res;
3916
3917 no_format:
3918   {
3919     GST_DEBUG_OBJECT (sink, "undefined format given, seek aborted.");
3920     return FALSE;
3921   }
3922 }
3923
3924 /* perform a seek, only executed in pull mode */
3925 static gboolean
3926 gst_base_sink_perform_seek (GstBaseSink * sink, GstPad * pad, GstEvent * event)
3927 {
3928   gboolean flush;
3929   gdouble rate;
3930   GstFormat seek_format, dest_format;
3931   GstSeekFlags flags;
3932   GstSeekType start_type, stop_type;
3933   gboolean seekseg_configured = FALSE;
3934   gint64 start, stop;
3935   gboolean update, res = TRUE;
3936   GstSegment seeksegment;
3937
3938   dest_format = sink->segment.format;
3939
3940   if (event) {
3941     GST_DEBUG_OBJECT (sink, "performing seek with event %p", event);
3942     gst_event_parse_seek (event, &rate, &seek_format, &flags,
3943         &start_type, &start, &stop_type, &stop);
3944
3945     flush = flags & GST_SEEK_FLAG_FLUSH;
3946   } else {
3947     GST_DEBUG_OBJECT (sink, "performing seek without event");
3948     flush = FALSE;
3949   }
3950
3951   if (flush) {
3952     GST_DEBUG_OBJECT (sink, "flushing upstream");
3953     gst_pad_push_event (pad, gst_event_new_flush_start ());
3954     gst_base_sink_flush_start (sink, pad);
3955   } else {
3956     GST_DEBUG_OBJECT (sink, "pausing pulling thread");
3957   }
3958
3959   GST_PAD_STREAM_LOCK (pad);
3960
3961   /* If we configured the seeksegment above, don't overwrite it now. Otherwise
3962    * copy the current segment info into the temp segment that we can actually
3963    * attempt the seek with. We only update the real segment if the seek succeeds. */
3964   if (!seekseg_configured) {
3965     memcpy (&seeksegment, &sink->segment, sizeof (GstSegment));
3966
3967     /* now configure the final seek segment */
3968     if (event) {
3969       if (sink->segment.format != seek_format) {
3970         /* OK, here's where we give the subclass a chance to convert the relative
3971          * seek into an absolute one in the processing format. We set up any
3972          * absolute seek above, before taking the stream lock. */
3973         if (!gst_base_sink_default_prepare_seek_segment (sink, event,
3974                 &seeksegment)) {
3975           GST_DEBUG_OBJECT (sink,
3976               "Preparing the seek failed after flushing. " "Aborting seek");
3977           res = FALSE;
3978         }
3979       } else {
3980         /* The seek format matches our processing format, no need to ask the
3981          * the subclass to configure the segment. */
3982         gst_segment_do_seek (&seeksegment, rate, seek_format, flags,
3983             start_type, start, stop_type, stop, &update);
3984       }
3985     }
3986     /* Else, no seek event passed, so we're just (re)starting the
3987        current segment. */
3988   }
3989
3990   if (res) {
3991     GST_DEBUG_OBJECT (sink, "segment configured from %" G_GINT64_FORMAT
3992         " to %" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT,
3993         seeksegment.start, seeksegment.stop, seeksegment.position);
3994
3995     /* do the seek, segment.position contains the new position. */
3996     res = gst_base_sink_default_do_seek (sink, &seeksegment);
3997   }
3998
3999   if (flush) {
4000     GST_DEBUG_OBJECT (sink, "stop flushing upstream");
4001     gst_pad_push_event (pad, gst_event_new_flush_stop (TRUE));
4002     gst_base_sink_flush_stop (sink, pad, TRUE);
4003   } else if (res && sink->running) {
4004     /* we are running the current segment and doing a non-flushing seek,
4005      * close the segment first based on the position. */
4006     GST_DEBUG_OBJECT (sink, "closing running segment %" G_GINT64_FORMAT
4007         " to %" G_GINT64_FORMAT, sink->segment.start, sink->segment.position);
4008   }
4009
4010   /* The subclass must have converted the segment to the processing format
4011    * by now */
4012   if (res && seeksegment.format != dest_format) {
4013     GST_DEBUG_OBJECT (sink, "Subclass failed to prepare a seek segment "
4014         "in the correct format. Aborting seek.");
4015     res = FALSE;
4016   }
4017
4018   GST_INFO_OBJECT (sink, "seeking done %d: %" GST_SEGMENT_FORMAT, res,
4019       &seeksegment);
4020
4021   /* if successful seek, we update our real segment and push
4022    * out the new segment. */
4023   if (res) {
4024     gst_segment_copy_into (&seeksegment, &sink->segment);
4025
4026     if (sink->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
4027       gst_element_post_message (GST_ELEMENT (sink),
4028           gst_message_new_segment_start (GST_OBJECT (sink),
4029               sink->segment.format, sink->segment.position));
4030     }
4031   }
4032
4033   sink->priv->discont = TRUE;
4034   sink->running = TRUE;
4035
4036   GST_PAD_STREAM_UNLOCK (pad);
4037
4038   return res;
4039 }
4040
4041 static void
4042 set_step_info (GstBaseSink * sink, GstStepInfo * current, GstStepInfo * pending,
4043     guint seqnum, GstFormat format, guint64 amount, gdouble rate,
4044     gboolean flush, gboolean intermediate)
4045 {
4046   GST_OBJECT_LOCK (sink);
4047   pending->seqnum = seqnum;
4048   pending->format = format;
4049   pending->amount = amount;
4050   pending->position = 0;
4051   pending->rate = rate;
4052   pending->flush = flush;
4053   pending->intermediate = intermediate;
4054   pending->valid = TRUE;
4055   /* flush invalidates the current stepping segment */
4056   if (flush)
4057     current->valid = FALSE;
4058   GST_OBJECT_UNLOCK (sink);
4059 }
4060
4061 static gboolean
4062 gst_base_sink_perform_step (GstBaseSink * sink, GstPad * pad, GstEvent * event)
4063 {
4064   GstBaseSinkPrivate *priv;
4065   GstBaseSinkClass *bclass;
4066   gboolean flush, intermediate;
4067   gdouble rate;
4068   GstFormat format;
4069   guint64 amount;
4070   guint seqnum;
4071   GstStepInfo *pending, *current;
4072   GstMessage *message;
4073
4074   bclass = GST_BASE_SINK_GET_CLASS (sink);
4075   priv = sink->priv;
4076
4077   GST_DEBUG_OBJECT (sink, "performing step with event %p", event);
4078
4079   gst_event_parse_step (event, &format, &amount, &rate, &flush, &intermediate);
4080   seqnum = gst_event_get_seqnum (event);
4081
4082   pending = &priv->pending_step;
4083   current = &priv->current_step;
4084
4085   /* post message first */
4086   message = gst_message_new_step_start (GST_OBJECT (sink), FALSE, format,
4087       amount, rate, flush, intermediate);
4088   gst_message_set_seqnum (message, seqnum);
4089   gst_element_post_message (GST_ELEMENT (sink), message);
4090
4091   if (flush) {
4092     /* we need to call ::unlock before locking PREROLL_LOCK
4093      * since we lock it before going into ::render */
4094     if (bclass->unlock)
4095       bclass->unlock (sink);
4096
4097     GST_BASE_SINK_PREROLL_LOCK (sink);
4098     /* now that we have the PREROLL lock, clear our unlock request */
4099     if (bclass->unlock_stop)
4100       bclass->unlock_stop (sink);
4101
4102     /* update the stepinfo and make it valid */
4103     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
4104         intermediate);
4105
4106     if (sink->priv->async_enabled) {
4107       /* and we need to commit our state again on the next
4108        * prerolled buffer */
4109       sink->playing_async = TRUE;
4110       priv->pending_step.need_preroll = TRUE;
4111       sink->need_preroll = FALSE;
4112       gst_base_sink_update_start_time (sink);
4113       gst_element_lost_state (GST_ELEMENT_CAST (sink));
4114     } else {
4115       sink->priv->have_latency = TRUE;
4116       sink->need_preroll = FALSE;
4117     }
4118     priv->current_sstart = GST_CLOCK_TIME_NONE;
4119     priv->current_sstop = GST_CLOCK_TIME_NONE;
4120     priv->eos_rtime = GST_CLOCK_TIME_NONE;
4121     priv->call_preroll = TRUE;
4122     gst_base_sink_set_last_buffer (sink, NULL);
4123     gst_base_sink_set_last_buffer_list (sink, NULL);
4124     gst_base_sink_reset_qos (sink);
4125
4126     if (sink->clock_id) {
4127       gst_clock_id_unschedule (sink->clock_id);
4128     }
4129
4130     if (sink->have_preroll) {
4131       GST_DEBUG_OBJECT (sink, "signal waiter");
4132       priv->step_unlock = TRUE;
4133       GST_BASE_SINK_PREROLL_SIGNAL (sink);
4134     }
4135     GST_BASE_SINK_PREROLL_UNLOCK (sink);
4136   } else {
4137     /* update the stepinfo and make it valid */
4138     set_step_info (sink, current, pending, seqnum, format, amount, rate, flush,
4139         intermediate);
4140   }
4141
4142   return TRUE;
4143 }
4144
4145 /* with STREAM_LOCK
4146  */
4147 static void
4148 gst_base_sink_loop (GstPad * pad)
4149 {
4150   GstObject *parent;
4151   GstBaseSink *basesink;
4152   GstBuffer *buf = NULL;
4153   GstFlowReturn result;
4154   guint blocksize;
4155   guint64 offset;
4156
4157   parent = GST_OBJECT_PARENT (pad);
4158   basesink = GST_BASE_SINK (parent);
4159
4160   g_assert (basesink->pad_mode == GST_PAD_MODE_PULL);
4161
4162   if ((blocksize = basesink->priv->blocksize) == 0)
4163     blocksize = -1;
4164
4165   offset = basesink->segment.position;
4166
4167   GST_DEBUG_OBJECT (basesink, "pulling %" G_GUINT64_FORMAT ", %u",
4168       offset, blocksize);
4169
4170   result = gst_pad_pull_range (pad, offset, blocksize, &buf);
4171   if (G_UNLIKELY (result != GST_FLOW_OK))
4172     goto paused;
4173
4174   if (G_UNLIKELY (buf == NULL))
4175     goto no_buffer;
4176
4177   offset += gst_buffer_get_size (buf);
4178
4179   basesink->segment.position = offset;
4180
4181   GST_BASE_SINK_PREROLL_LOCK (basesink);
4182   result = gst_base_sink_chain_unlocked (basesink, pad, buf, FALSE);
4183   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4184   if (G_UNLIKELY (result != GST_FLOW_OK))
4185     goto paused;
4186
4187   return;
4188
4189   /* ERRORS */
4190 paused:
4191   {
4192     GST_LOG_OBJECT (basesink, "pausing task, reason %s",
4193         gst_flow_get_name (result));
4194     gst_pad_pause_task (pad);
4195     if (result == GST_FLOW_EOS) {
4196       /* perform EOS logic */
4197       if (basesink->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
4198         gst_element_post_message (GST_ELEMENT_CAST (basesink),
4199             gst_message_new_segment_done (GST_OBJECT_CAST (basesink),
4200                 basesink->segment.format, basesink->segment.position));
4201         gst_base_sink_event (pad, parent,
4202             gst_event_new_segment_done (basesink->segment.format,
4203                 basesink->segment.position));
4204       } else {
4205         gst_base_sink_event (pad, parent, gst_event_new_eos ());
4206       }
4207     } else if (result == GST_FLOW_NOT_LINKED || result <= GST_FLOW_EOS) {
4208       /* for fatal errors we post an error message, post the error
4209        * first so the app knows about the error first.
4210        * wrong-state is not a fatal error because it happens due to
4211        * flushing and posting an error message in that case is the
4212        * wrong thing to do, e.g. when basesrc is doing a flushing
4213        * seek. */
4214       GST_ELEMENT_FLOW_ERROR (basesink, result);
4215       gst_base_sink_event (pad, parent, gst_event_new_eos ());
4216     }
4217     return;
4218   }
4219 no_buffer:
4220   {
4221     GST_LOG_OBJECT (basesink, "no buffer, pausing");
4222     GST_ELEMENT_ERROR (basesink, STREAM, FAILED,
4223         (_("Internal data flow error.")), ("element returned NULL buffer"));
4224     result = GST_FLOW_ERROR;
4225     goto paused;
4226   }
4227 }
4228
4229 static gboolean
4230 gst_base_sink_set_flushing (GstBaseSink * basesink, GstPad * pad,
4231     gboolean flushing)
4232 {
4233   GstBaseSinkClass *bclass;
4234
4235   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4236
4237   if (flushing) {
4238     /* unlock any subclasses, we need to do this before grabbing the
4239      * PREROLL_LOCK since we hold this lock before going into ::render. */
4240     if (bclass->unlock)
4241       bclass->unlock (basesink);
4242   }
4243
4244   GST_BASE_SINK_PREROLL_LOCK (basesink);
4245   basesink->flushing = flushing;
4246   if (flushing) {
4247     /* step 1, now that we have the PREROLL lock, clear our unlock request */
4248     if (bclass->unlock_stop)
4249       bclass->unlock_stop (basesink);
4250
4251     /* set need_preroll before we unblock the clock. If the clock is unblocked
4252      * before timing out, we can reuse the buffer for preroll. */
4253     basesink->need_preroll = TRUE;
4254
4255     /* step 2, unblock clock sync (if any) or any other blocking thing */
4256     if (basesink->clock_id) {
4257       gst_clock_id_unschedule (basesink->clock_id);
4258     }
4259
4260     /* flush out the data thread if it's locked in finish_preroll, this will
4261      * also flush out the EOS state */
4262     GST_DEBUG_OBJECT (basesink,
4263         "flushing out data thread, need preroll to TRUE");
4264
4265     /* we can't have EOS anymore now */
4266     basesink->eos = FALSE;
4267     basesink->priv->received_eos = FALSE;
4268     basesink->have_preroll = FALSE;
4269     basesink->priv->step_unlock = FALSE;
4270     /* can't report latency anymore until we preroll again */
4271     if (basesink->priv->async_enabled) {
4272       GST_OBJECT_LOCK (basesink);
4273       basesink->priv->have_latency = FALSE;
4274       GST_OBJECT_UNLOCK (basesink);
4275     }
4276     /* and signal any waiters now */
4277     GST_BASE_SINK_PREROLL_SIGNAL (basesink);
4278   }
4279   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
4280
4281   return TRUE;
4282 }
4283
4284 static gboolean
4285 gst_base_sink_default_activate_pull (GstBaseSink * basesink, gboolean active)
4286 {
4287   gboolean result;
4288
4289   if (active) {
4290     /* start task */
4291     result = gst_pad_start_task (basesink->sinkpad,
4292         (GstTaskFunction) gst_base_sink_loop, basesink->sinkpad, NULL);
4293   } else {
4294     /* step 2, make sure streaming finishes */
4295     result = gst_pad_stop_task (basesink->sinkpad);
4296   }
4297
4298   return result;
4299 }
4300
4301 static gboolean
4302 gst_base_sink_pad_activate (GstPad * pad, GstObject * parent)
4303 {
4304   gboolean result = FALSE;
4305   GstBaseSink *basesink;
4306   GstQuery *query;
4307   gboolean pull_mode;
4308
4309   basesink = GST_BASE_SINK (parent);
4310
4311   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
4312
4313   gst_base_sink_set_flushing (basesink, pad, FALSE);
4314
4315   /* we need to have the pull mode enabled */
4316   if (!basesink->can_activate_pull) {
4317     GST_DEBUG_OBJECT (basesink, "pull mode disabled");
4318     goto fallback;
4319   }
4320
4321   /* check if downstreams supports pull mode at all */
4322   query = gst_query_new_scheduling ();
4323
4324   if (!gst_pad_peer_query (pad, query)) {
4325     gst_query_unref (query);
4326     GST_DEBUG_OBJECT (basesink, "peer query failed, no pull mode");
4327     goto fallback;
4328   }
4329
4330   /* parse result of the query */
4331   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL);
4332   gst_query_unref (query);
4333
4334   if (!pull_mode) {
4335     GST_DEBUG_OBJECT (basesink, "pull mode not supported");
4336     goto fallback;
4337   }
4338
4339   /* set the pad mode before starting the task so that it's in the
4340    * correct state for the new thread. also the sink set_caps and get_caps
4341    * function checks this */
4342   basesink->pad_mode = GST_PAD_MODE_PULL;
4343
4344   /* we first try to negotiate a format so that when we try to activate
4345    * downstream, it knows about our format */
4346   if (!gst_base_sink_negotiate_pull (basesink)) {
4347     GST_DEBUG_OBJECT (basesink, "failed to negotiate in pull mode");
4348     goto fallback;
4349   }
4350
4351   /* ok activate now */
4352   if (!gst_pad_activate_mode (pad, GST_PAD_MODE_PULL, TRUE)) {
4353     /* clear any pending caps */
4354     GST_OBJECT_LOCK (basesink);
4355     gst_caps_replace (&basesink->priv->caps, NULL);
4356     GST_OBJECT_UNLOCK (basesink);
4357     GST_DEBUG_OBJECT (basesink, "failed to activate in pull mode");
4358     goto fallback;
4359   }
4360
4361   GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
4362   result = TRUE;
4363   goto done;
4364
4365   /* push mode fallback */
4366 fallback:
4367   GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
4368   if ((result = gst_pad_activate_mode (pad, GST_PAD_MODE_PUSH, TRUE))) {
4369     GST_DEBUG_OBJECT (basesink, "Success activating push mode");
4370   }
4371
4372 done:
4373   if (!result) {
4374     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
4375     gst_base_sink_set_flushing (basesink, pad, TRUE);
4376   }
4377
4378   return result;
4379 }
4380
4381 static gboolean
4382 gst_base_sink_pad_activate_push (GstPad * pad, GstObject * parent,
4383     gboolean active)
4384 {
4385   gboolean result;
4386   GstBaseSink *basesink;
4387
4388   basesink = GST_BASE_SINK (parent);
4389
4390   if (active) {
4391     if (!basesink->can_activate_push) {
4392       result = FALSE;
4393       basesink->pad_mode = GST_PAD_MODE_NONE;
4394     } else {
4395       result = TRUE;
4396       basesink->pad_mode = GST_PAD_MODE_PUSH;
4397     }
4398   } else {
4399     if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PUSH)) {
4400       g_warning ("Internal GStreamer activation error!!!");
4401       result = FALSE;
4402     } else {
4403       gst_base_sink_set_flushing (basesink, pad, TRUE);
4404       result = TRUE;
4405       basesink->pad_mode = GST_PAD_MODE_NONE;
4406     }
4407   }
4408
4409   return result;
4410 }
4411
4412 static gboolean
4413 gst_base_sink_negotiate_pull (GstBaseSink * basesink)
4414 {
4415   GstCaps *caps;
4416   gboolean result;
4417
4418   result = FALSE;
4419
4420   /* this returns the intersection between our caps and the peer caps. If there
4421    * is no peer, it returns %NULL and we can't operate in pull mode so we can
4422    * fail the negotiation. */
4423   caps = gst_pad_get_allowed_caps (GST_BASE_SINK_PAD (basesink));
4424   if (caps == NULL || gst_caps_is_empty (caps))
4425     goto no_caps_possible;
4426
4427   GST_DEBUG_OBJECT (basesink, "allowed caps: %" GST_PTR_FORMAT, caps);
4428
4429   if (gst_caps_is_any (caps)) {
4430     GST_DEBUG_OBJECT (basesink, "caps were ANY after fixating, "
4431         "allowing pull()");
4432     /* neither side has template caps in this case, so they are prepared for
4433        pull() without setcaps() */
4434     result = TRUE;
4435   } else {
4436     /* try to fixate */
4437     caps = gst_base_sink_fixate (basesink, caps);
4438     GST_DEBUG_OBJECT (basesink, "fixated to: %" GST_PTR_FORMAT, caps);
4439
4440     if (gst_caps_is_fixed (caps)) {
4441       if (!gst_pad_set_caps (GST_BASE_SINK_PAD (basesink), caps))
4442         goto could_not_set_caps;
4443
4444       result = TRUE;
4445     }
4446   }
4447
4448   gst_caps_unref (caps);
4449
4450   return result;
4451
4452 no_caps_possible:
4453   {
4454     GST_INFO_OBJECT (basesink, "Pipeline could not agree on caps");
4455     GST_DEBUG_OBJECT (basesink, "get_allowed_caps() returned EMPTY");
4456     if (caps)
4457       gst_caps_unref (caps);
4458     return FALSE;
4459   }
4460 could_not_set_caps:
4461   {
4462     GST_INFO_OBJECT (basesink, "Could not set caps: %" GST_PTR_FORMAT, caps);
4463     gst_caps_unref (caps);
4464     return FALSE;
4465   }
4466 }
4467
4468 /* this won't get called until we implement an activate function */
4469 static gboolean
4470 gst_base_sink_pad_activate_pull (GstPad * pad, GstObject * parent,
4471     gboolean active)
4472 {
4473   gboolean result = FALSE;
4474   GstBaseSink *basesink;
4475   GstBaseSinkClass *bclass;
4476
4477   basesink = GST_BASE_SINK (parent);
4478   bclass = GST_BASE_SINK_GET_CLASS (basesink);
4479
4480   if (active) {
4481     gint64 duration;
4482
4483     /* we mark we have a newsegment here because pull based
4484      * mode works just fine without having a newsegment before the
4485      * first buffer */
4486     gst_segment_init (&basesink->segment, GST_FORMAT_BYTES);
4487     GST_OBJECT_LOCK (basesink);
4488     basesink->have_newsegment = TRUE;
4489     GST_OBJECT_UNLOCK (basesink);
4490
4491     /* get the peer duration in bytes */
4492     result = gst_pad_peer_query_duration (pad, GST_FORMAT_BYTES, &duration);
4493     if (result) {
4494       GST_DEBUG_OBJECT (basesink,
4495           "setting duration in bytes to %" G_GINT64_FORMAT, duration);
4496       basesink->segment.duration = duration;
4497     } else {
4498       GST_DEBUG_OBJECT (basesink, "unknown duration");
4499     }
4500
4501     if (bclass->activate_pull)
4502       result = bclass->activate_pull (basesink, TRUE);
4503     else
4504       result = FALSE;
4505
4506     if (!result)
4507       goto activate_failed;
4508
4509   } else {
4510     if (G_UNLIKELY (basesink->pad_mode != GST_PAD_MODE_PULL)) {
4511       g_warning ("Internal GStreamer activation error!!!");
4512       result = FALSE;
4513     } else {
4514       result = gst_base_sink_set_flushing (basesink, pad, TRUE);
4515       if (bclass->activate_pull)
4516         result &= bclass->activate_pull (basesink, FALSE);
4517       basesink->pad_mode = GST_PAD_MODE_NONE;
4518     }
4519   }
4520
4521   return result;
4522
4523   /* ERRORS */
4524 activate_failed:
4525   {
4526     /* reset, as starting the thread failed */
4527     basesink->pad_mode = GST_PAD_MODE_NONE;
4528
4529     GST_ERROR_OBJECT (basesink, "subclass failed to activate in pull mode");
4530     return FALSE;
4531   }
4532 }
4533
4534 static gboolean
4535 gst_base_sink_pad_activate_mode (GstPad * pad, GstObject * parent,
4536     GstPadMode mode, gboolean active)
4537 {
4538   gboolean res;
4539
4540   switch (mode) {
4541     case GST_PAD_MODE_PULL:
4542       res = gst_base_sink_pad_activate_pull (pad, parent, active);
4543       break;
4544     case GST_PAD_MODE_PUSH:
4545       res = gst_base_sink_pad_activate_push (pad, parent, active);
4546       break;
4547     default:
4548       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
4549       res = FALSE;
4550       break;
4551   }
4552   return res;
4553 }
4554
4555 /* send an event to our sinkpad peer. */
4556 static gboolean
4557 gst_base_sink_send_event (GstElement * element, GstEvent * event)
4558 {
4559   GstPad *pad;
4560   GstBaseSink *basesink = GST_BASE_SINK (element);
4561   gboolean forward, result = TRUE;
4562   GstPadMode mode;
4563
4564   GST_OBJECT_LOCK (element);
4565   /* get the pad and the scheduling mode */
4566   pad = gst_object_ref (basesink->sinkpad);
4567   mode = basesink->pad_mode;
4568   GST_OBJECT_UNLOCK (element);
4569
4570   /* only push UPSTREAM events upstream */
4571   forward = GST_EVENT_IS_UPSTREAM (event);
4572
4573   GST_DEBUG_OBJECT (basesink, "handling event %p %" GST_PTR_FORMAT, event,
4574       event);
4575
4576   switch (GST_EVENT_TYPE (event)) {
4577     case GST_EVENT_LATENCY:
4578     {
4579       GstClockTime latency;
4580
4581       gst_event_parse_latency (event, &latency);
4582
4583       /* store the latency. We use this to adjust the running_time before syncing
4584        * it to the clock. */
4585       GST_OBJECT_LOCK (element);
4586       basesink->priv->latency = latency;
4587       if (!basesink->priv->have_latency)
4588         forward = FALSE;
4589       GST_OBJECT_UNLOCK (element);
4590       GST_DEBUG_OBJECT (basesink, "latency set to %" GST_TIME_FORMAT,
4591           GST_TIME_ARGS (latency));
4592
4593       /* We forward this event so that all elements know about the global pipeline
4594        * latency. This is interesting for an element when it wants to figure out
4595        * when a particular piece of data will be rendered. */
4596       break;
4597     }
4598     case GST_EVENT_SEEK:
4599       /* in pull mode we will execute the seek */
4600       if (mode == GST_PAD_MODE_PULL)
4601         result = gst_base_sink_perform_seek (basesink, pad, event);
4602       break;
4603     case GST_EVENT_STEP:
4604       result = gst_base_sink_perform_step (basesink, pad, event);
4605       forward = FALSE;
4606       break;
4607     default:
4608       break;
4609   }
4610
4611   if (forward) {
4612     GST_DEBUG_OBJECT (basesink, "sending event %p %" GST_PTR_FORMAT, event,
4613         event);
4614     result = gst_pad_push_event (pad, event);
4615   } else {
4616     /* not forwarded, unref the event */
4617     gst_event_unref (event);
4618   }
4619
4620   gst_object_unref (pad);
4621
4622   GST_DEBUG_OBJECT (basesink, "handled event: %d", result);
4623
4624   return result;
4625 }
4626
4627 static gboolean
4628 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
4629     gint64 * cur, gboolean * upstream)
4630 {
4631   GstClock *clock = NULL;
4632   gboolean res = FALSE;
4633   GstFormat oformat;
4634   GstSegment *segment;
4635   GstClockTime now, latency;
4636   GstClockTimeDiff base_time;
4637   gint64 time, base, offset, duration;
4638   gdouble rate;
4639   gint64 last;
4640   gboolean last_seen, with_clock, in_paused;
4641
4642   GST_OBJECT_LOCK (basesink);
4643   /* we can only get the segment when we are not NULL or READY */
4644   if (!basesink->have_newsegment)
4645     goto wrong_state;
4646
4647   in_paused = FALSE;
4648   /* when not in PLAYING or when we're busy with a state change, we
4649    * cannot read from the clock so we report time based on the
4650    * last seen timestamp. */
4651   if (GST_STATE (basesink) != GST_STATE_PLAYING ||
4652       GST_STATE_PENDING (basesink) != GST_STATE_VOID_PENDING) {
4653     in_paused = TRUE;
4654   }
4655
4656   segment = &basesink->segment;
4657
4658   /* get the format in the segment */
4659   oformat = segment->format;
4660
4661   /* report with last seen position when EOS */
4662   last_seen = basesink->eos;
4663
4664   /* assume we will use the clock for getting the current position */
4665   with_clock = TRUE;
4666   if (!basesink->sync)
4667     with_clock = FALSE;
4668
4669   /* and we need a clock */
4670   if (G_UNLIKELY ((clock = GST_ELEMENT_CLOCK (basesink)) == NULL))
4671     with_clock = FALSE;
4672   else
4673     gst_object_ref (clock);
4674
4675   /* mainloop might be querying position when going to playing async,
4676    * while (audio) rendering might be quickly advancing stream position,
4677    * so use clock asap rather than last reported position */
4678   if (in_paused && with_clock && g_atomic_int_get (&basesink->priv->to_playing)) {
4679     GST_DEBUG_OBJECT (basesink, "going to PLAYING, so not PAUSED");
4680     in_paused = FALSE;
4681   }
4682
4683   /* collect all data we need holding the lock */
4684   if (GST_CLOCK_TIME_IS_VALID (segment->time))
4685     time = segment->time;
4686   else
4687     time = 0;
4688
4689   if (GST_CLOCK_TIME_IS_VALID (segment->offset))
4690     offset = segment->offset;
4691   else
4692     offset = 0;
4693
4694   if (GST_CLOCK_TIME_IS_VALID (segment->stop))
4695     duration = segment->stop - segment->start;
4696   else
4697     duration = 0;
4698
4699   base = segment->base;
4700   rate = segment->rate * segment->applied_rate;
4701   latency = basesink->priv->latency;
4702
4703   if (in_paused) {
4704     /* in paused, use start_time */
4705     base_time = GST_ELEMENT_START_TIME (basesink);
4706     GST_DEBUG_OBJECT (basesink, "in paused, using start time %" GST_TIME_FORMAT,
4707         GST_TIME_ARGS (base_time));
4708   } else if (with_clock) {
4709     /* else use clock when needed */
4710     base_time = GST_ELEMENT_CAST (basesink)->base_time;
4711     GST_DEBUG_OBJECT (basesink, "using clock and base time %" GST_TIME_FORMAT,
4712         GST_TIME_ARGS (base_time));
4713   } else {
4714     /* else, no sync or clock -> no base time */
4715     GST_DEBUG_OBJECT (basesink, "no sync or no clock");
4716     base_time = -1;
4717   }
4718
4719   /* no base_time, we can't calculate running_time, use last seem timestamp to report
4720    * time */
4721   if (base_time == -1)
4722     last_seen = TRUE;
4723
4724   if (oformat == GST_FORMAT_TIME) {
4725     gint64 start, stop;
4726
4727     start = basesink->priv->current_sstart;
4728     stop = basesink->priv->current_sstop;
4729
4730     if (last_seen) {
4731       /* when we don't use the clock, we use the last position as a lower bound */
4732       if (stop == -1 || segment->rate > 0.0)
4733         last = start;
4734       else
4735         last = stop;
4736
4737       GST_DEBUG_OBJECT (basesink, "in PAUSED using last %" GST_TIME_FORMAT,
4738           GST_TIME_ARGS (last));
4739     } else {
4740       /* in playing and paused, use last stop time as upper bound */
4741       if (start == -1 || segment->rate > 0.0)
4742         last = stop;
4743       else
4744         last = start;
4745
4746       GST_DEBUG_OBJECT (basesink, "in PLAYING using last %" GST_TIME_FORMAT,
4747           GST_TIME_ARGS (last));
4748     }
4749   } else {
4750     /* convert position to stream time */
4751     last = gst_segment_to_stream_time (segment, oformat, segment->position);
4752
4753     GST_DEBUG_OBJECT (basesink, "in using last %" G_GINT64_FORMAT, last);
4754   }
4755
4756   /* need to release the object lock before we can get the time,
4757    * a clock might take the LOCK of the provider, which could be
4758    * a basesink subclass. */
4759   GST_OBJECT_UNLOCK (basesink);
4760
4761   if (last_seen) {
4762     /* in EOS or when no valid stream_time, report the value of last seen
4763      * timestamp */
4764     if (last == -1) {
4765       /* no timestamp, we need to ask upstream */
4766       GST_DEBUG_OBJECT (basesink, "no last seen timestamp, asking upstream");
4767       res = FALSE;
4768       *upstream = TRUE;
4769       goto done;
4770     }
4771     GST_DEBUG_OBJECT (basesink, "using last seen timestamp %" GST_TIME_FORMAT,
4772         GST_TIME_ARGS (last));
4773     *cur = last;
4774   } else {
4775     if (oformat != GST_FORMAT_TIME) {
4776       /* convert base, time and duration to time */
4777       if (!gst_pad_query_convert (basesink->sinkpad, oformat, base,
4778               GST_FORMAT_TIME, &base))
4779         goto convert_failed;
4780       if (!gst_pad_query_convert (basesink->sinkpad, oformat, duration,
4781               GST_FORMAT_TIME, &duration))
4782         goto convert_failed;
4783       if (!gst_pad_query_convert (basesink->sinkpad, oformat, time,
4784               GST_FORMAT_TIME, &time))
4785         goto convert_failed;
4786       if (!gst_pad_query_convert (basesink->sinkpad, oformat, last,
4787               GST_FORMAT_TIME, &last))
4788         goto convert_failed;
4789
4790       /* assume time format from now on */
4791       oformat = GST_FORMAT_TIME;
4792     }
4793
4794     if (!in_paused && with_clock) {
4795       now = gst_clock_get_time (clock);
4796     } else {
4797       now = base_time;
4798       base_time = 0;
4799     }
4800
4801     /* subtract base time and base time from the clock time.
4802      * Make sure we don't go negative. This is the current time in
4803      * the segment which we need to scale with the combined
4804      * rate and applied rate. */
4805     base_time += base;
4806     base_time += latency;
4807     if (GST_CLOCK_DIFF (base_time, now) < 0)
4808       base_time = now;
4809
4810     /* for negative rates we need to count back from the segment
4811      * duration. */
4812     if (rate < 0.0)
4813       time += duration;
4814
4815     *cur = time + offset + gst_guint64_to_gdouble (now - base_time) * rate;
4816
4817     /* never report more than last seen position */
4818     if (last != -1) {
4819       if (rate > 0.0)
4820         *cur = MIN (last, *cur);
4821       else
4822         *cur = MAX (last, *cur);
4823     }
4824
4825     GST_DEBUG_OBJECT (basesink,
4826         "now %" GST_TIME_FORMAT " - base_time %" GST_TIME_FORMAT " - base %"
4827         GST_TIME_FORMAT " + time %" GST_TIME_FORMAT "  last %" GST_TIME_FORMAT,
4828         GST_TIME_ARGS (now), GST_TIME_ARGS (base_time), GST_TIME_ARGS (base),
4829         GST_TIME_ARGS (time), GST_TIME_ARGS (last));
4830   }
4831
4832   if (oformat != format) {
4833     /* convert to final format */
4834     if (!gst_pad_query_convert (basesink->sinkpad, oformat, *cur, format, cur))
4835       goto convert_failed;
4836   }
4837
4838   res = TRUE;
4839
4840 done:
4841   GST_DEBUG_OBJECT (basesink, "res: %d, POSITION: %" GST_TIME_FORMAT,
4842       res, GST_TIME_ARGS (*cur));
4843
4844   if (clock)
4845     gst_object_unref (clock);
4846
4847   return res;
4848
4849   /* special cases */
4850 wrong_state:
4851   {
4852     /* in NULL or READY we always return FALSE and -1 */
4853     GST_DEBUG_OBJECT (basesink, "position in wrong state, return -1");
4854     res = FALSE;
4855     *cur = -1;
4856     GST_OBJECT_UNLOCK (basesink);
4857     goto done;
4858   }
4859 convert_failed:
4860   {
4861     GST_DEBUG_OBJECT (basesink, "convert failed, try upstream");
4862     *upstream = TRUE;
4863     res = FALSE;
4864     goto done;
4865   }
4866 }
4867
4868 static gboolean
4869 gst_base_sink_get_duration (GstBaseSink * basesink, GstFormat format,
4870     gint64 * dur, gboolean * upstream)
4871 {
4872   gboolean res = FALSE;
4873
4874   if (basesink->pad_mode == GST_PAD_MODE_PULL) {
4875     gint64 uduration;
4876
4877     /* get the duration in bytes, in pull mode that's all we are sure to
4878      * know. We have to explicitly get this value from upstream instead of
4879      * using our cached value because it might change. Duration caching
4880      * should be done at a higher level. */
4881     res =
4882         gst_pad_peer_query_duration (basesink->sinkpad, GST_FORMAT_BYTES,
4883         &uduration);
4884     if (res) {
4885       basesink->segment.duration = uduration;
4886       if (format != GST_FORMAT_BYTES) {
4887         /* convert to the requested format */
4888         res =
4889             gst_pad_query_convert (basesink->sinkpad, GST_FORMAT_BYTES,
4890             uduration, format, dur);
4891       } else {
4892         *dur = uduration;
4893       }
4894     }
4895     *upstream = FALSE;
4896   } else {
4897     *upstream = TRUE;
4898   }
4899
4900   return res;
4901 }
4902
4903 static gboolean
4904 default_element_query (GstElement * element, GstQuery * query)
4905 {
4906   gboolean res = FALSE;
4907
4908   GstBaseSink *basesink = GST_BASE_SINK (element);
4909
4910   switch (GST_QUERY_TYPE (query)) {
4911     case GST_QUERY_POSITION:
4912     {
4913       gint64 cur = 0;
4914       GstFormat format;
4915       gboolean upstream = FALSE;
4916
4917       gst_query_parse_position (query, &format, NULL);
4918
4919       GST_DEBUG_OBJECT (basesink, "position query in format %s",
4920           gst_format_get_name (format));
4921
4922       /* first try to get the position based on the clock */
4923       if ((res =
4924               gst_base_sink_get_position (basesink, format, &cur, &upstream))) {
4925         gst_query_set_position (query, format, cur);
4926       } else if (upstream) {
4927         /* fallback to peer query */
4928         res = gst_pad_peer_query (basesink->sinkpad, query);
4929       }
4930       if (!res) {
4931         /* we can handle a few things if upstream failed */
4932         if (format == GST_FORMAT_PERCENT) {
4933           gint64 dur = 0;
4934
4935           res = gst_base_sink_get_position (basesink, GST_FORMAT_TIME, &cur,
4936               &upstream);
4937           if (!res && upstream) {
4938             res =
4939                 gst_pad_peer_query_position (basesink->sinkpad, GST_FORMAT_TIME,
4940                 &cur);
4941           }
4942           if (res) {
4943             res = gst_base_sink_get_duration (basesink, GST_FORMAT_TIME, &dur,
4944                 &upstream);
4945             if (!res && upstream) {
4946               res =
4947                   gst_pad_peer_query_duration (basesink->sinkpad,
4948                   GST_FORMAT_TIME, &dur);
4949             }
4950           }
4951           if (res) {
4952             gint64 pos;
4953
4954             pos = gst_util_uint64_scale (100 * GST_FORMAT_PERCENT_SCALE, cur,
4955                 dur);
4956             gst_query_set_position (query, GST_FORMAT_PERCENT, pos);
4957           }
4958         }
4959       }
4960       break;
4961     }
4962     case GST_QUERY_DURATION:
4963     {
4964       gint64 dur = 0;
4965       GstFormat format;
4966       gboolean upstream = FALSE;
4967
4968       gst_query_parse_duration (query, &format, NULL);
4969
4970       GST_DEBUG_OBJECT (basesink, "duration query in format %s",
4971           gst_format_get_name (format));
4972
4973       if ((res =
4974               gst_base_sink_get_duration (basesink, format, &dur, &upstream))) {
4975         gst_query_set_duration (query, format, dur);
4976       } else if (upstream) {
4977         /* fallback to peer query */
4978         res = gst_pad_peer_query (basesink->sinkpad, query);
4979       }
4980       if (!res) {
4981         /* we can handle a few things if upstream failed */
4982         if (format == GST_FORMAT_PERCENT) {
4983           gst_query_set_duration (query, GST_FORMAT_PERCENT,
4984               GST_FORMAT_PERCENT_MAX);
4985           res = TRUE;
4986         }
4987       }
4988       break;
4989     }
4990     case GST_QUERY_LATENCY:
4991     {
4992       gboolean live, us_live;
4993       GstClockTime min, max;
4994
4995       if ((res = gst_base_sink_query_latency (basesink, &live, &us_live, &min,
4996                   &max))) {
4997         gst_query_set_latency (query, live, min, max);
4998       }
4999       break;
5000     }
5001     case GST_QUERY_JITTER:
5002       break;
5003     case GST_QUERY_RATE:
5004       /* gst_query_set_rate (query, basesink->segment_rate); */
5005       res = TRUE;
5006       break;
5007     case GST_QUERY_SEGMENT:
5008     {
5009       if (basesink->pad_mode == GST_PAD_MODE_PULL) {
5010         GstFormat format;
5011         gint64 start, stop;
5012
5013         format = basesink->segment.format;
5014
5015         start =
5016             gst_segment_to_stream_time (&basesink->segment, format,
5017             basesink->segment.start);
5018         if ((stop = basesink->segment.stop) == -1)
5019           stop = basesink->segment.duration;
5020         else
5021           stop = gst_segment_to_stream_time (&basesink->segment, format, stop);
5022
5023         gst_query_set_segment (query, basesink->segment.rate, format, start,
5024             stop);
5025         res = TRUE;
5026       } else {
5027         res = gst_pad_peer_query (basesink->sinkpad, query);
5028       }
5029       break;
5030     }
5031     case GST_QUERY_SEEKING:
5032     case GST_QUERY_CONVERT:
5033     case GST_QUERY_FORMATS:
5034     default:
5035       res = gst_pad_peer_query (basesink->sinkpad, query);
5036       break;
5037   }
5038   GST_DEBUG_OBJECT (basesink, "query %s returns %d",
5039       GST_QUERY_TYPE_NAME (query), res);
5040   return res;
5041 }
5042
5043 static void
5044 gst_base_sink_drain (GstBaseSink * basesink)
5045 {
5046   GstBuffer *old;
5047   GstBufferList *old_list;
5048
5049   GST_OBJECT_LOCK (basesink);
5050   if ((old = basesink->priv->last_buffer))
5051     basesink->priv->last_buffer = gst_buffer_copy_deep (old);
5052
5053   if ((old_list = basesink->priv->last_buffer_list))
5054     basesink->priv->last_buffer_list = gst_buffer_list_copy_deep (old_list);
5055   GST_OBJECT_UNLOCK (basesink);
5056
5057   if (old)
5058     gst_buffer_unref (old);
5059   if (old_list)
5060     gst_mini_object_unref (GST_MINI_OBJECT_CAST (old_list));
5061 }
5062
5063 static gboolean
5064 gst_base_sink_default_query (GstBaseSink * basesink, GstQuery * query)
5065 {
5066   gboolean res;
5067   GstBaseSinkClass *bclass;
5068
5069   bclass = GST_BASE_SINK_GET_CLASS (basesink);
5070
5071   switch (GST_QUERY_TYPE (query)) {
5072     case GST_QUERY_ALLOCATION:
5073     {
5074       gst_base_sink_drain (basesink);
5075       if (bclass->propose_allocation)
5076         res = bclass->propose_allocation (basesink, query);
5077       else
5078         res = FALSE;
5079       break;
5080     }
5081     case GST_QUERY_CAPS:
5082     {
5083       GstCaps *caps, *filter;
5084
5085       gst_query_parse_caps (query, &filter);
5086       caps = gst_base_sink_query_caps (basesink, basesink->sinkpad, filter);
5087       gst_query_set_caps_result (query, caps);
5088       gst_caps_unref (caps);
5089       res = TRUE;
5090       break;
5091     }
5092     case GST_QUERY_ACCEPT_CAPS:
5093     {
5094       GstCaps *caps, *allowed;
5095       gboolean subset;
5096
5097       /* slightly faster than the default implementation */
5098       gst_query_parse_accept_caps (query, &caps);
5099       allowed = gst_base_sink_query_caps (basesink, basesink->sinkpad, NULL);
5100       subset = gst_caps_is_subset (caps, allowed);
5101       GST_DEBUG_OBJECT (basesink, "Checking if requested caps %" GST_PTR_FORMAT
5102           " are a subset of pad caps %" GST_PTR_FORMAT " result %d", caps,
5103           allowed, subset);
5104       gst_caps_unref (allowed);
5105       gst_query_set_accept_caps_result (query, subset);
5106       res = TRUE;
5107       break;
5108     }
5109     case GST_QUERY_DRAIN:
5110     {
5111       gst_base_sink_drain (basesink);
5112       res = TRUE;
5113       break;
5114     }
5115     case GST_QUERY_POSITION:
5116     {
5117       res = default_element_query (GST_ELEMENT (basesink), query);
5118       break;
5119     }
5120     default:
5121       res =
5122           gst_pad_query_default (basesink->sinkpad, GST_OBJECT_CAST (basesink),
5123           query);
5124       break;
5125   }
5126   return res;
5127 }
5128
5129 static gboolean
5130 gst_base_sink_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
5131 {
5132   GstBaseSink *basesink;
5133   GstBaseSinkClass *bclass;
5134   gboolean res;
5135
5136   basesink = GST_BASE_SINK_CAST (parent);
5137   bclass = GST_BASE_SINK_GET_CLASS (basesink);
5138
5139   if (bclass->query)
5140     res = bclass->query (basesink, query);
5141   else
5142     res = FALSE;
5143
5144   return res;
5145 }
5146
5147 static GstStateChangeReturn
5148 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
5149 {
5150   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
5151   GstBaseSink *basesink = GST_BASE_SINK (element);
5152   GstBaseSinkClass *bclass;
5153   GstBaseSinkPrivate *priv;
5154
5155   priv = basesink->priv;
5156
5157   bclass = GST_BASE_SINK_GET_CLASS (basesink);
5158
5159   switch (transition) {
5160     case GST_STATE_CHANGE_NULL_TO_READY:
5161       if (bclass->start)
5162         if (!bclass->start (basesink))
5163           goto start_failed;
5164       break;
5165     case GST_STATE_CHANGE_READY_TO_PAUSED:
5166       /* need to complete preroll before this state change completes, there
5167        * is no data flow in READY so we can safely assume we need to preroll. */
5168       GST_BASE_SINK_PREROLL_LOCK (basesink);
5169       GST_DEBUG_OBJECT (basesink, "READY to PAUSED");
5170       basesink->have_newsegment = FALSE;
5171       gst_segment_init (&basesink->segment, GST_FORMAT_UNDEFINED);
5172       basesink->offset = 0;
5173       basesink->have_preroll = FALSE;
5174       priv->step_unlock = FALSE;
5175       basesink->need_preroll = TRUE;
5176       basesink->playing_async = TRUE;
5177       priv->current_sstart = GST_CLOCK_TIME_NONE;
5178       priv->current_sstop = GST_CLOCK_TIME_NONE;
5179       priv->eos_rtime = GST_CLOCK_TIME_NONE;
5180       priv->latency = 0;
5181       basesink->eos = FALSE;
5182       priv->received_eos = FALSE;
5183       gst_base_sink_reset_qos (basesink);
5184       priv->rc_next = -1;
5185       priv->committed = FALSE;
5186       priv->call_preroll = TRUE;
5187       priv->current_step.valid = FALSE;
5188       priv->pending_step.valid = FALSE;
5189       if (priv->async_enabled) {
5190         GST_DEBUG_OBJECT (basesink, "doing async state change");
5191         /* when async enabled, post async-start message and return ASYNC from
5192          * the state change function */
5193         ret = GST_STATE_CHANGE_ASYNC;
5194         gst_element_post_message (GST_ELEMENT_CAST (basesink),
5195             gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
5196       } else {
5197         priv->have_latency = TRUE;
5198       }
5199       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5200       break;
5201     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
5202       GST_BASE_SINK_PREROLL_LOCK (basesink);
5203       g_atomic_int_set (&basesink->priv->to_playing, TRUE);
5204       if (!gst_base_sink_needs_preroll (basesink)) {
5205         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, don't need preroll");
5206         /* no preroll needed anymore now. */
5207         basesink->playing_async = FALSE;
5208         basesink->need_preroll = FALSE;
5209         if (basesink->eos) {
5210           GstMessage *message;
5211
5212           /* need to post EOS message here */
5213           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
5214           message = gst_message_new_eos (GST_OBJECT_CAST (basesink));
5215           gst_message_set_seqnum (message, basesink->priv->seqnum);
5216           gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
5217         } else {
5218           GST_DEBUG_OBJECT (basesink, "signal preroll");
5219           GST_BASE_SINK_PREROLL_SIGNAL (basesink);
5220         }
5221       } else {
5222         GST_DEBUG_OBJECT (basesink, "PAUSED to PLAYING, we are not prerolled");
5223         basesink->need_preroll = TRUE;
5224         basesink->playing_async = TRUE;
5225         priv->call_preroll = TRUE;
5226         priv->committed = FALSE;
5227         if (priv->async_enabled) {
5228           GST_DEBUG_OBJECT (basesink, "doing async state change");
5229           ret = GST_STATE_CHANGE_ASYNC;
5230           gst_element_post_message (GST_ELEMENT_CAST (basesink),
5231               gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
5232         }
5233       }
5234       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5235       break;
5236     default:
5237       break;
5238   }
5239
5240   {
5241     GstStateChangeReturn bret;
5242
5243     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5244     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
5245       goto activate_failed;
5246   }
5247
5248   switch (transition) {
5249     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
5250       /* completed transition, so need not be marked any longer
5251        * And it should be unmarked, since e.g. losing our position upon flush
5252        * does not really change state to PAUSED ... */
5253       g_atomic_int_set (&basesink->priv->to_playing, FALSE);
5254       break;
5255     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
5256       g_atomic_int_set (&basesink->priv->to_playing, FALSE);
5257       GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED");
5258       /* FIXME, make sure we cannot enter _render first */
5259
5260       /* we need to call ::unlock before locking PREROLL_LOCK
5261        * since we lock it before going into ::render */
5262       if (bclass->unlock)
5263         bclass->unlock (basesink);
5264
5265       GST_BASE_SINK_PREROLL_LOCK (basesink);
5266       GST_DEBUG_OBJECT (basesink, "got preroll lock");
5267       /* now that we have the PREROLL lock, clear our unlock request */
5268       if (bclass->unlock_stop)
5269         bclass->unlock_stop (basesink);
5270
5271       if (basesink->clock_id) {
5272         GST_DEBUG_OBJECT (basesink, "unschedule clock");
5273         gst_clock_id_unschedule (basesink->clock_id);
5274       }
5275
5276       /* if we don't have a preroll buffer we need to wait for a preroll and
5277        * return ASYNC. */
5278       if (!gst_base_sink_needs_preroll (basesink)) {
5279         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, we are prerolled");
5280         basesink->playing_async = FALSE;
5281         basesink->need_preroll = FALSE;
5282       } else {
5283         if (GST_STATE_TARGET (GST_ELEMENT (basesink)) <= GST_STATE_READY) {
5284           GST_DEBUG_OBJECT (basesink, "element is <= READY");
5285           ret = GST_STATE_CHANGE_SUCCESS;
5286         } else {
5287           GST_DEBUG_OBJECT (basesink,
5288               "PLAYING to PAUSED, we are not prerolled");
5289           basesink->playing_async = TRUE;
5290           basesink->need_preroll = TRUE;
5291           priv->committed = FALSE;
5292           priv->call_preroll = TRUE;
5293           if (priv->async_enabled) {
5294             GST_DEBUG_OBJECT (basesink, "doing async state change");
5295             ret = GST_STATE_CHANGE_ASYNC;
5296             gst_element_post_message (GST_ELEMENT_CAST (basesink),
5297                 gst_message_new_async_start (GST_OBJECT_CAST (basesink)));
5298           }
5299         }
5300       }
5301       GST_DEBUG_OBJECT (basesink, "rendered: %" G_GUINT64_FORMAT
5302           ", dropped: %" G_GUINT64_FORMAT, priv->rendered, priv->dropped);
5303
5304       gst_base_sink_reset_qos (basesink);
5305       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5306       break;
5307     case GST_STATE_CHANGE_PAUSED_TO_READY:
5308       GST_BASE_SINK_PREROLL_LOCK (basesink);
5309       /* start by resetting our position state with the object lock so that the
5310        * position query gets the right idea. We do this before we post the
5311        * messages so that the message handlers pick this up. */
5312       GST_OBJECT_LOCK (basesink);
5313       basesink->have_newsegment = FALSE;
5314       priv->current_sstart = GST_CLOCK_TIME_NONE;
5315       priv->current_sstop = GST_CLOCK_TIME_NONE;
5316       priv->have_latency = FALSE;
5317       if (priv->cached_clock_id) {
5318         gst_clock_id_unref (priv->cached_clock_id);
5319         priv->cached_clock_id = NULL;
5320       }
5321       gst_caps_replace (&basesink->priv->caps, NULL);
5322       GST_OBJECT_UNLOCK (basesink);
5323
5324       gst_base_sink_set_last_buffer (basesink, NULL);
5325       gst_base_sink_set_last_buffer_list (basesink, NULL);
5326       priv->call_preroll = FALSE;
5327
5328       if (!priv->committed) {
5329         if (priv->async_enabled) {
5330           GST_DEBUG_OBJECT (basesink, "PAUSED to READY, posting async-done");
5331
5332           gst_element_post_message (GST_ELEMENT_CAST (basesink),
5333               gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
5334                   GST_STATE_PLAYING, GST_STATE_PAUSED, GST_STATE_READY));
5335
5336           gst_element_post_message (GST_ELEMENT_CAST (basesink),
5337               gst_message_new_async_done (GST_OBJECT_CAST (basesink),
5338                   GST_CLOCK_TIME_NONE));
5339         }
5340         priv->committed = TRUE;
5341       } else {
5342         GST_DEBUG_OBJECT (basesink, "PAUSED to READY, don't need_preroll");
5343       }
5344       GST_BASE_SINK_PREROLL_UNLOCK (basesink);
5345       break;
5346     case GST_STATE_CHANGE_READY_TO_NULL:
5347       if (bclass->stop) {
5348         if (!bclass->stop (basesink)) {
5349           GST_WARNING_OBJECT (basesink, "failed to stop");
5350         }
5351       }
5352       gst_base_sink_set_last_buffer (basesink, NULL);
5353       gst_base_sink_set_last_buffer_list (basesink, NULL);
5354       priv->call_preroll = FALSE;
5355       break;
5356     default:
5357       break;
5358   }
5359
5360   return ret;
5361
5362   /* ERRORS */
5363 start_failed:
5364   {
5365     GST_DEBUG_OBJECT (basesink, "failed to start");
5366     /* subclass is supposed to post a message but we post one as a fallback
5367      * just in case */
5368     GST_ELEMENT_ERROR (basesink, CORE, STATE_CHANGE, (NULL),
5369         ("Failed to start"));
5370     return GST_STATE_CHANGE_FAILURE;
5371   }
5372 activate_failed:
5373   {
5374     GST_DEBUG_OBJECT (basesink,
5375         "element failed to change states -- activation problem?");
5376     return GST_STATE_CHANGE_FAILURE;
5377   }
5378 }