87bd6d2404cc371b675ac849d6beb7c4ea990d7e
[platform/upstream/gstreamer.git] / libs / gst / base / gstbasesink.c
1 /* GStreamer
2  * Copyright (C) 2005 Wim Taymans <wim@fluendo.com>
3  *
4  * gstbasesink.c:
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  * This class is for elements that do output operations.
28  *
29  * <itemizedlist>
30  *   <listitem><para>one sinkpad</para></listitem>
31  *   <listitem><para>handles state changes</para></listitem>
32  *   <listitem><para>pull/push mode</para></listitem>
33  *   <listitem><para>handles seeking/query</para></listitem>
34  *   <listitem><para>handles preroll</para></listitem>
35  *   <listitem><para>EOS handling</para></listitem>
36  * </itemizedlist>
37  */
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #include "gstbasesink.h"
44 #include <gst/gstmarshal.h>
45 #include <gst/gst-i18n-lib.h>
46
47 GST_DEBUG_CATEGORY_STATIC (gst_base_sink_debug);
48 #define GST_CAT_DEFAULT gst_base_sink_debug
49
50 /* BaseSink signals and properties */
51 enum
52 {
53   /* FILL ME */
54   SIGNAL_HANDOFF,
55   LAST_SIGNAL
56 };
57
58 #define DEFAULT_SIZE 1024
59 #define DEFAULT_CAN_ACTIVATE_PULL FALSE /* fixme: enable me */
60 #define DEFAULT_CAN_ACTIVATE_PUSH TRUE
61
62 #define DEFAULT_SYNC TRUE
63
64 enum
65 {
66   PROP_0,
67   PROP_PREROLL_QUEUE_LEN,
68   PROP_SYNC
69 };
70
71 static GstElementClass *parent_class = NULL;
72
73 static void gst_base_sink_base_init (gpointer g_class);
74 static void gst_base_sink_class_init (GstBaseSinkClass * klass);
75 static void gst_base_sink_init (GstBaseSink * trans, gpointer g_class);
76 static void gst_base_sink_finalize (GObject * object);
77
78 GType
79 gst_base_sink_get_type (void)
80 {
81   static GType base_sink_type = 0;
82
83   if (!base_sink_type) {
84     static const GTypeInfo base_sink_info = {
85       sizeof (GstBaseSinkClass),
86       (GBaseInitFunc) gst_base_sink_base_init,
87       NULL,
88       (GClassInitFunc) gst_base_sink_class_init,
89       NULL,
90       NULL,
91       sizeof (GstBaseSink),
92       0,
93       (GInstanceInitFunc) gst_base_sink_init,
94     };
95
96     base_sink_type = g_type_register_static (GST_TYPE_ELEMENT,
97         "GstBaseSink", &base_sink_info, G_TYPE_FLAG_ABSTRACT);
98   }
99   return base_sink_type;
100 }
101
102 static void gst_base_sink_set_clock (GstElement * element, GstClock * clock);
103
104 static void gst_base_sink_set_property (GObject * object, guint prop_id,
105     const GValue * value, GParamSpec * pspec);
106 static void gst_base_sink_get_property (GObject * object, guint prop_id,
107     GValue * value, GParamSpec * pspec);
108
109 static gboolean gst_base_sink_send_event (GstElement * element,
110     GstEvent * event);
111 static gboolean gst_base_sink_query (GstElement * element, GstQuery * query);
112
113 static GstCaps *gst_base_sink_get_caps (GstBaseSink * sink);
114 static gboolean gst_base_sink_set_caps (GstBaseSink * sink, GstCaps * caps);
115 static GstFlowReturn gst_base_sink_buffer_alloc (GstBaseSink * sink,
116     guint64 offset, guint size, GstCaps * caps, GstBuffer ** buf);
117 static void gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
118     GstClockTime * start, GstClockTime * end);
119
120 static GstStateChangeReturn gst_base_sink_change_state (GstElement * element,
121     GstStateChange transition);
122
123 static GstFlowReturn gst_base_sink_chain (GstPad * pad, GstBuffer * buffer);
124 static void gst_base_sink_loop (GstPad * pad);
125 static gboolean gst_base_sink_activate (GstPad * pad);
126 static gboolean gst_base_sink_activate_push (GstPad * pad, gboolean active);
127 static gboolean gst_base_sink_activate_pull (GstPad * pad, gboolean active);
128 static gboolean gst_base_sink_event (GstPad * pad, GstEvent * event);
129 static inline GstFlowReturn gst_base_sink_handle_buffer (GstBaseSink * basesink,
130     GstBuffer * buf);
131 static inline gboolean gst_base_sink_handle_event (GstBaseSink * basesink,
132     GstEvent * event);
133
134 static void
135 gst_base_sink_base_init (gpointer g_class)
136 {
137   GST_DEBUG_CATEGORY_INIT (gst_base_sink_debug, "basesink", 0,
138       "basesink element");
139 }
140
141 static void
142 gst_base_sink_class_init (GstBaseSinkClass * klass)
143 {
144   GObjectClass *gobject_class;
145   GstElementClass *gstelement_class;
146
147   gobject_class = (GObjectClass *) klass;
148   gstelement_class = (GstElementClass *) klass;
149
150   parent_class = g_type_class_ref (GST_TYPE_ELEMENT);
151
152   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_sink_finalize);
153   gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_base_sink_set_property);
154   gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_base_sink_get_property);
155
156   /* FIXME, this next value should be configured using an event from the
157    * upstream element */
158   g_object_class_install_property (G_OBJECT_CLASS (klass),
159       PROP_PREROLL_QUEUE_LEN,
160       g_param_spec_uint ("preroll-queue-len", "preroll-queue-len",
161           "Number of buffers to queue during preroll", 0, G_MAXUINT, 0,
162           G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
163   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SYNC,
164       g_param_spec_boolean ("sync", "Sync", "Sync on the clock", DEFAULT_SYNC,
165           G_PARAM_READWRITE));
166
167   gstelement_class->set_clock = GST_DEBUG_FUNCPTR (gst_base_sink_set_clock);
168   gstelement_class->change_state =
169       GST_DEBUG_FUNCPTR (gst_base_sink_change_state);
170   gstelement_class->send_event = GST_DEBUG_FUNCPTR (gst_base_sink_send_event);
171   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_base_sink_query);
172
173   klass->get_caps = GST_DEBUG_FUNCPTR (gst_base_sink_get_caps);
174   klass->set_caps = GST_DEBUG_FUNCPTR (gst_base_sink_set_caps);
175   klass->buffer_alloc = GST_DEBUG_FUNCPTR (gst_base_sink_buffer_alloc);
176   klass->get_times = GST_DEBUG_FUNCPTR (gst_base_sink_get_times);
177 }
178
179 static GstCaps *
180 gst_base_sink_pad_getcaps (GstPad * pad)
181 {
182   GstBaseSinkClass *bclass;
183   GstBaseSink *bsink;
184   GstCaps *caps = NULL;
185
186   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
187   bclass = GST_BASE_SINK_GET_CLASS (bsink);
188   if (bclass->get_caps)
189     caps = bclass->get_caps (bsink);
190
191   if (caps == NULL) {
192     GstPadTemplate *pad_template;
193
194     pad_template =
195         gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
196     if (pad_template != NULL) {
197       caps = gst_caps_ref (gst_pad_template_get_caps (pad_template));
198     }
199   }
200   gst_object_unref (bsink);
201
202   return caps;
203 }
204
205 static gboolean
206 gst_base_sink_pad_setcaps (GstPad * pad, GstCaps * caps)
207 {
208   GstBaseSinkClass *bclass;
209   GstBaseSink *bsink;
210   gboolean res = FALSE;
211
212   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
213   bclass = GST_BASE_SINK_GET_CLASS (bsink);
214
215   if (bclass->set_caps)
216     res = bclass->set_caps (bsink, caps);
217
218   gst_object_unref (bsink);
219
220   return res;
221 }
222
223 static GstFlowReturn
224 gst_base_sink_pad_buffer_alloc (GstPad * pad, guint64 offset, guint size,
225     GstCaps * caps, GstBuffer ** buf)
226 {
227   GstBaseSinkClass *bclass;
228   GstBaseSink *bsink;
229   GstFlowReturn result = GST_FLOW_OK;
230
231   bsink = GST_BASE_SINK (gst_pad_get_parent (pad));
232   bclass = GST_BASE_SINK_GET_CLASS (bsink);
233
234   if (bclass->buffer_alloc)
235     result = bclass->buffer_alloc (bsink, offset, size, caps, buf);
236   else
237     *buf = NULL;                /* fallback in gstpad.c will allocate generic buffer */
238
239   gst_object_unref (bsink);
240
241   return result;
242 }
243
244 static void
245 gst_base_sink_init (GstBaseSink * basesink, gpointer g_class)
246 {
247   GstPadTemplate *pad_template;
248
249   pad_template =
250       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (g_class), "sink");
251   g_return_if_fail (pad_template != NULL);
252
253   basesink->sinkpad = gst_pad_new_from_template (pad_template, "sink");
254
255   gst_pad_set_getcaps_function (basesink->sinkpad,
256       GST_DEBUG_FUNCPTR (gst_base_sink_pad_getcaps));
257   gst_pad_set_setcaps_function (basesink->sinkpad,
258       GST_DEBUG_FUNCPTR (gst_base_sink_pad_setcaps));
259   gst_pad_set_bufferalloc_function (basesink->sinkpad,
260       GST_DEBUG_FUNCPTR (gst_base_sink_pad_buffer_alloc));
261   gst_pad_set_activate_function (basesink->sinkpad,
262       GST_DEBUG_FUNCPTR (gst_base_sink_activate));
263   gst_pad_set_activatepush_function (basesink->sinkpad,
264       GST_DEBUG_FUNCPTR (gst_base_sink_activate_push));
265   gst_pad_set_activatepull_function (basesink->sinkpad,
266       GST_DEBUG_FUNCPTR (gst_base_sink_activate_pull));
267   gst_pad_set_event_function (basesink->sinkpad,
268       GST_DEBUG_FUNCPTR (gst_base_sink_event));
269   gst_pad_set_chain_function (basesink->sinkpad,
270       GST_DEBUG_FUNCPTR (gst_base_sink_chain));
271   gst_element_add_pad (GST_ELEMENT (basesink), basesink->sinkpad);
272
273   basesink->pad_mode = GST_ACTIVATE_NONE;
274   GST_PAD_TASK (basesink->sinkpad) = NULL;
275   basesink->preroll_queue = g_queue_new ();
276
277   basesink->can_activate_push = DEFAULT_CAN_ACTIVATE_PUSH;
278   basesink->can_activate_pull = DEFAULT_CAN_ACTIVATE_PULL;
279
280   basesink->sync = DEFAULT_SYNC;
281
282   GST_OBJECT_FLAG_SET (basesink, GST_ELEMENT_IS_SINK);
283 }
284
285 static void
286 gst_base_sink_finalize (GObject * object)
287 {
288   GstBaseSink *basesink;
289
290   basesink = GST_BASE_SINK (object);
291
292   g_queue_free (basesink->preroll_queue);
293
294   G_OBJECT_CLASS (parent_class)->finalize (object);
295 }
296
297 static void
298 gst_base_sink_set_clock (GstElement * element, GstClock * clock)
299 {
300   GstBaseSink *sink;
301
302   sink = GST_BASE_SINK (element);
303
304   sink->clock = clock;
305 }
306
307 static void
308 gst_base_sink_set_property (GObject * object, guint prop_id,
309     const GValue * value, GParamSpec * pspec)
310 {
311   GstBaseSink *sink = GST_BASE_SINK (object);
312
313   switch (prop_id) {
314     case PROP_PREROLL_QUEUE_LEN:
315       /* preroll lock necessary to serialize with finish_preroll */
316       GST_PREROLL_LOCK (sink->sinkpad);
317       sink->preroll_queue_max_len = g_value_get_uint (value);
318       GST_PREROLL_UNLOCK (sink->sinkpad);
319       break;
320     case PROP_SYNC:
321       sink->sync = g_value_get_boolean (value);
322       break;
323     default:
324       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
325       break;
326   }
327 }
328
329 static void
330 gst_base_sink_get_property (GObject * object, guint prop_id, GValue * value,
331     GParamSpec * pspec)
332 {
333   GstBaseSink *sink = GST_BASE_SINK (object);
334
335   GST_LOCK (sink);
336   switch (prop_id) {
337     case PROP_PREROLL_QUEUE_LEN:
338       g_value_set_uint (value, sink->preroll_queue_max_len);
339       break;
340     case PROP_SYNC:
341       g_value_set_boolean (value, sink->sync);
342       break;
343     default:
344       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
345       break;
346   }
347   GST_UNLOCK (sink);
348 }
349
350 static GstCaps *
351 gst_base_sink_get_caps (GstBaseSink * sink)
352 {
353   return NULL;
354 }
355
356 static gboolean
357 gst_base_sink_set_caps (GstBaseSink * sink, GstCaps * caps)
358 {
359   return TRUE;
360 }
361
362 static GstFlowReturn
363 gst_base_sink_buffer_alloc (GstBaseSink * sink, guint64 offset, guint size,
364     GstCaps * caps, GstBuffer ** buf)
365 {
366   *buf = NULL;
367   return GST_FLOW_OK;
368 }
369
370 /* with PREROLL_LOCK */
371 static GstFlowReturn
372 gst_base_sink_preroll_queue_empty (GstBaseSink * basesink, GstPad * pad)
373 {
374   GstMiniObject *obj;
375   GQueue *q = basesink->preroll_queue;
376   GstFlowReturn ret;
377
378   ret = GST_FLOW_OK;
379
380   if (q) {
381     GST_DEBUG_OBJECT (basesink, "emptying queue");
382     while ((obj = g_queue_pop_head (q))) {
383       gboolean is_buffer;
384
385       is_buffer = GST_IS_BUFFER (obj);
386       if (G_LIKELY (is_buffer)) {
387         basesink->preroll_queued--;
388         basesink->buffers_queued--;
389       } else {
390         switch (GST_EVENT_TYPE (obj)) {
391           case GST_EVENT_EOS:
392             basesink->preroll_queued--;
393             break;
394           default:
395             break;
396         }
397         basesink->events_queued--;
398       }
399       /* we release the preroll lock while pushing so that we
400        * can still flush it while blocking on the clock or
401        * inside the element. */
402       GST_PREROLL_UNLOCK (pad);
403
404       if (G_LIKELY (is_buffer)) {
405         GST_DEBUG_OBJECT (basesink, "popped buffer %p", obj);
406         ret = gst_base_sink_handle_buffer (basesink, GST_BUFFER_CAST (obj));
407       } else {
408         GST_DEBUG_OBJECT (basesink, "popped event %p", obj);
409         gst_base_sink_handle_event (basesink, GST_EVENT_CAST (obj));
410         ret = GST_FLOW_OK;
411       }
412
413       GST_PREROLL_LOCK (pad);
414     }
415     GST_DEBUG_OBJECT (basesink, "queue empty");
416   }
417   return ret;
418 }
419
420 /* with PREROLL_LOCK */
421 static void
422 gst_base_sink_preroll_queue_flush (GstBaseSink * basesink, GstPad * pad)
423 {
424   GstMiniObject *obj;
425   GQueue *q = basesink->preroll_queue;
426
427   GST_DEBUG_OBJECT (basesink, "flushing queue %p", basesink);
428   if (q) {
429     while ((obj = g_queue_pop_head (q))) {
430       GST_DEBUG_OBJECT (basesink, "popped %p", obj);
431       gst_mini_object_unref (obj);
432     }
433   }
434   /* we can't have EOS anymore now */
435   basesink->eos = FALSE;
436   basesink->eos_queued = FALSE;
437   basesink->preroll_queued = 0;
438   basesink->buffers_queued = 0;
439   basesink->events_queued = 0;
440   basesink->have_preroll = FALSE;
441   /* and signal any waiters now */
442   GST_PREROLL_SIGNAL (pad);
443 }
444
445 /* with PREROLL_LOCK */
446 static gboolean
447 gst_base_sink_commit_state (GstBaseSink * basesink)
448 {
449   /* commit state and proceed to next pending state */
450   {
451     GstState current, next, pending, post_pending;
452     GstMessage *message;
453     gboolean post_paused = FALSE;
454     gboolean post_playing = FALSE;
455
456     GST_LOCK (basesink);
457     current = GST_STATE (basesink);
458     next = GST_STATE_NEXT (basesink);
459     pending = GST_STATE_PENDING (basesink);
460     post_pending = pending;
461
462     switch (pending) {
463       case GST_STATE_PLAYING:
464         basesink->need_preroll = FALSE;
465         post_playing = TRUE;
466         /* post PAUSED too when we were READY */
467         if (current == GST_STATE_READY) {
468           post_paused = TRUE;
469         }
470         break;
471       case GST_STATE_PAUSED:
472         basesink->need_preroll = TRUE;
473         post_paused = TRUE;
474         post_pending = GST_STATE_VOID_PENDING;
475         break;
476       case GST_STATE_READY:
477         goto stopping;
478       default:
479         break;
480     }
481
482     if (pending != GST_STATE_VOID_PENDING) {
483       GST_STATE (basesink) = pending;
484       GST_STATE_NEXT (basesink) = GST_STATE_VOID_PENDING;
485       GST_STATE_PENDING (basesink) = GST_STATE_VOID_PENDING;
486       GST_STATE_RETURN (basesink) = GST_STATE_CHANGE_SUCCESS;
487     }
488     GST_UNLOCK (basesink);
489
490     if (post_paused) {
491       message = gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
492           current, next, post_pending);
493       gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
494     }
495     if (post_playing) {
496       message = gst_message_new_state_changed (GST_OBJECT_CAST (basesink),
497           next, pending, GST_STATE_VOID_PENDING);
498       gst_element_post_message (GST_ELEMENT_CAST (basesink), message);
499     }
500     /* and mark dirty */
501     if (post_paused || post_playing) {
502       gst_element_post_message (GST_ELEMENT_CAST (basesink),
503           gst_message_new_state_dirty (GST_OBJECT_CAST (basesink)));
504     }
505
506     GST_STATE_BROADCAST (basesink);
507   }
508   return TRUE;
509
510 stopping:
511   {
512     /* app is going to READY */
513     GST_UNLOCK (basesink);
514     return FALSE;
515   }
516 }
517
518 /* with STREAM_LOCK */
519 static GstFlowReturn
520 gst_base_sink_handle_object (GstBaseSink * basesink, GstPad * pad,
521     GstMiniObject * obj)
522 {
523   gint length;
524   gboolean have_event;
525
526   GST_PREROLL_LOCK (pad);
527   /* push object on the queue */
528   GST_DEBUG_OBJECT (basesink, "push %p on preroll_queue", obj);
529   g_queue_push_tail (basesink->preroll_queue, obj);
530
531   have_event = GST_IS_EVENT (obj);
532   if (have_event) {
533     GstEvent *event = GST_EVENT (obj);
534
535     switch (GST_EVENT_TYPE (obj)) {
536       case GST_EVENT_EOS:
537         basesink->preroll_queued++;
538         basesink->eos = TRUE;
539         basesink->eos_queued = TRUE;
540         break;
541       case GST_EVENT_NEWSEGMENT:
542       {
543         gboolean update;
544         gdouble rate;
545         GstFormat format;
546         gint64 segment_start;
547         gint64 segment_stop;
548         gint64 segment_time;
549         GstClockTime duration;
550
551
552         /* the newsegment event is needed to bring the buffer timestamps to the
553          * stream time and to drop samples outside of the playback segment. */
554         gst_event_parse_newsegment (event, &update, &rate, &format,
555             &segment_start, &segment_stop, &segment_time);
556
557         basesink->have_newsegment = TRUE;
558
559         /* any other format with 0 also gives time 0, the other values are
560          * invalid as time though. */
561         if (format != GST_FORMAT_TIME && segment_start == 0) {
562           GST_DEBUG_OBJECT (basesink,
563               "non-time newsegment with start 0, coaxing into FORMAT_TIME");
564           format = GST_FORMAT_TIME;
565           segment_stop = -1;
566           segment_time = -1;
567         }
568
569         if (format != GST_FORMAT_TIME) {
570           GST_DEBUG_OBJECT (basesink,
571               "received non time %d NEW_SEGMENT %" G_GINT64_FORMAT
572               " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT,
573               format, segment_start, segment_stop, segment_time);
574
575           /* this means this sink will not be able to clip or drop samples
576            * and timestamps have to start from 0. */
577           basesink->segment_start = -1;
578           basesink->segment_stop = -1;
579           basesink->segment_time = -1;
580           goto done_newsegment;
581         }
582         /* check if we really have a new segment or the previous one is
583          * closed */
584         if (!update) {
585           /* the new segment has to be aligned with the old segment.
586            * We first update the accumulated time of the previous
587            * segment. the accumulated time is used when syncing to the
588            * clock. A flush event sets the accumulated time back to 0
589            */
590           if (GST_CLOCK_TIME_IS_VALID (basesink->segment_stop)) {
591             duration = basesink->segment_stop - basesink->segment_start;
592           } else if (GST_CLOCK_TIME_IS_VALID (basesink->current_end)) {
593             /* else use last seen timestamp as segment stop */
594             duration = basesink->current_end - basesink->segment_start;
595           } else {
596             duration = 0;
597           }
598         } else {
599           duration = segment_start - basesink->segment_start;
600         }
601
602         /* use previous rate to calculate duration */
603         basesink->segment_accum += gst_gdouble_to_guint64 (
604             (gst_guint64_to_gdouble (duration) / ABS (basesink->segment_rate)));
605         /* then update the current segment */
606         basesink->segment_rate = rate;
607         basesink->segment_start = segment_start;
608         basesink->segment_stop = segment_stop;
609         basesink->segment_time = segment_time;
610
611         GST_DEBUG_OBJECT (basesink,
612             "received NEWSEGMENT %" GST_TIME_FORMAT " -- %"
613             GST_TIME_FORMAT ", time %" GST_TIME_FORMAT ", accum %"
614             GST_TIME_FORMAT,
615             GST_TIME_ARGS (basesink->segment_start),
616             GST_TIME_ARGS (basesink->segment_stop),
617             GST_TIME_ARGS (basesink->segment_time),
618             GST_TIME_ARGS (basesink->segment_accum));
619       done_newsegment:
620         break;
621       }
622       default:
623         break;
624     }
625     basesink->events_queued++;
626   } else {
627     GstBuffer *buf = GST_BUFFER (obj);
628
629     if (!basesink->have_newsegment) {
630       GST_ELEMENT_WARNING (basesink, STREAM, FAILED,
631           (_("Internal data flow problem.")),
632           ("Received buffer without a new-segment. Cannot sync to clock."));
633       basesink->have_newsegment = TRUE;
634       /* this means this sink will not be able to sync to the clock */
635       basesink->segment_start = -1;
636       basesink->segment_stop = -1;
637     }
638
639     /* check if the buffer needs to be dropped */
640     if (TRUE) {
641       GstClockTime start = -1, end = -1;
642
643       /* we don't use the subclassed method as it may not return
644        * valid values for our purpose here */
645       gst_base_sink_get_times (basesink, buf, &start, &end);
646
647       GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
648           ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start),
649           GST_TIME_ARGS (end));
650
651       /* need to drop if the timestamp is not between segment_start and
652        * segment_stop. we check if the complete sample is outside of the
653        * range since the sink might be able to clip the sample. */
654       if (GST_CLOCK_TIME_IS_VALID (end) &&
655           GST_CLOCK_TIME_IS_VALID (basesink->segment_start)) {
656         if (end <= basesink->segment_start) {
657           GST_DEBUG_OBJECT (basesink,
658               "buffer end %" GST_TIME_FORMAT " <= segment start %"
659               GST_TIME_FORMAT ", dropping buffer", GST_TIME_ARGS (end),
660               GST_TIME_ARGS (basesink->segment_start));
661           goto dropping;
662         }
663       }
664       if (GST_CLOCK_TIME_IS_VALID (start) &&
665           GST_CLOCK_TIME_IS_VALID (basesink->segment_stop)) {
666         if (basesink->segment_stop <= start) {
667           GST_DEBUG_OBJECT (basesink,
668               "buffer start %" GST_TIME_FORMAT " >= segment stop %"
669               GST_TIME_FORMAT ", dropping buffer", GST_TIME_ARGS (start),
670               GST_TIME_ARGS (basesink->segment_stop));
671           goto dropping;
672         }
673       }
674     }
675     basesink->preroll_queued++;
676     basesink->buffers_queued++;
677   }
678
679   GST_DEBUG_OBJECT (basesink,
680       "now %d preroll, %d buffers, %d events on queue",
681       basesink->preroll_queued,
682       basesink->buffers_queued, basesink->events_queued);
683
684   /* check if we are prerolling */
685   if (!basesink->need_preroll)
686     goto no_preroll;
687
688   /* there is a buffer queued */
689   if (basesink->buffers_queued == 1) {
690     GST_DEBUG_OBJECT (basesink, "do preroll %p", obj);
691
692     /* if it's a buffer, we need to call the preroll method */
693     if (GST_IS_BUFFER (obj)) {
694       GstBaseSinkClass *bclass;
695       GstFlowReturn pres;
696       GstBuffer *buf = GST_BUFFER (obj);
697
698       GST_DEBUG_OBJECT (basesink, "preroll buffer %" GST_TIME_FORMAT,
699           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
700
701       bclass = GST_BASE_SINK_GET_CLASS (basesink);
702       if (bclass->preroll)
703         if ((pres = bclass->preroll (basesink, buf)) != GST_FLOW_OK)
704           goto preroll_failed;
705     }
706   }
707   length = basesink->preroll_queued;
708   GST_DEBUG_OBJECT (basesink, "prerolled length %d", length);
709
710   if (length == 1) {
711
712     basesink->have_preroll = TRUE;
713
714     /* commit state */
715     if (!gst_base_sink_commit_state (basesink))
716       goto stopping;
717
718     GST_LOCK (pad);
719     if (G_UNLIKELY (GST_PAD_IS_FLUSHING (pad)))
720       goto flushing;
721     GST_UNLOCK (pad);
722
723     /* it is possible that commiting the state made us go to PLAYING
724      * now in which case we don't need to block anymore. */
725     if (!basesink->need_preroll)
726       goto no_preroll;
727
728     length = basesink->preroll_queued;
729
730     /* FIXME: a pad probe could have made us lose the buffer, according
731      * to one of the python tests */
732     if (length == 0) {
733       GST_ERROR_OBJECT (basesink,
734           "preroll_queued dropped from 1 to 0 while committing state change");
735     }
736     g_assert (length <= 1);
737   }
738
739   /* see if we need to block now. We cannot block on events, only
740    * on buffers, the reason is that events can be sent from the
741    * application thread and we don't want to block there. */
742   if (length > basesink->preroll_queue_max_len && !have_event) {
743     /* block until the state changes, or we get a flush, or something */
744     GST_DEBUG_OBJECT (basesink, "waiting to finish preroll");
745     GST_PREROLL_WAIT (pad);
746     GST_DEBUG_OBJECT (basesink, "done preroll");
747     GST_LOCK (pad);
748     if (G_UNLIKELY (GST_PAD_IS_FLUSHING (pad)))
749       goto flushing;
750     GST_UNLOCK (pad);
751   }
752   GST_PREROLL_UNLOCK (pad);
753
754   return GST_FLOW_OK;
755
756 no_preroll:
757   {
758     GstFlowReturn ret;
759
760     GST_DEBUG_OBJECT (basesink, "no preroll needed");
761     /* maybe it was another sink that blocked in preroll, need to check for
762        buffers to drain */
763     basesink->have_preroll = FALSE;
764     ret = gst_base_sink_preroll_queue_empty (basesink, pad);
765     GST_PREROLL_UNLOCK (pad);
766
767     return ret;
768   }
769 dropping:
770   {
771     GstBuffer *buf;
772
773     buf = GST_BUFFER (g_queue_pop_tail (basesink->preroll_queue));
774
775     gst_buffer_unref (buf);
776     GST_PREROLL_UNLOCK (pad);
777
778     return GST_FLOW_OK;
779   }
780 flushing:
781   {
782     GST_UNLOCK (pad);
783     gst_base_sink_preroll_queue_flush (basesink, pad);
784     GST_PREROLL_UNLOCK (pad);
785     GST_DEBUG_OBJECT (basesink, "pad is flushing");
786
787     return GST_FLOW_WRONG_STATE;
788   }
789 stopping:
790   {
791     GST_PREROLL_UNLOCK (pad);
792     GST_DEBUG_OBJECT (basesink, "stopping");
793
794     return GST_FLOW_WRONG_STATE;
795   }
796 preroll_failed:
797   {
798     GST_DEBUG_OBJECT (basesink, "preroll failed");
799     gst_base_sink_preroll_queue_flush (basesink, pad);
800
801     GST_DEBUG_OBJECT (basesink, "abort state");
802     gst_element_abort_state (GST_ELEMENT (basesink));
803
804     return GST_FLOW_ERROR;
805   }
806 }
807
808 static gboolean
809 gst_base_sink_event (GstPad * pad, GstEvent * event)
810 {
811   GstBaseSink *basesink;
812   gboolean result = TRUE;
813   GstBaseSinkClass *bclass;
814
815   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
816
817   bclass = GST_BASE_SINK_GET_CLASS (basesink);
818
819   GST_DEBUG_OBJECT (basesink, "event %p", event);
820
821   switch (GST_EVENT_TYPE (event)) {
822     case GST_EVENT_EOS:
823     {
824       GstFlowReturn ret;
825
826       GST_STREAM_LOCK (pad);
827       /* EOS also finishes the preroll */
828       ret =
829           gst_base_sink_handle_object (basesink, pad, GST_MINI_OBJECT (event));
830       GST_STREAM_UNLOCK (pad);
831       break;
832     }
833     case GST_EVENT_NEWSEGMENT:
834     {
835       GstFlowReturn ret;
836
837       GST_STREAM_LOCK (pad);
838       ret =
839           gst_base_sink_handle_object (basesink, pad, GST_MINI_OBJECT (event));
840       GST_STREAM_UNLOCK (pad);
841       break;
842     }
843     case GST_EVENT_FLUSH_START:
844       /* make sure we are not blocked on the clock also clear any pending
845        * eos state. */
846       if (bclass->event)
847         bclass->event (basesink, event);
848
849       GST_LOCK (basesink);
850       basesink->flushing = TRUE;
851       if (basesink->clock_id) {
852         gst_clock_id_unschedule (basesink->clock_id);
853       }
854       GST_UNLOCK (basesink);
855
856       GST_PREROLL_LOCK (pad);
857       /* we need preroll after the flush */
858       GST_DEBUG_OBJECT (basesink, "flushing, need preroll after flush");
859       basesink->need_preroll = TRUE;
860       /* unlock from a possible state change/preroll */
861       gst_base_sink_preroll_queue_flush (basesink, pad);
862       GST_PREROLL_UNLOCK (pad);
863
864       /* and we need to commit our state again on the next
865        * prerolled buffer */
866       GST_STREAM_LOCK (pad);
867       gst_element_lost_state (GST_ELEMENT (basesink));
868       GST_STREAM_UNLOCK (pad);
869       GST_DEBUG_OBJECT (basesink, "event unref %p %p", basesink, event);
870       gst_event_unref (event);
871       break;
872     case GST_EVENT_FLUSH_STOP:
873       if (bclass->event)
874         bclass->event (basesink, event);
875
876       /* now we are completely unblocked and the _chain method
877        * will return */
878       GST_STREAM_LOCK (pad);
879       GST_LOCK (basesink);
880       basesink->flushing = FALSE;
881       GST_UNLOCK (basesink);
882       /* we need new segment info after the flush. */
883       basesink->segment_start = -1;
884       basesink->segment_stop = -1;
885       basesink->current_start = -1;
886       basesink->current_end = -1;
887       GST_DEBUG_OBJECT (basesink, "reset accum %" GST_TIME_FORMAT,
888           GST_TIME_ARGS (basesink->segment_accum));
889       basesink->segment_accum = 0;
890       GST_STREAM_UNLOCK (pad);
891
892       GST_DEBUG_OBJECT (basesink, "event unref %p %p", basesink, event);
893       gst_event_unref (event);
894       break;
895     default:
896       gst_event_unref (event);
897       break;
898   }
899   gst_object_unref (basesink);
900
901   return result;
902 }
903
904 /* default implementation to calculate the start and end
905  * timestamps on a buffer, subclasses can override
906  */
907 static void
908 gst_base_sink_get_times (GstBaseSink * basesink, GstBuffer * buffer,
909     GstClockTime * start, GstClockTime * end)
910 {
911   GstClockTime timestamp, duration;
912
913   timestamp = GST_BUFFER_TIMESTAMP (buffer);
914   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
915
916     /* get duration to calculate end time */
917     duration = GST_BUFFER_DURATION (buffer);
918     if (GST_CLOCK_TIME_IS_VALID (duration)) {
919       *end = timestamp + duration;
920     }
921     *start = timestamp;
922   }
923 }
924
925 /* with STREAM_LOCK and LOCK*/
926 static GstClockReturn
927 gst_base_sink_wait (GstBaseSink * basesink, GstClockTime time)
928 {
929   GstClockReturn ret;
930   GstClockID id;
931
932   /* no need to attempt a clock wait if we are flushing */
933   if (basesink->flushing) {
934     return GST_CLOCK_UNSCHEDULED;
935   }
936
937   /* clock_id should be NULL outside of this function */
938   g_assert (basesink->clock_id == NULL);
939   g_assert (GST_CLOCK_TIME_IS_VALID (time));
940
941   id = gst_clock_new_single_shot_id (basesink->clock, time);
942
943   basesink->clock_id = id;
944   /* release the object lock while waiting */
945   GST_UNLOCK (basesink);
946
947   ret = gst_clock_id_wait (id, NULL);
948
949   GST_LOCK (basesink);
950   gst_clock_id_unref (id);
951   basesink->clock_id = NULL;
952
953   return ret;
954 }
955
956 /* perform synchronisation on a buffer
957  *
958  * 1) check if we have a clock, if not, do nothing
959  * 2) calculate the start and end time of the buffer
960  * 3) create a single shot notification to wait on
961  *    the clock, save the entry so we can unlock it
962  * 4) wait on the clock, this blocks
963  * 5) unref the clockid again
964  */
965 static GstClockReturn
966 gst_base_sink_do_sync (GstBaseSink * basesink, GstBuffer * buffer)
967 {
968   GstClockReturn result = GST_CLOCK_OK;
969   GstClockTime start, end;
970   GstClockTimeDiff stream_start, stream_end;
971   GstBaseSinkClass *bclass;
972   gboolean start_valid, end_valid;
973
974   bclass = GST_BASE_SINK_GET_CLASS (basesink);
975
976   start = end = -1;
977   if (bclass->get_times)
978     bclass->get_times (basesink, buffer, &start, &end);
979
980   start_valid = GST_CLOCK_TIME_IS_VALID (start);
981   end_valid = GST_CLOCK_TIME_IS_VALID (end);
982
983   GST_DEBUG_OBJECT (basesink, "got times start: %" GST_TIME_FORMAT
984       ", end: %" GST_TIME_FORMAT, GST_TIME_ARGS (start), GST_TIME_ARGS (end));
985
986   /* if we don't have a timestamp, we don't sync */
987   if (!start_valid) {
988     GST_DEBUG_OBJECT (basesink, "start not valid");
989     goto done;
990   }
991
992   /* save last times seen. */
993   basesink->current_start = start;
994   if (end_valid)
995     basesink->current_end = end;
996   else
997     basesink->current_end = start;
998
999   if (GST_CLOCK_TIME_IS_VALID (basesink->segment_stop)) {
1000     /* check if not outside of the segment range, start is
1001      * always valid here. */
1002     if (start > basesink->segment_stop)
1003       goto out_of_segment;
1004   }
1005
1006   /* bring timestamp to stream time using last segment offset. */
1007   if (GST_CLOCK_TIME_IS_VALID (basesink->segment_start)) {
1008     /* check if not outside of the segment range */
1009     if (end_valid && end < basesink->segment_start)
1010       goto out_of_segment;
1011
1012     stream_start = (gint64) start - basesink->segment_start;
1013     stream_end = (gint64) end - basesink->segment_start;
1014   } else {
1015     stream_start = (gint64) start;
1016     stream_end = (gint64) end;
1017   }
1018
1019   /* correct for rate */
1020   if (basesink->segment_rate != 0.0) {
1021     stream_start /= ABS (basesink->segment_rate);
1022     if (end_valid)
1023       stream_end /= ABS (basesink->segment_rate);
1024   }
1025
1026   stream_start += basesink->segment_accum;
1027   if (end_valid)
1028     stream_end += basesink->segment_accum;
1029
1030   /* now do clocking */
1031   if (basesink->clock && basesink->sync) {
1032     GstClockTime base_time;
1033
1034     GST_LOCK (basesink);
1035
1036     base_time = GST_ELEMENT_CAST (basesink)->base_time;
1037
1038     GST_LOG_OBJECT (basesink,
1039         "waiting for clock, base time %" GST_TIME_FORMAT
1040         "stream_start %" GST_TIME_FORMAT,
1041         GST_TIME_ARGS (base_time), GST_TIME_ARGS (stream_start));
1042
1043     /* also save end_time of this buffer so that we can wait
1044      * to signal EOS */
1045     if (end_valid)
1046       basesink->end_time = stream_end + base_time;
1047     else
1048       basesink->end_time = GST_CLOCK_TIME_NONE;
1049
1050     result = gst_base_sink_wait (basesink, stream_start + base_time);
1051
1052     GST_UNLOCK (basesink);
1053
1054     GST_LOG_OBJECT (basesink, "clock entry done: %d", result);
1055   } else {
1056     GST_DEBUG_OBJECT (basesink, "no clock, not syncing");
1057   }
1058
1059 done:
1060   return result;
1061
1062 out_of_segment:
1063   {
1064     GST_LOG_OBJECT (basesink, "buffer skipped, not in segment");
1065     return GST_CLOCK_UNSCHEDULED;
1066   }
1067 }
1068
1069
1070 /* handle an event
1071  *
1072  * 2) render the event
1073  * 3) unref the event
1074  */
1075 static inline gboolean
1076 gst_base_sink_handle_event (GstBaseSink * basesink, GstEvent * event)
1077 {
1078   GstBaseSinkClass *bclass;
1079   gboolean ret;
1080
1081   switch (GST_EVENT_TYPE (event)) {
1082     case GST_EVENT_EOS:
1083       GST_LOCK (basesink);
1084       if (basesink->clock) {
1085         /* wait for last buffer to finish if we have a valid end time */
1086         if (GST_CLOCK_TIME_IS_VALID (basesink->end_time)) {
1087           gst_base_sink_wait (basesink, basesink->end_time);
1088           basesink->end_time = GST_CLOCK_TIME_NONE;
1089         }
1090       }
1091       GST_UNLOCK (basesink);
1092       break;
1093     default:
1094       break;
1095   }
1096
1097   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1098   if (bclass->event)
1099     ret = bclass->event (basesink, event);
1100   else
1101     ret = TRUE;
1102
1103   switch (GST_EVENT_TYPE (event)) {
1104     case GST_EVENT_EOS:
1105       GST_PREROLL_LOCK (basesink->sinkpad);
1106       /* if we are still EOS, we can post the EOS message */
1107       if (basesink->eos) {
1108         /* ok, now we can post the message */
1109         GST_DEBUG_OBJECT (basesink, "Now posting EOS");
1110         gst_element_post_message (GST_ELEMENT_CAST (basesink),
1111             gst_message_new_eos (GST_OBJECT_CAST (basesink)));
1112         basesink->eos_queued = FALSE;
1113       }
1114       GST_PREROLL_UNLOCK (basesink->sinkpad);
1115       break;
1116     default:
1117       break;
1118   }
1119
1120   GST_DEBUG_OBJECT (basesink, "event unref %p %p", basesink, event);
1121   gst_event_unref (event);
1122
1123   return ret;
1124 }
1125
1126 /* handle a buffer
1127  *
1128  * 1) first sync on the buffer
1129  * 2) render the buffer
1130  * 3) unref the buffer
1131  */
1132 static inline GstFlowReturn
1133 gst_base_sink_handle_buffer (GstBaseSink * basesink, GstBuffer * buf)
1134 {
1135   GstFlowReturn ret = GST_FLOW_OK;
1136   GstClockReturn status;
1137
1138   status = gst_base_sink_do_sync (basesink, buf);
1139   switch (status) {
1140     case GST_CLOCK_EARLY:
1141       GST_DEBUG_OBJECT (basesink, "buffer too late!, rendering anyway");
1142       /* fallthrough for now */
1143     case GST_CLOCK_OK:
1144     {
1145       GstBaseSinkClass *bclass;
1146
1147       bclass = GST_BASE_SINK_GET_CLASS (basesink);
1148       if (bclass->render)
1149         ret = bclass->render (basesink, buf);
1150       break;
1151     }
1152     default:
1153       GST_DEBUG_OBJECT (basesink, "clock returned %d, not rendering", status);
1154       break;
1155   }
1156
1157   GST_DEBUG_OBJECT (basesink, "buffer unref after render %p", basesink, buf);
1158   gst_buffer_unref (buf);
1159
1160   return ret;
1161 }
1162
1163 static GstFlowReturn
1164 gst_base_sink_chain (GstPad * pad, GstBuffer * buf)
1165 {
1166   GstBaseSink *basesink;
1167   GstFlowReturn result;
1168
1169   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
1170
1171   if (!(basesink->pad_mode == GST_ACTIVATE_PUSH)) {
1172     GST_LOCK (pad);
1173     g_warning ("Push on pad %s:%s, but it was not activated in push mode",
1174         GST_DEBUG_PAD_NAME (pad));
1175     GST_UNLOCK (pad);
1176     result = GST_FLOW_UNEXPECTED;
1177     goto done;
1178   }
1179
1180   result =
1181       gst_base_sink_handle_object (basesink, pad, GST_MINI_OBJECT_CAST (buf));
1182
1183 done:
1184   gst_object_unref (basesink);
1185
1186   return result;
1187 }
1188
1189 static void
1190 gst_base_sink_loop (GstPad * pad)
1191 {
1192   GstBaseSink *basesink;
1193   GstBuffer *buf = NULL;
1194   GstFlowReturn result;
1195
1196   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
1197
1198   g_assert (basesink->pad_mode == GST_ACTIVATE_PULL);
1199
1200   result = gst_pad_pull_range (pad, basesink->offset, DEFAULT_SIZE, &buf);
1201   if (result != GST_FLOW_OK)
1202     goto paused;
1203
1204   result = gst_base_sink_handle_object (basesink, pad, GST_MINI_OBJECT (buf));
1205   if (result != GST_FLOW_OK)
1206     goto paused;
1207
1208   gst_object_unref (basesink);
1209
1210   /* default */
1211   return;
1212
1213 paused:
1214   {
1215     gst_base_sink_event (pad, gst_event_new_eos ());
1216     gst_object_unref (basesink);
1217     gst_pad_pause_task (pad);
1218     return;
1219   }
1220 }
1221
1222 static gboolean
1223 gst_base_sink_deactivate (GstBaseSink * basesink, GstPad * pad)
1224 {
1225   gboolean result = FALSE;
1226   GstBaseSinkClass *bclass;
1227
1228   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1229
1230   /* step 1, unblock clock sync (if any) or any other blocking thing */
1231   GST_PREROLL_LOCK (pad);
1232   GST_LOCK (basesink);
1233   if (basesink->clock_id) {
1234     gst_clock_id_unschedule (basesink->clock_id);
1235   }
1236   GST_UNLOCK (basesink);
1237
1238   /* unlock any subclasses */
1239   if (bclass->unlock)
1240     bclass->unlock (basesink);
1241
1242   /* flush out the data thread if it's locked in finish_preroll */
1243   GST_DEBUG_OBJECT (basesink,
1244       "flushing out data thread, need preroll to FALSE");
1245   basesink->need_preroll = FALSE;
1246   gst_base_sink_preroll_queue_flush (basesink, pad);
1247   GST_PREROLL_SIGNAL (pad);
1248   GST_PREROLL_UNLOCK (pad);
1249
1250   /* step 2, make sure streaming finishes */
1251   result = gst_pad_stop_task (pad);
1252
1253   return result;
1254 }
1255
1256 static gboolean
1257 gst_base_sink_activate (GstPad * pad)
1258 {
1259   gboolean result = FALSE;
1260   GstBaseSink *basesink;
1261
1262   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
1263
1264   GST_DEBUG_OBJECT (basesink, "Trying pull mode first");
1265
1266   if (basesink->can_activate_pull && gst_pad_check_pull_range (pad)
1267       && gst_pad_activate_pull (pad, TRUE)) {
1268     GST_DEBUG_OBJECT (basesink, "Success activating pull mode");
1269     result = TRUE;
1270   } else {
1271     GST_DEBUG_OBJECT (basesink, "Falling back to push mode");
1272     if (gst_pad_activate_push (pad, TRUE)) {
1273       GST_DEBUG_OBJECT (basesink, "Success activating push mode");
1274       result = TRUE;
1275     }
1276   }
1277
1278   if (!result) {
1279     GST_WARNING_OBJECT (basesink, "Could not activate pad in either mode");
1280   }
1281
1282   gst_object_unref (basesink);
1283
1284   return result;
1285 }
1286
1287 static gboolean
1288 gst_base_sink_activate_push (GstPad * pad, gboolean active)
1289 {
1290   gboolean result;
1291   GstBaseSink *basesink;
1292
1293   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
1294
1295   if (active) {
1296     if (!basesink->can_activate_push) {
1297       result = FALSE;
1298       basesink->pad_mode = GST_ACTIVATE_NONE;
1299     } else {
1300       result = TRUE;
1301       basesink->pad_mode = GST_ACTIVATE_PUSH;
1302     }
1303   } else {
1304     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PUSH)) {
1305       g_warning ("Internal GStreamer activation error!!!");
1306       result = FALSE;
1307     } else {
1308       result = gst_base_sink_deactivate (basesink, pad);
1309       basesink->pad_mode = GST_ACTIVATE_NONE;
1310     }
1311   }
1312
1313   gst_object_unref (basesink);
1314
1315   return result;
1316 }
1317
1318 /* this won't get called until we implement an activate function */
1319 static gboolean
1320 gst_base_sink_activate_pull (GstPad * pad, gboolean active)
1321 {
1322   gboolean result = FALSE;
1323   GstBaseSink *basesink;
1324
1325   basesink = GST_BASE_SINK (gst_pad_get_parent (pad));
1326
1327   if (active) {
1328     if (!basesink->can_activate_pull) {
1329       result = FALSE;
1330       basesink->pad_mode = GST_ACTIVATE_NONE;
1331     } else {
1332       GstPad *peer = gst_pad_get_peer (pad);
1333
1334       if (G_UNLIKELY (peer == NULL)) {
1335         g_warning ("Trying to activate pad in pull mode, but no peer");
1336         result = FALSE;
1337         basesink->pad_mode = GST_ACTIVATE_NONE;
1338       } else {
1339         if (gst_pad_activate_pull (peer, TRUE)) {
1340           basesink->have_newsegment = TRUE;
1341           basesink->segment_start = basesink->segment_stop = 0;
1342
1343           /* set the pad mode before starting the task so that it's in the
1344              correct state for the new thread... */
1345           basesink->pad_mode = GST_ACTIVATE_PULL;
1346           result =
1347               gst_pad_start_task (pad, (GstTaskFunction) gst_base_sink_loop,
1348               pad);
1349           /* but if starting the thread fails, set it back */
1350           if (!result)
1351             basesink->pad_mode = GST_ACTIVATE_NONE;
1352         } else {
1353           GST_DEBUG_OBJECT (pad, "Failed to activate peer in pull mode");
1354           result = FALSE;
1355           basesink->pad_mode = GST_ACTIVATE_NONE;
1356         }
1357         gst_object_unref (peer);
1358       }
1359     }
1360   } else {
1361     if (G_UNLIKELY (basesink->pad_mode != GST_ACTIVATE_PULL)) {
1362       g_warning ("Internal GStreamer activation error!!!");
1363       result = FALSE;
1364     } else {
1365       basesink->have_newsegment = FALSE;
1366       result = gst_base_sink_deactivate (basesink, pad);
1367       basesink->pad_mode = GST_ACTIVATE_NONE;
1368     }
1369   }
1370
1371   gst_object_unref (basesink);
1372
1373   return result;
1374 }
1375
1376 static gboolean
1377 gst_base_sink_send_event (GstElement * element, GstEvent * event)
1378 {
1379   GstPad *pad;
1380   GstBaseSink *basesink = GST_BASE_SINK (element);
1381   gboolean result;
1382
1383   GST_LOCK (element);
1384   pad = basesink->sinkpad;
1385   gst_object_ref (pad);
1386   GST_UNLOCK (element);
1387
1388   result = gst_pad_push_event (pad, event);
1389
1390   gst_object_unref (pad);
1391
1392   return result;
1393 }
1394
1395 static gboolean
1396 gst_base_sink_peer_query (GstBaseSink * sink, GstQuery * query)
1397 {
1398   GstPad *peer;
1399   gboolean res = FALSE;
1400
1401   if ((peer = gst_pad_get_peer (sink->sinkpad))) {
1402     res = gst_pad_query (peer, query);
1403     gst_object_unref (peer);
1404   }
1405   return res;
1406 }
1407
1408 static gboolean
1409 gst_base_sink_get_position (GstBaseSink * basesink, GstFormat format,
1410     gint64 * cur)
1411 {
1412   GstClock *clock;
1413   gboolean res = FALSE;
1414
1415   switch (format) {
1416     case GST_FORMAT_TIME:
1417     {
1418       /* we can answer time format */
1419       GST_LOCK (basesink);
1420       if ((clock = GST_ELEMENT_CLOCK (basesink))) {
1421         GstClockTime now;
1422         gint64 segment_time;
1423
1424         gst_object_ref (clock);
1425         GST_UNLOCK (basesink);
1426
1427         now = gst_clock_get_time (clock);
1428
1429         GST_LOCK (basesink);
1430         if (GST_CLOCK_TIME_IS_VALID (basesink->segment_time))
1431           segment_time = basesink->segment_time;
1432         else
1433           segment_time = 0;
1434
1435         *cur = now - GST_ELEMENT_CAST (basesink)->base_time + segment_time;
1436
1437         GST_DEBUG_OBJECT (basesink,
1438             "now %" GST_TIME_FORMAT " + segment_time %" GST_TIME_FORMAT " = %"
1439             GST_TIME_FORMAT, GST_TIME_ARGS (now),
1440             GST_TIME_ARGS (segment_time), GST_TIME_ARGS (*cur));
1441
1442         gst_object_unref (clock);
1443
1444         res = TRUE;
1445       }
1446       GST_UNLOCK (basesink);
1447     }
1448     default:
1449       break;
1450   }
1451   return res;
1452 }
1453
1454 static gboolean
1455 gst_base_sink_query (GstElement * element, GstQuery * query)
1456 {
1457   gboolean res = FALSE;
1458
1459   GstBaseSink *basesink = GST_BASE_SINK (element);
1460
1461   switch (GST_QUERY_TYPE (query)) {
1462     case GST_QUERY_POSITION:
1463     {
1464       gint64 cur = 0;
1465       GstFormat format;
1466       gboolean eos;
1467
1468       GST_PREROLL_LOCK (basesink->sinkpad);
1469       eos = basesink->eos;
1470       GST_PREROLL_UNLOCK (basesink->sinkpad);
1471
1472       if (eos) {
1473         res = gst_base_sink_peer_query (basesink, query);
1474       } else {
1475         gst_query_parse_position (query, &format, NULL);
1476
1477         GST_DEBUG_OBJECT (basesink, "current position format %d", format);
1478
1479         if ((res = gst_base_sink_get_position (basesink, format, &cur))) {
1480           gst_query_set_position (query, format, cur);
1481         } else {
1482           res = gst_base_sink_peer_query (basesink, query);
1483         }
1484       }
1485       break;
1486     }
1487     case GST_QUERY_DURATION:
1488       res = gst_base_sink_peer_query (basesink, query);
1489       break;
1490     case GST_QUERY_LATENCY:
1491       break;
1492     case GST_QUERY_JITTER:
1493       break;
1494     case GST_QUERY_RATE:
1495       //gst_query_set_rate (query, basesink->segment_rate);
1496       res = TRUE;
1497       break;
1498     case GST_QUERY_SEGMENT:
1499     {
1500       /* FIXME, bring start/stop to stream time */
1501       gst_query_set_segment (query, basesink->segment_rate,
1502           GST_FORMAT_TIME, basesink->segment_start, basesink->segment_stop);
1503       break;
1504     }
1505     case GST_QUERY_SEEKING:
1506     case GST_QUERY_CONVERT:
1507     case GST_QUERY_FORMATS:
1508     default:
1509       res = gst_base_sink_peer_query (basesink, query);
1510       break;
1511   }
1512   return res;
1513 }
1514
1515 static GstStateChangeReturn
1516 gst_base_sink_change_state (GstElement * element, GstStateChange transition)
1517 {
1518   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1519   GstBaseSink *basesink = GST_BASE_SINK (element);
1520   GstBaseSinkClass *bclass;
1521
1522   bclass = GST_BASE_SINK_GET_CLASS (basesink);
1523
1524   switch (transition) {
1525     case GST_STATE_CHANGE_NULL_TO_READY:
1526       if (bclass->start)
1527         if (!bclass->start (basesink))
1528           goto start_failed;
1529       break;
1530     case GST_STATE_CHANGE_READY_TO_PAUSED:
1531       /* need to complete preroll before this state change completes, there
1532        * is no data flow in READY so we can safely assume we need to preroll. */
1533       basesink->offset = 0;
1534       GST_PREROLL_LOCK (basesink->sinkpad);
1535       basesink->have_preroll = FALSE;
1536       GST_DEBUG_OBJECT (basesink, "READY to PAUSED, need preroll to FALSE");
1537       basesink->need_preroll = TRUE;
1538       GST_PREROLL_UNLOCK (basesink->sinkpad);
1539       basesink->have_newsegment = FALSE;
1540       basesink->segment_rate = 1.0;
1541       basesink->segment_start = 0;
1542       basesink->segment_stop = 0;
1543       basesink->segment_time = 0;
1544       basesink->segment_accum = 0;
1545       ret = GST_STATE_CHANGE_ASYNC;
1546       break;
1547     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1548       GST_PREROLL_LOCK (basesink->sinkpad);
1549       /* no preroll needed */
1550       basesink->need_preroll = FALSE;
1551
1552       /* if we have EOS, we should empty the queue now as there will
1553        * be no more data received in the chain function.
1554        * FIXME, this could block the state change function too long when
1555        * we are pushing and syncing the buffers, better start a new
1556        * thread to do this. */
1557       if (basesink->eos) {
1558         gboolean do_eos = !basesink->eos_queued;
1559
1560         gst_base_sink_preroll_queue_empty (basesink, basesink->sinkpad);
1561
1562         /* need to post EOS message here if it was not in the preroll queue we
1563          * just emptied. */
1564         if (do_eos) {
1565           GST_DEBUG_OBJECT (basesink, "Now posting EOS");
1566           gst_element_post_message (GST_ELEMENT_CAST (basesink),
1567               gst_message_new_eos (GST_OBJECT_CAST (basesink)));
1568         }
1569       } else if (!basesink->have_preroll) {
1570         /* queue a commit_state */
1571         basesink->need_preroll = TRUE;
1572         GST_DEBUG_OBJECT (basesink,
1573             "PAUSED to PLAYING, !eos, !have_preroll, need preroll to FALSE");
1574         ret = GST_STATE_CHANGE_ASYNC;
1575         /* we know it's not waiting, no need to signal */
1576       } else {
1577         GST_DEBUG_OBJECT (basesink,
1578             "PAUSED to PLAYING, !eos, have_preroll, need preroll to FALSE");
1579         /* now let it play */
1580         GST_PREROLL_SIGNAL (basesink->sinkpad);
1581       }
1582       GST_PREROLL_UNLOCK (basesink->sinkpad);
1583       break;
1584     default:
1585       break;
1586   }
1587
1588   {
1589     GstStateChangeReturn bret;
1590
1591     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1592     if (bret == GST_STATE_CHANGE_FAILURE)
1593       goto activate_failed;
1594   }
1595
1596   switch (transition) {
1597     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1598     {
1599       GstBaseSinkClass *bclass;
1600
1601       bclass = GST_BASE_SINK_GET_CLASS (basesink);
1602
1603       GST_PREROLL_LOCK (basesink->sinkpad);
1604       GST_LOCK (basesink);
1605       /* unlock clock wait if any */
1606       if (basesink->clock_id) {
1607         gst_clock_id_unschedule (basesink->clock_id);
1608       }
1609       GST_UNLOCK (basesink);
1610
1611       /* unlock any subclasses */
1612       if (bclass->unlock)
1613         bclass->unlock (basesink);
1614
1615       /* if we don't have a preroll buffer and we have not received EOS,
1616        * we need to wait for a preroll */
1617       GST_DEBUG_OBJECT (basesink, "have_preroll: %d, EOS: %d",
1618           basesink->have_preroll, basesink->eos);
1619       if (!basesink->have_preroll && !basesink->eos
1620           && GST_STATE_PENDING (basesink) == GST_STATE_PAUSED) {
1621         GST_DEBUG_OBJECT (basesink, "PLAYING to PAUSED, need preroll to TRUE");
1622         basesink->need_preroll = TRUE;
1623         ret = GST_STATE_CHANGE_ASYNC;
1624       }
1625       GST_PREROLL_UNLOCK (basesink->sinkpad);
1626       break;
1627     }
1628     case GST_STATE_CHANGE_PAUSED_TO_READY:
1629       break;
1630     case GST_STATE_CHANGE_READY_TO_NULL:
1631       if (bclass->stop)
1632         if (!bclass->stop (basesink)) {
1633           GST_WARNING ("failed to stop");
1634         }
1635       break;
1636     default:
1637       break;
1638   }
1639
1640   return ret;
1641
1642   /* ERRORS */
1643 start_failed:
1644   {
1645     GST_DEBUG_OBJECT (basesink, "failed to start");
1646     return GST_STATE_CHANGE_FAILURE;
1647   }
1648 activate_failed:
1649   {
1650     GST_DEBUG_OBJECT (basesink,
1651         "element failed to change states -- activation problem?");
1652     return GST_STATE_CHANGE_FAILURE;
1653   }
1654 }