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