s5l870x : use mmu-arm.S
[kugel-rb.git] / apps / buffering.c
blobafc7c7ad6b8a1de4ea4104f6a8caa4892b75ed92
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 */
180 static inline uintptr_t ringbuf_offset(const void *ptr)
182 return (uintptr_t)(ptr - (void*)buffer);
185 /* Buffer pointer (p) plus value (v), wrapped if necessary */
186 static inline uintptr_t ringbuf_add(uintptr_t p, size_t v)
188 uintptr_t res = p + v;
189 if (res >= buffer_len)
190 res -= buffer_len; /* wrap if necssary */
191 return res;
195 /* Buffer pointer (p) minus value (v), wrapped if necessary */
196 static inline uintptr_t ringbuf_sub(uintptr_t p, size_t v)
198 uintptr_t res = p;
199 if (p < v)
200 res += buffer_len; /* wrap */
202 return res - v;
206 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
207 static inline ssize_t ringbuf_add_cross(uintptr_t p1, size_t v, uintptr_t p2)
209 ssize_t res = p1 + v - p2;
210 if (p1 >= p2) /* wrap if necessary */
211 res -= buffer_len;
213 return res;
216 /* Bytes available in the buffer */
217 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
220 LINKED LIST MANAGEMENT
221 ======================
223 add_handle : Add a handle to the list
224 rm_handle : Remove a handle from the list
225 find_handle : Get a handle pointer from an ID
226 move_handle : Move a handle in the buffer (with or without its data)
228 These functions only handle the linked list structure. They don't touch the
229 contents of the struct memory_handle headers. They also change the buf_*idx
230 pointers when necessary and manage the handle IDs.
232 The first and current (== last) handle are kept track of.
233 A new handle is added at buf_widx and becomes the current one.
234 buf_widx always points to the current writing position for the current handle
235 buf_ridx always points to the location of the first handle.
236 buf_ridx == buf_widx means the buffer is empty.
240 /* Add a new handle to the linked list and return it. It will have become the
241 new current handle.
242 data_size must contain the size of what will be in the handle.
243 can_wrap tells us whether this type of data may wrap on buffer
244 alloc_all tells us if we must immediately be able to allocate data_size
245 returns a valid memory handle if all conditions for allocation are met.
246 NULL if there memory_handle itself cannot be allocated or if the
247 data_size cannot be allocated and alloc_all is set. This function's
248 only potential side effect is to allocate space for the cur_handle
249 if it returns NULL.
251 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
252 bool alloc_all)
254 /* gives each handle a unique id */
255 static int cur_handle_id = 0;
256 size_t shift;
257 size_t new_widx;
258 size_t len;
259 int overlap;
261 if (num_handles >= BUF_MAX_HANDLES)
262 return NULL;
264 mutex_lock(&llist_mutex);
265 mutex_lock(&llist_mod_mutex);
267 if (cur_handle && cur_handle->filerem > 0) {
268 /* the current handle hasn't finished buffering. We can only add
269 a new one if there is already enough free space to finish
270 the buffering. */
271 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
272 if (ringbuf_add_cross(cur_handle->widx, req, buf_ridx) >= 0) {
273 /* Not enough space */
274 mutex_unlock(&llist_mod_mutex);
275 mutex_unlock(&llist_mutex);
276 return NULL;
277 } else {
278 /* Allocate the remainder of the space for the current handle */
279 buf_widx = ringbuf_add(cur_handle->widx, cur_handle->filerem);
283 /* align to 4 bytes up */
284 new_widx = ringbuf_add(buf_widx, 3) & ~3;
286 len = data_size + sizeof(struct memory_handle);
288 /* First, will the handle wrap? */
289 /* If the handle would wrap, move to the beginning of the buffer,
290 * or if the data must not but would wrap, move it to the beginning */
291 if( (new_widx + sizeof(struct memory_handle) > buffer_len) ||
292 (!can_wrap && (new_widx + len > buffer_len)) ) {
293 new_widx = 0;
296 /* How far we shifted buf_widx to align things, must be < buffer_len */
297 shift = ringbuf_sub(new_widx, buf_widx);
299 /* How much space are we short in the actual ring buffer? */
300 overlap = ringbuf_add_cross(buf_widx, shift + len, buf_ridx);
301 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
302 /* Not enough space for required allocations */
303 mutex_unlock(&llist_mod_mutex);
304 mutex_unlock(&llist_mutex);
305 return NULL;
308 /* There is enough space for the required data, advance the buf_widx and
309 * initialize the struct */
310 buf_widx = new_widx;
312 struct memory_handle *new_handle =
313 (struct memory_handle *)(&buffer[buf_widx]);
315 /* only advance the buffer write index of the size of the struct */
316 buf_widx = ringbuf_add(buf_widx, sizeof(struct memory_handle));
318 new_handle->id = cur_handle_id;
319 /* Wrap signed int is safe and 0 doesn't happen */
320 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
321 new_handle->next = NULL;
322 num_handles++;
324 if (!first_handle)
325 /* the new handle is the first one */
326 first_handle = new_handle;
328 if (cur_handle)
329 cur_handle->next = new_handle;
331 cur_handle = new_handle;
333 mutex_unlock(&llist_mod_mutex);
334 mutex_unlock(&llist_mutex);
335 return new_handle;
338 /* Delete a given memory handle from the linked list
339 and return true for success. Nothing is actually erased from memory. */
340 static bool rm_handle(const struct memory_handle *h)
342 if (h == NULL)
343 return true;
345 mutex_lock(&llist_mutex);
346 mutex_lock(&llist_mod_mutex);
348 if (h == first_handle) {
349 first_handle = h->next;
350 if (h == cur_handle) {
351 /* h was the first and last handle: the buffer is now empty */
352 cur_handle = NULL;
353 buf_ridx = buf_widx = 0;
354 } else {
355 /* update buf_ridx to point to the new first handle */
356 buf_ridx = (size_t)ringbuf_offset(first_handle);
358 } else {
359 struct memory_handle *m = first_handle;
360 /* Find the previous handle */
361 while (m && m->next != h) {
362 m = m->next;
364 if (m && m->next == h) {
365 m->next = h->next;
366 if (h == cur_handle) {
367 cur_handle = m;
368 buf_widx = cur_handle->widx;
370 } else {
371 mutex_unlock(&llist_mod_mutex);
372 mutex_unlock(&llist_mutex);
373 return false;
377 /* Invalidate the cache to prevent it from keeping the old location of h */
378 if (h == cached_handle)
379 cached_handle = NULL;
381 num_handles--;
383 mutex_unlock(&llist_mod_mutex);
384 mutex_unlock(&llist_mutex);
385 return true;
388 /* Return a pointer to the memory handle of given ID.
389 NULL if the handle wasn't found */
390 static struct memory_handle *find_handle(int handle_id)
392 if (handle_id < 0)
393 return NULL;
395 mutex_lock(&llist_mutex);
397 /* simple caching because most of the time the requested handle
398 will either be the same as the last, or the one after the last */
399 if (cached_handle)
401 if (cached_handle->id == handle_id) {
402 mutex_unlock(&llist_mutex);
403 return cached_handle;
404 } else if (cached_handle->next &&
405 (cached_handle->next->id == handle_id)) {
406 cached_handle = cached_handle->next;
407 mutex_unlock(&llist_mutex);
408 return cached_handle;
412 struct memory_handle *m = first_handle;
413 while (m && m->id != handle_id) {
414 m = m->next;
416 /* This condition can only be reached with !m or m->id == handle_id */
417 if (m)
418 cached_handle = m;
420 mutex_unlock(&llist_mutex);
421 return m;
424 /* Move a memory handle and data_size of its data delta bytes along the buffer.
425 delta maximum bytes available to move the handle. If the move is performed
426 it is set to the actual distance moved.
427 data_size is the amount of data to move along with the struct.
428 returns a valid memory_handle if the move is successful
429 NULL if the handle is NULL, the move would be less than the size of
430 a memory_handle after correcting for wraps or if the handle is not
431 found in the linked list for adjustment. This function has no side
432 effects if NULL is returned. */
433 static bool move_handle(struct memory_handle **h, size_t *delta,
434 size_t data_size, bool can_wrap)
436 struct memory_handle *dest;
437 const struct memory_handle *src;
438 int32_t *here;
439 int32_t *there;
440 int32_t *end;
441 int32_t *begin;
442 size_t final_delta = *delta, size_to_move, n;
443 uintptr_t oldpos, newpos;
444 intptr_t overlap, overlap_old;
446 if (h == NULL || (src = *h) == NULL)
447 return false;
449 size_to_move = sizeof(struct memory_handle) + data_size;
451 /* Align to four bytes, down */
452 final_delta &= ~3;
453 if (final_delta < sizeof(struct memory_handle)) {
454 /* It's not legal to move less than the size of the struct */
455 return false;
458 mutex_lock(&llist_mutex);
459 mutex_lock(&llist_mod_mutex);
461 oldpos = ringbuf_offset(src);
462 newpos = ringbuf_add(oldpos, final_delta);
463 overlap = ringbuf_add_cross(newpos, size_to_move, buffer_len - 1);
464 overlap_old = ringbuf_add_cross(oldpos, size_to_move, buffer_len -1);
466 if (overlap > 0) {
467 /* Some part of the struct + data would wrap, maybe ok */
468 size_t correction = 0;
469 /* If the overlap lands inside the memory_handle */
470 if (!can_wrap) {
471 /* Otherwise the overlap falls in the data area and must all be
472 * backed out. This may become conditional if ever we move
473 * data that is allowed to wrap (ie audio) */
474 correction = overlap;
475 } else if ((uintptr_t)overlap > data_size) {
476 /* Correct the position and real delta to prevent the struct from
477 * wrapping, this guarantees an aligned delta, I think */
478 correction = overlap - data_size;
480 if (correction) {
481 /* Align correction to four bytes up */
482 correction = (correction + 3) & ~3;
483 if (final_delta < correction + sizeof(struct memory_handle)) {
484 /* Delta cannot end up less than the size of the struct */
485 mutex_unlock(&llist_mod_mutex);
486 mutex_unlock(&llist_mutex);
487 return false;
489 newpos -= correction;
490 overlap -= correction;/* Used below to know how to split the data */
491 final_delta -= correction;
495 dest = (struct memory_handle *)(&buffer[newpos]);
497 if (src == first_handle) {
498 first_handle = dest;
499 buf_ridx = newpos;
500 } else {
501 struct memory_handle *m = first_handle;
502 while (m && m->next != src) {
503 m = m->next;
505 if (m && m->next == src) {
506 m->next = dest;
507 } else {
508 mutex_unlock(&llist_mod_mutex);
509 mutex_unlock(&llist_mutex);
510 return false;
515 /* Update the cache to prevent it from keeping the old location of h */
516 if (src == cached_handle)
517 cached_handle = dest;
519 /* the cur_handle pointer might need updating */
520 if (src == cur_handle)
521 cur_handle = dest;
524 /* Copying routine takes into account that the handles have a
525 * distance between each other which is a multiple of four. Faster 2 word
526 * copy may be ok but do this for safety and because wrapped copies should
527 * be fairly uncommon */
529 here = (int32_t *)((ringbuf_add(oldpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
530 there =(int32_t *)((ringbuf_add(newpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
531 end = (int32_t *)(( intptr_t)buffer + buffer_len - 4);
532 begin =(int32_t *)buffer;
534 n = (size_to_move & ~3)/4;
536 if ( overlap_old > 0 || overlap > 0 ) {
537 /* Old or moved handle wraps */
538 while (n--) {
539 if (here < begin)
540 here = end;
541 if (there < begin)
542 there = end;
543 *there-- = *here--;
545 } else {
546 /* both handles do not wrap */
547 memmove(dest,src,size_to_move);
551 /* Update the caller with the new location of h and the distance moved */
552 *h = dest;
553 *delta = final_delta;
554 mutex_unlock(&llist_mod_mutex);
555 mutex_unlock(&llist_mutex);
556 return dest;
561 BUFFER SPACE MANAGEMENT
562 =======================
564 update_data_counters: Updates the values in data_counters
565 buffer_is_low : Returns true if the amount of useful data in the buffer is low
566 buffer_handle : Buffer data for a handle
567 reset_handle : Reset write position and data buffer of a handle to its offset
568 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
569 shrink_handle : Free buffer space by moving a handle
570 fill_buffer : Call buffer_handle for all handles that have data to buffer
572 These functions are used by the buffering thread to manage buffer space.
575 static void update_data_counters(void)
577 struct memory_handle *m = find_handle(base_handle_id);
578 bool is_useful = m==NULL;
580 size_t buffered = 0;
581 size_t wasted = 0;
582 size_t remaining = 0;
583 size_t useful = 0;
585 mutex_lock(&llist_mutex);
587 m = first_handle;
588 while (m) {
589 buffered += m->available;
590 wasted += ringbuf_sub(m->ridx, m->data);
591 remaining += m->filerem;
593 if (m->id == base_handle_id)
594 is_useful = true;
596 if (is_useful)
597 useful += ringbuf_sub(m->widx, m->ridx);
599 m = m->next;
602 mutex_unlock(&llist_mutex);
604 data_counters.buffered = buffered;
605 data_counters.wasted = wasted;
606 data_counters.remaining = remaining;
607 data_counters.useful = useful;
610 static inline bool buffer_is_low(void)
612 update_data_counters();
613 return data_counters.useful < (conf_watermark / 2);
616 /* Buffer data for the given handle.
617 Return whether or not the buffering should continue explicitly. */
618 static bool buffer_handle(int handle_id)
620 logf("buffer_handle(%d)", handle_id);
621 struct memory_handle *h = find_handle(handle_id);
622 bool stop = false;
624 if (!h)
625 return true;
627 if (h->filerem == 0) {
628 /* nothing left to buffer */
629 return true;
632 if (h->fd < 0) /* file closed, reopen */
634 if (*h->path)
635 h->fd = open(h->path, O_RDONLY);
637 if (h->fd < 0)
639 /* could not open the file, truncate it where it is */
640 h->filesize -= h->filerem;
641 h->filerem = 0;
642 return true;
645 if (h->offset)
646 lseek(h->fd, h->offset, SEEK_SET);
649 trigger_cpu_boost();
651 if (h->type == TYPE_ID3)
653 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
655 /* metadata parsing failed: clear the buffer. */
656 memset(buffer + h->data, 0, sizeof(struct mp3entry));
658 close(h->fd);
659 h->fd = -1;
660 h->filerem = 0;
661 h->available = sizeof(struct mp3entry);
662 h->widx += sizeof(struct mp3entry);
663 send_event(BUFFER_EVENT_FINISHED, &h->id);
664 return true;
667 while (h->filerem > 0 && !stop)
669 /* max amount to copy */
670 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
671 buffer_len - h->widx);
673 ssize_t overlap;
674 uintptr_t next_handle = ringbuf_offset(h->next);
676 /* stop copying if it would overwrite the reading position */
677 if (ringbuf_add_cross(h->widx, copy_n, buf_ridx) >= 0)
678 return false;
680 /* FIXME: This would overwrite the next handle
681 * If this is true, then there's a handle even though we have still
682 * data to buffer. This should NEVER EVER happen! (but it does :( ) */
683 if (h->next && (overlap
684 = ringbuf_add_cross(h->widx, copy_n, next_handle)) > 0)
686 /* stop buffering data for now and post-pone buffering the rest */
687 stop = true;
688 DEBUGF( "%s(): Preventing handle corruption: h1.id:%d h2.id:%d"
689 " copy_n:%lu overlap:%ld h1.filerem:%lu\n", __func__,
690 h->id, h->next->id, (unsigned long)copy_n, overlap,
691 (unsigned long)h->filerem);
692 copy_n -= overlap;
695 /* rc is the actual amount read */
696 int rc = read(h->fd, &buffer[h->widx], copy_n);
698 if (rc < 0)
700 /* Some kind of filesystem error, maybe recoverable if not codec */
701 if (h->type == TYPE_CODEC) {
702 logf("Partial codec");
703 break;
706 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
707 h->filesize -= h->filerem;
708 h->filerem = 0;
709 break;
712 /* Advance buffer */
713 h->widx = ringbuf_add(h->widx, rc);
714 if (h == cur_handle)
715 buf_widx = h->widx;
716 h->available += rc;
717 h->filerem -= rc;
719 /* If this is a large file, see if we need to break or give the codec
720 * more time */
721 if (h->type == TYPE_PACKET_AUDIO &&
722 pcmbuf_is_lowdata() && !buffer_is_low())
724 sleep(1);
726 else
728 yield();
731 if (!queue_empty(&buffering_queue))
732 break;
735 if (h->filerem == 0) {
736 /* finished buffering the file */
737 close(h->fd);
738 h->fd = -1;
739 send_event(BUFFER_EVENT_FINISHED, &h->id);
742 return !stop;
745 /* Reset writing position and data buffer of a handle to its current offset.
746 Use this after having set the new offset to use. */
747 static void reset_handle(int handle_id)
749 size_t alignment_pad;
751 logf("reset_handle(%d)", handle_id);
753 struct memory_handle *h = find_handle(handle_id);
754 if (!h)
755 return;
757 /* Align to desired storage alignment */
758 alignment_pad = STORAGE_OVERLAP(h->offset - (size_t)(&buffer[h->start]));
759 h->ridx = h->widx = h->data = ringbuf_add(h->start, alignment_pad);
761 if (h == cur_handle)
762 buf_widx = h->widx;
763 h->available = 0;
764 h->filerem = h->filesize - h->offset;
766 if (h->fd >= 0) {
767 lseek(h->fd, h->offset, SEEK_SET);
771 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
772 static void rebuffer_handle(int handle_id, size_t newpos)
774 struct memory_handle *h = find_handle(handle_id);
775 if (!h)
776 return;
778 /* When seeking foward off of the buffer, if it is a short seek don't
779 rebuffer the whole track, just read enough to satisfy */
780 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
782 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
783 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
784 h->ridx = h->data + newpos;
785 return;
788 h->offset = newpos;
790 /* Reset the handle to its new offset */
791 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
792 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
794 uintptr_t next = ringbuf_offset(h->next);
795 if (ringbuf_sub(next, h->data) < h->filesize - newpos)
797 /* There isn't enough space to rebuffer all of the track from its new
798 offset, so we ask the user to free some */
799 DEBUGF("%s(): space is needed\n", __func__);
800 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
803 /* Now we ask for a rebuffer */
804 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
805 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
808 static bool close_handle(int handle_id)
810 struct memory_handle *h = find_handle(handle_id);
812 /* If the handle is not found, it is closed */
813 if (!h)
814 return true;
816 if (h->fd >= 0) {
817 close(h->fd);
818 h->fd = -1;
821 /* rm_handle returns true unless the handle somehow persists after exit */
822 return rm_handle(h);
825 /* Free buffer space by moving the handle struct right before the useful
826 part of its data buffer or by moving all the data. */
827 static void shrink_handle(struct memory_handle *h)
829 size_t delta;
831 if (!h)
832 return;
834 if (h->next && h->filerem == 0 &&
835 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
836 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
837 h->type == TYPE_ATOMIC_AUDIO))
839 /* metadata handle: we can move all of it */
840 uintptr_t handle_distance =
841 ringbuf_sub(ringbuf_offset(h->next), h->data);
842 delta = handle_distance - h->available;
844 /* The value of delta might change for alignment reasons */
845 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
846 return;
848 size_t olddata = h->data;
849 h->data = ringbuf_add(h->data, delta);
850 h->ridx = ringbuf_add(h->ridx, delta);
851 h->widx = ringbuf_add(h->widx, delta);
853 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
854 /* when moving an mp3entry we need to readjust its pointers. */
855 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
856 (void *)&buffer[h->data],
857 (const void *)&buffer[olddata]);
858 } else if (h->type == TYPE_BITMAP) {
859 /* adjust the bitmap's pointer */
860 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
861 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
864 else
866 /* only move the handle struct */
867 delta = ringbuf_sub(h->ridx, h->data);
868 if (!move_handle(&h, &delta, 0, true))
869 return;
871 h->data = ringbuf_add(h->data, delta);
872 h->start = ringbuf_add(h->start, delta);
873 h->available -= delta;
874 h->offset += delta;
878 /* Fill the buffer by buffering as much data as possible for handles that still
879 have data left to buffer
880 Return whether or not to continue filling after this */
881 static bool fill_buffer(void)
883 logf("fill_buffer()");
884 struct memory_handle *m;
885 shrink_handle(first_handle);
886 m = first_handle;
887 while (queue_empty(&buffering_queue) && m) {
888 if (m->filerem > 0) {
889 if (!buffer_handle(m->id)) {
890 m = NULL;
891 break;
894 m = m->next;
897 if (m) {
898 return true;
900 else
902 /* only spin the disk down if the filling wasn't interrupted by an
903 event arriving in the queue. */
904 storage_sleep();
905 return false;
909 #ifdef HAVE_ALBUMART
910 /* Given a file descriptor to a bitmap file, write the bitmap data to the
911 buffer, with a struct bitmap and the actual data immediately following.
912 Return value is the total size (struct + data). */
913 static int load_image(int fd, const char *path, struct dim *dim)
915 int rc;
916 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
918 /* get the desired image size */
919 bmp->width = dim->width, bmp->height = dim->height;
920 /* FIXME: alignment may be needed for the data buffer. */
921 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
922 #ifndef HAVE_JPEG
923 (void) path;
924 #endif
925 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
926 bmp->maskdata = NULL;
927 #endif
929 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
930 - sizeof(struct bitmap);
932 #ifdef HAVE_JPEG
933 int pathlen = strlen(path);
934 if (strcmp(path + pathlen - 4, ".bmp"))
935 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
936 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
937 else
938 #endif
939 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
940 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
941 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
943 #endif
947 MAIN BUFFERING API CALLS
948 ========================
950 bufopen : Request the opening of a new handle for a file
951 bufalloc : Open a new handle for data other than a file.
952 bufclose : Close an open handle
953 bufseek : Set the read pointer in a handle
954 bufadvance : Move the read pointer in a handle
955 bufread : Copy data from a handle into a given buffer
956 bufgetdata : Give a pointer to the handle's data
958 These functions are exported, to allow interaction with the buffer.
959 They take care of the content of the structs, and rely on the linked list
960 management functions for all the actual handle management work.
964 /* Reserve space in the buffer for a file.
965 filename: name of the file to open
966 offset: offset at which to start buffering the file, useful when the first
967 (offset-1) bytes of the file aren't needed.
968 type: one of the data types supported (audio, image, cuesheet, others
969 user_data: user data passed possibly passed in subcalls specific to a
970 data_type (only used for image (albumart) buffering so far )
971 return value: <0 if the file cannot be opened, or one file already
972 queued to be opened, otherwise the handle for the file in the buffer
974 int bufopen(const char *file, size_t offset, enum data_type type,
975 void *user_data)
977 #ifndef HAVE_ALBUMART
978 /* currently only used for aa loading */
979 (void)user_data;
980 #endif
981 if (type == TYPE_ID3)
983 /* ID3 case: allocate space, init the handle and return. */
985 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
986 if (!h)
987 return ERR_BUFFER_FULL;
989 h->fd = -1;
990 h->filesize = sizeof(struct mp3entry);
991 h->filerem = sizeof(struct mp3entry);
992 h->offset = 0;
993 h->data = buf_widx;
994 h->ridx = buf_widx;
995 h->widx = buf_widx;
996 h->available = 0;
997 h->type = type;
998 strlcpy(h->path, file, MAX_PATH);
1000 buf_widx += sizeof(struct mp3entry); /* safe because the handle
1001 can't wrap */
1003 /* Inform the buffering thread that we added a handle */
1004 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1005 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1007 return h->id;
1010 /* Other cases: there is a little more work. */
1012 int fd = open(file, O_RDONLY);
1013 if (fd < 0)
1014 return ERR_FILE_ERROR;
1016 size_t size = filesize(fd);
1017 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
1019 size_t adjusted_offset = offset;
1020 if (adjusted_offset > size)
1021 adjusted_offset = 0;
1023 /* Reserve extra space because alignment can move data forward */
1024 size_t padded_size = STORAGE_PAD(size-adjusted_offset);
1025 struct memory_handle *h = add_handle(padded_size, can_wrap, false);
1026 if (!h)
1028 DEBUGF("%s(): failed to add handle\n", __func__);
1029 close(fd);
1030 return ERR_BUFFER_FULL;
1033 strlcpy(h->path, file, MAX_PATH);
1034 h->offset = adjusted_offset;
1036 /* Don't bother to storage align bitmaps because they are not
1037 * loaded directly into the buffer.
1039 if (type != TYPE_BITMAP)
1041 size_t alignment_pad;
1043 /* Remember where data area starts, for use by reset_handle */
1044 h->start = buf_widx;
1046 /* Align to desired storage alignment */
1047 alignment_pad = STORAGE_OVERLAP(adjusted_offset - (size_t)(&buffer[buf_widx]));
1048 buf_widx = ringbuf_add(buf_widx, alignment_pad);
1051 h->ridx = buf_widx;
1052 h->widx = buf_widx;
1053 h->data = buf_widx;
1054 h->available = 0;
1055 h->filerem = 0;
1056 h->type = type;
1058 #ifdef HAVE_ALBUMART
1059 if (type == TYPE_BITMAP)
1061 /* Bitmap file: we load the data instead of the file */
1062 int rc;
1063 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1064 rc = load_image(fd, file, (struct dim*)user_data);
1065 mutex_unlock(&llist_mod_mutex);
1066 if (rc <= 0)
1068 rm_handle(h);
1069 close(fd);
1070 return ERR_FILE_ERROR;
1072 h->filerem = 0;
1073 h->filesize = rc;
1074 h->available = rc;
1075 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1076 buf_widx += rc; /* safe too */
1078 else
1079 #endif
1081 h->filerem = size - adjusted_offset;
1082 h->filesize = size;
1083 h->available = 0;
1084 h->widx = buf_widx;
1087 if (type == TYPE_CUESHEET) {
1088 h->fd = fd;
1089 /* Immediately start buffering those */
1090 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1091 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1092 } else {
1093 /* Other types will get buffered in the course of normal operations */
1094 h->fd = -1;
1095 close(fd);
1097 /* Inform the buffering thread that we added a handle */
1098 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1099 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1102 logf("bufopen: new hdl %d", h->id);
1103 return h->id;
1106 /* Open a new handle from data that needs to be copied from memory.
1107 src is the source buffer from which to copy data. It can be NULL to simply
1108 reserve buffer space.
1109 size is the requested size. The call will only be successful if the
1110 requested amount of data can entirely fit in the buffer without wrapping.
1111 Return value is the handle id for success or <0 for failure.
1113 int bufalloc(const void *src, size_t size, enum data_type type)
1115 struct memory_handle *h = add_handle(size, false, true);
1117 if (!h)
1118 return ERR_BUFFER_FULL;
1120 if (src) {
1121 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1122 /* specially take care of struct mp3entry */
1123 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1124 (const struct mp3entry *)src);
1125 } else {
1126 memcpy(&buffer[buf_widx], src, size);
1130 h->fd = -1;
1131 *h->path = 0;
1132 h->filesize = size;
1133 h->filerem = 0;
1134 h->offset = 0;
1135 h->ridx = buf_widx;
1136 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1137 h->data = buf_widx;
1138 h->available = size;
1139 h->type = type;
1141 buf_widx += size; /* safe too */
1143 logf("bufalloc: new hdl %d", h->id);
1144 return h->id;
1147 /* Close the handle. Return true for success and false for failure */
1148 bool bufclose(int handle_id)
1150 logf("bufclose(%d)", handle_id);
1152 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1153 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1156 /* Set reading index in handle (relatively to the start of the file).
1157 Access before the available data will trigger a rebuffer.
1158 Return 0 for success and < 0 for failure:
1159 -1 if the handle wasn't found
1160 -2 if the new requested position was beyond the end of the file
1162 int bufseek(int handle_id, size_t newpos)
1164 struct memory_handle *h = find_handle(handle_id);
1165 if (!h)
1166 return ERR_HANDLE_NOT_FOUND;
1168 if (newpos > h->filesize) {
1169 /* access beyond the end of the file */
1170 return ERR_INVALID_VALUE;
1172 else if (newpos < h->offset || h->offset + h->available < newpos) {
1173 /* access before or after buffered data. A rebuffer is needed. */
1174 rebuffer_handle(handle_id, newpos);
1176 else {
1177 h->ridx = ringbuf_add(h->data, newpos - h->offset);
1179 return 0;
1182 /* Advance the reading index in a handle (relatively to its current position).
1183 Return 0 for success and < 0 for failure */
1184 int bufadvance(int handle_id, off_t offset)
1186 const struct memory_handle *h = find_handle(handle_id);
1187 if (!h)
1188 return ERR_HANDLE_NOT_FOUND;
1190 size_t newpos = h->offset + ringbuf_sub(h->ridx, h->data) + offset;
1191 return bufseek(handle_id, newpos);
1194 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1195 * actual amount of data available for reading. This function explicitly
1196 * does not check the validity of the input handle. It does do range checks
1197 * on size and returns a valid (and explicit) amount of data for reading */
1198 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1199 bool guardbuf_limit)
1201 struct memory_handle *h = find_handle(handle_id);
1202 if (!h)
1203 return NULL;
1205 size_t avail = ringbuf_sub(h->widx, h->ridx);
1207 if (avail == 0 && h->filerem == 0)
1209 /* File is finished reading */
1210 *size = 0;
1211 return h;
1214 if (*size == 0 || *size > avail + h->filerem)
1215 *size = avail + h->filerem;
1217 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1219 logf("data request > guardbuf");
1220 /* If more than the size of the guardbuf is requested and this is a
1221 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1222 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1223 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1226 if (h->filerem > 0 && avail < *size)
1228 /* Data isn't ready. Request buffering */
1229 buf_request_buffer_handle(handle_id);
1230 /* Wait for the data to be ready */
1233 sleep(1);
1234 /* it is not safe for a non-buffering thread to sleep while
1235 * holding a handle */
1236 h = find_handle(handle_id);
1237 if (!h)
1238 return NULL;
1239 avail = ringbuf_sub(h->widx, h->ridx);
1241 while (h->filerem > 0 && avail < *size);
1244 *size = MIN(*size,avail);
1245 return h;
1248 /* Copy data from the given handle to the dest buffer.
1249 Return the number of bytes copied or < 0 for failure (handle not found).
1250 The caller is blocked until the requested amount of data is available.
1252 ssize_t bufread(int handle_id, size_t size, void *dest)
1254 const struct memory_handle *h;
1255 size_t adjusted_size = size;
1257 h = prep_bufdata(handle_id, &adjusted_size, false);
1258 if (!h)
1259 return ERR_HANDLE_NOT_FOUND;
1261 if (h->ridx + adjusted_size > buffer_len)
1263 /* the data wraps around the end of the buffer */
1264 size_t read = buffer_len - h->ridx;
1265 memcpy(dest, &buffer[h->ridx], read);
1266 memcpy(dest+read, buffer, adjusted_size - read);
1268 else
1270 memcpy(dest, &buffer[h->ridx], adjusted_size);
1273 return adjusted_size;
1276 /* Update the "data" pointer to make the handle's data available to the caller.
1277 Return the length of the available linear data or < 0 for failure (handle
1278 not found).
1279 The caller is blocked until the requested amount of data is available.
1280 size is the amount of linear data requested. it can be 0 to get as
1281 much as possible.
1282 The guard buffer may be used to provide the requested size. This means it's
1283 unsafe to request more than the size of the guard buffer.
1285 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1287 const struct memory_handle *h;
1288 size_t adjusted_size = size;
1290 h = prep_bufdata(handle_id, &adjusted_size, true);
1291 if (!h)
1292 return ERR_HANDLE_NOT_FOUND;
1294 if (h->ridx + adjusted_size > buffer_len)
1296 /* the data wraps around the end of the buffer :
1297 use the guard buffer to provide the requested amount of data. */
1298 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1299 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1300 so copy_n <= GUARD_BUFSIZE */
1301 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1304 if (data)
1305 *data = &buffer[h->ridx];
1307 return adjusted_size;
1310 ssize_t bufgettail(int handle_id, size_t size, void **data)
1312 size_t tidx;
1314 const struct memory_handle *h;
1316 h = find_handle(handle_id);
1318 if (!h)
1319 return ERR_HANDLE_NOT_FOUND;
1321 if (h->filerem)
1322 return ERR_HANDLE_NOT_DONE;
1324 /* We don't support tail requests of > guardbuf_size, for simplicity */
1325 if (size > GUARD_BUFSIZE)
1326 return ERR_INVALID_VALUE;
1328 tidx = ringbuf_sub(h->widx, size);
1330 if (tidx + size > buffer_len)
1332 size_t copy_n = tidx + size - buffer_len;
1333 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1336 *data = &buffer[tidx];
1337 return size;
1340 ssize_t bufcuttail(int handle_id, size_t size)
1342 struct memory_handle *h;
1343 size_t adjusted_size = size;
1345 h = find_handle(handle_id);
1347 if (!h)
1348 return ERR_HANDLE_NOT_FOUND;
1350 if (h->filerem)
1351 return ERR_HANDLE_NOT_DONE;
1353 if (h->available < adjusted_size)
1354 adjusted_size = h->available;
1356 h->available -= adjusted_size;
1357 h->filesize -= adjusted_size;
1358 h->widx = ringbuf_sub(h->widx, adjusted_size);
1359 if (h == cur_handle)
1360 buf_widx = h->widx;
1362 return adjusted_size;
1367 SECONDARY EXPORTED FUNCTIONS
1368 ============================
1370 buf_get_offset
1371 buf_handle_offset
1372 buf_request_buffer_handle
1373 buf_set_base_handle
1374 buf_used
1375 register_buffering_callback
1376 unregister_buffering_callback
1378 These functions are exported, to allow interaction with the buffer.
1379 They take care of the content of the structs, and rely on the linked list
1380 management functions for all the actual handle management work.
1383 /* Get a handle offset from a pointer */
1384 ssize_t buf_get_offset(int handle_id, void *ptr)
1386 const struct memory_handle *h = find_handle(handle_id);
1387 if (!h)
1388 return ERR_HANDLE_NOT_FOUND;
1390 return (size_t)ptr - (size_t)&buffer[h->ridx];
1393 ssize_t buf_handle_offset(int handle_id)
1395 const struct memory_handle *h = find_handle(handle_id);
1396 if (!h)
1397 return ERR_HANDLE_NOT_FOUND;
1398 return h->offset;
1401 void buf_request_buffer_handle(int handle_id)
1403 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1404 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1407 void buf_set_base_handle(int handle_id)
1409 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1410 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1413 /* Return the amount of buffer space used */
1414 size_t buf_used(void)
1416 return BUF_USED;
1419 void buf_set_watermark(size_t bytes)
1421 conf_watermark = bytes;
1424 static void shrink_buffer_inner(struct memory_handle *h)
1426 if (h == NULL)
1427 return;
1429 shrink_buffer_inner(h->next);
1431 shrink_handle(h);
1434 static void shrink_buffer(void)
1436 logf("shrink_buffer()");
1437 shrink_buffer_inner(first_handle);
1440 void buffering_thread(void)
1442 bool filling = false;
1443 struct queue_event ev;
1445 while (true)
1447 if (!filling) {
1448 cancel_cpu_boost();
1451 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1453 switch (ev.id)
1455 case Q_START_FILL:
1456 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1457 /* Call buffer callbacks here because this is one of two ways
1458 * to begin a full buffer fill */
1459 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1460 shrink_buffer();
1461 queue_reply(&buffering_queue, 1);
1462 filling |= buffer_handle((int)ev.data);
1463 break;
1465 case Q_BUFFER_HANDLE:
1466 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1467 queue_reply(&buffering_queue, 1);
1468 buffer_handle((int)ev.data);
1469 break;
1471 case Q_RESET_HANDLE:
1472 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1473 queue_reply(&buffering_queue, 1);
1474 reset_handle((int)ev.data);
1475 break;
1477 case Q_CLOSE_HANDLE:
1478 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1479 queue_reply(&buffering_queue, close_handle((int)ev.data));
1480 break;
1482 case Q_HANDLE_ADDED:
1483 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1484 /* A handle was added: the disk is spinning, so we can fill */
1485 filling = true;
1486 break;
1488 case Q_BASE_HANDLE:
1489 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1490 base_handle_id = (int)ev.data;
1491 break;
1493 #ifndef SIMULATOR
1494 case SYS_USB_CONNECTED:
1495 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1496 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1497 usb_wait_for_disconnect(&buffering_queue);
1498 break;
1499 #endif
1501 case SYS_TIMEOUT:
1502 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1503 break;
1506 update_data_counters();
1508 /* If the buffer is low, call the callbacks to get new data */
1509 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1510 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1512 #if 0
1513 /* TODO: This needs to be fixed to use the idle callback, disable it
1514 * for simplicity until its done right */
1515 #if MEM > 8
1516 /* If the disk is spinning, take advantage by filling the buffer */
1517 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1519 if (num_handles > 0 && data_counters.useful <= high_watermark)
1520 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1522 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1524 /* This is a new fill, shrink the buffer up first */
1525 if (!filling)
1526 shrink_buffer();
1527 filling = fill_buffer();
1528 update_data_counters();
1531 #endif
1532 #endif
1534 if (queue_empty(&buffering_queue)) {
1535 if (filling) {
1536 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1537 filling = fill_buffer();
1538 else if (data_counters.remaining == 0)
1539 filling = false;
1541 else if (ev.id == SYS_TIMEOUT)
1543 if (data_counters.remaining > 0 &&
1544 data_counters.useful <= conf_watermark) {
1545 shrink_buffer();
1546 filling = fill_buffer();
1553 void buffering_init(void)
1555 mutex_init(&llist_mutex);
1556 mutex_init(&llist_mod_mutex);
1557 #ifdef HAVE_PRIORITY_SCHEDULING
1558 /* This behavior not safe atm */
1559 mutex_set_preempt(&llist_mutex, false);
1560 mutex_set_preempt(&llist_mod_mutex, false);
1561 #endif
1563 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1565 queue_init(&buffering_queue, true);
1566 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1567 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1568 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1569 IF_COP(, CPU));
1571 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1572 buffering_thread_id);
1575 /* Initialise the buffering subsystem */
1576 bool buffering_reset(char *buf, size_t buflen)
1578 if (!buf || !buflen)
1579 return false;
1581 buffer = buf;
1582 /* Preserve alignment when wrapping around */
1583 buffer_len = STORAGE_ALIGN_DOWN(buflen);
1584 guard_buffer = buf + buflen;
1586 buf_widx = 0;
1587 buf_ridx = 0;
1589 first_handle = NULL;
1590 cur_handle = NULL;
1591 cached_handle = NULL;
1592 num_handles = 0;
1593 base_handle_id = -1;
1595 /* Set the high watermark as 75% full...or 25% empty :) */
1596 #if MEM > 8
1597 high_watermark = 3*buflen / 4;
1598 #endif
1600 thread_thaw(buffering_thread_id);
1602 return true;
1605 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1607 update_data_counters();
1608 dbgdata->num_handles = num_handles;
1609 dbgdata->data_rem = data_counters.remaining;
1610 dbgdata->wasted_space = data_counters.wasted;
1611 dbgdata->buffered_data = data_counters.buffered;
1612 dbgdata->useful_data = data_counters.useful;
1613 dbgdata->watermark = conf_watermark;