Merge branch '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_PAD_SET_PROXY_ALLOCATION (queue->sinkpad);
400   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
401
402   queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
403
404   gst_pad_set_activatemode_function (queue->srcpad,
405       gst_queue_src_activate_mode);
406   gst_pad_set_link_function (queue->srcpad, gst_queue_link_src);
407   gst_pad_set_event_function (queue->srcpad, gst_queue_handle_src_event);
408   gst_pad_set_query_function (queue->srcpad, gst_queue_handle_src_query);
409   GST_PAD_SET_PROXY_CAPS (queue->srcpad);
410   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
411
412   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
413   queue->max_size.buffers = DEFAULT_MAX_SIZE_BUFFERS;
414   queue->max_size.bytes = DEFAULT_MAX_SIZE_BYTES;
415   queue->max_size.time = DEFAULT_MAX_SIZE_TIME;
416   GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
417   GST_QUEUE_CLEAR_LEVEL (queue->orig_min_threshold);
418   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
419   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
420   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
421
422   queue->leaky = GST_QUEUE_NO_LEAK;
423   queue->srcresult = GST_FLOW_FLUSHING;
424
425   g_mutex_init (&queue->qlock);
426   g_cond_init (&queue->item_add);
427   g_cond_init (&queue->item_del);
428
429   g_queue_init (&queue->queue);
430
431   queue->sinktime = GST_CLOCK_TIME_NONE;
432   queue->srctime = GST_CLOCK_TIME_NONE;
433
434   queue->sink_tainted = TRUE;
435   queue->src_tainted = TRUE;
436
437   queue->newseg_applied_to_src = FALSE;
438
439   GST_DEBUG_OBJECT (queue,
440       "initialized queue's not_empty & not_full conditions");
441 }
442
443 /* called only once, as opposed to dispose */
444 static void
445 gst_queue_finalize (GObject * object)
446 {
447   GstMiniObject *data;
448   GstQueue *queue = GST_QUEUE (object);
449
450   GST_DEBUG_OBJECT (queue, "finalizing queue");
451
452   while ((data = g_queue_pop_head (&queue->queue)))
453     gst_mini_object_unref (data);
454
455   g_queue_clear (&queue->queue);
456   g_mutex_clear (&queue->qlock);
457   g_cond_clear (&queue->item_add);
458   g_cond_clear (&queue->item_del);
459
460   G_OBJECT_CLASS (parent_class)->finalize (object);
461 }
462
463 static GstPadLinkReturn
464 gst_queue_link_sink (GstPad * pad, GstPad * peer)
465 {
466   return GST_PAD_LINK_OK;
467 }
468
469 static GstPadLinkReturn
470 gst_queue_link_src (GstPad * pad, GstPad * peer)
471 {
472   GstPadLinkReturn result = GST_PAD_LINK_OK;
473   GstQueue *queue;
474
475   queue = GST_QUEUE (GST_PAD_PARENT (pad));
476
477   GST_DEBUG_OBJECT (queue, "queue linking source pad");
478
479   if (GST_PAD_LINKFUNC (peer)) {
480     result = GST_PAD_LINKFUNC (peer) (peer, pad);
481   }
482
483   if (GST_PAD_LINK_SUCCESSFUL (result)) {
484     GST_QUEUE_MUTEX_LOCK (queue);
485     if (queue->srcresult == GST_FLOW_OK) {
486       queue->push_newsegment = TRUE;
487       gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad);
488       GST_DEBUG_OBJECT (queue, "starting task as pad is linked");
489     } else {
490       GST_DEBUG_OBJECT (queue, "not starting task reason %s",
491           gst_flow_get_name (queue->srcresult));
492     }
493     GST_QUEUE_MUTEX_UNLOCK (queue);
494   }
495
496   return result;
497 }
498
499 /* calculate the diff between running time on the sink and src of the queue.
500  * This is the total amount of time in the queue. */
501 static void
502 update_time_level (GstQueue * queue)
503 {
504   gint64 sink_time, src_time;
505
506   if (queue->sink_tainted) {
507     GST_LOG_OBJECT (queue, "update sink time");
508     queue->sinktime =
509         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
510         queue->sink_segment.position);
511     queue->sink_tainted = FALSE;
512   }
513   sink_time = queue->sinktime;
514
515   if (queue->src_tainted) {
516     GST_LOG_OBJECT (queue, "update src time");
517     queue->srctime =
518         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
519         queue->src_segment.position);
520     queue->src_tainted = FALSE;
521   }
522   src_time = queue->srctime;
523
524   GST_LOG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
525       GST_TIME_ARGS (sink_time), GST_TIME_ARGS (src_time));
526
527   if (sink_time >= src_time)
528     queue->cur_level.time = sink_time - src_time;
529   else
530     queue->cur_level.time = 0;
531 }
532
533 /* take a SEGMENT event and apply the values to segment, updating the time
534  * level of queue. */
535 static void
536 apply_segment (GstQueue * queue, GstEvent * event, GstSegment * segment,
537     gboolean sink)
538 {
539   gst_event_copy_segment (event, segment);
540
541   /* now configure the values, we use these to track timestamps on the
542    * sinkpad. */
543   if (segment->format != GST_FORMAT_TIME) {
544     /* non-time format, pretent the current time segment is closed with a
545      * 0 start and unknown stop time. */
546     segment->format = GST_FORMAT_TIME;
547     segment->start = 0;
548     segment->stop = -1;
549     segment->time = 0;
550   }
551   if (sink)
552     queue->sink_tainted = TRUE;
553   else
554     queue->src_tainted = TRUE;
555
556   GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
557
558   /* segment can update the time level of the queue */
559   update_time_level (queue);
560 }
561
562 /* take a buffer and update segment, updating the time level of the queue. */
563 static void
564 apply_buffer (GstQueue * queue, GstBuffer * buffer, GstSegment * segment,
565     gboolean with_duration, gboolean sink)
566 {
567   GstClockTime duration, timestamp;
568
569   timestamp = GST_BUFFER_TIMESTAMP (buffer);
570   duration = GST_BUFFER_DURATION (buffer);
571
572   /* if no timestamp is set, assume it's continuous with the previous
573    * time */
574   if (timestamp == GST_CLOCK_TIME_NONE)
575     timestamp = segment->position;
576
577   /* add duration */
578   if (with_duration && duration != GST_CLOCK_TIME_NONE)
579     timestamp += duration;
580
581   GST_LOG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
582       GST_TIME_ARGS (timestamp));
583
584   segment->position = timestamp;
585   if (sink)
586     queue->sink_tainted = TRUE;
587   else
588     queue->src_tainted = TRUE;
589
590
591   /* calc diff with other end */
592   update_time_level (queue);
593 }
594
595 static void
596 gst_queue_locked_flush (GstQueue * queue)
597 {
598   GstMiniObject *data;
599
600   while ((data = g_queue_pop_head (&queue->queue))) {
601     /* Then lose another reference because we are supposed to destroy that
602        data when flushing */
603     gst_mini_object_unref (data);
604   }
605   GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
606   queue->min_threshold.buffers = queue->orig_min_threshold.buffers;
607   queue->min_threshold.bytes = queue->orig_min_threshold.bytes;
608   queue->min_threshold.time = queue->orig_min_threshold.time;
609   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
610   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
611   queue->head_needs_discont = queue->tail_needs_discont = FALSE;
612
613   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
614   queue->sink_tainted = queue->src_tainted = TRUE;
615
616   /* we deleted a lot of something */
617   GST_QUEUE_SIGNAL_DEL (queue);
618 }
619
620 /* enqueue an item an update the level stats, with QUEUE_LOCK */
621 static inline void
622 gst_queue_locked_enqueue_buffer (GstQueue * queue, gpointer item)
623 {
624   GstBuffer *buffer = GST_BUFFER_CAST (item);
625
626   /* add buffer to the statistics */
627   queue->cur_level.buffers++;
628   queue->cur_level.bytes += gst_buffer_get_size (buffer);
629   apply_buffer (queue, buffer, &queue->sink_segment, TRUE, TRUE);
630
631   g_queue_push_tail (&queue->queue, item);
632   GST_QUEUE_SIGNAL_ADD (queue);
633 }
634
635 static inline void
636 gst_queue_locked_enqueue_event (GstQueue * queue, gpointer item)
637 {
638   GstEvent *event = GST_EVENT_CAST (item);
639
640   switch (GST_EVENT_TYPE (event)) {
641     case GST_EVENT_EOS:
642       /* Zero the thresholds, this makes sure the queue is completely
643        * filled and we can read all data from the queue. */
644       GST_QUEUE_CLEAR_LEVEL (queue->min_threshold);
645       /* mark the queue as EOS. This prevents us from accepting more data. */
646       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from upstream");
647       queue->eos = TRUE;
648       break;
649     case GST_EVENT_SEGMENT:
650       apply_segment (queue, event, &queue->sink_segment, TRUE);
651       /* if the queue is empty, apply sink segment on the source */
652       if (queue->queue.length == 0) {
653         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "Apply segment on srcpad");
654         apply_segment (queue, event, &queue->src_segment, FALSE);
655         queue->newseg_applied_to_src = TRUE;
656       }
657       /* a new segment allows us to accept more buffers if we got EOS
658        * from downstream */
659       queue->unexpected = FALSE;
660       break;
661     default:
662       break;
663   }
664
665   g_queue_push_tail (&queue->queue, item);
666   GST_QUEUE_SIGNAL_ADD (queue);
667 }
668
669 /* dequeue an item from the queue and update level stats, with QUEUE_LOCK */
670 static GstMiniObject *
671 gst_queue_locked_dequeue (GstQueue * queue, gboolean * is_buffer)
672 {
673   GstMiniObject *item;
674
675   item = g_queue_pop_head (&queue->queue);
676   if (item == NULL)
677     goto no_item;
678
679   if (GST_IS_BUFFER (item)) {
680     GstBuffer *buffer = GST_BUFFER_CAST (item);
681
682     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
683         "retrieved buffer %p from queue", buffer);
684
685     queue->cur_level.buffers--;
686     queue->cur_level.bytes -= gst_buffer_get_size (buffer);
687     apply_buffer (queue, buffer, &queue->src_segment, TRUE, FALSE);
688
689     /* if the queue is empty now, update the other side */
690     if (queue->cur_level.buffers == 0)
691       queue->cur_level.time = 0;
692
693     *is_buffer = TRUE;
694   } else if (GST_IS_EVENT (item)) {
695     GstEvent *event = GST_EVENT_CAST (item);
696
697     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
698         "retrieved event %p from queue", event);
699
700     switch (GST_EVENT_TYPE (event)) {
701       case GST_EVENT_EOS:
702         /* queue is empty now that we dequeued the EOS */
703         GST_QUEUE_CLEAR_LEVEL (queue->cur_level);
704         break;
705       case GST_EVENT_SEGMENT:
706         /* apply newsegment if it has not already been applied */
707         if (G_LIKELY (!queue->newseg_applied_to_src)) {
708           apply_segment (queue, event, &queue->src_segment, FALSE);
709         } else {
710           queue->newseg_applied_to_src = FALSE;
711         }
712         break;
713       default:
714         break;
715     }
716
717     *is_buffer = FALSE;
718   } else {
719     g_warning
720         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
721         item, GST_OBJECT_NAME (queue));
722     item = NULL;
723   }
724   GST_QUEUE_SIGNAL_DEL (queue);
725
726   return item;
727
728   /* ERRORS */
729 no_item:
730   {
731     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "the queue is empty");
732     return NULL;
733   }
734 }
735
736 static gboolean
737 gst_queue_handle_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
738 {
739   GstQueue *queue;
740
741   queue = GST_QUEUE (parent);
742
743   switch (GST_EVENT_TYPE (event)) {
744     case GST_EVENT_FLUSH_START:
745     {
746       STATUS (queue, pad, "received flush start event");
747       /* forward event */
748       gst_pad_push_event (queue->srcpad, event);
749
750       /* now unblock the chain function */
751       GST_QUEUE_MUTEX_LOCK (queue);
752       queue->srcresult = GST_FLOW_FLUSHING;
753       /* unblock the loop and chain functions */
754       GST_QUEUE_SIGNAL_ADD (queue);
755       GST_QUEUE_SIGNAL_DEL (queue);
756       GST_QUEUE_MUTEX_UNLOCK (queue);
757
758       /* make sure it pauses, this should happen since we sent
759        * flush_start downstream. */
760       gst_pad_pause_task (queue->srcpad);
761       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
762       goto done;
763     }
764     case GST_EVENT_FLUSH_STOP:
765     {
766       STATUS (queue, pad, "received flush stop event");
767       /* forward event */
768       gst_pad_push_event (queue->srcpad, event);
769
770       GST_QUEUE_MUTEX_LOCK (queue);
771       gst_queue_locked_flush (queue);
772       queue->srcresult = GST_FLOW_OK;
773       queue->eos = FALSE;
774       queue->unexpected = FALSE;
775       if (gst_pad_is_linked (queue->srcpad)) {
776         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue_loop,
777             queue->srcpad);
778       } else {
779         GST_INFO_OBJECT (queue, "not re-starting task as pad is not linked");
780       }
781       GST_QUEUE_MUTEX_UNLOCK (queue);
782
783       STATUS (queue, pad, "after flush");
784       goto done;
785     }
786     default:
787       if (GST_EVENT_IS_SERIALIZED (event)) {
788         /* serialized events go in the queue */
789         GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
790         /* refuse more events on EOS */
791         if (queue->eos)
792           goto out_eos;
793         gst_queue_locked_enqueue_event (queue, event);
794         GST_QUEUE_MUTEX_UNLOCK (queue);
795       } else {
796         /* non-serialized events are passed upstream. */
797         gst_pad_push_event (queue->srcpad, event);
798       }
799       break;
800   }
801 done:
802   return TRUE;
803
804   /* ERRORS */
805 out_flushing:
806   {
807     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
808         "refusing event, we are flushing");
809     GST_QUEUE_MUTEX_UNLOCK (queue);
810     gst_event_unref (event);
811     return FALSE;
812   }
813 out_eos:
814   {
815     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "refusing event, we are EOS");
816     GST_QUEUE_MUTEX_UNLOCK (queue);
817     gst_event_unref (event);
818     return FALSE;
819   }
820 }
821
822 static gboolean
823 gst_queue_handle_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
824 {
825   gboolean res;
826
827   switch (GST_QUERY_TYPE (query)) {
828     default:
829       res = gst_pad_query_default (pad, parent, query);
830       break;
831   }
832   return res;
833 }
834
835 static gboolean
836 gst_queue_is_empty (GstQueue * queue)
837 {
838   if (queue->queue.length == 0)
839     return TRUE;
840
841   /* It is possible that a max size is reached before all min thresholds are.
842    * Therefore, only consider it empty if it is not filled. */
843   return ((queue->min_threshold.buffers > 0 &&
844           queue->cur_level.buffers < queue->min_threshold.buffers) ||
845       (queue->min_threshold.bytes > 0 &&
846           queue->cur_level.bytes < queue->min_threshold.bytes) ||
847       (queue->min_threshold.time > 0 &&
848           queue->cur_level.time < queue->min_threshold.time)) &&
849       !gst_queue_is_filled (queue);
850 }
851
852 static gboolean
853 gst_queue_is_filled (GstQueue * queue)
854 {
855   return (((queue->max_size.buffers > 0 &&
856               queue->cur_level.buffers >= queue->max_size.buffers) ||
857           (queue->max_size.bytes > 0 &&
858               queue->cur_level.bytes >= queue->max_size.bytes) ||
859           (queue->max_size.time > 0 &&
860               queue->cur_level.time >= queue->max_size.time)));
861 }
862
863 static void
864 gst_queue_leak_downstream (GstQueue * queue)
865 {
866   /* for as long as the queue is filled, dequeue an item and discard it */
867   while (gst_queue_is_filled (queue)) {
868     GstMiniObject *leak;
869     gboolean is_buffer;
870
871     leak = gst_queue_locked_dequeue (queue, &is_buffer);
872     /* there is nothing to dequeue and the queue is still filled.. This should
873      * not happen */
874     g_assert (leak != NULL);
875
876     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
877         "queue is full, leaking item %p on downstream end", leak);
878     gst_mini_object_unref (leak);
879
880     /* last buffer needs to get a DISCONT flag */
881     queue->head_needs_discont = TRUE;
882   }
883 }
884
885 static GstFlowReturn
886 gst_queue_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
887 {
888   GstQueue *queue;
889   GstClockTime duration, timestamp;
890
891   queue = GST_QUEUE_CAST (parent);
892
893   /* we have to lock the queue since we span threads */
894   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
895   /* when we received EOS, we refuse any more data */
896   if (queue->eos)
897     goto out_eos;
898   if (queue->unexpected)
899     goto out_unexpected;
900
901   timestamp = GST_BUFFER_TIMESTAMP (buffer);
902   duration = GST_BUFFER_DURATION (buffer);
903
904   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of size %"
905       G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
906       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
907       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
908
909   /* We make space available if we're "full" according to whatever
910    * the user defined as "full". Note that this only applies to buffers.
911    * We always handle events and they don't count in our statistics. */
912   while (gst_queue_is_filled (queue)) {
913     if (!queue->silent) {
914       GST_QUEUE_MUTEX_UNLOCK (queue);
915       g_signal_emit (queue, gst_queue_signals[SIGNAL_OVERRUN], 0);
916       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
917       /* we recheck, the signal could have changed the thresholds */
918       if (!gst_queue_is_filled (queue))
919         break;
920     }
921
922     /* how are we going to make space for this buffer? */
923     switch (queue->leaky) {
924       case GST_QUEUE_LEAK_UPSTREAM:
925         /* next buffer needs to get a DISCONT flag */
926         queue->tail_needs_discont = TRUE;
927         /* leak current buffer */
928         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
929             "queue is full, leaking buffer on upstream end");
930         /* now we can clean up and exit right away */
931         goto out_unref;
932       case GST_QUEUE_LEAK_DOWNSTREAM:
933         gst_queue_leak_downstream (queue);
934         break;
935       default:
936         g_warning ("Unknown leaky type, using default");
937         /* fall-through */
938       case GST_QUEUE_NO_LEAK:
939       {
940         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
941             "queue is full, waiting for free space");
942
943         /* don't leak. Instead, wait for space to be available */
944         do {
945           /* for as long as the queue is filled, wait till an item was deleted. */
946           GST_QUEUE_WAIT_DEL_CHECK (queue, out_flushing);
947         } while (gst_queue_is_filled (queue));
948
949         GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not full");
950
951         if (!queue->silent) {
952           GST_QUEUE_MUTEX_UNLOCK (queue);
953           g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
954           GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
955         }
956         break;
957       }
958     }
959   }
960
961   if (queue->tail_needs_discont) {
962     GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
963
964     if (subbuffer) {
965       buffer = subbuffer;
966       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
967     } else {
968       GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
969     }
970     queue->tail_needs_discont = FALSE;
971   }
972
973   /* put buffer in queue now */
974   gst_queue_locked_enqueue_buffer (queue, buffer);
975   GST_QUEUE_MUTEX_UNLOCK (queue);
976
977   return GST_FLOW_OK;
978
979   /* special conditions */
980 out_unref:
981   {
982     GST_QUEUE_MUTEX_UNLOCK (queue);
983
984     gst_buffer_unref (buffer);
985
986     return GST_FLOW_OK;
987   }
988 out_flushing:
989   {
990     GstFlowReturn ret = queue->srcresult;
991
992     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
993         "exit because task paused, reason: %s", gst_flow_get_name (ret));
994     GST_QUEUE_MUTEX_UNLOCK (queue);
995     gst_buffer_unref (buffer);
996
997     return ret;
998   }
999 out_eos:
1000   {
1001     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1002     GST_QUEUE_MUTEX_UNLOCK (queue);
1003
1004     gst_buffer_unref (buffer);
1005
1006     return GST_FLOW_EOS;
1007   }
1008 out_unexpected:
1009   {
1010     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
1011     GST_QUEUE_MUTEX_UNLOCK (queue);
1012
1013     gst_buffer_unref (buffer);
1014
1015     return GST_FLOW_EOS;
1016   }
1017 }
1018
1019 static void
1020 gst_queue_push_newsegment (GstQueue * queue)
1021 {
1022   GstEvent *event;
1023
1024   event = gst_event_new_segment (&queue->src_segment);
1025   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "pushing real newsegment event");
1026   gst_pad_push_event (queue->srcpad, event);
1027 }
1028
1029 /* dequeue an item from the queue an push it downstream. This functions returns
1030  * the result of the push. */
1031 static GstFlowReturn
1032 gst_queue_push_one (GstQueue * queue)
1033 {
1034   GstFlowReturn result = GST_FLOW_OK;
1035   GstMiniObject *data;
1036   gboolean is_buffer;
1037
1038   data = gst_queue_locked_dequeue (queue, &is_buffer);
1039   if (data == NULL)
1040     goto no_item;
1041
1042 next:
1043   if (is_buffer) {
1044     GstBuffer *buffer;
1045
1046     buffer = GST_BUFFER_CAST (data);
1047
1048     if (queue->head_needs_discont) {
1049       GstBuffer *subbuffer = gst_buffer_make_writable (buffer);
1050
1051       if (subbuffer) {
1052         buffer = subbuffer;
1053         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1054       } else {
1055         GST_DEBUG_OBJECT (queue, "Could not mark buffer as DISCONT");
1056       }
1057       queue->head_needs_discont = FALSE;
1058     }
1059
1060     GST_QUEUE_MUTEX_UNLOCK (queue);
1061     if (queue->push_newsegment) {
1062       gst_queue_push_newsegment (queue);
1063     }
1064     result = gst_pad_push (queue->srcpad, buffer);
1065
1066     /* need to check for srcresult here as well */
1067     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1068
1069     if (result == GST_FLOW_EOS) {
1070       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
1071       /* stop pushing buffers, we dequeue all items until we see an item that we
1072        * can push again, which is EOS or SEGMENT. If there is nothing in the
1073        * queue we can push, we set a flag to make the sinkpad refuse more
1074        * buffers with an EOS return value. */
1075       while ((data = gst_queue_locked_dequeue (queue, &is_buffer))) {
1076         if (is_buffer) {
1077           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1078               "dropping EOS buffer %p", data);
1079           gst_buffer_unref (GST_BUFFER_CAST (data));
1080         } else {
1081           GstEvent *event = GST_EVENT_CAST (data);
1082           GstEventType type = GST_EVENT_TYPE (event);
1083
1084           if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
1085             /* we found a pushable item in the queue, push it out */
1086             GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1087                 "pushing pushable event %s after EOS",
1088                 GST_EVENT_TYPE_NAME (event));
1089             goto next;
1090           }
1091           GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1092               "dropping EOS event %p", event);
1093           gst_event_unref (event);
1094         }
1095       }
1096       /* no more items in the queue. Set the unexpected flag so that upstream
1097        * make us refuse any more buffers on the sinkpad. Since we will still
1098        * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
1099        * task function does not shut down. */
1100       queue->unexpected = TRUE;
1101       result = GST_FLOW_OK;
1102     }
1103   } else {
1104     GstEvent *event = GST_EVENT_CAST (data);
1105     GstEventType type = GST_EVENT_TYPE (event);
1106
1107     GST_QUEUE_MUTEX_UNLOCK (queue);
1108
1109     if (queue->push_newsegment && type != GST_EVENT_SEGMENT) {
1110       gst_queue_push_newsegment (queue);
1111     }
1112     gst_pad_push_event (queue->srcpad, event);
1113
1114     GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1115     /* if we're EOS, return EOS so that the task pauses. */
1116     if (type == GST_EVENT_EOS) {
1117       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1118           "pushed EOS event %p, return EOS", event);
1119       result = GST_FLOW_EOS;
1120     }
1121   }
1122   return result;
1123
1124   /* ERRORS */
1125 no_item:
1126   {
1127     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1128         "exit because we have no item in the queue");
1129     return GST_FLOW_ERROR;
1130   }
1131 out_flushing:
1132   {
1133     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
1134     return GST_FLOW_FLUSHING;
1135   }
1136 }
1137
1138 static void
1139 gst_queue_loop (GstPad * pad)
1140 {
1141   GstQueue *queue;
1142   GstFlowReturn ret;
1143
1144   queue = (GstQueue *) GST_PAD_PARENT (pad);
1145
1146   /* have to lock for thread-safety */
1147   GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1148
1149   while (gst_queue_is_empty (queue)) {
1150     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is empty");
1151     if (!queue->silent) {
1152       GST_QUEUE_MUTEX_UNLOCK (queue);
1153       g_signal_emit (queue, gst_queue_signals[SIGNAL_UNDERRUN], 0);
1154       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1155     }
1156
1157     /* we recheck, the signal could have changed the thresholds */
1158     while (gst_queue_is_empty (queue)) {
1159       GST_QUEUE_WAIT_ADD_CHECK (queue, out_flushing);
1160     }
1161
1162     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is not empty");
1163     if (!queue->silent) {
1164       GST_QUEUE_MUTEX_UNLOCK (queue);
1165       g_signal_emit (queue, gst_queue_signals[SIGNAL_RUNNING], 0);
1166       g_signal_emit (queue, gst_queue_signals[SIGNAL_PUSHING], 0);
1167       GST_QUEUE_MUTEX_LOCK_CHECK (queue, out_flushing);
1168     }
1169   }
1170
1171   ret = gst_queue_push_one (queue);
1172   queue->push_newsegment = FALSE;
1173   queue->srcresult = ret;
1174   if (ret != GST_FLOW_OK)
1175     goto out_flushing;
1176
1177   GST_QUEUE_MUTEX_UNLOCK (queue);
1178
1179   return;
1180
1181   /* ERRORS */
1182 out_flushing:
1183   {
1184     gboolean eos = queue->eos;
1185     GstFlowReturn ret = queue->srcresult;
1186
1187     gst_pad_pause_task (queue->srcpad);
1188     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1189         "pause task, reason:  %s", gst_flow_get_name (ret));
1190     GST_QUEUE_SIGNAL_DEL (queue);
1191     GST_QUEUE_MUTEX_UNLOCK (queue);
1192     /* let app know about us giving up if upstream is not expected to do so */
1193     /* EOS is already taken care of elsewhere */
1194     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
1195       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
1196           (_("Internal data flow error.")),
1197           ("streaming task paused, reason %s (%d)",
1198               gst_flow_get_name (ret), ret));
1199       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
1200     }
1201     return;
1202   }
1203 }
1204
1205 static gboolean
1206 gst_queue_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1207 {
1208   gboolean res = TRUE;
1209   GstQueue *queue = GST_QUEUE (parent);
1210
1211 #ifndef GST_DISABLE_GST_DEBUG
1212   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%d)",
1213       event, GST_EVENT_TYPE (event));
1214 #endif
1215
1216   res = gst_pad_push_event (queue->sinkpad, event);
1217
1218   return res;
1219 }
1220
1221 static gboolean
1222 gst_queue_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1223 {
1224   GstQueue *queue = GST_QUEUE (parent);
1225   gboolean res;
1226
1227   res = gst_pad_query_default (pad, parent, query);
1228   if (!res)
1229     return FALSE;
1230
1231   switch (GST_QUERY_TYPE (query)) {
1232     case GST_QUERY_POSITION:
1233     {
1234       gint64 peer_pos;
1235       GstFormat format;
1236
1237       /* get peer position */
1238       gst_query_parse_position (query, &format, &peer_pos);
1239
1240       /* FIXME: this code assumes that there's no discont in the queue */
1241       switch (format) {
1242         case GST_FORMAT_BYTES:
1243           peer_pos -= queue->cur_level.bytes;
1244           break;
1245         case GST_FORMAT_TIME:
1246           peer_pos -= queue->cur_level.time;
1247           break;
1248         default:
1249           GST_DEBUG_OBJECT (queue, "Can't adjust query in %s format, don't "
1250               "know how to adjust value", gst_format_get_name (format));
1251           return TRUE;
1252       }
1253       /* set updated position */
1254       gst_query_set_position (query, format, peer_pos);
1255       break;
1256     }
1257     case GST_QUERY_LATENCY:
1258     {
1259       gboolean live;
1260       GstClockTime min, max;
1261
1262       gst_query_parse_latency (query, &live, &min, &max);
1263
1264       /* we can delay up to the limit of the queue in time. If we have no time
1265        * limit, the best thing we can do is to return an infinite delay. In
1266        * reality a better estimate would be the byte/buffer rate but that is not
1267        * possible right now. */
1268       if (queue->max_size.time > 0 && max != -1)
1269         max += queue->max_size.time;
1270       else
1271         max = -1;
1272
1273       /* adjust for min-threshold */
1274       if (queue->min_threshold.time > 0 && min != -1)
1275         min += queue->min_threshold.time;
1276
1277       gst_query_set_latency (query, live, min, max);
1278       break;
1279     }
1280     default:
1281       /* peer handled other queries */
1282       break;
1283   }
1284
1285   return TRUE;
1286 }
1287
1288 static gboolean
1289 gst_queue_sink_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1290     gboolean active)
1291 {
1292   gboolean result;
1293   GstQueue *queue;
1294
1295   queue = GST_QUEUE (parent);
1296
1297   switch (mode) {
1298     case GST_PAD_MODE_PUSH:
1299       if (active) {
1300         GST_QUEUE_MUTEX_LOCK (queue);
1301         queue->srcresult = GST_FLOW_OK;
1302         queue->eos = FALSE;
1303         queue->unexpected = FALSE;
1304         GST_QUEUE_MUTEX_UNLOCK (queue);
1305       } else {
1306         /* step 1, unblock chain function */
1307         GST_QUEUE_MUTEX_LOCK (queue);
1308         queue->srcresult = GST_FLOW_FLUSHING;
1309         gst_queue_locked_flush (queue);
1310         GST_QUEUE_MUTEX_UNLOCK (queue);
1311       }
1312       result = TRUE;
1313       break;
1314     default:
1315       result = FALSE;
1316       break;
1317   }
1318   return result;
1319 }
1320
1321 static gboolean
1322 gst_queue_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
1323     gboolean active)
1324 {
1325   gboolean result;
1326   GstQueue *queue;
1327
1328   queue = GST_QUEUE (parent);
1329
1330   switch (mode) {
1331     case GST_PAD_MODE_PUSH:
1332       if (active) {
1333         GST_QUEUE_MUTEX_LOCK (queue);
1334         queue->srcresult = GST_FLOW_OK;
1335         queue->eos = FALSE;
1336         queue->unexpected = FALSE;
1337         /* we do not start the task yet if the pad is not connected */
1338         if (gst_pad_is_linked (pad))
1339           result =
1340               gst_pad_start_task (pad, (GstTaskFunction) gst_queue_loop, pad);
1341         else {
1342           GST_INFO_OBJECT (queue, "not starting task as pad is not linked");
1343           result = TRUE;
1344         }
1345         GST_QUEUE_MUTEX_UNLOCK (queue);
1346       } else {
1347         /* step 1, unblock loop function */
1348         GST_QUEUE_MUTEX_LOCK (queue);
1349         queue->srcresult = GST_FLOW_FLUSHING;
1350         /* the item add signal will unblock */
1351         g_cond_signal (&queue->item_add);
1352         GST_QUEUE_MUTEX_UNLOCK (queue);
1353
1354         /* step 2, make sure streaming finishes */
1355         result = gst_pad_stop_task (pad);
1356       }
1357       break;
1358     default:
1359       result = FALSE;
1360       break;
1361   }
1362   return result;
1363 }
1364
1365 static void
1366 queue_capacity_change (GstQueue * queue)
1367 {
1368   if (queue->leaky == GST_QUEUE_LEAK_DOWNSTREAM) {
1369     gst_queue_leak_downstream (queue);
1370   }
1371
1372   /* changing the capacity of the queue must wake up
1373    * the _chain function, it might have more room now
1374    * to store the buffer/event in the queue */
1375   GST_QUEUE_SIGNAL_DEL (queue);
1376 }
1377
1378 /* Changing the minimum required fill level must
1379  * wake up the _loop function as it might now
1380  * be able to preceed.
1381  */
1382 #define QUEUE_THRESHOLD_CHANGE(q)\
1383   GST_QUEUE_SIGNAL_ADD (q);
1384
1385 static void
1386 gst_queue_set_property (GObject * object,
1387     guint prop_id, const GValue * value, GParamSpec * pspec)
1388 {
1389   GstQueue *queue = GST_QUEUE (object);
1390
1391   /* someone could change levels here, and since this
1392    * affects the get/put funcs, we need to lock for safety. */
1393   GST_QUEUE_MUTEX_LOCK (queue);
1394
1395   switch (prop_id) {
1396     case PROP_MAX_SIZE_BYTES:
1397       queue->max_size.bytes = g_value_get_uint (value);
1398       queue_capacity_change (queue);
1399       break;
1400     case PROP_MAX_SIZE_BUFFERS:
1401       queue->max_size.buffers = g_value_get_uint (value);
1402       queue_capacity_change (queue);
1403       break;
1404     case PROP_MAX_SIZE_TIME:
1405       queue->max_size.time = g_value_get_uint64 (value);
1406       queue_capacity_change (queue);
1407       break;
1408     case PROP_MIN_THRESHOLD_BYTES:
1409       queue->min_threshold.bytes = g_value_get_uint (value);
1410       queue->orig_min_threshold.bytes = queue->min_threshold.bytes;
1411       QUEUE_THRESHOLD_CHANGE (queue);
1412       break;
1413     case PROP_MIN_THRESHOLD_BUFFERS:
1414       queue->min_threshold.buffers = g_value_get_uint (value);
1415       queue->orig_min_threshold.buffers = queue->min_threshold.buffers;
1416       QUEUE_THRESHOLD_CHANGE (queue);
1417       break;
1418     case PROP_MIN_THRESHOLD_TIME:
1419       queue->min_threshold.time = g_value_get_uint64 (value);
1420       queue->orig_min_threshold.time = queue->min_threshold.time;
1421       QUEUE_THRESHOLD_CHANGE (queue);
1422       break;
1423     case PROP_LEAKY:
1424       queue->leaky = g_value_get_enum (value);
1425       break;
1426     case PROP_SILENT:
1427       queue->silent = g_value_get_boolean (value);
1428       break;
1429     default:
1430       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1431       break;
1432   }
1433
1434   GST_QUEUE_MUTEX_UNLOCK (queue);
1435 }
1436
1437 static void
1438 gst_queue_get_property (GObject * object,
1439     guint prop_id, GValue * value, GParamSpec * pspec)
1440 {
1441   GstQueue *queue = GST_QUEUE (object);
1442
1443   GST_QUEUE_MUTEX_LOCK (queue);
1444
1445   switch (prop_id) {
1446     case PROP_CUR_LEVEL_BYTES:
1447       g_value_set_uint (value, queue->cur_level.bytes);
1448       break;
1449     case PROP_CUR_LEVEL_BUFFERS:
1450       g_value_set_uint (value, queue->cur_level.buffers);
1451       break;
1452     case PROP_CUR_LEVEL_TIME:
1453       g_value_set_uint64 (value, queue->cur_level.time);
1454       break;
1455     case PROP_MAX_SIZE_BYTES:
1456       g_value_set_uint (value, queue->max_size.bytes);
1457       break;
1458     case PROP_MAX_SIZE_BUFFERS:
1459       g_value_set_uint (value, queue->max_size.buffers);
1460       break;
1461     case PROP_MAX_SIZE_TIME:
1462       g_value_set_uint64 (value, queue->max_size.time);
1463       break;
1464     case PROP_MIN_THRESHOLD_BYTES:
1465       g_value_set_uint (value, queue->min_threshold.bytes);
1466       break;
1467     case PROP_MIN_THRESHOLD_BUFFERS:
1468       g_value_set_uint (value, queue->min_threshold.buffers);
1469       break;
1470     case PROP_MIN_THRESHOLD_TIME:
1471       g_value_set_uint64 (value, queue->min_threshold.time);
1472       break;
1473     case PROP_LEAKY:
1474       g_value_set_enum (value, queue->leaky);
1475       break;
1476     case PROP_SILENT:
1477       g_value_set_boolean (value, queue->silent);
1478       break;
1479     default:
1480       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1481       break;
1482   }
1483
1484   GST_QUEUE_MUTEX_UNLOCK (queue);
1485 }