copy the classic_statusbar and rockbox_none .sbs's to .rsbs's also so remote displays...
[kugel-rb.git] / apps / buffering.c
blobe80dc79b54d5d2c1646f60f4b25d5cbe1a51758b
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2007 Nicolas Pennequin
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 #include "config.h"
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include "buffering.h"
29 #include "storage.h"
30 #include "system.h"
31 #include "thread.h"
32 #include "file.h"
33 #include "panic.h"
34 #include "memory.h"
35 #include "lcd.h"
36 #include "font.h"
37 #include "button.h"
38 #include "kernel.h"
39 #include "tree.h"
40 #include "debug.h"
41 #include "sprintf.h"
42 #include "settings.h"
43 #include "codecs.h"
44 #include "audio.h"
45 #include "mp3_playback.h"
46 #include "usb.h"
47 #include "screens.h"
48 #include "playlist.h"
49 #include "pcmbuf.h"
50 #include "bmp.h"
51 #include "appevents.h"
52 #include "metadata.h"
53 #ifdef HAVE_ALBUMART
54 #include "albumart.h"
55 #include "jpeg_load.h"
56 #include "bmp.h"
57 #endif
59 #define GUARD_BUFSIZE (32*1024)
61 /* Define LOGF_ENABLE to enable logf output in this file */
62 /*#define LOGF_ENABLE*/
63 #include "logf.h"
65 /* macros to enable logf for queues
66 logging on SYS_TIMEOUT can be disabled */
67 #ifdef SIMULATOR
68 /* Define this for logf output of all queuing except SYS_TIMEOUT */
69 #define BUFFERING_LOGQUEUES
70 /* Define this to logf SYS_TIMEOUT messages */
71 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
72 #endif
74 #ifdef BUFFERING_LOGQUEUES
75 #define LOGFQUEUE logf
76 #else
77 #define LOGFQUEUE(...)
78 #endif
80 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
81 #define LOGFQUEUE_SYS_TIMEOUT logf
82 #else
83 #define LOGFQUEUE_SYS_TIMEOUT(...)
84 #endif
86 /* default point to start buffer refill */
87 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
88 /* amount of data to read in one read() call */
89 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
91 #define BUF_HANDLE_MASK 0x7FFFFFFF
94 /* Ring buffer helper macros */
95 /* Buffer pointer (p) plus value (v), wrapped if necessary */
96 #define RINGBUF_ADD(p,v) (((p)+(v))<buffer_len ? (p)+(v) : (p)+(v)-buffer_len)
97 /* Buffer pointer (p) minus value (v), wrapped if necessary */
98 #define RINGBUF_SUB(p,v) ((p>=v) ? (p)-(v) : (p)+buffer_len-(v))
99 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
100 #define RINGBUF_ADD_CROSS(p1,v,p2) \
101 ((p1<p2) ? (int)((p1)+(v))-(int)(p2) : (int)((p1)+(v)-(p2))-(int)buffer_len)
102 /* Bytes available in the buffer */
103 #define BUF_USED RINGBUF_SUB(buf_widx, buf_ridx)
105 /* assert(sizeof(struct memory_handle)%4==0) */
106 struct memory_handle {
107 int id; /* A unique ID for the handle */
108 enum data_type type; /* Type of data buffered with this handle */
109 char path[MAX_PATH]; /* Path if data originated in a file */
110 int fd; /* File descriptor to path (-1 if closed) */
111 size_t data; /* Start index of the handle's data buffer */
112 volatile size_t ridx; /* Read pointer, relative to the main buffer */
113 size_t widx; /* Write pointer */
114 size_t filesize; /* File total length */
115 size_t filerem; /* Remaining bytes of file NOT in buffer */
116 volatile size_t available; /* Available bytes to read from buffer */
117 size_t offset; /* Offset at which we started reading the file */
118 struct memory_handle *next;
120 /* invariant: filesize == offset + available + filerem */
122 static char *buffer;
123 static char *guard_buffer;
125 static size_t buffer_len;
127 static volatile size_t buf_widx; /* current writing position */
128 static volatile size_t buf_ridx; /* current reading position */
129 /* buf_*idx are values relative to the buffer, not real pointers. */
131 /* Configuration */
132 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
133 #if MEM > 8
134 static size_t high_watermark = 0; /* High watermark for rebuffer */
135 #endif
137 /* current memory handle in the linked list. NULL when the list is empty. */
138 static struct memory_handle *cur_handle;
139 /* first memory handle in the linked list. NULL when the list is empty. */
140 static struct memory_handle *first_handle;
142 static int num_handles; /* number of handles in the list */
144 static int base_handle_id;
146 static struct mutex llist_mutex;
147 static struct mutex llist_mod_mutex;
149 /* Handle cache (makes find_handle faster).
150 This is global so that move_handle and rm_handle can invalidate it. */
151 static struct memory_handle *cached_handle = NULL;
153 static struct {
154 size_t remaining; /* Amount of data needing to be buffered */
155 size_t wasted; /* Amount of space available for freeing */
156 size_t buffered; /* Amount of data currently in the buffer */
157 size_t useful; /* Amount of data still useful to the user */
158 } data_counters;
161 /* Messages available to communicate with the buffering thread */
162 enum {
163 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
164 used in a low buffer situation. */
165 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
166 offset (the offset has to be set beforehand) */
167 Q_CLOSE_HANDLE, /* Request closing a handle */
168 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
170 /* Configuration: */
171 Q_START_FILL, /* Request that the buffering thread initiate a buffer
172 fill at its earliest convenience */
173 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
174 (which means the disk is spinning) */
177 /* Buffering thread */
178 static void buffering_thread(void);
179 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
180 static const char buffering_thread_name[] = "buffering";
181 static unsigned int buffering_thread_id = 0;
182 static struct event_queue buffering_queue;
183 static struct queue_sender_list buffering_queue_sender_list;
188 LINKED LIST MANAGEMENT
189 ======================
191 add_handle : Add a handle to the list
192 rm_handle : Remove a handle from the list
193 find_handle : Get a handle pointer from an ID
194 move_handle : Move a handle in the buffer (with or without its data)
196 These functions only handle the linked list structure. They don't touch the
197 contents of the struct memory_handle headers. They also change the buf_*idx
198 pointers when necessary and manage the handle IDs.
200 The first and current (== last) handle are kept track of.
201 A new handle is added at buf_widx and becomes the current one.
202 buf_widx always points to the current writing position for the current handle
203 buf_ridx always points to the location of the first handle.
204 buf_ridx == buf_widx means the buffer is empty.
208 /* Add a new handle to the linked list and return it. It will have become the
209 new current handle.
210 data_size must contain the size of what will be in the handle.
211 can_wrap tells us whether this type of data may wrap on buffer
212 alloc_all tells us if we must immediately be able to allocate data_size
213 returns a valid memory handle if all conditions for allocation are met.
214 NULL if there memory_handle itself cannot be allocated or if the
215 data_size cannot be allocated and alloc_all is set. This function's
216 only potential side effect is to allocate space for the cur_handle
217 if it returns NULL.
219 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
220 bool alloc_all)
222 /* gives each handle a unique id */
223 static int cur_handle_id = 0;
224 size_t shift;
225 size_t new_widx;
226 size_t len;
227 int overlap;
229 if (num_handles >= BUF_MAX_HANDLES)
230 return NULL;
232 mutex_lock(&llist_mutex);
233 mutex_lock(&llist_mod_mutex);
235 if (cur_handle && cur_handle->filerem > 0) {
236 /* the current handle hasn't finished buffering. We can only add
237 a new one if there is already enough free space to finish
238 the buffering. */
239 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
240 if (RINGBUF_ADD_CROSS(cur_handle->widx, req, buf_ridx) >= 0) {
241 /* Not enough space */
242 mutex_unlock(&llist_mod_mutex);
243 mutex_unlock(&llist_mutex);
244 return NULL;
245 } else {
246 /* Allocate the remainder of the space for the current handle */
247 buf_widx = RINGBUF_ADD(cur_handle->widx, cur_handle->filerem);
251 /* align to 4 bytes up */
252 new_widx = RINGBUF_ADD(buf_widx, 3) & ~3;
254 len = data_size + sizeof(struct memory_handle);
256 /* First, will the handle wrap? */
257 /* If the handle would wrap, move to the beginning of the buffer,
258 * or if the data must not but would wrap, move it to the beginning */
259 if( (new_widx + sizeof(struct memory_handle) > buffer_len) ||
260 (!can_wrap && (new_widx + len > buffer_len)) ) {
261 new_widx = 0;
264 /* How far we shifted buf_widx to align things, must be < buffer_len */
265 shift = RINGBUF_SUB(new_widx, buf_widx);
267 /* How much space are we short in the actual ring buffer? */
268 overlap = RINGBUF_ADD_CROSS(buf_widx, shift + len, buf_ridx);
269 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
270 /* Not enough space for required allocations */
271 mutex_unlock(&llist_mod_mutex);
272 mutex_unlock(&llist_mutex);
273 return NULL;
276 /* There is enough space for the required data, advance the buf_widx and
277 * initialize the struct */
278 buf_widx = new_widx;
280 struct memory_handle *new_handle =
281 (struct memory_handle *)(&buffer[buf_widx]);
283 /* only advance the buffer write index of the size of the struct */
284 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
286 new_handle->id = cur_handle_id;
287 /* Wrap signed int is safe and 0 doesn't happen */
288 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
289 new_handle->next = NULL;
290 num_handles++;
292 if (!first_handle)
293 /* the new handle is the first one */
294 first_handle = new_handle;
296 if (cur_handle)
297 cur_handle->next = new_handle;
299 cur_handle = new_handle;
301 mutex_unlock(&llist_mod_mutex);
302 mutex_unlock(&llist_mutex);
303 return new_handle;
306 /* Delete a given memory handle from the linked list
307 and return true for success. Nothing is actually erased from memory. */
308 static bool rm_handle(const struct memory_handle *h)
310 if (h == NULL)
311 return true;
313 mutex_lock(&llist_mutex);
314 mutex_lock(&llist_mod_mutex);
316 if (h == first_handle) {
317 first_handle = h->next;
318 if (h == cur_handle) {
319 /* h was the first and last handle: the buffer is now empty */
320 cur_handle = NULL;
321 buf_ridx = buf_widx = 0;
322 } else {
323 /* update buf_ridx to point to the new first handle */
324 buf_ridx = (void *)first_handle - (void *)buffer;
326 } else {
327 struct memory_handle *m = first_handle;
328 /* Find the previous handle */
329 while (m && m->next != h) {
330 m = m->next;
332 if (m && m->next == h) {
333 m->next = h->next;
334 if (h == cur_handle) {
335 cur_handle = m;
336 buf_widx = cur_handle->widx;
338 } else {
339 mutex_unlock(&llist_mod_mutex);
340 mutex_unlock(&llist_mutex);
341 return false;
345 /* Invalidate the cache to prevent it from keeping the old location of h */
346 if (h == cached_handle)
347 cached_handle = NULL;
349 num_handles--;
351 mutex_unlock(&llist_mod_mutex);
352 mutex_unlock(&llist_mutex);
353 return true;
356 /* Return a pointer to the memory handle of given ID.
357 NULL if the handle wasn't found */
358 static struct memory_handle *find_handle(int handle_id)
360 if (handle_id < 0)
361 return NULL;
363 mutex_lock(&llist_mutex);
365 /* simple caching because most of the time the requested handle
366 will either be the same as the last, or the one after the last */
367 if (cached_handle)
369 if (cached_handle->id == handle_id) {
370 mutex_unlock(&llist_mutex);
371 return cached_handle;
372 } else if (cached_handle->next &&
373 (cached_handle->next->id == handle_id)) {
374 cached_handle = cached_handle->next;
375 mutex_unlock(&llist_mutex);
376 return cached_handle;
380 struct memory_handle *m = first_handle;
381 while (m && m->id != handle_id) {
382 m = m->next;
384 /* This condition can only be reached with !m or m->id == handle_id */
385 if (m)
386 cached_handle = m;
388 mutex_unlock(&llist_mutex);
389 return m;
392 /* Move a memory handle and data_size of its data delta bytes along the buffer.
393 delta maximum bytes available to move the handle. If the move is performed
394 it is set to the actual distance moved.
395 data_size is the amount of data to move along with the struct.
396 returns a valid memory_handle if the move is successful
397 NULL if the handle is NULL, the move would be less than the size of
398 a memory_handle after correcting for wraps or if the handle is not
399 found in the linked list for adjustment. This function has no side
400 effects if NULL is returned. */
401 static bool move_handle(struct memory_handle **h, size_t *delta,
402 size_t data_size, bool can_wrap)
404 struct memory_handle *dest;
405 const struct memory_handle *src;
406 size_t newpos;
407 size_t size_to_move;
408 size_t final_delta = *delta;
409 int overlap;
411 if (h == NULL || (src = *h) == NULL)
412 return false;
414 size_to_move = sizeof(struct memory_handle) + data_size;
416 /* Align to four bytes, down */
417 final_delta &= ~3;
418 if (final_delta < sizeof(struct memory_handle)) {
419 /* It's not legal to move less than the size of the struct */
420 return false;
423 mutex_lock(&llist_mutex);
424 mutex_lock(&llist_mod_mutex);
426 newpos = RINGBUF_ADD((void *)src - (void *)buffer, final_delta);
427 overlap = RINGBUF_ADD_CROSS(newpos, size_to_move, buffer_len - 1);
429 if (overlap > 0) {
430 /* Some part of the struct + data would wrap, maybe ok */
431 size_t correction = 0;
432 /* If the overlap lands inside the memory_handle */
433 if ((unsigned)overlap > data_size) {
434 /* Correct the position and real delta to prevent the struct from
435 * wrapping, this guarantees an aligned delta, I think */
436 correction = overlap - data_size;
437 } else if (!can_wrap) {
438 /* Otherwise the overlap falls in the data area and must all be
439 * backed out. This may become conditional if ever we move
440 * data that is allowed to wrap (ie audio) */
441 correction = overlap;
442 /* Align correction to four bytes, up */
443 correction = (correction+3) & ~3;
445 if (correction) {
446 if (final_delta < correction + sizeof(struct memory_handle)) {
447 /* Delta cannot end up less than the size of the struct */
448 mutex_unlock(&llist_mod_mutex);
449 mutex_unlock(&llist_mutex);
450 return false;
453 newpos -= correction;
454 overlap -= correction;/* Used below to know how to split the data */
455 final_delta -= correction;
459 dest = (struct memory_handle *)(&buffer[newpos]);
461 if (src == first_handle) {
462 first_handle = dest;
463 buf_ridx = newpos;
464 } else {
465 struct memory_handle *m = first_handle;
466 while (m && m->next != src) {
467 m = m->next;
469 if (m && m->next == src) {
470 m->next = dest;
471 } else {
472 mutex_unlock(&llist_mod_mutex);
473 mutex_unlock(&llist_mutex);
474 return false;
479 /* Update the cache to prevent it from keeping the old location of h */
480 if (src == cached_handle)
481 cached_handle = dest;
483 /* the cur_handle pointer might need updating */
484 if (src == cur_handle)
485 cur_handle = dest;
487 if (overlap > 0) {
488 /* FIXME : this code is broken and can leave the data corrupted when
489 * the amount of data to move is close to the whole buffer size.
491 * Example : ('S' is the source data, '-' is empty buffer)
492 * Size of the buffer is 8 bytes, starts at 0.
493 * Size of the data to move is 7 bytes.
495 * -SSSSSSS
496 * ^-------- start of source data == 1
498 * DD-DDDDD ('D' is desired destination data)
499 * ^------ start of destination data == 3
501 * memmove(3, 1, 5);
502 * memmove(0, 7, 2);
504 * First memmove() call will leave the buffer in this state:
506 * -SSDDDDD
507 * ^^
508 * \--- data to be moved by the second memmove() call, but
509 * overwritten by the first call.
511 * See FS#10605 for more details
513 size_t first_part = size_to_move - overlap;
514 memmove(dest, src, first_part);
515 memmove(buffer, (const char *)src + first_part, overlap);
516 } else {
517 memmove(dest, src, size_to_move);
520 /* Update the caller with the new location of h and the distance moved */
521 *h = dest;
522 *delta = final_delta;
523 mutex_unlock(&llist_mod_mutex);
524 mutex_unlock(&llist_mutex);
525 return dest;
530 BUFFER SPACE MANAGEMENT
531 =======================
533 update_data_counters: Updates the values in data_counters
534 buffer_is_low : Returns true if the amount of useful data in the buffer is low
535 buffer_handle : Buffer data for a handle
536 reset_handle : Reset write position and data buffer of a handle to its offset
537 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
538 shrink_handle : Free buffer space by moving a handle
539 fill_buffer : Call buffer_handle for all handles that have data to buffer
541 These functions are used by the buffering thread to manage buffer space.
544 static void update_data_counters(void)
546 struct memory_handle *m = find_handle(base_handle_id);
547 bool is_useful = m==NULL;
549 size_t buffered = 0;
550 size_t wasted = 0;
551 size_t remaining = 0;
552 size_t useful = 0;
554 mutex_lock(&llist_mutex);
556 m = first_handle;
557 while (m) {
558 buffered += m->available;
559 wasted += RINGBUF_SUB(m->ridx, m->data);
560 remaining += m->filerem;
562 if (m->id == base_handle_id)
563 is_useful = true;
565 if (is_useful)
566 useful += RINGBUF_SUB(m->widx, m->ridx);
568 m = m->next;
571 mutex_unlock(&llist_mutex);
573 data_counters.buffered = buffered;
574 data_counters.wasted = wasted;
575 data_counters.remaining = remaining;
576 data_counters.useful = useful;
579 static inline bool buffer_is_low(void)
581 update_data_counters();
582 return data_counters.useful < (conf_watermark / 2);
585 /* Buffer data for the given handle.
586 Return whether or not the buffering should continue explicitly. */
587 static bool buffer_handle(int handle_id)
589 logf("buffer_handle(%d)", handle_id);
590 struct memory_handle *h = find_handle(handle_id);
591 if (!h)
592 return true;
594 if (h->filerem == 0) {
595 /* nothing left to buffer */
596 return true;
599 if (h->fd < 0) /* file closed, reopen */
601 if (*h->path)
602 h->fd = open(h->path, O_RDONLY);
604 if (h->fd < 0)
606 /* could not open the file, truncate it where it is */
607 h->filesize -= h->filerem;
608 h->filerem = 0;
609 return true;
612 if (h->offset)
613 lseek(h->fd, h->offset, SEEK_SET);
616 trigger_cpu_boost();
618 if (h->type == TYPE_ID3)
620 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
622 /* metadata parsing failed: clear the buffer. */
623 memset(buffer + h->data, 0, sizeof(struct mp3entry));
625 close(h->fd);
626 h->fd = -1;
627 h->filerem = 0;
628 h->available = sizeof(struct mp3entry);
629 h->widx += sizeof(struct mp3entry);
630 send_event(BUFFER_EVENT_FINISHED, &h->id);
631 return true;
634 while (h->filerem > 0)
636 /* max amount to copy */
637 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
638 buffer_len - h->widx);
640 /* stop copying if it would overwrite the reading position */
641 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
642 return false;
644 /* This would read into the next handle, this is broken */
645 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
646 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
647 /* Try to recover by truncating this file */
648 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
649 (unsigned)((void *)h->next - (void *)buffer));
650 h->filerem -= copy_n;
651 h->filesize -= copy_n;
652 logf("buf alloc short %ld", (long)copy_n);
653 if (h->filerem)
654 continue;
655 else
656 break;
659 /* rc is the actual amount read */
660 int rc = read(h->fd, &buffer[h->widx], copy_n);
662 if (rc < 0)
664 /* Some kind of filesystem error, maybe recoverable if not codec */
665 if (h->type == TYPE_CODEC) {
666 logf("Partial codec");
667 break;
670 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
671 h->filesize -= h->filerem;
672 h->filerem = 0;
673 break;
676 /* Advance buffer */
677 h->widx = RINGBUF_ADD(h->widx, rc);
678 if (h == cur_handle)
679 buf_widx = h->widx;
680 h->available += rc;
681 h->filerem -= rc;
683 /* If this is a large file, see if we need to break or give the codec
684 * more time */
685 if (h->type == TYPE_PACKET_AUDIO &&
686 pcmbuf_is_lowdata() && !buffer_is_low())
688 sleep(1);
690 else
692 yield();
695 if (!queue_empty(&buffering_queue))
696 break;
699 if (h->filerem == 0) {
700 /* finished buffering the file */
701 close(h->fd);
702 h->fd = -1;
703 send_event(BUFFER_EVENT_FINISHED, &h->id);
706 return true;
709 /* Reset writing position and data buffer of a handle to its current offset.
710 Use this after having set the new offset to use. */
711 static void reset_handle(int handle_id)
713 logf("reset_handle(%d)", handle_id);
715 struct memory_handle *h = find_handle(handle_id);
716 if (!h)
717 return;
719 h->ridx = h->widx = h->data;
720 if (h == cur_handle)
721 buf_widx = h->widx;
722 h->available = 0;
723 h->filerem = h->filesize - h->offset;
725 if (h->fd >= 0) {
726 lseek(h->fd, h->offset, SEEK_SET);
730 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
731 static void rebuffer_handle(int handle_id, size_t newpos)
733 struct memory_handle *h = find_handle(handle_id);
734 if (!h)
735 return;
737 /* When seeking foward off of the buffer, if it is a short seek don't
738 rebuffer the whole track, just read enough to satisfy */
739 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
741 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
742 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
743 h->ridx = h->data + newpos;
744 return;
747 h->offset = newpos;
749 /* Reset the handle to its new offset */
750 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
751 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
753 size_t next = (unsigned)((void *)h->next - (void *)buffer);
754 if (RINGBUF_SUB(next, h->data) < h->filesize - newpos)
756 /* There isn't enough space to rebuffer all of the track from its new
757 offset, so we ask the user to free some */
758 DEBUGF("rebuffer_handle: space is needed\n");
759 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
762 /* Now we ask for a rebuffer */
763 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
764 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
767 static bool close_handle(int handle_id)
769 struct memory_handle *h = find_handle(handle_id);
771 /* If the handle is not found, it is closed */
772 if (!h)
773 return true;
775 if (h->fd >= 0) {
776 close(h->fd);
777 h->fd = -1;
780 /* rm_handle returns true unless the handle somehow persists after exit */
781 return rm_handle(h);
784 /* Free buffer space by moving the handle struct right before the useful
785 part of its data buffer or by moving all the data. */
786 static void shrink_handle(struct memory_handle *h)
788 size_t delta;
790 if (!h)
791 return;
793 if (h->next && h->filerem == 0 &&
794 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
795 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
796 h->type == TYPE_ATOMIC_AUDIO))
798 /* metadata handle: we can move all of it */
799 size_t handle_distance =
800 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
801 delta = handle_distance - h->available;
803 /* The value of delta might change for alignment reasons */
804 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
805 return;
807 size_t olddata = h->data;
808 h->data = RINGBUF_ADD(h->data, delta);
809 h->ridx = RINGBUF_ADD(h->ridx, delta);
810 h->widx = RINGBUF_ADD(h->widx, delta);
812 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
813 /* when moving an mp3entry we need to readjust its pointers. */
814 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
815 (void *)&buffer[h->data],
816 (const void *)&buffer[olddata]);
817 } else if (h->type == TYPE_BITMAP) {
818 /* adjust the bitmap's pointer */
819 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
820 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
823 else
825 /* only move the handle struct */
826 delta = RINGBUF_SUB(h->ridx, h->data);
827 if (!move_handle(&h, &delta, 0, true))
828 return;
830 h->data = RINGBUF_ADD(h->data, delta);
831 h->available -= delta;
832 h->offset += delta;
836 /* Fill the buffer by buffering as much data as possible for handles that still
837 have data left to buffer
838 Return whether or not to continue filling after this */
839 static bool fill_buffer(void)
841 logf("fill_buffer()");
842 struct memory_handle *m;
843 shrink_handle(first_handle);
844 m = first_handle;
845 while (queue_empty(&buffering_queue) && m) {
846 if (m->filerem > 0) {
847 if (!buffer_handle(m->id)) {
848 m = NULL;
849 break;
852 m = m->next;
855 if (m) {
856 return true;
858 else
860 /* only spin the disk down if the filling wasn't interrupted by an
861 event arriving in the queue. */
862 storage_sleep();
863 return false;
867 #ifdef HAVE_ALBUMART
868 /* Given a file descriptor to a bitmap file, write the bitmap data to the
869 buffer, with a struct bitmap and the actual data immediately following.
870 Return value is the total size (struct + data). */
871 static int load_image(int fd, const char *path, struct dim *dim)
873 int rc;
874 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
876 /* get the desired image size */
877 bmp->width = dim->width, bmp->height = dim->height;
878 /* FIXME: alignment may be needed for the data buffer. */
879 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
880 #ifndef HAVE_JPEG
881 (void) path;
882 #endif
883 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
884 bmp->maskdata = NULL;
885 #endif
887 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
888 - sizeof(struct bitmap);
890 #ifdef HAVE_JPEG
891 int pathlen = strlen(path);
892 if (strcmp(path + pathlen - 4, ".bmp"))
893 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
894 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
895 else
896 #endif
897 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
898 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
899 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
901 #endif
905 MAIN BUFFERING API CALLS
906 ========================
908 bufopen : Request the opening of a new handle for a file
909 bufalloc : Open a new handle for data other than a file.
910 bufclose : Close an open handle
911 bufseek : Set the read pointer in a handle
912 bufadvance : Move the read pointer in a handle
913 bufread : Copy data from a handle into a given buffer
914 bufgetdata : Give a pointer to the handle's data
916 These functions are exported, to allow interaction with the buffer.
917 They take care of the content of the structs, and rely on the linked list
918 management functions for all the actual handle management work.
922 /* Reserve space in the buffer for a file.
923 filename: name of the file to open
924 offset: offset at which to start buffering the file, useful when the first
925 (offset-1) bytes of the file aren't needed.
926 type: one of the data types supported (audio, image, cuesheet, others
927 user_data: user data passed possibly passed in subcalls specific to a
928 data_type (only used for image (albumart) buffering so far )
929 return value: <0 if the file cannot be opened, or one file already
930 queued to be opened, otherwise the handle for the file in the buffer
932 int bufopen(const char *file, size_t offset, enum data_type type,
933 void *user_data)
935 #ifndef HAVE_ALBUMART
936 /* currently only used for aa loading */
937 (void)user_data;
938 #endif
939 if (type == TYPE_ID3)
941 /* ID3 case: allocate space, init the handle and return. */
943 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
944 if (!h)
945 return ERR_BUFFER_FULL;
947 h->fd = -1;
948 h->filesize = sizeof(struct mp3entry);
949 h->filerem = sizeof(struct mp3entry);
950 h->offset = 0;
951 h->data = buf_widx;
952 h->ridx = buf_widx;
953 h->widx = buf_widx;
954 h->available = 0;
955 h->type = type;
956 strlcpy(h->path, file, MAX_PATH);
958 buf_widx += sizeof(struct mp3entry); /* safe because the handle
959 can't wrap */
961 /* Inform the buffering thread that we added a handle */
962 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
963 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
965 return h->id;
968 /* Other cases: there is a little more work. */
970 int fd = open(file, O_RDONLY);
971 if (fd < 0)
972 return ERR_FILE_ERROR;
974 size_t size = filesize(fd);
975 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
977 size_t adjusted_offset = offset;
978 if (adjusted_offset > size)
979 adjusted_offset = 0;
981 struct memory_handle *h = add_handle(size-adjusted_offset, can_wrap, false);
982 if (!h)
984 DEBUGF("bufopen: failed to add handle\n");
985 close(fd);
986 return ERR_BUFFER_FULL;
989 strlcpy(h->path, file, MAX_PATH);
990 h->offset = adjusted_offset;
991 h->ridx = buf_widx;
992 h->widx = buf_widx;
993 h->data = buf_widx;
994 h->available = 0;
995 h->filerem = 0;
996 h->type = type;
998 #ifdef HAVE_ALBUMART
999 if (type == TYPE_BITMAP)
1001 /* Bitmap file: we load the data instead of the file */
1002 int rc;
1003 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1004 rc = load_image(fd, file, (struct dim*)user_data);
1005 mutex_unlock(&llist_mod_mutex);
1006 if (rc <= 0)
1008 rm_handle(h);
1009 close(fd);
1010 return ERR_FILE_ERROR;
1012 h->filerem = 0;
1013 h->filesize = rc;
1014 h->available = rc;
1015 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1016 buf_widx += rc; /* safe too */
1018 else
1019 #endif
1021 h->filerem = size - adjusted_offset;
1022 h->filesize = size;
1023 h->available = 0;
1024 h->widx = buf_widx;
1027 if (type == TYPE_CUESHEET) {
1028 h->fd = fd;
1029 /* Immediately start buffering those */
1030 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1031 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1032 } else {
1033 /* Other types will get buffered in the course of normal operations */
1034 h->fd = -1;
1035 close(fd);
1037 /* Inform the buffering thread that we added a handle */
1038 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1039 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1042 logf("bufopen: new hdl %d", h->id);
1043 return h->id;
1046 /* Open a new handle from data that needs to be copied from memory.
1047 src is the source buffer from which to copy data. It can be NULL to simply
1048 reserve buffer space.
1049 size is the requested size. The call will only be successful if the
1050 requested amount of data can entirely fit in the buffer without wrapping.
1051 Return value is the handle id for success or <0 for failure.
1053 int bufalloc(const void *src, size_t size, enum data_type type)
1055 struct memory_handle *h = add_handle(size, false, true);
1057 if (!h)
1058 return ERR_BUFFER_FULL;
1060 if (src) {
1061 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1062 /* specially take care of struct mp3entry */
1063 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1064 (const struct mp3entry *)src);
1065 } else {
1066 memcpy(&buffer[buf_widx], src, size);
1070 h->fd = -1;
1071 *h->path = 0;
1072 h->filesize = size;
1073 h->filerem = 0;
1074 h->offset = 0;
1075 h->ridx = buf_widx;
1076 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1077 h->data = buf_widx;
1078 h->available = size;
1079 h->type = type;
1081 buf_widx += size; /* safe too */
1083 logf("bufalloc: new hdl %d", h->id);
1084 return h->id;
1087 /* Close the handle. Return true for success and false for failure */
1088 bool bufclose(int handle_id)
1090 logf("bufclose(%d)", handle_id);
1092 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1093 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1096 /* Set reading index in handle (relatively to the start of the file).
1097 Access before the available data will trigger a rebuffer.
1098 Return 0 for success and < 0 for failure:
1099 -1 if the handle wasn't found
1100 -2 if the new requested position was beyond the end of the file
1102 int bufseek(int handle_id, size_t newpos)
1104 struct memory_handle *h = find_handle(handle_id);
1105 if (!h)
1106 return ERR_HANDLE_NOT_FOUND;
1108 if (newpos > h->filesize) {
1109 /* access beyond the end of the file */
1110 return ERR_INVALID_VALUE;
1112 else if (newpos < h->offset || h->offset + h->available < newpos) {
1113 /* access before or after buffered data. A rebuffer is needed. */
1114 rebuffer_handle(handle_id, newpos);
1116 else {
1117 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1119 return 0;
1122 /* Advance the reading index in a handle (relatively to its current position).
1123 Return 0 for success and < 0 for failure */
1124 int bufadvance(int handle_id, off_t offset)
1126 const struct memory_handle *h = find_handle(handle_id);
1127 if (!h)
1128 return ERR_HANDLE_NOT_FOUND;
1130 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1131 return bufseek(handle_id, newpos);
1134 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1135 * actual amount of data available for reading. This function explicitly
1136 * does not check the validity of the input handle. It does do range checks
1137 * on size and returns a valid (and explicit) amount of data for reading */
1138 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1139 bool guardbuf_limit)
1141 struct memory_handle *h = find_handle(handle_id);
1142 if (!h)
1143 return NULL;
1145 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1147 if (avail == 0 && h->filerem == 0)
1149 /* File is finished reading */
1150 *size = 0;
1151 return h;
1154 if (*size == 0 || *size > avail + h->filerem)
1155 *size = avail + h->filerem;
1157 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1159 logf("data request > guardbuf");
1160 /* If more than the size of the guardbuf is requested and this is a
1161 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1162 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1163 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1166 if (h->filerem > 0 && avail < *size)
1168 /* Data isn't ready. Request buffering */
1169 buf_request_buffer_handle(handle_id);
1170 /* Wait for the data to be ready */
1173 sleep(1);
1174 /* it is not safe for a non-buffering thread to sleep while
1175 * holding a handle */
1176 h = find_handle(handle_id);
1177 if (!h)
1178 return NULL;
1179 avail = RINGBUF_SUB(h->widx, h->ridx);
1181 while (h->filerem > 0 && avail < *size);
1184 *size = MIN(*size,avail);
1185 return h;
1188 /* Copy data from the given handle to the dest buffer.
1189 Return the number of bytes copied or < 0 for failure (handle not found).
1190 The caller is blocked until the requested amount of data is available.
1192 ssize_t bufread(int handle_id, size_t size, void *dest)
1194 const struct memory_handle *h;
1195 size_t adjusted_size = size;
1197 h = prep_bufdata(handle_id, &adjusted_size, false);
1198 if (!h)
1199 return ERR_HANDLE_NOT_FOUND;
1201 if (h->ridx + adjusted_size > buffer_len)
1203 /* the data wraps around the end of the buffer */
1204 size_t read = buffer_len - h->ridx;
1205 memcpy(dest, &buffer[h->ridx], read);
1206 memcpy(dest+read, buffer, adjusted_size - read);
1208 else
1210 memcpy(dest, &buffer[h->ridx], adjusted_size);
1213 return adjusted_size;
1216 /* Update the "data" pointer to make the handle's data available to the caller.
1217 Return the length of the available linear data or < 0 for failure (handle
1218 not found).
1219 The caller is blocked until the requested amount of data is available.
1220 size is the amount of linear data requested. it can be 0 to get as
1221 much as possible.
1222 The guard buffer may be used to provide the requested size. This means it's
1223 unsafe to request more than the size of the guard buffer.
1225 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1227 const struct memory_handle *h;
1228 size_t adjusted_size = size;
1230 h = prep_bufdata(handle_id, &adjusted_size, true);
1231 if (!h)
1232 return ERR_HANDLE_NOT_FOUND;
1234 if (h->ridx + adjusted_size > buffer_len)
1236 /* the data wraps around the end of the buffer :
1237 use the guard buffer to provide the requested amount of data. */
1238 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1239 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1240 so copy_n <= GUARD_BUFSIZE */
1241 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1244 if (data)
1245 *data = &buffer[h->ridx];
1247 return adjusted_size;
1250 ssize_t bufgettail(int handle_id, size_t size, void **data)
1252 size_t tidx;
1254 const struct memory_handle *h;
1256 h = find_handle(handle_id);
1258 if (!h)
1259 return ERR_HANDLE_NOT_FOUND;
1261 if (h->filerem)
1262 return ERR_HANDLE_NOT_DONE;
1264 /* We don't support tail requests of > guardbuf_size, for simplicity */
1265 if (size > GUARD_BUFSIZE)
1266 return ERR_INVALID_VALUE;
1268 tidx = RINGBUF_SUB(h->widx, size);
1270 if (tidx + size > buffer_len)
1272 size_t copy_n = tidx + size - buffer_len;
1273 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1276 *data = &buffer[tidx];
1277 return size;
1280 ssize_t bufcuttail(int handle_id, size_t size)
1282 struct memory_handle *h;
1283 size_t adjusted_size = size;
1285 h = find_handle(handle_id);
1287 if (!h)
1288 return ERR_HANDLE_NOT_FOUND;
1290 if (h->filerem)
1291 return ERR_HANDLE_NOT_DONE;
1293 if (h->available < adjusted_size)
1294 adjusted_size = h->available;
1296 h->available -= adjusted_size;
1297 h->filesize -= adjusted_size;
1298 h->widx = RINGBUF_SUB(h->widx, adjusted_size);
1299 if (h == cur_handle)
1300 buf_widx = h->widx;
1302 return adjusted_size;
1307 SECONDARY EXPORTED FUNCTIONS
1308 ============================
1310 buf_get_offset
1311 buf_handle_offset
1312 buf_request_buffer_handle
1313 buf_set_base_handle
1314 buf_used
1315 register_buffering_callback
1316 unregister_buffering_callback
1318 These functions are exported, to allow interaction with the buffer.
1319 They take care of the content of the structs, and rely on the linked list
1320 management functions for all the actual handle management work.
1323 /* Get a handle offset from a pointer */
1324 ssize_t buf_get_offset(int handle_id, void *ptr)
1326 const struct memory_handle *h = find_handle(handle_id);
1327 if (!h)
1328 return ERR_HANDLE_NOT_FOUND;
1330 return (size_t)ptr - (size_t)&buffer[h->ridx];
1333 ssize_t buf_handle_offset(int handle_id)
1335 const struct memory_handle *h = find_handle(handle_id);
1336 if (!h)
1337 return ERR_HANDLE_NOT_FOUND;
1338 return h->offset;
1341 void buf_request_buffer_handle(int handle_id)
1343 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1344 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1347 void buf_set_base_handle(int handle_id)
1349 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1350 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1353 /* Return the amount of buffer space used */
1354 size_t buf_used(void)
1356 return BUF_USED;
1359 void buf_set_watermark(size_t bytes)
1361 conf_watermark = bytes;
1364 static void shrink_buffer_inner(struct memory_handle *h)
1366 if (h == NULL)
1367 return;
1369 shrink_buffer_inner(h->next);
1371 shrink_handle(h);
1374 static void shrink_buffer(void)
1376 logf("shrink_buffer()");
1377 shrink_buffer_inner(first_handle);
1380 void buffering_thread(void)
1382 bool filling = false;
1383 struct queue_event ev;
1385 while (true)
1387 if (!filling) {
1388 cancel_cpu_boost();
1391 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1393 switch (ev.id)
1395 case Q_START_FILL:
1396 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1397 /* Call buffer callbacks here because this is one of two ways
1398 * to begin a full buffer fill */
1399 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1400 shrink_buffer();
1401 queue_reply(&buffering_queue, 1);
1402 filling |= buffer_handle((int)ev.data);
1403 break;
1405 case Q_BUFFER_HANDLE:
1406 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1407 queue_reply(&buffering_queue, 1);
1408 buffer_handle((int)ev.data);
1409 break;
1411 case Q_RESET_HANDLE:
1412 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1413 queue_reply(&buffering_queue, 1);
1414 reset_handle((int)ev.data);
1415 break;
1417 case Q_CLOSE_HANDLE:
1418 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1419 queue_reply(&buffering_queue, close_handle((int)ev.data));
1420 break;
1422 case Q_HANDLE_ADDED:
1423 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1424 /* A handle was added: the disk is spinning, so we can fill */
1425 filling = true;
1426 break;
1428 case Q_BASE_HANDLE:
1429 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1430 base_handle_id = (int)ev.data;
1431 break;
1433 #ifndef SIMULATOR
1434 case SYS_USB_CONNECTED:
1435 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1436 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1437 usb_wait_for_disconnect(&buffering_queue);
1438 break;
1439 #endif
1441 case SYS_TIMEOUT:
1442 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1443 break;
1446 update_data_counters();
1448 /* If the buffer is low, call the callbacks to get new data */
1449 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1450 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1452 #if 0
1453 /* TODO: This needs to be fixed to use the idle callback, disable it
1454 * for simplicity until its done right */
1455 #if MEM > 8
1456 /* If the disk is spinning, take advantage by filling the buffer */
1457 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1459 if (num_handles > 0 && data_counters.useful <= high_watermark)
1460 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1462 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1464 /* This is a new fill, shrink the buffer up first */
1465 if (!filling)
1466 shrink_buffer();
1467 filling = fill_buffer();
1468 update_data_counters();
1471 #endif
1472 #endif
1474 if (queue_empty(&buffering_queue)) {
1475 if (filling) {
1476 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1477 filling = fill_buffer();
1478 else if (data_counters.remaining == 0)
1479 filling = false;
1481 else if (ev.id == SYS_TIMEOUT)
1483 if (data_counters.remaining > 0 &&
1484 data_counters.useful <= conf_watermark) {
1485 shrink_buffer();
1486 filling = fill_buffer();
1493 void buffering_init(void)
1495 mutex_init(&llist_mutex);
1496 mutex_init(&llist_mod_mutex);
1497 #ifdef HAVE_PRIORITY_SCHEDULING
1498 /* This behavior not safe atm */
1499 mutex_set_preempt(&llist_mutex, false);
1500 mutex_set_preempt(&llist_mod_mutex, false);
1501 #endif
1503 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1505 queue_init(&buffering_queue, true);
1506 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1507 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1508 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1509 IF_COP(, CPU));
1511 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1512 buffering_thread_id);
1515 /* Initialise the buffering subsystem */
1516 bool buffering_reset(char *buf, size_t buflen)
1518 if (!buf || !buflen)
1519 return false;
1521 buffer = buf;
1522 buffer_len = buflen;
1523 guard_buffer = buf + buflen;
1525 buf_widx = 0;
1526 buf_ridx = 0;
1528 first_handle = NULL;
1529 cur_handle = NULL;
1530 cached_handle = NULL;
1531 num_handles = 0;
1532 base_handle_id = -1;
1534 /* Set the high watermark as 75% full...or 25% empty :) */
1535 #if MEM > 8
1536 high_watermark = 3*buflen / 4;
1537 #endif
1539 thread_thaw(buffering_thread_id);
1541 return true;
1544 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1546 update_data_counters();
1547 dbgdata->num_handles = num_handles;
1548 dbgdata->data_rem = data_counters.remaining;
1549 dbgdata->wasted_space = data_counters.wasted;
1550 dbgdata->buffered_data = data_counters.buffered;
1551 dbgdata->useful_data = data_counters.useful;
1552 dbgdata->watermark = conf_watermark;