Convert RINGBUF_* macros to inline functions, saving binsize and improving type safety.
[kugel-rb.git] / apps / buffering.c
blobee375e9172c9f5ed7cb631d847b31cf34141011c
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 /* assert(sizeof(struct memory_handle)%4==0) */
95 struct memory_handle {
96 int id; /* A unique ID for the handle */
97 enum data_type type; /* Type of data buffered with this handle */
98 char path[MAX_PATH]; /* Path if data originated in a file */
99 int fd; /* File descriptor to path (-1 if closed) */
100 size_t start; /* Start index of the handle's data buffer,
101 for use by reset_handle. */
102 size_t data; /* Start index of the handle's data */
103 volatile size_t ridx; /* Read pointer, relative to the main buffer */
104 size_t widx; /* Write pointer */
105 size_t filesize; /* File total length */
106 size_t filerem; /* Remaining bytes of file NOT in buffer */
107 volatile size_t available; /* Available bytes to read from buffer */
108 size_t offset; /* Offset at which we started reading the file */
109 struct memory_handle *next;
111 /* invariant: filesize == offset + available + filerem */
113 static char *buffer;
114 static char *guard_buffer;
116 static size_t buffer_len;
118 static volatile size_t buf_widx; /* current writing position */
119 static volatile size_t buf_ridx; /* current reading position */
120 /* buf_*idx are values relative to the buffer, not real pointers. */
122 /* Configuration */
123 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
124 #if MEM > 8
125 static size_t high_watermark = 0; /* High watermark for rebuffer */
126 #endif
128 /* current memory handle in the linked list. NULL when the list is empty. */
129 static struct memory_handle *cur_handle;
130 /* first memory handle in the linked list. NULL when the list is empty. */
131 static struct memory_handle *first_handle;
133 static int num_handles; /* number of handles in the list */
135 static int base_handle_id;
137 static struct mutex llist_mutex;
138 static struct mutex llist_mod_mutex;
140 /* Handle cache (makes find_handle faster).
141 This is global so that move_handle and rm_handle can invalidate it. */
142 static struct memory_handle *cached_handle = NULL;
144 static struct {
145 size_t remaining; /* Amount of data needing to be buffered */
146 size_t wasted; /* Amount of space available for freeing */
147 size_t buffered; /* Amount of data currently in the buffer */
148 size_t useful; /* Amount of data still useful to the user */
149 } data_counters;
152 /* Messages available to communicate with the buffering thread */
153 enum {
154 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
155 used in a low buffer situation. */
156 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
157 offset (the offset has to be set beforehand) */
158 Q_CLOSE_HANDLE, /* Request closing a handle */
159 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
161 /* Configuration: */
162 Q_START_FILL, /* Request that the buffering thread initiate a buffer
163 fill at its earliest convenience */
164 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
165 (which means the disk is spinning) */
168 /* Buffering thread */
169 static void buffering_thread(void);
170 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
171 static const char buffering_thread_name[] = "buffering";
172 static unsigned int buffering_thread_id = 0;
173 static struct event_queue buffering_queue;
174 static struct queue_sender_list buffering_queue_sender_list;
178 /* Ring buffer helper functions */
179 /* Buffer pointer (p) plus value (v), wrapped if necessary */
180 static inline uintptr_t ringbuf_add(uintptr_t p, size_t v)
182 uintptr_t res = p + v;
183 if (res >= buffer_len)
184 res -= buffer_len; /* wrap if necssary */
185 return res;
189 /* Buffer pointer (p) minus value (v), wrapped if necessary */
190 static inline uintptr_t ringbuf_sub(uintptr_t p, size_t v)
192 uintptr_t res = p;
193 if (p < v)
194 res += buffer_len; /* wrap */
196 return res - v;
200 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
201 static inline ssize_t ringbuf_add_cross(uintptr_t p1, size_t v, uintptr_t p2)
203 ssize_t res = p1 + v - p2;
204 if (p1 >= p2) /* wrap if necessary */
205 res -= buffer_len;
207 return res;
210 /* Bytes available in the buffer */
211 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
214 LINKED LIST MANAGEMENT
215 ======================
217 add_handle : Add a handle to the list
218 rm_handle : Remove a handle from the list
219 find_handle : Get a handle pointer from an ID
220 move_handle : Move a handle in the buffer (with or without its data)
222 These functions only handle the linked list structure. They don't touch the
223 contents of the struct memory_handle headers. They also change the buf_*idx
224 pointers when necessary and manage the handle IDs.
226 The first and current (== last) handle are kept track of.
227 A new handle is added at buf_widx and becomes the current one.
228 buf_widx always points to the current writing position for the current handle
229 buf_ridx always points to the location of the first handle.
230 buf_ridx == buf_widx means the buffer is empty.
234 /* Add a new handle to the linked list and return it. It will have become the
235 new current handle.
236 data_size must contain the size of what will be in the handle.
237 can_wrap tells us whether this type of data may wrap on buffer
238 alloc_all tells us if we must immediately be able to allocate data_size
239 returns a valid memory handle if all conditions for allocation are met.
240 NULL if there memory_handle itself cannot be allocated or if the
241 data_size cannot be allocated and alloc_all is set. This function's
242 only potential side effect is to allocate space for the cur_handle
243 if it returns NULL.
245 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
246 bool alloc_all)
248 /* gives each handle a unique id */
249 static int cur_handle_id = 0;
250 size_t shift;
251 size_t new_widx;
252 size_t len;
253 int overlap;
255 if (num_handles >= BUF_MAX_HANDLES)
256 return NULL;
258 mutex_lock(&llist_mutex);
259 mutex_lock(&llist_mod_mutex);
261 if (cur_handle && cur_handle->filerem > 0) {
262 /* the current handle hasn't finished buffering. We can only add
263 a new one if there is already enough free space to finish
264 the buffering. */
265 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
266 if (ringbuf_add_cross(cur_handle->widx, req, buf_ridx) >= 0) {
267 /* Not enough space */
268 mutex_unlock(&llist_mod_mutex);
269 mutex_unlock(&llist_mutex);
270 return NULL;
271 } else {
272 /* Allocate the remainder of the space for the current handle */
273 buf_widx = ringbuf_add(cur_handle->widx, cur_handle->filerem);
277 /* align to 4 bytes up */
278 new_widx = ringbuf_add(buf_widx, 3) & ~3;
280 len = data_size + sizeof(struct memory_handle);
282 /* First, will the handle wrap? */
283 /* If the handle would wrap, move to the beginning of the buffer,
284 * or if the data must not but would wrap, move it to the beginning */
285 if( (new_widx + sizeof(struct memory_handle) > buffer_len) ||
286 (!can_wrap && (new_widx + len > buffer_len)) ) {
287 new_widx = 0;
290 /* How far we shifted buf_widx to align things, must be < buffer_len */
291 shift = ringbuf_sub(new_widx, buf_widx);
293 /* How much space are we short in the actual ring buffer? */
294 overlap = ringbuf_add_cross(buf_widx, shift + len, buf_ridx);
295 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
296 /* Not enough space for required allocations */
297 mutex_unlock(&llist_mod_mutex);
298 mutex_unlock(&llist_mutex);
299 return NULL;
302 /* There is enough space for the required data, advance the buf_widx and
303 * initialize the struct */
304 buf_widx = new_widx;
306 struct memory_handle *new_handle =
307 (struct memory_handle *)(&buffer[buf_widx]);
309 /* only advance the buffer write index of the size of the struct */
310 buf_widx = ringbuf_add(buf_widx, sizeof(struct memory_handle));
312 new_handle->id = cur_handle_id;
313 /* Wrap signed int is safe and 0 doesn't happen */
314 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
315 new_handle->next = NULL;
316 num_handles++;
318 if (!first_handle)
319 /* the new handle is the first one */
320 first_handle = new_handle;
322 if (cur_handle)
323 cur_handle->next = new_handle;
325 cur_handle = new_handle;
327 mutex_unlock(&llist_mod_mutex);
328 mutex_unlock(&llist_mutex);
329 return new_handle;
332 /* Delete a given memory handle from the linked list
333 and return true for success. Nothing is actually erased from memory. */
334 static bool rm_handle(const struct memory_handle *h)
336 if (h == NULL)
337 return true;
339 mutex_lock(&llist_mutex);
340 mutex_lock(&llist_mod_mutex);
342 if (h == first_handle) {
343 first_handle = h->next;
344 if (h == cur_handle) {
345 /* h was the first and last handle: the buffer is now empty */
346 cur_handle = NULL;
347 buf_ridx = buf_widx = 0;
348 } else {
349 /* update buf_ridx to point to the new first handle */
350 buf_ridx = (void *)first_handle - (void *)buffer;
352 } else {
353 struct memory_handle *m = first_handle;
354 /* Find the previous handle */
355 while (m && m->next != h) {
356 m = m->next;
358 if (m && m->next == h) {
359 m->next = h->next;
360 if (h == cur_handle) {
361 cur_handle = m;
362 buf_widx = cur_handle->widx;
364 } else {
365 mutex_unlock(&llist_mod_mutex);
366 mutex_unlock(&llist_mutex);
367 return false;
371 /* Invalidate the cache to prevent it from keeping the old location of h */
372 if (h == cached_handle)
373 cached_handle = NULL;
375 num_handles--;
377 mutex_unlock(&llist_mod_mutex);
378 mutex_unlock(&llist_mutex);
379 return true;
382 /* Return a pointer to the memory handle of given ID.
383 NULL if the handle wasn't found */
384 static struct memory_handle *find_handle(int handle_id)
386 if (handle_id < 0)
387 return NULL;
389 mutex_lock(&llist_mutex);
391 /* simple caching because most of the time the requested handle
392 will either be the same as the last, or the one after the last */
393 if (cached_handle)
395 if (cached_handle->id == handle_id) {
396 mutex_unlock(&llist_mutex);
397 return cached_handle;
398 } else if (cached_handle->next &&
399 (cached_handle->next->id == handle_id)) {
400 cached_handle = cached_handle->next;
401 mutex_unlock(&llist_mutex);
402 return cached_handle;
406 struct memory_handle *m = first_handle;
407 while (m && m->id != handle_id) {
408 m = m->next;
410 /* This condition can only be reached with !m or m->id == handle_id */
411 if (m)
412 cached_handle = m;
414 mutex_unlock(&llist_mutex);
415 return m;
418 /* Move a memory handle and data_size of its data delta bytes along the buffer.
419 delta maximum bytes available to move the handle. If the move is performed
420 it is set to the actual distance moved.
421 data_size is the amount of data to move along with the struct.
422 returns a valid memory_handle if the move is successful
423 NULL if the handle is NULL, the move would be less than the size of
424 a memory_handle after correcting for wraps or if the handle is not
425 found in the linked list for adjustment. This function has no side
426 effects if NULL is returned. */
427 static bool move_handle(struct memory_handle **h, size_t *delta,
428 size_t data_size, bool can_wrap)
430 struct memory_handle *dest;
431 const struct memory_handle *src;
432 int32_t *here;
433 int32_t *there;
434 int32_t *end;
435 int32_t *begin;
436 size_t oldpos;
437 size_t newpos;
438 size_t size_to_move;
439 size_t final_delta = *delta;
440 size_t n;
441 int overlap;
442 int overlap_old;
444 if (h == NULL || (src = *h) == NULL)
445 return false;
447 size_to_move = sizeof(struct memory_handle) + data_size;
449 /* Align to four bytes, down */
450 final_delta &= ~3;
451 if (final_delta < sizeof(struct memory_handle)) {
452 /* It's not legal to move less than the size of the struct */
453 return false;
456 mutex_lock(&llist_mutex);
457 mutex_lock(&llist_mod_mutex);
459 oldpos = (void *)src - (void *)buffer;
460 newpos = ringbuf_add(oldpos, final_delta);
461 overlap = ringbuf_add_cross(newpos, size_to_move, buffer_len - 1);
462 overlap_old = ringbuf_add_cross(oldpos, size_to_move, buffer_len -1);
464 if (overlap > 0) {
465 /* Some part of the struct + data would wrap, maybe ok */
466 size_t correction = 0;
467 /* If the overlap lands inside the memory_handle */
468 if (!can_wrap) {
469 /* Otherwise the overlap falls in the data area and must all be
470 * backed out. This may become conditional if ever we move
471 * data that is allowed to wrap (ie audio) */
472 correction = overlap;
473 } else if ((unsigned)overlap > data_size) {
474 /* Correct the position and real delta to prevent the struct from
475 * wrapping, this guarantees an aligned delta, I think */
476 correction = overlap - data_size;
478 if (correction) {
479 /* Align correction to four bytes up */
480 correction = (correction + 3) & ~3;
481 if (final_delta < correction + sizeof(struct memory_handle)) {
482 /* Delta cannot end up less than the size of the struct */
483 mutex_unlock(&llist_mod_mutex);
484 mutex_unlock(&llist_mutex);
485 return false;
487 newpos -= correction;
488 overlap -= correction;/* Used below to know how to split the data */
489 final_delta -= correction;
493 dest = (struct memory_handle *)(&buffer[newpos]);
495 if (src == first_handle) {
496 first_handle = dest;
497 buf_ridx = newpos;
498 } else {
499 struct memory_handle *m = first_handle;
500 while (m && m->next != src) {
501 m = m->next;
503 if (m && m->next == src) {
504 m->next = dest;
505 } else {
506 mutex_unlock(&llist_mod_mutex);
507 mutex_unlock(&llist_mutex);
508 return false;
513 /* Update the cache to prevent it from keeping the old location of h */
514 if (src == cached_handle)
515 cached_handle = dest;
517 /* the cur_handle pointer might need updating */
518 if (src == cur_handle)
519 cur_handle = dest;
522 /* Copying routine takes into account that the handles have a
523 * distance between each other which is a multiple of four. Faster 2 word
524 * copy may be ok but do this for safety and because wrapped copies should
525 * be fairly uncommon */
527 here = (int32_t *)((ringbuf_add(oldpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
528 there =(int32_t *)((ringbuf_add(newpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
529 end = (int32_t *)(( intptr_t)buffer + buffer_len - 4);
530 begin =(int32_t *)buffer;
532 n = (size_to_move & ~3)/4;
534 if ( overlap_old > 0 || overlap > 0 ) {
535 /* Old or moved handle wraps */
536 while (n--) {
537 if (here < begin)
538 here = end;
539 if (there < begin)
540 there = end;
541 *there-- = *here--;
543 } else {
544 /* both handles do not wrap */
545 memmove(dest,src,size_to_move);
549 /* Update the caller with the new location of h and the distance moved */
550 *h = dest;
551 *delta = final_delta;
552 mutex_unlock(&llist_mod_mutex);
553 mutex_unlock(&llist_mutex);
554 return dest;
559 BUFFER SPACE MANAGEMENT
560 =======================
562 update_data_counters: Updates the values in data_counters
563 buffer_is_low : Returns true if the amount of useful data in the buffer is low
564 buffer_handle : Buffer data for a handle
565 reset_handle : Reset write position and data buffer of a handle to its offset
566 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
567 shrink_handle : Free buffer space by moving a handle
568 fill_buffer : Call buffer_handle for all handles that have data to buffer
570 These functions are used by the buffering thread to manage buffer space.
573 static void update_data_counters(void)
575 struct memory_handle *m = find_handle(base_handle_id);
576 bool is_useful = m==NULL;
578 size_t buffered = 0;
579 size_t wasted = 0;
580 size_t remaining = 0;
581 size_t useful = 0;
583 mutex_lock(&llist_mutex);
585 m = first_handle;
586 while (m) {
587 buffered += m->available;
588 wasted += ringbuf_sub(m->ridx, m->data);
589 remaining += m->filerem;
591 if (m->id == base_handle_id)
592 is_useful = true;
594 if (is_useful)
595 useful += ringbuf_sub(m->widx, m->ridx);
597 m = m->next;
600 mutex_unlock(&llist_mutex);
602 data_counters.buffered = buffered;
603 data_counters.wasted = wasted;
604 data_counters.remaining = remaining;
605 data_counters.useful = useful;
608 static inline bool buffer_is_low(void)
610 update_data_counters();
611 return data_counters.useful < (conf_watermark / 2);
614 /* Buffer data for the given handle.
615 Return whether or not the buffering should continue explicitly. */
616 static bool buffer_handle(int handle_id)
618 logf("buffer_handle(%d)", handle_id);
619 struct memory_handle *h = find_handle(handle_id);
620 if (!h)
621 return true;
623 if (h->filerem == 0) {
624 /* nothing left to buffer */
625 return true;
628 if (h->fd < 0) /* file closed, reopen */
630 if (*h->path)
631 h->fd = open(h->path, O_RDONLY);
633 if (h->fd < 0)
635 /* could not open the file, truncate it where it is */
636 h->filesize -= h->filerem;
637 h->filerem = 0;
638 return true;
641 if (h->offset)
642 lseek(h->fd, h->offset, SEEK_SET);
645 trigger_cpu_boost();
647 if (h->type == TYPE_ID3)
649 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
651 /* metadata parsing failed: clear the buffer. */
652 memset(buffer + h->data, 0, sizeof(struct mp3entry));
654 close(h->fd);
655 h->fd = -1;
656 h->filerem = 0;
657 h->available = sizeof(struct mp3entry);
658 h->widx += sizeof(struct mp3entry);
659 send_event(BUFFER_EVENT_FINISHED, &h->id);
660 return true;
663 while (h->filerem > 0)
665 /* max amount to copy */
666 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
667 buffer_len - h->widx);
669 /* stop copying if it would overwrite the reading position */
670 if (ringbuf_add_cross(h->widx, copy_n, buf_ridx) >= 0)
671 return false;
673 /* This would read into the next handle, this is broken
674 if (h->next && ringbuf_add_cross(h->widx, copy_n,
675 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
676 Try to recover by truncating this file
677 copy_n = ringbuf_add_cross(h->widx, copy_n,
678 (unsigned)((void *)h->next - (void *)buffer));
679 h->filerem -= copy_n;
680 h->filesize -= copy_n;
681 logf("buf alloc short %ld", (long)copy_n);
682 if (h->filerem)
683 continue;
684 else
685 break;
686 } */
688 /* rc is the actual amount read */
689 int rc = read(h->fd, &buffer[h->widx], copy_n);
691 if (rc < 0)
693 /* Some kind of filesystem error, maybe recoverable if not codec */
694 if (h->type == TYPE_CODEC) {
695 logf("Partial codec");
696 break;
699 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
700 h->filesize -= h->filerem;
701 h->filerem = 0;
702 break;
705 /* Advance buffer */
706 h->widx = ringbuf_add(h->widx, rc);
707 if (h == cur_handle)
708 buf_widx = h->widx;
709 h->available += rc;
710 h->filerem -= rc;
712 /* If this is a large file, see if we need to break or give the codec
713 * more time */
714 if (h->type == TYPE_PACKET_AUDIO &&
715 pcmbuf_is_lowdata() && !buffer_is_low())
717 sleep(1);
719 else
721 yield();
724 if (!queue_empty(&buffering_queue))
725 break;
728 if (h->filerem == 0) {
729 /* finished buffering the file */
730 close(h->fd);
731 h->fd = -1;
732 send_event(BUFFER_EVENT_FINISHED, &h->id);
735 return true;
738 /* Reset writing position and data buffer of a handle to its current offset.
739 Use this after having set the new offset to use. */
740 static void reset_handle(int handle_id)
742 size_t alignment_pad;
744 logf("reset_handle(%d)", handle_id);
746 struct memory_handle *h = find_handle(handle_id);
747 if (!h)
748 return;
750 /* Align to desired storage alignment */
751 alignment_pad = (h->offset - (size_t)(&buffer[h->start]))
752 & STORAGE_ALIGN_MASK;
753 h->ridx = h->widx = h->data = ringbuf_add(h->start, alignment_pad);
755 if (h == cur_handle)
756 buf_widx = h->widx;
757 h->available = 0;
758 h->filerem = h->filesize - h->offset;
760 if (h->fd >= 0) {
761 lseek(h->fd, h->offset, SEEK_SET);
765 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
766 static void rebuffer_handle(int handle_id, size_t newpos)
768 struct memory_handle *h = find_handle(handle_id);
769 if (!h)
770 return;
772 /* When seeking foward off of the buffer, if it is a short seek don't
773 rebuffer the whole track, just read enough to satisfy */
774 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
776 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
777 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
778 h->ridx = h->data + newpos;
779 return;
782 h->offset = newpos;
784 /* Reset the handle to its new offset */
785 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
786 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
788 size_t next = (unsigned)((void *)h->next - (void *)buffer);
789 if (ringbuf_sub(next, h->data) < h->filesize - newpos)
791 /* There isn't enough space to rebuffer all of the track from its new
792 offset, so we ask the user to free some */
793 DEBUGF("rebuffer_handle: space is needed\n");
794 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
797 /* Now we ask for a rebuffer */
798 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
799 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
802 static bool close_handle(int handle_id)
804 struct memory_handle *h = find_handle(handle_id);
806 /* If the handle is not found, it is closed */
807 if (!h)
808 return true;
810 if (h->fd >= 0) {
811 close(h->fd);
812 h->fd = -1;
815 /* rm_handle returns true unless the handle somehow persists after exit */
816 return rm_handle(h);
819 /* Free buffer space by moving the handle struct right before the useful
820 part of its data buffer or by moving all the data. */
821 static void shrink_handle(struct memory_handle *h)
823 size_t delta;
825 if (!h)
826 return;
828 if (h->next && h->filerem == 0 &&
829 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
830 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
831 h->type == TYPE_ATOMIC_AUDIO))
833 /* metadata handle: we can move all of it */
834 size_t handle_distance =
835 ringbuf_sub((unsigned)((void *)h->next - (void*)buffer), h->data);
836 delta = handle_distance - h->available;
838 /* The value of delta might change for alignment reasons */
839 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
840 return;
842 size_t olddata = h->data;
843 h->data = ringbuf_add(h->data, delta);
844 h->ridx = ringbuf_add(h->ridx, delta);
845 h->widx = ringbuf_add(h->widx, delta);
847 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
848 /* when moving an mp3entry we need to readjust its pointers. */
849 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
850 (void *)&buffer[h->data],
851 (const void *)&buffer[olddata]);
852 } else if (h->type == TYPE_BITMAP) {
853 /* adjust the bitmap's pointer */
854 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
855 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
858 else
860 /* only move the handle struct */
861 delta = ringbuf_sub(h->ridx, h->data);
862 if (!move_handle(&h, &delta, 0, true))
863 return;
865 h->data = ringbuf_add(h->data, delta);
866 h->start = ringbuf_add(h->start, delta);
867 h->available -= delta;
868 h->offset += delta;
872 /* Fill the buffer by buffering as much data as possible for handles that still
873 have data left to buffer
874 Return whether or not to continue filling after this */
875 static bool fill_buffer(void)
877 logf("fill_buffer()");
878 struct memory_handle *m;
879 shrink_handle(first_handle);
880 m = first_handle;
881 while (queue_empty(&buffering_queue) && m) {
882 if (m->filerem > 0) {
883 if (!buffer_handle(m->id)) {
884 m = NULL;
885 break;
888 m = m->next;
891 if (m) {
892 return true;
894 else
896 /* only spin the disk down if the filling wasn't interrupted by an
897 event arriving in the queue. */
898 storage_sleep();
899 return false;
903 #ifdef HAVE_ALBUMART
904 /* Given a file descriptor to a bitmap file, write the bitmap data to the
905 buffer, with a struct bitmap and the actual data immediately following.
906 Return value is the total size (struct + data). */
907 static int load_image(int fd, const char *path, struct dim *dim)
909 int rc;
910 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
912 /* get the desired image size */
913 bmp->width = dim->width, bmp->height = dim->height;
914 /* FIXME: alignment may be needed for the data buffer. */
915 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
916 #ifndef HAVE_JPEG
917 (void) path;
918 #endif
919 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
920 bmp->maskdata = NULL;
921 #endif
923 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
924 - sizeof(struct bitmap);
926 #ifdef HAVE_JPEG
927 int pathlen = strlen(path);
928 if (strcmp(path + pathlen - 4, ".bmp"))
929 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
930 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
931 else
932 #endif
933 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
934 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
935 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
937 #endif
941 MAIN BUFFERING API CALLS
942 ========================
944 bufopen : Request the opening of a new handle for a file
945 bufalloc : Open a new handle for data other than a file.
946 bufclose : Close an open handle
947 bufseek : Set the read pointer in a handle
948 bufadvance : Move the read pointer in a handle
949 bufread : Copy data from a handle into a given buffer
950 bufgetdata : Give a pointer to the handle's data
952 These functions are exported, to allow interaction with the buffer.
953 They take care of the content of the structs, and rely on the linked list
954 management functions for all the actual handle management work.
958 /* Reserve space in the buffer for a file.
959 filename: name of the file to open
960 offset: offset at which to start buffering the file, useful when the first
961 (offset-1) bytes of the file aren't needed.
962 type: one of the data types supported (audio, image, cuesheet, others
963 user_data: user data passed possibly passed in subcalls specific to a
964 data_type (only used for image (albumart) buffering so far )
965 return value: <0 if the file cannot be opened, or one file already
966 queued to be opened, otherwise the handle for the file in the buffer
968 int bufopen(const char *file, size_t offset, enum data_type type,
969 void *user_data)
971 #ifndef HAVE_ALBUMART
972 /* currently only used for aa loading */
973 (void)user_data;
974 #endif
975 if (type == TYPE_ID3)
977 /* ID3 case: allocate space, init the handle and return. */
979 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
980 if (!h)
981 return ERR_BUFFER_FULL;
983 h->fd = -1;
984 h->filesize = sizeof(struct mp3entry);
985 h->filerem = sizeof(struct mp3entry);
986 h->offset = 0;
987 h->data = buf_widx;
988 h->ridx = buf_widx;
989 h->widx = buf_widx;
990 h->available = 0;
991 h->type = type;
992 strlcpy(h->path, file, MAX_PATH);
994 buf_widx += sizeof(struct mp3entry); /* safe because the handle
995 can't wrap */
997 /* Inform the buffering thread that we added a handle */
998 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
999 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1001 return h->id;
1004 /* Other cases: there is a little more work. */
1006 int fd = open(file, O_RDONLY);
1007 if (fd < 0)
1008 return ERR_FILE_ERROR;
1010 size_t size = filesize(fd);
1011 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
1013 size_t adjusted_offset = offset;
1014 if (adjusted_offset > size)
1015 adjusted_offset = 0;
1017 /* Reserve extra space because alignment can move data forward */
1018 struct memory_handle *h = add_handle(size-adjusted_offset+STORAGE_ALIGN_MASK,
1019 can_wrap, false);
1020 if (!h)
1022 DEBUGF("bufopen: failed to add handle\n");
1023 close(fd);
1024 return ERR_BUFFER_FULL;
1027 strlcpy(h->path, file, MAX_PATH);
1028 h->offset = adjusted_offset;
1030 /* Don't bother to storage align bitmaps because they are not
1031 * loaded directly into the buffer.
1033 if (type != TYPE_BITMAP)
1035 size_t alignment_pad;
1037 /* Remember where data area starts, for use by reset_handle */
1038 h->start = buf_widx;
1040 /* Align to desired storage alignment */
1041 alignment_pad = (adjusted_offset - (size_t)(&buffer[buf_widx]))
1042 & STORAGE_ALIGN_MASK;
1043 buf_widx = ringbuf_add(buf_widx, alignment_pad);
1046 h->ridx = buf_widx;
1047 h->widx = buf_widx;
1048 h->data = buf_widx;
1049 h->available = 0;
1050 h->filerem = 0;
1051 h->type = type;
1053 #ifdef HAVE_ALBUMART
1054 if (type == TYPE_BITMAP)
1056 /* Bitmap file: we load the data instead of the file */
1057 int rc;
1058 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1059 rc = load_image(fd, file, (struct dim*)user_data);
1060 mutex_unlock(&llist_mod_mutex);
1061 if (rc <= 0)
1063 rm_handle(h);
1064 close(fd);
1065 return ERR_FILE_ERROR;
1067 h->filerem = 0;
1068 h->filesize = rc;
1069 h->available = rc;
1070 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1071 buf_widx += rc; /* safe too */
1073 else
1074 #endif
1076 h->filerem = size - adjusted_offset;
1077 h->filesize = size;
1078 h->available = 0;
1079 h->widx = buf_widx;
1082 if (type == TYPE_CUESHEET) {
1083 h->fd = fd;
1084 /* Immediately start buffering those */
1085 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1086 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1087 } else {
1088 /* Other types will get buffered in the course of normal operations */
1089 h->fd = -1;
1090 close(fd);
1092 /* Inform the buffering thread that we added a handle */
1093 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1094 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1097 logf("bufopen: new hdl %d", h->id);
1098 return h->id;
1101 /* Open a new handle from data that needs to be copied from memory.
1102 src is the source buffer from which to copy data. It can be NULL to simply
1103 reserve buffer space.
1104 size is the requested size. The call will only be successful if the
1105 requested amount of data can entirely fit in the buffer without wrapping.
1106 Return value is the handle id for success or <0 for failure.
1108 int bufalloc(const void *src, size_t size, enum data_type type)
1110 struct memory_handle *h = add_handle(size, false, true);
1112 if (!h)
1113 return ERR_BUFFER_FULL;
1115 if (src) {
1116 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1117 /* specially take care of struct mp3entry */
1118 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1119 (const struct mp3entry *)src);
1120 } else {
1121 memcpy(&buffer[buf_widx], src, size);
1125 h->fd = -1;
1126 *h->path = 0;
1127 h->filesize = size;
1128 h->filerem = 0;
1129 h->offset = 0;
1130 h->ridx = buf_widx;
1131 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1132 h->data = buf_widx;
1133 h->available = size;
1134 h->type = type;
1136 buf_widx += size; /* safe too */
1138 logf("bufalloc: new hdl %d", h->id);
1139 return h->id;
1142 /* Close the handle. Return true for success and false for failure */
1143 bool bufclose(int handle_id)
1145 logf("bufclose(%d)", handle_id);
1147 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1148 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1151 /* Set reading index in handle (relatively to the start of the file).
1152 Access before the available data will trigger a rebuffer.
1153 Return 0 for success and < 0 for failure:
1154 -1 if the handle wasn't found
1155 -2 if the new requested position was beyond the end of the file
1157 int bufseek(int handle_id, size_t newpos)
1159 struct memory_handle *h = find_handle(handle_id);
1160 if (!h)
1161 return ERR_HANDLE_NOT_FOUND;
1163 if (newpos > h->filesize) {
1164 /* access beyond the end of the file */
1165 return ERR_INVALID_VALUE;
1167 else if (newpos < h->offset || h->offset + h->available < newpos) {
1168 /* access before or after buffered data. A rebuffer is needed. */
1169 rebuffer_handle(handle_id, newpos);
1171 else {
1172 h->ridx = ringbuf_add(h->data, newpos - h->offset);
1174 return 0;
1177 /* Advance the reading index in a handle (relatively to its current position).
1178 Return 0 for success and < 0 for failure */
1179 int bufadvance(int handle_id, off_t offset)
1181 const struct memory_handle *h = find_handle(handle_id);
1182 if (!h)
1183 return ERR_HANDLE_NOT_FOUND;
1185 size_t newpos = h->offset + ringbuf_sub(h->ridx, h->data) + offset;
1186 return bufseek(handle_id, newpos);
1189 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1190 * actual amount of data available for reading. This function explicitly
1191 * does not check the validity of the input handle. It does do range checks
1192 * on size and returns a valid (and explicit) amount of data for reading */
1193 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1194 bool guardbuf_limit)
1196 struct memory_handle *h = find_handle(handle_id);
1197 if (!h)
1198 return NULL;
1200 size_t avail = ringbuf_sub(h->widx, h->ridx);
1202 if (avail == 0 && h->filerem == 0)
1204 /* File is finished reading */
1205 *size = 0;
1206 return h;
1209 if (*size == 0 || *size > avail + h->filerem)
1210 *size = avail + h->filerem;
1212 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1214 logf("data request > guardbuf");
1215 /* If more than the size of the guardbuf is requested and this is a
1216 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1217 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1218 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1221 if (h->filerem > 0 && avail < *size)
1223 /* Data isn't ready. Request buffering */
1224 buf_request_buffer_handle(handle_id);
1225 /* Wait for the data to be ready */
1228 sleep(1);
1229 /* it is not safe for a non-buffering thread to sleep while
1230 * holding a handle */
1231 h = find_handle(handle_id);
1232 if (!h)
1233 return NULL;
1234 avail = ringbuf_sub(h->widx, h->ridx);
1236 while (h->filerem > 0 && avail < *size);
1239 *size = MIN(*size,avail);
1240 return h;
1243 /* Copy data from the given handle to the dest buffer.
1244 Return the number of bytes copied or < 0 for failure (handle not found).
1245 The caller is blocked until the requested amount of data is available.
1247 ssize_t bufread(int handle_id, size_t size, void *dest)
1249 const struct memory_handle *h;
1250 size_t adjusted_size = size;
1252 h = prep_bufdata(handle_id, &adjusted_size, false);
1253 if (!h)
1254 return ERR_HANDLE_NOT_FOUND;
1256 if (h->ridx + adjusted_size > buffer_len)
1258 /* the data wraps around the end of the buffer */
1259 size_t read = buffer_len - h->ridx;
1260 memcpy(dest, &buffer[h->ridx], read);
1261 memcpy(dest+read, buffer, adjusted_size - read);
1263 else
1265 memcpy(dest, &buffer[h->ridx], adjusted_size);
1268 return adjusted_size;
1271 /* Update the "data" pointer to make the handle's data available to the caller.
1272 Return the length of the available linear data or < 0 for failure (handle
1273 not found).
1274 The caller is blocked until the requested amount of data is available.
1275 size is the amount of linear data requested. it can be 0 to get as
1276 much as possible.
1277 The guard buffer may be used to provide the requested size. This means it's
1278 unsafe to request more than the size of the guard buffer.
1280 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1282 const struct memory_handle *h;
1283 size_t adjusted_size = size;
1285 h = prep_bufdata(handle_id, &adjusted_size, true);
1286 if (!h)
1287 return ERR_HANDLE_NOT_FOUND;
1289 if (h->ridx + adjusted_size > buffer_len)
1291 /* the data wraps around the end of the buffer :
1292 use the guard buffer to provide the requested amount of data. */
1293 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1294 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1295 so copy_n <= GUARD_BUFSIZE */
1296 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1299 if (data)
1300 *data = &buffer[h->ridx];
1302 return adjusted_size;
1305 ssize_t bufgettail(int handle_id, size_t size, void **data)
1307 size_t tidx;
1309 const struct memory_handle *h;
1311 h = find_handle(handle_id);
1313 if (!h)
1314 return ERR_HANDLE_NOT_FOUND;
1316 if (h->filerem)
1317 return ERR_HANDLE_NOT_DONE;
1319 /* We don't support tail requests of > guardbuf_size, for simplicity */
1320 if (size > GUARD_BUFSIZE)
1321 return ERR_INVALID_VALUE;
1323 tidx = ringbuf_sub(h->widx, size);
1325 if (tidx + size > buffer_len)
1327 size_t copy_n = tidx + size - buffer_len;
1328 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1331 *data = &buffer[tidx];
1332 return size;
1335 ssize_t bufcuttail(int handle_id, size_t size)
1337 struct memory_handle *h;
1338 size_t adjusted_size = size;
1340 h = find_handle(handle_id);
1342 if (!h)
1343 return ERR_HANDLE_NOT_FOUND;
1345 if (h->filerem)
1346 return ERR_HANDLE_NOT_DONE;
1348 if (h->available < adjusted_size)
1349 adjusted_size = h->available;
1351 h->available -= adjusted_size;
1352 h->filesize -= adjusted_size;
1353 h->widx = ringbuf_sub(h->widx, adjusted_size);
1354 if (h == cur_handle)
1355 buf_widx = h->widx;
1357 return adjusted_size;
1362 SECONDARY EXPORTED FUNCTIONS
1363 ============================
1365 buf_get_offset
1366 buf_handle_offset
1367 buf_request_buffer_handle
1368 buf_set_base_handle
1369 buf_used
1370 register_buffering_callback
1371 unregister_buffering_callback
1373 These functions are exported, to allow interaction with the buffer.
1374 They take care of the content of the structs, and rely on the linked list
1375 management functions for all the actual handle management work.
1378 /* Get a handle offset from a pointer */
1379 ssize_t buf_get_offset(int handle_id, void *ptr)
1381 const struct memory_handle *h = find_handle(handle_id);
1382 if (!h)
1383 return ERR_HANDLE_NOT_FOUND;
1385 return (size_t)ptr - (size_t)&buffer[h->ridx];
1388 ssize_t buf_handle_offset(int handle_id)
1390 const struct memory_handle *h = find_handle(handle_id);
1391 if (!h)
1392 return ERR_HANDLE_NOT_FOUND;
1393 return h->offset;
1396 void buf_request_buffer_handle(int handle_id)
1398 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1399 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1402 void buf_set_base_handle(int handle_id)
1404 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1405 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1408 /* Return the amount of buffer space used */
1409 size_t buf_used(void)
1411 return BUF_USED;
1414 void buf_set_watermark(size_t bytes)
1416 conf_watermark = bytes;
1419 static void shrink_buffer_inner(struct memory_handle *h)
1421 if (h == NULL)
1422 return;
1424 shrink_buffer_inner(h->next);
1426 shrink_handle(h);
1429 static void shrink_buffer(void)
1431 logf("shrink_buffer()");
1432 shrink_buffer_inner(first_handle);
1435 void buffering_thread(void)
1437 bool filling = false;
1438 struct queue_event ev;
1440 while (true)
1442 if (!filling) {
1443 cancel_cpu_boost();
1446 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1448 switch (ev.id)
1450 case Q_START_FILL:
1451 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1452 /* Call buffer callbacks here because this is one of two ways
1453 * to begin a full buffer fill */
1454 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1455 shrink_buffer();
1456 queue_reply(&buffering_queue, 1);
1457 filling |= buffer_handle((int)ev.data);
1458 break;
1460 case Q_BUFFER_HANDLE:
1461 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1462 queue_reply(&buffering_queue, 1);
1463 buffer_handle((int)ev.data);
1464 break;
1466 case Q_RESET_HANDLE:
1467 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1468 queue_reply(&buffering_queue, 1);
1469 reset_handle((int)ev.data);
1470 break;
1472 case Q_CLOSE_HANDLE:
1473 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1474 queue_reply(&buffering_queue, close_handle((int)ev.data));
1475 break;
1477 case Q_HANDLE_ADDED:
1478 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1479 /* A handle was added: the disk is spinning, so we can fill */
1480 filling = true;
1481 break;
1483 case Q_BASE_HANDLE:
1484 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1485 base_handle_id = (int)ev.data;
1486 break;
1488 #ifndef SIMULATOR
1489 case SYS_USB_CONNECTED:
1490 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1491 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1492 usb_wait_for_disconnect(&buffering_queue);
1493 break;
1494 #endif
1496 case SYS_TIMEOUT:
1497 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1498 break;
1501 update_data_counters();
1503 /* If the buffer is low, call the callbacks to get new data */
1504 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1505 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1507 #if 0
1508 /* TODO: This needs to be fixed to use the idle callback, disable it
1509 * for simplicity until its done right */
1510 #if MEM > 8
1511 /* If the disk is spinning, take advantage by filling the buffer */
1512 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1514 if (num_handles > 0 && data_counters.useful <= high_watermark)
1515 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1517 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1519 /* This is a new fill, shrink the buffer up first */
1520 if (!filling)
1521 shrink_buffer();
1522 filling = fill_buffer();
1523 update_data_counters();
1526 #endif
1527 #endif
1529 if (queue_empty(&buffering_queue)) {
1530 if (filling) {
1531 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1532 filling = fill_buffer();
1533 else if (data_counters.remaining == 0)
1534 filling = false;
1536 else if (ev.id == SYS_TIMEOUT)
1538 if (data_counters.remaining > 0 &&
1539 data_counters.useful <= conf_watermark) {
1540 shrink_buffer();
1541 filling = fill_buffer();
1548 void buffering_init(void)
1550 mutex_init(&llist_mutex);
1551 mutex_init(&llist_mod_mutex);
1552 #ifdef HAVE_PRIORITY_SCHEDULING
1553 /* This behavior not safe atm */
1554 mutex_set_preempt(&llist_mutex, false);
1555 mutex_set_preempt(&llist_mod_mutex, false);
1556 #endif
1558 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1560 queue_init(&buffering_queue, true);
1561 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1562 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1563 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1564 IF_COP(, CPU));
1566 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1567 buffering_thread_id);
1570 /* Initialise the buffering subsystem */
1571 bool buffering_reset(char *buf, size_t buflen)
1573 if (!buf || !buflen)
1574 return false;
1576 buffer = buf;
1577 /* Preserve alignment when wrapping around */
1578 buffer_len = buflen & ~STORAGE_ALIGN_MASK;
1579 guard_buffer = buf + buflen;
1581 buf_widx = 0;
1582 buf_ridx = 0;
1584 first_handle = NULL;
1585 cur_handle = NULL;
1586 cached_handle = NULL;
1587 num_handles = 0;
1588 base_handle_id = -1;
1590 /* Set the high watermark as 75% full...or 25% empty :) */
1591 #if MEM > 8
1592 high_watermark = 3*buflen / 4;
1593 #endif
1595 thread_thaw(buffering_thread_id);
1597 return true;
1600 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1602 update_data_counters();
1603 dbgdata->num_handles = num_handles;
1604 dbgdata->data_rem = data_counters.remaining;
1605 dbgdata->wasted_space = data_counters.wasted;
1606 dbgdata->buffered_data = data_counters.buffered;
1607 dbgdata->useful_data = data_counters.useful;
1608 dbgdata->watermark = conf_watermark;