gstqueue2.c 123 KB
Newer Older
1 2 3
/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2003 Colin Walters <cwalters@gnome.org>
Wim Taymans's avatar
Wim Taymans committed
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 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * gstqueue2.c:
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
22 23
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
24 25 26 27
 */

/**
 * SECTION:element-queue2
28
 * @title: queue2
29 30
 *
 * Data is queued until one of the limits specified by the
31 32
 * #GstQueue2:max-size-buffers, #GstQueue2:max-size-bytes and/or
 * #GstQueue2:max-size-time properties has been reached. Any attempt to push
33 34 35 36 37 38 39
 * more buffers into the queue will block the pushing thread until more space
 * becomes available.
 *
 * The queue will create a new thread on the source pad to decouple the
 * processing on sink and source pad.
 *
 * You can query how many buffers are queued by reading the
40
 * #GstQueue2:current-level-buffers property.
41 42 43
 *
 * The default queue size limits are 100 buffers, 2MB of data, or
 * two seconds worth of data, whichever is reached first.
44
 *
45
 * If you set temp-template to a value such as /tmp/gstreamer-XXXXXX, the element
46 47 48
 * will allocate a random free filename and buffer data in the file.
 * By using this, it will buffer the entire stream data on the file independently
 * of the queue size limits, they will only be used for buffering statistics.
49
 *
50 51
 * The temp-location property will be used to notify the application of the
 * allocated filename.
52
 */
53

54 55 56
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
57

58 59
#include "gstqueue2.h"

60 61
#include <glib/gstdio.h>

62
#include "gst/gst-i18n-lib.h"
63
#include "gst/glib-compat-private.h"
64

65 66
#include <string.h>

LRN's avatar
LRN committed
67 68 69 70 71 72
#ifdef G_OS_WIN32
#include <io.h>                 /* lseek, open, close, read */
#undef lseek
#define lseek _lseeki64
#undef off_t
#define off_t guint64
73 74
#else
#include <unistd.h>
LRN's avatar
LRN committed
75 76
#endif

77 78 79 80
#ifdef __BIONIC__               /* Android */
#include <fcntl.h>
#endif

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

GST_DEBUG_CATEGORY_STATIC (queue_debug);
#define GST_CAT_DEFAULT (queue_debug)
GST_DEBUG_CATEGORY_STATIC (queue_dataflow);

enum
{
  LAST_SIGNAL
};

100 101
/* other defines */
#define DEFAULT_BUFFER_SIZE 4096
102
#define QUEUE_IS_USING_TEMP_FILE(queue) ((queue)->temp_template != NULL)
103
#define QUEUE_IS_USING_RING_BUFFER(queue) ((queue)->ring_buffer_max_size != 0)  /* for consistency with the above macro */
Wim Taymans's avatar
Wim Taymans committed
104
#define QUEUE_IS_USING_QUEUE(queue) (!QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER (queue))
105

Wim Taymans's avatar
Wim Taymans committed
106 107
#define QUEUE_MAX_BYTES(queue) MIN((queue)->max_level.bytes, (queue)->ring_buffer_max_size)

108 109 110 111 112
/* default property values */
#define DEFAULT_MAX_SIZE_BUFFERS   100  /* 100 buffers */
#define DEFAULT_MAX_SIZE_BYTES     (2 * 1024 * 1024)    /* 2 MB */
#define DEFAULT_MAX_SIZE_TIME      2 * GST_SECOND       /* 2 seconds */
#define DEFAULT_USE_BUFFERING      FALSE
113
#define DEFAULT_USE_TAGS_BITRATE   FALSE
114
#define DEFAULT_USE_RATE_ESTIMATE  TRUE
115 116
#define DEFAULT_LOW_PERCENT        10
#define DEFAULT_HIGH_PERCENT       99
117 118
#define DEFAULT_LOW_WATERMARK      0.01
#define DEFAULT_HIGH_WATERMARK     0.99
119
#define DEFAULT_TEMP_REMOVE        TRUE
120
#define DEFAULT_RING_BUFFER_MAX_SIZE 0
121

122 123 124 125 126 127 128 129 130 131
enum
{
  PROP_0,
  PROP_CUR_LEVEL_BUFFERS,
  PROP_CUR_LEVEL_BYTES,
  PROP_CUR_LEVEL_TIME,
  PROP_MAX_SIZE_BUFFERS,
  PROP_MAX_SIZE_BYTES,
  PROP_MAX_SIZE_TIME,
  PROP_USE_BUFFERING,
132
  PROP_USE_TAGS_BITRATE,
133 134 135
  PROP_USE_RATE_ESTIMATE,
  PROP_LOW_PERCENT,
  PROP_HIGH_PERCENT,
136 137
  PROP_LOW_WATERMARK,
  PROP_HIGH_WATERMARK,
138
  PROP_TEMP_TEMPLATE,
139 140
  PROP_TEMP_LOCATION,
  PROP_TEMP_REMOVE,
141
  PROP_RING_BUFFER_MAX_SIZE,
142
  PROP_AVG_IN_RATE,
143
  PROP_LAST
144 145
};

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
/* Explanation for buffer levels and percentages:
 *
 * The buffering_level functions here return a value in a normalized range
 * that specifies the queue's current fill level. The range goes from 0 to
 * MAX_BUFFERING_LEVEL. The low/high watermarks also use this same range.
 *
 * This is not to be confused with the buffering_percent value, which is
 * a *relative* quantity - relative to the low/high watermarks.
 * buffering_percent = 0% means buffering_level is at the low watermark.
 * buffering_percent = 100% means buffering_level is at the high watermark.
 * buffering_percent is used for determining if the fill level has reached
 * the high watermark, and for producing BUFFERING messages. This value
 * always uses a 0..100 range (since it is a percentage).
 *
 * To avoid future confusions, whenever "buffering level" is mentioned, it
 * refers to the absolute level which is in the 0..MAX_BUFFERING_LEVEL
 * range. Whenever "buffering_percent" is mentioned, it refers to the
 * percentage value that is relative to the low/high watermark. */

165 166 167 168 169 170
/* Using a buffering level range of 0..1000000 to allow for a
 * resolution in ppm (1 ppm = 0.0001%) */
#define MAX_BUFFERING_LEVEL 1000000

/* How much 1% makes up in the buffer level range */
#define BUF_LEVEL_PERCENT_FACTOR ((MAX_BUFFERING_LEVEL) / 100)
171

172
#define GST_QUEUE2_CLEAR_LEVEL(l) G_STMT_START {         \
173 174 175 176 177 178 179 180 181 182
  l.buffers = 0;                                        \
  l.bytes = 0;                                          \
  l.time = 0;                                           \
  l.rate_time = 0;                                      \
} G_STMT_END

#define STATUS(queue, pad, msg) \
  GST_CAT_LOG_OBJECT (queue_dataflow, queue, \
                      "(%s:%s) " msg ": %u of %u buffers, %u of %u " \
                      "bytes, %" G_GUINT64_FORMAT " of %" G_GUINT64_FORMAT \
183
                      " ns, %"G_GUINT64_FORMAT" items", \
184 185 186 187 188 189 190
                      GST_DEBUG_PAD_NAME (pad), \
                      queue->cur_level.buffers, \
                      queue->max_level.buffers, \
                      queue->cur_level.bytes, \
                      queue->max_level.bytes, \
                      queue->cur_level.time, \
                      queue->max_level.time, \
Wim Taymans's avatar
Wim Taymans committed
191
                      (guint64) (!QUEUE_IS_USING_QUEUE(queue) ? \
192
                        queue->current->writing_pos - queue->current->max_reading_pos : \
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
193
                        gst_queue_array_get_length(queue->queue)))
194

195
#define GST_QUEUE2_MUTEX_LOCK(q) G_STMT_START {                          \
Wim Taymans's avatar
Wim Taymans committed
196
  g_mutex_lock (&q->qlock);                                              \
197 198
} G_STMT_END

199 200 201
#define GST_QUEUE2_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
  GST_QUEUE2_MUTEX_LOCK (q);                                            \
  if (res != GST_FLOW_OK)                                               \
202 203 204
    goto label;                                                         \
} G_STMT_END

205
#define GST_QUEUE2_MUTEX_UNLOCK(q) G_STMT_START {                        \
Wim Taymans's avatar
Wim Taymans committed
206
  g_mutex_unlock (&q->qlock);                                            \
207 208
} G_STMT_END

209
#define GST_QUEUE2_WAIT_DEL_CHECK(q, res, label) G_STMT_START {         \
210 211
  STATUS (queue, q->sinkpad, "wait for DEL");                           \
  q->waiting_del = TRUE;                                                \
Wim Taymans's avatar
Wim Taymans committed
212
  g_cond_wait (&q->item_del, &queue->qlock);                              \
213
  q->waiting_del = FALSE;                                               \
214
  if (res != GST_FLOW_OK) {                                             \
215 216 217 218 219 220
    STATUS (queue, q->srcpad, "received DEL wakeup");                   \
    goto label;                                                         \
  }                                                                     \
  STATUS (queue, q->sinkpad, "received DEL");                           \
} G_STMT_END

221
#define GST_QUEUE2_WAIT_ADD_CHECK(q, res, label) G_STMT_START {         \
222 223
  STATUS (queue, q->srcpad, "wait for ADD");                            \
  q->waiting_add = TRUE;                                                \
Wim Taymans's avatar
Wim Taymans committed
224
  g_cond_wait (&q->item_add, &q->qlock);                                  \
225
  q->waiting_add = FALSE;                                               \
226
  if (res != GST_FLOW_OK) {                                             \
227 228 229 230 231 232
    STATUS (queue, q->srcpad, "received ADD wakeup");                   \
    goto label;                                                         \
  }                                                                     \
  STATUS (queue, q->srcpad, "received ADD");                            \
} G_STMT_END

233
#define GST_QUEUE2_SIGNAL_DEL(q) G_STMT_START {                          \
234 235
  if (q->waiting_del) {                                                 \
    STATUS (q, q->srcpad, "signal DEL");                                \
Wim Taymans's avatar
Wim Taymans committed
236
    g_cond_signal (&q->item_del);                                        \
237 238 239
  }                                                                     \
} G_STMT_END

240
#define GST_QUEUE2_SIGNAL_ADD(q) G_STMT_START {                          \
241 242
  if (q->waiting_add) {                                                 \
    STATUS (q, q->sinkpad, "signal ADD");                               \
Wim Taymans's avatar
Wim Taymans committed
243
    g_cond_signal (&q->item_add);                                        \
244 245 246
  }                                                                     \
} G_STMT_END

247 248 249 250 251 252 253 254 255 256
#define SET_PERCENT(q, perc) G_STMT_START {                              \
  if (perc != q->buffering_percent) {                                    \
    q->buffering_percent = perc;                                         \
    q->percent_changed = TRUE;                                           \
    GST_DEBUG_OBJECT (q, "buffering %d percent", perc);                  \
    get_buffering_stats (q, perc, &q->mode, &q->avg_in, &q->avg_out,     \
        &q->buffering_left);                                             \
  }                                                                      \
} G_STMT_END

257
#define _do_init \
258 259 260
    GST_DEBUG_CATEGORY_INIT (queue_debug, "queue2", 0, "queue element"); \
    GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue2_dataflow", 0, \
        "dataflow inside the queue element");
261 262
#define gst_queue2_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstQueue2, gst_queue2, GST_TYPE_ELEMENT, _do_init);
263

264
static void gst_queue2_finalize (GObject * object);
265

266
static void gst_queue2_set_property (GObject * object,
267
    guint prop_id, const GValue * value, GParamSpec * pspec);
268
static void gst_queue2_get_property (GObject * object,
269 270
    guint prop_id, GValue * value, GParamSpec * pspec);

271 272
static GstFlowReturn gst_queue2_chain (GstPad * pad, GstObject * parent,
    GstBuffer * buffer);
273
static GstFlowReturn gst_queue2_chain_list (GstPad * pad, GstObject * parent,
274
    GstBufferList * buffer_list);
275 276
static GstFlowReturn gst_queue2_push_one (GstQueue2 * queue);
static void gst_queue2_loop (GstPad * pad);
277

278 279
static GstFlowReturn gst_queue2_handle_sink_event (GstPad * pad,
    GstObject * parent, GstEvent * event);
280 281
static gboolean gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
    GstQuery * query);
282

283 284
static gboolean gst_queue2_handle_src_event (GstPad * pad, GstObject * parent,
    GstEvent * event);
285 286
static gboolean gst_queue2_handle_src_query (GstPad * pad, GstObject * parent,
    GstQuery * query);
287
static gboolean gst_queue2_handle_query (GstElement * element,
288
    GstQuery * query);
289

290 291
static GstFlowReturn gst_queue2_get_range (GstPad * pad, GstObject * parent,
    guint64 offset, guint length, GstBuffer ** buffer);
292

293 294 295 296
static gboolean gst_queue2_src_activate_mode (GstPad * pad, GstObject * parent,
    GstPadMode mode, gboolean active);
static gboolean gst_queue2_sink_activate_mode (GstPad * pad, GstObject * parent,
    GstPadMode mode, gboolean active);
297
static GstStateChangeReturn gst_queue2_change_state (GstElement * element,
298 299
    GstStateChange transition);

300 301
static gboolean gst_queue2_is_empty (GstQueue2 * queue);
static gboolean gst_queue2_is_filled (GstQueue2 * queue);
302

303
static void update_cur_level (GstQueue2 * queue, GstQueue2Range * range);
304
static void update_in_rates (GstQueue2 * queue, gboolean force);
305
static GstMessage *gst_queue2_get_buffering_message (GstQueue2 * queue);
306
static void gst_queue2_post_buffering (GstQueue2 * queue);
307

308 309 310 311
typedef enum
{
  GST_QUEUE2_ITEM_TYPE_UNKNOWN = 0,
  GST_QUEUE2_ITEM_TYPE_BUFFER,
312
  GST_QUEUE2_ITEM_TYPE_BUFFER_LIST,
313 314
  GST_QUEUE2_ITEM_TYPE_EVENT,
  GST_QUEUE2_ITEM_TYPE_QUERY
315
} GstQueue2ItemType;
316

317 318 319 320 321 322
typedef struct
{
  GstQueue2ItemType type;
  GstMiniObject *item;
} GstQueue2Item;

323
/* static guint gst_queue2_signals[LAST_SIGNAL] = { 0 }; */
324 325

static void
326
gst_queue2_class_init (GstQueue2Class * klass)
327 328 329 330
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);

331 332
  gobject_class->set_property = gst_queue2_set_property;
  gobject_class->get_property = gst_queue2_get_property;
333 334 335 336 337

  /* properties */
  g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BYTES,
      g_param_spec_uint ("current-level-bytes", "Current level (kB)",
          "Current amount of data in the queue (bytes)",
338
          0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
339 340 341
  g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_BUFFERS,
      g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
          "Current number of buffers in the queue",
342
          0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
343 344 345
  g_object_class_install_property (gobject_class, PROP_CUR_LEVEL_TIME,
      g_param_spec_uint64 ("current-level-time", "Current level (ns)",
          "Current amount of data in the queue (in ns)",
346
          0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
347 348 349 350

  g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BYTES,
      g_param_spec_uint ("max-size-bytes", "Max. size (kB)",
          "Max. amount of data in the queue (bytes, 0=disable)",
351
          0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
352 353
          G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
          G_PARAM_STATIC_STRINGS));
354 355
  g_object_class_install_property (gobject_class, PROP_MAX_SIZE_BUFFERS,
      g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
356 357
          "Max. number of buffers in the queue (0=disable)", 0, G_MAXUINT,
          DEFAULT_MAX_SIZE_BUFFERS,
358 359
          G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
          G_PARAM_STATIC_STRINGS));
360 361
  g_object_class_install_property (gobject_class, PROP_MAX_SIZE_TIME,
      g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
362
          "Max. amount of data in the queue (in ns, 0=disable)", 0, G_MAXUINT64,
363 364
          DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
          G_PARAM_STATIC_STRINGS));
365 366 367 368

  g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
      g_param_spec_boolean ("use-buffering", "Use buffering",
          "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
369 370
          DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
          G_PARAM_STATIC_STRINGS));
371 372 373 374 375 376
  g_object_class_install_property (gobject_class, PROP_USE_TAGS_BITRATE,
      g_param_spec_boolean ("use-tags-bitrate", "Use bitrate from tags",
          "Use a bitrate from upstream tags to estimate buffer duration if not provided",
          DEFAULT_USE_TAGS_BITRATE,
          G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
          G_PARAM_STATIC_STRINGS));
377 378 379
  g_object_class_install_property (gobject_class, PROP_USE_RATE_ESTIMATE,
      g_param_spec_boolean ("use-rate-estimate", "Use Rate Estimate",
          "Estimate the bitrate of the stream to calculate time level",
380 381
          DEFAULT_USE_RATE_ESTIMATE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
382 383
  g_object_class_install_property (gobject_class, PROP_LOW_PERCENT,
      g_param_spec_int ("low-percent", "Low percent",
384 385 386
          "Low threshold for buffering to start. Only used if use-buffering is True "
          "(Deprecated: use low-watermark instead)",
          0, 100, DEFAULT_LOW_WATERMARK * 100,
387
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388 389
  g_object_class_install_property (gobject_class, PROP_HIGH_PERCENT,
      g_param_spec_int ("high-percent", "High percent",
390 391 392 393 394 395 396 397 398 399 400
          "High threshold for buffering to finish. Only used if use-buffering is True "
          "(Deprecated: use high-watermark instead)",
          0, 100, DEFAULT_HIGH_WATERMARK * 100,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_LOW_WATERMARK,
      g_param_spec_double ("low-watermark", "Low watermark",
          "Low threshold for buffering to start. Only used if use-buffering is True",
          0.0, 1.0, DEFAULT_LOW_WATERMARK,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_HIGH_WATERMARK,
      g_param_spec_double ("high-watermark", "High watermark",
401
          "High threshold for buffering to finish. Only used if use-buffering is True",
402
          0.0, 1.0, DEFAULT_HIGH_WATERMARK,
403
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
404

405 406 407 408 409 410
  g_object_class_install_property (gobject_class, PROP_TEMP_TEMPLATE,
      g_param_spec_string ("temp-template", "Temporary File Template",
          "File template to store temporary files in, should contain directory "
          "and XXXXXX. (NULL == disabled)",
          NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

411 412
  g_object_class_install_property (gobject_class, PROP_TEMP_LOCATION,
      g_param_spec_string ("temp-location", "Temporary File Location",
413 414 415
          "Location to store temporary files in (Only read this property, "
          "use temp-template to configure the name template)",
          NULL, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
416

417 418 419 420 421
  /**
   * GstQueue2:temp-remove
   *
   * When temp-template is set, remove the temporary file when going to READY.
   */
422 423 424 425 426
  g_object_class_install_property (gobject_class, PROP_TEMP_REMOVE,
      g_param_spec_boolean ("temp-remove", "Remove the Temporary File",
          "Remove the temp-location after use",
          DEFAULT_TEMP_REMOVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

427 428 429
  /**
   * GstQueue2:ring-buffer-max-size
   *
430 431
   * The maximum size of the ring buffer in bytes. If set to 0, the ring
   * buffer is disabled. Default 0.
432 433
   */
  g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
434
      g_param_spec_uint64 ("ring-buffer-max-size",
435
          "Max. ring buffer size (bytes)",
436
          "Max. amount of data in the ring buffer (bytes, 0 = disabled)",
437
          0, G_MAXUINT64, DEFAULT_RING_BUFFER_MAX_SIZE,
438 439
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

440 441 442 443 444 445 446 447 448 449
  /**
   * GstQueue2:avg-in-rate
   *
   * The average input data rate.
   */
  g_object_class_install_property (gobject_class, PROP_AVG_IN_RATE,
      g_param_spec_int64 ("avg-in-rate", "Input data rate (bytes/s)",
          "Average input data rate (bytes/s)",
          0, G_MAXINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));

450
  /* set several parent class virtual functions */
451
  gobject_class->finalize = gst_queue2_finalize;
452

453 454
  gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
  gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
455

456
  gst_element_class_set_static_metadata (gstelement_class, "Queue 2",
457 458 459 460 461
      "Generic",
      "Simple data queue",
      "Erik Walthinsen <omega@cse.ogi.edu>, "
      "Wim Taymans <wim.taymans@gmail.com>");

462
  gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_queue2_change_state);
463
  gstelement_class->query = GST_DEBUG_FUNCPTR (gst_queue2_handle_query);
464 465 466
}

static void
467
gst_queue2_init (GstQueue2 * queue)
468 469 470 471
{
  queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");

  gst_pad_set_chain_function (queue->sinkpad,
472
      GST_DEBUG_FUNCPTR (gst_queue2_chain));
473 474
  gst_pad_set_chain_list_function (queue->sinkpad,
      GST_DEBUG_FUNCPTR (gst_queue2_chain_list));
475 476
  gst_pad_set_activatemode_function (queue->sinkpad,
      GST_DEBUG_FUNCPTR (gst_queue2_sink_activate_mode));
477
  gst_pad_set_event_full_function (queue->sinkpad,
478
      GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_event));
Wim Taymans's avatar
Wim Taymans committed
479 480
  gst_pad_set_query_function (queue->sinkpad,
      GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_query));
Wim Taymans's avatar
Wim Taymans committed
481
  GST_PAD_SET_PROXY_CAPS (queue->sinkpad);
482 483 484 485
  gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);

  queue->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");

486 487
  gst_pad_set_activatemode_function (queue->srcpad,
      GST_DEBUG_FUNCPTR (gst_queue2_src_activate_mode));
488
  gst_pad_set_getrange_function (queue->srcpad,
489
      GST_DEBUG_FUNCPTR (gst_queue2_get_range));
490
  gst_pad_set_event_function (queue->srcpad,
491
      GST_DEBUG_FUNCPTR (gst_queue2_handle_src_event));
492
  gst_pad_set_query_function (queue->srcpad,
493
      GST_DEBUG_FUNCPTR (gst_queue2_handle_src_query));
Wim Taymans's avatar
Wim Taymans committed
494
  GST_PAD_SET_PROXY_CAPS (queue->srcpad);
495 496 497
  gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);

  /* levels */
498
  GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
499 500 501 502 503 504
  queue->max_level.buffers = DEFAULT_MAX_SIZE_BUFFERS;
  queue->max_level.bytes = DEFAULT_MAX_SIZE_BYTES;
  queue->max_level.time = DEFAULT_MAX_SIZE_TIME;
  queue->max_level.rate_time = DEFAULT_MAX_SIZE_TIME;
  queue->use_buffering = DEFAULT_USE_BUFFERING;
  queue->use_rate_estimate = DEFAULT_USE_RATE_ESTIMATE;
505 506
  queue->low_watermark = DEFAULT_LOW_WATERMARK * MAX_BUFFERING_LEVEL;
  queue->high_watermark = DEFAULT_HIGH_WATERMARK * MAX_BUFFERING_LEVEL;
507 508 509 510

  gst_segment_init (&queue->sink_segment, GST_FORMAT_TIME);
  gst_segment_init (&queue->src_segment, GST_FORMAT_TIME);

511 512 513 514 515
  queue->sinktime = GST_CLOCK_TIME_NONE;
  queue->srctime = GST_CLOCK_TIME_NONE;
  queue->sink_tainted = TRUE;
  queue->src_tainted = TRUE;

516 517
  queue->srcresult = GST_FLOW_FLUSHING;
  queue->sinkresult = GST_FLOW_FLUSHING;
518
  queue->is_eos = FALSE;
519 520
  queue->in_timer = g_timer_new ();
  queue->out_timer = g_timer_new ();
521

Wim Taymans's avatar
Wim Taymans committed
522
  g_mutex_init (&queue->qlock);
523
  queue->waiting_add = FALSE;
Wim Taymans's avatar
Wim Taymans committed
524
  g_cond_init (&queue->item_add);
525
  queue->waiting_del = FALSE;
Wim Taymans's avatar
Wim Taymans committed
526
  g_cond_init (&queue->item_del);
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
527
  queue->queue = gst_queue_array_new_for_struct (sizeof (GstQueue2Item), 32);
528

529 530 531
  g_cond_init (&queue->query_handled);
  queue->last_query = FALSE;

532
  g_mutex_init (&queue->buffering_post_lock);
533 534
  queue->buffering_percent = 100;

535
  /* tempfile related */
536
  queue->temp_template = NULL;
537
  queue->temp_location = NULL;
538
  queue->temp_remove = DEFAULT_TEMP_REMOVE;
539

540
  queue->ring_buffer = NULL;
541
  queue->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
542

543 544 545 546 547 548
  GST_DEBUG_OBJECT (queue,
      "initialized queue's not_empty & not_full conditions");
}

/* called only once, as opposed to dispose */
static void
549
gst_queue2_finalize (GObject * object)
550
{
551
  GstQueue2 *queue = GST_QUEUE2 (object);
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
552
  GstQueue2Item *qitem;
553 554 555

  GST_DEBUG_OBJECT (queue, "finalizing queue");

Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
556
  while ((qitem = gst_queue_array_pop_head_struct (queue->queue))) {
557 558
    if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
      gst_mini_object_unref (qitem->item);
559
  }
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
560
  gst_queue_array_free (queue->queue);
561

562
  queue->last_query = FALSE;
Wim Taymans's avatar
Wim Taymans committed
563
  g_mutex_clear (&queue->qlock);
564
  g_mutex_clear (&queue->buffering_post_lock);
Wim Taymans's avatar
Wim Taymans committed
565 566
  g_cond_clear (&queue->item_add);
  g_cond_clear (&queue->item_del);
567
  g_cond_clear (&queue->query_handled);
568 569
  g_timer_destroy (queue->in_timer);
  g_timer_destroy (queue->out_timer);
570

571
  /* temp_file path cleanup  */
572 573
  g_free (queue->temp_template);
  g_free (queue->temp_location);
574

575 576 577
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

578 579 580 581 582 583
static void
debug_ranges (GstQueue2 * queue)
{
  GstQueue2Range *walk;

  for (walk = queue->ranges; walk; walk = walk->next) {
584 585 586 587 588 589
    GST_DEBUG_OBJECT (queue,
        "range [%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "] (rb [%"
        G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT "]), reading %" G_GUINT64_FORMAT
        " current range? %s", walk->offset, walk->writing_pos, walk->rb_offset,
        walk->rb_writing_pos, walk->reading_pos,
        walk == queue->current ? "**y**" : "  n  ");
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
  }
}

/* clear all the downloaded ranges */
static void
clean_ranges (GstQueue2 * queue)
{
  GST_DEBUG_OBJECT (queue, "clean queue ranges");

  g_slice_free_chain (GstQueue2Range, queue->ranges, next);
  queue->ranges = NULL;
  queue->current = NULL;
}

/* find a range that contains @offset or NULL when nothing does */
static GstQueue2Range *
606
find_range (GstQueue2 * queue, guint64 offset)
607
{
608 609
  GstQueue2Range *range = NULL;
  GstQueue2Range *walk;
610 611 612 613 614 615 616 617 618

  /* first do a quick check for the current range */
  for (walk = queue->ranges; walk; walk = walk->next) {
    if (offset >= walk->offset && offset <= walk->writing_pos) {
      /* we can reuse an existing range */
      range = walk;
      break;
    }
  }
Robert Swain's avatar
Robert Swain committed
619 620 621 622 623 624 625
  if (range) {
    GST_DEBUG_OBJECT (queue,
        "found range for %" G_GUINT64_FORMAT ": [%" G_GUINT64_FORMAT "-%"
        G_GUINT64_FORMAT "]", offset, range->offset, range->writing_pos);
  } else {
    GST_DEBUG_OBJECT (queue, "no range for %" G_GUINT64_FORMAT, offset);
  }
626 627 628
  return range;
}

Wim Taymans's avatar
Wim Taymans committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642
static void
update_cur_level (GstQueue2 * queue, GstQueue2Range * range)
{
  guint64 max_reading_pos, writing_pos;

  writing_pos = range->writing_pos;
  max_reading_pos = range->max_reading_pos;

  if (writing_pos > max_reading_pos)
    queue->cur_level.bytes = writing_pos - max_reading_pos;
  else
    queue->cur_level.bytes = 0;
}

643 644
/* make a new range for @offset or reuse an existing range */
static GstQueue2Range *
645
add_range (GstQueue2 * queue, guint64 offset, gboolean update_existing)
646 647 648 649 650
{
  GstQueue2Range *range, *prev, *next;

  GST_DEBUG_OBJECT (queue, "find range for %" G_GUINT64_FORMAT, offset);

651
  if ((range = find_range (queue, offset))) {
652 653 654
    GST_DEBUG_OBJECT (queue,
        "reusing range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, range->offset,
        range->writing_pos);
655 656 657 658 659
    if (update_existing && range->writing_pos != offset) {
      GST_DEBUG_OBJECT (queue, "updating range writing position to "
          "%" G_GUINT64_FORMAT, offset);
      range->writing_pos = offset;
    }
660 661 662 663 664 665
  } else {
    GST_DEBUG_OBJECT (queue,
        "new range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, offset);

    range = g_slice_new0 (GstQueue2Range);
    range->offset = offset;
666 667
    /* we want to write to the next location in the ring buffer */
    range->rb_offset = queue->current ? queue->current->rb_writing_pos : 0;
668
    range->writing_pos = offset;
669
    range->rb_writing_pos = range->rb_offset;
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    range->reading_pos = offset;
    range->max_reading_pos = offset;

    /* insert sorted */
    prev = NULL;
    next = queue->ranges;
    while (next) {
      if (next->offset > offset) {
        /* insert before next */
        GST_DEBUG_OBJECT (queue,
            "insert before range %p, offset %" G_GUINT64_FORMAT, next,
            next->offset);
        break;
      }
      /* try next */
      prev = next;
      next = next->next;
    }
    range->next = next;
    if (prev)
      prev->next = range;
    else
      queue->ranges = range;
  }
  debug_ranges (queue);

Wim Taymans's avatar
Wim Taymans committed
696 697 698
  /* update the stats for this range */
  update_cur_level (queue, range);

699 700 701 702 703 704 705 706 707 708 709 710 711
  return range;
}


/* clear and init the download ranges for offset 0 */
static void
init_ranges (GstQueue2 * queue)
{
  GST_DEBUG_OBJECT (queue, "init queue ranges");

  /* get rid of all the current ranges */
  clean_ranges (queue);
  /* make a range for offset 0 */
712
  queue->current = add_range (queue, 0, TRUE);
713 714
}

715 716 717
/* calculate the diff between running time on the sink and src of the queue.
 * This is the total amount of time in the queue. */
static void
718
update_time_level (GstQueue2 * queue)
719
{
720 721 722
  if (queue->sink_tainted) {
    queue->sinktime =
        gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
Wim Taymans's avatar
Wim Taymans committed
723
        queue->sink_segment.position);
724 725
    queue->sink_tainted = FALSE;
  }
726

727 728 729
  if (queue->src_tainted) {
    queue->srctime =
        gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
Wim Taymans's avatar
Wim Taymans committed
730
        queue->src_segment.position);
731 732
    queue->src_tainted = FALSE;
  }
733 734

  GST_DEBUG_OBJECT (queue, "sink %" GST_TIME_FORMAT ", src %" GST_TIME_FORMAT,
735
      GST_TIME_ARGS (queue->sinktime), GST_TIME_ARGS (queue->srctime));
736

737 738 739
  if (queue->sinktime != GST_CLOCK_TIME_NONE
      && queue->srctime != GST_CLOCK_TIME_NONE
      && queue->sinktime >= queue->srctime)
740
    queue->cur_level.time = queue->sinktime - queue->srctime;
741 742 743 744
  else
    queue->cur_level.time = 0;
}

Wim Taymans's avatar
Wim Taymans committed
745
/* take a SEGMENT event and apply the values to segment, updating the time
746 747
 * level of queue. */
static void
748 749
apply_segment (GstQueue2 * queue, GstEvent * event, GstSegment * segment,
    gboolean is_sink)
750
{
751
  gst_event_copy_segment (event, segment);
752

Wim Taymans's avatar
Wim Taymans committed
753
  if (segment->format == GST_FORMAT_BYTES) {
Wim Taymans's avatar
Wim Taymans committed
754
    if (!QUEUE_IS_USING_QUEUE (queue) && is_sink) {
755
      /* start is where we'll be getting from and as such writing next */
756
      queue->current = add_range (queue, segment->start, TRUE);
757
    }
758 759
  }

760 761
  /* now configure the values, we use these to track timestamps on the
   * sinkpad. */
Wim Taymans's avatar
Wim Taymans committed
762
  if (segment->format != GST_FORMAT_TIME) {
763
    /* non-time format, pretend the current time segment is closed with a
764
     * 0 start and unknown stop time. */
Wim Taymans's avatar
Wim Taymans committed
765 766 767 768
    segment->format = GST_FORMAT_TIME;
    segment->start = 0;
    segment->stop = -1;
    segment->time = 0;
769 770
  }

Wim Taymans's avatar
Wim Taymans committed
771
  GST_DEBUG_OBJECT (queue, "configured SEGMENT %" GST_SEGMENT_FORMAT, segment);
772

773 774 775 776 777
  if (is_sink)
    queue->sink_tainted = TRUE;
  else
    queue->src_tainted = TRUE;

778 779 780 781
  /* segment can update the time level of the queue */
  update_time_level (queue);
}

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
static void
apply_gap (GstQueue2 * queue, GstEvent * event,
    GstSegment * segment, gboolean is_sink)
{
  GstClockTime timestamp;
  GstClockTime duration;

  gst_event_parse_gap (event, &timestamp, &duration);

  if (GST_CLOCK_TIME_IS_VALID (timestamp)) {

    if (GST_CLOCK_TIME_IS_VALID (duration)) {
      timestamp += duration;
    }

    segment->position = timestamp;

    if (is_sink)
      queue->sink_tainted = TRUE;
    else
      queue->src_tainted = TRUE;

    /* calc diff with other end */
    update_time_level (queue);
  }
}

809 810
/* take a buffer and update segment, updating the time level of the queue. */
static void
811
apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
812
    guint64 size, gboolean is_sink)
813 814 815
{
  GstClockTime duration, timestamp;

816
  timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
817 818
  duration = GST_BUFFER_DURATION (buffer);

819 820 821 822 823 824 825 826
  /* If we have no duration, pick one from the bitrate if we can */
  if (duration == GST_CLOCK_TIME_NONE && queue->use_tags_bitrate) {
    guint bitrate =
        is_sink ? queue->sink_tags_bitrate : queue->src_tags_bitrate;
    if (bitrate)
      duration = gst_util_uint64_scale (size, 8 * GST_SECOND, bitrate);
  }

827
  /* if no timestamp is set, assume it's continuous with the previous
828 829
   * time */
  if (timestamp == GST_CLOCK_TIME_NONE)
Wim Taymans's avatar
Wim Taymans committed
830
    timestamp = segment->position;
831 832 833 834 835

  /* add duration */
  if (duration != GST_CLOCK_TIME_NONE)
    timestamp += duration;

Wim Taymans's avatar
Wim Taymans committed
836
  GST_DEBUG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
837 838
      GST_TIME_ARGS (timestamp));

Wim Taymans's avatar
Wim Taymans committed
839
  segment->position = timestamp;
840

841 842 843 844 845
  if (is_sink)
    queue->sink_tainted = TRUE;
  else
    queue->src_tainted = TRUE;

846 847 848 849
  /* calc diff with other end */
  update_time_level (queue);
}

850 851 852 853 854 855
struct BufListData
{
  GstClockTime timestamp;
  guint bitrate;
};

856 857
static gboolean
buffer_list_apply_time (GstBuffer ** buf, guint idx, gpointer data)
858
{
859 860
  struct BufListData *bld = data;
  GstClockTime *timestamp = &bld->timestamp;
861
  GstClockTime btime;
862

863
  GST_TRACE ("buffer %u has pts %" GST_TIME_FORMAT " dts %" GST_TIME_FORMAT
864
      " duration %" GST_TIME_FORMAT, idx,
865 866
      GST_TIME_ARGS (GST_BUFFER_PTS (*buf)),
      GST_TIME_ARGS (GST_BUFFER_DTS (*buf)),
867 868
      GST_TIME_ARGS (GST_BUFFER_DURATION (*buf)));

869 870 871
  btime = GST_BUFFER_DTS_OR_PTS (*buf);
  if (GST_CLOCK_TIME_IS_VALID (btime))
    *timestamp = btime;
872 873 874

  if (GST_BUFFER_DURATION_IS_VALID (*buf))
    *timestamp += GST_BUFFER_DURATION (*buf);
875 876 877 878 879 880 881
  else if (bld->bitrate != 0) {
    guint64 size = gst_buffer_get_size (*buf);

    /* If we have no duration, pick one from the bitrate if we can */
    *timestamp += gst_util_uint64_scale (bld->bitrate, 8 * GST_SECOND, size);
  }

882 883

  GST_TRACE ("ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (*timestamp));
884
  return TRUE;
885 886 887 888 889 890 891
}

/* take a buffer list and update segment, updating the time level of the queue */
static void
apply_buffer_list (GstQueue2 * queue, GstBufferList * buffer_list,
    GstSegment * segment, gboolean is_sink)
{
892
  struct BufListData bld;
893 894

  /* if no timestamp is set, assume it's continuous with the previous time */
895
  bld.timestamp = segment->position;
896

897 898 899 900 901 902 903 904 905
  if (queue->use_tags_bitrate) {
    if (is_sink)
      bld.bitrate = queue->sink_tags_bitrate;
    else
      bld.bitrate = queue->src_tags_bitrate;
  } else
    bld.bitrate = 0;

  gst_buffer_list_foreach (buffer_list, buffer_list_apply_time, &bld);
906 907

  GST_DEBUG_OBJECT (queue, "last_stop updated to %" GST_TIME_FORMAT,
908
      GST_TIME_ARGS (bld.timestamp));
909

910
  segment->position = bld.timestamp;
911 912 913 914 915 916 917 918 919 920

  if (is_sink)
    queue->sink_tainted = TRUE;
  else
    queue->src_tainted = TRUE;

  /* calc diff with other end */
  update_time_level (queue);
}

921
static inline gint
922 923
normalize_to_buffering_level (guint64 cur_level, guint64 max_level,
    guint64 alt_max)
924 925 926 927 928 929 930
{
  guint64 p;

  if (max_level == 0)
    return 0;

  if (alt_max > 0)
931 932
    p = gst_util_uint64_scale (cur_level, MAX_BUFFERING_LEVEL,
        MIN (max_level, alt_max));
933
  else
934
    p = gst_util_uint64_scale (cur_level, MAX_BUFFERING_LEVEL, max_level);
935

936
  return MIN (p, MAX_BUFFERING_LEVEL);
937 938
}

939
static gboolean
940 941
get_buffering_level (GstQueue2 * queue, gboolean * is_buffering,
    gint * buffering_level)
942
{
943
  gint buflevel, buflevel2;
944

945
  if (queue->high_watermark <= 0) {
946 947
    if (buffering_level)
      *buffering_level = MAX_BUFFERING_LEVEL;
948 949 950 951
    if (is_buffering)
      *is_buffering = FALSE;
    return FALSE;
  }
952 953
#define GET_BUFFER_LEVEL_FOR_QUANTITY(format,alt_max) \
    normalize_to_buffering_level (queue->cur_level.format,queue->max_level.format,(alt_max))
954

955 956 957
  if (queue->is_eos || queue->srcresult == GST_FLOW_NOT_LINKED) {
    /* on EOS and NOT_LINKED we are always 100% full, we set the var
     * here so that we can reuse the logic below to stop buffering */
958
    buflevel = MAX_BUFFERING_LEVEL;
959
    GST_LOG_OBJECT (queue, "we are %s", queue->is_eos ? "EOS" : "NOT_LINKED");
960
  } else {
961 962 963 964 965
    GST_LOG_OBJECT (queue,
        "Cur level bytes/time/buffers %u/%" GST_TIME_FORMAT "/%u",
        queue->cur_level.bytes, GST_TIME_ARGS (queue->cur_level.time),
        queue->cur_level.buffers);

966
    /* figure out the buffering level we are filled, we take the max of all formats. */
967
    if (!QUEUE_IS_USING_RING_BUFFER (queue)) {
968
      buflevel = GET_BUFFER_LEVEL_FOR_QUANTITY (bytes, 0);
969 970
    } else {
      guint64 rb_size = queue->ring_buffer_max_size;
971
      buflevel = GET_BUFFER_LEVEL_FOR_QUANTITY (bytes, rb_size);
972
    }
973