Fix a deadlock that happens if the next element sends an event and the previous eleme...
[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 (GST_PAD_PEER (queue->sinkpad), 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         break;
440       case GST_EVENT_EOS:
441         STATUS (queue, "received EOS");
442         break;
443       default:
444         /* we put the event in the queue, we don't have to act ourselves */
445         GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
446                             "adding event %p of type %d",
447                             data, GST_EVENT_TYPE (data));
448         break;
449     }
450   }
451   
452   if (GST_IS_BUFFER (data))
453     GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, 
454                         "adding buffer %p of size %d",
455                         data, GST_BUFFER_SIZE (data));
456
457   /* We make space available if we're "full" according to whatever
458    * the user defined as "full". Note that this only applies to buffers.
459    * We always handle events and they don't count in our statistics. */
460   if (GST_IS_BUFFER (data) &&
461       ((queue->max_size.buffers > 0 &&
462         queue->cur_level.buffers >= queue->max_size.buffers) ||
463        (queue->max_size.bytes > 0 &&
464         queue->cur_level.bytes >= queue->max_size.bytes) ||
465        (queue->max_size.time > 0 &&
466         queue->cur_level.time >= queue->max_size.time))) {
467     g_mutex_unlock (queue->qlock);
468     g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_OVERRUN], 0);
469     g_mutex_lock (queue->qlock);
470
471     /* how are we going to make space for this buffer? */
472     switch (queue->leaky) {
473       /* leak current buffer */
474       case GST_QUEUE_LEAK_UPSTREAM:
475         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
476                               "queue is full, leaking buffer on upstream end");
477         /* now we can clean up and exit right away */
478         g_mutex_unlock (queue->qlock);
479         goto out_unref;
480
481       /* leak first buffer in the queue */
482       case GST_QUEUE_LEAK_DOWNSTREAM: {
483         /* this is a bit hacky. We'll manually iterate the list
484          * and find the first buffer from the head on. We'll
485          * unref that and "fix up" the GQueue object... */
486         GList *item;
487         GstData *leak = NULL;
488
489         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
490                               "queue is full, leaking buffer on downstream end");
491
492         for (item = queue->queue->head; item != NULL; item = item->next) {
493           if (GST_IS_BUFFER (item->data)) {
494             leak = item->data;
495             break;
496           }
497         }
498
499         /* if we didn't find anything, it means we have no buffers
500          * in here. That cannot happen, since we had >= 1 bufs */
501         g_assert (leak);
502
503         /* Now remove it from the list, fixing up the GQueue
504          * CHECKME: is a queue->head the first or the last item? */
505         item = g_list_delete_link (queue->queue->head, item);
506         queue->queue->head = g_list_first (item);
507         queue->queue->tail = g_list_last (item);
508         queue->queue->length--;
509
510         /* and unref the data at the end. Twice, because we keep a ref
511          * to make things read-only. Also keep our list uptodate. */
512         queue->cur_level.bytes -= GST_BUFFER_SIZE (data);
513         queue->cur_level.buffers --;
514         if (GST_BUFFER_DURATION (data) != GST_CLOCK_TIME_NONE)
515           queue->cur_level.time -= GST_BUFFER_DURATION (data);
516
517         gst_data_unref (data);
518         gst_data_unref (data);
519         break;
520       }
521
522       default:
523         g_warning ("Unknown leaky type, using default");
524         /* fall-through */
525
526       /* don't leak. Instead, wait for space to be available */
527       case GST_QUEUE_NO_LEAK:
528         STATUS (queue, "pre-full wait");
529
530         while ((queue->max_size.buffers > 0 &&
531                 queue->cur_level.buffers >= queue->max_size.buffers) ||
532                (queue->max_size.bytes > 0 &&
533                 queue->cur_level.bytes >= queue->max_size.bytes) ||
534                (queue->max_size.time > 0 &&
535                 queue->cur_level.time >= queue->max_size.time)) {
536           /* if there's a pending state change for this queue
537            * or its manager, switch back to iterator so bottom
538            * half of state change executes */
539           if (queue->interrupt) {
540             GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue, "interrupted");
541             g_mutex_unlock (queue->qlock);
542             if (gst_scheduler_interrupt (gst_pad_get_scheduler (queue->sinkpad),
543                                          GST_ELEMENT (queue))) {
544               goto out_unref;
545             }
546             /* if we got here because we were unlocked after a
547              * flush, we don't need to add the buffer to the
548              * queue again */
549             if (queue->flush) {
550               GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
551                                     "not adding pending buffer after flush");
552               goto out_unref;
553             }
554             GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
555                                   "adding pending buffer after interrupt");
556             goto restart;
557           }
558
559           if (GST_STATE (queue) != GST_STATE_PLAYING) {
560             /* this means the other end is shut down. Try to
561              * signal to resolve the error */
562             if (!queue->may_deadlock) {
563               g_mutex_unlock (queue->qlock);
564               gst_data_unref (data);
565               gst_element_error (GST_ELEMENT (queue),
566                                  "deadlock found, source pad elements are shut down");
567               /* we don't go to out_unref here, since we want to
568                * unref the buffer *before* calling gst_element_error */
569               return;
570             } else {
571               GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
572                                       "%s: waiting for the app to restart "
573                                       "source pad elements",
574                                       GST_ELEMENT_NAME (queue));
575             }
576           }
577
578           /* OK, we've got a serious issue here. Imagine the situation
579            * where the puller (next element) is sending an event here,
580            * so it cannot pull events from the queue, and we cannot
581            * push data further because the queue is 'full' and therefore,
582            * we wait here (and do not handle events): deadlock! to solve
583            * that, we handle pending upstream events here, too. */
584           gst_queue_handle_pending_events (queue);
585
586           STATUS (queue, "waiting for item_del signal");
587           g_cond_wait (queue->item_del, queue->qlock);
588           STATUS (queue, "received item_del signal");
589         }
590
591         STATUS (queue, "post-full wait");
592         g_mutex_unlock (queue->qlock);
593         g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_RUNNING], 0);
594         g_mutex_lock (queue->qlock);
595         break;
596     }
597   }
598
599   /* put the buffer on the tail of the list. We keep a reference,
600    * so that the data is read-only while in here. There's a good
601    * reason to do so: we have a size and time counter, and any
602    * modification to the content could change any of the two. */
603   gst_data_ref (data);
604   g_queue_push_tail (queue->queue, data);
605
606   /* Note that we only add buffers (not events) to the statistics */
607   if (GST_IS_BUFFER (data)) {
608     queue->cur_level.buffers++;
609     queue->cur_level.bytes += GST_BUFFER_SIZE (data);
610     if (GST_BUFFER_DURATION (data) != GST_CLOCK_TIME_NONE)
611       queue->cur_level.time += GST_BUFFER_DURATION (data);
612   }
613
614   STATUS (queue, "+ level");
615
616   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, "signalling item_add");
617   g_cond_signal (queue->item_add);
618   g_mutex_unlock (queue->qlock);
619
620   return;
621
622 out_unref:
623   gst_data_unref (data);
624   return;
625 }
626
627 static GstData *
628 gst_queue_get (GstPad *pad)
629 {
630   GstQueue *queue;
631   GstData *data;
632
633   g_return_val_if_fail (pad != NULL, NULL);
634   g_return_val_if_fail (GST_IS_PAD (pad), NULL);
635
636   queue = GST_QUEUE (gst_pad_get_parent (pad));
637
638 restart:
639   /* have to lock for thread-safety */
640   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
641                       "locking t:%p", g_thread_self ());
642   g_mutex_lock (queue->qlock);
643   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
644                       "locked t:%p", g_thread_self ());
645
646   if (queue->queue->length == 0 ||
647       (queue->min_treshold.buffers > 0 &&
648        queue->cur_level.buffers < queue->min_treshold.buffers) ||
649       (queue->min_treshold.bytes > 0 &&
650        queue->cur_level.bytes < queue->min_treshold.bytes) ||
651       (queue->min_treshold.time > 0 &&
652        queue->cur_level.time < queue->min_treshold.time)) {
653     g_mutex_unlock (queue->qlock);
654     g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_UNDERRUN], 0);
655     g_mutex_lock (queue->qlock);
656
657     STATUS (queue, "pre-empty wait");
658     while (queue->queue->length == 0 ||
659            (queue->min_treshold.buffers > 0 &&
660             queue->cur_level.buffers < queue->min_treshold.buffers) ||
661            (queue->min_treshold.bytes > 0 &&
662             queue->cur_level.bytes < queue->min_treshold.bytes) ||
663            (queue->min_treshold.time > 0 &&
664             queue->cur_level.time < queue->min_treshold.time)) {
665       /* if there's a pending state change for this queue or its
666        * manager, switch back to iterator so bottom half of state
667        * change executes. */
668       if (queue->interrupt) {
669         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue, "interrupted");
670         g_mutex_unlock (queue->qlock);
671         if (gst_scheduler_interrupt (gst_pad_get_scheduler (queue->srcpad),
672                                      GST_ELEMENT (queue)))
673           return GST_DATA (gst_event_new (GST_EVENT_INTERRUPT));
674         goto restart;
675       }
676       if (GST_STATE (queue) != GST_STATE_PLAYING) {
677         /* this means the other end is shut down */
678         if (!queue->may_deadlock) {
679           g_mutex_unlock (queue->qlock);
680           gst_element_error (GST_ELEMENT (queue),
681                              "deadlock found, sink pad elements are shut down");
682           goto restart;
683         } else {
684           GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
685                                   "%s: waiting for the app to restart "
686                                   "source pad elements",
687                                   GST_ELEMENT_NAME (queue));
688         }
689       }
690
691       STATUS (queue, "waiting for item_add");
692     
693       if (queue->block_timeout != GST_CLOCK_TIME_NONE) {
694         GTimeVal timeout;
695         g_get_current_time (&timeout);
696         g_time_val_add (&timeout, queue->block_timeout / 1000);
697         if (!g_cond_timed_wait (queue->item_add, queue->qlock, &timeout)){
698           g_mutex_unlock (queue->qlock);
699           GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
700                                   "Sending filler event");
701           return GST_DATA (gst_event_new_filler ());
702         }
703       } else {
704         g_cond_wait (queue->item_add, queue->qlock);
705       }
706       STATUS (queue, "got item_add signal");
707     }
708
709     STATUS (queue, "post-empty wait");
710     g_mutex_unlock (queue->qlock);
711     g_signal_emit (G_OBJECT (queue), gst_queue_signals[SIGNAL_RUNNING], 0);
712     g_mutex_lock (queue->qlock);
713   }
714
715   /* There's something in the list now, whatever it is */
716   data = g_queue_pop_head (queue->queue);
717   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue,
718                       "retrieved data %p from queue", data);
719
720   if (GST_IS_BUFFER (data)) {
721     /* Update statistics */
722     queue->cur_level.buffers--;
723     queue->cur_level.bytes -= GST_BUFFER_SIZE (data);
724     if (GST_BUFFER_DURATION (data) != GST_CLOCK_TIME_NONE)
725       queue->cur_level.time -= GST_BUFFER_DURATION (data);
726   }
727
728   /* Now that we're done, we can lose our own reference to
729    * the item, since we're no longer in danger. */
730   gst_data_unref (data);
731
732   STATUS (queue, "after _get()");
733
734   GST_CAT_LOG_OBJECT (GST_CAT_DATAFLOW, queue, "signalling item_del");
735   g_cond_signal (queue->item_del);
736   g_mutex_unlock (queue->qlock);
737
738   /* FIXME: I suppose this needs to be locked, since the EOS
739    * bit affects the pipeline state. However, that bit is
740    * locked too so it'd cause a deadlock. */
741   if (GST_IS_EVENT (data)) {
742     GstEvent *event = GST_EVENT (data);
743     switch (GST_EVENT_TYPE (event)) {
744       case GST_EVENT_EOS:
745         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
746                               "queue \"%s\" eos",
747                               GST_ELEMENT_NAME (queue));
748         gst_element_set_eos (GST_ELEMENT (queue));
749         break;
750       default:
751         break;
752     }
753   }
754
755   return data;
756 }
757
758
759 static gboolean
760 gst_queue_handle_src_event (GstPad   *pad,
761                             GstEvent *event)
762 {
763   GstQueue *queue = GST_QUEUE (gst_pad_get_parent (pad));
764   gboolean res;
765
766   g_mutex_lock (queue->qlock);
767
768   if (gst_element_get_state (GST_ELEMENT (queue)) == GST_STATE_PLAYING) {
769     GstQueueEventResponse er;
770
771     /* push the event to the queue and wait for upstream consumption */
772     er.event = event;
773     er.handled = FALSE;
774     g_queue_push_tail (queue->events, &er);
775     GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
776                             "Preparing for loop for event handler");
777     /* see the chain function on why this is here - it prevents a deadlock */
778     g_cond_signal (queue->item_del);
779     while (!er.handled) {
780       g_cond_wait (queue->event_done, queue->qlock);
781     }
782     GST_CAT_WARNING_OBJECT (GST_CAT_DATAFLOW, queue,
783                             "Event handled");
784     res = er.ret;
785   } else {
786     res = gst_pad_event_default (pad, event); 
787
788     switch (GST_EVENT_TYPE (event)) {
789       case GST_EVENT_FLUSH:
790         GST_CAT_DEBUG_OBJECT (GST_CAT_DATAFLOW, queue,
791                               "FLUSH event, flushing queue\n");
792         gst_queue_locked_flush (queue);
793         break;
794       case GST_EVENT_SEEK:
795         if (GST_EVENT_SEEK_FLAGS (event) & GST_SEEK_FLAG_FLUSH) {
796           gst_queue_locked_flush (queue);
797         }
798       default:
799         break;
800     }
801   }
802
803   g_mutex_unlock (queue->qlock);
804
805   /* we have to claim success, but we don't really know */
806   return res;
807 }
808
809 static gboolean
810 gst_queue_release_locks (GstElement *element)
811 {
812   GstQueue *queue;
813
814   queue = GST_QUEUE (element);
815
816   g_mutex_lock (queue->qlock);
817   queue->interrupt = TRUE;
818   g_cond_signal (queue->item_add);
819   g_cond_signal (queue->item_del);
820   g_mutex_unlock (queue->qlock);
821
822   return TRUE;
823 }
824
825 static GstElementStateReturn
826 gst_queue_change_state (GstElement *element)
827 {
828   GstQueue *queue;
829   GstElementStateReturn ret = GST_STATE_SUCCESS;
830
831   queue = GST_QUEUE (element);
832
833   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "starting state change");
834
835   /* lock the queue so another thread (not in sync with this thread's state)
836    * can't call this queue's _get (or whatever)
837    */
838   g_mutex_lock (queue->qlock);
839
840   switch (GST_STATE_TRANSITION (element)) {
841     case GST_STATE_NULL_TO_READY:
842       gst_queue_locked_flush (queue);
843       break;
844     case GST_STATE_PAUSED_TO_PLAYING:
845       if (!GST_PAD_IS_LINKED (queue->sinkpad)) {
846         GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, queue,
847                               "queue %s is not linked",
848                               GST_ELEMENT_NAME (queue));
849         /* FIXME can this be? */
850         g_cond_signal (queue->item_add);
851
852         ret = GST_STATE_FAILURE;
853         goto error;
854       } else {
855         GstScheduler *src_sched, *sink_sched;
856             
857         src_sched = gst_pad_get_scheduler (GST_PAD (queue->srcpad));
858         sink_sched = gst_pad_get_scheduler (GST_PAD (queue->sinkpad));
859
860         if (src_sched == sink_sched) {
861           GST_CAT_DEBUG_OBJECT (GST_CAT_STATES, queue,
862                                 "queue %s does not connect different schedulers", 
863                                 GST_ELEMENT_NAME (queue));
864
865           g_warning ("queue %s does not connect different schedulers",
866                      GST_ELEMENT_NAME (queue));
867
868           ret = GST_STATE_FAILURE;
869           goto error;
870         }
871       }
872       queue->interrupt = FALSE;
873       break;
874     case GST_STATE_PAUSED_TO_READY:
875       gst_queue_locked_flush (queue);
876       break;
877     default:
878       break;
879   }
880
881   if (GST_ELEMENT_CLASS (parent_class)->change_state)
882     ret = GST_ELEMENT_CLASS (parent_class)->change_state (element);
883
884   /* this is an ugly hack to make sure our pads are always active.
885    * Reason for this is that pad activation for the queue element
886    * depends on 2 schedulers (ugh) */
887   gst_pad_set_active (queue->sinkpad, TRUE);
888   gst_pad_set_active (queue->srcpad, TRUE);
889
890 error:
891   g_mutex_unlock (queue->qlock);
892
893   GST_CAT_LOG_OBJECT (GST_CAT_STATES, element, "done with state change");
894
895   return ret;
896 }
897
898
899 static void
900 gst_queue_set_property (GObject      *object,
901                         guint         prop_id,
902                         const GValue *value,
903                         GParamSpec   *pspec)
904 {
905   GstQueue *queue = GST_QUEUE (object);
906
907   /* someone could change levels here, and since this
908    * affects the get/put funcs, we need to lock for safety. */
909   g_mutex_lock (queue->qlock);
910
911   switch (prop_id) {
912     case ARG_MAX_SIZE_BYTES:
913       queue->max_size.bytes = g_value_get_uint (value);
914       break;
915     case ARG_MAX_SIZE_BUFFERS:
916       queue->max_size.buffers = g_value_get_uint (value);
917       break;
918     case ARG_MAX_SIZE_TIME:
919       queue->max_size.time = g_value_get_uint64 (value);
920       break;
921     case ARG_MIN_TRESHOLD_BYTES:
922       queue->max_size.bytes = g_value_get_uint (value);
923       break;
924     case ARG_MIN_TRESHOLD_BUFFERS:
925       queue->max_size.buffers = g_value_get_uint (value);
926       break;
927     case ARG_MIN_TRESHOLD_TIME:
928       queue->max_size.time = g_value_get_uint64 (value);
929       break;
930     case ARG_LEAKY:
931       queue->leaky = g_value_get_enum (value);
932       break;
933     case ARG_MAY_DEADLOCK:
934       queue->may_deadlock = g_value_get_boolean (value);
935       break;
936     case ARG_BLOCK_TIMEOUT:
937       queue->block_timeout = g_value_get_uint64 (value);
938       break;
939     default:
940       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
941       break;
942   }
943
944   g_mutex_unlock (queue->qlock);
945 }
946
947 static void
948 gst_queue_get_property (GObject    *object,
949                         guint       prop_id,
950                         GValue     *value,
951                         GParamSpec *pspec)
952 {
953   GstQueue *queue = GST_QUEUE (object);
954
955   switch (prop_id) {
956     case ARG_CUR_LEVEL_BYTES:
957       g_value_set_uint (value, queue->cur_level.bytes);
958       break;
959     case ARG_CUR_LEVEL_BUFFERS:
960       g_value_set_uint (value, queue->cur_level.buffers);
961       break;
962     case ARG_CUR_LEVEL_TIME:
963       g_value_set_uint64 (value, queue->cur_level.time);
964       break;
965     case ARG_MAX_SIZE_BYTES:
966       g_value_set_uint (value, queue->max_size.bytes);
967       break;
968     case ARG_MAX_SIZE_BUFFERS:
969       g_value_set_uint (value, queue->max_size.buffers);
970       break;
971     case ARG_MAX_SIZE_TIME:
972       g_value_set_uint64 (value, queue->max_size.time);
973       break;
974     case ARG_MIN_TRESHOLD_BYTES:
975       g_value_set_uint (value, queue->min_treshold.bytes);
976       break;
977     case ARG_MIN_TRESHOLD_BUFFERS:
978       g_value_set_uint (value, queue->min_treshold.buffers);
979       break;
980     case ARG_MIN_TRESHOLD_TIME:
981       g_value_set_uint64 (value, queue->min_treshold.time);
982       break;
983     case ARG_LEAKY:
984       g_value_set_enum (value, queue->leaky);
985       break;
986     case ARG_MAY_DEADLOCK:
987       g_value_set_boolean (value, queue->may_deadlock);
988       break;
989     case ARG_BLOCK_TIMEOUT:
990       g_value_set_uint64 (value, queue->block_timeout);
991       break;
992     default:
993       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
994       break;
995   }
996 }