Merge branch 't/makefile_cleanups'
[paraslash.git] / buffer_tree.c
index 7b3355a28b98aa601431029c83063aac016d2d9d..88fb8362bb0c9233d9a5916519b4acf47f4a63ed 100644 (file)
@@ -1,3 +1,10 @@
+/*
+ * Copyright (C) 2009-2011 Andre Noll <maan@systemlinux.org>
+ *
+ * Licensed under the GPL v2. For licencing details see COPYING.
+ */
+
+/** \file buffer_tree.c Buffer tree and buffer pool implementations. */
 #include <regex.h>
 #include <stdbool.h>
 
 #include "string.h"
 #include "buffer_tree.h"
 #include "error.h"
+#include "sched.h"
 
+/* whead = NULL means area full */
+struct btr_pool {
+       char *name;
+       char *area_start;
+       char *area_end;
+       char *rhead;
+       char *whead;
+};
 
 struct btr_buffer {
        char *buf;
        size_t size;
        /** The number of references to this buffer. */
        int refcount;
+       /* NULL means no buffer pool but a malloced buffer. */
+       struct btr_pool *pool;
 };
 
 struct btr_buffer_reference {
@@ -20,6 +38,7 @@ struct btr_buffer_reference {
        size_t consumed;
        /* Each buffer reference belongs to the buffer queue list of some buffer tree node. */
        struct list_head node;
+       size_t wrap_count;
 };
 
 struct btr_node {
@@ -29,6 +48,8 @@ struct btr_node {
        struct list_head node;
        /* The children nodes of this btr node are linked together in a list. */
        struct list_head children;
+       /* Time of first data transfer. */
+       struct timeval start;
        /**
         * The input queue is a list of references to btr buffers. Each item on
         * the list represents an input buffer which has not been completely
@@ -39,45 +60,278 @@ struct btr_node {
        void *context;
 };
 
+/**
+ * Create a new buffer pool.
+ *
+ * \param name The name of the new buffer pool.
+ * \param area_size The size in bytes of the pool area.
+ *
+ * \return An opaque pointer to the newly created buffer pool. It must be
+ * passed to btr_pool_free() after it is no longer used to deallocate all
+ * resources.
+ */
+struct btr_pool *btr_pool_new(const char *name, size_t area_size)
+{
+       struct btr_pool *btrp;
+
+       PARA_INFO_LOG("%s, %zu bytes\n", name, area_size);
+       btrp = para_malloc(sizeof(*btrp));
+       btrp->area_start = para_malloc(area_size);
+       btrp->area_end = btrp->area_start + area_size;
+       btrp->rhead = btrp->area_start;
+       btrp->whead = btrp->area_start;
+       btrp->name = para_strdup(name);
+       return btrp;
+}
+
+/**
+ * Deallocate resources used by a buffer pool.
+ *
+ * \param btrp A pointer obtained via btr_pool_new().
+ */
+void btr_pool_free(struct btr_pool *btrp)
+{
+       if (!btrp)
+               return;
+       free(btrp->area_start);
+       free(btrp->name);
+       free(btrp);
+}
+
+/**
+ * Return the size of the buffer pool area.
+ *
+ * \param btrp The buffer pool.
+ *
+ * \return The same value which was passed during creation time to
+ * btr_pool_new().
+ */
+size_t btr_pool_size(struct btr_pool *btrp)
+{
+       return btrp->area_end - btrp->area_start;
+}
+
+static size_t btr_pool_filled(struct btr_pool *btrp)
+{
+       if (!btrp->whead)
+               return btr_pool_size(btrp);
+       if (btrp->rhead <= btrp->whead)
+               return  btrp->whead - btrp->rhead;
+       return btr_pool_size(btrp) - (btrp->rhead - btrp->whead);
+}
+
+/**
+ * Get the number of unused bytes in the buffer pool.
+ *
+ * \param btrp The pool.
+ *
+ * \return The number of bytes that can currently be allocated.
+ *
+ * Note that in general the returned number of bytes is not available as a
+ * single contiguous buffer. Use btr_pool_available() to obtain the length of
+ * the largest contiguous buffer that can currently be allocated from the
+ * buffer pool.
+ */
+size_t btr_pool_unused(struct btr_pool *btrp)
+{
+       return btr_pool_size(btrp) - btr_pool_filled(btrp);
+}
+
+/*
+ * Return maximal size available for one read. This is
+ * smaller than the value returned by btr_pool_unused().
+ */
+static size_t btr_pool_available(struct btr_pool *btrp)
+{
+       if (!btrp->whead)
+               return 0;
+       if (btrp->rhead <= btrp->whead)
+               return btrp->area_end - btrp->whead;
+       return btrp->rhead - btrp->whead;
+}
+
+/**
+ * Obtain the current write head.
+ *
+ * \param btrp The buffer pool.
+ * \param result The write head is returned here.
+ *
+ * \return The maximal amount of bytes that may be written to the returned
+ * buffer.
+ */
+size_t btr_pool_get_buffer(struct btr_pool *btrp, char **result)
+{
+       if (result)
+               *result = btrp->whead;
+       return btr_pool_available(btrp);
+}
+
+/**
+ * Get references to buffers pointing to free space of the buffer pool area.
+ *
+ * \param btrp The buffer pool.
+ * \param iov The scatter array.
+ *
+ * \return Zero if the buffer pool is full, one if the free space of the buffer
+ * pool area is available as a single contiguous buffer, two if the free space
+ * consists of two buffers. If this function returns the value n, then n
+ * elements of \a iov are initialized.
+ */
+int btr_pool_get_buffers(struct btr_pool *btrp, struct iovec iov[2])
+{
+       size_t sz, unused;
+       char *buf;
+
+       sz = btr_pool_get_buffer(btrp, &buf);
+       if (sz == 0)
+               return 0;
+       iov[0].iov_len = sz;
+       iov[0].iov_base = buf;
+       unused = btr_pool_unused(btrp);
+       if (sz == unused)
+               return 1;
+       iov[1].iov_len = unused - sz;
+       iov[1].iov_base = btrp->area_start;
+       return 2;
+}
+
+/**
+ * Mark a part of the buffer pool area as allocated.
+ *
+ * \param btrp The buffer pool.
+ * \param size The amount of bytes to be allocated.
+ *
+ * This is usually called after the caller wrote to the buffer obtained by
+ * btr_pool_get_buffer().
+ */
+static void btr_pool_allocate(struct btr_pool *btrp, size_t size)
+{
+       char *end;
+
+       if (size == 0)
+               return;
+       assert(size <= btr_pool_available(btrp));
+       end = btrp->whead + size;
+       assert(end <= btrp->area_end);
+
+       if (end == btrp->area_end) {
+               PARA_DEBUG_LOG("%s: end of pool area reached\n", btrp->name);
+               end = btrp->area_start;
+       }
+       if (end == btrp->rhead) {
+               PARA_DEBUG_LOG("%s btrp buffer full\n", btrp->name);
+               end = NULL; /* buffer full */
+       }
+       btrp->whead = end;
+}
+
+static void btr_pool_deallocate(struct btr_pool *btrp, size_t size)
+{
+       char *end = btrp->rhead + size;
+
+       if (size == 0)
+               return;
+       assert(end <= btrp->area_end);
+       assert(size <= btr_pool_filled(btrp));
+       if (end == btrp->area_end)
+               end = btrp->area_start;
+       if (!btrp->whead)
+               btrp->whead = btrp->rhead;
+       btrp->rhead = end;
+       if (btrp->rhead == btrp->whead)
+               btrp->rhead = btrp->whead = btrp->area_start;
+}
+
 #define FOR_EACH_CHILD(_tn, _btrn) list_for_each_entry((_tn), \
        &((_btrn)->children), node)
+#define FOR_EACH_CHILD_SAFE(_tn, _tmp, _btrn) \
+       list_for_each_entry_safe((_tn), (_tmp), &((_btrn)->children), node)
 
 #define FOR_EACH_BUFFER_REF(_br, _btrn) \
        list_for_each_entry((_br), &(_btrn)->input_queue, node)
 #define FOR_EACH_BUFFER_REF_SAFE(_br, _tmp, _btrn) \
        list_for_each_entry_safe((_br), (_tmp), &(_btrn)->input_queue, node)
 
-struct btr_node *btr_new_node(char *name, struct btr_node *parent,
-               btr_command_handler handler, void *context)
+/**
+ * Create a new buffer tree node.
+ *
+ * \param bnd Specifies how to create the new node.
+ *
+ * \return A pointer to the newly allocated node.
+ *
+ * This function always succeeds (or calls exit()). The returned pointer must
+ * be freed using btr_free_node() after the node has been removed from the
+ * buffer tree via btr_remove_node().
+ */
+struct btr_node *btr_new_node(struct btr_node_description *bnd)
 {
        struct btr_node *btrn = para_malloc(sizeof(*btrn));
 
-       btrn->name = para_strdup(name);
-       btrn->parent = parent;
-       btrn->execute = handler;
-       btrn->context = context;
-       if (parent)
-               list_add_tail(&btrn->node, &parent->children);
+       btrn->name = para_strdup(bnd->name);
+       btrn->parent = bnd->parent;
+       btrn->execute = bnd->handler;
+       btrn->context = bnd->context;
+       btrn->start.tv_sec = 0;
+       btrn->start.tv_usec = 0;
        INIT_LIST_HEAD(&btrn->children);
        INIT_LIST_HEAD(&btrn->input_queue);
+       if (!bnd->child) {
+               if (bnd->parent) {
+                       list_add_tail(&btrn->node, &bnd->parent->children);
+                       PARA_INFO_LOG("new leaf node: %s (child of %s)\n",
+                               bnd->name, bnd->parent->name);
+               } else
+                       PARA_INFO_LOG("added %s as btr root\n", bnd->name);
+               goto out;
+       }
+       if (!bnd->parent) {
+               assert(!bnd->child->parent);
+               PARA_INFO_LOG("new root: %s (was %s)\n",
+                       bnd->name, bnd->child->name);
+               btrn->parent = NULL;
+               list_add_tail(&bnd->child->node, &btrn->children);
+               /* link it in */
+               bnd->child->parent = btrn;
+               goto out;
+       }
+       PARA_EMERG_LOG("inserting internal nodes not yet supported.\n");
+       exit(EXIT_FAILURE);
+       assert(bnd->child->parent == bnd->parent);
+out:
        return btrn;
 }
 
 /*
  * Allocate a new btr buffer.
  *
- * The freshly allocated buffer will have a zero refcount.
+ * The freshly allocated buffer will have a zero refcount and will
+ * not be associated with a btr pool.
  */
 static struct btr_buffer *new_btrb(char *buf, size_t size)
 {
-       struct btr_buffer *btrb = para_malloc(sizeof(*btrb));
+       struct btr_buffer *btrb = para_calloc(sizeof(*btrb));
 
        btrb->buf = buf;
        btrb->size = size;
-       btrb->refcount = 0;
        return btrb;
 }
 
+static void dealloc_buffer(struct btr_buffer *btrb)
+{
+       if (btrb->pool)
+               btr_pool_deallocate(btrb->pool, btrb->size);
+       else
+               free(btrb->buf);
+}
+
+static struct btr_buffer_reference *get_first_input_br(struct btr_node *btrn)
+{
+       if (list_empty(&btrn->input_queue))
+               return NULL;
+       return list_first_entry(&btrn->input_queue,
+               struct btr_buffer_reference, node);
+}
+
 /*
  * Deallocate the reference, release the resources if refcount drops to zero.
  */
@@ -85,12 +339,11 @@ static void btr_drop_buffer_reference(struct btr_buffer_reference *br)
 {
        struct btr_buffer *btrb = br->btrb;
 
-       //PARA_CRIT_LOG("dropping buffer reference %p\n", br);
        list_del(&br->node);
        free(br);
        btrb->refcount--;
        if (btrb->refcount == 0) {
-               free(btrb->buf);
+               dealloc_buffer(btrb);
                free(btrb);
        }
 }
@@ -100,29 +353,125 @@ static void add_btrb_to_children(struct btr_buffer *btrb,
 {
        struct btr_node *ch;
 
+       if (btrn->start.tv_sec == 0)
+               btrn->start = *now;
        FOR_EACH_CHILD(ch, btrn) {
-               struct btr_buffer_reference *br = para_malloc(sizeof(*br));
+               struct btr_buffer_reference *br = para_calloc(sizeof(*br));
                br->btrb = btrb;
                br->consumed = consumed;
                list_add_tail(&br->node, &ch->input_queue);
                btrb->refcount++;
+               if (ch->start.tv_sec == 0)
+                       ch->start = *now;
        }
 }
 
+/**
+ * Insert a malloced buffer into the buffer tree.
+ *
+ * \param buf The buffer to insert.
+ * \param size The size of \a buf in bytes.
+ * \param btrn Position in the buffer tree to create the output.
+ *
+ * This creates references to \a buf and adds these references to each child of
+ * \a btrn. The buffer will be freed using standard free() once no buffer tree
+ * node is referencing it any more.
+ *
+ * Note that this function must not be used if \a buf was obtained from a
+ * buffer pool. Use btr_add_output_pool() in this case.
+ */
 void btr_add_output(char *buf, size_t size, struct btr_node *btrn)
 {
        struct btr_buffer *btrb;
 
+       assert(size != 0);
+       if (list_empty(&btrn->children)) {
+               free(buf);
+               return;
+       }
        btrb = new_btrb(buf, size);
        add_btrb_to_children(btrb, btrn, 0);
 }
 
+/**
+ * Feed data to child nodes of a buffer tree node.
+ *
+ * \param btrp The buffer pool.
+ * \param size The number of bytes to be allocated and fed to each child.
+ * \param btrn The node whose children are to be fed.
+ *
+ * This function allocates the amount of bytes from the buffer pool area,
+ * starting at the current value of the write head, and creates buffer
+ * references to the resulting part of the buffer pool area, one for each child
+ * of \a btrn. The references are then fed into the input queue of each child.
+ */
+void btr_add_output_pool(struct btr_pool *btrp, size_t size,
+               struct btr_node *btrn)
+{
+       struct btr_buffer *btrb;
+       char *buf;
+       size_t avail;
+
+       assert(size != 0);
+       if (list_empty(&btrn->children))
+               return;
+       avail = btr_pool_get_buffer(btrp, &buf);
+       assert(avail >= size);
+       btr_pool_allocate(btrp, size);
+       btrb = new_btrb(buf, size);
+       btrb->pool = btrp;
+       add_btrb_to_children(btrb, btrn, 0);
+}
+
+/**
+ * Copy data to write head of a buffer pool and feed it to all children nodes.
+ *
+ * \param src The source buffer.
+ * \param n The size of the source buffer in bytes.
+ * \param btrp The destination buffer pool.
+ * \param btrn Add the data as output of this node.
+ *
+ * This is expensive. The caller must make sure the data fits into the buffer
+ * pool area.
+ */
+void btr_copy(const void *src, size_t n, struct btr_pool *btrp,
+       struct btr_node *btrn)
+{
+       char *buf;
+       size_t sz, copy;
+
+       if (n == 0)
+               return;
+       assert(n <= btr_pool_unused(btrp));
+       sz = btr_pool_get_buffer(btrp, &buf);
+       copy = PARA_MIN(sz, n);
+       memcpy(buf, src, copy);
+       btr_add_output_pool(btrp, copy, btrn);
+       if (copy == n)
+               return;
+       sz = btr_pool_get_buffer(btrp, &buf);
+       assert(sz >= n - copy);
+       memcpy(buf, src + copy, n - copy);
+       btr_add_output_pool(btrp, n - copy, btrn);
+}
+
 static void btr_pushdown_br(struct btr_buffer_reference *br, struct btr_node *btrn)
 {
        add_btrb_to_children(br->btrb, btrn, br->consumed);
        btr_drop_buffer_reference(br);
 }
 
+/**
+ * Feed all buffer references of the input queue through the output channel.
+ *
+ * \param btrn The node whose buffer references should be pushed down.
+ *
+ * This function is useful for filters that do not change the contents of the
+ * buffers at all, like the wav filter or the amp filter if no amplification
+ * was specified. This function is rather cheap.
+ *
+ * \sa \ref btr_pushdown_one().
+ */
 void btr_pushdown(struct btr_node *btrn)
 {
        struct btr_buffer_reference *br, *tmp;
@@ -131,17 +480,69 @@ void btr_pushdown(struct btr_node *btrn)
                btr_pushdown_br(br, btrn);
 }
 
-/* Return true if this node has no children. */
-bool btr_no_children(struct btr_node *btrn)
+/**
+ * Feed the next buffer of the input queue through the output channel.
+ *
+ * \param btrn The node whose first input queue buffer should be pushed down.
+ *
+ * This works like \ref btr_pushdown() but pushes down only one buffer
+ * reference.
+ */
+void btr_pushdown_one(struct btr_node *btrn)
+{
+       struct btr_buffer_reference *br;
+
+       if (list_empty(&btrn->input_queue))
+               return;
+       br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
+       btr_pushdown_br(br, btrn);
+}
+
+/*
+ * Find out whether a node is a leaf node.
+ *
+ * \param btrn The node to check.
+ *
+ * \return True if this node has no children. False otherwise.
+ */
+static bool btr_no_children(struct btr_node *btrn)
 {
        return list_empty(&btrn->children);
 }
 
+/**
+ * Find out whether a node is an orphan node.
+ *
+ * \param btrn The buffer tree node.
+ *
+ * \return True if \a btrn has no parent.
+ *
+ * This function will always return true for the root node.  However in case
+ * nodes have been removed from the tree, other nodes may become orphans too.
+ */
 bool btr_no_parent(struct btr_node *btrn)
 {
        return !btrn->parent;
 }
 
+/**
+ * Find out whether it is OK to change an input buffer.
+ *
+ * \param btrn The buffer tree node to check.
+ *
+ * This is used by filters that produce exactly the same amount of output as
+ * there is input. The amp filter which multiplies each sample by some number
+ * is an example of such a filter. If there are no other nodes in the buffer
+ * tree that read the same input stream (i.e. if \a btrn has no siblings), a
+ * node may modify its input buffer directly and push down the modified buffer
+ * to its children, thereby avoiding to allocate a possibly large additional
+ * buffer.
+ *
+ * Since the buffer tree may change at any time, this function should be called
+ * during each post_select call.
+ *
+ * \return True if \a btrn has no siblings.
+ */
 bool btr_inplace_ok(struct btr_node *btrn)
 {
        if (!btrn->parent)
@@ -154,95 +555,233 @@ static inline size_t br_available_bytes(struct btr_buffer_reference *br)
        return br->btrb->size - br->consumed;
 }
 
-size_t btr_get_buffer_by_reference(struct btr_buffer_reference *br, char **buf)
+static size_t btr_get_buffer_by_reference(struct btr_buffer_reference *br, char **buf)
 {
-       *buf = br->btrb->buf + br->consumed;
+       if (buf)
+               *buf = br->btrb->buf + br->consumed;
        return br_available_bytes(br);
 }
 
+/**
+ * Obtain the next buffer of the input queue of a buffer tree node.
+ *
+ * \param btrn The node whose input queue is to be queried.
+ * \param bufp Result pointer.
+ *
+ * \return The number of bytes that can be read from buf. Zero if the input
+ * buffer queue is empty. In this case the value of \a bufp is undefined.
+ */
 size_t btr_next_buffer(struct btr_node *btrn, char **bufp)
 {
        struct btr_buffer_reference *br;
+       char *buf, *result = NULL;
+       size_t sz, rv = 0;
 
-       if (list_empty(&btrn->input_queue)) {
-               *bufp = NULL;
-               return 0;
+       FOR_EACH_BUFFER_REF(br, btrn) {
+               sz = btr_get_buffer_by_reference(br, &buf);
+               if (!result) {
+                       result = buf;
+                       rv = sz;
+                       if (!br->btrb->pool)
+                               break;
+                       continue;
+               }
+               if (!br->btrb->pool)
+                       break;
+               if (result + rv != buf)
+                       break;
+               rv += sz;
        }
-       br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
-       return btr_get_buffer_by_reference(br, bufp);
+       if (bufp)
+               *bufp = result;
+       return rv;
 }
 
+/**
+ * Deallocate the given number of bytes from the input queue.
+ *
+ * \param btrn The buffer tree node.
+ * \param numbytes The number of bytes to be deallocated.
+ *
+ * This function must be used to get rid of existing buffer references in the
+ * node's input queue. If no references to a buffer remain, the underlying
+ * buffers are either freed (in the non-buffer pool case) or the read head of
+ * the buffer pool is being advanced.
+ *
+ * Note that \a numbytes may be smaller than the buffer size. In this case the
+ * buffer is not deallocated and subsequent calls to btr_next_buffer() return
+ * the remaining part of the buffer.
+ */
 void btr_consume(struct btr_node *btrn, size_t numbytes)
 {
-       struct btr_buffer_reference *br;
+       struct btr_buffer_reference *br, *tmp;
+       size_t sz;
 
-       assert(!list_empty(&btrn->input_queue));
-       br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
-       assert(br->consumed + numbytes <= br->btrb->size);
-       br->consumed += numbytes;
-       if (br->consumed == br->btrb->size)
-               btr_drop_buffer_reference(br);
+       if (numbytes == 0)
+               return;
+       br = get_first_input_br(btrn);
+       assert(br);
+
+       if (br->wrap_count == 0) {
+               /*
+                * No wrap buffer. Drop buffer references whose buffer
+                * has been fully used. */
+               FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn) {
+                       if (br->consumed + numbytes <= br->btrb->size) {
+                               br->consumed += numbytes;
+                               if (br->consumed == br->btrb->size)
+                                       btr_drop_buffer_reference(br);
+                               return;
+                       }
+                       numbytes -= br->btrb->size - br->consumed;
+                       btr_drop_buffer_reference(br);
+               }
+               assert(false);
+       }
+       /*
+        * We have a wrap buffer, consume from it. If in total, i.e. including
+        * previous calls to brt_consume(), less than wrap_count has been
+        * consumed, there's nothing more we can do.
+        *
+        * Otherwise we drop the wrap buffer and consume from subsequent
+        * buffers of the input queue the correct amount of bytes. This is the
+        * total number of bytes that have been consumed from the wrap buffer.
+        */
+       PARA_DEBUG_LOG("consuming %zu/%zu bytes from wrap buffer\n", numbytes,
+               br_available_bytes(br));
+
+       assert(numbytes <= br_available_bytes(br));
+       if (br->consumed + numbytes < br->wrap_count) {
+               br->consumed += numbytes;
+               return;
+       }
+       PARA_DEBUG_LOG("dropping wrap buffer (%zu bytes)\n", br->btrb->size);
+       /* get rid of the wrap buffer */
+       sz = br->consumed + numbytes;
+       btr_drop_buffer_reference(br);
+       return btr_consume(btrn, sz);
 }
 
-static void flush_input_queue(struct btr_node *btrn)
+/**
+ * Clear the input queue of a buffer tree node.
+ *
+ * \param btrn The node whose input queue should be cleared.
+ */
+void btr_drain(struct btr_node *btrn)
 {
        struct btr_buffer_reference *br, *tmp;
+
        FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
                btr_drop_buffer_reference(br);
 }
 
-void btr_del_node(struct btr_node *btrn)
+/**
+ * Free all resources allocated by btr_new_node().
+ *
+ * \param btrn Pointer to a btr node obtained by \ref btr_new_node().
+ *
+ * Like free(3), it is OK to call this with a \p NULL pointer argument.
+ */
+void btr_free_node(struct btr_node *btrn)
+{
+       if (!btrn)
+               return;
+       free(btrn->name);
+       free(btrn);
+}
+
+/**
+ * Remove a node from a buffer tree.
+ *
+ * \param btrn The node to remove.
+ *
+ * This makes all child nodes of \a btrn orphans and removes \a btrn from the
+ * list of children of its parent. Moreover, the input queue of \a btrn is
+ * flushed if it is not empty.
+ *
+ * \sa \ref btr_splice_out_node.
+ */
+void btr_remove_node(struct btr_node *btrn)
 {
        struct btr_node *ch;
 
        if (!btrn)
                return;
-       PARA_NOTICE_LOG("deleting %s\n", btrn->name);
+       PARA_NOTICE_LOG("removing btr node %s from buffer tree\n", btrn->name);
        FOR_EACH_CHILD(ch, btrn)
                ch->parent = NULL;
-       flush_input_queue(btrn);
+       btr_drain(btrn);
        if (btrn->parent)
                list_del(&btrn->node);
-       free(btrn->name);
-       free(btrn);
 }
 
+/**
+ * Return the amount of available input bytes of a buffer tree node.
+ *
+ * \param btrn The node whose input size should be computed.
+ *
+ * \return The total number of bytes available in the node's input
+ * queue.
+ *
+ * This simply iterates over all buffer references in the input queue and
+ * returns the sum of the sizes of all references.
+ */
 size_t btr_get_input_queue_size(struct btr_node *btrn)
 {
        struct btr_buffer_reference *br;
-       size_t size = 0;
+       size_t size = 0, wrap_consumed = 0;
 
        FOR_EACH_BUFFER_REF(br, btrn) {
-               //PARA_CRIT_LOG("size: %zu\n", size);
+               if (br->wrap_count != 0) {
+                       wrap_consumed = br->consumed;
+                       continue;
+               }
                size += br_available_bytes(br);
        }
+       assert(wrap_consumed <= size);
+       size -= wrap_consumed;
        return size;
 }
 
-int btr_splice_out_node(struct btr_node *btrn)
+/**
+ * Remove a node from the buffer tree, reconnecting parent and children.
+ *
+ * \param btrn The node to splice out.
+ *
+ * This function is used by buffer tree nodes that do not exist during the
+ * whole lifetime of the buffer tree. Unlike btr_remove_node(), calling
+ * btr_splice_out_node() does not split the tree into disconnected components
+ * but reconnects the buffer tree by making all child nodes of \a btrn children
+ * of the parent of \a btrn.
+ */
+void btr_splice_out_node(struct btr_node *btrn)
 {
-       struct btr_node *ch;
+       struct btr_node *ch, *tmp;
 
-       if (!btrn)
-               return -ERRNO_TO_PARA_ERROR(EINVAL);
-       if (btr_get_input_queue_size(btrn) != 0)
-               return -ERRNO_TO_PARA_ERROR(EINVAL);
+       assert(btrn);
        PARA_NOTICE_LOG("splicing out %s\n", btrn->name);
+       btr_pushdown(btrn);
        if (btrn->parent)
                list_del(&btrn->node);
-       FOR_EACH_CHILD(ch, btrn)
+       FOR_EACH_CHILD_SAFE(ch, tmp, btrn) {
+               PARA_INFO_LOG("parent(%s): %s\n", ch->name,
+                       btrn->parent? btrn->parent->name : "NULL");
                ch->parent = btrn->parent;
-       free(btrn->name);
-       free(btrn);
-       return 1;
+               if (btrn->parent)
+                       list_move(&ch->node, &btrn->parent->children);
+       }
+       assert(list_empty(&btrn->children));
 }
 
 /**
- * Return the size of the largest input queue.
+ * Return number of queued output bytes of a buffer tree node.
  *
- * Iterates over all children of the given node.
+ * \param btrn The node whose output queue size should be computed.
+ *
+ * \return This function iterates over all children of the given node and
+ * returns the size of the largest input queue.
  */
-size_t btr_bytes_pending(struct btr_node *btrn)
+size_t btr_get_output_queue_size(struct btr_node *btrn)
 {
        size_t max_size = 0;
        struct btr_node *ch;
@@ -254,36 +793,352 @@ size_t btr_bytes_pending(struct btr_node *btrn)
        return max_size;
 }
 
-int btr_exec(struct btr_node *btrn, const char *command, char **value_result)
-{
-       if (!btrn)
-               return -ERRNO_TO_PARA_ERROR(EINVAL);
-       if (!btrn->execute)
-               return -ERRNO_TO_PARA_ERROR(ENOTSUP);
-       return btrn->execute(btrn, command, value_result);
-}
-
+/**
+ * Execute a inter-node command on a parent node.
+ *
+ * \param btrn The node to start looking.
+ * \param command The command to execute.
+ * \param value_result Additional arguments and result value.
+ *
+ * This function traverses the buffer tree upwards and looks for parent nodes
+ * of \a btrn that understands \a command. On the first such node the command
+ * is executed, and the result is stored in \a value_result.
+ *
+ * \return \p -ENOTSUP if no parent node of \a btrn understands \a command.
+ * Otherwise the return value of the command handler is returned.
+ */
 int btr_exec_up(struct btr_node *btrn, const char *command, char **value_result)
 {
        int ret;
 
        for (; btrn; btrn = btrn->parent) {
                struct btr_node *parent = btrn->parent;
-               PARA_CRIT_LOG("parent: %p\n", parent);
                if (!parent)
                        return -ERRNO_TO_PARA_ERROR(ENOTSUP);
                if (!parent->execute)
                        continue;
+               PARA_INFO_LOG("parent: %s, cmd: %s\n", parent->name, command);
                ret = parent->execute(parent, command, value_result);
                if (ret == -ERRNO_TO_PARA_ERROR(ENOTSUP))
                        continue;
                if (ret < 0)
                        return ret;
+               if (value_result && *value_result)
+                       PARA_NOTICE_LOG("%s(%s): %s\n", command, parent->name,
+                               *value_result);
+               return 1;
        }
        return -ERRNO_TO_PARA_ERROR(ENOTSUP);
 }
 
+/**
+ * Obtain the context of a buffer node tree.
+ *
+ * \param btrn The node whose output queue size should be computed.
+ *
+ * \return A pointer to the \a context address specified at node creation time.
+ *
+ * \sa btr_new_node(), struct \ref btr_node_description.
+ */
 void *btr_context(struct btr_node *btrn)
 {
        return btrn->context;
 }
+
+static bool need_buffer_pool_merge(struct btr_node *btrn)
+{
+       struct btr_buffer_reference *br = get_first_input_br(btrn);
+
+       if (!br)
+               return false;
+       if (br->wrap_count != 0)
+               return true;
+       if (br->btrb->pool)
+               return true;
+       return false;
+}
+
+static void merge_input_pool(struct btr_node *btrn, size_t dest_size)
+{
+       struct btr_buffer_reference *br, *wbr = NULL;
+       int num_refs; /* including wrap buffer */
+       char *buf, *buf1 = NULL, *buf2 = NULL;
+       size_t sz, sz1 = 0, sz2 = 0, wb_consumed = 0;
+
+       br = get_first_input_br(btrn);
+       if (!br || br_available_bytes(br) >= dest_size)
+               return;
+       num_refs = 0;
+       FOR_EACH_BUFFER_REF(br, btrn) {
+               num_refs++;
+               sz = btr_get_buffer_by_reference(br, &buf);
+               if (sz == 0)
+                       break;
+               if (br->wrap_count != 0) {
+                       assert(!wbr);
+                       assert(num_refs == 1);
+                       wbr = br;
+                       if (sz >= dest_size)
+                               return;
+                       wb_consumed = br->consumed;
+                       continue;
+               }
+               if (!buf1) {
+                       buf1 = buf;
+                       sz1 = sz;
+                       goto next;
+               }
+               if (buf1 + sz1 == buf) {
+                       sz1 += sz;
+                       goto next;
+               }
+               if (!buf2) {
+                       buf2 = buf;
+                       sz2 = sz;
+                       goto next;
+               }
+               assert(buf2 + sz2 == buf);
+               sz2 += sz;
+next:
+               if (sz1 + sz2 >= dest_size + wb_consumed)
+                       break;
+       }
+       if (!buf2) /* nothing to do */
+               return;
+       assert(buf1 && sz2 > 0);
+       /*
+        * If the second buffer is large, we only take the first part of it to
+        * avoid having to memcpy() huge buffers.
+        */
+       sz2 = PARA_MIN(sz2, (size_t)(64 * 1024));
+       if (!wbr) {
+               /* Make a new wrap buffer combining buf1 and buf2. */
+               sz = sz1 + sz2;
+               buf = para_malloc(sz);
+               PARA_DEBUG_LOG("merging input buffers: (%p:%zu, %p:%zu) -> %p:%zu\n",
+                       buf1, sz1, buf2, sz2, buf, sz);
+               memcpy(buf, buf1, sz1);
+               memcpy(buf + sz1, buf2, sz2);
+               br = para_calloc(sizeof(*br));
+               br->btrb = new_btrb(buf, sz);
+               br->btrb->refcount = 1;
+               br->consumed = 0;
+               /* This is a wrap buffer */
+               br->wrap_count = sz1;
+               para_list_add(&br->node, &btrn->input_queue);
+               return;
+       }
+       /*
+        * We already have a wrap buffer, but it is too small. It might be
+        * partially used.
+        */
+       if (wbr->wrap_count == sz1 && wbr->btrb->size >= sz1 + sz2) /* nothing we can do about it */
+               return;
+       sz = sz1 + sz2 - wbr->btrb->size; /* amount of new data */
+       PARA_DEBUG_LOG("increasing wrap buffer %zu -> %zu\n", wbr->btrb->size,
+               wbr->btrb->size + sz);
+       wbr->btrb->size += sz;
+       wbr->btrb->buf = para_realloc(wbr->btrb->buf, wbr->btrb->size);
+       /* copy the new data to the end of the reallocated buffer */
+       assert(sz2 >= sz);
+       memcpy(wbr->btrb->buf + wbr->btrb->size - sz, buf2 + sz2 - sz, sz);
+}
+
+/**
+ * Merge the first two input buffers into one.
+ *
+ * This is a quite expensive operation.
+ *
+ * \return The number of buffers that have been available (zero, one or two).
+ */
+static int merge_input(struct btr_node *btrn)
+{
+       struct btr_buffer_reference *brs[2], *br;
+       char *bufs[2], *buf;
+       size_t szs[2], sz;
+       int i;
+
+       if (list_empty(&btrn->input_queue))
+               return 0;
+       if (list_is_singular(&btrn->input_queue))
+               return 1;
+       i = 0;
+       /* get references to the first two buffers */
+       FOR_EACH_BUFFER_REF(br, btrn) {
+               brs[i] = br;
+               szs[i] = btr_get_buffer_by_reference(brs[i], bufs + i);
+               i++;
+               if (i == 2)
+                       break;
+       }
+       assert(i == 2);
+       /* make a new btrb that combines the two buffers and a br to it. */
+       sz = szs[0] + szs[1];
+       buf = para_malloc(sz);
+       PARA_DEBUG_LOG("%s: memory merging input buffers: (%zu, %zu) -> %zu\n",
+               btrn->name, szs[0], szs[1], sz);
+       memcpy(buf, bufs[0], szs[0]);
+       memcpy(buf + szs[0], bufs[1], szs[1]);
+
+       br = para_calloc(sizeof(*br));
+       br->btrb = new_btrb(buf, sz);
+       br->btrb->refcount = 1;
+
+       /* replace the first two refs by the new one */
+       btr_drop_buffer_reference(brs[0]);
+       btr_drop_buffer_reference(brs[1]);
+       para_list_add(&br->node, &btrn->input_queue);
+       return 2;
+}
+
+/**
+ * Combine input queue buffers.
+ *
+ * \param btrn The buffer tree node whose input should be merged.
+ * \param dest_size Stop merging if a buffer of at least this size exists.
+ *
+ * Used to combine as many buffers as needed into a single buffer whose size is
+ * at least \a dest_size. This function is rather cheap in case the parent node
+ * uses buffer pools and rather expensive otherwise.
+ *
+ * Note that if less than \a dest_size bytes are available in total, this
+ * function does nothing and subsequent calls to btr_next_buffer() will still
+ * return a buffer size less than \a dest_size.
+ */
+void btr_merge(struct btr_node *btrn, size_t dest_size)
+{
+       if (need_buffer_pool_merge(btrn))
+               return merge_input_pool(btrn, dest_size);
+       for (;;) {
+               char *buf;
+               size_t len = btr_next_buffer(btrn, &buf);
+               if (len >= dest_size)
+                       return;
+               PARA_DEBUG_LOG("input size = %zu < %zu = dest\n", len, dest_size);
+               if (merge_input(btrn) < 2)
+                       return;
+       }
+}
+
+static bool btr_eof(struct btr_node *btrn)
+{
+       char *buf;
+       size_t len = btr_next_buffer(btrn, &buf);
+
+       return (len == 0 && btr_no_parent(btrn));
+}
+
+static void log_tree_recursively(struct btr_node *btrn, int loglevel, int depth)
+{
+       struct btr_node *ch;
+       const char spaces[] = "                 ", *space = spaces + 16 - depth;
+
+       if (depth > 16)
+               return;
+       para_log(loglevel, "%s%s\n", space, btrn->name);
+       FOR_EACH_CHILD(ch, btrn)
+               log_tree_recursively(ch, loglevel, depth + 1);
+}
+
+/**
+ * Write the current buffer (sub-)tree to the log.
+ *
+ * \param btrn Start logging at this node.
+ * \param loglevel Set severity with which the tree should be logged.
+ */
+void btr_log_tree(struct btr_node *btrn, int loglevel)
+{
+       return log_tree_recursively(btrn, loglevel, 0);
+}
+
+/**
+ * Find the node with the given name in the buffer tree.
+ *
+ * \param name The name of the node to search.
+ * \param root Where to start the search.
+ *
+ * \return A pointer to the node with the given name on success. If \a name is
+ * \p NULL, the function returns \a root. If there is no node with the given
+ * name, \p NULL is returned.
+ */
+struct btr_node *btr_search_node(const char *name, struct btr_node *root)
+{
+       struct btr_node *ch;
+
+       if (!name)
+               return root;
+       if (!strcmp(root->name, name))
+               return root;
+       FOR_EACH_CHILD(ch, root) {
+               struct btr_node *result = btr_search_node(name, ch);
+               if (result)
+                       return result;
+       }
+       return NULL;
+}
+
+/** 640K ought to be enough for everybody ;) */
+#define BTRN_MAX_PENDING (96 * 1024)
+
+/**
+ * Return the current state of a buffer tree node.
+ *
+ * \param btrn The node whose state should be queried.
+ * \param min_iqs The minimal input queue size.
+ * \param type The supposed type of \a btrn.
+ *
+ * Most users of the buffer tree subsystem call this function from both
+ * their pre_select and the post_select methods.
+ *
+ * \return Negative if an error condition was detected, zero if there
+ * is nothing to do and positive otherwise.
+ *
+ * Examples:
+ *
+ * - If a non-root node has no parent and an empty input queue, the function
+ * returns \p -E_BTR_EOF. Similarly, if a non-leaf node has no children, \p
+ * -E_BTR_NO_CHILD is returned.
+ *
+ * - If less than \a min_iqs many bytes are available in the input queue and no
+ * EOF condition was detected, the function returns zero.
+ *
+ * - If there's plenty of data left in the input queue of the children of \a
+ * btrn, the function also returns zero in order to bound the memory usage of
+ * the buffer tree.
+ */
+int btr_node_status(struct btr_node *btrn, size_t min_iqs,
+       enum btr_node_type type)
+{
+       size_t iqs;
+
+       assert(btrn);
+       if (type != BTR_NT_LEAF) {
+               if (btr_no_children(btrn))
+                       return -E_BTR_NO_CHILD;
+               if (btr_get_output_queue_size(btrn) > BTRN_MAX_PENDING)
+                       return 0;
+       }
+       if (type != BTR_NT_ROOT) {
+               if (btr_eof(btrn))
+                       return -E_BTR_EOF;
+               iqs = btr_get_input_queue_size(btrn);
+               if (iqs == 0) /* we have a parent, because not eof */
+                       return 0;
+               if (iqs < min_iqs && !btr_no_parent(btrn))
+                       return 0;
+       }
+       return 1;
+}
+
+/**
+ * Get the time of the first I/O for a buffer tree node.
+ *
+ * \param btrn The node whose I/O time should be obtained.
+ * \param tv Result pointer.
+ *
+ * Mainly useful for the time display of para_audiod.
+ */
+void btr_get_node_start(struct btr_node *btrn, struct timeval *tv)
+{
+       *tv = btrn->start;
+}