gst/gstqueue.c: use gst_pad_proxy_getcaps()
[platform/upstream/gstreamer.git] / plugins / elements / gstqueue.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2003 Colin Walters <cwalters@gnome.org>
5  *
6  * gstqueue.c:
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24
25 #include "gst_private.h"
26
27 #include "gstqueue.h"
28 #include "gstscheduler.h"
29 #include "gstevent.h"
30 #include "gstinfo.h"
31
32 static GstElementDetails gst_queue_details = GST_ELEMENT_DETAILS (
33   "Queue",
34   "Generic",
35   "Simple data queue",
36   "Erik Walthinsen <omega@cse.ogi.edu>"
37 );
38
39
40 /* Queue signals and args */
41 enum {
42   SIGNAL_UNDERRUN,
43   SIGNAL_RUNNING,
44   SIGNAL_OVERRUN,
45   LAST_SIGNAL
46 };
47
48 enum {
49   ARG_0,
50   /* FIXME: don't we have another way of doing this
51    * "Gstreamer format" (frame/byte/time) queries? */
52   ARG_CUR_LEVEL_BUFFERS,
53   ARG_CUR_LEVEL_BYTES,
54   ARG_CUR_LEVEL_TIME,
55   ARG_MAX_SIZE_BUFFERS,
56   ARG_MAX_SIZE_BYTES,
57   ARG_MAX_SIZE_TIME,
58   ARG_MIN_TRESHOLD_BUFFERS,
59   ARG_MIN_TRESHOLD_BYTES,
60   ARG_MIN_TRESHOLD_TIME,
61   ARG_LEAKY,
62   ARG_MAY_DEADLOCK,
63   ARG_BLOCK_TIMEOUT
64   /* FILL ME */
65 };
66
67 typedef struct _GstQueueEventResponse {
68   GstEvent *event;
69   gboolean ret, handled;
70 } GstQueueEventResponse;
71
72 static void     gst_queue_base_init             (GstQueueClass *klass);
73 static void     gst_queue_class_init            (GstQueueClass *klass);
74 static void     gst_queue_init                  (GstQueue      *queue);
75 static void     gst_queue_dispose               (GObject       *object);
76
77 static void     gst_queue_set_property          (GObject       *object,
78                                                  guint          prop_id, 
79                                                  const GValue  *value,
80                                                  GParamSpec    *pspec);
81 static void     gst_queue_get_property          (GObject       *object,
82                                                  guint          prop_id, 
83                                                  GValue        *value,
84                                                  GParamSpec    *pspec);
85
86 static GstPadLinkReturn
87                 gst_queue_link                  (GstPad        *pad,
88                                                  const GstCaps *caps);
89 static void     gst_queue_chain                 (GstPad        *pad,
90                                                  GstData       *data);
91 static GstData *gst_queue_get                   (GstPad        *pad);
92         
93 static gboolean gst_queue_handle_src_event      (GstPad        *pad,
94                                                  GstEvent      *event);
95
96 static void     gst_queue_locked_flush          (GstQueue      *queue);
97
98 static GstElementStateReturn
99                 gst_queue_change_state          (GstElement    *element);
100 static gboolean gst_queue_release_locks         (GstElement    *element);
101
102   
103 #define GST_TYPE_QUEUE_LEAKY (queue_leaky_get_type ())
104
105 static GType
106 queue_leaky_get_type (void)
107 {
108   static GType queue_leaky_type = 0;
109   static GEnumValue queue_leaky[] = {
110     { GST_QUEUE_NO_LEAK,                "0", "Not Leaky" },
111     { GST_QUEUE_LEAK_UPSTREAM,          "1", "Leaky on Upstream" },
112     { GST_QUEUE_LEAK_DOWNSTREAM,        "2", "Leaky on Downstream" },
113     { 0, NULL, NULL },
114   };
115   if (!queue_leaky_type) {
116     queue_leaky_type = g_enum_register_static("GstQueueLeaky", queue_leaky);
117   }
118   return queue_leaky_type;
119 }
120
121 static GstElementClass *parent_class = NULL;
122 static guint gst_queue_signals[LAST_SIGNAL] = { 0 };
123
124 GType
125 gst_queue_get_type (void) 
126 {
127   static GType queue_type = 0;
128
129   if (!queue_type) {
130     static const GTypeInfo queue_info = {
131       sizeof (GstQueueClass),
132       (GBaseInitFunc) gst_queue_base_init,
133       NULL,
134       (GClassInitFunc) gst_queue_class_init,
135       NULL,
136       NULL,
137       sizeof (GstQueue),
138       4,
139       (GInstanceInitFunc) gst_queue_init,
140       NULL
141     };
142
143     queue_type = g_type_register_static (GST_TYPE_ELEMENT,
144                                          "GstQueue", &queue_info, 0);
145   }
146
147   return queue_type;
148 }
149
150 static void
151 gst_queue_base_init (GstQueueClass *klass)
152 {
153   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
154
155   gst_element_class_set_details (gstelement_class, &gst_queue_details);
156 }
157
158 static void
159 gst_queue_class_init (GstQueueClass *klass)
160 {
161   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
162   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
163
164   parent_class = g_type_class_peek_parent (klass);
165
166   /* signals */
167   gst_queue_signals[SIGNAL_UNDERRUN] =
168     g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
169                   G_STRUCT_OFFSET (GstQueueClass, underrun), NULL, NULL,
170                   g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
171   gst_queue_signals[SIGNAL_RUNNING] =
172     g_signal_new ("running", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
173                   G_STRUCT_OFFSET (GstQueueClass, running), NULL, NULL,
174                   g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
175   gst_queue_signals[SIGNAL_OVERRUN] =
176     g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
177                   G_STRUCT_OFFSET (GstQueueClass, overrun), NULL, NULL,
178                   g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
179
180   /* properties */
181   g_object_class_install_property (gobject_class, ARG_CUR_LEVEL_BYTES,
182     g_param_spec_uint ("current-level-bytes", "Current level (kB)",
183                        "Current amount of data in the queue (bytes)",
184                        0, G_MAXUINT, 0, G_PARAM_READABLE));
185   g_object_class_install_property (gobject_class, ARG_CUR_LEVEL_BUFFERS,
186     g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
187                        "Current number of buffers in the queue",
188                        0, G_MAXUINT, 0, G_PARAM_READABLE));
189   g_object_class_install_property (gobject_class, ARG_CUR_LEVEL_TIME,
190     g_param_spec_uint64 ("current-level-time", "Current level (ns)",
191                          "Current amount of data in the queue (in ns)",
192                          0, G_MAXUINT64, 0, G_PARAM_READABLE));
193
194   g_object_class_install_property (gobject_class, ARG_MAX_SIZE_BYTES,
195     g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
196                        "Max. amount of data in the queue (bytes, 0=disable)",
197                        0, G_MAXUINT, 0, G_PARAM_READWRITE));
198   g_object_class_install_property (gobject_class, ARG_MAX_SIZE_BUFFERS,
199     g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
200                        "Max. number of buffers in the queue (0=disable)",
201                        0, G_MAXUINT, 0, G_PARAM_READWRITE));
202   g_object_class_install_property (gobject_class, ARG_MAX_SIZE_TIME,
203     g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
204                          "Max. amount of data in the queue (in ns, 0=disable)",
205                          0, G_MAXUINT64, 0, G_PARAM_READWRITE));
206
207   g_object_class_install_property (gobject_class, ARG_MIN_TRESHOLD_BYTES,
208     g_param_spec_uint ("min-treshold-bytes", "Min. treshold (kB)",
209                        "Min. amount of data in the queue to allow reading (bytes, 0=disable)",
210                        0, G_MAXUINT, 0, G_PARAM_READWRITE));
211   g_object_class_install_property (gobject_class, ARG_MIN_TRESHOLD_BUFFERS,
212     g_param_spec_uint ("min-treshold-buffers", "Min. treshold (buffers)",
213                        "Min. number of buffers in the queue to allow reading (0=disable)",
214                        0, G_MAXUINT, 0, G_PARAM_READWRITE));
215   g_object_class_install_property (gobject_class, ARG_MIN_TRESHOLD_TIME,
216     g_param_spec_uint64 ("min-treshold-time", "Min. treshold (ns)",
217                          "Min. amount of data in the queue to allow reading (in ns, 0=disable)",
218                          0, G_MAXUINT64, 0, G_PARAM_READWRITE));
219
220   g_object_class_install_property (gobject_class, ARG_LEAKY,
221     g_param_spec_enum ("leaky", "Leaky",
222                        "Where the queue leaks, if at all",
223                        GST_TYPE_QUEUE_LEAKY, GST_QUEUE_NO_LEAK, G_PARAM_READWRITE));
224   g_object_class_install_property (gobject_class, ARG_MAY_DEADLOCK,
225     g_param_spec_boolean ("may_deadlock", "May Deadlock",
226                           "The queue may deadlock if it's full and not PLAYING",
227                           TRUE, G_PARAM_READWRITE));
228   g_object_class_install_property (gobject_class, ARG_BLOCK_TIMEOUT,
229     g_param_spec_uint64 ("block_timeout", "Timeout for Block", 
230                          "Nanoseconds until blocked queue times out and returns filler event. "
231                          "Value of -1 disables timeout",
232                          0, G_MAXUINT64, -1, G_PARAM_READWRITE));
233
234   /* set several parent class virtual functions */
235   gobject_class->dispose        = GST_DEBUG_FUNCPTR (gst_queue_dispose);
236   gobject_class->set_property   = GST_DEBUG_FUNCPTR (gst_queue_set_property);
237   gobject_class->get_property   = GST_DEBUG_FUNCPTR (gst_queue_get_property);
238
239   gstelement_class->change_state  = GST_DEBUG_FUNCPTR (gst_queue_change_state);
240   gstelement_class->release_locks = GST_DEBUG_FUNCPTR (gst_queue_release_locks);
241 }
242
243 static void
244 gst_queue_init (GstQueue *queue)
245 {
246   /* scheduling on this kind of element is, well, interesting */
247   GST_FLAG_SET (queue, GST_ELEMENT_DECOUPLED);
248   GST_FLAG_SET (queue, GST_ELEMENT_EVENT_AWARE);
249
250   queue->sinkpad = gst_pad_new ("sink", GST_PAD_SINK);
251   gst_pad_set_chain_function (queue->sinkpad, GST_DEBUG_FUNCPTR (gst_queue_chain));
252   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
253   gst_pad_set_link_function (queue->sinkpad, GST_DEBUG_FUNCPTR (gst_queue_link));
254   gst_pad_set_getcaps_function (queue->sinkpad, GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
255   gst_pad_set_active (queue->sinkpad, TRUE);
256
257   queue->srcpad = gst_pad_new ("src", GST_PAD_SRC);
258   gst_pad_set_get_function (queue->srcpad, GST_DEBUG_FUNCPTR (gst_queue_get));
259   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
260   gst_pad_set_link_function (queue->srcpad, GST_DEBUG_FUNCPTR (gst_queue_link));
261   gst_pad_set_getcaps_function (queue->srcpad, GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
262   gst_pad_set_event_function (queue->srcpad, GST_DEBUG_FUNCPTR (gst_queue_handle_src_event));
263   gst_pad_set_active (queue->srcpad, TRUE);
264
265   queue->cur_level.buffers      = 0; /* no content */
266   queue->cur_level.bytes        = 0; /* no content */
267   queue->cur_level.time         = 0; /* no content */
268   queue->max_size.buffers       = 100;          /* max. 100 buffers */
269   queue->max_size.bytes         = 1024 * 1024;  /* max. 1 MB */
270   queue->max_size.time          = GST_SECOND;   /* max. 1 sec. */
271   queue->min_treshold.buffers   = 0; /* no treshold */
272   queue->min_treshold.bytes     = 0; /* no treshold */
273   queue->min_treshold.time      = 0; /* no treshold */
274
275   queue->leaky = GST_QUEUE_NO_LEAK;
276   queue->may_deadlock = TRUE;
277   queue->block_timeout = GST_CLOCK_TIME_NONE;
278   queue->interrupt = FALSE;
279   queue->flush = FALSE;
280
281   queue->qlock = g_mutex_new ();
282   queue->item_add = g_cond_new ();
283   queue->item_del = g_cond_new ();
284   queue->event_done = g_cond_new ();
285   queue->events = g_queue_new ();
286   queue->queue = g_queue_new ();
287
288   GST_CAT_DEBUG_OBJECT (GST_CAT_THREAD, queue,
289                         "initialized queue's not_empty & not_full conditions");
290 }
291
292 static void
293 gst_queue_dispose (GObject *object)
294 {
295   GstQueue *queue = GST_QUEUE (object);
296
297   gst_element_set_state (GST_ELEMENT (queue), GST_STATE_NULL);
298
299   while (!g_queue_is_empty (queue->queue)) {
300     GstData *data = g_queue_pop_head (queue->queue);
301     gst_data_unref (data);
302   }
303   g_queue_free (queue->queue);
304   g_mutex_free (queue->qlock);
305   g_cond_free (queue->item_add);
306   g_cond_free (queue->item_del);
307   g_cond_free (queue->event_done);
308   while (!g_queue_is_empty (queue->events)) {
309     GstEvent *event = g_queue_pop_head (queue->events);
310     gst_event_unref (event);
311   }
312
313   if (G_OBJECT_CLASS (parent_class)->dispose)
314     G_OBJECT_CLASS (parent_class)->dispose (object);
315 }
316
317 static GstPad *
318 gst_queue_otherpad (GstPad *pad)
319 {
320   GstQueue *queue = GST_QUEUE (gst_pad_get_parent (pad));
321   GstPad *otherpad;
322
323   if (pad == queue->srcpad) 
324     otherpad = queue->sinkpad;
325   else
326     otherpad = queue->srcpad;
327
328   return otherpad;
329 }
330
331 static GstPadLinkReturn
332 gst_queue_link (GstPad  *pad, const GstCaps *caps)
333 {
334   return gst_pad_try_set_caps (gst_queue_otherpad (pad), caps);
335 }
336
337 static void
338 gst_queue_locked_flush (GstQueue *queue)
339 {
340   while (!g_queue_is_empty (queue->queue)) {
341     GstData *data = g_queue_pop_head (queue->queue);
342     gst_data_unref (data);
343   }
344   queue->timeval = NULL;
345   queue->cur_level.buffers = 0;
346   queue->cur_level.bytes = 0;
347   queue->cur_level.time = 0;
348
349   /* make sure any pending buffers to be added are flushed too */
350   queue->flush = TRUE;
351
352   /* we deleted something... */
353   g_cond_signal (queue->item_del);
354 }
355
356 static void
357 gst_queue_handle_pending_events (GstQueue *queue)
358 {
359   /* check for events to send upstream */
360   while (!g_queue_is_empty (queue->events)){
361     GstQueueEventResponse *er = g_queue_pop_head (queue->events);
362     GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue, "sending event upstream");
363     er->ret = gst_pad_event_default (queue->srcpad, er->event);
364     er->handled = TRUE;
365     g_cond_signal (queue->event_done);
366     GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue, "event sent");
367   }
368 }
369
370 #define STATUS(queue, msg) \
371   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, \
372                       "(%s:%s) " msg ": %u of %u-%u buffers, %u of %u-%u " \
373                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
374                       "-%" G_GUINT64_FORMAT " ns, %u elements", \
375                       GST_DEBUG_PAD_NAME (pad), \
376                       queue->cur_level.buffers, \
377                       queue->min_treshold.buffers, \
378                       queue->max_size.buffers, \
379                       queue->cur_level.bytes, \
380                       queue->min_treshold.bytes, \
381                       queue->max_size.bytes, \
382                       queue->cur_level.time, \
383                       queue->min_treshold.time, \
384                       queue->max_size.time, \
385                       queue->queue->length)
386
387 static void
388 gst_queue_chain (GstPad  *pad,
389                  GstData *data)
390 {
391   GstQueue *queue;
392
393   g_return_if_fail (pad != NULL);
394   g_return_if_fail (GST_IS_PAD (pad));
395   g_return_if_fail (data != NULL);
396
397   queue = GST_QUEUE (GST_OBJECT_PARENT (pad));
398   
399 restart:
400   /* we have to lock the queue since we span threads */
401   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, "locking t:%p", g_thread_self ());
402   g_mutex_lock (queue->qlock);
403   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, "locked t:%p", g_thread_self ());
404
405   gst_queue_handle_pending_events (queue);
406
407   /* assume don't need to flush this buffer when the queue is filled */
408   queue->flush = FALSE;
409   
410   if (GST_IS_EVENT (data)) {
411     switch (GST_EVENT_TYPE (data)) {
412       case GST_EVENT_FLUSH:
413         STATUS (queue, "received flush event");
414         gst_queue_locked_flush (queue);
415         STATUS (queue, "after flush");
416         break;
417       case GST_EVENT_EOS:
418         STATUS (queue, "received EOS");
419         break;
420       default:
421         /* we put the event in the queue, we don't have to act ourselves */
422         GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
423                             "adding event %p of type %d",
424                             data, GST_EVENT_TYPE (data));
425         break;
426     }
427   }
428   
429   if (GST_IS_BUFFER (data))
430     GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, 
431                         "adding buffer %p of size %d",
432                         data, GST_BUFFER_SIZE (data));
433
434   /* We make space available if we're "full" according to whatever
435    * the user defined as "full". Note that this only applies to buffers.
436    * We always handle events and they don't count in our statistics. */
437   if (GST_IS_BUFFER (data) &&
438       ((queue->max_size.buffers > 0 &&
439         queue->cur_level.buffers >= queue->max_size.buffers) ||
440        (queue->max_size.bytes > 0 &&
441         queue->cur_level.bytes >= queue->max_size.bytes) ||
442        (queue->max_size.time > 0 &&
443         queue->cur_level.time >= queue->max_size.time))) {
444     g_mutex_unlock (queue->qlock);
445     g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_OVERRUN], 0);
446     g_mutex_lock (queue->qlock);
447
448     /* how are we going to make space for this buffer? */
449     switch (queue->leaky) {
450       /* leak current buffer */
451       case GST_QUEUE_LEAK_UPSTREAM:
452         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
453                               "queue is full, leaking buffer on upstream end");
454         /* now we can clean up and exit right away */
455         g_mutex_unlock (queue->qlock);
456         goto out_unref;
457
458       /* leak first buffer in the queue */
459       case GST_QUEUE_LEAK_DOWNSTREAM: {
460         /* this is a bit hacky. We'll manually iterate the list
461          * and find the first buffer from the head on. We'll
462          * unref that and "fix up" the GQueue object... */
463         GList *item;
464         GstData *leak = NULL;
465
466         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
467                               "queue is full, leaking buffer on downstream end");
468
469         for (item = queue->queue->head; item != NULL; item = item->next) {
470           if (GST_IS_BUFFER (item->data)) {
471             leak = item->data;
472             break;
473           }
474         }
475
476         /* if we didn't find anything, it means we have no buffers
477          * in here. That cannot happen, since we had >= 1 bufs */
478         g_assert (leak);
479
480         /* Now remove it from the list, fixing up the GQueue
481          * CHECKME: is a queue->head the first or the last item? */
482         item = g_list_delete_link (queue->queue->head, item);
483         queue->queue->head = g_list_first (item);
484         queue->queue->tail = g_list_last (item);
485         queue->queue->length--;
486
487         /* and unref the data at the end. Twice, because we keep a ref
488          * to make things read-only. Also keep our list uptodate. */
489         queue->cur_level.bytes -= GST_BUFFER_SIZE (data);
490         queue->cur_level.buffers --;
491         if (GST_BUFFER_DURATION (data) != GST_CLOCK_TIME_NONE)
492           queue->cur_level.time -= GST_BUFFER_DURATION (data);
493
494         gst_data_unref (data);
495         gst_data_unref (data);
496         break;
497       }
498
499       default:
500         g_warning ("Unknown leaky type, using default");
501         /* fall-through */
502
503       /* don't leak. Instead, wait for space to be available */
504       case GST_QUEUE_NO_LEAK:
505         STATUS (queue, "pre-full wait");
506
507         while ((queue->max_size.buffers > 0 &&
508                 queue->cur_level.buffers >= queue->max_size.buffers) ||
509                (queue->max_size.bytes > 0 &&
510                 queue->cur_level.bytes >= queue->max_size.bytes) ||
511                (queue->max_size.time > 0 &&
512                 queue->cur_level.time >= queue->max_size.time)) {
513           /* if there's a pending state change for this queue
514            * or its manager, switch back to iterator so bottom
515            * half of state change executes */
516           if (queue->interrupt) {
517             GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue, "interrupted");
518             g_mutex_unlock (queue->qlock);
519             if (gst_scheduler_interrupt (gst_pad_get_scheduler (queue->sinkpad),
520                                          GST_ELEMENT (queue))) {
521               goto out_unref;
522             }
523             /* if we got here because we were unlocked after a
524              * flush, we don't need to add the buffer to the
525              * queue again */
526             if (queue->flush) {
527               GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
528                                     "not adding pending buffer after flush");
529               goto out_unref;
530             }
531             GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
532                                   "adding pending buffer after interrupt");
533             goto restart;
534           }
535
536           if (GST_STATE (queue) != GST_STATE_PLAYING) {
537             /* this means the other end is shut down. Try to
538              * signal to resolve the error */
539             if (!queue->may_deadlock) {
540               g_mutex_unlock (queue->qlock);
541               gst_data_unref (data);
542               gst_element_error (GST_ELEMENT (queue),
543                                  "deadlock found, source pad elements are shut down");
544               /* we don't go to out_unref here, since we want to
545                * unref the buffer *before* calling gst_element_error */
546               return;
547             } else {
548               GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
549                                       "%s: waiting for the app to restart "
550                                       "source pad elements",
551                                       GST_ELEMENT_NAME (queue));
552             }
553           }
554
555           /* OK, we've got a serious issue here. Imagine the situation
556            * where the puller (next element) is sending an event here,
557            * so it cannot pull events from the queue, and we cannot
558            * push data further because the queue is 'full' and therefore,
559            * we wait here (and do not handle events): deadlock! to solve
560            * that, we handle pending upstream events here, too. */
561           gst_queue_handle_pending_events (queue);
562
563           STATUS (queue, "waiting for item_del signal");
564           g_cond_wait (queue->item_del, queue->qlock);
565           STATUS (queue, "received item_del signal");
566         }
567
568         STATUS (queue, "post-full wait");
569         g_mutex_unlock (queue->qlock);
570         g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_RUNNING], 0);
571         g_mutex_lock (queue->qlock);
572         break;
573     }
574   }
575
576   /* put the buffer on the tail of the list. We keep a reference,
577    * so that the data is read-only while in here. There's a good
578    * reason to do so: we have a size and time counter, and any
579    * modification to the content could change any of the two. */
580   gst_data_ref (data);
581   g_queue_push_tail (queue->queue, data);
582
583   /* Note that we only add buffers (not events) to the statistics */
584   if (GST_IS_BUFFER (data)) {
585     queue->cur_level.buffers++;
586     queue->cur_level.bytes += GST_BUFFER_SIZE (data);
587     if (GST_BUFFER_DURATION (data) != GST_CLOCK_TIME_NONE)
588       queue->cur_level.time += GST_BUFFER_DURATION (data);
589   }
590
591   STATUS (queue, "+ level");
592
593   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, "signalling item_add");
594   g_cond_signal (queue->item_add);
595   g_mutex_unlock (queue->qlock);
596
597   return;
598
599 out_unref:
600   gst_data_unref (data);
601   return;
602 }
603
604 static GstData *
605 gst_queue_get (GstPad *pad)
606 {
607   GstQueue *queue;
608   GstData *data;
609
610   g_return_val_if_fail (pad != NULL, NULL);
611   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
612
613   queue = GST_QUEUE (gst_pad_get_parent (pad));
614
615 restart:
616   /* have to lock for thread-safety */
617   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
618                       "locking t:%p", g_thread_self ());
619   g_mutex_lock (queue->qlock);
620   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
621                       "locked t:%p", g_thread_self ());
622
623   if (queue->queue->length == 0 ||
624       (queue->min_treshold.buffers > 0 &&
625        queue->cur_level.buffers < queue->min_treshold.buffers) ||
626       (queue->min_treshold.bytes > 0 &&
627        queue->cur_level.bytes < queue->min_treshold.bytes) ||
628       (queue->min_treshold.time > 0 &&
629        queue->cur_level.time < queue->min_treshold.time)) {
630     g_mutex_unlock (queue->qlock);
631     g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_UNDERRUN], 0);
632     g_mutex_lock (queue->qlock);
633
634     STATUS (queue, "pre-empty wait");
635     while (queue->queue->length == 0 ||
636            (queue->min_treshold.buffers > 0 &&
637             queue->cur_level.buffers < queue->min_treshold.buffers) ||
638            (queue->min_treshold.bytes > 0 &&
639             queue->cur_level.bytes < queue->min_treshold.bytes) ||
640            (queue->min_treshold.time > 0 &&
641             queue->cur_level.time < queue->min_treshold.time)) {
642       /* if there's a pending state change for this queue or its
643        * manager, switch back to iterator so bottom half of state
644        * change executes. */
645       if (queue->interrupt) {
646         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue, "interrupted");
647         g_mutex_unlock (queue->qlock);
648         if (gst_scheduler_interrupt (gst_pad_get_scheduler (queue->srcpad),
649                                      GST_ELEMENT (queue)))
650           return GST_DATA (gst_event_new (GST_EVENT_INTERRUPT));
651         goto restart;
652       }
653       if (GST_STATE (queue) != GST_STATE_PLAYING) {
654         /* this means the other end is shut down */
655         if (!queue->may_deadlock) {
656           g_mutex_unlock (queue->qlock);
657           gst_element_error (GST_ELEMENT (queue),
658                              "deadlock found, sink pad elements are shut down");
659           goto restart;
660         } else {
661           GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
662                                   "%s: waiting for the app to restart "
663                                   "source pad elements",
664                                   GST_ELEMENT_NAME (queue));
665         }
666       }
667
668       STATUS (queue, "waiting for item_add");
669     
670       if (queue->block_timeout != GST_CLOCK_TIME_NONE) {
671         GTimeVal timeout;
672         g_get_current_time (&timeout);
673         g_time_val_add (&timeout, queue->block_timeout / 1000);
674         if (!g_cond_timed_wait (queue->item_add, queue->qlock, &timeout)){
675           g_mutex_unlock (queue->qlock);
676           GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
677                                   "Sending filler event");
678           return GST_DATA (gst_event_new_filler ());
679         }
680       } else {
681         g_cond_wait (queue->item_add, queue->qlock);
682       }
683       STATUS (queue, "got item_add signal");
684     }
685
686     STATUS (queue, "post-empty wait");
687     g_mutex_unlock (queue->qlock);
688     g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_RUNNING], 0);
689     g_mutex_lock (queue->qlock);
690   }
691
692   /* There's something in the list now, whatever it is */
693   data = g_queue_pop_head (queue->queue);
694   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
695                       "retrieved data %p from queue", data);
696
697   if (GST_IS_BUFFER (data)) {
698     /* Update statistics */
699     queue->cur_level.buffers--;
700     queue->cur_level.bytes -= GST_BUFFER_SIZE (data);
701     if (GST_BUFFER_DURATION (data) != GST_CLOCK_TIME_NONE)
702       queue->cur_level.time -= GST_BUFFER_DURATION (data);
703   }
704
705   /* Now that we're done, we can lose our own reference to
706    * the item, since we're no longer in danger. */
707   gst_data_unref (data);
708
709   STATUS (queue, "after _get()");
710
711   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, "signalling item_del");
712   g_cond_signal (queue->item_del);
713   g_mutex_unlock (queue->qlock);
714
715   /* FIXME: I suppose this needs to be locked, since the EOS
716    * bit affects the pipeline state. However, that bit is
717    * locked too so it'd cause a deadlock. */
718   if (GST_IS_EVENT (data)) {
719     GstEvent *event = GST_EVENT (data);
720     switch (GST_EVENT_TYPE (event)) {
721       case GST_EVENT_EOS:
722         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
723                               "queue \"%s\" eos",
724                               GST_ELEMENT_NAME (queue));
725         gst_element_set_eos (GST_ELEMENT (queue));
726         break;
727       default:
728         break;
729     }
730   }
731
732   return data;
733 }
734
735
736 static gboolean
737 gst_queue_handle_src_event (GstPad   *pad,
738                             GstEvent *event)
739 {
740   GstQueue *queue = GST_QUEUE (gst_pad_get_parent (pad));
741   gboolean res;
742
743   g_mutex_lock (queue->qlock);
744
745   if (gst_element_get_state (GST_ELEMENT (queue)) == GST_STATE_PLAYING) {
746     GstQueueEventResponse er;
747
748     /* push the event to the queue and wait for upstream consumption */
749     er.event = event;
750     er.handled = FALSE;
751     g_queue_push_tail (queue->events, &er);
752     GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
753                             "Preparing for loop for event handler");
754     /* see the chain function on why this is here - it prevents a deadlock */
755     g_cond_signal (queue->item_del);
756     while (!er.handled) {
757       GTimeVal timeout;
758       g_get_current_time (&timeout);
759       g_time_val_add (&timeout, 500 * 1000); /* half a second */
760       if (!g_cond_timed_wait (queue->event_done, queue->qlock, &timeout) &&
761           !er.handled) {
762         GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
763                                 "timeout in upstream event handling");
764         /* remove ourselves from the pending list. Since we're
765          * locked, others cannot reference this anymore. */
766         queue->queue->head = g_list_remove (queue->queue->head, &er);
767         queue->queue->head = g_list_first (queue->queue->head);
768         queue->queue->tail = g_list_last (queue->queue->head);
769         queue->queue->length--;
770         res = FALSE;
771         goto handled;
772       }
773     }
774     GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
775                             "Event handled");
776     res = er.ret;
777   } else {
778     res = gst_pad_event_default (pad, event); 
779
780     switch (GST_EVENT_TYPE (event)) {
781       case GST_EVENT_FLUSH:
782         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
783                               "FLUSH event, flushing queue\n");
784         gst_queue_locked_flush (queue);
785         break;
786       case GST_EVENT_SEEK:
787         if (GST_EVENT_SEEK_FLAGS (event) & GST_SEEK_FLAG_FLUSH) {
788           gst_queue_locked_flush (queue);
789         }
790       default:
791         break;
792     }
793   }
794 handled:
795   g_mutex_unlock (queue->qlock);
796
797   return res;
798 }
799
800 static gboolean
801 gst_queue_release_locks (GstElement *element)
802 {
803   GstQueue *queue;
804
805   queue = GST_QUEUE (element);
806
807   g_mutex_lock (queue->qlock);
808   queue->interrupt = TRUE;
809   g_cond_signal (queue->item_add);
810   g_cond_signal (queue->item_del);
811   g_mutex_unlock (queue->qlock);
812
813   return TRUE;
814 }
815
816 static GstElementStateReturn
817 gst_queue_change_state (GstElement *element)
818 {
819   GstQueue *queue;
820   GstElementStateReturn ret = GST_STATE_SUCCESS;
821
822   queue = GST_QUEUE (element);
823
824   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "starting state change");
825
826   /* lock the queue so another thread (not in sync with this thread's state)
827    * can't call this queue's _get (or whatever)
828    */
829   g_mutex_lock (queue->qlock);
830
831   switch (GST_STATE_TRANSITION (element)) {
832     case GST_STATE_NULL_TO_READY:
833       gst_queue_locked_flush (queue);
834       break;
835     case GST_STATE_PAUSED_TO_PLAYING:
836       if (!GST_PAD_IS_LINKED (queue->sinkpad)) {
837         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, queue,
838                               "queue %s is not linked",
839                               GST_ELEMENT_NAME (queue));
840         /* FIXME can this be? */
841         g_cond_signal (queue->item_add);
842
843         ret = GST_STATE_FAILURE;
844         goto error;
845       } else {
846         GstScheduler *src_sched, *sink_sched;
847             
848         src_sched = gst_pad_get_scheduler (GST_PAD (queue->srcpad));
849         sink_sched = gst_pad_get_scheduler (GST_PAD (queue->sinkpad));
850
851         if (src_sched == sink_sched) {
852           GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, queue,
853                                 "queue %s does not connect different schedulers", 
854                                 GST_ELEMENT_NAME (queue));
855
856           g_warning ("queue %s does not connect different schedulers",
857                      GST_ELEMENT_NAME (queue));
858
859           ret = GST_STATE_FAILURE;
860           goto error;
861         }
862       }
863       queue->interrupt = FALSE;
864       break;
865     case GST_STATE_PAUSED_TO_READY:
866       gst_queue_locked_flush (queue);
867       break;
868     default:
869       break;
870   }
871
872   if (GST_ELEMENT_CLASS (parent_class)->change_state)
873     ret = GST_ELEMENT_CLASS (parent_class)->change_state (element);
874
875   /* this is an ugly hack to make sure our pads are always active.
876    * Reason for this is that pad activation for the queue element
877    * depends on 2 schedulers (ugh) */
878   gst_pad_set_active (queue->sinkpad, TRUE);
879   gst_pad_set_active (queue->srcpad, TRUE);
880
881 error:
882   g_mutex_unlock (queue->qlock);
883
884   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "done with state change");
885
886   return ret;
887 }
888
889
890 static void
891 gst_queue_set_property (GObject      *object,
892                         guint         prop_id,
893                         const GValue *value,
894                         GParamSpec   *pspec)
895 {
896   GstQueue *queue = GST_QUEUE (object);
897
898   /* someone could change levels here, and since this
899    * affects the get/put funcs, we need to lock for safety. */
900   g_mutex_lock (queue->qlock);
901
902   switch (prop_id) {
903     case ARG_MAX_SIZE_BYTES:
904       queue->max_size.bytes = g_value_get_uint (value);
905       break;
906     case ARG_MAX_SIZE_BUFFERS:
907       queue->max_size.buffers = g_value_get_uint (value);
908       break;
909     case ARG_MAX_SIZE_TIME:
910       queue->max_size.time = g_value_get_uint64 (value);
911       break;
912     case ARG_MIN_TRESHOLD_BYTES:
913       queue->max_size.bytes = g_value_get_uint (value);
914       break;
915     case ARG_MIN_TRESHOLD_BUFFERS:
916       queue->max_size.buffers = g_value_get_uint (value);
917       break;
918     case ARG_MIN_TRESHOLD_TIME:
919       queue->max_size.time = g_value_get_uint64 (value);
920       break;
921     case ARG_LEAKY:
922       queue->leaky = g_value_get_enum (value);
923       break;
924     case ARG_MAY_DEADLOCK:
925       queue->may_deadlock = g_value_get_boolean (value);
926       break;
927     case ARG_BLOCK_TIMEOUT:
928       queue->block_timeout = g_value_get_uint64 (value);
929       break;
930     default:
931       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
932       break;
933   }
934
935   g_mutex_unlock (queue->qlock);
936 }
937
938 static void
939 gst_queue_get_property (GObject    *object,
940                         guint       prop_id,
941                         GValue     *value,
942                         GParamSpec *pspec)
943 {
944   GstQueue *queue = GST_QUEUE (object);
945
946   switch (prop_id) {
947     case ARG_CUR_LEVEL_BYTES:
948       g_value_set_uint (value, queue->cur_level.bytes);
949       break;
950     case ARG_CUR_LEVEL_BUFFERS:
951       g_value_set_uint (value, queue->cur_level.buffers);
952       break;
953     case ARG_CUR_LEVEL_TIME:
954       g_value_set_uint64 (value, queue->cur_level.time);
955       break;
956     case ARG_MAX_SIZE_BYTES:
957       g_value_set_uint (value, queue->max_size.bytes);
958       break;
959     case ARG_MAX_SIZE_BUFFERS:
960       g_value_set_uint (value, queue->max_size.buffers);
961       break;
962     case ARG_MAX_SIZE_TIME:
963       g_value_set_uint64 (value, queue->max_size.time);
964       break;
965     case ARG_MIN_TRESHOLD_BYTES:
966       g_value_set_uint (value, queue->min_treshold.bytes);
967       break;
968     case ARG_MIN_TRESHOLD_BUFFERS:
969       g_value_set_uint (value, queue->min_treshold.buffers);
970       break;
971     case ARG_MIN_TRESHOLD_TIME:
972       g_value_set_uint64 (value, queue->min_treshold.time);
973       break;
974     case ARG_LEAKY:
975       g_value_set_enum (value, queue->leaky);
976       break;
977     case ARG_MAY_DEADLOCK:
978       g_value_set_boolean (value, queue->may_deadlock);
979       break;
980     case ARG_BLOCK_TIMEOUT:
981       g_value_set_uint64 (value, queue->block_timeout);
982       break;
983     default:
984       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
985       break;
986   }
987 }