Merge remote-tracking branch 'origin/master' into 0.11
[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  *                    2005 Wim Taymans <wim@fluendo.com>
6  *
7  * gstqueue.c:
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, USA.
23  */
24
25 /**
26  * SECTION:element-queue
27  *
28  * Data is queued until one of the limits specified by the
29  * #GstQueue:max-size-buffers, #GstQueue:max-size-bytes and/or
30  * #GstQueue:max-size-time properties has been reached. Any attempt to push
31  * more buffers into the queue will block the pushing thread until more space
32  * becomes available.
33  *
34  * The queue will create a new thread on the source pad to decouple the
35  * processing on sink and source pad.
36  *
37  * You can query how many buffers are queued by reading the
38  * #GstQueue:current-level-buffers property. You can track changes
39  * by connecting to the notify::current-level-buffers signal (which
40  * like all signals will be emitted from the streaming thread). The same
41  * applies to the #GstQueue:current-level-time and
42  * #GstQueue:current-level-bytes properties.
43  *
44  * The default queue size limits are 200 buffers, 10MB of data, or
45  * one second worth of data, whichever is reached first.
46  *
47  * As said earlier, the queue blocks by default when one of the specified
48  * maximums (bytes, time, buffers) has been reached. You can set the
49  * #GstQueue:leaky property to specify that instead of blocking it should
50  * leak (drop) new or old buffers.
51  *
52  * The #GstQueue::underrun signal is emitted when the queue has less data than
53  * the specified minimum thresholds require (by default: when the queue is
54  * empty). The #GstQueue::overrun signal is emitted when the queue is filled
55  * up. Both signals are emitted from the context of the streaming thread.
56  */
57
58 #include "gst/gst_private.h"
59
60 #include <gst/gst.h>
61 #include "gstqueue.h"
62
63 #include "../../gst/gst-i18n-lib.h"
64 #include "../../gst/glib-compat-private.h"
65
66 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
67     GST_PAD_SINK,
68     GST_PAD_ALWAYS,
69     GST_STATIC_CAPS_ANY);
70
71 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
72     GST_PAD_SRC,
73     GST_PAD_ALWAYS,
74     GST_STATIC_CAPS_ANY);
75
76 GST_DEBUG_CATEGORY_STATIC (queue_debug);
77 #define GST_CAT_DEFAULT (queue_debug)
78 GST_DEBUG_CATEGORY_STATIC (queue_dataflow);
79
80 #define STATUS(queue, pad, msg) \
81   GST_CAT_LOG_OBJECT (queue_dataflow, queue, \
82                       "(%s:%s) " msg ": %u of %u-%u buffers, %u of %u-%u " \
83                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
84                       "-%" G_GUINT64_FORMAT " ns, %u items", \
85                       GST_DEBUG_PAD_NAME (pad), \
86                       queue->cur_level.buffers, \
87                       queue->min_threshold.buffers, \
88                       queue->max_size.buffers, \
89                       queue->cur_level.bytes, \
90                       queue->min_threshold.bytes, \
91                       queue->max_size.bytes, \
92                       queue->cur_level.time, \
93                       queue->min_threshold.time, \
94                       queue->max_size.time, \
95                       queue->queue.length)
96
97 /* Queue signals and args */
98 enum
99 {
100   SIGNAL_UNDERRUN,
101   SIGNAL_RUNNING,
102   SIGNAL_OVERRUN,
103   SIGNAL_PUSHING,
104   LAST_SIGNAL
105 };
106
107 enum
108 {
109   PROP_0,
110   /* FIXME: don't we have another way of doing this
111    * "Gstreamer format" (frame/byte/time) queries? */
112   PROP_CUR_LEVEL_BUFFERS,
113   PROP_CUR_LEVEL_BYTES,
114   PROP_CUR_LEVEL_TIME,
115   PROP_MAX_SIZE_BUFFERS,
116   PROP_MAX_SIZE_BYTES,
117   PROP_MAX_SIZE_TIME,
118   PROP_MIN_THRESHOLD_BUFFERS,
119   PROP_MIN_THRESHOLD_BYTES,
120   PROP_MIN_THRESHOLD_TIME,
121   PROP_LEAKY,
122   PROP_SILENT
123 };
124
125 /* default property values */
126 #define DEFAULT_MAX_SIZE_BUFFERS  200   /* 200 buffers */
127 #define DEFAULT_MAX_SIZE_BYTES    (10 * 1024 * 1024)    /* 10 MB       */
128 #define DEFAULT_MAX_SIZE_TIME     GST_SECOND    /* 1 second    */
129
130 #define GST_QUEUE_MUTEX_LOCK(q) G_STMT_START {                          \
131   g_mutex_lock (q->qlock);                                              \
132 } G_STMT_END
133
134 #define GST_QUEUE_MUTEX_LOCK_CHECK(q,label) G_STMT_START {              \
135   GST_QUEUE_MUTEX_LOCK (q);                                             \
136   if (q->srcresult != GST_FLOW_OK)                                      \
137     goto label;                                                         \
138 } G_STMT_END
139
140 #define GST_QUEUE_MUTEX_UNLOCK(q) G_STMT_START {                        \
141   g_mutex_unlock (q->qlock);                                            \
142 } G_STMT_END
143
144 #define GST_QUEUE_WAIT_DEL_CHECK(q, label) G_STMT_START {               \
145   STATUS (q, q->sinkpad, "wait for DEL");                               \
146   q->waiting_del = TRUE;                                                \
147   g_cond_wait (q->item_del, q->qlock);                                  \
148   q->waiting_del = FALSE;                                               \
149   if (q->srcresult != GST_FLOW_OK) {                                    \
150     STATUS (q, q->srcpad, "received DEL wakeup");                       \
151     goto label;                                                         \
152   }                                                                     \
153   STATUS (q, q->sinkpad, "received DEL");                               \
154 } G_STMT_END
155
156 #define GST_QUEUE_WAIT_ADD_CHECK(q, label) G_STMT_START {               \
157   STATUS (q, q->srcpad, "wait for ADD");                                \
158   q->waiting_add = TRUE;                                                \
159   g_cond_wait (q->item_add, q->qlock);                                  \
160   q->waiting_add = FALSE;                                               \
161   if (q->srcresult != GST_FLOW_OK) {                                    \
162     STATUS (q, q->srcpad, "received ADD wakeup");                       \
163     goto label;                                                         \
164   }                                                                     \
165   STATUS (q, q->srcpad, "received ADD");                                \
166 } G_STMT_END
167
168 #define GST_QUEUE_SIGNAL_DEL(q) G_STMT_START {                          \
169   if (q->waiting_del) {                                                 \
170     STATUS (q, q->srcpad, "signal DEL");                                \
171     g_cond_signal (q->item_del);                                        \
172   }                                                                     \
173 } G_STMT_END
174
175 #define GST_QUEUE_SIGNAL_ADD(q) G_STMT_START {                          \
176   if (q->waiting_add) {                                                 \
177     STATUS (q, q->sinkpad, "signal ADD");                               \
178     g_cond_signal (q->item_add);                                        \
179   }                                                                     \
180 } G_STMT_END
181
182 #define _do_init \
183     GST_DEBUG_CATEGORY_INIT (queue_debug, "queue", 0, "queue element"); \
184     GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue_dataflow", 0, \
185         "dataflow inside the queue element");
186 #define gst_queue_parent_class parent_class
187 G_DEFINE_TYPE_WITH_CODE (GstQueue, gst_queue, GST_TYPE_ELEMENT, _do_init);
188
189 static void gst_queue_finalize (GObject * object);
190
191 static void gst_queue_set_property (GObject * object,
192     guint prop_id, const GValue * value, GParamSpec * pspec);
193 static void gst_queue_get_property (GObject * object,
194     guint prop_id, GValue * value, GParamSpec * pspec);
195
196 static GstFlowReturn gst_queue_chain (GstPad * pad, GstObject * parent,
197     GstBuffer * buffer);
198 static GstFlowReturn gst_queue_push_one (GstQueue * queue);
199 static void gst_queue_loop (GstPad * pad);
200
201 static gboolean gst_queue_handle_sink_event (GstPad * pad, GstObject * parent,
202     GstEvent * event);
203 static gboolean gst_queue_handle_sink_query (GstPad * pad, GstObject * parent,
204     GstQuery * query);
205
206 static gboolean gst_queue_handle_src_event (GstPad * pad, GstObject * parent,
207     GstEvent * event);
208 static gboolean gst_queue_handle_src_query (GstPad * pad, GstObject * parent,
209     GstQuery * query);
210
211 static GstPadLinkReturn gst_queue_link_sink (GstPad * pad, GstPad * peer);
212 static GstPadLinkReturn gst_queue_link_src (GstPad * pad, GstPad * peer);
213 static void gst_queue_locked_flush (GstQueue * queue);
214
215 static gboolean gst_queue_src_activate_mode (GstPad * pad, GstObject * parent,
216     GstPadMode mode, gboolean active);
217 static gboolean gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent,
218     GstPadMode mode, gboolean active);
219
220 static gboolean gst_queue_is_empty (GstQueue * queue);
221 static gboolean gst_queue_is_filled (GstQueue * queue);
222
223 #define GST_TYPE_QUEUE_LEAKY (queue_leaky_get_type ())
224
225 static GType
226 queue_leaky_get_type (void)
227 {
228   static GType queue_leaky_type = 0;
229   static const GEnumValue queue_leaky[] = {
230     {GST_QUEUE_NO_LEAK, "Not Leaky", "no"},
231     {GST_QUEUE_LEAK_UPSTREAM, "Leaky on upstream (new buffers)", "upstream"},
232     {GST_QUEUE_LEAK_DOWNSTREAM, "Leaky on downstream (old buffers)",
233         "downstream"},
234     {0, NULL, NULL},
235   };
236
237   if (!queue_leaky_type) {
238     queue_leaky_type = g_enum_register_static ("GstQueueLeaky", queue_leaky);
239   }
240   return queue_leaky_type;
241 }
242
243 static guint gst_queue_signals[LAST_SIGNAL] = { 0 };
244
245 static void
246 gst_queue_class_init (GstQueueClass * klass)
247 {
248   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
249   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
250
251   gobject_class->set_property = gst_queue_set_property;
252   gobject_class->get_property = gst_queue_get_property;
253
254   /* signals */
255   /**
256    * GstQueue::underrun:
257    * @queue: the queue instance
258    *
259    * Reports that the buffer became empty (underrun).
260    * A buffer is empty if the total amount of data inside it (num-buffers, time,
261    * size) is lower than the boundary values which can be set through the
262    * GObject properties.
263    */
264   gst_queue_signals[SIGNAL_UNDERRUN] =
265       g_signal_new ("underrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
266       G_STRUCT_OFFSET (GstQueueClass, underrun), NULL, NULL,
267       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
268   /**
269    * GstQueue::running:
270    * @queue: the queue instance
271    *
272    * Reports that enough (min-threshold) data is in the queue. Use this signal
273    * together with the underrun signal to pause the pipeline on underrun and
274    * wait for the queue to fill-up before resume playback.
275    */
276   gst_queue_signals[SIGNAL_RUNNING] =
277       g_signal_new ("running", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
278       G_STRUCT_OFFSET (GstQueueClass, running), NULL, NULL,
279       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
280   /**
281    * GstQueue::overrun:
282    * @queue: the queue instance
283    *
284    * Reports that the buffer became full (overrun).
285    * A buffer is full if the total amount of data inside it (num-buffers, time,
286    * size) is higher than the boundary values which can be set through the
287    * GObject properties.
288    */
289   gst_queue_signals[SIGNAL_OVERRUN] =
290       g_signal_new ("overrun", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
291       G_STRUCT_OFFSET (GstQueueClass, overrun), NULL, NULL,
292       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
293   /**
294    * GstQueue::pushing:
295    * @queue: the queue instance
296    *
297    * Reports when the queue has enough data to start pushing data again on the
298    * source pad.
299    */
300   gst_queue_signals[SIGNAL_PUSHING] =
301       g_signal_new ("pushing", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_FIRST,
302       G_STRUCT_OFFSET (GstQueueClass, pushing), NULL, NULL,
303       g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
304
305   /* properties */
306   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
307       g_param_spec_uint ("current-level-bytes", "Current level (kB)",
308           "Current amount of data in the queue (bytes)",
309           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
310   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
311       g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
312           "Current number of buffers in the queue",
313           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
314   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
315       g_param_spec_uint64 ("current-level-time", "Current level (ns)",
316           "Current amount of data in the queue (in ns)",
317           0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
318
319   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
320       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
321           "Max. amount of data in the queue (bytes, 0=disable)",
322           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
323           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
324   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
325       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
326           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
327           DEFAULT_MAX_SIZE_BUFFERS,
328           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
329   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
330       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
331           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
332           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
333
334   g_object_class_install_property (gobject_class, PROP_MIN_THRESHOLD_BYTES,
335       g_param_spec_uint ("min-threshold-bytes", "Min. threshold (kB)",
336           "Min. amount of data in the queue to allow reading (bytes, 0=disable)",
337           0, G_MAXUINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338   g_object_class_install_property (gobject_class, PROP_MIN_THRESHOLD_BUFFERS,
339       g_param_spec_uint ("min-threshold-buffers", "Min. threshold (buffers)",
340           "Min. number of buffers in the queue to allow reading (0=disable)",
341           0, G_MAXUINT, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
342   g_object_class_install_property (gobject_class, PROP_MIN_THRESHOLD_TIME,
343       g_param_spec_uint64 ("min-threshold-time", "Min. threshold (ns)",
344           "Min. amount of data in the queue to allow reading (in ns, 0=disable)",
345           0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346
347   g_object_class_install_property (gobject_class, PROP_LEAKY,
348       g_param_spec_enum ("leaky", "Leaky",
349           "Where the queue leaks, if at all",
350           GST_TYPE_QUEUE_LEAKY, GST_QUEUE_NO_LEAK,
351           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352
353   /**
354    * GstQueue:silent
355    *
356    * Don't emit queue signals. Makes queues more lightweight if no signals are
357    * needed.
358    *
359    * Since: 0.10.31
360    */
361   g_object_class_install_property (gobject_class, PROP_SILENT,
362       g_param_spec_boolean ("silent", "Silent",
363           "Don't emit queue signals", FALSE,
364           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
365
366   gobject_class->finalize = gst_queue_finalize;
367
368   gst_element_class_set_details_simple (gstelement_class,
369       "Queue",
370       "Generic", "Simple data queue", "Erik Walthinsen <omega@cse.ogi.edu>");
371   gst_element_class_add_pad_template (gstelement_class,
372       gst_static_pad_template_get (&srctemplate));
373   gst_element_class_add_pad_template (gstelement_class,
374       gst_static_pad_template_get (&sinktemplate));
375
376   /* Registering debug symbols for function pointers */
377   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_src_activate_mode);
378   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_link_sink);
379   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_link_src);
380   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_sink_event);
381   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_sink_query);
382   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_src_event);
383   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_handle_src_query);
384   GST_DEBUG_REGISTER_FUNCPTR (gst_queue_chain);
385 }
386
387 static void
388 gst_queue_init (GstQueue * queue)
389 {
390   queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
391
392   gst_pad_set_chain_function (queue->sinkpad, gst_queue_chain);
393   gst_pad_set_activatemode_function (queue->sinkpad,
394       gst_queue_sink_activate_mode);
395   gst_pad_set_event_function (queue->sinkpad, gst_queue_handle_sink_event);
396   gst_pad_set_query_function (queue->sinkpad, gst_queue_handle_sink_query);
397   gst_pad_set_link_function (queue->sinkpad, gst_queue_link_sink);
398   GST_PAD_SET_PROXY_CAPS (queue->sinkpad);
399   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
400
401   queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
402
403   gst_pad_set_activatemode_function (queue->srcpad,
404       gst_queue_src_activate_mode);
405   gst_pad_set_link_function (queue->srcpad, gst_queue_link_src);
406   gst_pad_set_event_function (queue->srcpad, gst_queue_handle_src_event);
407   gst_pad_set_query_function (queue->srcpad, gst_queue_handle_src_query);
408   GST_PAD_SET_PROXY_CAPS (queue->srcpad);
409   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
410
411   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
412   queue->max_size.buffers = DEFAULT_MAX_SIZE_BUFFERS;
413   queue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
414   queue->max_size.time = DEFAULT_MAX_SIZE_TIME;
415   GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
416   GST_QUEUE_CLEAR_LEVEL (queue->orig_min_threshold);
417   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
418   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
419   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
420
421   queue->leaky = GST_QUEUE_NO_LEAK;
422   queue->srcresult = GST_FLOW_WRONG_STATE;
423
424   queue->qlock = g_mutex_new ();
425   queue->item_add = g_cond_new ();
426   queue->item_del = g_cond_new ();
427
428   g_queue_init (&queue->queue);
429
430   queue->sinktime = GST_CLOCK_TIME_NONE;
431   queue->srctime = GST_CLOCK_TIME_NONE;
432
433   queue->sink_tainted = TRUE;
434   queue->src_tainted = TRUE;
435
436   queue->newseg_applied_to_src = FALSE;
437
438   GST_DEBUG_OBJECT (queue,
439       "initialized queue's not_empty & not_full conditions");
440 }
441
442 /* called only once, as opposed to dispose */
443 static void
444 gst_queue_finalize (GObject * object)
445 {
446   GstMiniObject *data;
447   GstQueue *queue = GST_QUEUE (object);
448
449   GST_DEBUG_OBJECT (queue, "finalizing queue");
450
451   while ((data = g_queue_pop_head (&queue->queue)))
452     gst_mini_object_unref (data);
453
454   g_queue_clear (&queue->queue);
455   g_mutex_free (queue->qlock);
456   g_cond_free (queue->item_add);
457   g_cond_free (queue->item_del);
458
459   G_OBJECT_CLASS (parent_class)->finalize (object);
460 }
461
462 static GstPadLinkReturn
463 gst_queue_link_sink (GstPad * pad, GstPad * peer)
464 {
465   return GST_PAD_LINK_OK;
466 }
467
468 static GstPadLinkReturn
469 gst_queue_link_src (GstPad * pad, GstPad * peer)
470 {
471   GstPadLinkReturn result = GST_PAD_LINK_OK;
472   GstQueue *queue;
473
474   queue = GST_QUEUE (GST_PAD_PARENT (pad));
475
476   GST_DEBUG_OBJECT (queue, "queue linking source pad");
477
478   if (GST_PAD_LINKFUNC (peer)) {
479     result = GST_PAD_LINKFUNC (peer) (peer, pad);
480   }
481
482   if (GST_PAD_LINK_SUCCESSFUL (result)) {
483     GST_QUEUE_MUTEX_LOCK (queue);
484     if (queue->srcresult == GST_FLOW_OK) {
485       queue->push_newsegment = TRUE;
486       gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad);
487       GST_DEBUG_OBJECT (queue, "starting task as pad is linked");
488     } else {
489       GST_DEBUG_OBJECT (queue, "not starting task reason %s",
490           gst_flow_get_name (queue->srcresult));
491     }
492     GST_QUEUE_MUTEX_UNLOCK (queue);
493   }
494
495   return result;
496 }
497
498 /* calculate the diff between running time on the sink and src of the queue.
499  * This is the total amount of time in the queue. */
500 static void
501 update_time_level (GstQueue * queue)
502 {
503   gint64 sink_time, src_time;
504
505   if (queue->sink_tainted) {
506     GST_LOG_OBJECT (queue, "update sink time");
507     queue->sinktime =
508         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
509         queue->sink_segment.position);
510     queue->sink_tainted = FALSE;
511   }
512   sink_time = queue->sinktime;
513
514   if (queue->src_tainted) {
515     GST_LOG_OBJECT (queue, "update src time");
516     queue->srctime =
517         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
518         queue->src_segment.position);
519     queue->src_tainted = FALSE;
520   }
521   src_time = queue->srctime;
522
523   GST_LOG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
524       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
525
526   if (sink_time >= src_time)
527     queue->cur_level.time = sink_time - src_time;
528   else
529     queue->cur_level.time = 0;
530 }
531
532 /* take a SEGMENT event and apply the values to segment, updating the time
533  * level of queue. */
534 static void
535 apply_segment (GstQueue * queue, GstEvent * event, GstSegment * segment,
536     gboolean sink)
537 {
538   gst_event_copy_segment (event, segment);
539
540   /* now configure the values, we use these to track timestamps on the
541    * sinkpad. */
542   if (segment->format != GST_FORMAT_TIME) {
543     /* non-time format, pretent the current time segment is closed with a
544      * 0 start and unknown stop time. */
545     segment->format = GST_FORMAT_TIME;
546     segment->start = 0;
547     segment->stop = -1;
548     segment->time = 0;
549   }
550   if (sink)
551     queue->sink_tainted = TRUE;
552   else
553     queue->src_tainted = TRUE;
554
555   GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
556
557   /* segment can update the time level of the queue */
558   update_time_level (queue);
559 }
560
561 /* take a buffer and update segment, updating the time level of the queue. */
562 static void
563 apply_buffer (GstQueue * queue, GstBuffer * buffer, GstSegment * segment,
564     gboolean with_duration, gboolean sink)
565 {
566   GstClockTime duration, timestamp;
567
568   timestamp = GST_BUFFER_TIMESTAMP (buffer);
569   duration = GST_BUFFER_DURATION (buffer);
570
571   /* if no timestamp is set, assume it's continuous with the previous
572    * time */
573   if (timestamp == GST_CLOCK_TIME_NONE)
574     timestamp = segment->position;
575
576   /* add duration */
577   if (with_duration && duration != GST_CLOCK_TIME_NONE)
578     timestamp += duration;
579
580   GST_LOG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
581       GST_TIME_ARGS (timestamp));
582
583   segment->position = timestamp;
584   if (sink)
585     queue->sink_tainted = TRUE;
586   else
587     queue->src_tainted = TRUE;
588
589
590   /* calc diff with other end */
591   update_time_level (queue);
592 }
593
594 static void
595 gst_queue_locked_flush (GstQueue * queue)
596 {
597   GstMiniObject *data;
598
599   while ((data = g_queue_pop_head (&queue->queue))) {
600     /* Then lose another reference because we are supposed to destroy that
601        data when flushing */
602     gst_mini_object_unref (data);
603   }
604   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
605   queue->min_threshold.buffers = queue->orig_min_threshold.buffers;
606   queue->min_threshold.bytes = queue->orig_min_threshold.bytes;
607   queue->min_threshold.time = queue->orig_min_threshold.time;
608   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
609   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
610   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
611
612   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
613   queue->sink_tainted = queue->src_tainted = TRUE;
614
615   /* we deleted a lot of something */
616   GST_QUEUE_SIGNAL_DEL (queue);
617 }
618
619 /* enqueue an item an update the level stats, with QUEUE_LOCK */
620 static inline void
621 gst_queue_locked_enqueue_buffer (GstQueue * queue, gpointer item)
622 {
623   GstBuffer *buffer = GST_BUFFER_CAST (item);
624
625   /* add buffer to the statistics */
626   queue->cur_level.buffers++;
627   queue->cur_level.bytes += gst_buffer_get_size (buffer);
628   apply_buffer (queue, buffer, &queue->sink_segment, TRUE, TRUE);
629
630   g_queue_push_tail (&queue->queue, item);
631   GST_QUEUE_SIGNAL_ADD (queue);
632 }
633
634 static inline void
635 gst_queue_locked_enqueue_event (GstQueue * queue, gpointer item)
636 {
637   GstEvent *event = GST_EVENT_CAST (item);
638
639   switch (GST_EVENT_TYPE (event)) {
640     case GST_EVENT_EOS:
641       /* Zero the thresholds, this makes sure the queue is completely
642        * filled and we can read all data from the queue. */
643       GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
644       /* mark the queue as EOS. This prevents us from accepting more data. */
645       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from upstream");
646       queue->eos = TRUE;
647       break;
648     case GST_EVENT_SEGMENT:
649       apply_segment (queue, event, &queue->sink_segment, TRUE);
650       /* if the queue is empty, apply sink segment on the source */
651       if (queue->queue.length == 0) {
652         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "Apply segment on srcpad");
653         apply_segment (queue, event, &queue->src_segment, FALSE);
654         queue->newseg_applied_to_src = TRUE;
655       }
656       /* a new segment allows us to accept more buffers if we got EOS
657        * from downstream */
658       queue->unexpected = FALSE;
659       break;
660     default:
661       break;
662   }
663
664   g_queue_push_tail (&queue->queue, item);
665   GST_QUEUE_SIGNAL_ADD (queue);
666 }
667
668 /* dequeue an item from the queue and update level stats, with QUEUE_LOCK */
669 static GstMiniObject *
670 gst_queue_locked_dequeue (GstQueue * queue, gboolean * is_buffer)
671 {
672   GstMiniObject *item;
673
674   item = g_queue_pop_head (&queue->queue);
675   if (item == NULL)
676     goto no_item;
677
678   if (GST_IS_BUFFER (item)) {
679     GstBuffer *buffer = GST_BUFFER_CAST (item);
680
681     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
682         "retrieved buffer %p from queue", buffer);
683
684     queue->cur_level.buffers--;
685     queue->cur_level.bytes -= gst_buffer_get_size (buffer);
686     apply_buffer (queue, buffer, &queue->src_segment, TRUE, FALSE);
687
688     /* if the queue is empty now, update the other side */
689     if (queue->cur_level.buffers == 0)
690       queue->cur_level.time = 0;
691
692     *is_buffer = TRUE;
693   } else if (GST_IS_EVENT (item)) {
694     GstEvent *event = GST_EVENT_CAST (item);
695
696     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
697         "retrieved event %p from queue", event);
698
699     switch (GST_EVENT_TYPE (event)) {
700       case GST_EVENT_EOS:
701         /* queue is empty now that we dequeued the EOS */
702         GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
703         break;
704       case GST_EVENT_SEGMENT:
705         /* apply newsegment if it has not already been applied */
706         if (G_LIKELY (!queue->newseg_applied_to_src)) {
707           apply_segment (queue, event, &queue->src_segment, FALSE);
708         } else {
709           queue->newseg_applied_to_src = FALSE;
710         }
711         break;
712       default:
713         break;
714     }
715
716     *is_buffer = FALSE;
717   } else {
718     g_warning
719         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
720         item, GST_OBJECT_NAME (queue));
721     item = NULL;
722   }
723   GST_QUEUE_SIGNAL_DEL (queue);
724
725   return item;
726
727   /* ERRORS */
728 no_item:
729   {
730     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "the queue is empty");
731     return NULL;
732   }
733 }
734
735 static gboolean
736 gst_queue_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
737 {
738   GstQueue *queue;
739
740   queue = GST_QUEUE (parent);
741
742   switch (GST_EVENT_TYPE (event)) {
743     case GST_EVENT_FLUSH_START:
744     {
745       STATUS (queue, pad, "received flush start event");
746       /* forward event */
747       gst_pad_push_event (queue->srcpad, event);
748
749       /* now unblock the chain function */
750       GST_QUEUE_MUTEX_LOCK (queue);
751       queue->srcresult = GST_FLOW_WRONG_STATE;
752       /* unblock the loop and chain functions */
753       GST_QUEUE_SIGNAL_ADD (queue);
754       GST_QUEUE_SIGNAL_DEL (queue);
755       GST_QUEUE_MUTEX_UNLOCK (queue);
756
757       /* make sure it pauses, this should happen since we sent
758        * flush_start downstream. */
759       gst_pad_pause_task (queue->srcpad);
760       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
761       goto done;
762     }
763     case GST_EVENT_FLUSH_STOP:
764     {
765       STATUS (queue, pad, "received flush stop event");
766       /* forward event */
767       gst_pad_push_event (queue->srcpad, event);
768
769       GST_QUEUE_MUTEX_LOCK (queue);
770       gst_queue_locked_flush (queue);
771       queue->srcresult = GST_FLOW_OK;
772       queue->eos = FALSE;
773       queue->unexpected = FALSE;
774       if (gst_pad_is_linked (queue->srcpad)) {
775         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue_loop,
776             queue->srcpad);
777       } else {
778         GST_INFO_OBJECT (queue, "not re-starting task as pad is not linked");
779       }
780       GST_QUEUE_MUTEX_UNLOCK (queue);
781
782       STATUS (queue, pad, "after flush");
783       goto done;
784     }
785     default:
786       if (GST_EVENT_IS_SERIALIZED (event)) {
787         /* serialized events go in the queue */
788         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
789         /* refuse more events on EOS */
790         if (queue->eos)
791           goto out_eos;
792         gst_queue_locked_enqueue_event (queue, event);
793         GST_QUEUE_MUTEX_UNLOCK (queue);
794       } else {
795         /* non-serialized events are passed upstream. */
796         gst_pad_push_event (queue->srcpad, event);
797       }
798       break;
799   }
800 done:
801   return TRUE;
802
803   /* ERRORS */
804 out_flushing:
805   {
806     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
807         "refusing event, we are flushing");
808     GST_QUEUE_MUTEX_UNLOCK (queue);
809     gst_event_unref (event);
810     return FALSE;
811   }
812 out_eos:
813   {
814     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "refusing event, we are EOS");
815     GST_QUEUE_MUTEX_UNLOCK (queue);
816     gst_event_unref (event);
817     return FALSE;
818   }
819 }
820
821 static gboolean
822 gst_queue_handle_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
823 {
824   gboolean res;
825
826   switch (GST_QUERY_TYPE (query)) {
827     default:
828       res = gst_pad_query_default (pad, parent, query);
829       break;
830   }
831   return res;
832 }
833
834 static gboolean
835 gst_queue_is_empty (GstQueue * queue)
836 {
837   if (queue->queue.length == 0)
838     return TRUE;
839
840   /* It is possible that a max size is reached before all min thresholds are.
841    * Therefore, only consider it empty if it is not filled. */
842   return ((queue->min_threshold.buffers > 0 &&
843           queue->cur_level.buffers < queue->min_threshold.buffers) ||
844       (queue->min_threshold.bytes > 0 &&
845           queue->cur_level.bytes < queue->min_threshold.bytes) ||
846       (queue->min_threshold.time > 0 &&
847           queue->cur_level.time < queue->min_threshold.time)) &&
848       !gst_queue_is_filled (queue);
849 }
850
851 static gboolean
852 gst_queue_is_filled (GstQueue * queue)
853 {
854   return (((queue->max_size.buffers > 0 &&
855               queue->cur_level.buffers >= queue->max_size.buffers) ||
856           (queue->max_size.bytes > 0 &&
857               queue->cur_level.bytes >= queue->max_size.bytes) ||
858           (queue->max_size.time > 0 &&
859               queue->cur_level.time >= queue->max_size.time)));
860 }
861
862 static void
863 gst_queue_leak_downstream (GstQueue * queue)
864 {
865   /* for as long as the queue is filled, dequeue an item and discard it */
866   while (gst_queue_is_filled (queue)) {
867     GstMiniObject *leak;
868     gboolean is_buffer;
869
870     leak = gst_queue_locked_dequeue (queue, &is_buffer);
871     /* there is nothing to dequeue and the queue is still filled.. This should
872      * not happen */
873     g_assert (leak != NULL);
874
875     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
876         "queue is full, leaking item %p on downstream end", leak);
877     gst_mini_object_unref (leak);
878
879     /* last buffer needs to get a DISCONT flag */
880     queue->head_needs_discont = TRUE;
881   }
882 }
883
884 static GstFlowReturn
885 gst_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
886 {
887   GstQueue *queue;
888   GstClockTime duration, timestamp;
889
890   queue = GST_QUEUE_CAST (parent);
891
892   /* we have to lock the queue since we span threads */
893   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
894   /* when we received EOS, we refuse any more data */
895   if (queue->eos)
896     goto out_eos;
897   if (queue->unexpected)
898     goto out_unexpected;
899
900   timestamp = GST_BUFFER_TIMESTAMP (buffer);
901   duration = GST_BUFFER_DURATION (buffer);
902
903   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of size %"
904       G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
905       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
906       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
907
908   /* We make space available if we're "full" according to whatever
909    * the user defined as "full". Note that this only applies to buffers.
910    * We always handle events and they don't count in our statistics. */
911   while (gst_queue_is_filled (queue)) {
912     if (!queue->silent) {
913       GST_QUEUE_MUTEX_UNLOCK (queue);
914       g_signal_emit (queue, gst_queue_signals[SIGNAL_OVERRUN], 0);
915       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
916       /* we recheck, the signal could have changed the thresholds */
917       if (!gst_queue_is_filled (queue))
918         break;
919     }
920
921     /* how are we going to make space for this buffer? */
922     switch (queue->leaky) {
923       case GST_QUEUE_LEAK_UPSTREAM:
924         /* next buffer needs to get a DISCONT flag */
925         queue->tail_needs_discont = TRUE;
926         /* leak current buffer */
927         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
928             "queue is full, leaking buffer on upstream end");
929         /* now we can clean up and exit right away */
930         goto out_unref;
931       case GST_QUEUE_LEAK_DOWNSTREAM:
932         gst_queue_leak_downstream (queue);
933         break;
934       default:
935         g_warning ("Unknown leaky type, using default");
936         /* fall-through */
937       case GST_QUEUE_NO_LEAK:
938       {
939         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
940             "queue is full, waiting for free space");
941
942         /* don't leak. Instead, wait for space to be available */
943         do {
944           /* for as long as the queue is filled, wait till an item was deleted. */
945           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
946         } while (gst_queue_is_filled (queue));
947
948         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not full");
949
950         if (!queue->silent) {
951           GST_QUEUE_MUTEX_UNLOCK (queue);
952           g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
953           GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
954         }
955         break;
956       }
957     }
958   }
959
960   if (queue->tail_needs_discont) {
961     GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
962
963     if (subbuffer) {
964       buffer = subbuffer;
965       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
966     } else {
967       GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
968     }
969     queue->tail_needs_discont = FALSE;
970   }
971
972   /* put buffer in queue now */
973   gst_queue_locked_enqueue_buffer (queue, buffer);
974   GST_QUEUE_MUTEX_UNLOCK (queue);
975
976   return GST_FLOW_OK;
977
978   /* special conditions */
979 out_unref:
980   {
981     GST_QUEUE_MUTEX_UNLOCK (queue);
982
983     gst_buffer_unref (buffer);
984
985     return GST_FLOW_OK;
986   }
987 out_flushing:
988   {
989     GstFlowReturn ret = queue->srcresult;
990
991     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
992         "exit because task paused, reason: %s", gst_flow_get_name (ret));
993     GST_QUEUE_MUTEX_UNLOCK (queue);
994     gst_buffer_unref (buffer);
995
996     return ret;
997   }
998 out_eos:
999   {
1000     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1001     GST_QUEUE_MUTEX_UNLOCK (queue);
1002
1003     gst_buffer_unref (buffer);
1004
1005     return GST_FLOW_EOS;
1006   }
1007 out_unexpected:
1008   {
1009     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1010     GST_QUEUE_MUTEX_UNLOCK (queue);
1011
1012     gst_buffer_unref (buffer);
1013
1014     return GST_FLOW_EOS;
1015   }
1016 }
1017
1018 static void
1019 gst_queue_push_newsegment (GstQueue * queue)
1020 {
1021   GstEvent *event;
1022
1023   event = gst_event_new_segment (&queue->src_segment);
1024   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "pushing real newsegment event");
1025   gst_pad_push_event (queue->srcpad, event);
1026 }
1027
1028 /* dequeue an item from the queue an push it downstream. This functions returns
1029  * the result of the push. */
1030 static GstFlowReturn
1031 gst_queue_push_one (GstQueue * queue)
1032 {
1033   GstFlowReturn result = GST_FLOW_OK;
1034   GstMiniObject *data;
1035   gboolean is_buffer;
1036
1037   data = gst_queue_locked_dequeue (queue, &is_buffer);
1038   if (data == NULL)
1039     goto no_item;
1040
1041 next:
1042   if (is_buffer) {
1043     GstBuffer *buffer;
1044
1045     buffer = GST_BUFFER_CAST (data);
1046
1047     if (queue->head_needs_discont) {
1048       GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
1049
1050       if (subbuffer) {
1051         buffer = subbuffer;
1052         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1053       } else {
1054         GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
1055       }
1056       queue->head_needs_discont = FALSE;
1057     }
1058
1059     GST_QUEUE_MUTEX_UNLOCK (queue);
1060     if (queue->push_newsegment) {
1061       gst_queue_push_newsegment (queue);
1062     }
1063     result = gst_pad_push (queue->srcpad, buffer);
1064
1065     /* need to check for srcresult here as well */
1066     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1067
1068     if (result == GST_FLOW_EOS) {
1069       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
1070       /* stop pushing buffers, we dequeue all items until we see an item that we
1071        * can push again, which is EOS or SEGMENT. If there is nothing in the
1072        * queue we can push, we set a flag to make the sinkpad refuse more
1073        * buffers with an EOS return value. */
1074       while ((data = gst_queue_locked_dequeue (queue, &is_buffer))) {
1075         if (is_buffer) {
1076           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1077               "dropping EOS buffer %p", data);
1078           gst_buffer_unref (GST_BUFFER_CAST (data));
1079         } else {
1080           GstEvent *event = GST_EVENT_CAST (data);
1081           GstEventType type = GST_EVENT_TYPE (event);
1082
1083           if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
1084             /* we found a pushable item in the queue, push it out */
1085             GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1086                 "pushing pushable event %s after EOS",
1087                 GST_EVENT_TYPE_NAME (event));
1088             goto next;
1089           }
1090           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1091               "dropping EOS event %p", event);
1092           gst_event_unref (event);
1093         }
1094       }
1095       /* no more items in the queue. Set the unexpected flag so that upstream
1096        * make us refuse any more buffers on the sinkpad. Since we will still
1097        * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
1098        * task function does not shut down. */
1099       queue->unexpected = TRUE;
1100       result = GST_FLOW_OK;
1101     }
1102   } else {
1103     GstEvent *event = GST_EVENT_CAST (data);
1104     GstEventType type = GST_EVENT_TYPE (event);
1105
1106     GST_QUEUE_MUTEX_UNLOCK (queue);
1107
1108     if (queue->push_newsegment && type != GST_EVENT_SEGMENT) {
1109       gst_queue_push_newsegment (queue);
1110     }
1111     gst_pad_push_event (queue->srcpad, event);
1112
1113     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1114     /* if we're EOS, return EOS so that the task pauses. */
1115     if (type == GST_EVENT_EOS) {
1116       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1117           "pushed EOS event %p, return EOS", event);
1118       result = GST_FLOW_EOS;
1119     }
1120   }
1121   return result;
1122
1123   /* ERRORS */
1124 no_item:
1125   {
1126     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1127         "exit because we have no item in the queue");
1128     return GST_FLOW_ERROR;
1129   }
1130 out_flushing:
1131   {
1132     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
1133     return GST_FLOW_WRONG_STATE;
1134   }
1135 }
1136
1137 static void
1138 gst_queue_loop (GstPad * pad)
1139 {
1140   GstQueue *queue;
1141   GstFlowReturn ret;
1142
1143   queue = (GstQueue *) GST_PAD_PARENT (pad);
1144
1145   /* have to lock for thread-safety */
1146   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1147
1148   while (gst_queue_is_empty (queue)) {
1149     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is empty");
1150     if (!queue->silent) {
1151       GST_QUEUE_MUTEX_UNLOCK (queue);
1152       g_signal_emit (queue, gst_queue_signals[SIGNAL_UNDERRUN], 0);
1153       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1154     }
1155
1156     /* we recheck, the signal could have changed the thresholds */
1157     while (gst_queue_is_empty (queue)) {
1158       GST_QUEUE_WAIT_ADD_CHECK (queue, out_flushing);
1159     }
1160
1161     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not empty");
1162     if (!queue->silent) {
1163       GST_QUEUE_MUTEX_UNLOCK (queue);
1164       g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
1165       g_signal_emit (queue, gst_queue_signals[SIGNAL_PUSHING], 0);
1166       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1167     }
1168   }
1169
1170   ret = gst_queue_push_one (queue);
1171   queue->push_newsegment = FALSE;
1172   queue->srcresult = ret;
1173   if (ret != GST_FLOW_OK)
1174     goto out_flushing;
1175
1176   GST_QUEUE_MUTEX_UNLOCK (queue);
1177
1178   return;
1179
1180   /* ERRORS */
1181 out_flushing:
1182   {
1183     gboolean eos = queue->eos;
1184     GstFlowReturn ret = queue->srcresult;
1185
1186     gst_pad_pause_task (queue->srcpad);
1187     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1188         "pause task, reason:  %s", gst_flow_get_name (ret));
1189     GST_QUEUE_SIGNAL_DEL (queue);
1190     GST_QUEUE_MUTEX_UNLOCK (queue);
1191     /* let app know about us giving up if upstream is not expected to do so */
1192     /* EOS is already taken care of elsewhere */
1193     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1194       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
1195           (_("Internal data flow error.")),
1196           ("streaming task paused, reason %s (%d)",
1197               gst_flow_get_name (ret), ret));
1198       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
1199     }
1200     return;
1201   }
1202 }
1203
1204 static gboolean
1205 gst_queue_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1206 {
1207   gboolean res = TRUE;
1208   GstQueue *queue = GST_QUEUE (parent);
1209
1210 #ifndef GST_DISABLE_GST_DEBUG
1211   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%d)",
1212       event, GST_EVENT_TYPE (event));
1213 #endif
1214
1215   res = gst_pad_push_event (queue->sinkpad, event);
1216
1217   return res;
1218 }
1219
1220 static gboolean
1221 gst_queue_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1222 {
1223   GstQueue *queue = GST_QUEUE (parent);
1224   gboolean res;
1225
1226   res = gst_pad_peer_query (queue->sinkpad, query);
1227   if (!res)
1228     return FALSE;
1229
1230   switch (GST_QUERY_TYPE (query)) {
1231     case GST_QUERY_POSITION:
1232     {
1233       gint64 peer_pos;
1234       GstFormat format;
1235
1236       /* get peer position */
1237       gst_query_parse_position (query, &format, &peer_pos);
1238
1239       /* FIXME: this code assumes that there's no discont in the queue */
1240       switch (format) {
1241         case GST_FORMAT_BYTES:
1242           peer_pos -= queue->cur_level.bytes;
1243           break;
1244         case GST_FORMAT_TIME:
1245           peer_pos -= queue->cur_level.time;
1246           break;
1247         default:
1248           GST_DEBUG_OBJECT (queue, "Can't adjust query in %s format, don't "
1249               "know how to adjust value", gst_format_get_name (format));
1250           return TRUE;
1251       }
1252       /* set updated position */
1253       gst_query_set_position (query, format, peer_pos);
1254       break;
1255     }
1256     case GST_QUERY_LATENCY:
1257     {
1258       gboolean live;
1259       GstClockTime min, max;
1260
1261       gst_query_parse_latency (query, &live, &min, &max);
1262
1263       /* we can delay up to the limit of the queue in time. If we have no time
1264        * limit, the best thing we can do is to return an infinite delay. In
1265        * reality a better estimate would be the byte/buffer rate but that is not
1266        * possible right now. */
1267       if (queue->max_size.time > 0 && max != -1)
1268         max += queue->max_size.time;
1269       else
1270         max = -1;
1271
1272       /* adjust for min-threshold */
1273       if (queue->min_threshold.time > 0 && min != -1)
1274         min += queue->min_threshold.time;
1275
1276       gst_query_set_latency (query, live, min, max);
1277       break;
1278     }
1279     default:
1280       /* peer handled other queries */
1281       break;
1282   }
1283
1284   return TRUE;
1285 }
1286
1287 static gboolean
1288 gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1289     gboolean active)
1290 {
1291   gboolean result;
1292   GstQueue *queue;
1293
1294   queue = GST_QUEUE (parent);
1295
1296   switch (mode) {
1297     case GST_PAD_MODE_PUSH:
1298       if (active) {
1299         GST_QUEUE_MUTEX_LOCK (queue);
1300         queue->srcresult = GST_FLOW_OK;
1301         queue->eos = FALSE;
1302         queue->unexpected = FALSE;
1303         GST_QUEUE_MUTEX_UNLOCK (queue);
1304       } else {
1305         /* step 1, unblock chain function */
1306         GST_QUEUE_MUTEX_LOCK (queue);
1307         queue->srcresult = GST_FLOW_WRONG_STATE;
1308         gst_queue_locked_flush (queue);
1309         GST_QUEUE_MUTEX_UNLOCK (queue);
1310       }
1311       result = TRUE;
1312       break;
1313     default:
1314       result = FALSE;
1315       break;
1316   }
1317   return result;
1318 }
1319
1320 static gboolean
1321 gst_queue_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1322     gboolean active)
1323 {
1324   gboolean result;
1325   GstQueue *queue;
1326
1327   queue = GST_QUEUE (parent);
1328
1329   switch (mode) {
1330     case GST_PAD_MODE_PUSH:
1331       if (active) {
1332         GST_QUEUE_MUTEX_LOCK (queue);
1333         queue->srcresult = GST_FLOW_OK;
1334         queue->eos = FALSE;
1335         queue->unexpected = FALSE;
1336         /* we do not start the task yet if the pad is not connected */
1337         if (gst_pad_is_linked (pad))
1338           result =
1339               gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad);
1340         else {
1341           GST_INFO_OBJECT (queue, "not starting task as pad is not linked");
1342           result = TRUE;
1343         }
1344         GST_QUEUE_MUTEX_UNLOCK (queue);
1345       } else {
1346         /* step 1, unblock loop function */
1347         GST_QUEUE_MUTEX_LOCK (queue);
1348         queue->srcresult = GST_FLOW_WRONG_STATE;
1349         /* the item add signal will unblock */
1350         g_cond_signal (queue->item_add);
1351         GST_QUEUE_MUTEX_UNLOCK (queue);
1352
1353         /* step 2, make sure streaming finishes */
1354         result = gst_pad_stop_task (pad);
1355       }
1356       break;
1357     default:
1358       result = FALSE;
1359       break;
1360   }
1361   return result;
1362 }
1363
1364 static void
1365 queue_capacity_change (GstQueue * queue)
1366 {
1367   if (queue->leaky == GST_QUEUE_LEAK_DOWNSTREAM) {
1368     gst_queue_leak_downstream (queue);
1369   }
1370
1371   /* changing the capacity of the queue must wake up
1372    * the _chain function, it might have more room now
1373    * to store the buffer/event in the queue */
1374   GST_QUEUE_SIGNAL_DEL (queue);
1375 }
1376
1377 /* Changing the minimum required fill level must
1378  * wake up the _loop function as it might now
1379  * be able to preceed.
1380  */
1381 #define QUEUE_THRESHOLD_CHANGE(q)\
1382   GST_QUEUE_SIGNAL_ADD (q);
1383
1384 static void
1385 gst_queue_set_property (GObject * object,
1386     guint prop_id, const GValue * value, GParamSpec * pspec)
1387 {
1388   GstQueue *queue = GST_QUEUE (object);
1389
1390   /* someone could change levels here, and since this
1391    * affects the get/put funcs, we need to lock for safety. */
1392   GST_QUEUE_MUTEX_LOCK (queue);
1393
1394   switch (prop_id) {
1395     case PROP_MAX_SIZE_BYTES:
1396       queue->max_size.bytes = g_value_get_uint (value);
1397       queue_capacity_change (queue);
1398       break;
1399     case PROP_MAX_SIZE_BUFFERS:
1400       queue->max_size.buffers = g_value_get_uint (value);
1401       queue_capacity_change (queue);
1402       break;
1403     case PROP_MAX_SIZE_TIME:
1404       queue->max_size.time = g_value_get_uint64 (value);
1405       queue_capacity_change (queue);
1406       break;
1407     case PROP_MIN_THRESHOLD_BYTES:
1408       queue->min_threshold.bytes = g_value_get_uint (value);
1409       queue->orig_min_threshold.bytes = queue->min_threshold.bytes;
1410       QUEUE_THRESHOLD_CHANGE (queue);
1411       break;
1412     case PROP_MIN_THRESHOLD_BUFFERS:
1413       queue->min_threshold.buffers = g_value_get_uint (value);
1414       queue->orig_min_threshold.buffers = queue->min_threshold.buffers;
1415       QUEUE_THRESHOLD_CHANGE (queue);
1416       break;
1417     case PROP_MIN_THRESHOLD_TIME:
1418       queue->min_threshold.time = g_value_get_uint64 (value);
1419       queue->orig_min_threshold.time = queue->min_threshold.time;
1420       QUEUE_THRESHOLD_CHANGE (queue);
1421       break;
1422     case PROP_LEAKY:
1423       queue->leaky = g_value_get_enum (value);
1424       break;
1425     case PROP_SILENT:
1426       queue->silent = g_value_get_boolean (value);
1427       break;
1428     default:
1429       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1430       break;
1431   }
1432
1433   GST_QUEUE_MUTEX_UNLOCK (queue);
1434 }
1435
1436 static void
1437 gst_queue_get_property (GObject * object,
1438     guint prop_id, GValue * value, GParamSpec * pspec)
1439 {
1440   GstQueue *queue = GST_QUEUE (object);
1441
1442   GST_QUEUE_MUTEX_LOCK (queue);
1443
1444   switch (prop_id) {
1445     case PROP_CUR_LEVEL_BYTES:
1446       g_value_set_uint (value, queue->cur_level.bytes);
1447       break;
1448     case PROP_CUR_LEVEL_BUFFERS:
1449       g_value_set_uint (value, queue->cur_level.buffers);
1450       break;
1451     case PROP_CUR_LEVEL_TIME:
1452       g_value_set_uint64 (value, queue->cur_level.time);
1453       break;
1454     case PROP_MAX_SIZE_BYTES:
1455       g_value_set_uint (value, queue->max_size.bytes);
1456       break;
1457     case PROP_MAX_SIZE_BUFFERS:
1458       g_value_set_uint (value, queue->max_size.buffers);
1459       break;
1460     case PROP_MAX_SIZE_TIME:
1461       g_value_set_uint64 (value, queue->max_size.time);
1462       break;
1463     case PROP_MIN_THRESHOLD_BYTES:
1464       g_value_set_uint (value, queue->min_threshold.bytes);
1465       break;
1466     case PROP_MIN_THRESHOLD_BUFFERS:
1467       g_value_set_uint (value, queue->min_threshold.buffers);
1468       break;
1469     case PROP_MIN_THRESHOLD_TIME:
1470       g_value_set_uint64 (value, queue->min_threshold.time);
1471       break;
1472     case PROP_LEAKY:
1473       g_value_set_enum (value, queue->leaky);
1474       break;
1475     case PROP_SILENT:
1476       g_value_set_boolean (value, queue->silent);
1477       break;
1478     default:
1479       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1480       break;
1481   }
1482
1483   GST_QUEUE_MUTEX_UNLOCK (queue);
1484 }