Merge branch 'tizen_3.0' into tizen
[platform/upstream/gstreamer.git] / plugins / elements / gstqueue2.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2003 Colin Walters <cwalters@gnome.org>
4  *                    2000,2005,2007 Wim Taymans <wim.taymans@gmail.com>
5  *                    2007 Thiago Sousa Santos <thiagoss@lcc.ufcg.edu.br>
6  *                 SA 2010 ST-Ericsson <benjamin.gaignard@stericsson.com>
7  *
8  * gstqueue2.c:
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 /**
27  * SECTION:element-queue2
28  *
29  * Data is queued until one of the limits specified by the
30  * #GstQueue2:max-size-buffers, #GstQueue2:max-size-bytes and/or
31  * #GstQueue2:max-size-time properties has been reached. Any attempt to push
32  * more buffers into the queue will block the pushing thread until more space
33  * becomes available.
34  *
35  * The queue will create a new thread on the source pad to decouple the
36  * processing on sink and source pad.
37  *
38  * You can query how many buffers are queued by reading the
39  * #GstQueue2:current-level-buffers property.
40  *
41  * The default queue size limits are 100 buffers, 2MB of data, or
42  * two seconds worth of data, whichever is reached first.
43  *
44  * If you set temp-template to a value such as /tmp/gstreamer-XXXXXX, the element
45  * will allocate a random free filename and buffer data in the file.
46  * By using this, it will buffer the entire stream data on the file independently
47  * of the queue size limits, they will only be used for buffering statistics.
48  *
49  * The temp-location property will be used to notify the application of the
50  * allocated filename.
51  */
52
53 #ifdef HAVE_CONFIG_H
54 #include "config.h"
55 #endif
56
57 #include "gstqueue2.h"
58
59 #include <glib/gstdio.h>
60
61 #include "gst/gst-i18n-lib.h"
62 #include "gst/glib-compat-private.h"
63
64 #include <string.h>
65
66 #ifdef G_OS_WIN32
67 #include <io.h>                 /* lseek, open, close, read */
68 #undef lseek
69 #define lseek _lseeki64
70 #undef off_t
71 #define off_t guint64
72 #else
73 #include <unistd.h>
74 #endif
75
76 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
77     GST_PAD_SINK,
78     GST_PAD_ALWAYS,
79     GST_STATIC_CAPS_ANY);
80
81 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
82     GST_PAD_SRC,
83     GST_PAD_ALWAYS,
84     GST_STATIC_CAPS_ANY);
85
86 GST_DEBUG_CATEGORY_STATIC (queue_debug);
87 #define GST_CAT_DEFAULT (queue_debug)
88 GST_DEBUG_CATEGORY_STATIC (queue_dataflow);
89
90 enum
91 {
92   LAST_SIGNAL
93 };
94
95 /* other defines */
96 #define DEFAULT_BUFFER_SIZE 4096
97 #define QUEUE_IS_USING_TEMP_FILE(queue) ((queue)->temp_template != NULL)
98 #define QUEUE_IS_USING_RING_BUFFER(queue) ((queue)->ring_buffer_max_size != 0)  /* for consistency with the above macro */
99 #define QUEUE_IS_USING_QUEUE(queue) (!QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER (queue))
100
101 #define QUEUE_MAX_BYTES(queue) MIN((queue)->max_level.bytes, (queue)->ring_buffer_max_size)
102
103 /* default property values */
104 #define DEFAULT_MAX_SIZE_BUFFERS   100  /* 100 buffers */
105 #define DEFAULT_MAX_SIZE_BYTES     (2 * 1024 * 1024)    /* 2 MB */
106 #define DEFAULT_MAX_SIZE_TIME      2 * GST_SECOND       /* 2 seconds */
107 #define DEFAULT_USE_BUFFERING      FALSE
108 #define DEFAULT_USE_RATE_ESTIMATE  TRUE
109 #define DEFAULT_LOW_PERCENT        10
110 #define DEFAULT_HIGH_PERCENT       99
111 #define DEFAULT_TEMP_REMOVE        TRUE
112 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
113
114 enum
115 {
116   PROP_0,
117   PROP_CUR_LEVEL_BUFFERS,
118   PROP_CUR_LEVEL_BYTES,
119   PROP_CUR_LEVEL_TIME,
120   PROP_MAX_SIZE_BUFFERS,
121   PROP_MAX_SIZE_BYTES,
122   PROP_MAX_SIZE_TIME,
123   PROP_USE_BUFFERING,
124   PROP_USE_RATE_ESTIMATE,
125   PROP_LOW_PERCENT,
126   PROP_HIGH_PERCENT,
127   PROP_TEMP_TEMPLATE,
128   PROP_TEMP_LOCATION,
129   PROP_TEMP_REMOVE,
130   PROP_RING_BUFFER_MAX_SIZE,
131 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
132   PROP_BUFFER_MODE,
133 #endif
134   PROP_LAST
135 };
136
137 #define GST_QUEUE2_CLEAR_LEVEL(l) G_STMT_START {         \
138   l.buffers = 0;                                        \
139   l.bytes = 0;                                          \
140   l.time = 0;                                           \
141   l.rate_time = 0;                                      \
142 } G_STMT_END
143
144 #define STATUS(queue, pad, msg) \
145   GST_CAT_LOG_OBJECT (queue_dataflow, queue, \
146                       "(%s:%s) " msg ": %u of %u buffers, %u of %u " \
147                       "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
148                       " ns, %"G_GUINT64_FORMAT" items", \
149                       GST_DEBUG_PAD_NAME (pad), \
150                       queue->cur_level.buffers, \
151                       queue->max_level.buffers, \
152                       queue->cur_level.bytes, \
153                       queue->max_level.bytes, \
154                       queue->cur_level.time, \
155                       queue->max_level.time, \
156                       (guint64) (!QUEUE_IS_USING_QUEUE(queue) ? \
157                         queue->current->writing_pos - queue->current->max_reading_pos : \
158                         queue->queue.length))
159
160 #define GST_QUEUE2_MUTEX_LOCK(q) G_STMT_START {                          \
161   g_mutex_lock (&q->qlock);                                              \
162 } G_STMT_END
163
164 #define GST_QUEUE2_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
165   GST_QUEUE2_MUTEX_LOCK (q);                                            \
166   if (res != GST_FLOW_OK)                                               \
167     goto label;                                                         \
168 } G_STMT_END
169
170 #define GST_QUEUE2_MUTEX_UNLOCK(q) G_STMT_START {                        \
171   g_mutex_unlock (&q->qlock);                                            \
172 } G_STMT_END
173
174 #define GST_QUEUE2_WAIT_DEL_CHECK(q, res, label) G_STMT_START {         \
175   STATUS (queue, q->sinkpad, "wait for DEL");                           \
176   q->waiting_del = TRUE;                                                \
177   g_cond_wait (&q->item_del, &queue->qlock);                              \
178   q->waiting_del = FALSE;                                               \
179   if (res != GST_FLOW_OK) {                                             \
180     STATUS (queue, q->srcpad, "received DEL wakeup");                   \
181     goto label;                                                         \
182   }                                                                     \
183   STATUS (queue, q->sinkpad, "received DEL");                           \
184 } G_STMT_END
185
186 #define GST_QUEUE2_WAIT_ADD_CHECK(q, res, label) G_STMT_START {         \
187   STATUS (queue, q->srcpad, "wait for ADD");                            \
188   q->waiting_add = TRUE;                                                \
189   g_cond_wait (&q->item_add, &q->qlock);                                  \
190   q->waiting_add = FALSE;                                               \
191   if (res != GST_FLOW_OK) {                                             \
192     STATUS (queue, q->srcpad, "received ADD wakeup");                   \
193     goto label;                                                         \
194   }                                                                     \
195   STATUS (queue, q->srcpad, "received ADD");                            \
196 } G_STMT_END
197
198 #define GST_QUEUE2_SIGNAL_DEL(q) G_STMT_START {                          \
199   if (q->waiting_del) {                                                 \
200     STATUS (q, q->srcpad, "signal DEL");                                \
201     g_cond_signal (&q->item_del);                                        \
202   }                                                                     \
203 } G_STMT_END
204
205 #define GST_QUEUE2_SIGNAL_ADD(q) G_STMT_START {                          \
206   if (q->waiting_add) {                                                 \
207     STATUS (q, q->sinkpad, "signal ADD");                               \
208     g_cond_signal (&q->item_add);                                        \
209   }                                                                     \
210 } G_STMT_END
211
212 #define SET_PERCENT(q, perc) G_STMT_START {                              \
213   if (perc != q->buffering_percent) {                                    \
214     q->buffering_percent = perc;                                         \
215     q->percent_changed = TRUE;                                           \
216     GST_DEBUG_OBJECT (q, "buffering %d percent", perc);                  \
217     get_buffering_stats (q, perc, &q->mode, &q->avg_in, &q->avg_out,     \
218         &q->buffering_left);                                             \
219   }                                                                      \
220 } G_STMT_END
221
222 #define _do_init \
223     GST_DEBUG_CATEGORY_INIT (queue_debug, "queue2", 0, "queue element"); \
224     GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue2_dataflow", 0, \
225         "dataflow inside the queue element");
226 #define gst_queue2_parent_class parent_class
227 G_DEFINE_TYPE_WITH_CODE (GstQueue2, gst_queue2, GST_TYPE_ELEMENT, _do_init);
228
229 static void gst_queue2_finalize (GObject * object);
230
231 static void gst_queue2_set_property (GObject * object,
232     guint prop_id, const GValue * value, GParamSpec * pspec);
233 static void gst_queue2_get_property (GObject * object,
234     guint prop_id, GValue * value, GParamSpec * pspec);
235
236 static GstFlowReturn gst_queue2_chain (GstPad * pad, GstObject * parent,
237     GstBuffer * buffer);
238 static GstFlowReturn gst_queue2_chain_list (GstPad * pad, GstObject * parent,
239     GstBufferList * buffer_list);
240 static GstFlowReturn gst_queue2_push_one (GstQueue2 * queue);
241 static void gst_queue2_loop (GstPad * pad);
242
243 static gboolean gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
244     GstEvent * event);
245 static gboolean gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
246     GstQuery * query);
247
248 static gboolean gst_queue2_handle_src_event (GstPad * pad, GstObject * parent,
249     GstEvent * event);
250 static gboolean gst_queue2_handle_src_query (GstPad * pad, GstObject * parent,
251     GstQuery * query);
252 static gboolean gst_queue2_handle_query (GstElement * element,
253     GstQuery * query);
254
255 static GstFlowReturn gst_queue2_get_range (GstPad * pad, GstObject * parent,
256     guint64 offset, guint length, GstBuffer ** buffer);
257
258 static gboolean gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent,
259     GstPadMode mode, gboolean active);
260 static gboolean gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
261     GstPadMode mode, gboolean active);
262 static GstStateChangeReturn gst_queue2_change_state (GstElement * element,
263     GstStateChange transition);
264
265 static gboolean gst_queue2_is_empty (GstQueue2 * queue);
266 static gboolean gst_queue2_is_filled (GstQueue2 * queue);
267
268 static void update_cur_level (GstQueue2 * queue, GstQueue2Range * range);
269 static void update_in_rates (GstQueue2 * queue);
270 static void gst_queue2_post_buffering (GstQueue2 * queue);
271 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
272 static gboolean change_current_range(GstQueue2 * queue, GstQueue2Range *req_range, guint64 offset, guint length);
273 #endif
274
275 typedef enum
276 {
277   GST_QUEUE2_ITEM_TYPE_UNKNOWN = 0,
278   GST_QUEUE2_ITEM_TYPE_BUFFER,
279   GST_QUEUE2_ITEM_TYPE_BUFFER_LIST,
280   GST_QUEUE2_ITEM_TYPE_EVENT,
281   GST_QUEUE2_ITEM_TYPE_QUERY
282 } GstQueue2ItemType;
283
284 typedef struct
285 {
286   GstQueue2ItemType type;
287   GstMiniObject *item;
288 } GstQueue2Item;
289
290 /* static guint gst_queue2_signals[LAST_SIGNAL] = { 0 }; */
291
292 static void
293 gst_queue2_class_init (GstQueue2Class * klass)
294 {
295   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
296   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
297
298   gobject_class->set_property = gst_queue2_set_property;
299   gobject_class->get_property = gst_queue2_get_property;
300
301   /* properties */
302   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
303       g_param_spec_uint ("current-level-bytes", "Current level (kB)",
304           "Current amount of data in the queue (bytes)",
305           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
306   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
307       g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
308           "Current number of buffers in the queue",
309           0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
310   g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
311       g_param_spec_uint64 ("current-level-time", "Current level (ns)",
312           "Current amount of data in the queue (in ns)",
313           0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
314
315   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
316       g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
317           "Max. amount of data in the queue (bytes, 0=disable)",
318           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
319           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
320           G_PARAM_STATIC_STRINGS));
321   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
322       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
323           "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
324           DEFAULT_MAX_SIZE_BUFFERS,
325           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
326           G_PARAM_STATIC_STRINGS));
327   g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
328       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
329           "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
330           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
331           G_PARAM_STATIC_STRINGS));
332
333   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
334       g_param_spec_boolean ("use-buffering", "Use buffering",
335           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
336           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
337           G_PARAM_STATIC_STRINGS));
338   g_object_class_install_property (gobject_class, PROP_USE_RATE_ESTIMATE,
339       g_param_spec_boolean ("use-rate-estimate", "Use Rate Estimate",
340           "Estimate the bitrate of the stream to calculate time level",
341           DEFAULT_USE_RATE_ESTIMATE,
342           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
343   g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
344       g_param_spec_int ("low-percent", "Low percent",
345           "Low threshold for buffering to start. Only used if use-buffering is True",
346           0, 100, DEFAULT_LOW_PERCENT,
347           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348   g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
349       g_param_spec_int ("high-percent", "High percent",
350           "High threshold for buffering to finish. Only used if use-buffering is True",
351           0, 100, DEFAULT_HIGH_PERCENT,
352           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
353
354   g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
355       g_param_spec_string ("temp-template", "Temporary File Template",
356           "File template to store temporary files in, should contain directory "
357           "and XXXXXX. (NULL == disabled)",
358           NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
359
360   g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
361       g_param_spec_string ("temp-location", "Temporary File Location",
362           "Location to store temporary files in (Only read this property, "
363           "use temp-template to configure the name template)",
364           NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
365
366   /**
367    * GstQueue2:temp-remove
368    *
369    * When temp-template is set, remove the temporary file when going to READY.
370    */
371   g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
372       g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
373           "Remove the temp-location after use",
374           DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
375
376   /**
377    * GstQueue2:ring-buffer-max-size
378    *
379    * The maximum size of the ring buffer in bytes. If set to 0, the ring
380    * buffer is disabled. Default 0.
381    */
382   g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
383       g_param_spec_uint64 ("ring-buffer-max-size",
384           "Max. ring buffer size (bytes)",
385           "Max. amount of data in the ring buffer (bytes, 0 = disabled)",
386           0, G_MAXUINT64, DEFAULT_RING_BUFFER_MAX_SIZE,
387           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388
389 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
390   /**
391    * GstQueue2:buffer-mode:
392    *
393    * Control the buffering mode used by the queue2.
394    */
395   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
396       g_param_spec_enum ("buffer-mode", "Buffer Mode",
397           "Control the buffering algorithm in use",
398           GST_TYPE_BUFFERING_MODE, GST_BUFFERING_STREAM,
399           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
400 #endif
401
402   /* set several parent class virtual functions */
403   gobject_class->finalize = gst_queue2_finalize;
404
405   gst_element_class_add_pad_template (gstelement_class,
406       gst_static_pad_template_get (&srctemplate));
407   gst_element_class_add_pad_template (gstelement_class,
408       gst_static_pad_template_get (&sinktemplate));
409
410   gst_element_class_set_static_metadata (gstelement_class, "Queue 2",
411       "Generic",
412       "Simple data queue",
413       "Erik Walthinsen <omega@cse.ogi.edu>, "
414       "Wim Taymans <wim.taymans@gmail.com>");
415
416   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_queue2_change_state);
417   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_queue2_handle_query);
418 }
419
420 static void
421 gst_queue2_init (GstQueue2 * queue)
422 {
423   queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
424
425   gst_pad_set_chain_function (queue->sinkpad,
426       GST_DEBUG_FUNCPTR (gst_queue2_chain));
427   gst_pad_set_chain_list_function (queue->sinkpad,
428       GST_DEBUG_FUNCPTR (gst_queue2_chain_list));
429   gst_pad_set_activatemode_function (queue->sinkpad,
430       GST_DEBUG_FUNCPTR (gst_queue2_sink_activate_mode));
431   gst_pad_set_event_function (queue->sinkpad,
432       GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_event));
433   gst_pad_set_query_function (queue->sinkpad,
434       GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_query));
435   GST_PAD_SET_PROXY_CAPS (queue->sinkpad);
436   gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
437
438   queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
439
440   gst_pad_set_activatemode_function (queue->srcpad,
441       GST_DEBUG_FUNCPTR (gst_queue2_src_activate_mode));
442   gst_pad_set_getrange_function (queue->srcpad,
443       GST_DEBUG_FUNCPTR (gst_queue2_get_range));
444   gst_pad_set_event_function (queue->srcpad,
445       GST_DEBUG_FUNCPTR (gst_queue2_handle_src_event));
446   gst_pad_set_query_function (queue->srcpad,
447       GST_DEBUG_FUNCPTR (gst_queue2_handle_src_query));
448   GST_PAD_SET_PROXY_CAPS (queue->srcpad);
449   gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
450
451   /* levels */
452   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
453   queue->max_level.buffers = DEFAULT_MAX_SIZE_BUFFERS;
454   queue->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
455   queue->max_level.time = DEFAULT_MAX_SIZE_TIME;
456   queue->max_level.rate_time = DEFAULT_MAX_SIZE_TIME;
457   queue->use_buffering = DEFAULT_USE_BUFFERING;
458   queue->use_rate_estimate = DEFAULT_USE_RATE_ESTIMATE;
459   queue->low_percent = DEFAULT_LOW_PERCENT;
460   queue->high_percent = DEFAULT_HIGH_PERCENT;
461
462   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
463   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
464
465   queue->sinktime = GST_CLOCK_TIME_NONE;
466   queue->srctime = GST_CLOCK_TIME_NONE;
467   queue->sink_tainted = TRUE;
468   queue->src_tainted = TRUE;
469
470   queue->srcresult = GST_FLOW_FLUSHING;
471   queue->sinkresult = GST_FLOW_FLUSHING;
472   queue->is_eos = FALSE;
473   queue->in_timer = g_timer_new ();
474   queue->out_timer = g_timer_new ();
475
476   g_mutex_init (&queue->qlock);
477   queue->waiting_add = FALSE;
478   g_cond_init (&queue->item_add);
479   queue->waiting_del = FALSE;
480   g_cond_init (&queue->item_del);
481   g_queue_init (&queue->queue);
482
483   g_cond_init (&queue->query_handled);
484   queue->last_query = FALSE;
485
486   g_mutex_init (&queue->buffering_post_lock);
487   queue->buffering_percent = 100;
488
489   /* tempfile related */
490   queue->temp_template = NULL;
491   queue->temp_location = NULL;
492   queue->temp_remove = DEFAULT_TEMP_REMOVE;
493
494   queue->ring_buffer = NULL;
495   queue->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
496 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
497   queue->mode = -1;
498 #endif
499   GST_DEBUG_OBJECT (queue,
500       "initialized queue's not_empty & not_full conditions");
501 }
502
503 /* called only once, as opposed to dispose */
504 static void
505 gst_queue2_finalize (GObject * object)
506 {
507   GstQueue2 *queue = GST_QUEUE2 (object);
508
509   GST_DEBUG_OBJECT (queue, "finalizing queue");
510
511   while (!g_queue_is_empty (&queue->queue)) {
512     GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
513
514     if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
515       gst_mini_object_unref (qitem->item);
516     g_slice_free (GstQueue2Item, qitem);
517   }
518
519   queue->last_query = FALSE;
520   g_queue_clear (&queue->queue);
521   g_mutex_clear (&queue->qlock);
522   g_mutex_clear (&queue->buffering_post_lock);
523   g_cond_clear (&queue->item_add);
524   g_cond_clear (&queue->item_del);
525   g_cond_clear (&queue->query_handled);
526   g_timer_destroy (queue->in_timer);
527   g_timer_destroy (queue->out_timer);
528
529   /* temp_file path cleanup  */
530   g_free (queue->temp_template);
531   g_free (queue->temp_location);
532
533   G_OBJECT_CLASS (parent_class)->finalize (object);
534 }
535
536 static void
537 debug_ranges (GstQueue2 * queue)
538 {
539   GstQueue2Range *walk;
540
541   for (walk = queue->ranges; walk; walk = walk->next) {
542     GST_DEBUG_OBJECT (queue,
543         "range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "] (rb [%"
544         G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "]), reading %" G_GUINT64_FORMAT
545         " current range? %s", walk->offset, walk->writing_pos, walk->rb_offset,
546         walk->rb_writing_pos, walk->reading_pos,
547         walk == queue->current ? "**y**" : "  n  ");
548   }
549 }
550
551 /* clear all the downloaded ranges */
552 static void
553 clean_ranges (GstQueue2 * queue)
554 {
555   GST_DEBUG_OBJECT (queue, "clean queue ranges");
556
557   g_slice_free_chain (GstQueue2Range, queue->ranges, next);
558   queue->ranges = NULL;
559   queue->current = NULL;
560 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
561   queue->read = NULL;
562 #endif
563 }
564
565 /* find a range that contains @offset or NULL when nothing does */
566 static GstQueue2Range *
567 find_range (GstQueue2 * queue, guint64 offset)
568 {
569   GstQueue2Range *range = NULL;
570   GstQueue2Range *walk;
571
572   /* first do a quick check for the current range */
573   for (walk = queue->ranges; walk; walk = walk->next) {
574     if (offset >= walk->offset && offset <= walk->writing_pos) {
575       /* we can reuse an existing range */
576       range = walk;
577       break;
578     }
579   }
580   if (range) {
581     GST_DEBUG_OBJECT (queue,
582         "found range for %" G_GUINT64_FORMAT ": [%" G_GUINT64_FORMAT "-%"
583         G_GUINT64_FORMAT "]", offset, range->offset, range->writing_pos);
584   } else {
585     GST_DEBUG_OBJECT (queue, "no range for %" G_GUINT64_FORMAT, offset);
586   }
587   return range;
588 }
589
590 static void
591 update_cur_level (GstQueue2 * queue, GstQueue2Range * range)
592 {
593   guint64 max_reading_pos, writing_pos;
594
595   writing_pos = range->writing_pos;
596   max_reading_pos = range->max_reading_pos;
597
598   if (writing_pos > max_reading_pos)
599     queue->cur_level.bytes = writing_pos - max_reading_pos;
600   else
601     queue->cur_level.bytes = 0;
602 }
603
604 /* make a new range for @offset or reuse an existing range */
605 static GstQueue2Range *
606 add_range (GstQueue2 * queue, guint64 offset, gboolean update_existing)
607 {
608   GstQueue2Range *range, *prev, *next;
609
610   GST_DEBUG_OBJECT (queue, "find range for %" G_GUINT64_FORMAT, offset);
611
612   if ((range = find_range (queue, offset))) {
613     GST_DEBUG_OBJECT (queue,
614         "reusing range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, range->offset,
615         range->writing_pos);
616     if (update_existing && range->writing_pos != offset) {
617       GST_DEBUG_OBJECT (queue, "updating range writing position to "
618           "%" G_GUINT64_FORMAT, offset);
619       range->writing_pos = offset;
620     }
621   } else {
622     GST_DEBUG_OBJECT (queue,
623         "new range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, offset);
624
625     range = g_slice_new0 (GstQueue2Range);
626     range->offset = offset;
627     /* we want to write to the next location in the ring buffer */
628     range->rb_offset = queue->current ? queue->current->rb_writing_pos : 0;
629     range->writing_pos = offset;
630     range->rb_writing_pos = range->rb_offset;
631     range->reading_pos = offset;
632     range->max_reading_pos = offset;
633
634     /* insert sorted */
635     prev = NULL;
636     next = queue->ranges;
637     while (next) {
638       if (next->offset > offset) {
639         /* insert before next */
640         GST_DEBUG_OBJECT (queue,
641             "insert before range %p, offset %" G_GUINT64_FORMAT, next,
642             next->offset);
643         break;
644       }
645       /* try next */
646       prev = next;
647       next = next->next;
648     }
649     range->next = next;
650     if (prev)
651       prev->next = range;
652     else
653       queue->ranges = range;
654   }
655   debug_ranges (queue);
656
657   /* update the stats for this range */
658   update_cur_level (queue, range);
659
660   return range;
661 }
662
663
664 /* clear and init the download ranges for offset 0 */
665 static void
666 init_ranges (GstQueue2 * queue)
667 {
668   GST_DEBUG_OBJECT (queue, "init queue ranges");
669
670   /* get rid of all the current ranges */
671   clean_ranges (queue);
672   /* make a range for offset 0 */
673 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
674   queue->current = queue->read = add_range (queue, 0, TRUE);
675 #else
676   queue->current = add_range (queue, 0, TRUE);
677 #endif
678 }
679
680 /* calculate the diff between running time on the sink and src of the queue.
681  * This is the total amount of time in the queue. */
682 static void
683 update_time_level (GstQueue2 * queue)
684 {
685   if (queue->sink_tainted) {
686     queue->sinktime =
687         gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
688         queue->sink_segment.position);
689     queue->sink_tainted = FALSE;
690   }
691
692   if (queue->src_tainted) {
693     queue->srctime =
694         gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
695         queue->src_segment.position);
696     queue->src_tainted = FALSE;
697   }
698
699   GST_DEBUG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
700       GST_TIME_ARGS (queue->sinktime), GST_TIME_ARGS (queue->srctime));
701
702   if (queue->sinktime != GST_CLOCK_TIME_NONE
703       && queue->srctime != GST_CLOCK_TIME_NONE
704       && queue->sinktime >= queue->srctime)
705     queue->cur_level.time = queue->sinktime - queue->srctime;
706   else
707     queue->cur_level.time = 0;
708 }
709
710 /* take a SEGMENT event and apply the values to segment, updating the time
711  * level of queue. */
712 static void
713 apply_segment (GstQueue2 * queue, GstEvent * event, GstSegment * segment,
714     gboolean is_sink)
715 {
716   gst_event_copy_segment (event, segment);
717
718   if (segment->format == GST_FORMAT_BYTES) {
719     if (!QUEUE_IS_USING_QUEUE (queue) && is_sink) {
720       /* start is where we'll be getting from and as such writing next */
721 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
722       queue->current = queue->read = add_range (queue, segment->start, TRUE);
723 #else
724       queue->current = add_range (queue, segment->start, TRUE);
725 #endif
726     }
727   }
728
729   /* now configure the values, we use these to track timestamps on the
730    * sinkpad. */
731   if (segment->format != GST_FORMAT_TIME) {
732     /* non-time format, pretent the current time segment is closed with a
733      * 0 start and unknown stop time. */
734     segment->format = GST_FORMAT_TIME;
735     segment->start = 0;
736     segment->stop = -1;
737     segment->time = 0;
738   }
739
740   GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
741
742   if (is_sink)
743     queue->sink_tainted = TRUE;
744   else
745     queue->src_tainted = TRUE;
746
747   /* segment can update the time level of the queue */
748   update_time_level (queue);
749 }
750
751 static void
752 apply_gap (GstQueue2 * queue, GstEvent * event,
753     GstSegment * segment, gboolean is_sink)
754 {
755   GstClockTime timestamp;
756   GstClockTime duration;
757
758   gst_event_parse_gap (event, &timestamp, &duration);
759
760   if (GST_CLOCK_TIME_IS_VALID (timestamp)) {
761
762     if (GST_CLOCK_TIME_IS_VALID (duration)) {
763       timestamp += duration;
764     }
765
766     segment->position = timestamp;
767
768     if (is_sink)
769       queue->sink_tainted = TRUE;
770     else
771       queue->src_tainted = TRUE;
772
773     /* calc diff with other end */
774     update_time_level (queue);
775   }
776 }
777
778 /* take a buffer and update segment, updating the time level of the queue. */
779 static void
780 apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
781     gboolean is_sink)
782 {
783   GstClockTime duration, timestamp;
784
785   timestamp = GST_BUFFER_TIMESTAMP (buffer);
786   duration = GST_BUFFER_DURATION (buffer);
787
788   /* if no timestamp is set, assume it's continuous with the previous
789    * time */
790   if (timestamp == GST_CLOCK_TIME_NONE)
791     timestamp = segment->position;
792
793   /* add duration */
794   if (duration != GST_CLOCK_TIME_NONE)
795     timestamp += duration;
796
797   GST_DEBUG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
798       GST_TIME_ARGS (timestamp));
799
800   segment->position = timestamp;
801
802   if (is_sink)
803     queue->sink_tainted = TRUE;
804   else
805     queue->src_tainted = TRUE;
806
807   /* calc diff with other end */
808   update_time_level (queue);
809 }
810
811 static gboolean
812 buffer_list_apply_time (GstBuffer ** buf, guint idx, gpointer data)
813 {
814   GstClockTime *timestamp = data;
815
816   GST_TRACE ("buffer %u has ts %" GST_TIME_FORMAT
817       " duration %" GST_TIME_FORMAT, idx,
818       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (*buf)),
819       GST_TIME_ARGS (GST_BUFFER_DURATION (*buf)));
820
821   if (GST_BUFFER_TIMESTAMP_IS_VALID (*buf))
822     *timestamp = GST_BUFFER_TIMESTAMP (*buf);
823
824   if (GST_BUFFER_DURATION_IS_VALID (*buf))
825     *timestamp += GST_BUFFER_DURATION (*buf);
826
827   GST_TRACE ("ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (*timestamp));
828   return TRUE;
829 }
830
831 /* take a buffer list and update segment, updating the time level of the queue */
832 static void
833 apply_buffer_list (GstQueue2 * queue, GstBufferList * buffer_list,
834     GstSegment * segment, gboolean is_sink)
835 {
836   GstClockTime timestamp;
837
838   /* if no timestamp is set, assume it's continuous with the previous time */
839   timestamp = segment->position;
840
841   gst_buffer_list_foreach (buffer_list, buffer_list_apply_time, &timestamp);
842
843   GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
844       GST_TIME_ARGS (timestamp));
845
846   segment->position = timestamp;
847
848   if (is_sink)
849     queue->sink_tainted = TRUE;
850   else
851     queue->src_tainted = TRUE;
852
853   /* calc diff with other end */
854   update_time_level (queue);
855 }
856
857 static gboolean
858 get_buffering_percent (GstQueue2 * queue, gboolean * is_buffering,
859     gint * percent)
860 {
861   gint perc;
862
863   if (queue->high_percent <= 0) {
864     if (percent)
865       *percent = 100;
866     if (is_buffering)
867       *is_buffering = FALSE;
868     return FALSE;
869   }
870 #define GET_PERCENT(format,alt_max) ((queue->max_level.format) > 0 ? (queue->cur_level.format) * 100 / ((alt_max) > 0 ? MIN ((alt_max), (queue->max_level.format)) : (queue->max_level.format)) : 0)
871
872   if (queue->is_eos) {
873     /* on EOS we are always 100% full, we set the var here so that it we can
874      * reuse the logic below to stop buffering */
875     perc = 100;
876     GST_LOG_OBJECT (queue, "we are EOS");
877   } else {
878     /* figure out the percent we are filled, we take the max of all formats. */
879     if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
880       perc = GET_PERCENT (bytes, 0);
881     } else {
882       guint64 rb_size = queue->ring_buffer_max_size;
883       perc = GET_PERCENT (bytes, rb_size);
884     }
885     perc = MAX (perc, GET_PERCENT (time, 0));
886     perc = MAX (perc, GET_PERCENT (buffers, 0));
887
888     /* also apply the rate estimate when we need to */
889     if (queue->use_rate_estimate)
890       perc = MAX (perc, GET_PERCENT (rate_time, 0));
891   }
892 #undef GET_PERCENT
893
894   if (is_buffering)
895     *is_buffering = queue->is_buffering;
896
897   /* scale to high percent so that it becomes the 100% mark */
898   perc = perc * 100 / queue->high_percent;
899   /* clip */
900   if (perc > 100)
901     perc = 100;
902
903   if (percent)
904     *percent = perc;
905
906   GST_DEBUG_OBJECT (queue, "buffering %d, percent %d", queue->is_buffering,
907       perc);
908
909   return TRUE;
910 }
911
912 static void
913 get_buffering_stats (GstQueue2 * queue, gint percent, GstBufferingMode * mode,
914     gint * avg_in, gint * avg_out, gint64 * buffering_left)
915 {
916 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
917   if (queue->mode != -1) {
918     *mode = queue->mode;
919   } else {
920     if (mode) {
921       if (!QUEUE_IS_USING_QUEUE (queue)) {
922         if (QUEUE_IS_USING_RING_BUFFER (queue))
923           *mode = GST_BUFFERING_TIMESHIFT;
924         else
925           *mode = GST_BUFFERING_DOWNLOAD;
926       } else {
927         *mode = GST_BUFFERING_STREAM;
928       }
929     }
930   }
931 #else
932   if (mode) {
933     if (!QUEUE_IS_USING_QUEUE (queue)) {
934       if (QUEUE_IS_USING_RING_BUFFER (queue))
935         *mode = GST_BUFFERING_TIMESHIFT;
936       else
937         *mode = GST_BUFFERING_DOWNLOAD;
938     } else {
939       *mode = GST_BUFFERING_STREAM;
940     }
941   }
942 #endif
943
944   if (avg_in)
945     *avg_in = queue->byte_in_rate;
946   if (avg_out)
947     *avg_out = queue->byte_out_rate;
948
949   if (buffering_left) {
950     *buffering_left = (percent == 100 ? 0 : -1);
951
952     if (queue->use_rate_estimate) {
953       guint64 max, cur;
954
955       max = queue->max_level.rate_time;
956       cur = queue->cur_level.rate_time;
957
958       if (percent != 100 && max > cur)
959         *buffering_left = (max - cur) / 1000000;
960     }
961   }
962 }
963
964 static void
965 gst_queue2_post_buffering (GstQueue2 * queue)
966 {
967   GstMessage *msg = NULL;
968
969   g_mutex_lock (&queue->buffering_post_lock);
970   GST_QUEUE2_MUTEX_LOCK (queue);
971   if (queue->percent_changed) {
972     gint percent = queue->buffering_percent;
973
974     queue->percent_changed = FALSE;
975
976     GST_DEBUG_OBJECT (queue, "Going to post buffering: %d%%", percent);
977     msg = gst_message_new_buffering (GST_OBJECT_CAST (queue), percent);
978
979     gst_message_set_buffering_stats (msg, queue->mode, queue->avg_in,
980         queue->avg_out, queue->buffering_left);
981   }
982   GST_QUEUE2_MUTEX_UNLOCK (queue);
983
984   if (msg != NULL)
985     gst_element_post_message (GST_ELEMENT_CAST (queue), msg);
986
987   g_mutex_unlock (&queue->buffering_post_lock);
988 }
989
990 static void
991 update_buffering (GstQueue2 * queue)
992 {
993   gint percent;
994 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
995   GstQueue2Range *range;
996
997   if (queue->read)
998     range = queue->read;
999   else
1000     range = queue->current;
1001 #endif
1002
1003   /* Ensure the variables used to calculate buffering state are up-to-date. */
1004 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1005   if (range)
1006     update_cur_level (queue, range);
1007 #else
1008   if (queue->current)
1009     update_cur_level (queue, queue->current);
1010 #endif
1011   update_in_rates (queue);
1012
1013   if (!get_buffering_percent (queue, NULL, &percent))
1014     return;
1015
1016   if (queue->is_buffering) {
1017     /* if we were buffering see if we reached the high watermark */
1018     if (percent >= 100)
1019       queue->is_buffering = FALSE;
1020
1021     SET_PERCENT (queue, percent);
1022   } else {
1023     /* we were not buffering, check if we need to start buffering if we drop
1024      * below the low threshold */
1025     if (percent < queue->low_percent) {
1026       queue->is_buffering = TRUE;
1027       SET_PERCENT (queue, percent);
1028     }
1029   }
1030 }
1031
1032 static void
1033 reset_rate_timer (GstQueue2 * queue)
1034 {
1035   queue->bytes_in = 0;
1036   queue->bytes_out = 0;
1037   queue->byte_in_rate = 0.0;
1038   queue->byte_in_period = 0;
1039   queue->byte_out_rate = 0.0;
1040   queue->last_in_elapsed = 0.0;
1041   queue->last_out_elapsed = 0.0;
1042   queue->in_timer_started = FALSE;
1043   queue->out_timer_started = FALSE;
1044 }
1045
1046 /* the interval in seconds to recalculate the rate */
1047 #define RATE_INTERVAL    0.2
1048 /* Tuning for rate estimation. We use a large window for the input rate because
1049  * it should be stable when connected to a network. The output rate is less
1050  * stable (the elements preroll, queues behind a demuxer fill, ...) and should
1051  * therefore adapt more quickly.
1052  * However, initial input rate may be subject to a burst, and should therefore
1053  * initially also adapt more quickly to changes, and only later on give higher
1054  * weight to previous values. */
1055 #define AVG_IN(avg,val,w1,w2)  ((avg) * (w1) + (val) * (w2)) / ((w1) + (w2))
1056 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
1057
1058 static void
1059 update_in_rates (GstQueue2 * queue)
1060 {
1061   gdouble elapsed, period;
1062   gdouble byte_in_rate;
1063
1064   if (!queue->in_timer_started) {
1065     queue->in_timer_started = TRUE;
1066     g_timer_start (queue->in_timer);
1067     return;
1068   }
1069
1070   elapsed = g_timer_elapsed (queue->in_timer, NULL);
1071
1072   /* recalc after each interval. */
1073   if (queue->last_in_elapsed + RATE_INTERVAL < elapsed) {
1074     period = elapsed - queue->last_in_elapsed;
1075
1076     GST_DEBUG_OBJECT (queue,
1077         "rates: period %f, in %" G_GUINT64_FORMAT ", global period %f",
1078         period, queue->bytes_in, queue->byte_in_period);
1079
1080     byte_in_rate = queue->bytes_in / period;
1081
1082     if (queue->byte_in_rate == 0.0)
1083       queue->byte_in_rate = byte_in_rate;
1084     else
1085       queue->byte_in_rate = AVG_IN (queue->byte_in_rate, byte_in_rate,
1086           (double) queue->byte_in_period, period);
1087
1088     /* another data point, cap at 16 for long time running average */
1089     if (queue->byte_in_period < 16 * RATE_INTERVAL)
1090       queue->byte_in_period += period;
1091
1092     /* reset the values to calculate rate over the next interval */
1093     queue->last_in_elapsed = elapsed;
1094     queue->bytes_in = 0;
1095   }
1096
1097   if (queue->byte_in_rate > 0.0) {
1098     queue->cur_level.rate_time =
1099         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1100   }
1101   GST_DEBUG_OBJECT (queue, "rates: in %f, time %" GST_TIME_FORMAT,
1102       queue->byte_in_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1103 }
1104
1105 static void
1106 update_out_rates (GstQueue2 * queue)
1107 {
1108   gdouble elapsed, period;
1109   gdouble byte_out_rate;
1110
1111   if (!queue->out_timer_started) {
1112     queue->out_timer_started = TRUE;
1113     g_timer_start (queue->out_timer);
1114     return;
1115   }
1116
1117   elapsed = g_timer_elapsed (queue->out_timer, NULL);
1118
1119   /* recalc after each interval. */
1120   if (queue->last_out_elapsed + RATE_INTERVAL < elapsed) {
1121     period = elapsed - queue->last_out_elapsed;
1122
1123     GST_DEBUG_OBJECT (queue,
1124         "rates: period %f, out %" G_GUINT64_FORMAT, period, queue->bytes_out);
1125
1126     byte_out_rate = queue->bytes_out / period;
1127
1128     if (queue->byte_out_rate == 0.0)
1129       queue->byte_out_rate = byte_out_rate;
1130     else
1131       queue->byte_out_rate = AVG_OUT (queue->byte_out_rate, byte_out_rate);
1132
1133     /* reset the values to calculate rate over the next interval */
1134     queue->last_out_elapsed = elapsed;
1135     queue->bytes_out = 0;
1136   }
1137   if (queue->byte_in_rate > 0.0) {
1138     queue->cur_level.rate_time =
1139         queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
1140   }
1141   GST_DEBUG_OBJECT (queue, "rates: out %f, time %" GST_TIME_FORMAT,
1142       queue->byte_out_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
1143 }
1144
1145 static void
1146 update_cur_pos (GstQueue2 * queue, GstQueue2Range * range, guint64 pos)
1147 {
1148   guint64 reading_pos, max_reading_pos;
1149
1150   reading_pos = pos;
1151   max_reading_pos = range->max_reading_pos;
1152
1153   max_reading_pos = MAX (max_reading_pos, reading_pos);
1154
1155   GST_DEBUG_OBJECT (queue,
1156       "updating max_reading_pos from %" G_GUINT64_FORMAT " to %"
1157       G_GUINT64_FORMAT, range->max_reading_pos, max_reading_pos);
1158   range->max_reading_pos = max_reading_pos;
1159
1160   update_cur_level (queue, range);
1161 }
1162
1163 static gboolean
1164 perform_seek_to_offset (GstQueue2 * queue, guint64 offset)
1165 {
1166   GstEvent *event;
1167   gboolean res;
1168
1169   /* until we receive the FLUSH_STOP from this seek, we skip data */
1170   queue->seeking = TRUE;
1171   GST_QUEUE2_MUTEX_UNLOCK (queue);
1172
1173   debug_ranges (queue);
1174
1175   GST_DEBUG_OBJECT (queue, "Seeking to %" G_GUINT64_FORMAT, offset);
1176
1177   event =
1178       gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1179       GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1180       GST_SEEK_TYPE_NONE, -1);
1181
1182   res = gst_pad_push_event (queue->sinkpad, event);
1183   GST_QUEUE2_MUTEX_LOCK (queue);
1184
1185   if (res) {
1186     /* Between us sending the seek event and re-acquiring the lock, the source
1187      * thread might already have pushed data and moved along the range's
1188      * writing_pos beyond the seek offset. In that case we don't want to set
1189      * the writing position back to the requested seek position, as it would
1190      * cause data to be written to the wrong offset in the file or ring buffer.
1191      * We still do the add_range call to switch the current range to the
1192      * requested range, or create one if one doesn't exist yet. */
1193 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1194     queue->current = queue->read = add_range (queue, offset, FALSE);
1195 #else
1196     queue->current = add_range (queue, offset, FALSE);
1197 #endif
1198   }
1199
1200   return res;
1201 }
1202
1203 /* get the threshold for when we decide to seek rather than wait */
1204 static guint64
1205 get_seek_threshold (GstQueue2 * queue)
1206 {
1207   guint64 threshold;
1208
1209   /* FIXME, find a good threshold based on the incoming rate. */
1210   threshold = 1024 * 512;
1211
1212   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1213     threshold = MIN (threshold,
1214         QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes);
1215   }
1216   return threshold;
1217 }
1218
1219 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1220 /* check the buffered data size, not to change range repeatedly.
1221  * changing range cause the new http connection and it makes buffering state frequently. */
1222 static gboolean
1223 change_current_range(GstQueue2 * queue, GstQueue2Range *req_range, guint64 offset, guint length)
1224 {
1225   guint64 curr_level = 0;
1226   guint64 curr_min_level = 0;
1227
1228   if (queue->current->writing_pos > queue->current->reading_pos)
1229     curr_level = queue->current->writing_pos - queue->current->reading_pos;
1230
1231   /* FIXME, find a good threshold based on the incoming rate and content bitrate. */
1232   curr_min_level = MIN((queue->max_level.bytes*0.05), get_seek_threshold(queue));
1233
1234   GST_DEBUG_OBJECT(queue, " curr[w%"G_GUINT64_FORMAT", r%"G_GUINT64_FORMAT
1235         ", d%"G_GUINT64_FORMAT", m%"G_GUINT64_FORMAT
1236         "] u[%"G_GUINT64_FORMAT"][EOS:%d]",
1237         queue->current->writing_pos, queue->current->reading_pos,
1238         curr_level, curr_min_level,
1239         queue->upstream_size, queue->is_eos);
1240
1241   /* FIXME, find a good threshold based on the incoming rate and content bitrate. */
1242   if ((queue->is_eos) ||
1243       (queue->upstream_size > 0 && queue->current->writing_pos >= queue->upstream_size) ||
1244       (curr_level >= curr_min_level)) {
1245     GST_DEBUG_OBJECT (queue, "Range Switching");
1246     return TRUE;
1247   } else {
1248     GST_DEBUG_OBJECT (queue, "keep receiving data without range switching.");
1249     return FALSE;
1250   }
1251 }
1252 #endif
1253
1254 /* see if there is enough data in the file to read a full buffer */
1255 static gboolean
1256 gst_queue2_have_data (GstQueue2 * queue, guint64 offset, guint length)
1257 {
1258   GstQueue2Range *range;
1259 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1260   gboolean need_to_seek = TRUE;
1261 #endif
1262   GST_DEBUG_OBJECT (queue, "looking for offset %" G_GUINT64_FORMAT ", len %u",
1263       offset, length);
1264
1265   if ((range = find_range (queue, offset))) {
1266 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1267     queue->read = range;
1268 #endif
1269     if (queue->current != range) {
1270       GST_DEBUG_OBJECT (queue, "switching ranges, do seek to range position");
1271 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1272       if (QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER(queue))
1273         need_to_seek = change_current_range(queue, range, offset, length);
1274
1275       if (need_to_seek == TRUE)
1276         perform_seek_to_offset (queue, range->writing_pos);
1277 #else
1278       perform_seek_to_offset (queue, range->writing_pos);
1279 #endif
1280     }
1281
1282     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1283         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1284
1285     /* we have a range for offset */
1286     GST_DEBUG_OBJECT (queue,
1287         "we have a range %p, offset %" G_GUINT64_FORMAT ", writing_pos %"
1288         G_GUINT64_FORMAT, range, range->offset, range->writing_pos);
1289
1290     if (!QUEUE_IS_USING_RING_BUFFER (queue) && queue->is_eos)
1291       return TRUE;
1292
1293     if (offset + length <= range->writing_pos)
1294       return TRUE;
1295     else
1296       GST_DEBUG_OBJECT (queue,
1297           "Need more data (%" G_GUINT64_FORMAT " bytes more)",
1298           (offset + length) - range->writing_pos);
1299
1300   } else {
1301     GST_INFO_OBJECT (queue, "not found in any range off %" G_GUINT64_FORMAT
1302         " len %u", offset, length);
1303
1304 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1305     queue->read = queue->current;
1306 #endif
1307
1308     /* we don't have the range, see how far away we are */
1309     if (!queue->is_eos && queue->current) {
1310       guint64 threshold = get_seek_threshold (queue);
1311
1312       if (offset >= queue->current->offset && offset <=
1313           queue->current->writing_pos + threshold) {
1314         GST_INFO_OBJECT (queue,
1315             "requested data is within range, wait for data");
1316         return FALSE;
1317       }
1318     }
1319
1320     /* too far away, do a seek */
1321     perform_seek_to_offset (queue, offset);
1322   }
1323
1324   return FALSE;
1325 }
1326
1327 #ifdef HAVE_FSEEKO
1328 #define FSEEK_FILE(file,offset)  (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1329 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1330 #define FSEEK_FILE(file,offset)  (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1331 #else
1332 #define FSEEK_FILE(file,offset)  (fseek (file, offset, SEEK_SET) != 0)
1333 #endif
1334
1335 static GstFlowReturn
1336 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1337     guint8 * dst, gint64 * read_return)
1338 {
1339   guint8 *ring_buffer;
1340   size_t res;
1341
1342   ring_buffer = queue->ring_buffer;
1343
1344   if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1345     goto seek_failed;
1346
1347   /* this should not block */
1348   GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1349       length, offset);
1350   if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1351     res = fread (dst, 1, length, queue->temp_file);
1352   } else {
1353     memcpy (dst, ring_buffer + offset, length);
1354     res = length;
1355   }
1356
1357   GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1358
1359   if (G_UNLIKELY (res < length)) {
1360     if (!QUEUE_IS_USING_TEMP_FILE (queue))
1361       goto could_not_read;
1362     /* check for errors or EOF */
1363     if (ferror (queue->temp_file))
1364       goto could_not_read;
1365     if (feof (queue->temp_file) && length > 0)
1366       goto eos;
1367   }
1368
1369   *read_return = res;
1370
1371   return GST_FLOW_OK;
1372
1373 seek_failed:
1374   {
1375     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1376     return GST_FLOW_ERROR;
1377   }
1378 could_not_read:
1379   {
1380     GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1381     return GST_FLOW_ERROR;
1382   }
1383 eos:
1384   {
1385     GST_DEBUG ("non-regular file hits EOS");
1386     return GST_FLOW_EOS;
1387   }
1388 }
1389
1390 static GstFlowReturn
1391 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1392     GstBuffer ** buffer)
1393 {
1394   GstBuffer *buf;
1395   GstMapInfo info;
1396   guint8 *data;
1397   guint64 file_offset;
1398   guint block_length, remaining, read_length;
1399   guint64 rb_size;
1400   guint64 max_size;
1401   guint64 rpos;
1402   GstFlowReturn ret = GST_FLOW_OK;
1403
1404   /* allocate the output buffer of the requested size */
1405   if (*buffer == NULL)
1406     buf = gst_buffer_new_allocate (NULL, length, NULL);
1407   else
1408     buf = *buffer;
1409
1410   gst_buffer_map (buf, &info, GST_MAP_WRITE);
1411   data = info.data;
1412
1413   GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1414       offset);
1415
1416   rpos = offset;
1417   rb_size = queue->ring_buffer_max_size;
1418   max_size = QUEUE_MAX_BYTES (queue);
1419
1420   remaining = length;
1421   while (remaining > 0) {
1422     /* configure how much/whether to read */
1423     if (!gst_queue2_have_data (queue, rpos, remaining)) {
1424       read_length = 0;
1425
1426       if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1427         guint64 level;
1428
1429         /* calculate how far away the offset is */
1430 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1431         if (queue->read->writing_pos > rpos)
1432           level = queue->read->writing_pos - rpos;
1433 #else
1434         if (queue->current->writing_pos > rpos)
1435           level = queue->current->writing_pos - rpos;
1436 #endif
1437         else
1438           level = 0;
1439
1440         GST_DEBUG_OBJECT (queue,
1441             "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1442             ", level %" G_GUINT64_FORMAT ", max %" G_GUINT64_FORMAT,
1443 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1444             rpos, queue->read->writing_pos, level, max_size);
1445 #else
1446             rpos, queue->current->writing_pos, level, max_size);
1447 #endif
1448
1449         if (level >= max_size) {
1450           /* we don't have the data but if we have a ring buffer that is full, we
1451            * need to read */
1452           GST_DEBUG_OBJECT (queue,
1453               "ring buffer full, reading QUEUE_MAX_BYTES %"
1454               G_GUINT64_FORMAT " bytes", max_size);
1455           read_length = max_size;
1456         } else if (queue->is_eos) {
1457           /* won't get any more data so read any data we have */
1458           if (level) {
1459             GST_DEBUG_OBJECT (queue,
1460                 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1461                 level);
1462             read_length = level;
1463             remaining = level;
1464             length = level;
1465           } else
1466             goto hit_eos;
1467         }
1468       }
1469
1470       if (read_length == 0) {
1471         if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1472 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1473           GST_DEBUG_OBJECT (queue,
1474               "update current position [%" G_GUINT64_FORMAT "-%"
1475               G_GUINT64_FORMAT "]", rpos, queue->read->max_reading_pos);
1476           update_cur_pos (queue, queue->read, rpos);
1477 #else
1478           GST_DEBUG_OBJECT (queue,
1479               "update current position [%" G_GUINT64_FORMAT "-%"
1480               G_GUINT64_FORMAT "]", rpos, queue->current->max_reading_pos);
1481           update_cur_pos (queue, queue->current, rpos);
1482 #endif
1483           GST_QUEUE2_SIGNAL_DEL (queue);
1484         }
1485
1486         if (queue->use_buffering)
1487           update_buffering (queue);
1488
1489         GST_DEBUG_OBJECT (queue, "waiting for add");
1490         GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1491         continue;
1492       }
1493     } else {
1494       /* we have the requested data so read it */
1495       read_length = remaining;
1496     }
1497
1498     /* set range reading_pos to actual reading position for this read */
1499 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1500     queue->read->reading_pos = rpos;
1501 #else
1502     queue->current->reading_pos = rpos;
1503 #endif
1504
1505     /* configure how much and from where to read */
1506     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1507       file_offset =
1508 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1509           (queue->read->rb_offset + (rpos -
1510               queue->read->offset)) % rb_size;
1511 #else
1512           (queue->current->rb_offset + (rpos -
1513               queue->current->offset)) % rb_size;
1514 #endif
1515       if (file_offset + read_length > rb_size) {
1516         block_length = rb_size - file_offset;
1517       } else {
1518         block_length = read_length;
1519       }
1520     } else {
1521       file_offset = rpos;
1522       block_length = read_length;
1523     }
1524
1525     /* while we still have data to read, we loop */
1526     while (read_length > 0) {
1527       gint64 read_return;
1528
1529       ret =
1530           gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1531           data, &read_return);
1532       if (ret != GST_FLOW_OK)
1533         goto read_error;
1534
1535       file_offset += read_return;
1536       if (QUEUE_IS_USING_RING_BUFFER (queue))
1537         file_offset %= rb_size;
1538
1539       data += read_return;
1540       read_length -= read_return;
1541       block_length = read_length;
1542       remaining -= read_return;
1543
1544 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1545       rpos = (queue->read->reading_pos += read_return);
1546       update_cur_pos (queue, queue->read, queue->read->reading_pos);
1547 #else
1548       rpos = (queue->current->reading_pos += read_return);
1549       update_cur_pos (queue, queue->current, queue->current->reading_pos);
1550 #endif
1551     }
1552     GST_QUEUE2_SIGNAL_DEL (queue);
1553     GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1554   }
1555
1556   gst_buffer_unmap (buf, &info);
1557   gst_buffer_resize (buf, 0, length);
1558
1559   GST_BUFFER_OFFSET (buf) = offset;
1560   GST_BUFFER_OFFSET_END (buf) = offset + length;
1561
1562   *buffer = buf;
1563
1564   return ret;
1565
1566   /* ERRORS */
1567 hit_eos:
1568   {
1569     GST_DEBUG_OBJECT (queue, "EOS hit and we don't have any requested data");
1570     gst_buffer_unmap (buf, &info);
1571     if (*buffer == NULL)
1572       gst_buffer_unref (buf);
1573     return GST_FLOW_EOS;
1574   }
1575 out_flushing:
1576   {
1577     GST_DEBUG_OBJECT (queue, "we are flushing");
1578     gst_buffer_unmap (buf, &info);
1579     if (*buffer == NULL)
1580       gst_buffer_unref (buf);
1581     return GST_FLOW_FLUSHING;
1582   }
1583 read_error:
1584   {
1585     GST_DEBUG_OBJECT (queue, "we have a read error");
1586     gst_buffer_unmap (buf, &info);
1587     if (*buffer == NULL)
1588       gst_buffer_unref (buf);
1589     return ret;
1590   }
1591 }
1592
1593 /* should be called with QUEUE_LOCK */
1594 static GstMiniObject *
1595 gst_queue2_read_item_from_file (GstQueue2 * queue)
1596 {
1597   GstMiniObject *item;
1598
1599   if (queue->stream_start_event != NULL) {
1600     item = GST_MINI_OBJECT_CAST (queue->stream_start_event);
1601     queue->stream_start_event = NULL;
1602   } else if (queue->starting_segment != NULL) {
1603     item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1604     queue->starting_segment = NULL;
1605   } else {
1606     GstFlowReturn ret;
1607     GstBuffer *buffer = NULL;
1608     guint64 reading_pos;
1609
1610 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
1611     reading_pos = queue->read->reading_pos;
1612 #else
1613     reading_pos = queue->current->reading_pos;
1614 #endif
1615
1616     ret =
1617         gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1618         &buffer);
1619
1620     switch (ret) {
1621       case GST_FLOW_OK:
1622         item = GST_MINI_OBJECT_CAST (buffer);
1623         break;
1624       case GST_FLOW_EOS:
1625         item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1626         break;
1627       default:
1628         item = NULL;
1629         break;
1630     }
1631   }
1632   return item;
1633 }
1634
1635 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1636  * the temp filename. */
1637 static gboolean
1638 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1639 {
1640   gint fd = -1;
1641   gchar *name = NULL;
1642
1643   if (queue->temp_file)
1644     goto already_opened;
1645
1646   GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1647
1648   /* If temp_template was set, allocate a filename and open that filen */
1649
1650   /* nothing to do */
1651   if (queue->temp_template == NULL)
1652     goto no_directory;
1653
1654   /* make copy of the template, we don't want to change this */
1655   name = g_strdup (queue->temp_template);
1656   fd = g_mkstemp (name);
1657   if (fd == -1)
1658     goto mkstemp_failed;
1659
1660   /* open the file for update/writing */
1661   queue->temp_file = fdopen (fd, "wb+");
1662   /* error creating file */
1663   if (queue->temp_file == NULL)
1664     goto open_failed;
1665
1666   g_free (queue->temp_location);
1667   queue->temp_location = name;
1668
1669   GST_QUEUE2_MUTEX_UNLOCK (queue);
1670
1671   /* we can't emit the notify with the lock */
1672   g_object_notify (G_OBJECT (queue), "temp-location");
1673
1674   GST_QUEUE2_MUTEX_LOCK (queue);
1675
1676   GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1677
1678   return TRUE;
1679
1680   /* ERRORS */
1681 already_opened:
1682   {
1683     GST_DEBUG_OBJECT (queue, "temp file was already open");
1684     return TRUE;
1685   }
1686 no_directory:
1687   {
1688     GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1689         (_("No Temp directory specified.")), (NULL));
1690     return FALSE;
1691   }
1692 mkstemp_failed:
1693   {
1694     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1695         (_("Could not create temp file \"%s\"."), queue->temp_template),
1696         GST_ERROR_SYSTEM);
1697     g_free (name);
1698     return FALSE;
1699   }
1700 open_failed:
1701   {
1702     GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1703         (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1704     g_free (name);
1705     if (fd != -1)
1706       close (fd);
1707     return FALSE;
1708   }
1709 }
1710
1711 static void
1712 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1713 {
1714   /* nothing to do */
1715   if (queue->temp_file == NULL)
1716     return;
1717
1718   GST_DEBUG_OBJECT (queue, "closing temp file");
1719
1720   fflush (queue->temp_file);
1721   fclose (queue->temp_file);
1722
1723   if (queue->temp_remove) {
1724     if (remove (queue->temp_location) < 0) {
1725       GST_WARNING_OBJECT (queue, "Failed to remove temporary file %s: %s",
1726           queue->temp_location, g_strerror (errno));
1727     }
1728   }
1729
1730   queue->temp_file = NULL;
1731   clean_ranges (queue);
1732 }
1733
1734 static void
1735 gst_queue2_flush_temp_file (GstQueue2 * queue)
1736 {
1737   if (queue->temp_file == NULL)
1738     return;
1739
1740   GST_DEBUG_OBJECT (queue, "flushing temp file");
1741
1742   queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1743 }
1744
1745 static void
1746 gst_queue2_locked_flush (GstQueue2 * queue, gboolean full, gboolean clear_temp)
1747 {
1748   if (!QUEUE_IS_USING_QUEUE (queue)) {
1749     if (QUEUE_IS_USING_TEMP_FILE (queue) && clear_temp)
1750       gst_queue2_flush_temp_file (queue);
1751     init_ranges (queue);
1752   } else {
1753     while (!g_queue_is_empty (&queue->queue)) {
1754       GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
1755
1756       if (!full && qitem->type == GST_QUEUE2_ITEM_TYPE_EVENT
1757           && GST_EVENT_IS_STICKY (qitem->item)
1758           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_SEGMENT
1759           && GST_EVENT_TYPE (qitem->item) != GST_EVENT_EOS) {
1760         gst_pad_store_sticky_event (queue->srcpad,
1761             GST_EVENT_CAST (qitem->item));
1762       }
1763
1764       /* Then lose another reference because we are supposed to destroy that
1765          data when flushing */
1766       if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
1767         gst_mini_object_unref (qitem->item);
1768       g_slice_free (GstQueue2Item, qitem);
1769     }
1770   }
1771   queue->last_query = FALSE;
1772   g_cond_signal (&queue->query_handled);
1773   GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1774   gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1775   gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1776   queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1777   queue->sink_tainted = queue->src_tainted = TRUE;
1778   if (queue->starting_segment != NULL)
1779     gst_event_unref (queue->starting_segment);
1780   queue->starting_segment = NULL;
1781   queue->segment_event_received = FALSE;
1782   gst_event_replace (&queue->stream_start_event, NULL);
1783
1784   /* we deleted a lot of something */
1785   GST_QUEUE2_SIGNAL_DEL (queue);
1786 }
1787
1788 static gboolean
1789 gst_queue2_wait_free_space (GstQueue2 * queue)
1790 {
1791   /* We make space available if we're "full" according to whatever
1792    * the user defined as "full". */
1793   if (gst_queue2_is_filled (queue)) {
1794     gboolean started;
1795
1796     /* pause the timer while we wait. The fact that we are waiting does not mean
1797      * the byterate on the input pad is lower */
1798     if ((started = queue->in_timer_started))
1799       g_timer_stop (queue->in_timer);
1800
1801     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1802         "queue is full, waiting for free space");
1803     do {
1804       /* Wait for space to be available, we could be unlocked because of a flush. */
1805       GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1806     }
1807     while (gst_queue2_is_filled (queue));
1808
1809     /* and continue if we were running before */
1810     if (started)
1811       g_timer_continue (queue->in_timer);
1812   }
1813   return TRUE;
1814
1815   /* ERRORS */
1816 out_flushing:
1817   {
1818     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1819     return FALSE;
1820   }
1821 }
1822
1823 static gboolean
1824 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1825 {
1826   GstMapInfo info;
1827   guint8 *data, *ring_buffer;
1828   guint size, rb_size;
1829   guint64 writing_pos, new_writing_pos;
1830   GstQueue2Range *range, *prev, *next;
1831   gboolean do_seek = FALSE;
1832
1833   if (QUEUE_IS_USING_RING_BUFFER (queue))
1834     writing_pos = queue->current->rb_writing_pos;
1835   else
1836     writing_pos = queue->current->writing_pos;
1837   ring_buffer = queue->ring_buffer;
1838   rb_size = queue->ring_buffer_max_size;
1839
1840   gst_buffer_map (buffer, &info, GST_MAP_READ);
1841
1842   size = info.size;
1843   data = info.data;
1844
1845   GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1846       writing_pos);
1847
1848   /* sanity check */
1849   if (GST_BUFFER_OFFSET_IS_VALID (buffer) &&
1850       GST_BUFFER_OFFSET (buffer) != queue->current->writing_pos) {
1851     GST_WARNING_OBJECT (queue, "buffer offset does not match current writing "
1852         "position! %" G_GINT64_FORMAT " != %" G_GINT64_FORMAT,
1853         GST_BUFFER_OFFSET (buffer), queue->current->writing_pos);
1854   }
1855
1856   while (size > 0) {
1857     guint to_write;
1858
1859     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1860       gint64 space;
1861
1862       /* calculate the space in the ring buffer not used by data from
1863        * the current range */
1864       while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1865         /* wait until there is some free space */
1866         GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1867       }
1868       /* get the amount of space we have */
1869       space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1870
1871       /* calculate if we need to split or if we can write the entire
1872        * buffer now */
1873       to_write = MIN (size, space);
1874
1875       /* the writing position in the ring buffer after writing (part
1876        * or all of) the buffer */
1877       new_writing_pos = (writing_pos + to_write) % rb_size;
1878
1879       prev = NULL;
1880       range = queue->ranges;
1881
1882       /* if we need to overwrite data in the ring buffer, we need to
1883        * update the ranges
1884        *
1885        * warning: this code is complicated and includes some
1886        * simplifications - pen, paper and diagrams for the cases
1887        * recommended! */
1888       while (range) {
1889         guint64 range_data_start, range_data_end;
1890         GstQueue2Range *range_to_destroy = NULL;
1891
1892         range_data_start = range->rb_offset;
1893         range_data_end = range->rb_writing_pos;
1894
1895         /* handle the special case where the range has no data in it */
1896         if (range->writing_pos == range->offset) {
1897           if (range != queue->current) {
1898             GST_DEBUG_OBJECT (queue,
1899                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1900                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1901             /* remove range */
1902             range_to_destroy = range;
1903             if (prev)
1904               prev->next = range->next;
1905           }
1906           goto next_range;
1907         }
1908
1909         if (range_data_end > range_data_start) {
1910           if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1911             goto next_range;
1912
1913           if (new_writing_pos > range_data_start) {
1914             if (new_writing_pos >= range_data_end) {
1915               GST_DEBUG_OBJECT (queue,
1916                   "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1917                   G_GUINT64_FORMAT, range->offset, range->writing_pos);
1918               /* remove range */
1919               range_to_destroy = range;
1920               if (prev)
1921                 prev->next = range->next;
1922             } else {
1923               GST_DEBUG_OBJECT (queue,
1924                   "advancing offsets from %" G_GUINT64_FORMAT " (%"
1925                   G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1926                   G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1927                   range->offset + new_writing_pos - range_data_start,
1928                   new_writing_pos);
1929               range->offset += (new_writing_pos - range_data_start);
1930               range->rb_offset = new_writing_pos;
1931             }
1932           }
1933         } else {
1934           guint64 new_wpos_virt = writing_pos + to_write;
1935
1936           if (new_wpos_virt <= range_data_start)
1937             goto next_range;
1938
1939           if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1940             GST_DEBUG_OBJECT (queue,
1941                 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1942                 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1943             /* remove range */
1944             range_to_destroy = range;
1945             if (prev)
1946               prev->next = range->next;
1947           } else {
1948             GST_DEBUG_OBJECT (queue,
1949                 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1950                 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1951                 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1952                 range->offset + new_writing_pos - range_data_start,
1953                 new_writing_pos);
1954             range->offset += (new_wpos_virt - range_data_start);
1955             range->rb_offset = new_writing_pos;
1956           }
1957         }
1958
1959       next_range:
1960         if (!range_to_destroy)
1961           prev = range;
1962
1963         range = range->next;
1964         if (range_to_destroy) {
1965           if (range_to_destroy == queue->ranges)
1966             queue->ranges = range;
1967           g_slice_free (GstQueue2Range, range_to_destroy);
1968           range_to_destroy = NULL;
1969         }
1970       }
1971     } else {
1972       to_write = size;
1973       new_writing_pos = writing_pos + to_write;
1974     }
1975
1976     if (QUEUE_IS_USING_TEMP_FILE (queue)
1977         && FSEEK_FILE (queue->temp_file, writing_pos))
1978       goto seek_failed;
1979
1980     if (new_writing_pos > writing_pos) {
1981       GST_INFO_OBJECT (queue,
1982           "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1983           "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1984           queue->current->writing_pos, queue->current->rb_writing_pos);
1985       /* either not using ring buffer or no wrapping, just write */
1986       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1987         if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1988           goto handle_error;
1989       } else {
1990         memcpy (ring_buffer + writing_pos, data, to_write);
1991       }
1992
1993       if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1994         /* try to merge with next range */
1995         while ((next = queue->current->next)) {
1996           GST_INFO_OBJECT (queue,
1997               "checking merge with next range %" G_GUINT64_FORMAT " < %"
1998               G_GUINT64_FORMAT, new_writing_pos, next->offset);
1999           if (new_writing_pos < next->offset)
2000             break;
2001
2002           GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
2003               next->writing_pos);
2004
2005           /* remove the group */
2006           queue->current->next = next->next;
2007
2008           /* We use the threshold to decide if we want to do a seek or simply
2009            * read the data again. If there is not so much data in the range we
2010            * prefer to avoid to seek and read it again. */
2011           if (next->writing_pos > new_writing_pos + get_seek_threshold (queue)) {
2012             /* the new range had more data than the threshold, it's worth keeping
2013              * it and doing a seek. */
2014             new_writing_pos = next->writing_pos;
2015             do_seek = TRUE;
2016           }
2017           g_slice_free (GstQueue2Range, next);
2018         }
2019         goto update_and_signal;
2020       }
2021     } else {
2022       /* wrapping */
2023       guint block_one, block_two;
2024
2025       block_one = rb_size - writing_pos;
2026       block_two = to_write - block_one;
2027
2028       if (block_one > 0) {
2029         GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
2030         /* write data to end of ring buffer */
2031         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2032           if (fwrite (data, block_one, 1, queue->temp_file) != 1)
2033             goto handle_error;
2034         } else {
2035           memcpy (ring_buffer + writing_pos, data, block_one);
2036         }
2037       }
2038
2039       if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
2040         goto seek_failed;
2041
2042       if (block_two > 0) {
2043         GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
2044         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2045           if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
2046             goto handle_error;
2047         } else {
2048           memcpy (ring_buffer, data + block_one, block_two);
2049         }
2050       }
2051     }
2052
2053   update_and_signal:
2054     /* update the writing positions */
2055     size -= to_write;
2056     GST_INFO_OBJECT (queue,
2057         "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
2058         to_write, writing_pos, size);
2059
2060     if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2061       data += to_write;
2062       queue->current->writing_pos += to_write;
2063       queue->current->rb_writing_pos = writing_pos = new_writing_pos;
2064     } else {
2065       queue->current->writing_pos = writing_pos = new_writing_pos;
2066 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
2067       if (do_seek) {
2068         if (queue->upstream_size == 0 || new_writing_pos < queue->upstream_size)
2069           perform_seek_to_offset (queue, new_writing_pos);
2070         else
2071           queue->is_eos = TRUE;
2072       }
2073 #endif
2074     }
2075
2076 #ifndef TIZEN_FEATURE_QUEUE2_MODIFICATION
2077     if (do_seek)
2078       perform_seek_to_offset (queue, new_writing_pos);
2079 #endif
2080
2081     update_cur_level (queue, queue->current);
2082
2083     /* update the buffering status */
2084     if (queue->use_buffering)
2085       update_buffering (queue);
2086
2087     GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
2088         queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
2089
2090     GST_QUEUE2_SIGNAL_ADD (queue);
2091   }
2092
2093   gst_buffer_unmap (buffer, &info);
2094
2095   return TRUE;
2096
2097   /* ERRORS */
2098 out_flushing:
2099   {
2100     GST_DEBUG_OBJECT (queue, "we are flushing");
2101     gst_buffer_unmap (buffer, &info);
2102     /* FIXME - GST_FLOW_EOS ? */
2103     return FALSE;
2104   }
2105 seek_failed:
2106   {
2107     GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
2108     gst_buffer_unmap (buffer, &info);
2109     return FALSE;
2110   }
2111 handle_error:
2112   {
2113     switch (errno) {
2114       case ENOSPC:{
2115         GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
2116         break;
2117       }
2118       default:{
2119         GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
2120             (_("Error while writing to download file.")),
2121             ("%s", g_strerror (errno)));
2122       }
2123     }
2124     gst_buffer_unmap (buffer, &info);
2125     return FALSE;
2126   }
2127 }
2128
2129 static gboolean
2130 buffer_list_create_write (GstBuffer ** buf, guint idx, gpointer q)
2131 {
2132   GstQueue2 *queue = q;
2133
2134   GST_TRACE_OBJECT (queue,
2135       "writing buffer %u of size %" G_GSIZE_FORMAT " bytes", idx,
2136       gst_buffer_get_size (*buf));
2137
2138   if (!gst_queue2_create_write (queue, *buf)) {
2139     GST_INFO_OBJECT (queue, "create_write() returned FALSE, bailing out");
2140     return FALSE;
2141   }
2142   return TRUE;
2143 }
2144
2145 static gboolean
2146 buffer_list_calc_size (GstBuffer ** buf, guint idx, gpointer data)
2147 {
2148   guint *p_size = data;
2149   gsize buf_size;
2150
2151   buf_size = gst_buffer_get_size (*buf);
2152   GST_TRACE ("buffer %u in has size %" G_GSIZE_FORMAT, idx, buf_size);
2153   *p_size += buf_size;
2154   return TRUE;
2155 }
2156
2157 /* enqueue an item an update the level stats */
2158 static void
2159 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item,
2160     GstQueue2ItemType item_type)
2161 {
2162   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2163     GstBuffer *buffer;
2164     guint size;
2165
2166     buffer = GST_BUFFER_CAST (item);
2167     size = gst_buffer_get_size (buffer);
2168
2169     /* add buffer to the statistics */
2170     if (QUEUE_IS_USING_QUEUE (queue)) {
2171       queue->cur_level.buffers++;
2172       queue->cur_level.bytes += size;
2173     }
2174     queue->bytes_in += size;
2175
2176     /* apply new buffer to segment stats */
2177     apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
2178     /* update the byterate stats */
2179     update_in_rates (queue);
2180
2181     if (!QUEUE_IS_USING_QUEUE (queue)) {
2182       /* FIXME - check return value? */
2183       gst_queue2_create_write (queue, buffer);
2184     }
2185   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2186     GstBufferList *buffer_list;
2187     guint size = 0;
2188
2189     buffer_list = GST_BUFFER_LIST_CAST (item);
2190
2191     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2192     GST_LOG_OBJECT (queue, "total size of buffer list: %u bytes", size);
2193
2194     /* add buffer to the statistics */
2195     if (QUEUE_IS_USING_QUEUE (queue)) {
2196       queue->cur_level.buffers += gst_buffer_list_length (buffer_list);
2197       queue->cur_level.bytes += size;
2198     }
2199     queue->bytes_in += size;
2200
2201     /* apply new buffer to segment stats */
2202     apply_buffer_list (queue, buffer_list, &queue->sink_segment, TRUE);
2203
2204     /* update the byterate stats */
2205     update_in_rates (queue);
2206
2207     if (!QUEUE_IS_USING_QUEUE (queue)) {
2208       gst_buffer_list_foreach (buffer_list, buffer_list_create_write, queue);
2209     }
2210   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2211     GstEvent *event;
2212
2213     event = GST_EVENT_CAST (item);
2214
2215     switch (GST_EVENT_TYPE (event)) {
2216       case GST_EVENT_EOS:
2217         /* Zero the thresholds, this makes sure the queue is completely
2218          * filled and we can read all data from the queue. */
2219         GST_DEBUG_OBJECT (queue, "we have EOS");
2220         queue->is_eos = TRUE;
2221         break;
2222       case GST_EVENT_SEGMENT:
2223         apply_segment (queue, event, &queue->sink_segment, TRUE);
2224         /* This is our first new segment, we hold it
2225          * as we can't save it on the temp file */
2226         if (!QUEUE_IS_USING_QUEUE (queue)) {
2227           if (queue->segment_event_received)
2228             goto unexpected_event;
2229
2230           queue->segment_event_received = TRUE;
2231           if (queue->starting_segment != NULL)
2232             gst_event_unref (queue->starting_segment);
2233           queue->starting_segment = event;
2234           item = NULL;
2235         }
2236         /* a new segment allows us to accept more buffers if we got EOS
2237          * from downstream */
2238         queue->unexpected = FALSE;
2239         break;
2240       case GST_EVENT_GAP:
2241         apply_gap (queue, event, &queue->sink_segment, TRUE);
2242         break;
2243       case GST_EVENT_STREAM_START:
2244         if (!QUEUE_IS_USING_QUEUE (queue)) {
2245           gst_event_replace (&queue->stream_start_event, event);
2246           gst_event_unref (event);
2247           item = NULL;
2248         }
2249         break;
2250       case GST_EVENT_CAPS:{
2251         GstCaps *caps;
2252
2253         gst_event_parse_caps (event, &caps);
2254         GST_INFO ("got caps: %" GST_PTR_FORMAT, caps);
2255
2256         if (!QUEUE_IS_USING_QUEUE (queue)) {
2257           GST_LOG ("Dropping caps event, not using queue");
2258           gst_event_unref (event);
2259           item = NULL;
2260         }
2261         break;
2262       }
2263       default:
2264         if (!QUEUE_IS_USING_QUEUE (queue))
2265           goto unexpected_event;
2266         break;
2267     }
2268   } else if (GST_IS_QUERY (item)) {
2269     /* Can't happen as we check that in the caller */
2270     if (!QUEUE_IS_USING_QUEUE (queue))
2271       g_assert_not_reached ();
2272   } else {
2273     g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
2274         item, GST_OBJECT_NAME (queue));
2275     /* we can't really unref since we don't know what it is */
2276     item = NULL;
2277   }
2278
2279   if (item) {
2280     /* update the buffering status */
2281     if (queue->use_buffering)
2282       update_buffering (queue);
2283
2284     if (QUEUE_IS_USING_QUEUE (queue)) {
2285       GstQueue2Item *qitem = g_slice_new (GstQueue2Item);
2286       qitem->type = item_type;
2287       qitem->item = item;
2288       g_queue_push_tail (&queue->queue, qitem);
2289     } else {
2290       gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
2291     }
2292
2293     GST_QUEUE2_SIGNAL_ADD (queue);
2294   }
2295
2296   return;
2297
2298   /* ERRORS */
2299 unexpected_event:
2300   {
2301     g_warning
2302         ("Unexpected event of kind %s can't be added in temp file of queue %s ",
2303         gst_event_type_get_name (GST_EVENT_TYPE (item)),
2304         GST_OBJECT_NAME (queue));
2305     gst_event_unref (GST_EVENT_CAST (item));
2306     return;
2307   }
2308 }
2309
2310 /* dequeue an item from the queue and update level stats */
2311 static GstMiniObject *
2312 gst_queue2_locked_dequeue (GstQueue2 * queue, GstQueue2ItemType * item_type)
2313 {
2314   GstMiniObject *item;
2315
2316   if (!QUEUE_IS_USING_QUEUE (queue)) {
2317     item = gst_queue2_read_item_from_file (queue);
2318   } else {
2319     GstQueue2Item *qitem = g_queue_pop_head (&queue->queue);
2320
2321     if (qitem == NULL)
2322       goto no_item;
2323
2324     item = qitem->item;
2325     g_slice_free (GstQueue2Item, qitem);
2326   }
2327
2328   if (item == NULL)
2329     goto no_item;
2330
2331   if (GST_IS_BUFFER (item)) {
2332     GstBuffer *buffer;
2333     guint size;
2334
2335     buffer = GST_BUFFER_CAST (item);
2336     size = gst_buffer_get_size (buffer);
2337     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER;
2338
2339     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2340         "retrieved buffer %p from queue", buffer);
2341
2342     if (QUEUE_IS_USING_QUEUE (queue)) {
2343       queue->cur_level.buffers--;
2344       queue->cur_level.bytes -= size;
2345     }
2346     queue->bytes_out += size;
2347
2348     apply_buffer (queue, buffer, &queue->src_segment, FALSE);
2349     /* update the byterate stats */
2350     update_out_rates (queue);
2351     /* update the buffering */
2352     if (queue->use_buffering)
2353       update_buffering (queue);
2354
2355   } else if (GST_IS_EVENT (item)) {
2356     GstEvent *event = GST_EVENT_CAST (item);
2357
2358     *item_type = GST_QUEUE2_ITEM_TYPE_EVENT;
2359
2360     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2361         "retrieved event %p from queue", event);
2362
2363     switch (GST_EVENT_TYPE (event)) {
2364       case GST_EVENT_EOS:
2365         /* queue is empty now that we dequeued the EOS */
2366         GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
2367         break;
2368       case GST_EVENT_SEGMENT:
2369         apply_segment (queue, event, &queue->src_segment, FALSE);
2370         break;
2371       case GST_EVENT_GAP:
2372         apply_gap (queue, event, &queue->src_segment, FALSE);
2373         break;
2374       default:
2375         break;
2376     }
2377   } else if (GST_IS_BUFFER_LIST (item)) {
2378     GstBufferList *buffer_list;
2379     guint size = 0;
2380
2381     buffer_list = GST_BUFFER_LIST_CAST (item);
2382     gst_buffer_list_foreach (buffer_list, buffer_list_calc_size, &size);
2383     *item_type = GST_QUEUE2_ITEM_TYPE_BUFFER_LIST;
2384
2385     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2386         "retrieved buffer list %p from queue", buffer_list);
2387
2388     if (QUEUE_IS_USING_QUEUE (queue)) {
2389       queue->cur_level.buffers -= gst_buffer_list_length (buffer_list);
2390       queue->cur_level.bytes -= size;
2391     }
2392     queue->bytes_out += size;
2393
2394     apply_buffer_list (queue, buffer_list, &queue->src_segment, FALSE);
2395     /* update the byterate stats */
2396     update_out_rates (queue);
2397     /* update the buffering */
2398     if (queue->use_buffering)
2399       update_buffering (queue);
2400   } else if (GST_IS_QUERY (item)) {
2401     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2402         "retrieved query %p from queue", item);
2403     *item_type = GST_QUEUE2_ITEM_TYPE_QUERY;
2404   } else {
2405     g_warning
2406         ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
2407         item, GST_OBJECT_NAME (queue));
2408     item = NULL;
2409     *item_type = GST_QUEUE2_ITEM_TYPE_UNKNOWN;
2410   }
2411   GST_QUEUE2_SIGNAL_DEL (queue);
2412
2413   return item;
2414
2415   /* ERRORS */
2416 no_item:
2417   {
2418     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
2419     return NULL;
2420   }
2421 }
2422
2423 static gboolean
2424 gst_queue2_handle_sink_event (GstPad * pad, GstObject * parent,
2425     GstEvent * event)
2426 {
2427   gboolean ret = TRUE;
2428   GstQueue2 *queue;
2429
2430   queue = GST_QUEUE2 (parent);
2431
2432   switch (GST_EVENT_TYPE (event)) {
2433     case GST_EVENT_FLUSH_START:
2434     {
2435       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
2436       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2437         /* forward event */
2438         ret = gst_pad_push_event (queue->srcpad, event);
2439
2440         /* now unblock the chain function */
2441         GST_QUEUE2_MUTEX_LOCK (queue);
2442         queue->srcresult = GST_FLOW_FLUSHING;
2443         queue->sinkresult = GST_FLOW_FLUSHING;
2444         /* unblock the loop and chain functions */
2445         GST_QUEUE2_SIGNAL_ADD (queue);
2446         GST_QUEUE2_SIGNAL_DEL (queue);
2447         queue->last_query = FALSE;
2448         g_cond_signal (&queue->query_handled);
2449         GST_QUEUE2_MUTEX_UNLOCK (queue);
2450
2451         /* make sure it pauses, this should happen since we sent
2452          * flush_start downstream. */
2453         gst_pad_pause_task (queue->srcpad);
2454         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
2455       } else {
2456         GST_QUEUE2_MUTEX_LOCK (queue);
2457         /* flush the sink pad */
2458         queue->sinkresult = GST_FLOW_FLUSHING;
2459         GST_QUEUE2_SIGNAL_DEL (queue);
2460         queue->last_query = FALSE;
2461         g_cond_signal (&queue->query_handled);
2462         GST_QUEUE2_MUTEX_UNLOCK (queue);
2463
2464         gst_event_unref (event);
2465       }
2466       break;
2467     }
2468     case GST_EVENT_FLUSH_STOP:
2469     {
2470       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2471
2472       if (GST_PAD_MODE (queue->srcpad) == GST_PAD_MODE_PUSH) {
2473         /* forward event */
2474         ret = gst_pad_push_event (queue->srcpad, event);
2475
2476         GST_QUEUE2_MUTEX_LOCK (queue);
2477         gst_queue2_locked_flush (queue, FALSE, TRUE);
2478         queue->srcresult = GST_FLOW_OK;
2479         queue->sinkresult = GST_FLOW_OK;
2480         queue->is_eos = FALSE;
2481         queue->unexpected = FALSE;
2482         queue->seeking = FALSE;
2483         /* reset rate counters */
2484         reset_rate_timer (queue);
2485         gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2486             queue->srcpad, NULL);
2487         GST_QUEUE2_MUTEX_UNLOCK (queue);
2488       } else {
2489         GST_QUEUE2_MUTEX_LOCK (queue);
2490         queue->segment_event_received = FALSE;
2491         queue->is_eos = FALSE;
2492         queue->unexpected = FALSE;
2493         queue->sinkresult = GST_FLOW_OK;
2494         queue->seeking = FALSE;
2495         GST_QUEUE2_MUTEX_UNLOCK (queue);
2496
2497         gst_event_unref (event);
2498       }
2499       break;
2500     }
2501     default:
2502       if (GST_EVENT_IS_SERIALIZED (event)) {
2503         /* serialized events go in the queue */
2504         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2505         if (queue->srcresult != GST_FLOW_OK) {
2506           /* Errors in sticky event pushing are no problem and ignored here
2507            * as they will cause more meaningful errors during data flow.
2508            * For EOS events, that are not followed by data flow, we still
2509            * return FALSE here though and report an error.
2510            */
2511           if (!GST_EVENT_IS_STICKY (event)) {
2512             goto out_flow_error;
2513           } else if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
2514             if (queue->srcresult == GST_FLOW_NOT_LINKED
2515                 || queue->srcresult < GST_FLOW_EOS) {
2516               GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2517                   (_("Internal data flow error.")),
2518                   ("streaming task paused, reason %s (%d)",
2519                       gst_flow_get_name (queue->srcresult), queue->srcresult));
2520             }
2521             goto out_flow_error;
2522           }
2523         }
2524         /* refuse more events on EOS */
2525         if (queue->is_eos)
2526           goto out_eos;
2527         gst_queue2_locked_enqueue (queue, event, GST_QUEUE2_ITEM_TYPE_EVENT);
2528         GST_QUEUE2_MUTEX_UNLOCK (queue);
2529         gst_queue2_post_buffering (queue);
2530       } else {
2531         /* non-serialized events are passed upstream. */
2532         ret = gst_pad_push_event (queue->srcpad, event);
2533       }
2534       break;
2535   }
2536   return ret;
2537
2538   /* ERRORS */
2539 out_flushing:
2540   {
2541     GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2542     GST_QUEUE2_MUTEX_UNLOCK (queue);
2543     gst_event_unref (event);
2544     return FALSE;
2545   }
2546 out_eos:
2547   {
2548     GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2549     GST_QUEUE2_MUTEX_UNLOCK (queue);
2550     gst_event_unref (event);
2551     return FALSE;
2552   }
2553 out_flow_error:
2554   {
2555     GST_LOG_OBJECT (queue,
2556         "refusing event, we have a downstream flow error: %s",
2557         gst_flow_get_name (queue->srcresult));
2558     GST_QUEUE2_MUTEX_UNLOCK (queue);
2559     gst_event_unref (event);
2560     return FALSE;
2561   }
2562 }
2563
2564 static gboolean
2565 gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
2566     GstQuery * query)
2567 {
2568   GstQueue2 *queue;
2569   gboolean res;
2570
2571   queue = GST_QUEUE2 (parent);
2572
2573   switch (GST_QUERY_TYPE (query)) {
2574     default:
2575       if (GST_QUERY_IS_SERIALIZED (query)) {
2576         GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received query %p", query);
2577         /* serialized events go in the queue. We need to be certain that we
2578          * don't cause deadlocks waiting for the query return value. We check if
2579          * the queue is empty (nothing is blocking downstream and the query can
2580          * be pushed for sure) or we are not buffering. If we are buffering,
2581          * the pipeline waits to unblock downstream until our queue fills up
2582          * completely, which can not happen if we block on the query..
2583          * Therefore we only potentially block when we are not buffering. */
2584         GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2585         if (QUEUE_IS_USING_QUEUE (queue) && (gst_queue2_is_empty (queue)
2586                 || !queue->use_buffering)) {
2587           if (!g_atomic_int_get (&queue->downstream_may_block)) {
2588             gst_queue2_locked_enqueue (queue, query,
2589                 GST_QUEUE2_ITEM_TYPE_QUERY);
2590
2591             STATUS (queue, queue->sinkpad, "wait for QUERY");
2592             g_cond_wait (&queue->query_handled, &queue->qlock);
2593             if (queue->sinkresult != GST_FLOW_OK)
2594               goto out_flushing;
2595             res = queue->last_query;
2596           } else {
2597             GST_DEBUG_OBJECT (queue, "refusing query, downstream might block");
2598             res = FALSE;
2599           }
2600         } else {
2601           GST_DEBUG_OBJECT (queue,
2602               "refusing query, we are not using the queue");
2603           res = FALSE;
2604         }
2605         GST_QUEUE2_MUTEX_UNLOCK (queue);
2606         gst_queue2_post_buffering (queue);
2607       } else {
2608         res = gst_pad_query_default (pad, parent, query);
2609       }
2610       break;
2611   }
2612   return res;
2613
2614   /* ERRORS */
2615 out_flushing:
2616   {
2617     GST_DEBUG_OBJECT (queue, "refusing query, we are flushing");
2618     GST_QUEUE2_MUTEX_UNLOCK (queue);
2619     return FALSE;
2620   }
2621 }
2622
2623 static gboolean
2624 gst_queue2_is_empty (GstQueue2 * queue)
2625 {
2626   /* never empty on EOS */
2627   if (queue->is_eos)
2628     return FALSE;
2629
2630   if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2631     return queue->current->writing_pos <= queue->current->max_reading_pos;
2632   } else {
2633     if (queue->queue.length == 0)
2634       return TRUE;
2635   }
2636
2637   return FALSE;
2638 }
2639
2640 static gboolean
2641 gst_queue2_is_filled (GstQueue2 * queue)
2642 {
2643   gboolean res;
2644
2645   /* always filled on EOS */
2646   if (queue->is_eos)
2647     return TRUE;
2648
2649 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2650     (queue->cur_level.format) >= ((alt_max) ? \
2651       MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2652
2653   /* if using a ring buffer we're filled if all ring buffer space is used
2654    * _by the current range_ */
2655   if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2656     guint64 rb_size = queue->ring_buffer_max_size;
2657     GST_DEBUG_OBJECT (queue,
2658         "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2659         queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2660     return CHECK_FILLED (bytes, rb_size);
2661   }
2662
2663   /* if using file, we're never filled if we don't have EOS */
2664   if (QUEUE_IS_USING_TEMP_FILE (queue))
2665     return FALSE;
2666
2667   /* we are never filled when we have no buffers at all */
2668   if (queue->cur_level.buffers == 0)
2669     return FALSE;
2670
2671   /* we are filled if one of the current levels exceeds the max */
2672   res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2673       || CHECK_FILLED (time, 0);
2674
2675   /* if we need to, use the rate estimate to check against the max time we are
2676    * allowed to queue */
2677   if (queue->use_rate_estimate)
2678     res |= CHECK_FILLED (rate_time, 0);
2679
2680 #undef CHECK_FILLED
2681   return res;
2682 }
2683
2684 static GstFlowReturn
2685 gst_queue2_chain_buffer_or_buffer_list (GstQueue2 * queue,
2686     GstMiniObject * item, GstQueue2ItemType item_type)
2687 {
2688   /* we have to lock the queue since we span threads */
2689   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2690   /* when we received EOS, we refuse more data */
2691   if (queue->is_eos)
2692     goto out_eos;
2693   /* when we received unexpected from downstream, refuse more buffers */
2694   if (queue->unexpected)
2695     goto out_unexpected;
2696
2697   /* while we didn't receive the newsegment, we're seeking and we skip data */
2698   if (queue->seeking)
2699     goto out_seeking;
2700
2701   if (!gst_queue2_wait_free_space (queue))
2702     goto out_flushing;
2703
2704   /* put buffer in queue now */
2705   gst_queue2_locked_enqueue (queue, item, item_type);
2706   GST_QUEUE2_MUTEX_UNLOCK (queue);
2707   gst_queue2_post_buffering (queue);
2708
2709   return GST_FLOW_OK;
2710
2711   /* special conditions */
2712 out_flushing:
2713   {
2714     GstFlowReturn ret = queue->sinkresult;
2715
2716     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2717         "exit because task paused, reason: %s", gst_flow_get_name (ret));
2718     GST_QUEUE2_MUTEX_UNLOCK (queue);
2719     gst_mini_object_unref (item);
2720
2721     return ret;
2722   }
2723 out_eos:
2724   {
2725     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2726     GST_QUEUE2_MUTEX_UNLOCK (queue);
2727     gst_mini_object_unref (item);
2728
2729     return GST_FLOW_EOS;
2730   }
2731 out_seeking:
2732   {
2733     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are seeking");
2734     GST_QUEUE2_MUTEX_UNLOCK (queue);
2735     gst_mini_object_unref (item);
2736
2737     return GST_FLOW_OK;
2738   }
2739 out_unexpected:
2740   {
2741     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2742     GST_QUEUE2_MUTEX_UNLOCK (queue);
2743     gst_mini_object_unref (item);
2744
2745     return GST_FLOW_EOS;
2746   }
2747 }
2748
2749 static GstFlowReturn
2750 gst_queue2_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2751 {
2752   GstQueue2 *queue;
2753
2754   queue = GST_QUEUE2 (parent);
2755
2756   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received buffer %p of "
2757       "size %" G_GSIZE_FORMAT ", time %" GST_TIME_FORMAT ", duration %"
2758       GST_TIME_FORMAT, buffer, gst_buffer_get_size (buffer),
2759       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2760       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2761
2762   return gst_queue2_chain_buffer_or_buffer_list (queue,
2763       GST_MINI_OBJECT_CAST (buffer), GST_QUEUE2_ITEM_TYPE_BUFFER);
2764 }
2765
2766 static GstFlowReturn
2767 gst_queue2_chain_list (GstPad * pad, GstObject * parent,
2768     GstBufferList * buffer_list)
2769 {
2770   GstQueue2 *queue;
2771
2772   queue = GST_QUEUE2 (parent);
2773
2774   GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2775       "received buffer list %p", buffer_list);
2776
2777   return gst_queue2_chain_buffer_or_buffer_list (queue,
2778       GST_MINI_OBJECT_CAST (buffer_list), GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2779 }
2780
2781 static GstMiniObject *
2782 gst_queue2_dequeue_on_eos (GstQueue2 * queue, GstQueue2ItemType * item_type)
2783 {
2784   GstMiniObject *data;
2785
2786   GST_CAT_LOG_OBJECT (queue_dataflow, queue, "got EOS from downstream");
2787
2788   /* stop pushing buffers, we dequeue all items until we see an item that we
2789    * can push again, which is EOS or SEGMENT. If there is nothing in the
2790    * queue we can push, we set a flag to make the sinkpad refuse more
2791    * buffers with an EOS return value until we receive something
2792    * pushable again or we get flushed. */
2793   while ((data = gst_queue2_locked_dequeue (queue, item_type))) {
2794     if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2795       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2796           "dropping EOS buffer %p", data);
2797       gst_buffer_unref (GST_BUFFER_CAST (data));
2798     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2799       GstEvent *event = GST_EVENT_CAST (data);
2800       GstEventType type = GST_EVENT_TYPE (event);
2801
2802       if (type == GST_EVENT_EOS || type == GST_EVENT_SEGMENT) {
2803         /* we found a pushable item in the queue, push it out */
2804         GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2805             "pushing pushable event %s after EOS", GST_EVENT_TYPE_NAME (event));
2806         return data;
2807       }
2808       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2809           "dropping EOS event %p", event);
2810       gst_event_unref (event);
2811     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2812       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2813           "dropping EOS buffer list %p", data);
2814       gst_buffer_list_unref (GST_BUFFER_LIST_CAST (data));
2815     } else if (*item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2816       queue->last_query = FALSE;
2817       g_cond_signal (&queue->query_handled);
2818       GST_CAT_LOG_OBJECT (queue_dataflow, queue, "dropping EOS query %p", data);
2819     }
2820   }
2821   /* no more items in the queue. Set the unexpected flag so that upstream
2822    * make us refuse any more buffers on the sinkpad. Since we will still
2823    * accept EOS and SEGMENT we return _FLOW_OK to the caller so that the
2824    * task function does not shut down. */
2825   queue->unexpected = TRUE;
2826   return NULL;
2827 }
2828
2829 /* dequeue an item from the queue an push it downstream. This functions returns
2830  * the result of the push. */
2831 static GstFlowReturn
2832 gst_queue2_push_one (GstQueue2 * queue)
2833 {
2834   GstFlowReturn result = queue->srcresult;
2835   GstMiniObject *data;
2836   GstQueue2ItemType item_type;
2837
2838   data = gst_queue2_locked_dequeue (queue, &item_type);
2839   if (data == NULL)
2840     goto no_item;
2841
2842 next:
2843   STATUS (queue, queue->srcpad, "We have something dequeud");
2844   g_atomic_int_set (&queue->downstream_may_block,
2845       item_type == GST_QUEUE2_ITEM_TYPE_BUFFER ||
2846       item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST);
2847   GST_QUEUE2_MUTEX_UNLOCK (queue);
2848   gst_queue2_post_buffering (queue);
2849
2850   if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER) {
2851     GstBuffer *buffer;
2852
2853     buffer = GST_BUFFER_CAST (data);
2854
2855     result = gst_pad_push (queue->srcpad, buffer);
2856     g_atomic_int_set (&queue->downstream_may_block, 0);
2857
2858     /* need to check for srcresult here as well */
2859     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2860     if (result == GST_FLOW_EOS) {
2861       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2862       if (data != NULL)
2863         goto next;
2864       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2865        * to the caller so that the task function does not shut down */
2866       result = GST_FLOW_OK;
2867     }
2868   } else if (item_type == GST_QUEUE2_ITEM_TYPE_EVENT) {
2869     GstEvent *event = GST_EVENT_CAST (data);
2870     GstEventType type = GST_EVENT_TYPE (event);
2871
2872     gst_pad_push_event (queue->srcpad, event);
2873
2874     /* if we're EOS, return EOS so that the task pauses. */
2875     if (type == GST_EVENT_EOS) {
2876       GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2877           "pushed EOS event %p, return EOS", event);
2878       result = GST_FLOW_EOS;
2879     }
2880
2881     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2882   } else if (item_type == GST_QUEUE2_ITEM_TYPE_BUFFER_LIST) {
2883     GstBufferList *buffer_list;
2884
2885     buffer_list = GST_BUFFER_LIST_CAST (data);
2886
2887     result = gst_pad_push_list (queue->srcpad, buffer_list);
2888     g_atomic_int_set (&queue->downstream_may_block, 0);
2889
2890     /* need to check for srcresult here as well */
2891     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2892     if (result == GST_FLOW_EOS) {
2893       data = gst_queue2_dequeue_on_eos (queue, &item_type);
2894       if (data != NULL)
2895         goto next;
2896       /* Since we will still accept EOS and SEGMENT we return _FLOW_OK
2897        * to the caller so that the task function does not shut down */
2898       result = GST_FLOW_OK;
2899     }
2900   } else if (item_type == GST_QUEUE2_ITEM_TYPE_QUERY) {
2901     GstQuery *query = GST_QUERY_CAST (data);
2902
2903     GST_LOG_OBJECT (queue->srcpad, "Peering query %p", query);
2904     queue->last_query = gst_pad_peer_query (queue->srcpad, query);
2905     GST_LOG_OBJECT (queue->srcpad, "Peered query");
2906     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2907         "did query %p, return %d", query, queue->last_query);
2908     g_cond_signal (&queue->query_handled);
2909     GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2910     result = GST_FLOW_OK;
2911   }
2912   return result;
2913
2914   /* ERRORS */
2915 no_item:
2916   {
2917     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2918         "exit because we have no item in the queue");
2919     return GST_FLOW_ERROR;
2920   }
2921 out_flushing:
2922   {
2923     GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2924     return GST_FLOW_FLUSHING;
2925   }
2926 }
2927
2928 /* called repeatedly with @pad as the source pad. This function should push out
2929  * data to the peer element. */
2930 static void
2931 gst_queue2_loop (GstPad * pad)
2932 {
2933   GstQueue2 *queue;
2934 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
2935   GstFlowReturn ret = GST_FLOW_OK;
2936 #else
2937   GstFlowReturn ret;
2938 #endif
2939
2940   queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2941
2942   /* have to lock for thread-safety */
2943   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2944
2945   if (gst_queue2_is_empty (queue)) {
2946     gboolean started;
2947
2948     /* pause the timer while we wait. The fact that we are waiting does not mean
2949      * the byterate on the output pad is lower */
2950     if ((started = queue->out_timer_started))
2951       g_timer_stop (queue->out_timer);
2952
2953     GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2954         "queue is empty, waiting for new data");
2955     do {
2956       /* Wait for data to be available, we could be unlocked because of a flush. */
2957       GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2958     }
2959     while (gst_queue2_is_empty (queue));
2960
2961     /* and continue if we were running before */
2962     if (started)
2963       g_timer_continue (queue->out_timer);
2964   }
2965 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
2966   if (!queue->is_buffering) {
2967     ret = gst_queue2_push_one (queue);
2968   }
2969 #else
2970   ret = gst_queue2_push_one (queue);
2971 #endif
2972   queue->srcresult = ret;
2973   queue->sinkresult = ret;
2974   if (ret != GST_FLOW_OK)
2975     goto out_flushing;
2976
2977   GST_QUEUE2_MUTEX_UNLOCK (queue);
2978   gst_queue2_post_buffering (queue);
2979
2980   return;
2981
2982   /* ERRORS */
2983 out_flushing:
2984   {
2985     gboolean eos = queue->is_eos;
2986     GstFlowReturn ret = queue->srcresult;
2987
2988     gst_pad_pause_task (queue->srcpad);
2989     if (ret == GST_FLOW_FLUSHING) {
2990       gst_queue2_locked_flush (queue, FALSE, FALSE);
2991     } else {
2992       GST_QUEUE2_SIGNAL_DEL (queue);
2993       queue->last_query = FALSE;
2994       g_cond_signal (&queue->query_handled);
2995     }
2996     GST_QUEUE2_MUTEX_UNLOCK (queue);
2997     GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2998         "pause task, reason:  %s", gst_flow_get_name (queue->srcresult));
2999     /* let app know about us giving up if upstream is not expected to do so */
3000     /* EOS is already taken care of elsewhere */
3001     if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS)) {
3002       GST_ELEMENT_ERROR (queue, STREAM, FAILED,
3003           (_("Internal data flow error.")),
3004           ("streaming task paused, reason %s (%d)",
3005               gst_flow_get_name (ret), ret));
3006       gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
3007     }
3008     return;
3009   }
3010 }
3011
3012 static gboolean
3013 gst_queue2_handle_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
3014 {
3015   gboolean res = TRUE;
3016   GstQueue2 *queue = GST_QUEUE2 (parent);
3017
3018 #ifndef GST_DISABLE_GST_DEBUG
3019   GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
3020       event, GST_EVENT_TYPE_NAME (event));
3021 #endif
3022
3023   switch (GST_EVENT_TYPE (event)) {
3024     case GST_EVENT_FLUSH_START:
3025       if (QUEUE_IS_USING_QUEUE (queue)) {
3026         /* just forward upstream */
3027         res = gst_pad_push_event (queue->sinkpad, event);
3028       } else {
3029         /* now unblock the getrange function */
3030         GST_QUEUE2_MUTEX_LOCK (queue);
3031         GST_DEBUG_OBJECT (queue, "flushing");
3032         queue->srcresult = GST_FLOW_FLUSHING;
3033         GST_QUEUE2_SIGNAL_ADD (queue);
3034         GST_QUEUE2_MUTEX_UNLOCK (queue);
3035
3036         /* when using a temp file, we eat the event */
3037         res = TRUE;
3038         gst_event_unref (event);
3039       }
3040       break;
3041     case GST_EVENT_FLUSH_STOP:
3042       if (QUEUE_IS_USING_QUEUE (queue)) {
3043         /* just forward upstream */
3044         res = gst_pad_push_event (queue->sinkpad, event);
3045       } else {
3046         /* now unblock the getrange function */
3047         GST_QUEUE2_MUTEX_LOCK (queue);
3048         queue->srcresult = GST_FLOW_OK;
3049         GST_QUEUE2_MUTEX_UNLOCK (queue);
3050
3051         /* when using a temp file, we eat the event */
3052         res = TRUE;
3053         gst_event_unref (event);
3054       }
3055       break;
3056     case GST_EVENT_RECONFIGURE:
3057       GST_QUEUE2_MUTEX_LOCK (queue);
3058       /* assume downstream is linked now and try to push again */
3059       if (queue->srcresult == GST_FLOW_NOT_LINKED) {
3060         queue->srcresult = GST_FLOW_OK;
3061         queue->sinkresult = GST_FLOW_OK;
3062         if (GST_PAD_MODE (pad) == GST_PAD_MODE_PUSH) {
3063           gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad,
3064               NULL);
3065         }
3066       }
3067       GST_QUEUE2_MUTEX_UNLOCK (queue);
3068
3069       res = gst_pad_push_event (queue->sinkpad, event);
3070       break;
3071     default:
3072       res = gst_pad_push_event (queue->sinkpad, event);
3073       break;
3074   }
3075
3076   return res;
3077 }
3078
3079 static gboolean
3080 gst_queue2_handle_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
3081 {
3082   GstQueue2 *queue;
3083
3084   queue = GST_QUEUE2 (parent);
3085
3086   switch (GST_QUERY_TYPE (query)) {
3087     case GST_QUERY_POSITION:
3088     {
3089       gint64 peer_pos;
3090       GstFormat format;
3091
3092       if (!gst_pad_peer_query (queue->sinkpad, query))
3093         goto peer_failed;
3094
3095       /* get peer position */
3096       gst_query_parse_position (query, &format, &peer_pos);
3097
3098       /* FIXME: this code assumes that there's no discont in the queue */
3099       switch (format) {
3100         case GST_FORMAT_BYTES:
3101           peer_pos -= queue->cur_level.bytes;
3102           break;
3103         case GST_FORMAT_TIME:
3104           peer_pos -= queue->cur_level.time;
3105           break;
3106         default:
3107           GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
3108               "know how to adjust value", gst_format_get_name (format));
3109           return FALSE;
3110       }
3111       /* set updated position */
3112       gst_query_set_position (query, format, peer_pos);
3113       break;
3114     }
3115     case GST_QUERY_DURATION:
3116     {
3117       GST_DEBUG_OBJECT (queue, "doing peer query");
3118
3119       if (!gst_pad_peer_query (queue->sinkpad, query))
3120         goto peer_failed;
3121
3122       GST_DEBUG_OBJECT (queue, "peer query success");
3123       break;
3124     }
3125     case GST_QUERY_BUFFERING:
3126     {
3127       gint percent;
3128       gboolean is_buffering;
3129       GstBufferingMode mode;
3130       gint avg_in, avg_out;
3131       gint64 buffering_left;
3132
3133       GST_DEBUG_OBJECT (queue, "query buffering");
3134
3135       get_buffering_percent (queue, &is_buffering, &percent);
3136       gst_query_set_buffering_percent (query, is_buffering, percent);
3137
3138       get_buffering_stats (queue, percent, &mode, &avg_in, &avg_out,
3139           &buffering_left);
3140       gst_query_set_buffering_stats (query, mode, avg_in, avg_out,
3141           buffering_left);
3142
3143       if (!QUEUE_IS_USING_QUEUE (queue)) {
3144         /* add ranges for download and ringbuffer buffering */
3145         GstFormat format;
3146         gint64 start, stop, range_start, range_stop;
3147         guint64 writing_pos;
3148         gint64 estimated_total;
3149         gint64 duration;
3150         gboolean peer_res, is_eos;
3151         GstQueue2Range *queued_ranges;
3152
3153         /* we need a current download region */
3154         if (queue->current == NULL)
3155           return FALSE;
3156
3157         writing_pos = queue->current->writing_pos;
3158         is_eos = queue->is_eos;
3159
3160         if (is_eos) {
3161           /* we're EOS, we know the duration in bytes now */
3162           peer_res = TRUE;
3163           duration = writing_pos;
3164         } else {
3165           /* get duration of upstream in bytes */
3166           peer_res = gst_pad_peer_query_duration (queue->sinkpad,
3167               GST_FORMAT_BYTES, &duration);
3168         }
3169
3170         GST_DEBUG_OBJECT (queue, "percent %d, duration %" G_GINT64_FORMAT
3171             ", writing %" G_GINT64_FORMAT, percent, duration, writing_pos);
3172
3173         /* calculate remaining and total download time */
3174         if (peer_res && avg_in > 0.0)
3175           estimated_total = ((duration - writing_pos) * 1000) / avg_in;
3176         else
3177           estimated_total = -1;
3178
3179         GST_DEBUG_OBJECT (queue, "estimated-total %" G_GINT64_FORMAT,
3180             estimated_total);
3181
3182         gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
3183
3184         switch (format) {
3185           case GST_FORMAT_PERCENT:
3186             /* we need duration */
3187             if (!peer_res)
3188               goto peer_failed;
3189
3190             start = 0;
3191             /* get our available data relative to the duration */
3192             if (duration != -1)
3193               stop =
3194                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX, writing_pos,
3195                   duration);
3196             else
3197               stop = -1;
3198             break;
3199           case GST_FORMAT_BYTES:
3200             start = 0;
3201             stop = writing_pos;
3202             break;
3203           default:
3204             start = -1;
3205             stop = -1;
3206             break;
3207         }
3208
3209         /* fill out the buffered ranges */
3210         for (queued_ranges = queue->ranges; queued_ranges;
3211             queued_ranges = queued_ranges->next) {
3212           switch (format) {
3213             case GST_FORMAT_PERCENT:
3214               if (duration == -1) {
3215                 range_start = 0;
3216                 range_stop = 0;
3217                 break;
3218               }
3219 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
3220               range_start =
3221                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
3222                   queued_ranges->reading_pos, duration);
3223 #else
3224               range_start =
3225                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
3226                   queued_ranges->offset, duration);
3227 #endif
3228               range_stop =
3229                   gst_util_uint64_scale (GST_FORMAT_PERCENT_MAX,
3230                   queued_ranges->writing_pos, duration);
3231               break;
3232             case GST_FORMAT_BYTES:
3233 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
3234               range_start = queued_ranges->reading_pos;
3235 #else
3236               range_start = queued_ranges->offset;
3237 #endif
3238               range_stop = queued_ranges->writing_pos;
3239               break;
3240             default:
3241               range_start = -1;
3242               range_stop = -1;
3243               break;
3244           }
3245           if (range_start == range_stop)
3246             continue;
3247           GST_DEBUG_OBJECT (queue,
3248               "range starting at %" G_GINT64_FORMAT " and finishing at %"
3249               G_GINT64_FORMAT, range_start, range_stop);
3250           gst_query_add_buffering_range (query, range_start, range_stop);
3251         }
3252
3253         gst_query_set_buffering_range (query, format, start, stop,
3254             estimated_total);
3255       }
3256       break;
3257     }
3258     case GST_QUERY_SCHEDULING:
3259     {
3260       gboolean pull_mode;
3261       GstSchedulingFlags flags = 0;
3262 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
3263       if ((!QUEUE_IS_USING_QUEUE (queue)) && !gst_pad_peer_query (queue->sinkpad, query))
3264 #else
3265       if (!gst_pad_peer_query (queue->sinkpad, query))
3266 #endif
3267         goto peer_failed;
3268
3269       gst_query_parse_scheduling (query, &flags, NULL, NULL, NULL);
3270
3271 #ifdef TIZEN_FEATURE_QUEUE2_MODIFICATION
3272       if (!(flags & GST_SCHEDULING_FLAG_SEEKABLE)) {
3273         GST_DEBUG_OBJECT(queue, "peer can support only push mode");
3274         gst_query_set_scheduling (query, flags, 0, -1, 0);
3275         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
3276         break;
3277       }
3278 #endif
3279       GST_DEBUG_OBJECT(queue, "peer can support pull mode");
3280
3281       /* we can operate in pull mode when we are using a tempfile */
3282       pull_mode = !QUEUE_IS_USING_QUEUE (queue);
3283
3284       if (pull_mode)
3285         flags |= GST_SCHEDULING_FLAG_SEEKABLE;
3286       gst_query_set_scheduling (query, flags, 0, -1, 0);
3287       if (pull_mode)
3288         gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
3289       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
3290       break;
3291     }
3292     default:
3293       /* peer handled other queries */
3294       if (!gst_pad_query_default (pad, parent, query))
3295         goto peer_failed;
3296       break;
3297   }
3298
3299   return TRUE;
3300
3301   /* ERRORS */
3302 peer_failed:
3303   {
3304     GST_DEBUG_OBJECT (queue, "failed peer query");
3305     return FALSE;
3306   }
3307 }
3308
3309 static gboolean
3310 gst_queue2_handle_query (GstElement * element, GstQuery * query)
3311 {
3312   GstQueue2 *queue = GST_QUEUE2 (element);
3313
3314   /* simply forward to the srcpad query function */
3315   return gst_queue2_handle_src_query (queue->srcpad, GST_OBJECT_CAST (element),
3316       query);
3317 }
3318
3319 static void
3320 gst_queue2_update_upstream_size (GstQueue2 * queue)
3321 {
3322   gint64 upstream_size = -1;
3323
3324   if (gst_pad_peer_query_duration (queue->sinkpad, GST_FORMAT_BYTES,
3325           &upstream_size)) {
3326     GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
3327
3328     /* upstream_size can be negative but queue->upstream_size is unsigned.
3329      * Prevent setting negative values to it (the query can return -1) */
3330     if (upstream_size >= 0)
3331       queue->upstream_size = upstream_size;
3332     else
3333       queue->upstream_size = 0;
3334   }
3335 }
3336
3337 static GstFlowReturn
3338 gst_queue2_get_range (GstPad * pad, GstObject * parent, guint64 offset,
3339     guint length, GstBuffer ** buffer)
3340 {
3341   GstQueue2 *queue;
3342   GstFlowReturn ret;
3343
3344   queue = GST_QUEUE2_CAST (parent);
3345
3346   length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
3347   GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
3348   offset = (offset == -1) ? queue->current->reading_pos : offset;
3349
3350   GST_DEBUG_OBJECT (queue,
3351       "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
3352
3353   /* catch any reads beyond the size of the file here to make sure queue2
3354    * doesn't send seek events beyond the size of the file upstream, since
3355    * that would confuse elements such as souphttpsrc and/or http servers.
3356    * Demuxers often just loop until EOS at the end of the file to figure out
3357    * when they've read all the end-headers or index chunks. */
3358   if (G_UNLIKELY (offset >= queue->upstream_size)) {
3359     gst_queue2_update_upstream_size (queue);
3360     if (queue->upstream_size > 0 && offset >= queue->upstream_size)
3361       goto out_unexpected;
3362   }
3363
3364   if (G_UNLIKELY (offset + length > queue->upstream_size)) {
3365     gst_queue2_update_upstream_size (queue);
3366     if (queue->upstream_size > 0 && offset + length >= queue->upstream_size) {
3367       length = queue->upstream_size - offset;
3368       GST_DEBUG_OBJECT (queue, "adjusting length downto %d", length);
3369     }
3370   }
3371
3372   /* FIXME - function will block when the range is not yet available */
3373   ret = gst_queue2_create_read (queue, offset, length, buffer);
3374   GST_QUEUE2_MUTEX_UNLOCK (queue);
3375   gst_queue2_post_buffering (queue);
3376
3377   return ret;
3378
3379   /* ERRORS */
3380 out_flushing:
3381   {
3382     ret = queue->srcresult;
3383
3384     GST_DEBUG_OBJECT (queue, "we are flushing");
3385     GST_QUEUE2_MUTEX_UNLOCK (queue);
3386     return ret;
3387   }
3388 out_unexpected:
3389   {
3390     GST_DEBUG_OBJECT (queue, "read beyond end of file");
3391     GST_QUEUE2_MUTEX_UNLOCK (queue);
3392     return GST_FLOW_EOS;
3393   }
3394 }
3395
3396 /* sink currently only operates in push mode */
3397 static gboolean
3398 gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
3399     GstPadMode mode, gboolean active)
3400 {
3401   gboolean result;
3402   GstQueue2 *queue;
3403
3404   queue = GST_QUEUE2 (parent);
3405
3406   switch (mode) {
3407     case GST_PAD_MODE_PUSH:
3408       if (active) {
3409         GST_QUEUE2_MUTEX_LOCK (queue);
3410         GST_DEBUG_OBJECT (queue, "activating push mode");
3411         queue->srcresult = GST_FLOW_OK;
3412         queue->sinkresult = GST_FLOW_OK;
3413         queue->is_eos = FALSE;
3414         queue->unexpected = FALSE;
3415         reset_rate_timer (queue);
3416         GST_QUEUE2_MUTEX_UNLOCK (queue);
3417       } else {
3418         /* unblock chain function */
3419         GST_QUEUE2_MUTEX_LOCK (queue);
3420         GST_DEBUG_OBJECT (queue, "deactivating push mode");
3421         queue->srcresult = GST_FLOW_FLUSHING;
3422         queue->sinkresult = GST_FLOW_FLUSHING;
3423         GST_QUEUE2_SIGNAL_DEL (queue);
3424         /* Unblock query handler */
3425         queue->last_query = FALSE;
3426         g_cond_signal (&queue->query_handled);
3427         GST_QUEUE2_MUTEX_UNLOCK (queue);
3428
3429         /* wait until it is unblocked and clean up */
3430         GST_PAD_STREAM_LOCK (pad);
3431         GST_QUEUE2_MUTEX_LOCK (queue);
3432         gst_queue2_locked_flush (queue, TRUE, FALSE);
3433         GST_QUEUE2_MUTEX_UNLOCK (queue);
3434         GST_PAD_STREAM_UNLOCK (pad);
3435       }
3436       result = TRUE;
3437       break;
3438     default:
3439       result = FALSE;
3440       break;
3441   }
3442   return result;
3443 }
3444
3445 /* src operating in push mode, we start a task on the source pad that pushes out
3446  * buffers from the queue */
3447 static gboolean
3448 gst_queue2_src_activate_push (GstPad * pad, GstObject * parent, gboolean active)
3449 {
3450   gboolean result = FALSE;
3451   GstQueue2 *queue;
3452
3453   queue = GST_QUEUE2 (parent);
3454
3455   if (active) {
3456     GST_QUEUE2_MUTEX_LOCK (queue);
3457     GST_DEBUG_OBJECT (queue, "activating push mode");
3458     queue->srcresult = GST_FLOW_OK;
3459     queue->sinkresult = GST_FLOW_OK;
3460     queue->is_eos = FALSE;
3461     queue->unexpected = FALSE;
3462     result =
3463         gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad, NULL);
3464     GST_QUEUE2_MUTEX_UNLOCK (queue);
3465   } else {
3466     /* unblock loop function */
3467     GST_QUEUE2_MUTEX_LOCK (queue);
3468     GST_DEBUG_OBJECT (queue, "deactivating push mode");
3469     queue->srcresult = GST_FLOW_FLUSHING;
3470     queue->sinkresult = GST_FLOW_FLUSHING;
3471     /* the item add signal will unblock */
3472     GST_QUEUE2_SIGNAL_ADD (queue);
3473     GST_QUEUE2_MUTEX_UNLOCK (queue);
3474
3475     /* step 2, make sure streaming finishes */
3476     result = gst_pad_stop_task (pad);
3477   }
3478
3479   return result;
3480 }
3481
3482 /* pull mode, downstream will call our getrange function */
3483 static gboolean
3484 gst_queue2_src_activate_pull (GstPad * pad, GstObject * parent, gboolean active)
3485 {
3486   gboolean result;
3487   GstQueue2 *queue;
3488
3489   queue = GST_QUEUE2 (parent);
3490
3491   if (active) {
3492     GST_QUEUE2_MUTEX_LOCK (queue);
3493     if (!QUEUE_IS_USING_QUEUE (queue)) {
3494       if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3495         /* open the temp file now */
3496         result = gst_queue2_open_temp_location_file (queue);
3497       } else if (!queue->ring_buffer) {
3498         queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
3499         result = ! !queue->ring_buffer;
3500       } else {
3501         result = TRUE;
3502       }
3503
3504       GST_DEBUG_OBJECT (queue, "activating pull mode");
3505       init_ranges (queue);
3506       queue->srcresult = GST_FLOW_OK;
3507       queue->sinkresult = GST_FLOW_OK;
3508       queue->is_eos = FALSE;
3509       queue->unexpected = FALSE;
3510       queue->upstream_size = 0;
3511     } else {
3512       GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
3513       /* this is not allowed, we cannot operate in pull mode without a temp
3514        * file. */
3515       queue->srcresult = GST_FLOW_FLUSHING;
3516       queue->sinkresult = GST_FLOW_FLUSHING;
3517       result = FALSE;
3518     }
3519     GST_QUEUE2_MUTEX_UNLOCK (queue);
3520   } else {
3521     GST_QUEUE2_MUTEX_LOCK (queue);
3522     GST_DEBUG_OBJECT (queue, "deactivating pull mode");
3523     queue->srcresult = GST_FLOW_FLUSHING;
3524     queue->sinkresult = GST_FLOW_FLUSHING;
3525     /* this will unlock getrange */
3526     GST_QUEUE2_SIGNAL_ADD (queue);
3527     result = TRUE;
3528     GST_QUEUE2_MUTEX_UNLOCK (queue);
3529   }
3530
3531   return result;
3532 }
3533
3534 static gboolean
3535 gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent, GstPadMode mode,
3536     gboolean active)
3537 {
3538   gboolean res;
3539
3540   switch (mode) {
3541     case GST_PAD_MODE_PULL:
3542       res = gst_queue2_src_activate_pull (pad, parent, active);
3543       break;
3544     case GST_PAD_MODE_PUSH:
3545       res = gst_queue2_src_activate_push (pad, parent, active);
3546       break;
3547     default:
3548       GST_LOG_OBJECT (pad, "unknown activation mode %d", mode);
3549       res = FALSE;
3550       break;
3551   }
3552   return res;
3553 }
3554
3555 static GstStateChangeReturn
3556 gst_queue2_change_state (GstElement * element, GstStateChange transition)
3557 {
3558   GstQueue2 *queue;
3559   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3560
3561   queue = GST_QUEUE2 (element);
3562
3563   switch (transition) {
3564     case GST_STATE_CHANGE_NULL_TO_READY:
3565       break;
3566     case GST_STATE_CHANGE_READY_TO_PAUSED:
3567       GST_QUEUE2_MUTEX_LOCK (queue);
3568       if (!QUEUE_IS_USING_QUEUE (queue)) {
3569         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3570           if (!gst_queue2_open_temp_location_file (queue))
3571             ret = GST_STATE_CHANGE_FAILURE;
3572         } else {
3573           if (queue->ring_buffer) {
3574             g_free (queue->ring_buffer);
3575             queue->ring_buffer = NULL;
3576           }
3577           if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
3578             ret = GST_STATE_CHANGE_FAILURE;
3579         }
3580         init_ranges (queue);
3581       }
3582       queue->segment_event_received = FALSE;
3583       queue->starting_segment = NULL;
3584       gst_event_replace (&queue->stream_start_event, NULL);
3585       GST_QUEUE2_MUTEX_UNLOCK (queue);
3586       break;
3587     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3588       break;
3589     default:
3590       break;
3591   }
3592
3593   if (ret == GST_STATE_CHANGE_FAILURE)
3594     return ret;
3595
3596   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3597
3598   if (ret == GST_STATE_CHANGE_FAILURE)
3599     return ret;
3600
3601   switch (transition) {
3602     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3603       break;
3604     case GST_STATE_CHANGE_PAUSED_TO_READY:
3605       GST_QUEUE2_MUTEX_LOCK (queue);
3606       if (!QUEUE_IS_USING_QUEUE (queue)) {
3607         if (QUEUE_IS_USING_TEMP_FILE (queue)) {
3608           gst_queue2_close_temp_location_file (queue);
3609         } else if (queue->ring_buffer) {
3610           g_free (queue->ring_buffer);
3611           queue->ring_buffer = NULL;
3612         }
3613         clean_ranges (queue);
3614       }
3615       if (queue->starting_segment != NULL) {
3616         gst_event_unref (queue->starting_segment);
3617         queue->starting_segment = NULL;
3618       }
3619       gst_event_replace (&queue->stream_start_event, NULL);
3620       GST_QUEUE2_MUTEX_UNLOCK (queue);
3621       break;
3622     case GST_STATE_CHANGE_READY_TO_NULL:
3623       break;
3624     default:
3625       break;
3626   }
3627
3628   return ret;
3629 }
3630
3631 /* changing the capacity of the queue must wake up
3632  * the _chain function, it might have more room now
3633  * to store the buffer/event in the queue */
3634 #define QUEUE_CAPACITY_CHANGE(q) \
3635   GST_QUEUE2_SIGNAL_DEL (queue); \
3636   if (queue->use_buffering)      \
3637     update_buffering (queue);
3638
3639 /* Changing the minimum required fill level must
3640  * wake up the _loop function as it might now
3641  * be able to preceed.
3642  */
3643 #define QUEUE_THRESHOLD_CHANGE(q)\
3644   GST_QUEUE2_SIGNAL_ADD (queue);
3645
3646 static void
3647 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
3648 {
3649   GstState state;
3650
3651   /* the element must be stopped in order to do this */
3652   GST_OBJECT_LOCK (queue);
3653   state = GST_STATE (queue);
3654   if (state != GST_STATE_READY && state != GST_STATE_NULL)
3655     goto wrong_state;
3656   GST_OBJECT_UNLOCK (queue);
3657
3658   /* set new location */
3659   g_free (queue->temp_template);
3660   queue->temp_template = g_strdup (template);
3661
3662   return;
3663
3664 /* ERROR */
3665 wrong_state:
3666   {
3667     GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
3668     GST_OBJECT_UNLOCK (queue);
3669   }
3670 }
3671
3672 static void
3673 gst_queue2_set_property (GObject * object,
3674     guint prop_id, const GValue * value, GParamSpec * pspec)
3675 {
3676   GstQueue2 *queue = GST_QUEUE2 (object);
3677
3678   /* someone could change levels here, and since this
3679    * affects the get/put funcs, we need to lock for safety. */
3680   GST_QUEUE2_MUTEX_LOCK (queue);
3681
3682   switch (prop_id) {
3683     case PROP_MAX_SIZE_BYTES:
3684       queue->max_level.bytes = g_value_get_uint (value);
3685       QUEUE_CAPACITY_CHANGE (queue);
3686       break;
3687     case PROP_MAX_SIZE_BUFFERS:
3688       queue->max_level.buffers = g_value_get_uint (value);
3689       QUEUE_CAPACITY_CHANGE (queue);
3690       break;
3691     case PROP_MAX_SIZE_TIME:
3692       queue->max_level.time = g_value_get_uint64 (value);
3693       /* set rate_time to the same value. We use an extra field in the level
3694        * structure so that we can easily access and compare it */
3695       queue->max_level.rate_time = queue->max_level.time;
3696       QUEUE_CAPACITY_CHANGE (queue);
3697       break;
3698     case PROP_USE_BUFFERING:
3699       queue->use_buffering = g_value_get_boolean (value);
3700       if (!queue->use_buffering && queue->is_buffering) {
3701         GST_DEBUG_OBJECT (queue, "Disabled buffering while buffering, "
3702             "posting 100%% message");
3703         SET_PERCENT (queue, 100);
3704         queue->is_buffering = FALSE;
3705       }
3706
3707       if (queue->use_buffering) {
3708         queue->is_buffering = TRUE;
3709         update_buffering (queue);
3710       }
3711       break;
3712     case PROP_USE_RATE_ESTIMATE:
3713       queue->use_rate_estimate = g_value_get_boolean (value);
3714       break;
3715     case PROP_LOW_PERCENT:
3716       queue->low_percent = g_value_get_int (value);
3717       break;
3718     case PROP_HIGH_PERCENT:
3719       queue->high_percent = g_value_get_int (value);
3720       break;
3721     case PROP_TEMP_TEMPLATE:
3722       gst_queue2_set_temp_template (queue, g_value_get_string (value));
3723       break;
3724     case PROP_TEMP_REMOVE:
3725       queue->temp_remove = g_value_get_boolean (value);
3726       break;
3727     case PROP_RING_BUFFER_MAX_SIZE:
3728       queue->ring_buffer_max_size = g_value_get_uint64 (value);
3729       break;
3730 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
3731     case PROP_BUFFER_MODE:
3732       queue->mode = g_value_get_enum (value);
3733       break;
3734 #endif
3735     default:
3736       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3737       break;
3738   }
3739
3740   GST_QUEUE2_MUTEX_UNLOCK (queue);
3741   gst_queue2_post_buffering (queue);
3742 }
3743
3744 static void
3745 gst_queue2_get_property (GObject * object,
3746     guint prop_id, GValue * value, GParamSpec * pspec)
3747 {
3748   GstQueue2 *queue = GST_QUEUE2 (object);
3749
3750   GST_QUEUE2_MUTEX_LOCK (queue);
3751
3752   switch (prop_id) {
3753     case PROP_CUR_LEVEL_BYTES:
3754       g_value_set_uint (value, queue->cur_level.bytes);
3755       break;
3756     case PROP_CUR_LEVEL_BUFFERS:
3757       g_value_set_uint (value, queue->cur_level.buffers);
3758       break;
3759     case PROP_CUR_LEVEL_TIME:
3760       g_value_set_uint64 (value, queue->cur_level.time);
3761       break;
3762     case PROP_MAX_SIZE_BYTES:
3763       g_value_set_uint (value, queue->max_level.bytes);
3764       break;
3765     case PROP_MAX_SIZE_BUFFERS:
3766       g_value_set_uint (value, queue->max_level.buffers);
3767       break;
3768     case PROP_MAX_SIZE_TIME:
3769       g_value_set_uint64 (value, queue->max_level.time);
3770       break;
3771     case PROP_USE_BUFFERING:
3772       g_value_set_boolean (value, queue->use_buffering);
3773       break;
3774     case PROP_USE_RATE_ESTIMATE:
3775       g_value_set_boolean (value, queue->use_rate_estimate);
3776       break;
3777     case PROP_LOW_PERCENT:
3778       g_value_set_int (value, queue->low_percent);
3779       break;
3780     case PROP_HIGH_PERCENT:
3781       g_value_set_int (value, queue->high_percent);
3782       break;
3783     case PROP_TEMP_TEMPLATE:
3784       g_value_set_string (value, queue->temp_template);
3785       break;
3786     case PROP_TEMP_LOCATION:
3787       g_value_set_string (value, queue->temp_location);
3788       break;
3789     case PROP_TEMP_REMOVE:
3790       g_value_set_boolean (value, queue->temp_remove);
3791       break;
3792     case PROP_RING_BUFFER_MAX_SIZE:
3793       g_value_set_uint64 (value, queue->ring_buffer_max_size);
3794       break;
3795 #ifdef TIZEN_FEATURE_RTSPSRC_MODIFICATION
3796     case PROP_BUFFER_MODE:
3797       g_value_set_enum (value, queue->mode);
3798       break;
3799 #endif
3800     default:
3801       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3802       break;
3803   }
3804
3805   GST_QUEUE2_MUTEX_UNLOCK (queue);
3806 }