Fix minor typos in description fields.
[kugel-rb.git] / apps / buffering.c
blob46b6455178b4c6155fd641810365fb762e16b6b2
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 <inttypes.h>
28 #include "buffering.h"
30 #include "storage.h"
31 #include "system.h"
32 #include "thread.h"
33 #include "file.h"
34 #include "panic.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 "settings.h"
42 #include "codecs.h"
43 #include "audio.h"
44 #include "mp3_playback.h"
45 #include "usb.h"
46 #include "screens.h"
47 #include "playlist.h"
48 #include "pcmbuf.h"
49 #include "appevents.h"
50 #include "metadata.h"
51 #ifdef HAVE_ALBUMART
52 #include "albumart.h"
53 #include "jpeg_load.h"
54 #include "bmp.h"
55 #endif
57 #define GUARD_BUFSIZE (32*1024)
59 /* Define LOGF_ENABLE to enable logf output in this file */
60 /*#define LOGF_ENABLE*/
61 #include "logf.h"
63 /* macros to enable logf for queues
64 logging on SYS_TIMEOUT can be disabled */
65 #ifdef SIMULATOR
66 /* Define this for logf output of all queuing except SYS_TIMEOUT */
67 #define BUFFERING_LOGQUEUES
68 /* Define this to logf SYS_TIMEOUT messages */
69 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
70 #endif
72 #ifdef BUFFERING_LOGQUEUES
73 #define LOGFQUEUE logf
74 #else
75 #define LOGFQUEUE(...)
76 #endif
78 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
79 #define LOGFQUEUE_SYS_TIMEOUT logf
80 #else
81 #define LOGFQUEUE_SYS_TIMEOUT(...)
82 #endif
84 /* default point to start buffer refill */
85 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
86 /* amount of data to read in one read() call */
87 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
89 #define BUF_HANDLE_MASK 0x7FFFFFFF
92 /* assert(sizeof(struct memory_handle)%4==0) */
93 struct memory_handle {
94 int id; /* A unique ID for the handle */
95 enum data_type type; /* Type of data buffered with this handle */
96 char path[MAX_PATH]; /* Path if data originated in a file */
97 int fd; /* File descriptor to path (-1 if closed) */
98 size_t start; /* Start index of the handle's data buffer,
99 for use by reset_handle. */
100 size_t data; /* Start index of the handle's data */
101 volatile size_t ridx; /* Read pointer, relative to the main buffer */
102 size_t widx; /* Write pointer */
103 size_t filesize; /* File total length */
104 size_t filerem; /* Remaining bytes of file NOT in buffer */
105 volatile size_t available; /* Available bytes to read from buffer */
106 size_t offset; /* Offset at which we started reading the file */
107 struct memory_handle *next;
109 /* invariant: filesize == offset + available + filerem */
111 static char *buffer;
112 static char *guard_buffer;
114 static size_t buffer_len;
116 static volatile size_t buf_widx; /* current writing position */
117 static volatile size_t buf_ridx; /* current reading position */
118 /* buf_*idx are values relative to the buffer, not real pointers. */
120 /* Configuration */
121 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
122 #if MEM > 8
123 static size_t high_watermark = 0; /* High watermark for rebuffer */
124 #endif
126 /* current memory handle in the linked list. NULL when the list is empty. */
127 static struct memory_handle *cur_handle;
128 /* first memory handle in the linked list. NULL when the list is empty. */
129 static struct memory_handle *first_handle;
131 static int num_handles; /* number of handles in the list */
133 static int base_handle_id;
135 static struct mutex llist_mutex;
136 static struct mutex llist_mod_mutex;
138 /* Handle cache (makes find_handle faster).
139 This is global so that move_handle and rm_handle can invalidate it. */
140 static struct memory_handle *cached_handle = NULL;
142 static struct {
143 size_t remaining; /* Amount of data needing to be buffered */
144 size_t wasted; /* Amount of space available for freeing */
145 size_t buffered; /* Amount of data currently in the buffer */
146 size_t useful; /* Amount of data still useful to the user */
147 } data_counters;
150 /* Messages available to communicate with the buffering thread */
151 enum {
152 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
153 used in a low buffer situation. */
154 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
155 offset (the offset has to be set beforehand) */
156 Q_CLOSE_HANDLE, /* Request closing a handle */
157 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
159 /* Configuration: */
160 Q_START_FILL, /* Request that the buffering thread initiate a buffer
161 fill at its earliest convenience */
162 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
163 (which means the disk is spinning) */
166 /* Buffering thread */
167 static void buffering_thread(void);
168 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
169 static const char buffering_thread_name[] = "buffering";
170 static unsigned int buffering_thread_id = 0;
171 static struct event_queue buffering_queue;
172 static struct queue_sender_list buffering_queue_sender_list;
176 /* Ring buffer helper functions */
178 static inline uintptr_t ringbuf_offset(const void *ptr)
180 return (uintptr_t)(ptr - (void*)buffer);
183 /* Buffer pointer (p) plus value (v), wrapped if necessary */
184 static inline uintptr_t ringbuf_add(uintptr_t p, size_t v)
186 uintptr_t res = p + v;
187 if (res >= buffer_len)
188 res -= buffer_len; /* wrap if necssary */
189 return res;
193 /* Buffer pointer (p) minus value (v), wrapped if necessary */
194 static inline uintptr_t ringbuf_sub(uintptr_t p, size_t v)
196 uintptr_t res = p;
197 if (p < v)
198 res += buffer_len; /* wrap */
200 return res - v;
204 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
205 static inline ssize_t ringbuf_add_cross(uintptr_t p1, size_t v, uintptr_t p2)
207 ssize_t res = p1 + v - p2;
208 if (p1 >= p2) /* wrap if necessary */
209 res -= buffer_len;
211 return res;
214 /* Bytes available in the buffer */
215 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
218 LINKED LIST MANAGEMENT
219 ======================
221 add_handle : Add a handle to the list
222 rm_handle : Remove a handle from the list
223 find_handle : Get a handle pointer from an ID
224 move_handle : Move a handle in the buffer (with or without its data)
226 These functions only handle the linked list structure. They don't touch the
227 contents of the struct memory_handle headers. They also change the buf_*idx
228 pointers when necessary and manage the handle IDs.
230 The first and current (== last) handle are kept track of.
231 A new handle is added at buf_widx and becomes the current one.
232 buf_widx always points to the current writing position for the current handle
233 buf_ridx always points to the location of the first handle.
234 buf_ridx == buf_widx means the buffer is empty.
238 /* Add a new handle to the linked list and return it. It will have become the
239 new current handle.
240 data_size must contain the size of what will be in the handle.
241 can_wrap tells us whether this type of data may wrap on buffer
242 alloc_all tells us if we must immediately be able to allocate data_size
243 returns a valid memory handle if all conditions for allocation are met.
244 NULL if there memory_handle itself cannot be allocated or if the
245 data_size cannot be allocated and alloc_all is set. This function's
246 only potential side effect is to allocate space for the cur_handle
247 if it returns NULL.
249 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
250 bool alloc_all)
252 /* gives each handle a unique id */
253 static int cur_handle_id = 0;
254 size_t shift;
255 size_t new_widx;
256 size_t len;
257 int overlap;
259 if (num_handles >= BUF_MAX_HANDLES)
260 return NULL;
262 mutex_lock(&llist_mutex);
263 mutex_lock(&llist_mod_mutex);
265 if (cur_handle && cur_handle->filerem > 0) {
266 /* the current handle hasn't finished buffering. We can only add
267 a new one if there is already enough free space to finish
268 the buffering. */
269 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
270 if (ringbuf_add_cross(cur_handle->widx, req, buf_ridx) >= 0) {
271 /* Not enough space */
272 mutex_unlock(&llist_mod_mutex);
273 mutex_unlock(&llist_mutex);
274 return NULL;
275 } else {
276 /* Allocate the remainder of the space for the current handle */
277 buf_widx = ringbuf_add(cur_handle->widx, cur_handle->filerem);
281 /* align to 4 bytes up */
282 new_widx = ringbuf_add(buf_widx, 3) & ~3;
284 len = data_size + sizeof(struct memory_handle);
286 /* First, will the handle wrap? */
287 /* If the handle would wrap, move to the beginning of the buffer,
288 * or if the data must not but would wrap, move it to the beginning */
289 if( (new_widx + sizeof(struct memory_handle) > buffer_len) ||
290 (!can_wrap && (new_widx + len > buffer_len)) ) {
291 new_widx = 0;
294 /* How far we shifted buf_widx to align things, must be < buffer_len */
295 shift = ringbuf_sub(new_widx, buf_widx);
297 /* How much space are we short in the actual ring buffer? */
298 overlap = ringbuf_add_cross(buf_widx, shift + len, buf_ridx);
299 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
300 /* Not enough space for required allocations */
301 mutex_unlock(&llist_mod_mutex);
302 mutex_unlock(&llist_mutex);
303 return NULL;
306 /* There is enough space for the required data, advance the buf_widx and
307 * initialize the struct */
308 buf_widx = new_widx;
310 struct memory_handle *new_handle =
311 (struct memory_handle *)(&buffer[buf_widx]);
313 /* only advance the buffer write index of the size of the struct */
314 buf_widx = ringbuf_add(buf_widx, sizeof(struct memory_handle));
316 new_handle->id = cur_handle_id;
317 /* Wrap signed int is safe and 0 doesn't happen */
318 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
319 new_handle->next = NULL;
320 num_handles++;
322 if (!first_handle)
323 /* the new handle is the first one */
324 first_handle = new_handle;
326 if (cur_handle)
327 cur_handle->next = new_handle;
329 cur_handle = new_handle;
331 mutex_unlock(&llist_mod_mutex);
332 mutex_unlock(&llist_mutex);
333 return new_handle;
336 /* Delete a given memory handle from the linked list
337 and return true for success. Nothing is actually erased from memory. */
338 static bool rm_handle(const struct memory_handle *h)
340 if (h == NULL)
341 return true;
343 mutex_lock(&llist_mutex);
344 mutex_lock(&llist_mod_mutex);
346 if (h == first_handle) {
347 first_handle = h->next;
348 if (h == cur_handle) {
349 /* h was the first and last handle: the buffer is now empty */
350 cur_handle = NULL;
351 buf_ridx = buf_widx = 0;
352 } else {
353 /* update buf_ridx to point to the new first handle */
354 buf_ridx = (size_t)ringbuf_offset(first_handle);
356 } else {
357 struct memory_handle *m = first_handle;
358 /* Find the previous handle */
359 while (m && m->next != h) {
360 m = m->next;
362 if (m && m->next == h) {
363 m->next = h->next;
364 if (h == cur_handle) {
365 cur_handle = m;
366 buf_widx = cur_handle->widx;
368 } else {
369 mutex_unlock(&llist_mod_mutex);
370 mutex_unlock(&llist_mutex);
371 return false;
375 /* Invalidate the cache to prevent it from keeping the old location of h */
376 if (h == cached_handle)
377 cached_handle = NULL;
379 num_handles--;
381 mutex_unlock(&llist_mod_mutex);
382 mutex_unlock(&llist_mutex);
383 return true;
386 /* Return a pointer to the memory handle of given ID.
387 NULL if the handle wasn't found */
388 static struct memory_handle *find_handle(int handle_id)
390 if (handle_id < 0)
391 return NULL;
393 mutex_lock(&llist_mutex);
395 /* simple caching because most of the time the requested handle
396 will either be the same as the last, or the one after the last */
397 if (cached_handle)
399 if (cached_handle->id == handle_id) {
400 mutex_unlock(&llist_mutex);
401 return cached_handle;
402 } else if (cached_handle->next &&
403 (cached_handle->next->id == handle_id)) {
404 cached_handle = cached_handle->next;
405 mutex_unlock(&llist_mutex);
406 return cached_handle;
410 struct memory_handle *m = first_handle;
411 while (m && m->id != handle_id) {
412 m = m->next;
414 /* This condition can only be reached with !m or m->id == handle_id */
415 if (m)
416 cached_handle = m;
418 mutex_unlock(&llist_mutex);
419 return m;
422 /* Move a memory handle and data_size of its data delta bytes along the buffer.
423 delta maximum bytes available to move the handle. If the move is performed
424 it is set to the actual distance moved.
425 data_size is the amount of data to move along with the struct.
426 returns true if the move is successful and false if the handle is NULL,
427 the move would be less than the size of a memory_handle after
428 correcting for wraps or if the handle is not found in the linked
429 list for adjustment. This function has no side effects if false
430 is returned. */
431 static bool move_handle(struct memory_handle **h, size_t *delta,
432 size_t data_size, bool can_wrap)
434 struct memory_handle *dest;
435 const struct memory_handle *src;
436 int32_t *here;
437 int32_t *there;
438 int32_t *end;
439 int32_t *begin;
440 size_t final_delta = *delta, size_to_move, n;
441 uintptr_t oldpos, newpos;
442 intptr_t overlap, 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 = ringbuf_offset(src);
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 ((uintptr_t)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 true;
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 bool stop = false;
622 if (!h)
623 return true;
625 if (h->filerem == 0) {
626 /* nothing left to buffer */
627 return true;
630 if (h->fd < 0) /* file closed, reopen */
632 if (*h->path)
633 h->fd = open(h->path, O_RDONLY);
635 if (h->fd < 0)
637 /* could not open the file, truncate it where it is */
638 h->filesize -= h->filerem;
639 h->filerem = 0;
640 return true;
643 if (h->offset)
644 lseek(h->fd, h->offset, SEEK_SET);
647 trigger_cpu_boost();
649 if (h->type == TYPE_ID3)
651 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
653 /* metadata parsing failed: clear the buffer. */
654 memset(buffer + h->data, 0, sizeof(struct mp3entry));
656 close(h->fd);
657 h->fd = -1;
658 h->filerem = 0;
659 h->available = sizeof(struct mp3entry);
660 h->widx += sizeof(struct mp3entry);
661 send_event(BUFFER_EVENT_FINISHED, &h->id);
662 return true;
665 while (h->filerem > 0 && !stop)
667 /* max amount to copy */
668 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
669 buffer_len - h->widx);
671 ssize_t overlap;
672 uintptr_t next_handle = ringbuf_offset(h->next);
674 /* stop copying if it would overwrite the reading position */
675 if (ringbuf_add_cross(h->widx, copy_n, buf_ridx) >= 0)
676 return false;
678 /* FIXME: This would overwrite the next handle
679 * If this is true, then there's a handle even though we have still
680 * data to buffer. This should NEVER EVER happen! (but it does :( ) */
681 if (h->next && (overlap
682 = ringbuf_add_cross(h->widx, copy_n, next_handle)) > 0)
684 /* stop buffering data for now and post-pone buffering the rest */
685 stop = true;
686 DEBUGF( "%s(): Preventing handle corruption: h1.id:%d h2.id:%d"
687 " copy_n:%lu overlap:%ld h1.filerem:%lu\n", __func__,
688 h->id, h->next->id, (unsigned long)copy_n, (long)overlap,
689 (unsigned long)h->filerem);
690 copy_n -= overlap;
693 /* rc is the actual amount read */
694 int rc = read(h->fd, &buffer[h->widx], copy_n);
696 if (rc < 0)
698 /* Some kind of filesystem error, maybe recoverable if not codec */
699 if (h->type == TYPE_CODEC) {
700 logf("Partial codec");
701 break;
704 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
705 h->filesize -= h->filerem;
706 h->filerem = 0;
707 break;
710 /* Advance buffer */
711 h->widx = ringbuf_add(h->widx, rc);
712 if (h == cur_handle)
713 buf_widx = h->widx;
714 h->available += rc;
715 h->filerem -= rc;
717 /* If this is a large file, see if we need to break or give the codec
718 * more time */
719 if (h->type == TYPE_PACKET_AUDIO &&
720 pcmbuf_is_lowdata() && !buffer_is_low())
722 sleep(1);
724 else
726 yield();
729 if (!queue_empty(&buffering_queue))
730 break;
733 if (h->filerem == 0) {
734 /* finished buffering the file */
735 close(h->fd);
736 h->fd = -1;
737 send_event(BUFFER_EVENT_FINISHED, &h->id);
740 return !stop;
743 /* Reset writing position and data buffer of a handle to its current offset.
744 Use this after having set the new offset to use. */
745 static void reset_handle(int handle_id)
747 size_t alignment_pad;
749 logf("reset_handle(%d)", handle_id);
751 struct memory_handle *h = find_handle(handle_id);
752 if (!h)
753 return;
755 /* Align to desired storage alignment */
756 alignment_pad = STORAGE_OVERLAP(h->offset - (size_t)(&buffer[h->start]));
757 h->ridx = h->widx = h->data = ringbuf_add(h->start, alignment_pad);
759 if (h == cur_handle)
760 buf_widx = h->widx;
761 h->available = 0;
762 h->filerem = h->filesize - h->offset;
764 if (h->fd >= 0) {
765 lseek(h->fd, h->offset, SEEK_SET);
769 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
770 static void rebuffer_handle(int handle_id, size_t newpos)
772 struct memory_handle *h = find_handle(handle_id);
773 if (!h)
774 return;
776 /* When seeking foward off of the buffer, if it is a short seek don't
777 rebuffer the whole track, just read enough to satisfy */
778 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
780 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
781 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
782 h->ridx = ringbuf_add(h->data, newpos - h->offset);
783 return;
786 h->offset = newpos;
788 /* Reset the handle to its new offset */
789 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
790 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
792 uintptr_t next = ringbuf_offset(h->next);
793 if (ringbuf_sub(next, h->data) < h->filesize - newpos)
795 /* There isn't enough space to rebuffer all of the track from its new
796 offset, so we ask the user to free some */
797 DEBUGF("%s(): space is needed\n", __func__);
798 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
801 /* Now we ask for a rebuffer */
802 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
803 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
806 static bool close_handle(int handle_id)
808 struct memory_handle *h = find_handle(handle_id);
810 /* If the handle is not found, it is closed */
811 if (!h)
812 return true;
814 if (h->fd >= 0) {
815 close(h->fd);
816 h->fd = -1;
819 /* rm_handle returns true unless the handle somehow persists after exit */
820 return rm_handle(h);
823 /* Free buffer space by moving the handle struct right before the useful
824 part of its data buffer or by moving all the data. */
825 static void shrink_handle(struct memory_handle *h)
827 size_t delta;
829 if (!h)
830 return;
832 if (h->next && h->filerem == 0 &&
833 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
834 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
835 h->type == TYPE_ATOMIC_AUDIO))
837 /* metadata handle: we can move all of it */
838 uintptr_t handle_distance =
839 ringbuf_sub(ringbuf_offset(h->next), h->data);
840 delta = handle_distance - h->available;
842 /* The value of delta might change for alignment reasons */
843 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
844 return;
846 size_t olddata = h->data;
847 h->data = ringbuf_add(h->data, delta);
848 h->ridx = ringbuf_add(h->ridx, delta);
849 h->widx = ringbuf_add(h->widx, delta);
851 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
852 /* when moving an mp3entry we need to readjust its pointers. */
853 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
854 (void *)&buffer[h->data],
855 (const void *)&buffer[olddata]);
856 } else if (h->type == TYPE_BITMAP) {
857 /* adjust the bitmap's pointer */
858 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
859 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
862 else
864 /* only move the handle struct */
865 delta = ringbuf_sub(h->ridx, h->data);
866 if (!move_handle(&h, &delta, 0, true))
867 return;
869 h->data = ringbuf_add(h->data, delta);
870 h->start = ringbuf_add(h->start, delta);
871 h->available -= delta;
872 h->offset += delta;
876 /* Fill the buffer by buffering as much data as possible for handles that still
877 have data left to buffer
878 Return whether or not to continue filling after this */
879 static bool fill_buffer(void)
881 logf("fill_buffer()");
882 struct memory_handle *m;
883 shrink_handle(first_handle);
884 m = first_handle;
885 while (queue_empty(&buffering_queue) && m) {
886 if (m->filerem > 0) {
887 if (!buffer_handle(m->id)) {
888 m = NULL;
889 break;
892 m = m->next;
895 if (m) {
896 return true;
898 else
900 /* only spin the disk down if the filling wasn't interrupted by an
901 event arriving in the queue. */
902 storage_sleep();
903 return false;
907 #ifdef HAVE_ALBUMART
908 /* Given a file descriptor to a bitmap file, write the bitmap data to the
909 buffer, with a struct bitmap and the actual data immediately following.
910 Return value is the total size (struct + data). */
911 static int load_image(int fd, const char *path, struct dim *dim)
913 int rc;
914 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
916 /* get the desired image size */
917 bmp->width = dim->width, bmp->height = dim->height;
918 /* FIXME: alignment may be needed for the data buffer. */
919 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
920 #ifndef HAVE_JPEG
921 (void) path;
922 #endif
923 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
924 bmp->maskdata = NULL;
925 #endif
927 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
928 - sizeof(struct bitmap);
930 #ifdef HAVE_JPEG
931 int pathlen = strlen(path);
932 if (strcmp(path + pathlen - 4, ".bmp"))
933 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
934 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
935 else
936 #endif
937 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
938 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
939 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
941 #endif
945 MAIN BUFFERING API CALLS
946 ========================
948 bufopen : Request the opening of a new handle for a file
949 bufalloc : Open a new handle for data other than a file.
950 bufclose : Close an open handle
951 bufseek : Set the read pointer in a handle
952 bufadvance : Move the read pointer in a handle
953 bufread : Copy data from a handle into a given buffer
954 bufgetdata : Give a pointer to the handle's data
956 These functions are exported, to allow interaction with the buffer.
957 They take care of the content of the structs, and rely on the linked list
958 management functions for all the actual handle management work.
962 /* Reserve space in the buffer for a file.
963 filename: name of the file to open
964 offset: offset at which to start buffering the file, useful when the first
965 (offset-1) bytes of the file aren't needed.
966 type: one of the data types supported (audio, image, cuesheet, others
967 user_data: user data passed possibly passed in subcalls specific to a
968 data_type (only used for image (albumart) buffering so far )
969 return value: <0 if the file cannot be opened, or one file already
970 queued to be opened, otherwise the handle for the file in the buffer
972 int bufopen(const char *file, size_t offset, enum data_type type,
973 void *user_data)
975 #ifndef HAVE_ALBUMART
976 /* currently only used for aa loading */
977 (void)user_data;
978 #endif
979 if (type == TYPE_ID3)
981 /* ID3 case: allocate space, init the handle and return. */
983 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
984 if (!h)
985 return ERR_BUFFER_FULL;
987 h->fd = -1;
988 h->filesize = sizeof(struct mp3entry);
989 h->filerem = sizeof(struct mp3entry);
990 h->offset = 0;
991 h->data = buf_widx;
992 h->ridx = buf_widx;
993 h->widx = buf_widx;
994 h->available = 0;
995 h->type = type;
996 strlcpy(h->path, file, MAX_PATH);
998 buf_widx += sizeof(struct mp3entry); /* safe because the handle
999 can't wrap */
1001 /* Inform the buffering thread that we added a handle */
1002 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1003 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1005 return h->id;
1008 /* Other cases: there is a little more work. */
1009 int fd = open(file, O_RDONLY);
1010 if (fd < 0)
1011 return ERR_FILE_ERROR;
1013 size_t size = filesize(fd);
1014 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
1016 size_t adjusted_offset = offset;
1017 if (adjusted_offset > size)
1018 adjusted_offset = 0;
1020 /* Reserve extra space because alignment can move data forward */
1021 size_t padded_size = STORAGE_PAD(size-adjusted_offset);
1022 struct memory_handle *h = add_handle(padded_size, can_wrap, false);
1023 if (!h)
1025 DEBUGF("%s(): failed to add handle\n", __func__);
1026 close(fd);
1027 return ERR_BUFFER_FULL;
1030 strlcpy(h->path, file, MAX_PATH);
1031 h->offset = adjusted_offset;
1033 /* Don't bother to storage align bitmaps because they are not
1034 * loaded directly into the buffer.
1036 if (type != TYPE_BITMAP)
1038 size_t alignment_pad;
1040 /* Remember where data area starts, for use by reset_handle */
1041 h->start = buf_widx;
1043 /* Align to desired storage alignment */
1044 alignment_pad = STORAGE_OVERLAP(adjusted_offset - (size_t)(&buffer[buf_widx]));
1045 buf_widx = ringbuf_add(buf_widx, alignment_pad);
1048 h->ridx = buf_widx;
1049 h->widx = buf_widx;
1050 h->data = buf_widx;
1051 h->available = 0;
1052 h->filerem = 0;
1053 h->type = type;
1055 #ifdef HAVE_ALBUMART
1056 if (type == TYPE_BITMAP)
1058 /* Bitmap file: we load the data instead of the file */
1059 int rc;
1060 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1061 rc = load_image(fd, file, (struct dim*)user_data);
1062 mutex_unlock(&llist_mod_mutex);
1063 if (rc <= 0)
1065 rm_handle(h);
1066 close(fd);
1067 return ERR_FILE_ERROR;
1069 h->filerem = 0;
1070 h->filesize = rc;
1071 h->available = rc;
1072 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1073 buf_widx += rc; /* safe too */
1075 else
1076 #endif
1078 h->filerem = size - adjusted_offset;
1079 h->filesize = size;
1080 h->available = 0;
1081 h->widx = buf_widx;
1084 if (type == TYPE_CUESHEET) {
1085 h->fd = fd;
1086 /* Immediately start buffering those */
1087 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1088 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1089 } else {
1090 /* Other types will get buffered in the course of normal operations */
1091 h->fd = -1;
1092 close(fd);
1094 /* Inform the buffering thread that we added a handle */
1095 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1096 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1099 logf("bufopen: new hdl %d", h->id);
1100 return h->id;
1103 /* Open a new handle from data that needs to be copied from memory.
1104 src is the source buffer from which to copy data. It can be NULL to simply
1105 reserve buffer space.
1106 size is the requested size. The call will only be successful if the
1107 requested amount of data can entirely fit in the buffer without wrapping.
1108 Return value is the handle id for success or <0 for failure.
1110 int bufalloc(const void *src, size_t size, enum data_type type)
1112 struct memory_handle *h = add_handle(size, false, true);
1114 if (!h)
1115 return ERR_BUFFER_FULL;
1117 if (src) {
1118 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1119 /* specially take care of struct mp3entry */
1120 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1121 (const struct mp3entry *)src);
1122 } else {
1123 memcpy(&buffer[buf_widx], src, size);
1127 h->fd = -1;
1128 *h->path = 0;
1129 h->filesize = size;
1130 h->filerem = 0;
1131 h->offset = 0;
1132 h->ridx = buf_widx;
1133 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1134 h->data = buf_widx;
1135 h->available = size;
1136 h->type = type;
1138 buf_widx += size; /* safe too */
1140 logf("bufalloc: new hdl %d", h->id);
1141 return h->id;
1144 /* Close the handle. Return true for success and false for failure */
1145 bool bufclose(int handle_id)
1147 logf("bufclose(%d)", handle_id);
1149 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1150 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1153 /* Set reading index in handle (relatively to the start of the file).
1154 Access before the available data will trigger a rebuffer.
1155 Return 0 for success and < 0 for failure:
1156 -1 if the handle wasn't found
1157 -2 if the new requested position was beyond the end of the file
1159 int bufseek(int handle_id, size_t newpos)
1161 struct memory_handle *h = find_handle(handle_id);
1162 if (!h)
1163 return ERR_HANDLE_NOT_FOUND;
1165 if (newpos > h->filesize) {
1166 /* access beyond the end of the file */
1167 return ERR_INVALID_VALUE;
1169 else if (newpos < h->offset || h->offset + h->available < newpos) {
1170 /* access before or after buffered data. A rebuffer is needed. */
1171 rebuffer_handle(handle_id, newpos);
1173 else {
1174 h->ridx = ringbuf_add(h->data, newpos - h->offset);
1176 return 0;
1179 /* Advance the reading index in a handle (relatively to its current position).
1180 Return 0 for success and < 0 for failure */
1181 int bufadvance(int handle_id, off_t offset)
1183 const struct memory_handle *h = find_handle(handle_id);
1184 if (!h)
1185 return ERR_HANDLE_NOT_FOUND;
1187 size_t newpos = h->offset + ringbuf_sub(h->ridx, h->data) + offset;
1188 return bufseek(handle_id, newpos);
1191 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1192 * actual amount of data available for reading. This function explicitly
1193 * does not check the validity of the input handle. It does do range checks
1194 * on size and returns a valid (and explicit) amount of data for reading */
1195 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1196 bool guardbuf_limit)
1198 struct memory_handle *h = find_handle(handle_id);
1199 if (!h)
1200 return NULL;
1202 size_t avail = ringbuf_sub(h->widx, h->ridx);
1204 if (avail == 0 && h->filerem == 0)
1206 /* File is finished reading */
1207 *size = 0;
1208 return h;
1211 if (*size == 0 || *size > avail + h->filerem)
1212 *size = avail + h->filerem;
1214 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1216 logf("data request > guardbuf");
1217 /* If more than the size of the guardbuf is requested and this is a
1218 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1219 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1220 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1223 if (h->filerem > 0 && avail < *size)
1225 /* Data isn't ready. Request buffering */
1226 buf_request_buffer_handle(handle_id);
1227 /* Wait for the data to be ready */
1230 sleep(1);
1231 /* it is not safe for a non-buffering thread to sleep while
1232 * holding a handle */
1233 h = find_handle(handle_id);
1234 if (!h)
1235 return NULL;
1236 avail = ringbuf_sub(h->widx, h->ridx);
1238 while (h->filerem > 0 && avail < *size);
1241 *size = MIN(*size,avail);
1242 return h;
1245 /* Copy data from the given handle to the dest buffer.
1246 Return the number of bytes copied or < 0 for failure (handle not found).
1247 The caller is blocked until the requested amount of data is available.
1249 ssize_t bufread(int handle_id, size_t size, void *dest)
1251 const struct memory_handle *h;
1252 size_t adjusted_size = size;
1254 h = prep_bufdata(handle_id, &adjusted_size, false);
1255 if (!h)
1256 return ERR_HANDLE_NOT_FOUND;
1258 if (h->ridx + adjusted_size > buffer_len)
1260 /* the data wraps around the end of the buffer */
1261 size_t read = buffer_len - h->ridx;
1262 memcpy(dest, &buffer[h->ridx], read);
1263 memcpy(dest+read, buffer, adjusted_size - read);
1265 else
1267 memcpy(dest, &buffer[h->ridx], adjusted_size);
1270 return adjusted_size;
1273 /* Update the "data" pointer to make the handle's data available to the caller.
1274 Return the length of the available linear data or < 0 for failure (handle
1275 not found).
1276 The caller is blocked until the requested amount of data is available.
1277 size is the amount of linear data requested. it can be 0 to get as
1278 much as possible.
1279 The guard buffer may be used to provide the requested size. This means it's
1280 unsafe to request more than the size of the guard buffer.
1282 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1284 const struct memory_handle *h;
1285 size_t adjusted_size = size;
1287 h = prep_bufdata(handle_id, &adjusted_size, true);
1288 if (!h)
1289 return ERR_HANDLE_NOT_FOUND;
1291 if (h->ridx + adjusted_size > buffer_len)
1293 /* the data wraps around the end of the buffer :
1294 use the guard buffer to provide the requested amount of data. */
1295 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1296 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1297 so copy_n <= GUARD_BUFSIZE */
1298 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1301 if (data)
1302 *data = &buffer[h->ridx];
1304 return adjusted_size;
1307 ssize_t bufgettail(int handle_id, size_t size, void **data)
1309 size_t tidx;
1311 const struct memory_handle *h;
1313 h = find_handle(handle_id);
1315 if (!h)
1316 return ERR_HANDLE_NOT_FOUND;
1318 if (h->filerem)
1319 return ERR_HANDLE_NOT_DONE;
1321 /* We don't support tail requests of > guardbuf_size, for simplicity */
1322 if (size > GUARD_BUFSIZE)
1323 return ERR_INVALID_VALUE;
1325 tidx = ringbuf_sub(h->widx, size);
1327 if (tidx + size > buffer_len)
1329 size_t copy_n = tidx + size - buffer_len;
1330 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1333 *data = &buffer[tidx];
1334 return size;
1337 ssize_t bufcuttail(int handle_id, size_t size)
1339 struct memory_handle *h;
1340 size_t adjusted_size = size;
1342 h = find_handle(handle_id);
1344 if (!h)
1345 return ERR_HANDLE_NOT_FOUND;
1347 if (h->filerem)
1348 return ERR_HANDLE_NOT_DONE;
1350 if (h->available < adjusted_size)
1351 adjusted_size = h->available;
1353 h->available -= adjusted_size;
1354 h->filesize -= adjusted_size;
1355 h->widx = ringbuf_sub(h->widx, adjusted_size);
1356 if (h == cur_handle)
1357 buf_widx = h->widx;
1359 return adjusted_size;
1364 SECONDARY EXPORTED FUNCTIONS
1365 ============================
1367 buf_get_offset
1368 buf_handle_offset
1369 buf_request_buffer_handle
1370 buf_set_base_handle
1371 buf_used
1372 register_buffering_callback
1373 unregister_buffering_callback
1375 These functions are exported, to allow interaction with the buffer.
1376 They take care of the content of the structs, and rely on the linked list
1377 management functions for all the actual handle management work.
1380 /* Get a handle offset from a pointer */
1381 ssize_t buf_get_offset(int handle_id, void *ptr)
1383 const struct memory_handle *h = find_handle(handle_id);
1384 if (!h)
1385 return ERR_HANDLE_NOT_FOUND;
1387 return (size_t)ptr - (size_t)&buffer[h->ridx];
1390 ssize_t buf_handle_offset(int handle_id)
1392 const struct memory_handle *h = find_handle(handle_id);
1393 if (!h)
1394 return ERR_HANDLE_NOT_FOUND;
1395 return h->offset;
1398 void buf_request_buffer_handle(int handle_id)
1400 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1401 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1404 void buf_set_base_handle(int handle_id)
1406 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1407 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1410 /* Return the amount of buffer space used */
1411 size_t buf_used(void)
1413 return BUF_USED;
1416 void buf_set_watermark(size_t bytes)
1418 conf_watermark = bytes;
1421 static void shrink_buffer_inner(struct memory_handle *h)
1423 if (h == NULL)
1424 return;
1426 shrink_buffer_inner(h->next);
1428 shrink_handle(h);
1431 static void shrink_buffer(void)
1433 logf("shrink_buffer()");
1434 shrink_buffer_inner(first_handle);
1437 void buffering_thread(void)
1439 bool filling = false;
1440 struct queue_event ev;
1442 while (true)
1444 if (!filling) {
1445 cancel_cpu_boost();
1448 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1450 switch (ev.id)
1452 case Q_START_FILL:
1453 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1454 /* Call buffer callbacks here because this is one of two ways
1455 * to begin a full buffer fill */
1456 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1457 shrink_buffer();
1458 queue_reply(&buffering_queue, 1);
1459 filling |= buffer_handle((int)ev.data);
1460 break;
1462 case Q_BUFFER_HANDLE:
1463 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1464 queue_reply(&buffering_queue, 1);
1465 buffer_handle((int)ev.data);
1466 break;
1468 case Q_RESET_HANDLE:
1469 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1470 queue_reply(&buffering_queue, 1);
1471 reset_handle((int)ev.data);
1472 break;
1474 case Q_CLOSE_HANDLE:
1475 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1476 queue_reply(&buffering_queue, close_handle((int)ev.data));
1477 break;
1479 case Q_HANDLE_ADDED:
1480 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1481 /* A handle was added: the disk is spinning, so we can fill */
1482 filling = true;
1483 break;
1485 case Q_BASE_HANDLE:
1486 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1487 base_handle_id = (int)ev.data;
1488 break;
1490 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
1491 case SYS_USB_CONNECTED:
1492 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1493 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1494 usb_wait_for_disconnect(&buffering_queue);
1495 break;
1496 #endif
1498 case SYS_TIMEOUT:
1499 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1500 break;
1503 update_data_counters();
1505 /* If the buffer is low, call the callbacks to get new data */
1506 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1507 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1509 #if 0
1510 /* TODO: This needs to be fixed to use the idle callback, disable it
1511 * for simplicity until its done right */
1512 #if MEM > 8
1513 /* If the disk is spinning, take advantage by filling the buffer */
1514 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1516 if (num_handles > 0 && data_counters.useful <= high_watermark)
1517 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1519 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1521 /* This is a new fill, shrink the buffer up first */
1522 if (!filling)
1523 shrink_buffer();
1524 filling = fill_buffer();
1525 update_data_counters();
1528 #endif
1529 #endif
1531 if (queue_empty(&buffering_queue)) {
1532 if (filling) {
1533 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1534 filling = fill_buffer();
1535 else if (data_counters.remaining == 0)
1536 filling = false;
1538 else if (ev.id == SYS_TIMEOUT)
1540 if (data_counters.remaining > 0 &&
1541 data_counters.useful <= conf_watermark) {
1542 shrink_buffer();
1543 filling = fill_buffer();
1550 void buffering_init(void)
1552 mutex_init(&llist_mutex);
1553 mutex_init(&llist_mod_mutex);
1554 #ifdef HAVE_PRIORITY_SCHEDULING
1555 /* This behavior not safe atm */
1556 mutex_set_preempt(&llist_mutex, false);
1557 mutex_set_preempt(&llist_mod_mutex, false);
1558 #endif
1560 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1562 queue_init(&buffering_queue, true);
1563 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1564 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1565 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1566 IF_COP(, CPU));
1568 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1569 buffering_thread_id);
1572 /* Initialise the buffering subsystem */
1573 bool buffering_reset(char *buf, size_t buflen)
1575 if (!buf || !buflen)
1576 return false;
1578 buffer = buf;
1579 buffer_len = buflen;
1580 guard_buffer = buf + buflen;
1582 buf_widx = 0;
1583 buf_ridx = 0;
1585 first_handle = NULL;
1586 cur_handle = NULL;
1587 cached_handle = NULL;
1588 num_handles = 0;
1589 base_handle_id = -1;
1591 /* Set the high watermark as 75% full...or 25% empty :) */
1592 #if MEM > 8
1593 high_watermark = 3*buflen / 4;
1594 #endif
1596 thread_thaw(buffering_thread_id);
1598 return true;
1601 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1603 update_data_counters();
1604 dbgdata->num_handles = num_handles;
1605 dbgdata->data_rem = data_counters.remaining;
1606 dbgdata->wasted_space = data_counters.wasted;
1607 dbgdata->buffered_data = data_counters.buffered;
1608 dbgdata->useful_data = data_counters.useful;
1609 dbgdata->watermark = conf_watermark;