audiod: Make default filters work also for udp streams.
[paraslash.git] / buffer_tree.c
1 #include <regex.h>
2 #include <stdbool.h>
3
4 #include "para.h"
5 #include "list.h"
6 #include "string.h"
7 #include "buffer_tree.h"
8 #include "error.h"
9 #include "sched.h"
10
11 /* whead = NULL means area full */
12 struct btr_pool {
13         char *name;
14         char *area_start;
15         char *area_end;
16         char *rhead;
17         char *whead;
18 };
19
20 struct btr_buffer {
21         char *buf;
22         size_t size;
23         /** The number of references to this buffer. */
24         int refcount;
25         /* NULL means no buffer pool but a malloced buffer. */
26         struct btr_pool *pool;
27 };
28
29 struct btr_buffer_reference {
30         struct btr_buffer *btrb;
31         size_t consumed;
32         /* Each buffer reference belongs to the buffer queue list of some buffer tree node. */
33         struct list_head node;
34         size_t wrap_count;
35 };
36
37 struct btr_node {
38         char *name;
39         struct btr_node *parent;
40         /* The position of this btr node in the buffer tree. */
41         struct list_head node;
42         /* The children nodes of this btr node are linked together in a list. */
43         struct list_head children;
44         /* Time of first data transfer. */
45         struct timeval start;
46         /**
47          * The input queue is a list of references to btr buffers. Each item on
48          * the list represents an input buffer which has not been completely
49          * used by this btr node.
50          */
51         struct list_head input_queue;
52         btr_command_handler execute;
53         void *context;
54 };
55
56 /**
57  * Create a new buffer pool.
58  *
59  * \param name The name of the new buffer pool.
60  * \param area_size The size in bytes of the pool area.
61  *
62  * \return An opaque pointer to the newly created buffer pool. It must be
63  * passed to btr_pool_free() after it is no longer used to deallocate all
64  * resources.
65  */
66 struct btr_pool *btr_pool_new(const char *name, size_t area_size)
67 {
68         struct btr_pool *btrp;
69
70         PARA_INFO_LOG("%s, %zu bytes\n", name, area_size);
71         btrp = para_malloc(sizeof(*btrp));
72         btrp->area_start = para_malloc(area_size);
73         btrp->area_end = btrp->area_start + area_size;
74         btrp->rhead = btrp->area_start;
75         btrp->whead = btrp->area_start;
76         btrp->name = para_strdup(name);
77         return btrp;
78 }
79
80 /**
81  * Deallocate resources used by a buffer pool.
82  *
83  * \param btrp A pointer obtained via btr_pool_new().
84  */
85 void btr_pool_free(struct btr_pool *btrp)
86 {
87         if (!btrp)
88                 return;
89         free(btrp->area_start);
90         free(btrp->name);
91         free(btrp);
92 }
93
94 /**
95  * Return the size of the buffer pool area.
96  *
97  * \param btrp The buffer pool.
98  *
99  * \return The same value which was passed during creation time to
100  * btr_pool_new().
101  */
102 size_t btr_pool_size(struct btr_pool *btrp)
103 {
104         return btrp->area_end - btrp->area_start;
105 }
106
107 static size_t btr_pool_filled(struct btr_pool *btrp)
108 {
109         if (!btrp->whead)
110                 return btr_pool_size(btrp);
111         if (btrp->rhead <= btrp->whead)
112                 return  btrp->whead - btrp->rhead;
113         return btr_pool_size(btrp) - (btrp->rhead - btrp->whead);
114 }
115
116 /**
117  * Get the number of unused bytes in the buffer pool.
118  *
119  * \param btrp The pool.
120  *
121  * \return The number of bytes that can currently be allocated.
122  *
123  * Note that in general the returned number of bytes is not available as a
124  * single contiguous buffer. Use btr_pool_available() to obtain the length of
125  * the largest contiguous buffer that can currently be allocated from the
126  * buffer pool.
127  */
128 size_t btr_pool_unused(struct btr_pool *btrp)
129 {
130         return btr_pool_size(btrp) - btr_pool_filled(btrp);
131 }
132
133 /*
134  * Return maximal size available for one read. This is
135  * smaller than the value returned by btr_pool_unused().
136  */
137 static size_t btr_pool_available(struct btr_pool *btrp)
138 {
139         if (!btrp->whead)
140                 return 0;
141         if (btrp->rhead <= btrp->whead)
142                 return btrp->area_end - btrp->whead;
143         return btrp->rhead - btrp->whead;
144 }
145
146 /**
147  * Obtain the current write head.
148  *
149  * \param btrp The buffer pool.
150  * \param result The write head is returned here.
151  *
152  * \return The maximal amount of bytes that may be written to the returned
153  * buffer.
154  */
155 size_t btr_pool_get_buffer(struct btr_pool *btrp, char **result)
156 {
157         if (result)
158                 *result = btrp->whead;
159         return btr_pool_available(btrp);
160 }
161
162 /**
163  * Get references to buffers pointing to free space of the buffer pool area.
164  *
165  * \param btrp The buffer pool.
166  * \param iov The scatter array.
167  *
168  * \return Zero if the buffer pool is full, one if the free space of the buffer
169  * pool area is available as a single contiguous buffer, two if the free space
170  * consists of two buffers. If this function returns the value n, then n
171  * elements of \a iov are initialized.
172  */
173 int btr_pool_get_buffers(struct btr_pool *btrp, struct iovec iov[2])
174 {
175         size_t sz, unused;
176         char *buf;
177
178         sz = btr_pool_get_buffer(btrp, &buf);
179         if (sz == 0)
180                 return 0;
181         iov[0].iov_len = sz;
182         iov[0].iov_base = buf;
183         unused = btr_pool_unused(btrp);
184         if (sz == unused)
185                 return 1;
186         iov[1].iov_len = unused - sz;
187         iov[1].iov_base = btrp->area_start;
188         return 2;
189 }
190
191 /**
192  * Mark a part of the buffer pool area as allocated.
193  *
194  * \param btrp The buffer pool.
195  * \param size The amount of bytes to be allocated.
196  *
197  * This is usually called after the caller wrote to the buffer obtained by
198  * btr_pool_get_buffer().
199  */
200 static void btr_pool_allocate(struct btr_pool *btrp, size_t size)
201 {
202         char *end;
203
204         if (size == 0)
205                 return;
206         assert(size <= btr_pool_available(btrp));
207         end = btrp->whead + size;
208         assert(end <= btrp->area_end);
209
210         if (end == btrp->area_end) {
211                 PARA_DEBUG_LOG("%s: end of pool area reached\n", btrp->name);
212                 end = btrp->area_start;
213         }
214         if (end == btrp->rhead) {
215                 PARA_DEBUG_LOG("%s btrp buffer full\n", btrp->name);
216                 end = NULL; /* buffer full */
217         }
218         btrp->whead = end;
219 }
220
221 static void btr_pool_deallocate(struct btr_pool *btrp, size_t size)
222 {
223         char *end = btrp->rhead + size;
224
225         if (size == 0)
226                 return;
227         assert(end <= btrp->area_end);
228         assert(size <= btr_pool_filled(btrp));
229         if (end == btrp->area_end)
230                 end = btrp->area_start;
231         if (!btrp->whead)
232                 btrp->whead = btrp->rhead;
233         btrp->rhead = end;
234         if (btrp->rhead == btrp->whead)
235                 btrp->rhead = btrp->whead = btrp->area_start;
236 }
237
238 #define FOR_EACH_CHILD(_tn, _btrn) list_for_each_entry((_tn), \
239         &((_btrn)->children), node)
240 #define FOR_EACH_CHILD_SAFE(_tn, _tmp, _btrn) \
241         list_for_each_entry_safe((_tn), (_tmp), &((_btrn)->children), node)
242
243 #define FOR_EACH_BUFFER_REF(_br, _btrn) \
244         list_for_each_entry((_br), &(_btrn)->input_queue, node)
245 #define FOR_EACH_BUFFER_REF_SAFE(_br, _tmp, _btrn) \
246         list_for_each_entry_safe((_br), (_tmp), &(_btrn)->input_queue, node)
247
248 /**
249  * Create a new buffer tree node.
250  *
251  * \param bnd Specifies how to create the new node.
252  *
253  * This function always succeeds (or calls exit()). The returned pointer must
254  * be freed using btr_free_node() after the node has been removed from the
255  * buffer tree via btr_remove_node().
256  */
257 struct btr_node *btr_new_node(struct btr_node_description *bnd)
258 {
259         struct btr_node *btrn = para_malloc(sizeof(*btrn));
260
261         btrn->name = para_strdup(bnd->name);
262         btrn->parent = bnd->parent;
263         btrn->execute = bnd->handler;
264         btrn->context = bnd->context;
265         btrn->start.tv_sec = 0;
266         btrn->start.tv_usec = 0;
267         INIT_LIST_HEAD(&btrn->children);
268         INIT_LIST_HEAD(&btrn->input_queue);
269         if (!bnd->child) {
270                 if (bnd->parent) {
271                         list_add_tail(&btrn->node, &bnd->parent->children);
272                         PARA_INFO_LOG("new leaf node: %s (child of %s)\n",
273                                 bnd->name, bnd->parent->name);
274                 } else
275                         PARA_INFO_LOG("added %s as btr root\n", bnd->name);
276                 goto out;
277         }
278         if (!bnd->parent) {
279                 assert(!bnd->child->parent);
280                 PARA_INFO_LOG("new root: %s (was %s)\n",
281                         bnd->name, bnd->child->name);
282                 btrn->parent = NULL;
283                 list_add_tail(&bnd->child->node, &btrn->children);
284                 /* link it in */
285                 bnd->child->parent = btrn;
286                 goto out;
287         }
288         PARA_EMERG_LOG("inserting internal nodes not yet supported.\n");
289         exit(EXIT_FAILURE);
290         assert(bnd->child->parent == bnd->parent);
291 out:
292         return btrn;
293 }
294
295 /*
296  * Allocate a new btr buffer.
297  *
298  * The freshly allocated buffer will have a zero refcount and will
299  * not be associated with a btr pool.
300  */
301 static struct btr_buffer *new_btrb(char *buf, size_t size)
302 {
303         struct btr_buffer *btrb = para_calloc(sizeof(*btrb));
304
305         btrb->buf = buf;
306         btrb->size = size;
307         return btrb;
308 }
309
310 static void dealloc_buffer(struct btr_buffer *btrb)
311 {
312         if (btrb->pool)
313                 btr_pool_deallocate(btrb->pool, btrb->size);
314         else
315                 free(btrb->buf);
316 }
317
318 static struct btr_buffer_reference *get_first_input_br(struct btr_node *btrn)
319 {
320         if (list_empty(&btrn->input_queue))
321                 return NULL;
322         return list_first_entry(&btrn->input_queue,
323                 struct btr_buffer_reference, node);
324 }
325
326 /*
327  * Deallocate the reference, release the resources if refcount drops to zero.
328  */
329 static void btr_drop_buffer_reference(struct btr_buffer_reference *br)
330 {
331         struct btr_buffer *btrb = br->btrb;
332
333         list_del(&br->node);
334         free(br);
335         btrb->refcount--;
336         if (btrb->refcount == 0) {
337                 dealloc_buffer(btrb);
338                 free(btrb);
339         }
340 }
341
342 static void add_btrb_to_children(struct btr_buffer *btrb,
343                 struct btr_node *btrn, size_t consumed)
344 {
345         struct btr_node *ch;
346
347         if (btrn->start.tv_sec == 0)
348                 btrn->start = *now;
349         FOR_EACH_CHILD(ch, btrn) {
350                 struct btr_buffer_reference *br = para_calloc(sizeof(*br));
351                 br->btrb = btrb;
352                 br->consumed = consumed;
353                 list_add_tail(&br->node, &ch->input_queue);
354                 btrb->refcount++;
355                 if (ch->start.tv_sec == 0)
356                         ch->start = *now;
357         }
358 }
359
360 /**
361  * Insert a malloced buffer into the buffer tree.
362  *
363  * \param buf The buffer to insert.
364  * \param size The size of \a buf in bytes.
365  * \param btrn Position in the buffer tree to create the output.
366  *
367  * This creates references to \a buf and adds these references to each child of
368  * \a btrn. The buffer will be freed using standard free() once no buffer tree
369  * node is referencing it any more.
370  *
371  * Note that this function must not be used if \a buf was obtained from a
372  * buffer pool. Use btr_add_output_pool() in this case.
373  */
374 void btr_add_output(char *buf, size_t size, struct btr_node *btrn)
375 {
376         struct btr_buffer *btrb;
377
378         assert(size != 0);
379         if (list_empty(&btrn->children)) {
380                 free(buf);
381                 return;
382         }
383         btrb = new_btrb(buf, size);
384         add_btrb_to_children(btrb, btrn, 0);
385 }
386
387 /**
388  * Feed data to child nodes of a buffer tree node.
389  *
390  * \param btrp The buffer pool.
391  * \param size The number of bytes to be allocated and fed to each child.
392  * \param btrn The node whose children are to be fed.
393  *
394  * This function allocates the amount of bytes from the buffer pool area,
395  * starting at the current value of the write head, and creates buffer
396  * references to the resulting part of the buffer pool area, one for each child
397  * of \a btrn. The references are then fed into the input queue of each child.
398  */
399 void btr_add_output_pool(struct btr_pool *btrp, size_t size,
400                 struct btr_node *btrn)
401 {
402         struct btr_buffer *btrb;
403         char *buf;
404         size_t avail;
405
406         assert(size != 0);
407         if (list_empty(&btrn->children))
408                 return;
409         avail = btr_pool_get_buffer(btrp, &buf);
410         assert(avail >= size);
411         btr_pool_allocate(btrp, size);
412         btrb = new_btrb(buf, size);
413         btrb->pool = btrp;
414         add_btrb_to_children(btrb, btrn, 0);
415 }
416
417 /**
418  * Copy data to write head of a buffer pool and feed it to all children nodes.
419  *
420  * \param src The source buffer.
421  * \param n The size of the source buffer in bytes.
422  * \param btrp The destination buffer pool.
423  * \param btrn Add the data as output of this node.
424  *
425  * This is expensive. The caller must make sure the data fits into the buffer
426  * pool area.
427  */
428 void btr_copy(const void *src, size_t n, struct btr_pool *btrp,
429         struct btr_node *btrn)
430 {
431         char *buf;
432         size_t sz, copy;
433
434         if (n == 0)
435                 return;
436         assert(n <= btr_pool_unused(btrp));
437         sz = btr_pool_get_buffer(btrp, &buf);
438         copy = PARA_MIN(sz, n);
439         memcpy(buf, src, copy);
440         btr_add_output_pool(btrp, copy, btrn);
441         if (copy == n)
442                 return;
443         sz = btr_pool_get_buffer(btrp, &buf);
444         assert(sz >= n - copy);
445         memcpy(buf, src + copy, n - copy);
446         btr_add_output_pool(btrp, n - copy, btrn);
447 }
448
449 static void btr_pushdown_br(struct btr_buffer_reference *br, struct btr_node *btrn)
450 {
451         add_btrb_to_children(br->btrb, btrn, br->consumed);
452         btr_drop_buffer_reference(br);
453 }
454
455 /**
456  * Feed all buffer references of the input queue through the output channel.
457  *
458  * \param btrn The node whose buffer references should be pushed down.
459  *
460  * This function is useful for filters that do not change the contents of the
461  * buffers at all, like the wav filter or the amp filter if no amplification
462  * was specified. This function is rather cheap.
463  *
464  * \sa \ref btr_pushdown_one().
465  */
466 void btr_pushdown(struct btr_node *btrn)
467 {
468         struct btr_buffer_reference *br, *tmp;
469
470         FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
471                 btr_pushdown_br(br, btrn);
472 }
473
474 /**
475  * Feed the next buffer of the input queue through the output channel.
476  *
477  * \param btrn The node whose first input queue buffer should be pushed down.
478  *
479  * This works like \ref btr_pushdown() but pushes down only one buffer
480  * reference.
481  */
482 void btr_pushdown_one(struct btr_node *btrn)
483 {
484         struct btr_buffer_reference *br;
485
486         if (list_empty(&btrn->input_queue))
487                 return;
488         br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
489         btr_pushdown_br(br, btrn);
490 }
491
492 /*
493  * Find out whether a node is a leaf node.
494  *
495  * \param btrn The node to check.
496  *
497  * \return True if this node has no children. False otherwise.
498  */
499 static bool btr_no_children(struct btr_node *btrn)
500 {
501         return list_empty(&btrn->children);
502 }
503
504 /**
505  * Find out whether a node is an orphan node.
506  *
507  * \param btrn The buffer tree node.
508  *
509  * \return True if \a btrn has no parent.
510  *
511  * This function will always return true for the root node.  However in case
512  * nodes have been removed from the tree, other nodes may become orphans too.
513  */
514 bool btr_no_parent(struct btr_node *btrn)
515 {
516         return !btrn->parent;
517 }
518
519 /**
520  * Find out whether it is OK to change an input buffer.
521  *
522  * \param btrn The buffer tree node to check.
523  *
524  * This is used by filters that produce exactly the same amount of output as
525  * there is input. The amp filter which multiplies each sample by some number
526  * is an example of such a filter. If there are no other nodes in the buffer
527  * tree that read the same input stream (i.e. if \a btrn has no siblings), a
528  * node may modify its input buffer directly and push down the modified buffer
529  * to its children, thereby avoiding to allocate a possibly large additional
530  * buffer.
531  *
532  * Since the buffer tree may change at any time, this function should be called
533  * during each post_select call.
534  *
535  * \return True if \a btrn has no siblings.
536  */
537 bool btr_inplace_ok(struct btr_node *btrn)
538 {
539         if (!btrn->parent)
540                 return true;
541         return list_is_singular(&btrn->parent->children);
542 }
543
544 static inline size_t br_available_bytes(struct btr_buffer_reference *br)
545 {
546         return br->btrb->size - br->consumed;
547 }
548
549 static size_t btr_get_buffer_by_reference(struct btr_buffer_reference *br, char **buf)
550 {
551         if (buf)
552                 *buf = br->btrb->buf + br->consumed;
553         return br_available_bytes(br);
554 }
555
556 /**
557  * Obtain the next buffer of the input queue of a buffer tree node.
558  *
559  * \param btrn The node whose input queue is to be queried.
560  * \param bufp Result pointer.
561  *
562  * \return The number of bytes that can be read from buf. Zero if the input
563  * buffer queue is empty. In this case the value of \a bufp is undefined.
564  */
565 size_t btr_next_buffer(struct btr_node *btrn, char **bufp)
566 {
567         struct btr_buffer_reference *br;
568         char *buf, *result = NULL;
569         size_t sz, rv = 0;
570
571         FOR_EACH_BUFFER_REF(br, btrn) {
572                 sz = btr_get_buffer_by_reference(br, &buf);
573                 if (!result) {
574                         result = buf;
575                         rv = sz;
576                         if (!br->btrb->pool)
577                                 break;
578                         continue;
579                 }
580                 if (!br->btrb->pool)
581                         break;
582                 if (result + rv != buf)
583                         break;
584                 rv += sz;
585         }
586         if (bufp)
587                 *bufp = result;
588         return rv;
589 }
590
591 /**
592  * Deallocate the given number of bytes from the input queue.
593  *
594  * \param btrn The buffer tree node.
595  * \param numbytes The number of bytes to be deallocated.
596  *
597  * This function must be used to get rid of existing buffer references in the
598  * node's input queue. If no references to a buffer remain, the underlying
599  * buffers are either freed (in the non-buffer tree case) or the read head of
600  * the buffer pool is being advanced.
601  *
602  * Note that \a numbytes may be smaller than the buffer size. In this case the
603  * buffer is not deallocated and subsequent calls to btr_next_buffer() return
604  * the remaining part of the buffer.
605  */
606 void btr_consume(struct btr_node *btrn, size_t numbytes)
607 {
608         struct btr_buffer_reference *br, *tmp;
609         size_t sz;
610
611         if (numbytes == 0)
612                 return;
613         br = get_first_input_br(btrn);
614         assert(br);
615
616         if (br->wrap_count == 0) {
617                 /*
618                  * No wrap buffer. Drop buffer references whose buffer
619                  * has been fully used. */
620                 FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn) {
621                         if (br->consumed + numbytes <= br->btrb->size) {
622                                 br->consumed += numbytes;
623                                 if (br->consumed == br->btrb->size)
624                                         btr_drop_buffer_reference(br);
625                                 return;
626                         }
627                         numbytes -= br->btrb->size - br->consumed;
628                         btr_drop_buffer_reference(br);
629                 }
630                 assert(true);
631         }
632         /*
633          * We have a wrap buffer, consume from it. If in total, i.e. including
634          * previous calls to brt_consume(), less than wrap_count has been
635          * consumed, there's nothing more we can do.
636          *
637          * Otherwise we drop the wrap buffer and consume from subsequent
638          * buffers of the input queue the correct amount of bytes. This is the
639          * total number of bytes that have been consumed from the wrap buffer.
640          */
641         PARA_DEBUG_LOG("consuming %zu/%zu bytes from wrap buffer\n", numbytes,
642                 br_available_bytes(br));
643
644         assert(numbytes <= br_available_bytes(br));
645         if (br->consumed + numbytes < br->wrap_count) {
646                 br->consumed += numbytes;
647                 return;
648         }
649         PARA_DEBUG_LOG("dropping wrap buffer (%zu bytes)\n", br->btrb->size);
650         /* get rid of the wrap buffer */
651         sz = br->consumed + numbytes;
652         btr_drop_buffer_reference(br);
653         return btr_consume(btrn, sz);
654 }
655
656 static void flush_input_queue(struct btr_node *btrn)
657 {
658         struct btr_buffer_reference *br, *tmp;
659         FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
660                 btr_drop_buffer_reference(br);
661 }
662
663 /**
664  * Free all resources allocated by btr_new_node().
665  *
666  * Like free(3), it is OK to call this with a \p NULL pointer argument.
667  */
668 void btr_free_node(struct btr_node *btrn)
669 {
670         if (!btrn)
671                 return;
672         free(btrn->name);
673         free(btrn);
674 }
675
676 /**
677  * Remove a node from a buffer tree.
678  *
679  * \param btrn The node to remove.
680  *
681  * This makes all child nodes of \a btrn orphans and removes \a btrn from the
682  * list of children of its parent. Moreover, the input queue of \a btrn is
683  * flushed if it is not empty.
684  *
685  * \sa \ref btr_splice_out_node.
686  */
687 void btr_remove_node(struct btr_node *btrn)
688 {
689         struct btr_node *ch;
690
691         if (!btrn)
692                 return;
693         PARA_NOTICE_LOG("removing btr node %s from buffer tree\n", btrn->name);
694         FOR_EACH_CHILD(ch, btrn)
695                 ch->parent = NULL;
696         flush_input_queue(btrn);
697         if (btrn->parent)
698                 list_del(&btrn->node);
699 }
700
701 /**
702  * Return the amount of available input bytes of a buffer tree node.
703  *
704  * \param btrn The node whose input size should be computed.
705  *
706  * \return The total number of bytes available in the node's input
707  * queue.
708  *
709  * This simply iterates over all buffer references in the input queue and
710  * returns the sum of the sizes of all references.
711  */
712 size_t btr_get_input_queue_size(struct btr_node *btrn)
713 {
714         struct btr_buffer_reference *br;
715         size_t size = 0, wrap_consumed = 0;
716
717         FOR_EACH_BUFFER_REF(br, btrn) {
718                 if (br->wrap_count != 0) {
719                         wrap_consumed = br->consumed;
720                         continue;
721                 }
722                 size += br_available_bytes(br);
723         }
724         assert(wrap_consumed <= size);
725         size -= wrap_consumed;
726         return size;
727 }
728
729 /**
730  * Remove a node from the buffer tree, reconnecting parent and children.
731  *
732  * \param btrn The node to splice out.
733  *
734  * This function is used by buffer tree nodes that do not exist during the
735  * whole lifetime of the buffer tree. Unlike btr_remove_node(), calling
736  * btr_splice_out_node() does not split the tree into disconnected components
737  * but reconnects the buffer tree by making all child nodes of \a btrn children
738  * of the parent of \a btrn.
739  */
740 void btr_splice_out_node(struct btr_node *btrn)
741 {
742         struct btr_node *ch, *tmp;
743
744         assert(btrn);
745         PARA_NOTICE_LOG("splicing out %s\n", btrn->name);
746         btr_pushdown(btrn);
747         if (btrn->parent)
748                 list_del(&btrn->node);
749         FOR_EACH_CHILD_SAFE(ch, tmp, btrn) {
750                 PARA_INFO_LOG("parent(%s): %s\n", ch->name,
751                         btrn->parent? btrn->parent->name : "NULL");
752                 ch->parent = btrn->parent;
753                 if (btrn->parent)
754                         list_move(&ch->node, &btrn->parent->children);
755         }
756         assert(list_empty(&btrn->children));
757 }
758
759 /**
760  * Return number of queued output bytes of a buffer tree node.
761  *
762  * \param btrn The node whose output queue size should be computed.
763  *
764  * This function iterates over all children of the given node and returns the
765  * size of the largest input queue.
766  */
767 size_t btr_get_output_queue_size(struct btr_node *btrn)
768 {
769         size_t max_size = 0;
770         struct btr_node *ch;
771
772         FOR_EACH_CHILD(ch, btrn) {
773                 size_t size = btr_get_input_queue_size(ch);
774                 max_size = PARA_MAX(max_size, size);
775         }
776         return max_size;
777 }
778
779 int btr_exec(struct btr_node *btrn, const char *command, char **value_result)
780 {
781         if (!btrn)
782                 return -ERRNO_TO_PARA_ERROR(EINVAL);
783         if (!btrn->execute)
784                 return -ERRNO_TO_PARA_ERROR(ENOTSUP);
785         return btrn->execute(btrn, command, value_result);
786 }
787
788 /**
789  * Execute a inter-node command on a parent node.
790  *
791  * \param btrn The node to start looking.
792  * \param command The command to execute.
793  * \param value_result Additional arguments and result value.
794  *
795  * This function traverses the buffer tree upwards and looks for parent nodes
796  * of \a btrn that understands \a command. On the first such node the command
797  * is executed, and the result is stored in \a value_result.
798  *
799  * \return \p -ENOTSUP if no parent node of \a btrn understands \a command.
800  * Otherwise the return value of the command handler is returned.
801  */
802 int btr_exec_up(struct btr_node *btrn, const char *command, char **value_result)
803 {
804         int ret;
805
806         for (; btrn; btrn = btrn->parent) {
807                 struct btr_node *parent = btrn->parent;
808                 if (!parent)
809                         return -ERRNO_TO_PARA_ERROR(ENOTSUP);
810                 if (!parent->execute)
811                         continue;
812                 PARA_INFO_LOG("parent: %s, cmd: %s\n", parent->name, command);
813                 ret = parent->execute(parent, command, value_result);
814                 if (ret == -ERRNO_TO_PARA_ERROR(ENOTSUP))
815                         continue;
816                 if (ret < 0)
817                         return ret;
818                 if (value_result && *value_result)
819                         PARA_NOTICE_LOG("%s(%s): %s\n", command, parent->name,
820                                 *value_result);
821                 return 1;
822         }
823         return -ERRNO_TO_PARA_ERROR(ENOTSUP);
824 }
825
826 /**
827  * Obtain the context of a buffer node tree.
828  *
829  * The returned pointer equals the context pointer used at creation time of the
830  * node.
831  *
832  * \sa btr_new_node(), struct \ref btr_node_description.
833  */
834 void *btr_context(struct btr_node *btrn)
835 {
836         return btrn->context;
837 }
838
839 static bool need_buffer_pool_merge(struct btr_node *btrn)
840 {
841         struct btr_buffer_reference *br = get_first_input_br(btrn);
842
843         if (!br)
844                 return false;
845         if (br->wrap_count != 0)
846                 return true;
847         if (br->btrb->pool)
848                 return true;
849         return false;
850 }
851
852 static void merge_input_pool(struct btr_node *btrn, size_t dest_size)
853 {
854         struct btr_buffer_reference *br, *wbr = NULL;
855         int num_refs; /* including wrap buffer */
856         char *buf, *buf1 = NULL, *buf2 = NULL;
857         size_t sz, sz1 = 0, sz2 = 0, wb_consumed = 0;
858
859         br = get_first_input_br(btrn);
860         if (!br || br_available_bytes(br) >= dest_size)
861                 return;
862         num_refs = 0;
863         FOR_EACH_BUFFER_REF(br, btrn) {
864                 num_refs++;
865                 sz = btr_get_buffer_by_reference(br, &buf);
866                 if (sz == 0)
867                         break;
868                 if (br->wrap_count != 0) {
869                         assert(!wbr);
870                         assert(num_refs == 1);
871                         wbr = br;
872                         if (sz >= dest_size)
873                                 return;
874                         wb_consumed = br->consumed;
875                         continue;
876                 }
877                 if (!buf1) {
878                         buf1 = buf;
879                         sz1 = sz;
880                         goto next;
881                 }
882                 if (buf1 + sz1 == buf) {
883                         sz1 += sz;
884                         goto next;
885                 }
886                 if (!buf2) {
887                         buf2 = buf;
888                         sz2 = sz;
889                         goto next;
890                 }
891                 assert(buf2 + sz2 == buf);
892                 sz2 += sz;
893 next:
894                 if (sz1 + sz2 >= dest_size + wb_consumed)
895                         break;
896         }
897         if (!buf2) /* nothing to do */
898                 return;
899         assert(buf1 && sz2 > 0);
900         /*
901          * If the second buffer is large, we only take the first part of it to
902          * avoid having to memcpy() huge buffers.
903          */
904         sz2 = PARA_MIN(sz2, (size_t)(64 * 1024));
905         if (!wbr) {
906                 /* Make a new wrap buffer combining buf1 and buf2. */
907                 sz = sz1 + sz2;
908                 buf = para_malloc(sz);
909                 PARA_DEBUG_LOG("merging input buffers: (%p:%zu, %p:%zu) -> %p:%zu\n",
910                         buf1, sz1, buf2, sz2, buf, sz);
911                 memcpy(buf, buf1, sz1);
912                 memcpy(buf + sz1, buf2, sz2);
913                 br = para_calloc(sizeof(*br));
914                 br->btrb = new_btrb(buf, sz);
915                 br->btrb->refcount = 1;
916                 br->consumed = 0;
917                 /* This is a wrap buffer */
918                 br->wrap_count = sz1;
919                 para_list_add(&br->node, &btrn->input_queue);
920                 return;
921         }
922         /*
923          * We already have a wrap buffer, but it is too small. It might be
924          * partially used.
925          */
926         if (wbr->wrap_count == sz1 && wbr->btrb->size >= sz1 + sz2) /* nothing we can do about it */
927                 return;
928         sz = sz1 + sz2 - wbr->btrb->size; /* amount of new data */
929         PARA_DEBUG_LOG("increasing wrap buffer %zu -> %zu\n", wbr->btrb->size,
930                 wbr->btrb->size + sz);
931         wbr->btrb->size += sz;
932         wbr->btrb->buf = para_realloc(wbr->btrb->buf, wbr->btrb->size);
933         /* copy the new data to the end of the reallocated buffer */
934         assert(sz2 >= sz);
935         memcpy(wbr->btrb->buf + wbr->btrb->size - sz, buf2 + sz2 - sz, sz);
936 }
937
938 /**
939  * Merge the first two input buffers into one.
940  *
941  * This is a quite expensive operation.
942  *
943  * \return The number of buffers that have been available (zero, one or two).
944  */
945 static int merge_input(struct btr_node *btrn)
946 {
947         struct btr_buffer_reference *brs[2], *br;
948         char *bufs[2], *buf;
949         size_t szs[2], sz;
950         int i;
951
952         if (list_empty(&btrn->input_queue))
953                 return 0;
954         if (list_is_singular(&btrn->input_queue))
955                 return 1;
956         i = 0;
957         /* get references to the first two buffers */
958         FOR_EACH_BUFFER_REF(br, btrn) {
959                 brs[i] = br;
960                 szs[i] = btr_get_buffer_by_reference(brs[i], bufs + i);
961                 i++;
962                 if (i == 2)
963                         break;
964         }
965         assert(i == 2);
966         /* make a new btrb that combines the two buffers and a br to it. */
967         sz = szs[0] + szs[1];
968         buf = para_malloc(sz);
969         PARA_DEBUG_LOG("%s: memory merging input buffers: (%zu, %zu) -> %zu\n",
970                 btrn->name, szs[0], szs[1], sz);
971         memcpy(buf, bufs[0], szs[0]);
972         memcpy(buf + szs[0], bufs[1], szs[1]);
973
974         br = para_calloc(sizeof(*br));
975         br->btrb = new_btrb(buf, sz);
976         br->btrb->refcount = 1;
977
978         /* replace the first two refs by the new one */
979         btr_drop_buffer_reference(brs[0]);
980         btr_drop_buffer_reference(brs[1]);
981         para_list_add(&br->node, &btrn->input_queue);
982         return 2;
983 }
984
985 /**
986  * Combine input queue buffers.
987  *
988  * \param btrn The buffer tree node whose input should be merged.
989  * \param dest_size Stop merging if a buffer of at least this size exists.
990  *
991  * Used to combine as many buffers as needed into a single buffer whose size is
992  * at least \a dest_size. This function is rather cheap in case the parent node
993  * uses buffer pools and rather expensive otherwise.
994  *
995  * Note that if less than \a dest_size bytes are available in total, this
996  * function does nothing and subsequent calls to btr_next_buffer() will still
997  * return a buffer size less than \a dest_size.
998  */
999 void btr_merge(struct btr_node *btrn, size_t dest_size)
1000 {
1001         if (need_buffer_pool_merge(btrn))
1002                 return merge_input_pool(btrn, dest_size);
1003         for (;;) {
1004                 char *buf;
1005                 size_t len = btr_next_buffer(btrn, &buf);
1006                 if (len >= dest_size)
1007                         return;
1008                 PARA_DEBUG_LOG("input size = %zu < %zu = dest\n", len, dest_size);
1009                 if (merge_input(btrn) < 2)
1010                         return;
1011         }
1012 }
1013
1014 static bool btr_eof(struct btr_node *btrn)
1015 {
1016         char *buf;
1017         size_t len = btr_next_buffer(btrn, &buf);
1018
1019         return (len == 0 && btr_no_parent(btrn));
1020 }
1021
1022 static void log_tree_recursively(struct btr_node *btrn, int loglevel, int depth)
1023 {
1024         struct btr_node *ch;
1025         const char spaces[] = "                 ", *space = spaces + 16 - depth;
1026
1027         if (depth > 16)
1028                 return;
1029         para_log(loglevel, "%s%s\n", space, btrn->name);
1030         FOR_EACH_CHILD(ch, btrn)
1031                 log_tree_recursively(ch, loglevel, depth + 1);
1032 }
1033
1034 /**
1035  * Write the current buffer (sub-)tree to the log.
1036  *
1037  * \param btrn Start logging at this node.
1038  * \param loglevel Set severity with which the tree should be logged.
1039  */
1040 void btr_log_tree(struct btr_node *btrn, int loglevel)
1041 {
1042         return log_tree_recursively(btrn, loglevel, 0);
1043 }
1044
1045 /**
1046  * Find the node with the given name in the buffer tree.
1047  *
1048  * \param name The name of the node to search.
1049  * \param root Where to start the search.
1050  *
1051  * \return A pointer to the node with the given name on success. If \a name is
1052  * \p NULL, the function returns \a root. If there is no node with the given
1053  * name, \p NULL is returned.
1054  */
1055 struct btr_node *btr_search_node(const char *name, struct btr_node *root)
1056 {
1057         struct btr_node *ch;
1058
1059         if (!name)
1060                 return root;
1061         if (!strcmp(root->name, name))
1062                 return root;
1063         FOR_EACH_CHILD(ch, root) {
1064                 struct btr_node *result = btr_search_node(name, ch);
1065                 if (result)
1066                         return result;
1067         }
1068         return NULL;
1069 }
1070
1071 /** 640K ought to be enough for everybody ;) */
1072 #define BTRN_MAX_PENDING (640 * 1024)
1073
1074 /**
1075  * Return the current state of a buffer tree node.
1076  *
1077  * \param btrn The node whose state should be queried.
1078  * \param min_iqs The minimal input queue size.
1079  * \param type The supposed type of \a btrn.
1080  *
1081  * Most users of the buffer tree subsystem call this function from both
1082  * their pre_select and the post_select methods.
1083  *
1084  * \return Negative if an error condition was detected, zero if there
1085  * is nothing to do and positive otherwise.
1086  *
1087  * Examples:
1088  *
1089  * - If a non-root node has no parent and an empty input queue, the function
1090  * returns \p -E_BTR_EOF. Similarly, if a non-leaf node has no children, \p
1091  * -E_BTR_NO_CHILD is returned.
1092  *
1093  * - If less than \a min_iqs many bytes are available in the input queue and no
1094  * EOF condition was detected, the function returns zero.
1095  *
1096  * - If there's plenty of data left in the input queue of the children of \a
1097  * btrn, the function also returns zero in order to bound the memory usage of
1098  * the buffer tree.
1099  */
1100 int btr_node_status(struct btr_node *btrn, size_t min_iqs,
1101         enum btr_node_type type)
1102 {
1103         size_t iqs;
1104
1105         assert(btrn);
1106         if (type != BTR_NT_LEAF) {
1107                 if (btr_no_children(btrn))
1108                         return -E_BTR_NO_CHILD;
1109                 if (btr_get_output_queue_size(btrn) > BTRN_MAX_PENDING)
1110                         return 0;
1111         }
1112         if (type != BTR_NT_ROOT) {
1113                 if (btr_eof(btrn))
1114                         return -E_BTR_EOF;
1115                 iqs = btr_get_input_queue_size(btrn);
1116                 if (iqs == 0) /* we have a parent, because not eof */
1117                         return 0;
1118                 if (iqs < min_iqs && !btr_no_parent(btrn))
1119                         return 0;
1120         }
1121         return 1;
1122 }
1123
1124 /**
1125  * Get the time of the first I/O for a buffer tree node.
1126  *
1127  * \param btrn The node whose I/O time should be obtained.
1128  * \param tv Result pointer.
1129  *
1130  * Mainly useful for the time display of para_audiod.
1131  */
1132 void btr_get_node_start(struct btr_node *btrn, struct timeval *tv)
1133 {
1134         *tv = btrn->start;
1135 }