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