gstqueue2.c 129 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 57
 *
 * If the #GstQueue2:use-buffering property is set to TRUE, and any writable
 * property is modified, #GstQueue2 will attempt to post a buffering message
 * if the changes to the properties also cause the buffering percentage to be
 * changed (for example, because the queue's capacity was changed and it already
 * contains some data).
58
 */
59

60 61 62
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
63

64 65
#include "gstqueue2.h"

66 67
#include <glib/gstdio.h>

68
#include "gst/gst-i18n-lib.h"
69
#include "gst/glib-compat-private.h"
70

71 72
#include <string.h>

LRN's avatar
LRN committed
73 74 75 76 77 78
#ifdef G_OS_WIN32
#include <io.h>                 /* lseek, open, close, read */
#undef lseek
#define lseek _lseeki64
#undef off_t
#define off_t guint64
79 80
#else
#include <unistd.h>
LRN's avatar
LRN committed
81 82
#endif

83 84 85 86
#ifdef __BIONIC__               /* Android */
#include <fcntl.h>
#endif

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
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
};

106 107
/* other defines */
#define DEFAULT_BUFFER_SIZE 4096
108
#define QUEUE_IS_USING_TEMP_FILE(queue) ((queue)->temp_template != NULL)
109
#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
110
#define QUEUE_IS_USING_QUEUE(queue) (!QUEUE_IS_USING_TEMP_FILE(queue) && !QUEUE_IS_USING_RING_BUFFER (queue))
111

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

114 115 116 117 118
/* 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
119
#define DEFAULT_USE_TAGS_BITRATE   FALSE
120
#define DEFAULT_USE_RATE_ESTIMATE  TRUE
121 122
#define DEFAULT_LOW_PERCENT        10
#define DEFAULT_HIGH_PERCENT       99
123 124
#define DEFAULT_LOW_WATERMARK      0.01
#define DEFAULT_HIGH_WATERMARK     0.99
125
#define DEFAULT_TEMP_REMOVE        TRUE
126
#define DEFAULT_RING_BUFFER_MAX_SIZE 0
127
#define DEFAULT_USE_BITRATE_QUERY  TRUE
128

129 130 131 132 133 134 135 136 137 138
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,
139
  PROP_USE_TAGS_BITRATE,
140 141 142
  PROP_USE_RATE_ESTIMATE,
  PROP_LOW_PERCENT,
  PROP_HIGH_PERCENT,
143 144
  PROP_LOW_WATERMARK,
  PROP_HIGH_WATERMARK,
145
  PROP_TEMP_TEMPLATE,
146 147
  PROP_TEMP_LOCATION,
  PROP_TEMP_REMOVE,
148
  PROP_RING_BUFFER_MAX_SIZE,
149
  PROP_AVG_IN_RATE,
150 151
  PROP_USE_BITRATE_QUERY,
  PROP_BITRATE,
152
  PROP_LAST
153
};
154
static GParamSpec *obj_props[PROP_LAST] = { NULL, };
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
/* 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. */

175 176 177 178 179 180
/* 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)
181

182
#define GST_QUEUE2_CLEAR_LEVEL(l) G_STMT_START {         \
183 184 185 186 187 188 189 190 191 192
  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 \
193
                      " ns, %"G_GUINT64_FORMAT" items", \
194 195 196 197 198 199 200
                      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
201
                      (guint64) (!QUEUE_IS_USING_QUEUE(queue) ? \
202
                        queue->current->writing_pos - queue->current->max_reading_pos : \
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
203
                        gst_queue_array_get_length(queue->queue)))
204

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

209 210 211
#define GST_QUEUE2_MUTEX_LOCK_CHECK(q,res,label) G_STMT_START {         \
  GST_QUEUE2_MUTEX_LOCK (q);                                            \
  if (res != GST_FLOW_OK)                                               \
212 213 214
    goto label;                                                         \
} G_STMT_END

215
#define GST_QUEUE2_MUTEX_UNLOCK(q) G_STMT_START {                        \
Wim Taymans's avatar
Wim Taymans committed
216
  g_mutex_unlock (&q->qlock);                                            \
217 218
} G_STMT_END

219
#define GST_QUEUE2_WAIT_DEL_CHECK(q, res, label) G_STMT_START {         \
220 221
  STATUS (queue, q->sinkpad, "wait for DEL");                           \
  q->waiting_del = TRUE;                                                \
Wim Taymans's avatar
Wim Taymans committed
222
  g_cond_wait (&q->item_del, &queue->qlock);                              \
223
  q->waiting_del = FALSE;                                               \
224
  if (res != GST_FLOW_OK) {                                             \
225 226 227 228 229 230
    STATUS (queue, q->srcpad, "received DEL wakeup");                   \
    goto label;                                                         \
  }                                                                     \
  STATUS (queue, q->sinkpad, "received DEL");                           \
} G_STMT_END

231
#define GST_QUEUE2_WAIT_ADD_CHECK(q, res, label) G_STMT_START {         \
232 233
  STATUS (queue, q->srcpad, "wait for ADD");                            \
  q->waiting_add = TRUE;                                                \
Wim Taymans's avatar
Wim Taymans committed
234
  g_cond_wait (&q->item_add, &q->qlock);                                  \
235
  q->waiting_add = FALSE;                                               \
236
  if (res != GST_FLOW_OK) {                                             \
237 238 239 240 241 242
    STATUS (queue, q->srcpad, "received ADD wakeup");                   \
    goto label;                                                         \
  }                                                                     \
  STATUS (queue, q->srcpad, "received ADD");                            \
} G_STMT_END

243
#define GST_QUEUE2_SIGNAL_DEL(q) G_STMT_START {                          \
244 245
  if (q->waiting_del) {                                                 \
    STATUS (q, q->srcpad, "signal DEL");                                \
Wim Taymans's avatar
Wim Taymans committed
246
    g_cond_signal (&q->item_del);                                        \
247 248 249
  }                                                                     \
} G_STMT_END

250
#define GST_QUEUE2_SIGNAL_ADD(q) G_STMT_START {                          \
251 252
  if (q->waiting_add) {                                                 \
    STATUS (q, q->sinkpad, "signal ADD");                               \
Wim Taymans's avatar
Wim Taymans committed
253
    g_cond_signal (&q->item_add);                                        \
254 255 256
  }                                                                     \
} G_STMT_END

257 258 259 260 261 262 263 264 265 266
#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

267
#define _do_init \
268 269 270
    GST_DEBUG_CATEGORY_INIT (queue_debug, "queue2", 0, "queue element"); \
    GST_DEBUG_CATEGORY_INIT (queue_dataflow, "queue2_dataflow", 0, \
        "dataflow inside the queue element");
271 272
#define gst_queue2_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstQueue2, gst_queue2, GST_TYPE_ELEMENT, _do_init);
273

274
static void gst_queue2_finalize (GObject * object);
275

276
static void gst_queue2_set_property (GObject * object,
277
    guint prop_id, const GValue * value, GParamSpec * pspec);
278
static void gst_queue2_get_property (GObject * object,
279 280
    guint prop_id, GValue * value, GParamSpec * pspec);

281 282
static GstFlowReturn gst_queue2_chain (GstPad * pad, GstObject * parent,
    GstBuffer * buffer);
283
static GstFlowReturn gst_queue2_chain_list (GstPad * pad, GstObject * parent,
284
    GstBufferList * buffer_list);
285 286
static GstFlowReturn gst_queue2_push_one (GstQueue2 * queue);
static void gst_queue2_loop (GstPad * pad);
287

288 289
static GstFlowReturn gst_queue2_handle_sink_event (GstPad * pad,
    GstObject * parent, GstEvent * event);
290 291
static gboolean gst_queue2_handle_sink_query (GstPad * pad, GstObject * parent,
    GstQuery * query);
292

293 294
static gboolean gst_queue2_handle_src_event (GstPad * pad, GstObject * parent,
    GstEvent * event);
295 296
static gboolean gst_queue2_handle_src_query (GstPad * pad, GstObject * parent,
    GstQuery * query);
297
static gboolean gst_queue2_handle_query (GstElement * element,
298
    GstQuery * query);
299

300 301
static GstFlowReturn gst_queue2_get_range (GstPad * pad, GstObject * parent,
    guint64 offset, guint length, GstBuffer ** buffer);
302

303 304 305 306
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);
307
static GstStateChangeReturn gst_queue2_change_state (GstElement * element,
308 309
    GstStateChange transition);

310 311
static gboolean gst_queue2_is_empty (GstQueue2 * queue);
static gboolean gst_queue2_is_filled (GstQueue2 * queue);
312

313
static void update_cur_level (GstQueue2 * queue, GstQueue2Range * range);
314
static void update_in_rates (GstQueue2 * queue, gboolean force);
315 316
static GstMessage *gst_queue2_get_buffering_message (GstQueue2 * queue,
    gint * percent);
317
static void update_buffering (GstQueue2 * queue);
318
static void gst_queue2_post_buffering (GstQueue2 * queue);
319

320 321 322 323
typedef enum
{
  GST_QUEUE2_ITEM_TYPE_UNKNOWN = 0,
  GST_QUEUE2_ITEM_TYPE_BUFFER,
324
  GST_QUEUE2_ITEM_TYPE_BUFFER_LIST,
325 326
  GST_QUEUE2_ITEM_TYPE_EVENT,
  GST_QUEUE2_ITEM_TYPE_QUERY
327
} GstQueue2ItemType;
328

329 330 331 332 333 334
typedef struct
{
  GstQueue2ItemType type;
  GstMiniObject *item;
} GstQueue2Item;

335
/* static guint gst_queue2_signals[LAST_SIGNAL] = { 0 }; */
336 337

static void
338
gst_queue2_class_init (GstQueue2Class * klass)
339 340 341 342
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);

343 344
  gobject_class->set_property = gst_queue2_set_property;
  gobject_class->get_property = gst_queue2_get_property;
345 346

  /* properties */
347 348 349 350
  obj_props[PROP_CUR_LEVEL_BYTES] = g_param_spec_uint ("current-level-bytes",
      "Current level (kB)", "Current amount of data in the queue (bytes)",
      0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_CUR_LEVEL_BUFFERS] =
351
      g_param_spec_uint ("current-level-buffers", "Current level (buffers)",
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
      "Current number of buffers in the queue",
      0, G_MAXUINT, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_CUR_LEVEL_TIME] = g_param_spec_uint64 ("current-level-time",
      "Current level (ns)", "Current amount of data in the queue (in ns)",
      0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

  obj_props[PROP_MAX_SIZE_BYTES] = g_param_spec_uint ("max-size-bytes",
      "Max. size (kB)", "Max. amount of data in the queue (bytes, 0=disable)",
      0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
      G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_MAX_SIZE_BUFFERS] = g_param_spec_uint ("max-size-buffers",
      "Max. size (buffers)", "Max. number of buffers in the queue (0=disable)",
      0, G_MAXUINT, DEFAULT_MAX_SIZE_BUFFERS,
      G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_MAX_SIZE_TIME] = g_param_spec_uint64 ("max-size-time",
      "Max. size (ns)", "Max. amount of data in the queue (in ns, 0=disable)",
      0, G_MAXUINT64, DEFAULT_MAX_SIZE_TIME,
      G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS);

  obj_props[PROP_USE_BUFFERING] = g_param_spec_boolean ("use-buffering",
      "Use buffering",
373 374
      "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds "
      "(0% = low-watermark, 100% = high-watermark)",
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
      DEFAULT_USE_BUFFERING,
      G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS);
  obj_props[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);
  obj_props[PROP_USE_RATE_ESTIMATE] = g_param_spec_boolean ("use-rate-estimate",
      "Use Rate Estimate",
      "Estimate the bitrate of the stream to calculate time level",
      DEFAULT_USE_RATE_ESTIMATE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_LOW_PERCENT] = g_param_spec_int ("low-percent", "Low percent",
      "Low threshold for buffering to start. Only used if use-buffering is True "
      "(Deprecated: use low-watermark instead)",
      0, 100, DEFAULT_LOW_WATERMARK * 100,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_HIGH_PERCENT] = g_param_spec_int ("high-percent",
      "High percent",
      "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);
  obj_props[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);
  obj_props[PROP_HIGH_WATERMARK] = g_param_spec_double ("high-watermark",
      "High watermark",
      "High threshold for buffering to finish. Only used if use-buffering is True",
      0.0, 1.0, DEFAULT_HIGH_WATERMARK,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  obj_props[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);

  obj_props[PROP_TEMP_LOCATION] = g_param_spec_string ("temp-location",
      "Temporary File Location",
      "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);

  obj_props[PROP_USE_BITRATE_QUERY] = g_param_spec_boolean ("use-bitrate-query",
      "Use bitrate from downstream query",
      "Use a bitrate from a downstream query to estimate buffer duration if not provided",
      DEFAULT_USE_BITRATE_QUERY,
      G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING | G_PARAM_STATIC_STRINGS);
425

426 427 428 429 430
  /**
   * GstQueue2:temp-remove
   *
   * When temp-template is set, remove the temporary file when going to READY.
   */
431 432 433
  obj_props[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);
434

435 436 437
  /**
   * GstQueue2:ring-buffer-max-size
   *
438 439
   * The maximum size of the ring buffer in bytes. If set to 0, the ring
   * buffer is disabled. Default 0.
440
   */
441
  obj_props[PROP_RING_BUFFER_MAX_SIZE] =
442
      g_param_spec_uint64 ("ring-buffer-max-size",
443 444 445 446
      "Max. ring buffer size (bytes)",
      "Max. amount of data in the ring buffer (bytes, 0 = disabled)",
      0, G_MAXUINT64, DEFAULT_RING_BUFFER_MAX_SIZE,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
447

448 449 450 451 452
  /**
   * GstQueue2:avg-in-rate
   *
   * The average input data rate.
   */
453 454 455
  obj_props[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);
456

457 458 459 460 461 462 463
  /**
   * GstQueue2:bitrate
   *
   * The value used to convert between byte and time values for limiting
   * the size of the queue.  Values are taken from either the upstream tags
   * or from the downstream bitrate query.
   */
464 465 466 467 468
  obj_props[PROP_BITRATE] = g_param_spec_uint64 ("bitrate", "Bitrate (bits/s)",
      "Conversion value between data size and time",
      0, G_MAXUINT64, 0, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

  g_object_class_install_properties (gobject_class, PROP_LAST, obj_props);
469

470
  /* set several parent class virtual functions */
471
  gobject_class->finalize = gst_queue2_finalize;
472

473 474
  gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
  gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
475

476
  gst_element_class_set_static_metadata (gstelement_class, "Queue 2",
477 478 479 480 481
      "Generic",
      "Simple data queue",
      "Erik Walthinsen <omega@cse.ogi.edu>, "
      "Wim Taymans <wim.taymans@gmail.com>");

482
  gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_queue2_change_state);
483
  gstelement_class->query = GST_DEBUG_FUNCPTR (gst_queue2_handle_query);
484 485 486
}

static void
487
gst_queue2_init (GstQueue2 * queue)
488 489 490 491
{
  queue->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");

  gst_pad_set_chain_function (queue->sinkpad,
492
      GST_DEBUG_FUNCPTR (gst_queue2_chain));
493 494
  gst_pad_set_chain_list_function (queue->sinkpad,
      GST_DEBUG_FUNCPTR (gst_queue2_chain_list));
495 496
  gst_pad_set_activatemode_function (queue->sinkpad,
      GST_DEBUG_FUNCPTR (gst_queue2_sink_activate_mode));
497
  gst_pad_set_event_full_function (queue->sinkpad,
498
      GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_event));
Wim Taymans's avatar
Wim Taymans committed
499 500
  gst_pad_set_query_function (queue->sinkpad,
      GST_DEBUG_FUNCPTR (gst_queue2_handle_sink_query));
Wim Taymans's avatar
Wim Taymans committed
501
  GST_PAD_SET_PROXY_CAPS (queue->sinkpad);
502 503 504 505
  gst_element_add_pad (GST_ELEMENT (queue), queue->sinkpad);

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

506 507
  gst_pad_set_activatemode_function (queue->srcpad,
      GST_DEBUG_FUNCPTR (gst_queue2_src_activate_mode));
508
  gst_pad_set_getrange_function (queue->srcpad,
509
      GST_DEBUG_FUNCPTR (gst_queue2_get_range));
510
  gst_pad_set_event_function (queue->srcpad,
511
      GST_DEBUG_FUNCPTR (gst_queue2_handle_src_event));
512
  gst_pad_set_query_function (queue->srcpad,
513
      GST_DEBUG_FUNCPTR (gst_queue2_handle_src_query));
Wim Taymans's avatar
Wim Taymans committed
514
  GST_PAD_SET_PROXY_CAPS (queue->srcpad);
515 516 517
  gst_element_add_pad (GST_ELEMENT (queue), queue->srcpad);

  /* levels */
518
  GST_QUEUE2_CLEAR_LEVEL (queue->cur_level);
519 520 521 522 523 524
  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;
525 526
  queue->low_watermark = DEFAULT_LOW_WATERMARK * MAX_BUFFERING_LEVEL;
  queue->high_watermark = DEFAULT_HIGH_WATERMARK * MAX_BUFFERING_LEVEL;
527 528 529 530

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

531 532 533 534 535
  queue->sinktime = GST_CLOCK_TIME_NONE;
  queue->srctime = GST_CLOCK_TIME_NONE;
  queue->sink_tainted = TRUE;
  queue->src_tainted = TRUE;

536 537
  queue->srcresult = GST_FLOW_FLUSHING;
  queue->sinkresult = GST_FLOW_FLUSHING;
538
  queue->is_eos = FALSE;
539 540
  queue->in_timer = g_timer_new ();
  queue->out_timer = g_timer_new ();
541

Wim Taymans's avatar
Wim Taymans committed
542
  g_mutex_init (&queue->qlock);
543
  queue->waiting_add = FALSE;
Wim Taymans's avatar
Wim Taymans committed
544
  g_cond_init (&queue->item_add);
545
  queue->waiting_del = FALSE;
Wim Taymans's avatar
Wim Taymans committed
546
  g_cond_init (&queue->item_del);
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
547
  queue->queue = gst_queue_array_new_for_struct (sizeof (GstQueue2Item), 32);
548

549 550 551
  g_cond_init (&queue->query_handled);
  queue->last_query = FALSE;

552
  g_mutex_init (&queue->buffering_post_lock);
553
  queue->buffering_percent = 100;
554
  queue->last_posted_buffering_percent = -1;
555

556
  /* tempfile related */
557
  queue->temp_template = NULL;
558
  queue->temp_location = NULL;
559
  queue->temp_remove = DEFAULT_TEMP_REMOVE;
560

561
  queue->ring_buffer = NULL;
562
  queue->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
563

564 565
  queue->use_bitrate_query = DEFAULT_USE_BITRATE_QUERY;

566 567 568 569 570 571
  GST_DEBUG_OBJECT (queue,
      "initialized queue's not_empty & not_full conditions");
}

/* called only once, as opposed to dispose */
static void
572
gst_queue2_finalize (GObject * object)
573
{
574
  GstQueue2 *queue = GST_QUEUE2 (object);
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
575
  GstQueue2Item *qitem;
576 577 578

  GST_DEBUG_OBJECT (queue, "finalizing queue");

Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
579
  while ((qitem = gst_queue_array_pop_head_struct (queue->queue))) {
580 581
    if (qitem->type != GST_QUEUE2_ITEM_TYPE_QUERY)
      gst_mini_object_unref (qitem->item);
582
  }
Dimitrios Katsaros's avatar
Dimitrios Katsaros committed
583
  gst_queue_array_free (queue->queue);
584

585
  queue->last_query = FALSE;
Wim Taymans's avatar
Wim Taymans committed
586
  g_mutex_clear (&queue->qlock);
587
  g_mutex_clear (&queue->buffering_post_lock);
Wim Taymans's avatar
Wim Taymans committed
588 589
  g_cond_clear (&queue->item_add);
  g_cond_clear (&queue->item_del);
590
  g_cond_clear (&queue->query_handled);
591 592
  g_timer_destroy (queue->in_timer);
  g_timer_destroy (queue->out_timer);
593

594
  /* temp_file path cleanup  */
595 596
  g_free (queue->temp_template);
  g_free (queue->temp_location);
597

598 599 600
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

601 602 603 604 605 606
static void
debug_ranges (GstQueue2 * queue)
{
  GstQueue2Range *walk;

  for (walk = queue->ranges; walk; walk = walk->next) {
607 608 609 610 611 612
    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  ");
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
  }
}

/* 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 *
629
find_range (GstQueue2 * queue, guint64 offset)
630
{
631 632
  GstQueue2Range *range = NULL;
  GstQueue2Range *walk;
633 634 635 636 637 638 639 640 641

  /* 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
642 643 644 645 646 647 648
  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);
  }
649 650 651
  return range;
}

Wim Taymans's avatar
Wim Taymans committed
652 653 654 655 656 657 658 659 660 661 662 663 664 665
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;
}

666 667
/* make a new range for @offset or reuse an existing range */
static GstQueue2Range *
668
add_range (GstQueue2 * queue, guint64 offset, gboolean update_existing)
669 670 671 672 673
{
  GstQueue2Range *range, *prev, *next;

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

674
  if ((range = find_range (queue, offset))) {
675 676 677
    GST_DEBUG_OBJECT (queue,
        "reusing range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, range->offset,
        range->writing_pos);
678 679 680 681 682
    if (update_existing && range->writing_pos != offset) {
      GST_DEBUG_OBJECT (queue, "updating range writing position to "
          "%" G_GUINT64_FORMAT, offset);
      range->writing_pos = offset;
    }
683 684 685 686 687 688
  } else {
    GST_DEBUG_OBJECT (queue,
        "new range %" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, offset);

    range = g_slice_new0 (GstQueue2Range);
    range->offset = offset;
689 690
    /* we want to write to the next location in the ring buffer */
    range->rb_offset = queue->current ? queue->current->rb_writing_pos : 0;
691
    range->writing_pos = offset;
692
    range->rb_writing_pos = range->rb_offset;
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    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
719 720 721
  /* update the stats for this range */
  update_cur_level (queue, range);

722 723 724 725 726 727 728 729 730 731 732 733 734
  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 */
735
  queue->current = add_range (queue, 0, TRUE);
736 737
}

738 739 740
/* 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
741
update_time_level (GstQueue2 * queue)
742
{
743 744 745
  if (queue->sink_tainted) {
    queue->sinktime =
        gst_segment_to_running_time (&queue->sink_segment, GST_FORMAT_TIME,
Wim Taymans's avatar
Wim Taymans committed
746
        queue->sink_segment.position);
747 748
    queue->sink_tainted = FALSE;
  }
749

750 751 752
  if (queue->src_tainted) {
    queue->srctime =
        gst_segment_to_running_time (&queue->src_segment, GST_FORMAT_TIME,
Wim Taymans's avatar
Wim Taymans committed
753
        queue->src_segment.position);
754 755
    queue->src_tainted = FALSE;
  }
756 757

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

760 761 762
  if (queue->sinktime != GST_CLOCK_TIME_NONE
      && queue->srctime != GST_CLOCK_TIME_NONE
      && queue->sinktime >= queue->srctime)
763
    queue->cur_level.time = queue->sinktime - queue->srctime;
764 765 766 767
  else
    queue->cur_level.time = 0;
}

Wim Taymans's avatar
Wim Taymans committed
768
/* take a SEGMENT event and apply the values to segment, updating the time
769 770
 * level of queue. */
static void
771 772
apply_segment (GstQueue2 * queue, GstEvent * event, GstSegment * segment,
    gboolean is_sink)
773
{
774
  gst_event_copy_segment (event, segment);
775

Wim Taymans's avatar
Wim Taymans committed
776
  if (segment->format == GST_FORMAT_BYTES) {
Wim Taymans's avatar
Wim Taymans committed
777
    if (!QUEUE_IS_USING_QUEUE (queue) && is_sink) {
778
      /* start is where we'll be getting from and as such writing next */
779
      queue->current = add_range (queue, segment->start, TRUE);
780
    }
781 782
  }

783 784
  /* now configure the values, we use these to track timestamps on the
   * sinkpad. */
Wim Taymans's avatar
Wim Taymans committed
785
  if (segment->format != GST_FORMAT_TIME) {
786
    /* non-time format, pretend the current time segment is closed with a
787
     * 0 start and unknown stop time. */
Wim Taymans's avatar
Wim Taymans committed
788 789 790 791
    segment->format = GST_FORMAT_TIME;
    segment->start = 0;
    segment->stop = -1;
    segment->time = 0;
792 793
  }

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

796 797 798 799 800
  if (is_sink)
    queue->sink_tainted = TRUE;
  else
    queue->src_tainted = TRUE;

801 802 803 804
  /* segment can update the time level of the queue */
  update_time_level (queue);
}

805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
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);
  }
}

832 833 834 835 836
static void
query_downstream_bitrate (GstQueue2 * queue)
{
  GstQuery *query = gst_query_new_bitrate ();
  guint downstream_bitrate = 0;
837
  gboolean changed;
838 839 840 841 842 843 844 845 846 847 848 849

  if (gst_pad_peer_query (queue->srcpad, query)) {
    gst_query_parse_bitrate (query, &downstream_bitrate);
    GST_DEBUG_OBJECT (queue, "Got bitrate of %u from downstream",
        downstream_bitrate);
  } else {
    GST_DEBUG_OBJECT (queue, "Failed to query bitrate from downstream");
  }

  gst_query_unref (query);

  GST_QUEUE2_MUTEX_LOCK (queue);
850
  changed = queue->downstream_bitrate != downstream_bitrate;
851 852 853
  queue->downstream_bitrate = downstream_bitrate;
  GST_QUEUE2_MUTEX_UNLOCK (queue);

854 855 856 857 858 859 860
  if (changed) {
    if (queue->use_buffering)
      update_buffering (queue);
    gst_queue2_post_buffering (queue);

    g_object_notify_by_pspec (G_OBJECT (queue), obj_props[PROP_BITRATE]);
  }
861 862
}

863 864
/* take a buffer and update segment, updating the time level of the queue. */
static void
865
apply_buffer (GstQueue2 * queue, GstBuffer * buffer, GstSegment * segment,
866
    guint64 size, gboolean is_sink)
867 868 869
{
  GstClockTime duration, timestamp;

870
  timestamp = GST_BUFFER_DTS_OR_PTS (buffer);
871 872
  duration = GST_BUFFER_DURATION (buffer);

873
  /* If we have no duration, pick one from the bitrate if we can */
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
  if (duration == GST_CLOCK_TIME_NONE) {
    if (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);
    }
    if (duration == GST_CLOCK_TIME_NONE && !is_sink && queue->use_bitrate_query) {
      if (queue->downstream_bitrate > 0) {
        duration =
            gst_util_uint64_scale (size, 8 * GST_SECOND,
            queue->downstream_bitrate);

        GST_LOG_OBJECT (queue, "got bitrate %u resulting in estimated "
            "duration %" GST_TIME_FORMAT, queue->downstream_bitrate,
            GST_TIME_ARGS (duration));
      }
    }
892 893
  }

894
  /* if no timestamp is set, assume it's continuous with the previous
895 896
   * time */
  if (timestamp == GST_CLOCK_TIME_NONE)
Wim Taymans's avatar
Wim Taymans committed
897
    timestamp = segment->position;
898 899 900 901 902

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

Wim Taymans's avatar
Wim Taymans committed
903
  GST_DEBUG_OBJECT (queue, "position updated to %" GST_TIME_FORMAT,
904 905
      GST_TIME_ARGS (timestamp));

Wim Taymans's avatar
Wim Taymans committed
906
  segment->position = timestamp;
907

908 909 910 911 912
  if (is_sink)
    queue->sink_tainted = TRUE;
  else
    queue->src_tainted = TRUE;

913 914 915 916
  /* calc diff with other end */
  update_time_level (queue);
}

917 918 919 920 921 922
struct BufListData
{
  GstClockTime timestamp;
  guint bitrate;
};

923 924
static gboolean
buffer_list_apply_time (GstBuffer ** buf, guint idx, gpointer data)
925
{
926 927
  struct BufListData *bld = data;
  GstClockTime *timestamp = &bld->timestamp;
928
  GstClockTime btime;
929

930
  GST_TRACE ("buffer %u has pts %" GST_TIME_FORMAT " dts %" GST_TIME_FORMAT
931
      " duration %" GST_TIME_FORMAT, idx,
932 933
      GST_TIME_ARGS (GST_BUFFER_PTS (*buf)),
      GST_TIME_ARGS (GST_BUFFER_DTS (*buf)),
934 935
      GST_TIME_ARGS (GST_BUFFER_DURATION (*buf)));

936 937 938
  btime = GST_BUFFER_DTS_OR_PTS (*buf);
  if (GST_CLOCK_TIME_IS_VALID (btime))
    *timestamp = btime;
939 940 941

  if (GST_BUFFER_DURATION_IS_VALID (*buf))
    *timestamp += GST_BUFFER_DURATION (*buf);
942 943 944 945 946 947 948
  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);
  }

949 950

  GST_TRACE ("ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (*timestamp));
951
  return TRUE;
952 953 954 955 956 957 958
}

/* 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)
{
959
  struct BufListData bld;
960 961

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

964
  bld.bitrate = 0;
965 966 967 968 969
  if (queue->use_tags_bitrate) {
    if (is_sink)
      bld.bitrate = queue->sink_tags_bitrate;
    else
      bld.bitrate = queue->src_tags_bitrate;
970 971 972 973
  }
  if (!is_sink && bld.bitrate == 0 && queue->use_bitrate_query) {
    bld.bitrate = queue->downstream_bitrate;
  }
974 975

  gst_buffer_list_foreach (buffer_list, buffer_list_apply_time, &bld);
976 977

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

980
  segment->position = bld.timestamp;
981 982 983 984 985 986 987 988 989 990

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

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

991
static inline gint
992 993
normalize_to_buffering_level (guint64 cur_level, guint64 max_level,
    guint64 alt_max)
994 995 996 997 998 999 1000
{
  guint64 p;

  if (max_level == 0)
    return 0;

  if (alt_max > 0)
1001 1002
    p = gst_util_uint64_scale (cur_level, MAX_BUFFERING_LEVEL,
        MIN (max_level, alt_max));
1003
  else
1004
    p = gst_util_uint64_scale (cur_level, MAX_BUFFERING_LEVEL, max_level);
1005

1006
  return MIN (p, MAX_BUFFERING_LEVEL);
1007 1008
}

1009
static gboolean
1010 1011
get_buffering_level (GstQueue2 * queue, gboolean * is_buffering,
    gint * buffering_level)
1012
{
1013
  gint buflevel, buflevel2;
1014

1015
  if (queue->high_watermark <= 0) {
1016 1017
    if (buffering_level)
      *buffering_level = MAX_BUFFERING_LEVEL;
1018 1019 1020 1021
    if (is_buffering)
      *is_buffering = FALSE;
    return FALSE;
  }
1022 1023
#define GET_BUFFER_LEVEL_FOR_QUANTITY(format,alt_max) \
    normalize_to_buffering_level (queue->cur_level.format,queue->max_level.format,(alt_max))
1024