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