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