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