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