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., 59 Temple Place - Suite 330,
23 * Boston, MA 02111-1307, USA.
24 */
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-tmpl 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 * Since 0.10.24, setting the temp-location property with a filename is deprecated
50 * because it's impossible to securely open a temporary file in this way. The
51 * property will still be used to notify the application of the allocated
52 * filename, though.
53 *
54 * Last reviewed on 2009-07-10 (0.10.24)
55 */
57 #ifdef HAVE_CONFIG_H
58 #include "config.h"
59 #endif
61 #include "gstqueue2.h"
63 #include <glib/gstdio.h>
65 #include "gst/gst-i18n-lib.h"
67 #include <string.h>
69 #ifdef G_OS_WIN32
70 #include <io.h> /* lseek, open, close, read */
71 #undef lseek
72 #define lseek _lseeki64
73 #undef off_t
74 #define off_t guint64
75 #else
76 #include <unistd.h>
77 #endif
79 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
80 GST_PAD_SINK,
81 GST_PAD_ALWAYS,
82 GST_STATIC_CAPS_ANY);
84 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
85 GST_PAD_SRC,
86 GST_PAD_ALWAYS,
87 GST_STATIC_CAPS_ANY);
89 GST_DEBUG_CATEGORY_STATIC (queue_debug);
90 #define GST_CAT_DEFAULT (queue_debug)
91 GST_DEBUG_CATEGORY_STATIC (queue_dataflow);
93 enum
94 {
95 LAST_SIGNAL
96 };
98 /* other defines */
99 #define DEFAULT_BUFFER_SIZE 4096
100 #define QUEUE_IS_USING_TEMP_FILE(queue) ((queue)->temp_location_set || (queue)->temp_template != NULL)
101 #define QUEUE_IS_USING_RING_BUFFER(queue) ((queue)->ring_buffer_max_size != 0) /* for consistency with the above macro */
102 #define QUEUE_IS_USING_QUEUE(queue) (!QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER (queue))
104 #define QUEUE_MAX_BYTES(queue) MIN((queue)->max_level.bytes, (queue)->ring_buffer_max_size)
106 /* default property values */
107 #define DEFAULT_MAX_SIZE_BUFFERS 100 /* 100 buffers */
108 #define DEFAULT_MAX_SIZE_BYTES (2 * 1024 * 1024) /* 2 MB */
109 #define DEFAULT_MAX_SIZE_TIME 2 * GST_SECOND /* 2 seconds */
110 #define DEFAULT_USE_BUFFERING FALSE
111 #define DEFAULT_USE_RATE_ESTIMATE TRUE
112 #define DEFAULT_LOW_PERCENT 10
113 #define DEFAULT_HIGH_PERCENT 99
114 #define DEFAULT_TEMP_REMOVE TRUE
115 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
117 enum
118 {
119 PROP_0,
120 PROP_CUR_LEVEL_BUFFERS,
121 PROP_CUR_LEVEL_BYTES,
122 PROP_CUR_LEVEL_TIME,
123 PROP_MAX_SIZE_BUFFERS,
124 PROP_MAX_SIZE_BYTES,
125 PROP_MAX_SIZE_TIME,
126 PROP_USE_BUFFERING,
127 PROP_USE_RATE_ESTIMATE,
128 PROP_LOW_PERCENT,
129 PROP_HIGH_PERCENT,
130 PROP_TEMP_TEMPLATE,
131 PROP_TEMP_LOCATION,
132 PROP_TEMP_REMOVE,
133 PROP_RING_BUFFER_MAX_SIZE,
134 PROP_LAST
135 };
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
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))
160 #define GST_QUEUE2_MUTEX_LOCK(q) G_STMT_START { \
161 g_mutex_lock (q->qlock); \
162 } G_STMT_END
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
170 #define GST_QUEUE2_MUTEX_UNLOCK(q) G_STMT_START { \
171 g_mutex_unlock (q->qlock); \
172 } G_STMT_END
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
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
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
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
212 #define _do_init(bla) \
213 GST_DEBUG_CATEGORY_INIT (queue_debug, "queue2", 0, "queue element"); \
214 GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue2_dataflow", 0, \
215 "dataflow inside the queue element");
217 GST_BOILERPLATE_FULL (GstQueue2, gst_queue2, GstElement, GST_TYPE_ELEMENT,
218 _do_init);
220 static void gst_queue2_finalize (GObject * object);
222 static void gst_queue2_set_property (GObject * object,
223 guint prop_id, const GValue * value, GParamSpec * pspec);
224 static void gst_queue2_get_property (GObject * object,
225 guint prop_id, GValue * value, GParamSpec * pspec);
227 static GstFlowReturn gst_queue2_chain (GstPad * pad, GstBuffer * buffer);
228 static GstFlowReturn gst_queue2_bufferalloc (GstPad * pad, guint64 offset,
229 guint size, GstCaps * caps, GstBuffer ** buf);
230 static GstFlowReturn gst_queue2_push_one (GstQueue2 * queue);
231 static void gst_queue2_loop (GstPad * pad);
233 static gboolean gst_queue2_handle_sink_event (GstPad * pad, GstEvent * event);
235 static gboolean gst_queue2_handle_src_event (GstPad * pad, GstEvent * event);
236 static gboolean gst_queue2_handle_src_query (GstPad * pad, GstQuery * query);
237 static gboolean gst_queue2_handle_query (GstElement * element,
238 GstQuery * query);
240 static GstCaps *gst_queue2_getcaps (GstPad * pad);
241 static gboolean gst_queue2_acceptcaps (GstPad * pad, GstCaps * caps);
243 static GstFlowReturn gst_queue2_get_range (GstPad * pad, guint64 offset,
244 guint length, GstBuffer ** buffer);
245 static gboolean gst_queue2_src_checkgetrange_function (GstPad * pad);
247 static gboolean gst_queue2_src_activate_pull (GstPad * pad, gboolean active);
248 static gboolean gst_queue2_src_activate_push (GstPad * pad, gboolean active);
249 static gboolean gst_queue2_sink_activate_push (GstPad * pad, gboolean active);
250 static GstStateChangeReturn gst_queue2_change_state (GstElement * element,
251 GstStateChange transition);
253 static gboolean gst_queue2_is_empty (GstQueue2 * queue);
254 static gboolean gst_queue2_is_filled (GstQueue2 * queue);
256 static void update_cur_level (GstQueue2 * queue, GstQueue2Range * range);
259 /* static guint gst_queue2_signals[LAST_SIGNAL] = { 0 }; */
261 static void
262 gst_queue2_base_init (gpointer g_class)
263 {
264 GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
266 gst_element_class_add_pad_template (gstelement_class,
267 gst_static_pad_template_get (&srctemplate));
268 gst_element_class_add_pad_template (gstelement_class,
269 gst_static_pad_template_get (&sinktemplate));
271 gst_element_class_set_details_simple (gstelement_class, "Queue 2",
272 "Generic",
273 "Simple data queue",
274 "Erik Walthinsen <omega@cse.ogi.edu>, "
275 "Wim Taymans <wim.taymans@gmail.com>");
276 }
278 static void
279 gst_queue2_class_init (GstQueue2Class * klass)
280 {
281 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
282 GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
284 gobject_class->set_property = gst_queue2_set_property;
285 gobject_class->get_property = gst_queue2_get_property;
287 /* properties */
288 g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
289 g_param_spec_uint ("current-level-bytes", "Current level (kB)",
290 "Current amount of data in the queue (bytes)",
291 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
292 g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
293 g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
294 "Current number of buffers in the queue",
295 0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
296 g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
297 g_param_spec_uint64 ("current-level-time", "Current level (ns)",
298 "Current amount of data in the queue (in ns)",
299 0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
301 g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
302 g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
303 "Max. amount of data in the queue (bytes, 0=disable)",
304 0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
305 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306 g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
307 g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
308 "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
309 DEFAULT_MAX_SIZE_BUFFERS,
310 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
311 g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
312 g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
313 "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
314 DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
316 g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
317 g_param_spec_boolean ("use-buffering", "Use buffering",
318 "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
319 DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
320 g_object_class_install_property (gobject_class, PROP_USE_RATE_ESTIMATE,
321 g_param_spec_boolean ("use-rate-estimate", "Use Rate Estimate",
322 "Estimate the bitrate of the stream to calculate time level",
323 DEFAULT_USE_RATE_ESTIMATE,
324 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
325 g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
326 g_param_spec_int ("low-percent", "Low percent",
327 "Low threshold for buffering to start. Only used if use-buffering is True",
328 0, 100, DEFAULT_LOW_PERCENT,
329 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
330 g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
331 g_param_spec_int ("high-percent", "High percent",
332 "High threshold for buffering to finish. Only used if use-buffering is True",
333 0, 100, DEFAULT_HIGH_PERCENT,
334 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
336 g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
337 g_param_spec_string ("temp-template", "Temporary File Template",
338 "File template to store temporary files in, should contain directory "
339 "and XXXXXX. (NULL == disabled)",
340 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
342 g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
343 g_param_spec_string ("temp-location", "Temporary File Location",
344 "Location to store temporary files in (Deprecated: Only read this "
345 "property, use temp-template to configure the name template)",
346 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348 /**
349 * GstQueue2:temp-remove
350 *
351 * When temp-template is set, remove the temporary file when going to READY.
352 *
353 * Since: 0.10.26
354 */
355 g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
356 g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
357 "Remove the temp-location after use",
358 DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
360 /**
361 * GstQueue2:ring-buffer-max-size
362 *
363 * The maximum size of the ring buffer in bytes. If set to 0, the ring
364 * buffer is disabled. Default 0.
365 *
366 * Since: 0.10.31
367 */
368 g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
369 g_param_spec_uint64 ("ring-buffer-max-size",
370 "Max. ring buffer size (bytes)",
371 "Max. amount of data in the ring buffer (bytes, 0 = disabled",
372 0, G_MAXUINT, DEFAULT_RING_BUFFER_MAX_SIZE,
373 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
375 /* set several parent class virtual functions */
376 gobject_class->finalize = gst_queue2_finalize;
378 gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_queue2_change_state);
379 gstelement_class->query = GST_DEBUG_FUNCPTR (gst_queue2_handle_query);
380 }
382 static void
383 gst_queue2_init (GstQueue2 * queue, GstQueue2Class * g_class)
384 {
385 queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
387 gst_pad_set_chain_function (queue->sinkpad,
388 GST_DEBUG_FUNCPTR (gst_queue2_chain));
389 gst_pad_set_activatepush_function (queue->sinkpad,
390 GST_DEBUG_FUNCPTR (gst_queue2_sink_activate_push));
391 gst_pad_set_event_function (queue->sinkpad,
392 GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_event));
393 gst_pad_set_getcaps_function (queue->sinkpad,
394 GST_DEBUG_FUNCPTR (gst_queue2_getcaps));
395 gst_pad_set_acceptcaps_function (queue->sinkpad,
396 GST_DEBUG_FUNCPTR (gst_queue2_acceptcaps));
397 gst_pad_set_bufferalloc_function (queue->sinkpad,
398 GST_DEBUG_FUNCPTR (gst_queue2_bufferalloc));
399 gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);
401 queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");
403 gst_pad_set_activatepull_function (queue->srcpad,
404 GST_DEBUG_FUNCPTR (gst_queue2_src_activate_pull));
405 gst_pad_set_activatepush_function (queue->srcpad,
406 GST_DEBUG_FUNCPTR (gst_queue2_src_activate_push));
407 gst_pad_set_getrange_function (queue->srcpad,
408 GST_DEBUG_FUNCPTR (gst_queue2_get_range));
409 gst_pad_set_checkgetrange_function (queue->srcpad,
410 GST_DEBUG_FUNCPTR (gst_queue2_src_checkgetrange_function));
411 gst_pad_set_getcaps_function (queue->srcpad,
412 GST_DEBUG_FUNCPTR (gst_queue2_getcaps));
413 gst_pad_set_acceptcaps_function (queue->srcpad,
414 GST_DEBUG_FUNCPTR (gst_queue2_acceptcaps));
415 gst_pad_set_event_function (queue->srcpad,
416 GST_DEBUG_FUNCPTR (gst_queue2_handle_src_event));
417 gst_pad_set_query_function (queue->srcpad,
418 GST_DEBUG_FUNCPTR (gst_queue2_handle_src_query));
419 gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);
421 /* levels */
422 GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
423 queue->max_level.buffers = DEFAULT_MAX_SIZE_BUFFERS;
424 queue->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
425 queue->max_level.time = DEFAULT_MAX_SIZE_TIME;
426 queue->max_level.rate_time = DEFAULT_MAX_SIZE_TIME;
427 queue->use_buffering = DEFAULT_USE_BUFFERING;
428 queue->use_rate_estimate = DEFAULT_USE_RATE_ESTIMATE;
429 queue->low_percent = DEFAULT_LOW_PERCENT;
430 queue->high_percent = DEFAULT_HIGH_PERCENT;
432 gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
433 gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
435 queue->sinktime = GST_CLOCK_TIME_NONE;
436 queue->srctime = GST_CLOCK_TIME_NONE;
437 queue->sink_tainted = TRUE;
438 queue->src_tainted = TRUE;
440 queue->srcresult = GST_FLOW_WRONG_STATE;
441 queue->sinkresult = GST_FLOW_WRONG_STATE;
442 queue->is_eos = FALSE;
443 queue->in_timer = g_timer_new ();
444 queue->out_timer = g_timer_new ();
446 queue->qlock = g_mutex_new ();
447 queue->waiting_add = FALSE;
448 queue->item_add = g_cond_new ();
449 queue->waiting_del = FALSE;
450 queue->item_del = g_cond_new ();
451 queue->queue = g_queue_new ();
453 queue->buffering_percent = 100;
455 /* tempfile related */
456 queue->temp_template = NULL;
457 queue->temp_location = NULL;
458 queue->temp_location_set = FALSE;
459 queue->temp_remove = DEFAULT_TEMP_REMOVE;
461 queue->ring_buffer = NULL;
462 queue->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
464 GST_DEBUG_OBJECT (queue,
465 "initialized queue's not_empty & not_full conditions");
466 }
468 /* called only once, as opposed to dispose */
469 static void
470 gst_queue2_finalize (GObject * object)
471 {
472 GstQueue2 *queue = GST_QUEUE2 (object);
474 GST_DEBUG_OBJECT (queue, "finalizing queue");
476 while (!g_queue_is_empty (queue->queue)) {
477 GstMiniObject *data = g_queue_pop_head (queue->queue);
479 gst_mini_object_unref (data);
480 }
482 g_queue_free (queue->queue);
483 g_mutex_free (queue->qlock);
484 g_cond_free (queue->item_add);
485 g_cond_free (queue->item_del);
486 g_timer_destroy (queue->in_timer);
487 g_timer_destroy (queue->out_timer);
489 /* temp_file path cleanup */
490 g_free (queue->temp_template);
491 g_free (queue->temp_location);
493 G_OBJECT_CLASS (parent_class)->finalize (object);
494 }
496 static void
497 debug_ranges (GstQueue2 * queue)
498 {
499 GstQueue2Range *walk;
501 for (walk = queue->ranges; walk; walk = walk->next) {
502 GST_DEBUG_OBJECT (queue,
503 "range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "] (rb [%"
504 G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "]), reading %" G_GUINT64_FORMAT
505 " current range? %s", walk->offset, walk->writing_pos, walk->rb_offset,
506 walk->rb_writing_pos, walk->reading_pos,
507 walk == queue->current ? "**y**" : " n ");
508 }
509 }
511 /* clear all the downloaded ranges */
512 static void
513 clean_ranges (GstQueue2 * queue)
514 {
515 GST_DEBUG_OBJECT (queue, "clean queue ranges");
517 g_slice_free_chain (GstQueue2Range, queue->ranges, next);
518 queue->ranges = NULL;
519 queue->current = NULL;
520 }
522 /* find a range that contains @offset or NULL when nothing does */
523 static GstQueue2Range *
524 find_range (GstQueue2 * queue, guint64 offset)
525 {
526 GstQueue2Range *range = NULL;
527 GstQueue2Range *walk;
529 /* first do a quick check for the current range */
530 for (walk = queue->ranges; walk; walk = walk->next) {
531 if (offset >= walk->offset && offset <= walk->writing_pos) {
532 /* we can reuse an existing range */
533 range = walk;
534 break;
535 }
536 }
537 if (range) {
538 GST_DEBUG_OBJECT (queue,
539 "found range for %" G_GUINT64_FORMAT ": [%" G_GUINT64_FORMAT "-%"
540 G_GUINT64_FORMAT "]", offset, range->offset, range->writing_pos);
541 } else {
542 GST_DEBUG_OBJECT (queue, "no range for %" G_GUINT64_FORMAT, offset);
543 }
544 return range;
545 }
547 static void
548 update_cur_level (GstQueue2 * queue, GstQueue2Range * range)
549 {
550 guint64 max_reading_pos, writing_pos;
552 writing_pos = range->writing_pos;
553 max_reading_pos = range->max_reading_pos;
555 if (writing_pos > max_reading_pos)
556 queue->cur_level.bytes = writing_pos - max_reading_pos;
557 else
558 queue->cur_level.bytes = 0;
559 }
561 /* make a new range for @offset or reuse an existing range */
562 static GstQueue2Range *
563 add_range (GstQueue2 * queue, guint64 offset)
564 {
565 GstQueue2Range *range, *prev, *next;
567 GST_DEBUG_OBJECT (queue, "find range for %" G_GUINT64_FORMAT, offset);
569 if ((range = find_range (queue, offset))) {
570 GST_DEBUG_OBJECT (queue,
571 "reusing range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, range->offset,
572 range->writing_pos);
573 range->writing_pos = offset;
574 } else {
575 GST_DEBUG_OBJECT (queue,
576 "new range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, offset);
578 range = g_slice_new0 (GstQueue2Range);
579 range->offset = offset;
580 /* we want to write to the next location in the ring buffer */
581 range->rb_offset = queue->current ? queue->current->rb_writing_pos : 0;
582 range->writing_pos = offset;
583 range->rb_writing_pos = range->rb_offset;
584 range->reading_pos = offset;
585 range->max_reading_pos = offset;
587 /* insert sorted */
588 prev = NULL;
589 next = queue->ranges;
590 while (next) {
591 if (next->offset > offset) {
592 /* insert before next */
593 GST_DEBUG_OBJECT (queue,
594 "insert before range %p, offset %" G_GUINT64_FORMAT, next,
595 next->offset);
596 break;
597 }
598 /* try next */
599 prev = next;
600 next = next->next;
601 }
602 range->next = next;
603 if (prev)
604 prev->next = range;
605 else
606 queue->ranges = range;
607 }
608 debug_ranges (queue);
610 /* update the stats for this range */
611 update_cur_level (queue, range);
613 return range;
614 }
617 /* clear and init the download ranges for offset 0 */
618 static void
619 init_ranges (GstQueue2 * queue)
620 {
621 GST_DEBUG_OBJECT (queue, "init queue ranges");
623 /* get rid of all the current ranges */
624 clean_ranges (queue);
625 /* make a range for offset 0 */
626 queue->current = add_range (queue, 0);
627 }
629 static gboolean
630 gst_queue2_acceptcaps (GstPad * pad, GstCaps * caps)
631 {
632 GstQueue2 *queue;
633 GstPad *otherpad;
634 gboolean result;
636 queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
638 otherpad = (pad == queue->srcpad ? queue->sinkpad : queue->srcpad);
639 result = gst_pad_peer_accept_caps (otherpad, caps);
641 return result;
642 }
644 static GstCaps *
645 gst_queue2_getcaps (GstPad * pad)
646 {
647 GstQueue2 *queue;
648 GstPad *otherpad;
649 GstCaps *result;
651 queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
653 otherpad = (pad == queue->srcpad ? queue->sinkpad : queue->srcpad);
654 result = gst_pad_peer_get_caps (otherpad);
655 if (result == NULL)
656 result = gst_caps_new_any ();
658 return result;
659 }
661 static GstFlowReturn
662 gst_queue2_bufferalloc (GstPad * pad, guint64 offset, guint size,
663 GstCaps * caps, GstBuffer ** buf)
664 {
665 GstQueue2 *queue;
666 GstFlowReturn result;
668 queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
670 /* Forward to src pad, without setting caps on the src pad */
671 result = gst_pad_alloc_buffer (queue->srcpad, offset, size, caps, buf);
673 return result;
674 }
676 /* calculate the diff between running time on the sink and src of the queue.
677 * This is the total amount of time in the queue. */
678 static void
679 update_time_level (GstQueue2 * queue)
680 {
681 if (queue->sink_tainted) {
682 queue->sinktime =
683 gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
684 queue->sink_segment.last_stop);
685 queue->sink_tainted = FALSE;
686 }
688 if (queue->src_tainted) {
689 queue->srctime =
690 gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
691 queue->src_segment.last_stop);
692 queue->src_tainted = FALSE;
693 }
695 GST_DEBUG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
696 GST_TIME_ARGS (queue->sinktime), GST_TIME_ARGS (queue->srctime));
698 if (queue->sinktime >= queue->srctime)
699 queue->cur_level.time = queue->sinktime - queue->srctime;
700 else
701 queue->cur_level.time = 0;
702 }
704 /* take a NEWSEGMENT event and apply the values to segment, updating the time
705 * level of queue. */
706 static void
707 apply_segment (GstQueue2 * queue, GstEvent * event, GstSegment * segment,
708 gboolean is_sink)
709 {
710 gboolean update;
711 GstFormat format;
712 gdouble rate, arate;
713 gint64 start, stop, time;
715 gst_event_parse_new_segment_full (event, &update, &rate, &arate,
716 &format, &start, &stop, &time);
718 GST_DEBUG_OBJECT (queue,
719 "received NEWSEGMENT update %d, rate %lf, applied rate %lf, "
720 "format %d, "
721 "%" G_GINT64_FORMAT " -- %" G_GINT64_FORMAT ", time %"
722 G_GINT64_FORMAT, update, rate, arate, format, start, stop, time);
724 if (format == GST_FORMAT_BYTES) {
725 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
726 /* start is where we'll be getting from and as such writing next */
727 queue->current = add_range (queue, start);
728 /* update the stats for this range */
729 update_cur_level (queue, queue->current);
730 }
731 }
733 /* now configure the values, we use these to track timestamps on the
734 * sinkpad. */
735 if (format != GST_FORMAT_TIME) {
736 /* non-time format, pretent the current time segment is closed with a
737 * 0 start and unknown stop time. */
738 update = FALSE;
739 format = GST_FORMAT_TIME;
740 start = 0;
741 stop = -1;
742 time = 0;
743 }
744 gst_segment_set_newsegment_full (segment, update,
745 rate, arate, format, start, stop, time);
747 GST_DEBUG_OBJECT (queue,
748 "configured NEWSEGMENT %" GST_SEGMENT_FORMAT, segment);
750 if (is_sink)
751 queue->sink_tainted = TRUE;
752 else
753 queue->src_tainted = TRUE;
755 /* segment can update the time level of the queue */
756 update_time_level (queue);
757 }
759 /* take a buffer and update segment, updating the time level of the queue. */
760 static void
761 apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
762 gboolean is_sink)
763 {
764 GstClockTime duration, timestamp;
766 timestamp = GST_BUFFER_TIMESTAMP (buffer);
767 duration = GST_BUFFER_DURATION (buffer);
769 /* if no timestamp is set, assume it's continuous with the previous
770 * time */
771 if (timestamp == GST_CLOCK_TIME_NONE)
772 timestamp = segment->last_stop;
774 /* add duration */
775 if (duration != GST_CLOCK_TIME_NONE)
776 timestamp += duration;
778 GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
779 GST_TIME_ARGS (timestamp));
781 gst_segment_set_last_stop (segment, GST_FORMAT_TIME, timestamp);
783 if (is_sink)
784 queue->sink_tainted = TRUE;
785 else
786 queue->src_tainted = TRUE;
788 /* calc diff with other end */
789 update_time_level (queue);
790 }
792 static void
793 update_buffering (GstQueue2 * queue)
794 {
795 gint64 percent;
796 gboolean post = FALSE;
798 if (queue->high_percent <= 0)
799 return;
801 #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)
803 if (queue->is_eos) {
804 /* on EOS we are always 100% full, we set the var here so that it we can
805 * reuse the logic below to stop buffering */
806 percent = 100;
807 GST_LOG_OBJECT (queue, "we are EOS");
808 } else {
809 /* figure out the percent we are filled, we take the max of all formats. */
811 if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
812 percent = GET_PERCENT (bytes, 0);
813 } else {
814 guint64 rb_size = queue->ring_buffer_max_size;
815 percent = GET_PERCENT (bytes, rb_size);
816 }
817 percent = MAX (percent, GET_PERCENT (time, 0));
818 percent = MAX (percent, GET_PERCENT (buffers, 0));
820 /* also apply the rate estimate when we need to */
821 if (queue->use_rate_estimate)
822 percent = MAX (percent, GET_PERCENT (rate_time, 0));
823 }
825 if (queue->is_buffering) {
826 post = TRUE;
827 /* if we were buffering see if we reached the high watermark */
828 if (percent >= queue->high_percent)
829 queue->is_buffering = FALSE;
830 } else {
831 /* we were not buffering, check if we need to start buffering if we drop
832 * below the low threshold */
833 if (percent < queue->low_percent) {
834 queue->is_buffering = TRUE;
835 queue->buffering_iteration++;
836 post = TRUE;
837 }
838 }
839 if (post) {
840 GstMessage *message;
841 GstBufferingMode mode;
842 gint64 buffering_left = -1;
844 /* scale to high percent so that it becomes the 100% mark */
845 percent = percent * 100 / queue->high_percent;
846 /* clip */
847 if (percent > 100)
848 percent = 100;
850 if (percent != queue->buffering_percent) {
851 queue->buffering_percent = percent;
853 if (!QUEUE_IS_USING_QUEUE (queue)) {
854 GstFormat fmt = GST_FORMAT_BYTES;
855 gint64 duration;
857 if (QUEUE_IS_USING_RING_BUFFER (queue))
858 mode = GST_BUFFERING_TIMESHIFT;
859 else
860 mode = GST_BUFFERING_DOWNLOAD;
862 if (queue->byte_in_rate > 0) {
863 if (gst_pad_query_peer_duration (queue->sinkpad, &fmt, &duration))
864 buffering_left =
865 (gdouble) ((duration -
866 queue->current->writing_pos) * 1000) / queue->byte_in_rate;
867 } else {
868 buffering_left = G_MAXINT64;
869 }
870 } else {
871 mode = GST_BUFFERING_STREAM;
872 }
874 GST_DEBUG_OBJECT (queue, "buffering %d percent", (gint) percent);
875 message = gst_message_new_buffering (GST_OBJECT_CAST (queue),
876 (gint) percent);
877 gst_message_set_buffering_stats (message, mode,
878 queue->byte_in_rate, queue->byte_out_rate, buffering_left);
880 gst_element_post_message (GST_ELEMENT_CAST (queue), message);
881 }
882 } else {
883 GST_DEBUG_OBJECT (queue, "filled %d percent", (gint) percent);
884 }
886 #undef GET_PERCENT
887 }
889 static void
890 reset_rate_timer (GstQueue2 * queue)
891 {
892 queue->bytes_in = 0;
893 queue->bytes_out = 0;
894 queue->byte_in_rate = 0.0;
895 queue->byte_out_rate = 0.0;
896 queue->last_in_elapsed = 0.0;
897 queue->last_out_elapsed = 0.0;
898 queue->in_timer_started = FALSE;
899 queue->out_timer_started = FALSE;
900 }
902 /* the interval in seconds to recalculate the rate */
903 #define RATE_INTERVAL 0.2
904 /* Tuning for rate estimation. We use a large window for the input rate because
905 * it should be stable when connected to a network. The output rate is less
906 * stable (the elements preroll, queues behind a demuxer fill, ...) and should
907 * therefore adapt more quickly. */
908 #define AVG_IN(avg,val) ((avg) * 15.0 + (val)) / 16.0
909 #define AVG_OUT(avg,val) ((avg) * 3.0 + (val)) / 4.0
911 static void
912 update_in_rates (GstQueue2 * queue)
913 {
914 gdouble elapsed, period;
915 gdouble byte_in_rate;
917 if (!queue->in_timer_started) {
918 queue->in_timer_started = TRUE;
919 g_timer_start (queue->in_timer);
920 return;
921 }
923 elapsed = g_timer_elapsed (queue->in_timer, NULL);
925 /* recalc after each interval. */
926 if (queue->last_in_elapsed + RATE_INTERVAL < elapsed) {
927 period = elapsed - queue->last_in_elapsed;
929 GST_DEBUG_OBJECT (queue,
930 "rates: period %f, in %" G_GUINT64_FORMAT, period, queue->bytes_in);
932 byte_in_rate = queue->bytes_in / period;
934 if (queue->byte_in_rate == 0.0)
935 queue->byte_in_rate = byte_in_rate;
936 else
937 queue->byte_in_rate = AVG_IN (queue->byte_in_rate, byte_in_rate);
939 /* reset the values to calculate rate over the next interval */
940 queue->last_in_elapsed = elapsed;
941 queue->bytes_in = 0;
942 }
944 if (queue->byte_in_rate > 0.0) {
945 queue->cur_level.rate_time =
946 queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
947 }
948 GST_DEBUG_OBJECT (queue, "rates: in %f, time %" GST_TIME_FORMAT,
949 queue->byte_in_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
950 }
952 static void
953 update_out_rates (GstQueue2 * queue)
954 {
955 gdouble elapsed, period;
956 gdouble byte_out_rate;
958 if (!queue->out_timer_started) {
959 queue->out_timer_started = TRUE;
960 g_timer_start (queue->out_timer);
961 return;
962 }
964 elapsed = g_timer_elapsed (queue->out_timer, NULL);
966 /* recalc after each interval. */
967 if (queue->last_out_elapsed + RATE_INTERVAL < elapsed) {
968 period = elapsed - queue->last_out_elapsed;
970 GST_DEBUG_OBJECT (queue,
971 "rates: period %f, out %" G_GUINT64_FORMAT, period, queue->bytes_out);
973 byte_out_rate = queue->bytes_out / period;
975 if (queue->byte_out_rate == 0.0)
976 queue->byte_out_rate = byte_out_rate;
977 else
978 queue->byte_out_rate = AVG_OUT (queue->byte_out_rate, byte_out_rate);
980 /* reset the values to calculate rate over the next interval */
981 queue->last_out_elapsed = elapsed;
982 queue->bytes_out = 0;
983 }
984 if (queue->byte_in_rate > 0.0) {
985 queue->cur_level.rate_time =
986 queue->cur_level.bytes / queue->byte_in_rate * GST_SECOND;
987 }
988 GST_DEBUG_OBJECT (queue, "rates: out %f, time %" GST_TIME_FORMAT,
989 queue->byte_out_rate, GST_TIME_ARGS (queue->cur_level.rate_time));
990 }
992 static void
993 update_cur_pos (GstQueue2 * queue, GstQueue2Range * range, guint64 pos)
994 {
995 guint64 reading_pos, max_reading_pos;
997 reading_pos = pos;
998 max_reading_pos = range->max_reading_pos;
1000 max_reading_pos = MAX (max_reading_pos, reading_pos);
1002 GST_DEBUG_OBJECT (queue,
1003 "updating max_reading_pos from %" G_GUINT64_FORMAT " to %"
1004 G_GUINT64_FORMAT, range->max_reading_pos, max_reading_pos);
1005 range->max_reading_pos = max_reading_pos;
1007 update_cur_level (queue, range);
1008 }
1010 static gboolean
1011 perform_seek_to_offset (GstQueue2 * queue, guint64 offset)
1012 {
1013 GstEvent *event;
1014 gboolean res;
1016 GST_QUEUE2_MUTEX_UNLOCK (queue);
1018 GST_DEBUG_OBJECT (queue, "Seeking to %" G_GUINT64_FORMAT, offset);
1020 event =
1021 gst_event_new_seek (1.0, GST_FORMAT_BYTES,
1022 GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE, GST_SEEK_TYPE_SET, offset,
1023 GST_SEEK_TYPE_NONE, -1);
1025 res = gst_pad_push_event (queue->sinkpad, event);
1026 GST_QUEUE2_MUTEX_LOCK (queue);
1028 if (res)
1029 queue->current = add_range (queue, offset);
1031 return res;
1032 }
1034 /* see if there is enough data in the file to read a full buffer */
1035 static gboolean
1036 gst_queue2_have_data (GstQueue2 * queue, guint64 offset, guint length)
1037 {
1038 GstQueue2Range *range;
1040 GST_DEBUG_OBJECT (queue, "looking for offset %" G_GUINT64_FORMAT ", len %u",
1041 offset, length);
1043 if ((range = find_range (queue, offset))) {
1044 if (queue->current != range) {
1045 GST_DEBUG_OBJECT (queue, "switching ranges, do seek to range position");
1046 perform_seek_to_offset (queue, range->writing_pos);
1047 }
1049 GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1050 queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1052 /* we have a range for offset */
1053 GST_DEBUG_OBJECT (queue,
1054 "we have a range %p, offset %" G_GUINT64_FORMAT ", writing_pos %"
1055 G_GUINT64_FORMAT, range, range->offset, range->writing_pos);
1057 if (!QUEUE_IS_USING_RING_BUFFER (queue) && queue->is_eos)
1058 return TRUE;
1060 if (offset + length <= range->writing_pos)
1061 return TRUE;
1062 else
1063 GST_DEBUG_OBJECT (queue,
1064 "Need more data (%" G_GUINT64_FORMAT " bytes more)",
1065 (offset + length) - range->writing_pos);
1067 } else {
1068 GST_INFO_OBJECT (queue, "not found in any range");
1069 /* we don't have the range, see how far away we are, FIXME, find a good
1070 * threshold based on the incomming rate. */
1071 if (!queue->is_eos && queue->current) {
1072 if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1073 if (offset < queue->current->offset || offset >
1074 queue->current->writing_pos + QUEUE_MAX_BYTES (queue) -
1075 queue->cur_level.bytes) {
1076 perform_seek_to_offset (queue, offset);
1077 } else {
1078 GST_INFO_OBJECT (queue,
1079 "requested data is within range, wait for data");
1080 }
1081 } else if (offset < queue->current->writing_pos + 200000) {
1082 update_cur_pos (queue, queue->current, offset + length);
1083 GST_INFO_OBJECT (queue, "wait for data");
1084 return FALSE;
1085 }
1086 }
1088 /* too far away, do a seek */
1089 perform_seek_to_offset (queue, offset);
1090 }
1092 return FALSE;
1093 }
1095 #ifdef HAVE_FSEEKO
1096 #define FSEEK_FILE(file,offset) (fseeko (file, (off_t) offset, SEEK_SET) != 0)
1097 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
1098 #define FSEEK_FILE(file,offset) (lseek (fileno (file), (off_t) offset, SEEK_SET) == (off_t) -1)
1099 #else
1100 #define FSEEK_FILE(file,offset) (fseek (file, offset, SEEK_SET) != 0)
1101 #endif
1103 static gint64
1104 gst_queue2_read_data_at_offset (GstQueue2 * queue, guint64 offset, guint length,
1105 guint8 * dst)
1106 {
1107 guint8 *ring_buffer;
1108 size_t res;
1110 ring_buffer = queue->ring_buffer;
1112 if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, offset))
1113 goto seek_failed;
1115 /* this should not block */
1116 GST_LOG_OBJECT (queue, "Reading %d bytes from offset %" G_GUINT64_FORMAT,
1117 length, offset);
1118 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1119 res = fread (dst, 1, length, queue->temp_file);
1120 } else {
1121 memcpy (dst, ring_buffer + offset, length);
1122 res = length;
1123 }
1125 GST_LOG_OBJECT (queue, "read %" G_GSIZE_FORMAT " bytes", res);
1127 if (G_UNLIKELY (res < length)) {
1128 if (!QUEUE_IS_USING_TEMP_FILE (queue))
1129 goto could_not_read;
1130 /* check for errors or EOF */
1131 if (ferror (queue->temp_file))
1132 goto could_not_read;
1133 if (feof (queue->temp_file) && length > 0)
1134 goto eos;
1135 }
1137 return res;
1139 seek_failed:
1140 {
1141 GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1142 return GST_FLOW_ERROR;
1143 }
1144 could_not_read:
1145 {
1146 GST_ELEMENT_ERROR (queue, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
1147 return GST_FLOW_ERROR;
1148 }
1149 eos:
1150 {
1151 GST_DEBUG ("non-regular file hits EOS");
1152 return GST_FLOW_UNEXPECTED;
1153 }
1154 }
1156 static GstFlowReturn
1157 gst_queue2_create_read (GstQueue2 * queue, guint64 offset, guint length,
1158 GstBuffer ** buffer)
1159 {
1160 GstBuffer *buf;
1161 guint8 *data;
1162 guint64 file_offset;
1163 guint block_length, remaining, read_length;
1164 gint64 read_return;
1165 guint64 rb_size;
1166 guint64 rpos;
1168 /* allocate the output buffer of the requested size */
1169 buf = gst_buffer_new_and_alloc (length);
1170 data = GST_BUFFER_DATA (buf);
1172 GST_DEBUG_OBJECT (queue, "Reading %u bytes from %" G_GUINT64_FORMAT, length,
1173 offset);
1175 rpos = offset;
1176 rb_size = queue->ring_buffer_max_size;
1178 remaining = length;
1179 while (remaining > 0) {
1180 /* configure how much/whether to read */
1181 if (!gst_queue2_have_data (queue, rpos, remaining)) {
1182 read_length = 0;
1184 if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1185 guint64 level;
1187 /* calculate how far away the offset is */
1188 if (queue->current->writing_pos > rpos)
1189 level = queue->current->writing_pos - rpos;
1190 else
1191 level = 0;
1193 GST_DEBUG_OBJECT (queue,
1194 "reading %" G_GUINT64_FORMAT ", writing %" G_GUINT64_FORMAT
1195 ", level %" G_GUINT64_FORMAT,
1196 rpos, queue->current->writing_pos, level);
1198 if (level >= rb_size) {
1199 /* we don't have the data but if we have a ring buffer that is full, we
1200 * need to read */
1201 GST_DEBUG_OBJECT (queue,
1202 "ring buffer full, reading ring-buffer-max-size %"
1203 G_GUINT64_FORMAT " bytes", rb_size);
1204 read_length = rb_size;
1205 } else if (queue->is_eos) {
1206 /* won't get any more data so read any data we have */
1207 if (level) {
1208 GST_DEBUG_OBJECT (queue,
1209 "EOS hit but read %" G_GUINT64_FORMAT " bytes that we have",
1210 level);
1211 read_length = level;
1212 } else {
1213 GST_DEBUG_OBJECT (queue,
1214 "EOS hit and we don't have any requested data");
1215 return GST_FLOW_UNEXPECTED;
1216 }
1217 }
1218 }
1220 if (read_length == 0) {
1221 if (QUEUE_IS_USING_RING_BUFFER (queue)
1222 && queue->current->max_reading_pos > rpos) {
1223 /* protect cached data (data between offset and max_reading_pos)
1224 * and update current level */
1225 GST_DEBUG_OBJECT (queue,
1226 "protecting cached data [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1227 "]", rpos, queue->current->max_reading_pos);
1228 queue->current->max_reading_pos = rpos;
1229 update_cur_level (queue, queue->current);
1230 }
1231 GST_DEBUG_OBJECT (queue, "waiting for add");
1232 GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
1233 continue;
1234 }
1235 } else {
1236 /* we have the requested data so read it */
1237 read_length = remaining;
1238 }
1240 /* set range reading_pos to actual reading position for this read */
1241 queue->current->reading_pos = rpos;
1243 /* congfigure how much and from where to read */
1244 if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1245 file_offset =
1246 (queue->current->rb_offset + (rpos -
1247 queue->current->offset)) % rb_size;
1248 if (file_offset + read_length > rb_size) {
1249 block_length = rb_size - file_offset;
1250 } else {
1251 block_length = read_length;
1252 }
1253 } else {
1254 file_offset = rpos;
1255 block_length = read_length;
1256 }
1258 /* while we still have data to read, we loop */
1259 while (read_length > 0) {
1260 read_return =
1261 gst_queue2_read_data_at_offset (queue, file_offset, block_length,
1262 data);
1263 if (read_return < 0)
1264 goto read_error;
1266 file_offset += read_return;
1267 if (QUEUE_IS_USING_RING_BUFFER (queue))
1268 file_offset %= rb_size;
1270 data += read_return;
1271 read_length -= read_return;
1272 block_length = read_length;
1273 remaining -= read_return;
1275 rpos = (queue->current->reading_pos += read_return);
1276 update_cur_pos (queue, queue->current, queue->current->reading_pos);
1277 }
1278 GST_QUEUE2_SIGNAL_DEL (queue);
1279 GST_DEBUG_OBJECT (queue, "%u bytes left to read", remaining);
1280 }
1282 GST_BUFFER_SIZE (buf) = length;
1283 GST_BUFFER_OFFSET (buf) = offset;
1284 GST_BUFFER_OFFSET_END (buf) = offset + length;
1286 *buffer = buf;
1288 return GST_FLOW_OK;
1290 /* ERRORS */
1291 out_flushing:
1292 {
1293 GST_DEBUG_OBJECT (queue, "we are flushing");
1294 return GST_FLOW_WRONG_STATE;
1295 }
1296 read_error:
1297 {
1298 GST_DEBUG_OBJECT (queue, "we have a read error");
1299 gst_buffer_unref (buf);
1300 return read_return;
1301 }
1302 }
1304 /* should be called with QUEUE_LOCK */
1305 static GstMiniObject *
1306 gst_queue2_read_item_from_file (GstQueue2 * queue)
1307 {
1308 GstMiniObject *item;
1310 if (queue->starting_segment != NULL) {
1311 item = GST_MINI_OBJECT_CAST (queue->starting_segment);
1312 queue->starting_segment = NULL;
1313 } else {
1314 GstFlowReturn ret;
1315 GstBuffer *buffer;
1316 guint64 reading_pos;
1318 reading_pos = queue->current->reading_pos;
1320 ret =
1321 gst_queue2_create_read (queue, reading_pos, DEFAULT_BUFFER_SIZE,
1322 &buffer);
1324 switch (ret) {
1325 case GST_FLOW_OK:
1326 item = GST_MINI_OBJECT_CAST (buffer);
1327 break;
1328 case GST_FLOW_UNEXPECTED:
1329 item = GST_MINI_OBJECT_CAST (gst_event_new_eos ());
1330 break;
1331 default:
1332 item = NULL;
1333 break;
1334 }
1335 }
1336 return item;
1337 }
1339 /* must be called with MUTEX_LOCK. Will briefly release the lock when notifying
1340 * the temp filename. */
1341 static gboolean
1342 gst_queue2_open_temp_location_file (GstQueue2 * queue)
1343 {
1344 gint fd = -1;
1345 gchar *name = NULL;
1347 if (queue->temp_file)
1348 goto already_opened;
1350 GST_DEBUG_OBJECT (queue, "opening temp file %s", queue->temp_template);
1352 /* we have two cases:
1353 * - temp_location was set to something !NULL (Deprecated). in this case we
1354 * open the specified filename.
1355 * - temp_template was set, allocate a filename and open that filename
1356 */
1357 if (!queue->temp_location_set) {
1358 /* nothing to do */
1359 if (queue->temp_template == NULL)
1360 goto no_directory;
1362 /* make copy of the template, we don't want to change this */
1363 name = g_strdup (queue->temp_template);
1364 fd = g_mkstemp (name);
1365 if (fd == -1)
1366 goto mkstemp_failed;
1368 /* open the file for update/writing */
1369 queue->temp_file = fdopen (fd, "wb+");
1370 /* error creating file */
1371 if (queue->temp_file == NULL)
1372 goto open_failed;
1374 g_free (queue->temp_location);
1375 queue->temp_location = name;
1377 GST_QUEUE2_MUTEX_UNLOCK (queue);
1379 /* we can't emit the notify with the lock */
1380 g_object_notify (G_OBJECT (queue), "temp-location");
1382 GST_QUEUE2_MUTEX_LOCK (queue);
1383 } else {
1384 /* open the file for update/writing, this is deprecated but we still need to
1385 * support it for API/ABI compatibility */
1386 queue->temp_file = g_fopen (queue->temp_location, "wb+");
1387 /* error creating file */
1388 if (queue->temp_file == NULL)
1389 goto open_failed;
1390 }
1391 GST_DEBUG_OBJECT (queue, "opened temp file %s", queue->temp_template);
1393 return TRUE;
1395 /* ERRORS */
1396 already_opened:
1397 {
1398 GST_DEBUG_OBJECT (queue, "temp file was already open");
1399 return TRUE;
1400 }
1401 no_directory:
1402 {
1403 GST_ELEMENT_ERROR (queue, RESOURCE, NOT_FOUND,
1404 (_("No Temp directory specified.")), (NULL));
1405 return FALSE;
1406 }
1407 mkstemp_failed:
1408 {
1409 GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1410 (_("Could not create temp file \"%s\"."), queue->temp_template),
1411 GST_ERROR_SYSTEM);
1412 g_free (name);
1413 return FALSE;
1414 }
1415 open_failed:
1416 {
1417 GST_ELEMENT_ERROR (queue, RESOURCE, OPEN_READ,
1418 (_("Could not open file \"%s\" for reading."), name), GST_ERROR_SYSTEM);
1419 g_free (name);
1420 if (fd != -1)
1421 close (fd);
1422 return FALSE;
1423 }
1424 }
1426 static void
1427 gst_queue2_close_temp_location_file (GstQueue2 * queue)
1428 {
1429 /* nothing to do */
1430 if (queue->temp_file == NULL)
1431 return;
1433 GST_DEBUG_OBJECT (queue, "closing temp file");
1435 fflush (queue->temp_file);
1436 fclose (queue->temp_file);
1438 if (queue->temp_remove)
1439 remove (queue->temp_location);
1441 queue->temp_file = NULL;
1442 clean_ranges (queue);
1443 }
1445 static void
1446 gst_queue2_flush_temp_file (GstQueue2 * queue)
1447 {
1448 if (queue->temp_file == NULL)
1449 return;
1451 GST_DEBUG_OBJECT (queue, "flushing temp file");
1453 queue->temp_file = g_freopen (queue->temp_location, "wb+", queue->temp_file);
1454 }
1456 static void
1457 gst_queue2_locked_flush (GstQueue2 * queue)
1458 {
1459 if (!QUEUE_IS_USING_QUEUE (queue)) {
1460 if (QUEUE_IS_USING_TEMP_FILE (queue))
1461 gst_queue2_flush_temp_file (queue);
1462 init_ranges (queue);
1463 } else {
1464 while (!g_queue_is_empty (queue->queue)) {
1465 GstMiniObject *data = g_queue_pop_head (queue->queue);
1467 /* Then lose another reference because we are supposed to destroy that
1468 data when flushing */
1469 gst_mini_object_unref (data);
1470 }
1471 }
1472 GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1473 gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
1474 gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);
1475 queue->sinktime = queue->srctime = GST_CLOCK_TIME_NONE;
1476 queue->sink_tainted = queue->src_tainted = TRUE;
1477 if (queue->starting_segment != NULL)
1478 gst_event_unref (queue->starting_segment);
1479 queue->starting_segment = NULL;
1480 queue->segment_event_received = FALSE;
1482 /* we deleted a lot of something */
1483 GST_QUEUE2_SIGNAL_DEL (queue);
1484 }
1486 static gboolean
1487 gst_queue2_wait_free_space (GstQueue2 * queue)
1488 {
1489 /* We make space available if we're "full" according to whatever
1490 * the user defined as "full". */
1491 if (gst_queue2_is_filled (queue)) {
1492 gboolean started;
1494 /* pause the timer while we wait. The fact that we are waiting does not mean
1495 * the byterate on the input pad is lower */
1496 if ((started = queue->in_timer_started))
1497 g_timer_stop (queue->in_timer);
1499 GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
1500 "queue is full, waiting for free space");
1501 do {
1502 /* Wait for space to be available, we could be unlocked because of a flush. */
1503 GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1504 }
1505 while (gst_queue2_is_filled (queue));
1507 /* and continue if we were running before */
1508 if (started)
1509 g_timer_continue (queue->in_timer);
1510 }
1511 return TRUE;
1513 /* ERRORS */
1514 out_flushing:
1515 {
1516 GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "queue is flushing");
1517 return FALSE;
1518 }
1519 }
1521 static gboolean
1522 gst_queue2_create_write (GstQueue2 * queue, GstBuffer * buffer)
1523 {
1524 guint8 *data, *ring_buffer;
1525 guint size, rb_size;
1526 guint64 writing_pos, new_writing_pos;
1527 GstQueue2Range *range, *prev, *next;
1529 if (QUEUE_IS_USING_RING_BUFFER (queue))
1530 writing_pos = queue->current->rb_writing_pos;
1531 else
1532 writing_pos = queue->current->writing_pos;
1533 ring_buffer = queue->ring_buffer;
1534 rb_size = queue->ring_buffer_max_size;
1536 size = GST_BUFFER_SIZE (buffer);
1537 data = GST_BUFFER_DATA (buffer);
1539 GST_DEBUG_OBJECT (queue, "Writing %u bytes to %" G_GUINT64_FORMAT, size,
1540 GST_BUFFER_OFFSET (buffer));
1542 while (size > 0) {
1543 guint to_write;
1545 if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1546 gint64 space;
1548 /* calculate the space in the ring buffer not used by data from
1549 * the current range */
1550 while (QUEUE_MAX_BYTES (queue) <= queue->cur_level.bytes) {
1551 /* wait until there is some free space */
1552 GST_QUEUE2_WAIT_DEL_CHECK (queue, queue->sinkresult, out_flushing);
1553 }
1554 /* get the amount of space we have */
1555 space = QUEUE_MAX_BYTES (queue) - queue->cur_level.bytes;
1557 /* calculate if we need to split or if we can write the entire
1558 * buffer now */
1559 to_write = MIN (size, space);
1561 /* the writing position in the ring buffer after writing (part
1562 * or all of) the buffer */
1563 new_writing_pos = (writing_pos + to_write) % rb_size;
1565 prev = NULL;
1566 range = queue->ranges;
1568 /* if we need to overwrite data in the ring buffer, we need to
1569 * update the ranges
1570 *
1571 * warning: this code is complicated and includes some
1572 * simplifications - pen, paper and diagrams for the cases
1573 * recommended! */
1574 while (range) {
1575 guint64 range_data_start, range_data_end;
1576 GstQueue2Range *range_to_destroy = NULL;
1578 range_data_start = range->rb_offset;
1579 range_data_end = range->rb_writing_pos;
1581 /* handle the special case where the range has no data in it */
1582 if (range->writing_pos == range->offset) {
1583 if (range != queue->current) {
1584 GST_DEBUG_OBJECT (queue,
1585 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1586 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1587 /* remove range */
1588 range_to_destroy = range;
1589 if (prev)
1590 prev->next = range->next;
1591 }
1592 goto next_range;
1593 }
1595 if (range_data_end > range_data_start) {
1596 if (writing_pos >= range_data_end && new_writing_pos >= writing_pos)
1597 goto next_range;
1599 if (new_writing_pos > range_data_start) {
1600 if (new_writing_pos >= range_data_end) {
1601 GST_DEBUG_OBJECT (queue,
1602 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1603 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1604 /* remove range */
1605 range_to_destroy = range;
1606 if (prev)
1607 prev->next = range->next;
1608 } else {
1609 GST_DEBUG_OBJECT (queue,
1610 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1611 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1612 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1613 range->offset + new_writing_pos - range_data_start,
1614 new_writing_pos);
1615 range->offset += (new_writing_pos - range_data_start);
1616 range->rb_offset = new_writing_pos;
1617 }
1618 }
1619 } else {
1620 guint64 new_wpos_virt = writing_pos + to_write;
1622 if (new_wpos_virt <= range_data_start)
1623 goto next_range;
1625 if (new_wpos_virt > rb_size && new_writing_pos >= range_data_end) {
1626 GST_DEBUG_OBJECT (queue,
1627 "Removing range: offset %" G_GUINT64_FORMAT ", wpos %"
1628 G_GUINT64_FORMAT, range->offset, range->writing_pos);
1629 /* remove range */
1630 range_to_destroy = range;
1631 if (prev)
1632 prev->next = range->next;
1633 } else {
1634 GST_DEBUG_OBJECT (queue,
1635 "advancing offsets from %" G_GUINT64_FORMAT " (%"
1636 G_GUINT64_FORMAT ") to %" G_GUINT64_FORMAT " (%"
1637 G_GUINT64_FORMAT ")", range->offset, range->rb_offset,
1638 range->offset + new_writing_pos - range_data_start,
1639 new_writing_pos);
1640 range->offset += (new_wpos_virt - range_data_start);
1641 range->rb_offset = new_writing_pos;
1642 }
1643 }
1645 next_range:
1646 if (!range_to_destroy)
1647 prev = range;
1649 range = range->next;
1650 if (range_to_destroy) {
1651 if (range_to_destroy == queue->ranges)
1652 queue->ranges = range;
1653 g_slice_free (GstQueue2Range, range_to_destroy);
1654 range_to_destroy = NULL;
1655 }
1656 }
1657 } else {
1658 to_write = size;
1659 new_writing_pos = writing_pos + to_write;
1660 }
1662 if (QUEUE_IS_USING_TEMP_FILE (queue)
1663 && FSEEK_FILE (queue->temp_file, writing_pos))
1664 goto seek_failed;
1666 if (new_writing_pos > writing_pos) {
1667 GST_INFO_OBJECT (queue,
1668 "writing %u bytes to range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1669 "] (rb wpos %" G_GUINT64_FORMAT ")", to_write, queue->current->offset,
1670 queue->current->writing_pos, queue->current->rb_writing_pos);
1671 /* either not using ring buffer or no wrapping, just write */
1672 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1673 if (fwrite (data, to_write, 1, queue->temp_file) != 1)
1674 goto handle_error;
1675 } else {
1676 memcpy (ring_buffer + writing_pos, data, to_write);
1677 }
1679 if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
1680 /* try to merge with next range */
1681 while ((next = queue->current->next)) {
1682 GST_INFO_OBJECT (queue,
1683 "checking merge with next range %" G_GUINT64_FORMAT " < %"
1684 G_GUINT64_FORMAT, new_writing_pos, next->offset);
1685 if (new_writing_pos < next->offset)
1686 break;
1688 GST_DEBUG_OBJECT (queue, "merging ranges %" G_GUINT64_FORMAT,
1689 next->writing_pos);
1691 /* remove the group, we could choose to not read the data in this range
1692 * again. This would involve us doing a seek to the current writing position
1693 * in the range. FIXME, It would probably make sense to do a seek when there
1694 * is a lot of data in the range we merged with to avoid reading it all
1695 * again. */
1696 queue->current->next = next->next;
1697 g_slice_free (GstQueue2Range, next);
1699 debug_ranges (queue);
1700 }
1701 goto update_and_signal;
1702 }
1703 } else {
1704 /* wrapping */
1705 guint block_one, block_two;
1707 block_one = rb_size - writing_pos;
1708 block_two = to_write - block_one;
1710 if (block_one > 0) {
1711 GST_INFO_OBJECT (queue, "writing %u bytes", block_one);
1712 /* write data to end of ring buffer */
1713 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1714 if (fwrite (data, block_one, 1, queue->temp_file) != 1)
1715 goto handle_error;
1716 } else {
1717 memcpy (ring_buffer + writing_pos, data, block_one);
1718 }
1719 }
1721 if (QUEUE_IS_USING_TEMP_FILE (queue) && FSEEK_FILE (queue->temp_file, 0))
1722 goto seek_failed;
1724 if (block_two > 0) {
1725 GST_INFO_OBJECT (queue, "writing %u bytes", block_two);
1726 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
1727 if (fwrite (data + block_one, block_two, 1, queue->temp_file) != 1)
1728 goto handle_error;
1729 } else {
1730 memcpy (ring_buffer, data + block_one, block_two);
1731 }
1732 }
1733 }
1735 update_and_signal:
1736 /* update the writing positions */
1737 size -= to_write;
1738 GST_INFO_OBJECT (queue,
1739 "wrote %u bytes to %" G_GUINT64_FORMAT " (%u bytes remaining to write)",
1740 to_write, writing_pos, size);
1742 if (QUEUE_IS_USING_RING_BUFFER (queue)) {
1743 data += to_write;
1744 queue->current->writing_pos += to_write;
1745 queue->current->rb_writing_pos = writing_pos = new_writing_pos;
1746 } else {
1747 queue->current->writing_pos = writing_pos = new_writing_pos;
1748 }
1749 update_cur_level (queue, queue->current);
1751 /* update the buffering status */
1752 if (queue->use_buffering)
1753 update_buffering (queue);
1755 GST_INFO_OBJECT (queue, "cur_level.bytes %u (max %" G_GUINT64_FORMAT ")",
1756 queue->cur_level.bytes, QUEUE_MAX_BYTES (queue));
1758 GST_QUEUE2_SIGNAL_ADD (queue);
1759 };
1761 return TRUE;
1763 /* ERRORS */
1764 out_flushing:
1765 {
1766 GST_DEBUG_OBJECT (queue, "we are flushing");
1767 /* FIXME - GST_FLOW_UNEXPECTED ? */
1768 return FALSE;
1769 }
1770 seek_failed:
1771 {
1772 GST_ELEMENT_ERROR (queue, RESOURCE, SEEK, (NULL), GST_ERROR_SYSTEM);
1773 return FALSE;
1774 }
1775 handle_error:
1776 {
1777 switch (errno) {
1778 case ENOSPC:{
1779 GST_ELEMENT_ERROR (queue, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
1780 break;
1781 }
1782 default:{
1783 GST_ELEMENT_ERROR (queue, RESOURCE, WRITE,
1784 (_("Error while writing to download file.")),
1785 ("%s", g_strerror (errno)));
1786 }
1787 }
1788 return FALSE;
1789 }
1790 }
1792 /* enqueue an item an update the level stats */
1793 static void
1794 gst_queue2_locked_enqueue (GstQueue2 * queue, gpointer item, gboolean isbuffer)
1795 {
1796 if (isbuffer) {
1797 GstBuffer *buffer;
1798 guint size;
1800 buffer = GST_BUFFER_CAST (item);
1801 size = GST_BUFFER_SIZE (buffer);
1803 /* add buffer to the statistics */
1804 if (QUEUE_IS_USING_QUEUE (queue)) {
1805 queue->cur_level.buffers++;
1806 queue->cur_level.bytes += size;
1807 }
1808 queue->bytes_in += size;
1810 /* apply new buffer to segment stats */
1811 apply_buffer (queue, buffer, &queue->sink_segment, TRUE);
1812 /* update the byterate stats */
1813 update_in_rates (queue);
1815 if (!QUEUE_IS_USING_QUEUE (queue)) {
1816 /* FIXME - check return value? */
1817 gst_queue2_create_write (queue, buffer);
1818 }
1819 } else if (GST_IS_EVENT (item)) {
1820 GstEvent *event;
1822 event = GST_EVENT_CAST (item);
1824 switch (GST_EVENT_TYPE (event)) {
1825 case GST_EVENT_EOS:
1826 /* Zero the thresholds, this makes sure the queue is completely
1827 * filled and we can read all data from the queue. */
1828 GST_DEBUG_OBJECT (queue, "we have EOS");
1829 queue->is_eos = TRUE;
1830 break;
1831 case GST_EVENT_NEWSEGMENT:
1832 apply_segment (queue, event, &queue->sink_segment, TRUE);
1833 /* This is our first new segment, we hold it
1834 * as we can't save it on the temp file */
1835 if (!QUEUE_IS_USING_QUEUE (queue)) {
1836 if (queue->segment_event_received)
1837 goto unexpected_event;
1839 queue->segment_event_received = TRUE;
1840 if (queue->starting_segment != NULL)
1841 gst_event_unref (queue->starting_segment);
1842 queue->starting_segment = event;
1843 item = NULL;
1844 }
1845 /* a new segment allows us to accept more buffers if we got UNEXPECTED
1846 * from downstream */
1847 queue->unexpected = FALSE;
1848 break;
1849 default:
1850 if (!QUEUE_IS_USING_QUEUE (queue))
1851 goto unexpected_event;
1852 break;
1853 }
1854 } else {
1855 g_warning ("Unexpected item %p added in queue %s (refcounting problem?)",
1856 item, GST_OBJECT_NAME (queue));
1857 /* we can't really unref since we don't know what it is */
1858 item = NULL;
1859 }
1861 if (item) {
1862 /* update the buffering status */
1863 if (queue->use_buffering)
1864 update_buffering (queue);
1866 if (QUEUE_IS_USING_QUEUE (queue)) {
1867 g_queue_push_tail (queue->queue, item);
1868 } else {
1869 gst_mini_object_unref (GST_MINI_OBJECT_CAST (item));
1870 }
1872 GST_QUEUE2_SIGNAL_ADD (queue);
1873 }
1875 return;
1877 /* ERRORS */
1878 unexpected_event:
1879 {
1880 g_warning
1881 ("Unexpected event of kind %s can't be added in temp file of queue %s ",
1882 gst_event_type_get_name (GST_EVENT_TYPE (item)),
1883 GST_OBJECT_NAME (queue));
1884 gst_event_unref (GST_EVENT_CAST (item));
1885 return;
1886 }
1887 }
1889 /* dequeue an item from the queue and update level stats */
1890 static GstMiniObject *
1891 gst_queue2_locked_dequeue (GstQueue2 * queue, gboolean * is_buffer)
1892 {
1893 GstMiniObject *item;
1895 if (!QUEUE_IS_USING_QUEUE (queue))
1896 item = gst_queue2_read_item_from_file (queue);
1897 else
1898 item = g_queue_pop_head (queue->queue);
1900 if (item == NULL)
1901 goto no_item;
1903 if (GST_IS_BUFFER (item)) {
1904 GstBuffer *buffer;
1905 guint size;
1907 buffer = GST_BUFFER_CAST (item);
1908 size = GST_BUFFER_SIZE (buffer);
1909 *is_buffer = TRUE;
1911 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1912 "retrieved buffer %p from queue", buffer);
1914 if (QUEUE_IS_USING_QUEUE (queue)) {
1915 queue->cur_level.buffers--;
1916 queue->cur_level.bytes -= size;
1917 }
1918 queue->bytes_out += size;
1920 apply_buffer (queue, buffer, &queue->src_segment, FALSE);
1921 /* update the byterate stats */
1922 update_out_rates (queue);
1923 /* update the buffering */
1924 if (queue->use_buffering)
1925 update_buffering (queue);
1927 } else if (GST_IS_EVENT (item)) {
1928 GstEvent *event = GST_EVENT_CAST (item);
1930 *is_buffer = FALSE;
1932 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
1933 "retrieved event %p from queue", event);
1935 switch (GST_EVENT_TYPE (event)) {
1936 case GST_EVENT_EOS:
1937 /* queue is empty now that we dequeued the EOS */
1938 GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
1939 break;
1940 case GST_EVENT_NEWSEGMENT:
1941 apply_segment (queue, event, &queue->src_segment, FALSE);
1942 break;
1943 default:
1944 break;
1945 }
1946 } else {
1947 g_warning
1948 ("Unexpected item %p dequeued from queue %s (refcounting problem?)",
1949 item, GST_OBJECT_NAME (queue));
1950 item = NULL;
1951 }
1952 GST_QUEUE2_SIGNAL_DEL (queue);
1954 return item;
1956 /* ERRORS */
1957 no_item:
1958 {
1959 GST_CAT_LOG_OBJECT (queue_dataflow, queue, "the queue is empty");
1960 return NULL;
1961 }
1962 }
1964 static gboolean
1965 gst_queue2_handle_sink_event (GstPad * pad, GstEvent * event)
1966 {
1967 GstQueue2 *queue;
1969 queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
1971 switch (GST_EVENT_TYPE (event)) {
1972 case GST_EVENT_FLUSH_START:
1973 {
1974 GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush start event");
1975 if (QUEUE_IS_USING_QUEUE (queue)) {
1976 /* forward event */
1977 gst_pad_push_event (queue->srcpad, event);
1979 /* now unblock the chain function */
1980 GST_QUEUE2_MUTEX_LOCK (queue);
1981 queue->srcresult = GST_FLOW_WRONG_STATE;
1982 queue->sinkresult = GST_FLOW_WRONG_STATE;
1983 /* unblock the loop and chain functions */
1984 GST_QUEUE2_SIGNAL_ADD (queue);
1985 GST_QUEUE2_SIGNAL_DEL (queue);
1986 GST_QUEUE2_MUTEX_UNLOCK (queue);
1988 /* make sure it pauses, this should happen since we sent
1989 * flush_start downstream. */
1990 gst_pad_pause_task (queue->srcpad);
1991 GST_CAT_LOG_OBJECT (queue_dataflow, queue, "loop stopped");
1992 } else {
1993 GST_QUEUE2_MUTEX_LOCK (queue);
1994 /* flush the sink pad */
1995 queue->sinkresult = GST_FLOW_WRONG_STATE;
1996 GST_QUEUE2_SIGNAL_DEL (queue);
1997 GST_QUEUE2_MUTEX_UNLOCK (queue);
1999 gst_event_unref (event);
2000 }
2001 goto done;
2002 }
2003 case GST_EVENT_FLUSH_STOP:
2004 {
2005 GST_CAT_LOG_OBJECT (queue_dataflow, queue, "received flush stop event");
2007 if (QUEUE_IS_USING_QUEUE (queue)) {
2008 /* forward event */
2009 gst_pad_push_event (queue->srcpad, event);
2011 GST_QUEUE2_MUTEX_LOCK (queue);
2012 gst_queue2_locked_flush (queue);
2013 queue->srcresult = GST_FLOW_OK;
2014 queue->sinkresult = GST_FLOW_OK;
2015 queue->is_eos = FALSE;
2016 queue->unexpected = FALSE;
2017 /* reset rate counters */
2018 reset_rate_timer (queue);
2019 gst_pad_start_task (queue->srcpad, (GstTaskFunction) gst_queue2_loop,
2020 queue->srcpad);
2021 GST_QUEUE2_MUTEX_UNLOCK (queue);
2022 } else {
2023 GST_QUEUE2_MUTEX_LOCK (queue);
2024 queue->segment_event_received = FALSE;
2025 queue->is_eos = FALSE;
2026 queue->unexpected = FALSE;
2027 queue->sinkresult = GST_FLOW_OK;
2028 GST_QUEUE2_MUTEX_UNLOCK (queue);
2030 gst_event_unref (event);
2031 }
2032 goto done;
2033 }
2034 default:
2035 if (GST_EVENT_IS_SERIALIZED (event)) {
2036 /* serialized events go in the queue */
2037 GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2038 /* refuse more events on EOS */
2039 if (queue->is_eos)
2040 goto out_eos;
2041 gst_queue2_locked_enqueue (queue, event, FALSE);
2042 GST_QUEUE2_MUTEX_UNLOCK (queue);
2043 } else {
2044 /* non-serialized events are passed upstream. */
2045 gst_pad_push_event (queue->srcpad, event);
2046 }
2047 break;
2048 }
2049 done:
2050 return TRUE;
2052 /* ERRORS */
2053 out_flushing:
2054 {
2055 GST_DEBUG_OBJECT (queue, "refusing event, we are flushing");
2056 GST_QUEUE2_MUTEX_UNLOCK (queue);
2057 gst_event_unref (event);
2058 return FALSE;
2059 }
2060 out_eos:
2061 {
2062 GST_DEBUG_OBJECT (queue, "refusing event, we are EOS");
2063 GST_QUEUE2_MUTEX_UNLOCK (queue);
2064 gst_event_unref (event);
2065 return FALSE;
2066 }
2067 }
2069 static gboolean
2070 gst_queue2_is_empty (GstQueue2 * queue)
2071 {
2072 /* never empty on EOS */
2073 if (queue->is_eos)
2074 return FALSE;
2076 if (!QUEUE_IS_USING_QUEUE (queue) && queue->current) {
2077 return queue->current->writing_pos <= queue->current->max_reading_pos;
2078 } else {
2079 if (queue->queue->length == 0)
2080 return TRUE;
2081 }
2083 return FALSE;
2084 }
2086 static gboolean
2087 gst_queue2_is_filled (GstQueue2 * queue)
2088 {
2089 gboolean res;
2091 /* always filled on EOS */
2092 if (queue->is_eos)
2093 return TRUE;
2095 #define CHECK_FILLED(format,alt_max) ((queue->max_level.format) > 0 && \
2096 (queue->cur_level.format) >= ((alt_max) ? \
2097 MIN ((queue->max_level.format), (alt_max)) : (queue->max_level.format)))
2099 /* if using a ring buffer we're filled if all ring buffer space is used
2100 * _by the current range_ */
2101 if (QUEUE_IS_USING_RING_BUFFER (queue)) {
2102 guint64 rb_size = queue->ring_buffer_max_size;
2103 GST_DEBUG_OBJECT (queue,
2104 "max bytes %u, rb size %" G_GUINT64_FORMAT ", cur bytes %u",
2105 queue->max_level.bytes, rb_size, queue->cur_level.bytes);
2106 return CHECK_FILLED (bytes, rb_size);
2107 }
2109 /* if using file, we're never filled if we don't have EOS */
2110 if (QUEUE_IS_USING_TEMP_FILE (queue))
2111 return FALSE;
2113 /* we are never filled when we have no buffers at all */
2114 if (queue->cur_level.buffers == 0)
2115 return FALSE;
2117 /* we are filled if one of the current levels exceeds the max */
2118 res = CHECK_FILLED (buffers, 0) || CHECK_FILLED (bytes, 0)
2119 || CHECK_FILLED (time, 0);
2121 /* if we need to, use the rate estimate to check against the max time we are
2122 * allowed to queue */
2123 if (queue->use_rate_estimate)
2124 res |= CHECK_FILLED (rate_time, 0);
2126 #undef CHECK_FILLED
2127 return res;
2128 }
2130 static GstFlowReturn
2131 gst_queue2_chain (GstPad * pad, GstBuffer * buffer)
2132 {
2133 GstQueue2 *queue;
2135 queue = GST_QUEUE2 (GST_OBJECT_PARENT (pad));
2137 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2138 "received buffer %p of size %d, time %" GST_TIME_FORMAT ", duration %"
2139 GST_TIME_FORMAT, buffer, GST_BUFFER_SIZE (buffer),
2140 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
2141 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2143 /* we have to lock the queue since we span threads */
2144 GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->sinkresult, out_flushing);
2145 /* when we received EOS, we refuse more data */
2146 if (queue->is_eos)
2147 goto out_eos;
2148 /* when we received unexpected from downstream, refuse more buffers */
2149 if (queue->unexpected)
2150 goto out_unexpected;
2152 if (!gst_queue2_wait_free_space (queue))
2153 goto out_flushing;
2155 /* put buffer in queue now */
2156 gst_queue2_locked_enqueue (queue, buffer, TRUE);
2157 GST_QUEUE2_MUTEX_UNLOCK (queue);
2159 return GST_FLOW_OK;
2161 /* special conditions */
2162 out_flushing:
2163 {
2164 GstFlowReturn ret = queue->sinkresult;
2166 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2167 "exit because task paused, reason: %s", gst_flow_get_name (ret));
2168 GST_QUEUE2_MUTEX_UNLOCK (queue);
2169 gst_buffer_unref (buffer);
2171 return ret;
2172 }
2173 out_eos:
2174 {
2175 GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we received EOS");
2176 GST_QUEUE2_MUTEX_UNLOCK (queue);
2177 gst_buffer_unref (buffer);
2179 return GST_FLOW_UNEXPECTED;
2180 }
2181 out_unexpected:
2182 {
2183 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2184 "exit because we received UNEXPECTED");
2185 GST_QUEUE2_MUTEX_UNLOCK (queue);
2186 gst_buffer_unref (buffer);
2188 return GST_FLOW_UNEXPECTED;
2189 }
2190 }
2192 /* dequeue an item from the queue an push it downstream. This functions returns
2193 * the result of the push. */
2194 static GstFlowReturn
2195 gst_queue2_push_one (GstQueue2 * queue)
2196 {
2197 GstFlowReturn result = GST_FLOW_OK;
2198 GstMiniObject *data;
2199 gboolean is_buffer = FALSE;
2201 data = gst_queue2_locked_dequeue (queue, &is_buffer);
2202 if (data == NULL)
2203 goto no_item;
2205 next:
2206 GST_QUEUE2_MUTEX_UNLOCK (queue);
2208 if (is_buffer) {
2209 GstBuffer *buffer;
2210 GstCaps *caps;
2212 buffer = GST_BUFFER_CAST (data);
2213 caps = GST_BUFFER_CAPS (buffer);
2215 /* set caps before pushing the buffer so that core does not try to do
2216 * something fancy to check if this is possible. */
2217 if (caps && caps != GST_PAD_CAPS (queue->srcpad))
2218 gst_pad_set_caps (queue->srcpad, caps);
2220 result = gst_pad_push (queue->srcpad, buffer);
2222 /* need to check for srcresult here as well */
2223 GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2224 if (result == GST_FLOW_UNEXPECTED) {
2225 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2226 "got UNEXPECTED from downstream");
2227 /* stop pushing buffers, we dequeue all items until we see an item that we
2228 * can push again, which is EOS or NEWSEGMENT. If there is nothing in the
2229 * queue we can push, we set a flag to make the sinkpad refuse more
2230 * buffers with an UNEXPECTED return value until we receive something
2231 * pushable again or we get flushed. */
2232 while ((data = gst_queue2_locked_dequeue (queue, &is_buffer))) {
2233 if (is_buffer) {
2234 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2235 "dropping UNEXPECTED buffer %p", data);
2236 gst_buffer_unref (GST_BUFFER_CAST (data));
2237 } else if (GST_IS_EVENT (data)) {
2238 GstEvent *event = GST_EVENT_CAST (data);
2239 GstEventType type = GST_EVENT_TYPE (event);
2241 if (type == GST_EVENT_EOS || type == GST_EVENT_NEWSEGMENT) {
2242 /* we found a pushable item in the queue, push it out */
2243 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2244 "pushing pushable event %s after UNEXPECTED",
2245 GST_EVENT_TYPE_NAME (event));
2246 goto next;
2247 }
2248 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2249 "dropping UNEXPECTED event %p", event);
2250 gst_event_unref (event);
2251 }
2252 }
2253 /* no more items in the queue. Set the unexpected flag so that upstream
2254 * make us refuse any more buffers on the sinkpad. Since we will still
2255 * accept EOS and NEWSEGMENT we return _FLOW_OK to the caller so that the
2256 * task function does not shut down. */
2257 queue->unexpected = TRUE;
2258 result = GST_FLOW_OK;
2259 }
2260 } else if (GST_IS_EVENT (data)) {
2261 GstEvent *event = GST_EVENT_CAST (data);
2262 GstEventType type = GST_EVENT_TYPE (event);
2264 gst_pad_push_event (queue->srcpad, event);
2266 /* if we're EOS, return UNEXPECTED so that the task pauses. */
2267 if (type == GST_EVENT_EOS) {
2268 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2269 "pushed EOS event %p, return UNEXPECTED", event);
2270 result = GST_FLOW_UNEXPECTED;
2271 }
2273 GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2274 }
2275 return result;
2277 /* ERRORS */
2278 no_item:
2279 {
2280 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2281 "exit because we have no item in the queue");
2282 return GST_FLOW_ERROR;
2283 }
2284 out_flushing:
2285 {
2286 GST_CAT_LOG_OBJECT (queue_dataflow, queue, "exit because we are flushing");
2287 return GST_FLOW_WRONG_STATE;
2288 }
2289 }
2291 /* called repeadedly with @pad as the source pad. This function should push out
2292 * data to the peer element. */
2293 static void
2294 gst_queue2_loop (GstPad * pad)
2295 {
2296 GstQueue2 *queue;
2297 GstFlowReturn ret;
2299 queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2301 /* have to lock for thread-safety */
2302 GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2304 if (gst_queue2_is_empty (queue)) {
2305 gboolean started;
2307 /* pause the timer while we wait. The fact that we are waiting does not mean
2308 * the byterate on the output pad is lower */
2309 if ((started = queue->out_timer_started))
2310 g_timer_stop (queue->out_timer);
2312 GST_CAT_DEBUG_OBJECT (queue_dataflow, queue,
2313 "queue is empty, waiting for new data");
2314 do {
2315 /* Wait for data to be available, we could be unlocked because of a flush. */
2316 GST_QUEUE2_WAIT_ADD_CHECK (queue, queue->srcresult, out_flushing);
2317 }
2318 while (gst_queue2_is_empty (queue));
2320 /* and continue if we were running before */
2321 if (started)
2322 g_timer_continue (queue->out_timer);
2323 }
2324 ret = gst_queue2_push_one (queue);
2325 queue->srcresult = ret;
2326 queue->sinkresult = ret;
2327 if (ret != GST_FLOW_OK)
2328 goto out_flushing;
2330 GST_QUEUE2_MUTEX_UNLOCK (queue);
2332 return;
2334 /* ERRORS */
2335 out_flushing:
2336 {
2337 gboolean eos = queue->is_eos;
2338 GstFlowReturn ret = queue->srcresult;
2340 gst_pad_pause_task (queue->srcpad);
2341 GST_QUEUE2_MUTEX_UNLOCK (queue);
2342 GST_CAT_LOG_OBJECT (queue_dataflow, queue,
2343 "pause task, reason: %s", gst_flow_get_name (queue->srcresult));
2344 /* let app know about us giving up if upstream is not expected to do so */
2345 /* UNEXPECTED is already taken care of elsewhere */
2346 if (eos && (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED)) {
2347 GST_ELEMENT_ERROR (queue, STREAM, FAILED,
2348 (_("Internal data flow error.")),
2349 ("streaming task paused, reason %s (%d)",
2350 gst_flow_get_name (ret), ret));
2351 gst_pad_push_event (queue->srcpad, gst_event_new_eos ());
2352 }
2353 return;
2354 }
2355 }
2357 static gboolean
2358 gst_queue2_handle_src_event (GstPad * pad, GstEvent * event)
2359 {
2360 gboolean res = TRUE;
2361 GstQueue2 *queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2363 #ifndef GST_DISABLE_GST_DEBUG
2364 GST_CAT_DEBUG_OBJECT (queue_dataflow, queue, "got event %p (%s)",
2365 event, GST_EVENT_TYPE_NAME (event));
2366 #endif
2368 switch (GST_EVENT_TYPE (event)) {
2369 case GST_EVENT_FLUSH_START:
2370 if (QUEUE_IS_USING_QUEUE (queue)) {
2371 /* just forward upstream */
2372 res = gst_pad_push_event (queue->sinkpad, event);
2373 } else {
2374 /* now unblock the getrange function */
2375 GST_QUEUE2_MUTEX_LOCK (queue);
2376 GST_DEBUG_OBJECT (queue, "flushing");
2377 queue->srcresult = GST_FLOW_WRONG_STATE;
2378 GST_QUEUE2_SIGNAL_ADD (queue);
2379 GST_QUEUE2_MUTEX_UNLOCK (queue);
2381 /* when using a temp file, we eat the event */
2382 res = TRUE;
2383 gst_event_unref (event);
2384 }
2385 break;
2386 case GST_EVENT_FLUSH_STOP:
2387 if (QUEUE_IS_USING_QUEUE (queue)) {
2388 /* just forward upstream */
2389 res = gst_pad_push_event (queue->sinkpad, event);
2390 } else {
2391 /* now unblock the getrange function */
2392 GST_QUEUE2_MUTEX_LOCK (queue);
2393 queue->srcresult = GST_FLOW_OK;
2394 if (queue->current) {
2395 /* forget the highest read offset, we'll calculate a new one when we
2396 * get the next getrange request. We need to do this in order to reset
2397 * the buffering percentage */
2398 queue->current->max_reading_pos = 0;
2399 }
2400 GST_QUEUE2_MUTEX_UNLOCK (queue);
2402 /* when using a temp file, we eat the event */
2403 res = TRUE;
2404 gst_event_unref (event);
2405 }
2406 break;
2407 default:
2408 res = gst_pad_push_event (queue->sinkpad, event);
2409 break;
2410 }
2412 return res;
2413 }
2415 static gboolean
2416 gst_queue2_peer_query (GstQueue2 * queue, GstPad * pad, GstQuery * query)
2417 {
2418 gboolean ret = FALSE;
2419 GstPad *peer;
2421 if ((peer = gst_pad_get_peer (pad))) {
2422 ret = gst_pad_query (peer, query);
2423 gst_object_unref (peer);
2424 }
2425 return ret;
2426 }
2428 static gboolean
2429 gst_queue2_handle_src_query (GstPad * pad, GstQuery * query)
2430 {
2431 GstQueue2 *queue;
2433 queue = GST_QUEUE2 (GST_PAD_PARENT (pad));
2435 switch (GST_QUERY_TYPE (query)) {
2436 case GST_QUERY_POSITION:
2437 {
2438 gint64 peer_pos;
2439 GstFormat format;
2441 if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2442 goto peer_failed;
2444 /* get peer position */
2445 gst_query_parse_position (query, &format, &peer_pos);
2447 /* FIXME: this code assumes that there's no discont in the queue */
2448 switch (format) {
2449 case GST_FORMAT_BYTES:
2450 peer_pos -= queue->cur_level.bytes;
2451 break;
2452 case GST_FORMAT_TIME:
2453 peer_pos -= queue->cur_level.time;
2454 break;
2455 default:
2456 GST_WARNING_OBJECT (queue, "dropping query in %s format, don't "
2457 "know how to adjust value", gst_format_get_name (format));
2458 return FALSE;
2459 }
2460 /* set updated position */
2461 gst_query_set_position (query, format, peer_pos);
2462 break;
2463 }
2464 case GST_QUERY_DURATION:
2465 {
2466 GST_DEBUG_OBJECT (queue, "doing peer query");
2468 if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2469 goto peer_failed;
2471 GST_DEBUG_OBJECT (queue, "peer query success");
2472 break;
2473 }
2474 case GST_QUERY_BUFFERING:
2475 {
2476 GstFormat format;
2478 GST_DEBUG_OBJECT (queue, "query buffering");
2480 /* FIXME - is this condition correct? what should ring buffer do? */
2481 if (QUEUE_IS_USING_QUEUE (queue)) {
2482 /* no temp file, just forward to the peer */
2483 if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2484 goto peer_failed;
2485 GST_DEBUG_OBJECT (queue, "buffering forwarded to peer");
2486 } else {
2487 gint64 start, stop, range_start, range_stop;
2488 guint64 writing_pos;
2489 gint percent;
2490 gint64 estimated_total, buffering_left;
2491 GstFormat peer_fmt;
2492 gint64 duration;
2493 gboolean peer_res, is_buffering, is_eos;
2494 gdouble byte_in_rate, byte_out_rate;
2495 GstQueue2Range *queued_ranges;
2497 /* we need a current download region */
2498 if (queue->current == NULL)
2499 return FALSE;
2501 writing_pos = queue->current->writing_pos;
2502 byte_in_rate = queue->byte_in_rate;
2503 byte_out_rate = queue->byte_out_rate;
2504 is_buffering = queue->is_buffering;
2505 is_eos = queue->is_eos;
2506 percent = queue->buffering_percent;
2508 if (is_eos) {
2509 /* we're EOS, we know the duration in bytes now */
2510 peer_res = TRUE;
2511 duration = writing_pos;
2512 } else {
2513 /* get duration of upstream in bytes */
2514 peer_fmt = GST_FORMAT_BYTES;
2515 peer_res = gst_pad_query_peer_duration (queue->sinkpad, &peer_fmt,
2516 &duration);
2517 }
2519 /* calculate remaining and total download time */
2520 if (peer_res && byte_in_rate > 0.0) {
2521 estimated_total = (duration * 1000) / byte_in_rate;
2522 buffering_left = ((duration - writing_pos) * 1000) / byte_in_rate;
2523 } else {
2524 estimated_total = -1;
2525 buffering_left = -1;
2526 }
2527 GST_DEBUG_OBJECT (queue, "estimated %" G_GINT64_FORMAT ", left %"
2528 G_GINT64_FORMAT, estimated_total, buffering_left);
2530 gst_query_parse_buffering_range (query, &format, NULL, NULL, NULL);
2532 switch (format) {
2533 case GST_FORMAT_PERCENT:
2534 /* we need duration */
2535 if (!peer_res)
2536 goto peer_failed;
2538 GST_DEBUG_OBJECT (queue,
2539 "duration %" G_GINT64_FORMAT ", writing %" G_GINT64_FORMAT,
2540 duration, writing_pos);
2542 start = 0;
2543 /* get our available data relative to the duration */
2544 if (duration != -1)
2545 stop = GST_FORMAT_PERCENT_MAX * writing_pos / duration;
2546 else
2547 stop = -1;
2548 break;
2549 case GST_FORMAT_BYTES:
2550 start = 0;
2551 stop = writing_pos;
2552 break;
2553 default:
2554 start = -1;
2555 stop = -1;
2556 break;
2557 }
2559 /* fill out the buffered ranges */
2560 for (queued_ranges = queue->ranges; queued_ranges;
2561 queued_ranges = queued_ranges->next) {
2562 switch (format) {
2563 case GST_FORMAT_PERCENT:
2564 if (duration == -1) {
2565 range_start = 0;
2566 range_stop = 0;
2567 break;
2568 }
2569 range_start = 100 * queued_ranges->offset / duration;
2570 range_stop = 100 * queued_ranges->writing_pos / duration;
2571 break;
2572 case GST_FORMAT_BYTES:
2573 range_start = queued_ranges->offset;
2574 range_stop = queued_ranges->writing_pos;
2575 break;
2576 default:
2577 range_start = -1;
2578 range_stop = -1;
2579 break;
2580 }
2581 if (range_start == range_stop)
2582 continue;
2583 GST_DEBUG_OBJECT (queue,
2584 "range starting at %" G_GINT64_FORMAT " and finishing at %"
2585 G_GINT64_FORMAT, range_start, range_stop);
2586 gst_query_add_buffering_range (query, range_start, range_stop);
2587 }
2589 gst_query_set_buffering_percent (query, is_buffering, percent);
2590 gst_query_set_buffering_range (query, format, start, stop,
2591 estimated_total);
2592 gst_query_set_buffering_stats (query, GST_BUFFERING_DOWNLOAD,
2593 byte_in_rate, byte_out_rate, buffering_left);
2594 }
2595 break;
2596 }
2597 default:
2598 /* peer handled other queries */
2599 if (!gst_queue2_peer_query (queue, queue->sinkpad, query))
2600 goto peer_failed;
2601 break;
2602 }
2604 return TRUE;
2606 /* ERRORS */
2607 peer_failed:
2608 {
2609 GST_DEBUG_OBJECT (queue, "failed peer query");
2610 return FALSE;
2611 }
2612 }
2614 static gboolean
2615 gst_queue2_handle_query (GstElement * element, GstQuery * query)
2616 {
2617 /* simply forward to the srcpad query function */
2618 return gst_queue2_handle_src_query (GST_QUEUE2_CAST (element)->srcpad, query);
2619 }
2621 static void
2622 gst_queue2_update_upstream_size (GstQueue2 * queue)
2623 {
2624 GstFormat fmt = GST_FORMAT_BYTES;
2625 gint64 upstream_size = -1;
2627 if (gst_pad_query_peer_duration (queue->sinkpad, &fmt, &upstream_size)) {
2628 GST_INFO_OBJECT (queue, "upstream size: %" G_GINT64_FORMAT, upstream_size);
2629 queue->upstream_size = upstream_size;
2630 }
2631 }
2633 static GstFlowReturn
2634 gst_queue2_get_range (GstPad * pad, guint64 offset, guint length,
2635 GstBuffer ** buffer)
2636 {
2637 GstQueue2 *queue;
2638 GstFlowReturn ret;
2640 queue = GST_QUEUE2_CAST (gst_pad_get_parent (pad));
2642 length = (length == -1) ? DEFAULT_BUFFER_SIZE : length;
2643 GST_QUEUE2_MUTEX_LOCK_CHECK (queue, queue->srcresult, out_flushing);
2644 offset = (offset == -1) ? queue->current->reading_pos : offset;
2646 GST_DEBUG_OBJECT (queue,
2647 "Getting range: offset %" G_GUINT64_FORMAT ", length %u", offset, length);
2649 /* catch any reads beyond the size of the file here to make sure queue2
2650 * doesn't send seek events beyond the size of the file upstream, since
2651 * that would confuse elements such as souphttpsrc and/or http servers.
2652 * Demuxers often just loop until EOS at the end of the file to figure out
2653 * when they've read all the end-headers or index chunks. */
2654 if (G_UNLIKELY (offset >= queue->upstream_size)) {
2655 gst_queue2_update_upstream_size (queue);
2656 if (queue->upstream_size > 0 && offset >= queue->upstream_size)
2657 goto out_unexpected;
2658 }
2660 /* FIXME - function will block when the range is not yet available */
2661 ret = gst_queue2_create_read (queue, offset, length, buffer);
2662 GST_QUEUE2_MUTEX_UNLOCK (queue);
2664 gst_object_unref (queue);
2666 return ret;
2668 /* ERRORS */
2669 out_flushing:
2670 {
2671 ret = queue->srcresult;
2673 GST_DEBUG_OBJECT (queue, "we are flushing");
2674 GST_QUEUE2_MUTEX_UNLOCK (queue);
2675 gst_object_unref (queue);
2676 return ret;
2677 }
2678 out_unexpected:
2679 {
2680 GST_DEBUG_OBJECT (queue, "read beyond end of file");
2681 GST_QUEUE2_MUTEX_UNLOCK (queue);
2682 gst_object_unref (queue);
2683 return GST_FLOW_UNEXPECTED;
2684 }
2685 }
2687 static gboolean
2688 gst_queue2_src_checkgetrange_function (GstPad * pad)
2689 {
2690 GstQueue2 *queue;
2691 gboolean ret;
2693 queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2695 /* we can operate in pull mode when we are using a tempfile */
2696 ret = !QUEUE_IS_USING_QUEUE (queue);
2698 gst_object_unref (GST_OBJECT (queue));
2700 return ret;
2701 }
2703 /* sink currently only operates in push mode */
2704 static gboolean
2705 gst_queue2_sink_activate_push (GstPad * pad, gboolean active)
2706 {
2707 gboolean result = TRUE;
2708 GstQueue2 *queue;
2710 queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2712 if (active) {
2713 GST_QUEUE2_MUTEX_LOCK (queue);
2714 GST_DEBUG_OBJECT (queue, "activating push mode");
2715 queue->srcresult = GST_FLOW_OK;
2716 queue->sinkresult = GST_FLOW_OK;
2717 queue->is_eos = FALSE;
2718 queue->unexpected = FALSE;
2719 reset_rate_timer (queue);
2720 GST_QUEUE2_MUTEX_UNLOCK (queue);
2721 } else {
2722 /* unblock chain function */
2723 GST_QUEUE2_MUTEX_LOCK (queue);
2724 GST_DEBUG_OBJECT (queue, "deactivating push mode");
2725 queue->srcresult = GST_FLOW_WRONG_STATE;
2726 queue->sinkresult = GST_FLOW_WRONG_STATE;
2727 gst_queue2_locked_flush (queue);
2728 GST_QUEUE2_MUTEX_UNLOCK (queue);
2729 }
2731 gst_object_unref (queue);
2733 return result;
2734 }
2736 /* src operating in push mode, we start a task on the source pad that pushes out
2737 * buffers from the queue */
2738 static gboolean
2739 gst_queue2_src_activate_push (GstPad * pad, gboolean active)
2740 {
2741 gboolean result = FALSE;
2742 GstQueue2 *queue;
2744 queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2746 if (active) {
2747 GST_QUEUE2_MUTEX_LOCK (queue);
2748 GST_DEBUG_OBJECT (queue, "activating push mode");
2749 queue->srcresult = GST_FLOW_OK;
2750 queue->sinkresult = GST_FLOW_OK;
2751 queue->is_eos = FALSE;
2752 queue->unexpected = FALSE;
2753 result = gst_pad_start_task (pad, (GstTaskFunction) gst_queue2_loop, pad);
2754 GST_QUEUE2_MUTEX_UNLOCK (queue);
2755 } else {
2756 /* unblock loop function */
2757 GST_QUEUE2_MUTEX_LOCK (queue);
2758 GST_DEBUG_OBJECT (queue, "deactivating push mode");
2759 queue->srcresult = GST_FLOW_WRONG_STATE;
2760 queue->sinkresult = GST_FLOW_WRONG_STATE;
2761 /* the item add signal will unblock */
2762 GST_QUEUE2_SIGNAL_ADD (queue);
2763 GST_QUEUE2_MUTEX_UNLOCK (queue);
2765 /* step 2, make sure streaming finishes */
2766 result = gst_pad_stop_task (pad);
2767 }
2769 gst_object_unref (queue);
2771 return result;
2772 }
2774 /* pull mode, downstream will call our getrange function */
2775 static gboolean
2776 gst_queue2_src_activate_pull (GstPad * pad, gboolean active)
2777 {
2778 gboolean result;
2779 GstQueue2 *queue;
2781 queue = GST_QUEUE2 (gst_pad_get_parent (pad));
2783 if (active) {
2784 GST_QUEUE2_MUTEX_LOCK (queue);
2785 if (!QUEUE_IS_USING_QUEUE (queue)) {
2786 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2787 /* open the temp file now */
2788 result = gst_queue2_open_temp_location_file (queue);
2789 } else if (!queue->ring_buffer) {
2790 queue->ring_buffer = g_malloc (queue->ring_buffer_max_size);
2791 result = !!queue->ring_buffer;
2792 } else {
2793 result = TRUE;
2794 }
2796 GST_DEBUG_OBJECT (queue, "activating pull mode");
2797 init_ranges (queue);
2798 queue->srcresult = GST_FLOW_OK;
2799 queue->sinkresult = GST_FLOW_OK;
2800 queue->is_eos = FALSE;
2801 queue->unexpected = FALSE;
2802 queue->upstream_size = 0;
2803 GST_QUEUE2_MUTEX_UNLOCK (queue);
2804 } else {
2805 GST_QUEUE2_MUTEX_LOCK (queue);
2806 GST_DEBUG_OBJECT (queue, "no temp file, cannot activate pull mode");
2807 /* this is not allowed, we cannot operate in pull mode without a temp
2808 * file. */
2809 queue->srcresult = GST_FLOW_WRONG_STATE;
2810 queue->sinkresult = GST_FLOW_WRONG_STATE;
2811 result = FALSE;
2812 GST_QUEUE2_MUTEX_UNLOCK (queue);
2813 }
2814 } else {
2815 GST_QUEUE2_MUTEX_LOCK (queue);
2816 GST_DEBUG_OBJECT (queue, "deactivating pull mode");
2817 queue->srcresult = GST_FLOW_WRONG_STATE;
2818 queue->sinkresult = GST_FLOW_WRONG_STATE;
2819 /* this will unlock getrange */
2820 GST_QUEUE2_SIGNAL_ADD (queue);
2821 result = TRUE;
2822 GST_QUEUE2_MUTEX_UNLOCK (queue);
2823 }
2824 gst_object_unref (queue);
2826 return result;
2827 }
2829 static GstStateChangeReturn
2830 gst_queue2_change_state (GstElement * element, GstStateChange transition)
2831 {
2832 GstQueue2 *queue;
2833 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2835 queue = GST_QUEUE2 (element);
2837 switch (transition) {
2838 case GST_STATE_CHANGE_NULL_TO_READY:
2839 break;
2840 case GST_STATE_CHANGE_READY_TO_PAUSED:
2841 GST_QUEUE2_MUTEX_LOCK (queue);
2842 if (!QUEUE_IS_USING_QUEUE (queue)) {
2843 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2844 if (!gst_queue2_open_temp_location_file (queue))
2845 ret = GST_STATE_CHANGE_FAILURE;
2846 } else {
2847 if (queue->ring_buffer) {
2848 g_free (queue->ring_buffer);
2849 queue->ring_buffer = NULL;
2850 }
2851 if (!(queue->ring_buffer = g_malloc (queue->ring_buffer_max_size)))
2852 ret = GST_STATE_CHANGE_FAILURE;
2853 }
2854 init_ranges (queue);
2855 }
2856 queue->segment_event_received = FALSE;
2857 queue->starting_segment = NULL;
2858 GST_QUEUE2_MUTEX_UNLOCK (queue);
2859 break;
2860 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2861 break;
2862 default:
2863 break;
2864 }
2866 if (ret == GST_STATE_CHANGE_FAILURE)
2867 return ret;
2869 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2871 if (ret == GST_STATE_CHANGE_FAILURE)
2872 return ret;
2874 switch (transition) {
2875 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2876 break;
2877 case GST_STATE_CHANGE_PAUSED_TO_READY:
2878 GST_QUEUE2_MUTEX_LOCK (queue);
2879 if (!QUEUE_IS_USING_QUEUE (queue)) {
2880 if (QUEUE_IS_USING_TEMP_FILE (queue)) {
2881 gst_queue2_close_temp_location_file (queue);
2882 } else if (queue->ring_buffer) {
2883 g_free (queue->ring_buffer);
2884 queue->ring_buffer = NULL;
2885 }
2886 }
2887 if (queue->starting_segment != NULL) {
2888 gst_event_unref (queue->starting_segment);
2889 queue->starting_segment = NULL;
2890 }
2891 GST_QUEUE2_MUTEX_UNLOCK (queue);
2892 break;
2893 case GST_STATE_CHANGE_READY_TO_NULL:
2894 break;
2895 default:
2896 break;
2897 }
2899 return ret;
2900 }
2902 /* changing the capacity of the queue must wake up
2903 * the _chain function, it might have more room now
2904 * to store the buffer/event in the queue */
2905 #define QUEUE_CAPACITY_CHANGE(q)\
2906 GST_QUEUE2_SIGNAL_DEL (queue);
2908 /* Changing the minimum required fill level must
2909 * wake up the _loop function as it might now
2910 * be able to preceed.
2911 */
2912 #define QUEUE_THRESHOLD_CHANGE(q)\
2913 GST_QUEUE2_SIGNAL_ADD (queue);
2915 static void
2916 gst_queue2_set_temp_template (GstQueue2 * queue, const gchar * template)
2917 {
2918 GstState state;
2920 /* the element must be stopped in order to do this */
2921 GST_OBJECT_LOCK (queue);
2922 state = GST_STATE (queue);
2923 if (state != GST_STATE_READY && state != GST_STATE_NULL)
2924 goto wrong_state;
2925 GST_OBJECT_UNLOCK (queue);
2927 /* set new location */
2928 g_free (queue->temp_template);
2929 queue->temp_template = g_strdup (template);
2931 return;
2933 /* ERROR */
2934 wrong_state:
2935 {
2936 GST_WARNING_OBJECT (queue, "setting temp-template property in wrong state");
2937 GST_OBJECT_UNLOCK (queue);
2938 }
2939 }
2941 static void
2942 gst_queue2_set_property (GObject * object,
2943 guint prop_id, const GValue * value, GParamSpec * pspec)
2944 {
2945 GstQueue2 *queue = GST_QUEUE2 (object);
2947 /* someone could change levels here, and since this
2948 * affects the get/put funcs, we need to lock for safety. */
2949 GST_QUEUE2_MUTEX_LOCK (queue);
2951 switch (prop_id) {
2952 case PROP_MAX_SIZE_BYTES:
2953 queue->max_level.bytes = g_value_get_uint (value);
2954 QUEUE_CAPACITY_CHANGE (queue);
2955 break;
2956 case PROP_MAX_SIZE_BUFFERS:
2957 queue->max_level.buffers = g_value_get_uint (value);
2958 QUEUE_CAPACITY_CHANGE (queue);
2959 break;
2960 case PROP_MAX_SIZE_TIME:
2961 queue->max_level.time = g_value_get_uint64 (value);
2962 /* set rate_time to the same value. We use an extra field in the level
2963 * structure so that we can easily access and compare it */
2964 queue->max_level.rate_time = queue->max_level.time;
2965 QUEUE_CAPACITY_CHANGE (queue);
2966 break;
2967 case PROP_USE_BUFFERING:
2968 queue->use_buffering = g_value_get_boolean (value);
2969 break;
2970 case PROP_USE_RATE_ESTIMATE:
2971 queue->use_rate_estimate = g_value_get_boolean (value);
2972 break;
2973 case PROP_LOW_PERCENT:
2974 queue->low_percent = g_value_get_int (value);
2975 break;
2976 case PROP_HIGH_PERCENT:
2977 queue->high_percent = g_value_get_int (value);
2978 break;
2979 case PROP_TEMP_TEMPLATE:
2980 gst_queue2_set_temp_template (queue, g_value_get_string (value));
2981 break;
2982 case PROP_TEMP_LOCATION:
2983 g_free (queue->temp_location);
2984 queue->temp_location = g_value_dup_string (value);
2985 /* you can set the property back to NULL to make it use the temp-tmpl
2986 * property. */
2987 queue->temp_location_set = queue->temp_location != NULL;
2988 break;
2989 case PROP_TEMP_REMOVE:
2990 queue->temp_remove = g_value_get_boolean (value);
2991 break;
2992 case PROP_RING_BUFFER_MAX_SIZE:
2993 queue->ring_buffer_max_size = g_value_get_uint64 (value);
2994 break;
2995 default:
2996 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2997 break;
2998 }
3000 GST_QUEUE2_MUTEX_UNLOCK (queue);
3001 }
3003 static void
3004 gst_queue2_get_property (GObject * object,
3005 guint prop_id, GValue * value, GParamSpec * pspec)
3006 {
3007 GstQueue2 *queue = GST_QUEUE2 (object);
3009 GST_QUEUE2_MUTEX_LOCK (queue);
3011 switch (prop_id) {
3012 case PROP_CUR_LEVEL_BYTES:
3013 g_value_set_uint (value, queue->cur_level.bytes);
3014 break;
3015 case PROP_CUR_LEVEL_BUFFERS:
3016 g_value_set_uint (value, queue->cur_level.buffers);
3017 break;
3018 case PROP_CUR_LEVEL_TIME:
3019 g_value_set_uint64 (value, queue->cur_level.time);
3020 break;
3021 case PROP_MAX_SIZE_BYTES:
3022 g_value_set_uint (value, queue->max_level.bytes);
3023 break;
3024 case PROP_MAX_SIZE_BUFFERS:
3025 g_value_set_uint (value, queue->max_level.buffers);
3026 break;
3027 case PROP_MAX_SIZE_TIME:
3028 g_value_set_uint64 (value, queue->max_level.time);
3029 break;
3030 case PROP_USE_BUFFERING:
3031 g_value_set_boolean (value, queue->use_buffering);
3032 break;
3033 case PROP_USE_RATE_ESTIMATE:
3034 g_value_set_boolean (value, queue->use_rate_estimate);
3035 break;
3036 case PROP_LOW_PERCENT:
3037 g_value_set_int (value, queue->low_percent);
3038 break;
3039 case PROP_HIGH_PERCENT:
3040 g_value_set_int (value, queue->high_percent);
3041 break;
3042 case PROP_TEMP_TEMPLATE:
3043 g_value_set_string (value, queue->temp_template);
3044 break;
3045 case PROP_TEMP_LOCATION:
3046 g_value_set_string (value, queue->temp_location);
3047 break;
3048 case PROP_TEMP_REMOVE:
3049 g_value_set_boolean (value, queue->temp_remove);
3050 break;
3051 case PROP_RING_BUFFER_MAX_SIZE:
3052 g_value_set_uint64 (value, queue->ring_buffer_max_size);
3053 break;
3054 default:
3055 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3056 break;
3057 }
3059 GST_QUEUE2_MUTEX_UNLOCK (queue);
3060 }