Needed to do a few more things to have r29291 correct.
[kugel-rb.git] / apps / buffering.c
blob85028dc8e67ac68612f359b444f475fbc84d4a23
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 #include "playback.h"
56 #endif
58 #define GUARD_BUFSIZE (32*1024)
60 /* Define LOGF_ENABLE to enable logf output in this file */
61 /*#define LOGF_ENABLE*/
62 #include "logf.h"
64 /* macros to enable logf for queues
65 logging on SYS_TIMEOUT can be disabled */
66 #ifdef SIMULATOR
67 /* Define this for logf output of all queuing except SYS_TIMEOUT */
68 #define BUFFERING_LOGQUEUES
69 /* Define this to logf SYS_TIMEOUT messages */
70 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
71 #endif
73 #ifdef BUFFERING_LOGQUEUES
74 #define LOGFQUEUE logf
75 #else
76 #define LOGFQUEUE(...)
77 #endif
79 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
80 #define LOGFQUEUE_SYS_TIMEOUT logf
81 #else
82 #define LOGFQUEUE_SYS_TIMEOUT(...)
83 #endif
85 /* default point to start buffer refill */
86 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
87 /* amount of data to read in one read() call */
88 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
90 #define BUF_HANDLE_MASK 0x7FFFFFFF
93 /* assert(sizeof(struct memory_handle)%4==0) */
94 struct memory_handle {
95 int id; /* A unique ID for the handle */
96 enum data_type type; /* Type of data buffered with this handle */
97 char path[MAX_PATH]; /* Path if data originated in a file */
98 int fd; /* File descriptor to path (-1 if closed) */
99 size_t start; /* Start index of the handle's data buffer,
100 for use by reset_handle. */
101 size_t data; /* Start index of the handle's data */
102 volatile size_t ridx; /* Read pointer, relative to the main buffer */
103 size_t widx; /* Write pointer */
104 size_t filesize; /* File total length */
105 size_t filerem; /* Remaining bytes of file NOT in buffer */
106 volatile size_t available; /* Available bytes to read from buffer */
107 size_t offset; /* Offset at which we started reading the file */
108 struct memory_handle *next;
110 /* invariant: filesize == offset + available + filerem */
112 static char *buffer;
113 static char *guard_buffer;
115 static size_t buffer_len;
117 static volatile size_t buf_widx; /* current writing position */
118 static volatile size_t buf_ridx; /* current reading position */
119 /* buf_*idx are values relative to the buffer, not real pointers. */
121 /* Configuration */
122 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
123 #if MEMORYSIZE > 8
124 static size_t high_watermark = 0; /* High watermark for rebuffer */
125 #endif
127 /* current memory handle in the linked list. NULL when the list is empty. */
128 static struct memory_handle *cur_handle;
129 /* first memory handle in the linked list. NULL when the list is empty. */
130 static struct memory_handle *first_handle;
132 static int num_handles; /* number of handles in the list */
134 static int base_handle_id;
136 static struct mutex llist_mutex;
137 static struct mutex llist_mod_mutex;
139 /* Handle cache (makes find_handle faster).
140 This is global so that move_handle and rm_handle can invalidate it. */
141 static struct memory_handle *cached_handle = NULL;
143 static struct {
144 size_t remaining; /* Amount of data needing to be buffered */
145 size_t wasted; /* Amount of space available for freeing */
146 size_t buffered; /* Amount of data currently in the buffer */
147 size_t useful; /* Amount of data still useful to the user */
148 } data_counters;
151 /* Messages available to communicate with the buffering thread */
152 enum {
153 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
154 used in a low buffer situation. */
155 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
156 offset (the offset has to be set beforehand) */
157 Q_CLOSE_HANDLE, /* Request closing a handle */
158 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
160 /* Configuration: */
161 Q_START_FILL, /* Request that the buffering thread initiate a buffer
162 fill at its earliest convenience */
163 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
164 (which means the disk is spinning) */
167 /* Buffering thread */
168 static void buffering_thread(void);
169 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
170 static const char buffering_thread_name[] = "buffering";
171 static unsigned int buffering_thread_id = 0;
172 static struct event_queue buffering_queue;
173 static struct queue_sender_list buffering_queue_sender_list;
177 /* Ring buffer helper functions */
179 static inline uintptr_t ringbuf_offset(const void *ptr)
181 return (uintptr_t)(ptr - (void*)buffer);
184 /* Buffer pointer (p) plus value (v), wrapped if necessary */
185 static inline uintptr_t ringbuf_add(uintptr_t p, size_t v)
187 uintptr_t res = p + v;
188 if (res >= buffer_len)
189 res -= buffer_len; /* wrap if necssary */
190 return res;
194 /* Buffer pointer (p) minus value (v), wrapped if necessary */
195 static inline uintptr_t ringbuf_sub(uintptr_t p, size_t v)
197 uintptr_t res = p;
198 if (p < v)
199 res += buffer_len; /* wrap */
201 return res - v;
205 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
206 static inline ssize_t ringbuf_add_cross(uintptr_t p1, size_t v, uintptr_t p2)
208 ssize_t res = p1 + v - p2;
209 if (p1 >= p2) /* wrap if necessary */
210 res -= buffer_len;
212 return res;
215 /* Bytes available in the buffer */
216 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
219 LINKED LIST MANAGEMENT
220 ======================
222 add_handle : Add a handle to the list
223 rm_handle : Remove a handle from the list
224 find_handle : Get a handle pointer from an ID
225 move_handle : Move a handle in the buffer (with or without its data)
227 These functions only handle the linked list structure. They don't touch the
228 contents of the struct memory_handle headers. They also change the buf_*idx
229 pointers when necessary and manage the handle IDs.
231 The first and current (== last) handle are kept track of.
232 A new handle is added at buf_widx and becomes the current one.
233 buf_widx always points to the current writing position for the current handle
234 buf_ridx always points to the location of the first handle.
235 buf_ridx == buf_widx means the buffer is empty.
239 /* Add a new handle to the linked list and return it. It will have become the
240 new current handle.
241 data_size must contain the size of what will be in the handle.
242 can_wrap tells us whether this type of data may wrap on buffer
243 alloc_all tells us if we must immediately be able to allocate data_size
244 returns a valid memory handle if all conditions for allocation are met.
245 NULL if there memory_handle itself cannot be allocated or if the
246 data_size cannot be allocated and alloc_all is set. */
247 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
248 bool alloc_all)
250 /* gives each handle a unique id */
251 static int cur_handle_id = 0;
252 size_t shift;
253 size_t widx, new_widx;
254 size_t len;
255 ssize_t overlap;
257 if (num_handles >= BUF_MAX_HANDLES)
258 return NULL;
260 mutex_lock(&llist_mutex);
261 mutex_lock(&llist_mod_mutex);
263 widx = buf_widx;
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 widx = ringbuf_add(cur_handle->widx, cur_handle->filerem);
281 /* align to 4 bytes up */
282 new_widx = ringbuf_add(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 the new_widx to align things, must be < buffer_len */
295 shift = ringbuf_sub(new_widx, widx);
297 /* How much space are we short in the actual ring buffer? */
298 overlap = ringbuf_add_cross(widx, shift + len, buf_ridx);
299 if (overlap >= 0 && (alloc_all || (size_t)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 size_t final_delta = *delta, size_to_move;
437 uintptr_t oldpos, newpos;
438 intptr_t overlap, overlap_old;
440 if (h == NULL || (src = *h) == NULL)
441 return false;
443 size_to_move = sizeof(struct memory_handle) + data_size;
445 /* Align to four bytes, down */
446 final_delta &= ~3;
447 if (final_delta < sizeof(struct memory_handle)) {
448 /* It's not legal to move less than the size of the struct */
449 return false;
452 mutex_lock(&llist_mutex);
453 mutex_lock(&llist_mod_mutex);
455 oldpos = ringbuf_offset(src);
456 newpos = ringbuf_add(oldpos, final_delta);
457 overlap = ringbuf_add_cross(newpos, size_to_move, buffer_len);
458 overlap_old = ringbuf_add_cross(oldpos, size_to_move, buffer_len);
460 if (overlap > 0) {
461 /* Some part of the struct + data would wrap, maybe ok */
462 ssize_t correction = 0;
463 /* If the overlap lands inside the memory_handle */
464 if (!can_wrap) {
465 /* Otherwise the overlap falls in the data area and must all be
466 * backed out. This may become conditional if ever we move
467 * data that is allowed to wrap (ie audio) */
468 correction = overlap;
469 } else if ((uintptr_t)overlap > data_size) {
470 /* Correct the position and real delta to prevent the struct from
471 * wrapping, this guarantees an aligned delta if the struct size is
472 * aligned and the buffer is aligned */
473 correction = overlap - data_size;
475 if (correction) {
476 /* Align correction to four bytes up */
477 correction = (correction + 3) & ~3;
478 if (final_delta < correction + sizeof(struct memory_handle)) {
479 /* Delta cannot end up less than the size of the struct */
480 mutex_unlock(&llist_mod_mutex);
481 mutex_unlock(&llist_mutex);
482 return false;
484 newpos -= correction;
485 overlap -= correction;/* Used below to know how to split the data */
486 final_delta -= correction;
490 dest = (struct memory_handle *)(&buffer[newpos]);
492 if (src == first_handle) {
493 first_handle = dest;
494 buf_ridx = newpos;
495 } else {
496 struct memory_handle *m = first_handle;
497 while (m && m->next != src) {
498 m = m->next;
500 if (m && m->next == src) {
501 m->next = dest;
502 } else {
503 mutex_unlock(&llist_mod_mutex);
504 mutex_unlock(&llist_mutex);
505 return false;
509 /* Update the cache to prevent it from keeping the old location of h */
510 if (src == cached_handle)
511 cached_handle = dest;
513 /* the cur_handle pointer might need updating */
514 if (src == cur_handle)
515 cur_handle = dest;
517 /* x = handle(s) following this one...
518 * ...if last handle, unmoveable if metadata, only shrinkable if audio.
519 * In other words, no legal move can be made that would have the src head
520 * and dest tail of the data overlap itself. These facts reduce the
521 * problem to four essential permutations.
523 * movement: always "clockwise" >>>>
525 * (src nowrap, dest nowrap)
526 * |0123 x |
527 * | 0123x | etc...
528 * move: "0123"
530 * (src nowrap, dest wrap)
531 * | x0123 |
532 * |23x 01|
533 * move: "23", "01"
535 * (src wrap, dest nowrap)
536 * |23 x01|
537 * | 0123x |
538 * move: "23", "01"
540 * (src wrap, dest wrap)
541 * |23 x 01|
542 * |123x 0|
543 * move: "23", "1", "0"
545 if (overlap_old > 0) {
546 /* Move over already wrapped data by the final delta */
547 memmove(&buffer[final_delta], buffer, overlap_old);
548 if (overlap <= 0)
549 size_to_move -= overlap_old;
552 if (overlap > 0) {
553 /* Move data that now wraps to the beginning */
554 size_to_move -= overlap;
555 memmove(buffer, SKIPBYTES(src, size_to_move),
556 overlap_old > 0 ? final_delta : (size_t)overlap);
559 /* Move leading fragment containing handle struct */
560 memmove(dest, src, size_to_move);
562 /* Update the caller with the new location of h and the distance moved */
563 *h = dest;
564 *delta = final_delta;
565 mutex_unlock(&llist_mod_mutex);
566 mutex_unlock(&llist_mutex);
567 return true;
572 BUFFER SPACE MANAGEMENT
573 =======================
575 update_data_counters: Updates the values in data_counters
576 buffer_is_low : Returns true if the amount of useful data in the buffer is low
577 buffer_handle : Buffer data for a handle
578 reset_handle : Reset write position and data buffer of a handle to its offset
579 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
580 shrink_handle : Free buffer space by moving a handle
581 fill_buffer : Call buffer_handle for all handles that have data to buffer
583 These functions are used by the buffering thread to manage buffer space.
586 static void update_data_counters(void)
588 struct memory_handle *m = find_handle(base_handle_id);
589 bool is_useful = m==NULL;
591 size_t buffered = 0;
592 size_t wasted = 0;
593 size_t remaining = 0;
594 size_t useful = 0;
596 mutex_lock(&llist_mutex);
598 m = first_handle;
599 while (m) {
600 buffered += m->available;
601 wasted += ringbuf_sub(m->ridx, m->data);
602 remaining += m->filerem;
604 if (m->id == base_handle_id)
605 is_useful = true;
607 if (is_useful)
608 useful += ringbuf_sub(m->widx, m->ridx);
610 m = m->next;
613 mutex_unlock(&llist_mutex);
615 data_counters.buffered = buffered;
616 data_counters.wasted = wasted;
617 data_counters.remaining = remaining;
618 data_counters.useful = useful;
621 static inline bool buffer_is_low(void)
623 update_data_counters();
624 return data_counters.useful < (conf_watermark / 2);
627 /* Buffer data for the given handle.
628 Return whether or not the buffering should continue explicitly. */
629 static bool buffer_handle(int handle_id)
631 logf("buffer_handle(%d)", handle_id);
632 struct memory_handle *h = find_handle(handle_id);
633 bool stop = false;
635 if (!h)
636 return true;
638 if (h->filerem == 0) {
639 /* nothing left to buffer */
640 return true;
643 if (h->fd < 0) /* file closed, reopen */
645 if (*h->path)
646 h->fd = open(h->path, O_RDONLY);
648 if (h->fd < 0)
650 /* could not open the file, truncate it where it is */
651 h->filesize -= h->filerem;
652 h->filerem = 0;
653 return true;
656 if (h->offset)
657 lseek(h->fd, h->offset, SEEK_SET);
660 trigger_cpu_boost();
662 if (h->type == TYPE_ID3)
664 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
666 /* metadata parsing failed: clear the buffer. */
667 memset(buffer + h->data, 0, sizeof(struct mp3entry));
669 close(h->fd);
670 h->fd = -1;
671 h->filerem = 0;
672 h->available = sizeof(struct mp3entry);
673 h->widx += sizeof(struct mp3entry);
674 send_event(BUFFER_EVENT_FINISHED, &h->id);
675 return true;
678 while (h->filerem > 0 && !stop)
680 /* max amount to copy */
681 ssize_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
682 buffer_len - h->widx);
683 uintptr_t offset = h->next ? ringbuf_offset(h->next) : buf_ridx;
684 ssize_t overlap = ringbuf_add_cross(h->widx, copy_n, offset);
686 if (!h->next)
687 overlap++; /* sub one more below to avoid buffer overflow */
689 if (overlap > 0)
691 /* read only up to available space and stop if it would overwrite
692 the reading position or the next handle */
693 stop = true;
694 copy_n -= overlap;
697 if (copy_n <= 0)
698 return false; /* no space for read */
700 /* rc is the actual amount read */
701 int rc = read(h->fd, &buffer[h->widx], copy_n);
703 if (rc < 0)
705 /* Some kind of filesystem error, maybe recoverable if not codec */
706 if (h->type == TYPE_CODEC) {
707 logf("Partial codec");
708 break;
711 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
712 h->filesize -= h->filerem;
713 h->filerem = 0;
714 break;
717 /* Advance buffer */
718 h->widx = ringbuf_add(h->widx, rc);
719 if (h == cur_handle)
720 buf_widx = h->widx;
721 h->available += rc;
722 h->filerem -= rc;
724 /* If this is a large file, see if we need to break or give the codec
725 * more time */
726 if (h->type == TYPE_PACKET_AUDIO &&
727 pcmbuf_is_lowdata() && !buffer_is_low())
729 sleep(1);
731 else
733 yield();
736 if (!queue_empty(&buffering_queue))
737 break;
740 if (h->filerem == 0) {
741 /* finished buffering the file */
742 close(h->fd);
743 h->fd = -1;
744 send_event(BUFFER_EVENT_FINISHED, &h->id);
747 return !stop;
750 /* Reset writing position and data buffer of a handle to its current offset.
751 Use this after having set the new offset to use. */
752 static void reset_handle(int handle_id)
754 size_t alignment_pad;
756 logf("reset_handle(%d)", handle_id);
758 struct memory_handle *h = find_handle(handle_id);
759 if (!h)
760 return;
762 /* Align to desired storage alignment */
763 alignment_pad = STORAGE_OVERLAP(h->offset - (size_t)(&buffer[h->start]));
764 h->ridx = h->widx = h->data = ringbuf_add(h->start, alignment_pad);
766 if (h == cur_handle)
767 buf_widx = h->widx;
768 h->available = 0;
769 h->filerem = h->filesize - h->offset;
771 if (h->fd >= 0) {
772 lseek(h->fd, h->offset, SEEK_SET);
776 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
777 static void rebuffer_handle(int handle_id, size_t newpos)
779 struct memory_handle *h = find_handle(handle_id);
780 if (!h)
781 return;
783 /* When seeking foward off of the buffer, if it is a short seek don't
784 rebuffer the whole track, just read enough to satisfy */
785 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
787 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
788 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
789 h->ridx = ringbuf_add(h->data, newpos - h->offset);
790 return;
793 h->offset = newpos;
795 /* Reset the handle to its new offset */
796 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
797 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
799 uintptr_t next = ringbuf_offset(h->next);
800 if (ringbuf_sub(next, h->data) < h->filesize - newpos)
802 /* There isn't enough space to rebuffer all of the track from its new
803 offset, so we ask the user to free some */
804 DEBUGF("%s(): space is needed\n", __func__);
805 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
808 /* Now we ask for a rebuffer */
809 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
810 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
813 static bool close_handle(int handle_id)
815 struct memory_handle *h = find_handle(handle_id);
817 /* If the handle is not found, it is closed */
818 if (!h)
819 return true;
821 if (h->fd >= 0) {
822 close(h->fd);
823 h->fd = -1;
826 /* rm_handle returns true unless the handle somehow persists after exit */
827 return rm_handle(h);
830 /* Free buffer space by moving the handle struct right before the useful
831 part of its data buffer or by moving all the data. */
832 static void shrink_handle(struct memory_handle *h)
834 size_t delta;
836 if (!h)
837 return;
839 if (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
840 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
841 h->type == TYPE_ATOMIC_AUDIO)
843 /* metadata handle: we can move all of it */
844 if (!h->next || h->filerem != 0)
845 return; /* Last handle or not finished loading */
847 uintptr_t handle_distance =
848 ringbuf_sub(ringbuf_offset(h->next), h->data);
849 delta = handle_distance - h->available;
851 /* The value of delta might change for alignment reasons */
852 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
853 return;
855 size_t olddata = h->data;
856 h->data = ringbuf_add(h->data, delta);
857 h->ridx = ringbuf_add(h->ridx, delta);
858 h->widx = ringbuf_add(h->widx, delta);
860 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
861 /* when moving an mp3entry we need to readjust its pointers. */
862 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
863 (void *)&buffer[h->data],
864 (const void *)&buffer[olddata]);
865 } else if (h->type == TYPE_BITMAP) {
866 /* adjust the bitmap's pointer */
867 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
868 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
871 else
873 /* only move the handle struct */
874 delta = ringbuf_sub(h->ridx, h->data);
875 if (!move_handle(&h, &delta, 0, true))
876 return;
878 h->data = ringbuf_add(h->data, delta);
879 h->start = ringbuf_add(h->start, delta);
880 h->available -= delta;
881 h->offset += delta;
885 /* Fill the buffer by buffering as much data as possible for handles that still
886 have data left to buffer
887 Return whether or not to continue filling after this */
888 static bool fill_buffer(void)
890 logf("fill_buffer()");
891 struct memory_handle *m;
892 shrink_handle(first_handle);
893 m = first_handle;
894 while (queue_empty(&buffering_queue) && m) {
895 if (m->filerem > 0) {
896 if (!buffer_handle(m->id)) {
897 m = NULL;
898 break;
901 m = m->next;
904 if (m) {
905 return true;
907 else
909 /* only spin the disk down if the filling wasn't interrupted by an
910 event arriving in the queue. */
911 storage_sleep();
912 return false;
916 #ifdef HAVE_ALBUMART
917 /* Given a file descriptor to a bitmap file, write the bitmap data to the
918 buffer, with a struct bitmap and the actual data immediately following.
919 Return value is the total size (struct + data). */
920 static int load_image(int fd, const char *path, struct bufopen_bitmap_data *data)
922 int rc;
923 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
924 struct dim *dim = data->dim;
925 struct mp3_albumart *aa = data->embedded_albumart;
927 /* get the desired image size */
928 bmp->width = dim->width, bmp->height = dim->height;
929 /* FIXME: alignment may be needed for the data buffer. */
930 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
931 #ifndef HAVE_JPEG
932 (void) path;
933 #endif
934 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
935 bmp->maskdata = NULL;
936 #endif
938 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
939 - sizeof(struct bitmap);
941 #ifdef HAVE_JPEG
942 if (aa != NULL)
944 lseek(fd, aa->pos, SEEK_SET);
945 rc = clip_jpeg_fd(fd, aa->size, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
946 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
948 else if (strcmp(path + strlen(path) - 4, ".bmp"))
949 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
950 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
951 else
952 #endif
953 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
954 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
955 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
957 #endif
961 MAIN BUFFERING API CALLS
962 ========================
964 bufopen : Request the opening of a new handle for a file
965 bufalloc : Open a new handle for data other than a file.
966 bufclose : Close an open handle
967 bufseek : Set the read pointer in a handle
968 bufadvance : Move the read pointer in a handle
969 bufread : Copy data from a handle into a given buffer
970 bufgetdata : Give a pointer to the handle's data
972 These functions are exported, to allow interaction with the buffer.
973 They take care of the content of the structs, and rely on the linked list
974 management functions for all the actual handle management work.
978 /* Reserve space in the buffer for a file.
979 filename: name of the file to open
980 offset: offset at which to start buffering the file, useful when the first
981 (offset-1) bytes of the file aren't needed.
982 type: one of the data types supported (audio, image, cuesheet, others
983 user_data: user data passed possibly passed in subcalls specific to a
984 data_type (only used for image (albumart) buffering so far )
985 return value: <0 if the file cannot be opened, or one file already
986 queued to be opened, otherwise the handle for the file in the buffer
988 int bufopen(const char *file, size_t offset, enum data_type type,
989 void *user_data)
991 #ifndef HAVE_ALBUMART
992 /* currently only used for aa loading */
993 (void)user_data;
994 #endif
995 if (type == TYPE_ID3)
997 /* ID3 case: allocate space, init the handle and return. */
999 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
1000 if (!h)
1001 return ERR_BUFFER_FULL;
1003 h->fd = -1;
1004 h->filesize = sizeof(struct mp3entry);
1005 h->filerem = sizeof(struct mp3entry);
1006 h->offset = 0;
1007 h->data = buf_widx;
1008 h->ridx = buf_widx;
1009 h->widx = buf_widx;
1010 h->available = 0;
1011 h->type = type;
1012 strlcpy(h->path, file, MAX_PATH);
1014 buf_widx += sizeof(struct mp3entry); /* safe because the handle
1015 can't wrap */
1017 /* Inform the buffering thread that we added a handle */
1018 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1019 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1021 return h->id;
1023 #ifdef APPLICATION
1024 /* loading code from memory is not supported in application builds */
1025 else if (type == TYPE_CODEC)
1026 return ERR_UNSUPPORTED_TYPE;
1027 #endif
1028 /* Other cases: there is a little more work. */
1029 int fd = open(file, O_RDONLY);
1030 if (fd < 0)
1031 return ERR_FILE_ERROR;
1033 size_t size = 0;
1034 #ifdef HAVE_ALBUMART
1035 if (type == TYPE_BITMAP)
1036 { /* if albumart is embedded, the complete file is not buffered,
1037 * but only the jpeg part; filesize() would be wrong */
1038 struct bufopen_bitmap_data *aa = (struct bufopen_bitmap_data*)user_data;
1039 if (aa->embedded_albumart)
1040 size = aa->embedded_albumart->size;
1042 #endif
1043 if (size == 0)
1044 size = filesize(fd);
1045 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
1047 size_t adjusted_offset = offset;
1048 if (adjusted_offset > size)
1049 adjusted_offset = 0;
1051 /* Reserve extra space because alignment can move data forward */
1052 size_t padded_size = STORAGE_PAD(size-adjusted_offset);
1053 struct memory_handle *h = add_handle(padded_size, can_wrap, false);
1054 if (!h)
1056 DEBUGF("%s(): failed to add handle\n", __func__);
1057 close(fd);
1058 return ERR_BUFFER_FULL;
1061 strlcpy(h->path, file, MAX_PATH);
1062 h->offset = adjusted_offset;
1064 /* Don't bother to storage align bitmaps because they are not
1065 * loaded directly into the buffer.
1067 if (type != TYPE_BITMAP)
1069 size_t alignment_pad;
1071 /* Remember where data area starts, for use by reset_handle */
1072 h->start = buf_widx;
1074 /* Align to desired storage alignment */
1075 alignment_pad = STORAGE_OVERLAP(adjusted_offset - (size_t)(&buffer[buf_widx]));
1076 buf_widx = ringbuf_add(buf_widx, alignment_pad);
1079 h->ridx = buf_widx;
1080 h->widx = buf_widx;
1081 h->data = buf_widx;
1082 h->available = 0;
1083 h->filerem = 0;
1084 h->type = type;
1086 #ifdef HAVE_ALBUMART
1087 if (type == TYPE_BITMAP)
1089 /* Bitmap file: we load the data instead of the file */
1090 int rc;
1091 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1092 rc = load_image(fd, file, (struct bufopen_bitmap_data*)user_data);
1093 mutex_unlock(&llist_mod_mutex);
1094 if (rc <= 0)
1096 rm_handle(h);
1097 close(fd);
1098 return ERR_FILE_ERROR;
1100 h->filerem = 0;
1101 h->filesize = rc;
1102 h->available = rc;
1103 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1104 buf_widx += rc; /* safe too */
1106 else
1107 #endif
1109 h->filerem = size - adjusted_offset;
1110 h->filesize = size;
1111 h->available = 0;
1112 h->widx = buf_widx;
1115 if (type == TYPE_CUESHEET) {
1116 h->fd = fd;
1117 /* Immediately start buffering those */
1118 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1119 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1120 } else {
1121 /* Other types will get buffered in the course of normal operations */
1122 h->fd = -1;
1123 close(fd);
1125 /* Inform the buffering thread that we added a handle */
1126 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1127 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1130 logf("bufopen: new hdl %d", h->id);
1131 return h->id;
1134 /* Open a new handle from data that needs to be copied from memory.
1135 src is the source buffer from which to copy data. It can be NULL to simply
1136 reserve buffer space.
1137 size is the requested size. The call will only be successful if the
1138 requested amount of data can entirely fit in the buffer without wrapping.
1139 Return value is the handle id for success or <0 for failure.
1141 int bufalloc(const void *src, size_t size, enum data_type type)
1143 struct memory_handle *h = add_handle(size, false, true);
1145 if (!h)
1146 return ERR_BUFFER_FULL;
1148 if (src) {
1149 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1150 /* specially take care of struct mp3entry */
1151 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1152 (const struct mp3entry *)src);
1153 } else {
1154 memcpy(&buffer[buf_widx], src, size);
1158 h->fd = -1;
1159 *h->path = 0;
1160 h->filesize = size;
1161 h->filerem = 0;
1162 h->offset = 0;
1163 h->ridx = buf_widx;
1164 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1165 h->data = buf_widx;
1166 h->available = size;
1167 h->type = type;
1169 buf_widx += size; /* safe too */
1171 logf("bufalloc: new hdl %d", h->id);
1172 return h->id;
1175 /* Close the handle. Return true for success and false for failure */
1176 bool bufclose(int handle_id)
1178 logf("bufclose(%d)", handle_id);
1180 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1181 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1184 /* Set reading index in handle (relatively to the start of the file).
1185 Access before the available data will trigger a rebuffer.
1186 Return 0 for success and < 0 for failure:
1187 -1 if the handle wasn't found
1188 -2 if the new requested position was beyond the end of the file
1190 int bufseek(int handle_id, size_t newpos)
1192 struct memory_handle *h = find_handle(handle_id);
1193 if (!h)
1194 return ERR_HANDLE_NOT_FOUND;
1196 if (newpos > h->filesize) {
1197 /* access beyond the end of the file */
1198 return ERR_INVALID_VALUE;
1200 else if (newpos < h->offset || h->offset + h->available < newpos) {
1201 /* access before or after buffered data. A rebuffer is needed. */
1202 rebuffer_handle(handle_id, newpos);
1204 else {
1205 h->ridx = ringbuf_add(h->data, newpos - h->offset);
1207 return 0;
1210 /* Advance the reading index in a handle (relatively to its current position).
1211 Return 0 for success and < 0 for failure */
1212 int bufadvance(int handle_id, off_t offset)
1214 const struct memory_handle *h = find_handle(handle_id);
1215 if (!h)
1216 return ERR_HANDLE_NOT_FOUND;
1218 size_t newpos = h->offset + ringbuf_sub(h->ridx, h->data) + offset;
1219 return bufseek(handle_id, newpos);
1222 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1223 * actual amount of data available for reading. This function explicitly
1224 * does not check the validity of the input handle. It does do range checks
1225 * on size and returns a valid (and explicit) amount of data for reading */
1226 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1227 bool guardbuf_limit)
1229 struct memory_handle *h = find_handle(handle_id);
1230 if (!h)
1231 return NULL;
1233 size_t avail = ringbuf_sub(h->widx, h->ridx);
1235 if (avail == 0 && h->filerem == 0)
1237 /* File is finished reading */
1238 *size = 0;
1239 return h;
1242 if (*size == 0 || *size > avail + h->filerem)
1243 *size = avail + h->filerem;
1245 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1247 logf("data request > guardbuf");
1248 /* If more than the size of the guardbuf is requested and this is a
1249 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1250 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1251 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1254 if (h->filerem > 0 && avail < *size)
1256 /* Data isn't ready. Request buffering */
1257 buf_request_buffer_handle(handle_id);
1258 /* Wait for the data to be ready */
1261 sleep(1);
1262 /* it is not safe for a non-buffering thread to sleep while
1263 * holding a handle */
1264 h = find_handle(handle_id);
1265 if (!h)
1266 return NULL;
1267 avail = ringbuf_sub(h->widx, h->ridx);
1269 while (h->filerem > 0 && avail < *size);
1272 *size = MIN(*size,avail);
1273 return h;
1276 /* Copy data from the given handle to the dest buffer.
1277 Return the number of bytes copied or < 0 for failure (handle not found).
1278 The caller is blocked until the requested amount of data is available.
1280 ssize_t bufread(int handle_id, size_t size, void *dest)
1282 const struct memory_handle *h;
1283 size_t adjusted_size = size;
1285 h = prep_bufdata(handle_id, &adjusted_size, false);
1286 if (!h)
1287 return ERR_HANDLE_NOT_FOUND;
1289 if (h->ridx + adjusted_size > buffer_len)
1291 /* the data wraps around the end of the buffer */
1292 size_t read = buffer_len - h->ridx;
1293 memcpy(dest, &buffer[h->ridx], read);
1294 memcpy(dest+read, buffer, adjusted_size - read);
1296 else
1298 memcpy(dest, &buffer[h->ridx], adjusted_size);
1301 return adjusted_size;
1304 /* Update the "data" pointer to make the handle's data available to the caller.
1305 Return the length of the available linear data or < 0 for failure (handle
1306 not found).
1307 The caller is blocked until the requested amount of data is available.
1308 size is the amount of linear data requested. it can be 0 to get as
1309 much as possible.
1310 The guard buffer may be used to provide the requested size. This means it's
1311 unsafe to request more than the size of the guard buffer.
1313 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1315 const struct memory_handle *h;
1316 size_t adjusted_size = size;
1318 h = prep_bufdata(handle_id, &adjusted_size, true);
1319 if (!h)
1320 return ERR_HANDLE_NOT_FOUND;
1322 if (h->ridx + adjusted_size > buffer_len)
1324 /* the data wraps around the end of the buffer :
1325 use the guard buffer to provide the requested amount of data. */
1326 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1327 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1328 so copy_n <= GUARD_BUFSIZE */
1329 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1332 if (data)
1333 *data = &buffer[h->ridx];
1335 return adjusted_size;
1338 ssize_t bufgettail(int handle_id, size_t size, void **data)
1340 size_t tidx;
1342 const struct memory_handle *h;
1344 h = find_handle(handle_id);
1346 if (!h)
1347 return ERR_HANDLE_NOT_FOUND;
1349 if (h->filerem)
1350 return ERR_HANDLE_NOT_DONE;
1352 /* We don't support tail requests of > guardbuf_size, for simplicity */
1353 if (size > GUARD_BUFSIZE)
1354 return ERR_INVALID_VALUE;
1356 tidx = ringbuf_sub(h->widx, size);
1358 if (tidx + size > buffer_len)
1360 size_t copy_n = tidx + size - buffer_len;
1361 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1364 *data = &buffer[tidx];
1365 return size;
1368 ssize_t bufcuttail(int handle_id, size_t size)
1370 struct memory_handle *h;
1371 size_t adjusted_size = size;
1373 h = find_handle(handle_id);
1375 if (!h)
1376 return ERR_HANDLE_NOT_FOUND;
1378 if (h->filerem)
1379 return ERR_HANDLE_NOT_DONE;
1381 if (h->available < adjusted_size)
1382 adjusted_size = h->available;
1384 h->available -= adjusted_size;
1385 h->filesize -= adjusted_size;
1386 h->widx = ringbuf_sub(h->widx, adjusted_size);
1387 if (h == cur_handle)
1388 buf_widx = h->widx;
1390 return adjusted_size;
1395 SECONDARY EXPORTED FUNCTIONS
1396 ============================
1398 buf_get_offset
1399 buf_handle_offset
1400 buf_request_buffer_handle
1401 buf_set_base_handle
1402 buf_used
1403 register_buffering_callback
1404 unregister_buffering_callback
1406 These functions are exported, to allow interaction with the buffer.
1407 They take care of the content of the structs, and rely on the linked list
1408 management functions for all the actual handle management work.
1411 /* Get a handle offset from a pointer */
1412 ssize_t buf_get_offset(int handle_id, void *ptr)
1414 const struct memory_handle *h = find_handle(handle_id);
1415 if (!h)
1416 return ERR_HANDLE_NOT_FOUND;
1418 return (size_t)ptr - (size_t)&buffer[h->ridx];
1421 ssize_t buf_handle_offset(int handle_id)
1423 const struct memory_handle *h = find_handle(handle_id);
1424 if (!h)
1425 return ERR_HANDLE_NOT_FOUND;
1426 return h->offset;
1429 void buf_request_buffer_handle(int handle_id)
1431 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1432 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1435 void buf_set_base_handle(int handle_id)
1437 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1438 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1441 /* Return the amount of buffer space used */
1442 size_t buf_used(void)
1444 return BUF_USED;
1447 void buf_set_watermark(size_t bytes)
1449 conf_watermark = bytes;
1452 static void shrink_buffer_inner(struct memory_handle *h)
1454 if (h == NULL)
1455 return;
1457 shrink_buffer_inner(h->next);
1459 shrink_handle(h);
1462 static void shrink_buffer(void)
1464 logf("shrink_buffer()");
1465 shrink_buffer_inner(first_handle);
1468 void buffering_thread(void)
1470 bool filling = false;
1471 struct queue_event ev;
1473 while (true)
1475 if (!filling) {
1476 cancel_cpu_boost();
1479 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1481 switch (ev.id)
1483 case Q_START_FILL:
1484 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1485 /* Call buffer callbacks here because this is one of two ways
1486 * to begin a full buffer fill */
1487 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1488 shrink_buffer();
1489 queue_reply(&buffering_queue, 1);
1490 filling |= buffer_handle((int)ev.data);
1491 break;
1493 case Q_BUFFER_HANDLE:
1494 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1495 queue_reply(&buffering_queue, 1);
1496 buffer_handle((int)ev.data);
1497 break;
1499 case Q_RESET_HANDLE:
1500 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1501 queue_reply(&buffering_queue, 1);
1502 reset_handle((int)ev.data);
1503 break;
1505 case Q_CLOSE_HANDLE:
1506 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1507 queue_reply(&buffering_queue, close_handle((int)ev.data));
1508 break;
1510 case Q_HANDLE_ADDED:
1511 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1512 /* A handle was added: the disk is spinning, so we can fill */
1513 filling = true;
1514 break;
1516 case Q_BASE_HANDLE:
1517 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1518 base_handle_id = (int)ev.data;
1519 break;
1521 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
1522 case SYS_USB_CONNECTED:
1523 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1524 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1525 usb_wait_for_disconnect(&buffering_queue);
1526 break;
1527 #endif
1529 case SYS_TIMEOUT:
1530 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1531 break;
1534 update_data_counters();
1536 /* If the buffer is low, call the callbacks to get new data */
1537 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1538 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1540 #if 0
1541 /* TODO: This needs to be fixed to use the idle callback, disable it
1542 * for simplicity until its done right */
1543 #if MEMORYSIZE > 8
1544 /* If the disk is spinning, take advantage by filling the buffer */
1545 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1547 if (num_handles > 0 && data_counters.useful <= high_watermark)
1548 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1550 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1552 /* This is a new fill, shrink the buffer up first */
1553 if (!filling)
1554 shrink_buffer();
1555 filling = fill_buffer();
1556 update_data_counters();
1559 #endif
1560 #endif
1562 if (queue_empty(&buffering_queue)) {
1563 if (filling) {
1564 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1565 filling = fill_buffer();
1566 else if (data_counters.remaining == 0)
1567 filling = false;
1569 else if (ev.id == SYS_TIMEOUT)
1571 if (data_counters.remaining > 0 &&
1572 data_counters.useful <= conf_watermark) {
1573 shrink_buffer();
1574 filling = fill_buffer();
1581 void buffering_init(void)
1583 mutex_init(&llist_mutex);
1584 mutex_init(&llist_mod_mutex);
1585 #ifdef HAVE_PRIORITY_SCHEDULING
1586 /* This behavior not safe atm */
1587 mutex_set_preempt(&llist_mutex, false);
1588 mutex_set_preempt(&llist_mod_mutex, false);
1589 #endif
1591 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1593 queue_init(&buffering_queue, true);
1594 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1595 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1596 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1597 IF_COP(, CPU));
1599 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1600 buffering_thread_id);
1603 /* Initialise the buffering subsystem */
1604 bool buffering_reset(char *buf, size_t buflen)
1606 /* Wraps of storage-aligned data must also be storage aligned,
1607 thus buf and buflen must be a aligned to an integer multiple of
1608 the storage alignment */
1609 STORAGE_ALIGN_BUFFER(buf, buflen);
1611 if (!buf || !buflen)
1612 return false;
1614 buffer = buf;
1615 buffer_len = buflen;
1616 guard_buffer = buf + buflen;
1618 buf_widx = 0;
1619 buf_ridx = 0;
1621 first_handle = NULL;
1622 cur_handle = NULL;
1623 cached_handle = NULL;
1624 num_handles = 0;
1625 base_handle_id = -1;
1627 /* Set the high watermark as 75% full...or 25% empty :) */
1628 #if MEMORYSIZE > 8
1629 high_watermark = 3*buflen / 4;
1630 #endif
1632 thread_thaw(buffering_thread_id);
1634 return true;
1637 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1639 update_data_counters();
1640 dbgdata->num_handles = num_handles;
1641 dbgdata->data_rem = data_counters.remaining;
1642 dbgdata->wasted_space = data_counters.wasted;
1643 dbgdata->buffered_data = data_counters.buffered;
1644 dbgdata->useful_data = data_counters.useful;
1645 dbgdata->watermark = conf_watermark;