Bring Gigabeat S bootloader one step close to a release version.
[kugel-rb.git] / apps / buffering.c
blob84a6fca3d679b5c63a9cbac9106575e77482133a
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2007 Nicolas Pennequin
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 #include "config.h"
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include "buffering.h"
27 #include "ata.h"
28 #include "system.h"
29 #include "thread.h"
30 #include "file.h"
31 #include "panic.h"
32 #include "memory.h"
33 #include "lcd.h"
34 #include "font.h"
35 #include "button.h"
36 #include "kernel.h"
37 #include "tree.h"
38 #include "debug.h"
39 #include "sprintf.h"
40 #include "settings.h"
41 #include "codecs.h"
42 #include "audio.h"
43 #include "mp3_playback.h"
44 #include "usb.h"
45 #include "status.h"
46 #include "screens.h"
47 #include "playlist.h"
48 #include "pcmbuf.h"
49 #include "buffer.h"
50 #include "bmp.h"
51 #include "events.h"
52 #include "metadata.h"
54 #if MEM > 1
55 #define GUARD_BUFSIZE (32*1024)
56 #else
57 #define GUARD_BUFSIZE (8*1024)
58 #endif
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*512)
87 /* amount of data to read in one read() call */
88 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
89 /* point at which the file buffer will fight for CPU time */
90 #define BUFFERING_CRITICAL_LEVEL (1024*128)
92 #define BUF_HANDLE_MASK 0x7FFFFFFF
95 /* Ring buffer helper macros */
96 /* Buffer pointer (p) plus value (v), wrapped if necessary */
97 #define RINGBUF_ADD(p,v) (((p)+(v))<buffer_len ? (p)+(v) : (p)+(v)-buffer_len)
98 /* Buffer pointer (p) minus value (v), wrapped if necessary */
99 #define RINGBUF_SUB(p,v) ((p>=v) ? (p)-(v) : (p)+buffer_len-(v))
100 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
101 #define RINGBUF_ADD_CROSS(p1,v,p2) \
102 ((p1<p2) ? (int)((p1)+(v))-(int)(p2) : (int)((p1)+(v)-(p2))-(int)buffer_len)
103 /* Bytes available in the buffer */
104 #define BUF_USED RINGBUF_SUB(buf_widx, buf_ridx)
106 /* assert(sizeof(struct memory_handle)%4==0) */
107 struct memory_handle {
108 int id; /* A unique ID for the handle */
109 enum data_type type; /* Type of data buffered with this handle */
110 char path[MAX_PATH]; /* Path if data originated in a file */
111 int fd; /* File descriptor to path (-1 if closed) */
112 size_t data; /* Start index of the handle's data buffer */
113 volatile size_t ridx; /* Read pointer, relative to the main buffer */
114 size_t widx; /* Write pointer */
115 size_t filesize; /* File total length */
116 size_t filerem; /* Remaining bytes of file NOT in buffer */
117 volatile size_t available; /* Available bytes to read from buffer */
118 size_t offset; /* Offset at which we started reading the file */
119 struct memory_handle *next;
121 /* invariant: filesize == offset + available + filerem */
123 static char *buffer;
124 static char *guard_buffer;
126 static size_t buffer_len;
128 static volatile size_t buf_widx; /* current writing position */
129 static volatile size_t buf_ridx; /* current reading position */
130 /* buf_*idx are values relative to the buffer, not real pointers. */
132 /* Configuration */
133 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
134 #if MEM > 8
135 static size_t high_watermark = 0; /* High watermark for rebuffer */
136 #endif
138 /* current memory handle in the linked list. NULL when the list is empty. */
139 static struct memory_handle *cur_handle;
140 /* first memory handle in the linked list. NULL when the list is empty. */
141 static struct memory_handle *first_handle;
143 static int num_handles; /* number of handles in the list */
145 static int base_handle_id;
147 static struct mutex llist_mutex;
149 /* Handle cache (makes find_handle faster).
150 This is global so that move_handle and rm_handle can invalidate it. */
151 static struct memory_handle *cached_handle = NULL;
153 static struct {
154 size_t remaining; /* Amount of data needing to be buffered */
155 size_t wasted; /* Amount of space available for freeing */
156 size_t buffered; /* Amount of data currently in the buffer */
157 size_t useful; /* Amount of data still useful to the user */
158 } data_counters;
161 /* Messages available to communicate with the buffering thread */
162 enum {
163 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
164 used in a low buffer situation. */
165 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
166 offset (the offset has to be set beforehand) */
167 Q_CLOSE_HANDLE, /* Request closing a handle */
168 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
170 /* Configuration: */
171 Q_SET_WATERMARK,
172 Q_START_FILL, /* Request that the buffering thread initiate a buffer
173 fill at its earliest convenience */
174 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
175 (which means the disk is spinning) */
178 /* Buffering thread */
179 static void buffering_thread(void);
180 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
181 static const char buffering_thread_name[] = "buffering";
182 static struct thread_entry *buffering_thread_p;
183 static struct event_queue buffering_queue;
184 static struct queue_sender_list buffering_queue_sender_list;
189 LINKED LIST MANAGEMENT
190 ======================
192 add_handle : Add a handle to the list
193 rm_handle : Remove a handle from the list
194 find_handle : Get a handle pointer from an ID
195 move_handle : Move a handle in the buffer (with or without its data)
197 These functions only handle the linked list structure. They don't touch the
198 contents of the struct memory_handle headers. They also change the buf_*idx
199 pointers when necessary and manage the handle IDs.
201 The first and current (== last) handle are kept track of.
202 A new handle is added at buf_widx and becomes the current one.
203 buf_widx always points to the current writing position for the current handle
204 buf_ridx always points to the location of the first handle.
205 buf_ridx == buf_widx means the buffer is empty.
209 /* Add a new handle to the linked list and return it. It will have become the
210 new current handle.
211 data_size must contain the size of what will be in the handle.
212 can_wrap tells us whether this type of data may wrap on buffer
213 alloc_all tells us if we must immediately be able to allocate data_size
214 returns a valid memory handle if all conditions for allocation are met.
215 NULL if there memory_handle itself cannot be allocated or if the
216 data_size cannot be allocated and alloc_all is set. This function's
217 only potential side effect is to allocate space for the cur_handle
218 if it returns NULL.
220 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
221 bool alloc_all)
223 /* gives each handle a unique id */
224 static int cur_handle_id = 0;
225 size_t shift;
226 size_t new_widx;
227 size_t len;
228 int overlap;
230 if (num_handles >= BUF_MAX_HANDLES)
231 return NULL;
233 mutex_lock(&llist_mutex);
235 if (cur_handle && cur_handle->filerem > 0) {
236 /* the current handle hasn't finished buffering. We can only add
237 a new one if there is already enough free space to finish
238 the buffering. */
239 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
240 if (RINGBUF_ADD_CROSS(cur_handle->widx, req, buf_ridx) >= 0) {
241 /* Not enough space */
242 mutex_unlock(&llist_mutex);
243 return NULL;
244 } else {
245 /* Allocate the remainder of the space for the current handle */
246 buf_widx = RINGBUF_ADD(cur_handle->widx, cur_handle->filerem);
250 /* align to 4 bytes up */
251 new_widx = RINGBUF_ADD(buf_widx, 3) & ~3;
253 len = data_size + sizeof(struct memory_handle);
255 /* First, will the handle wrap? */
256 overlap = RINGBUF_ADD_CROSS(new_widx, sizeof(struct memory_handle),
257 buffer_len - 1);
258 /* If the handle would wrap, move to the beginning of the buffer,
259 * otherwise check if the data can/would wrap and move it to the
260 * beginning if needed */
261 if (overlap > 0) {
262 new_widx = 0;
263 } else if (!can_wrap) {
264 overlap = RINGBUF_ADD_CROSS(new_widx, len, buffer_len - 1);
265 if (overlap > 0)
266 new_widx += data_size - overlap;
269 /* How far we shifted buf_widx to align things, must be < buffer_len */
270 shift = RINGBUF_SUB(new_widx, buf_widx);
272 /* How much space are we short in the actual ring buffer? */
273 overlap = RINGBUF_ADD_CROSS(buf_widx, shift + len, buf_ridx);
274 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
275 /* Not enough space for required allocations */
276 mutex_unlock(&llist_mutex);
277 return NULL;
280 /* There is enough space for the required data, advance the buf_widx and
281 * initialize the struct */
282 buf_widx = new_widx;
284 struct memory_handle *new_handle =
285 (struct memory_handle *)(&buffer[buf_widx]);
287 /* only advance the buffer write index of the size of the struct */
288 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
290 new_handle->id = cur_handle_id;
291 /* Wrap signed int is safe and 0 doesn't happen */
292 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
293 new_handle->next = NULL;
294 num_handles++;
296 if (!first_handle)
297 /* the new handle is the first one */
298 first_handle = new_handle;
300 if (cur_handle)
301 cur_handle->next = new_handle;
303 cur_handle = new_handle;
305 mutex_unlock(&llist_mutex);
306 return new_handle;
309 /* Delete a given memory handle from the linked list
310 and return true for success. Nothing is actually erased from memory. */
311 static bool rm_handle(const struct memory_handle *h)
313 if (h == NULL)
314 return true;
316 mutex_lock(&llist_mutex);
318 if (h == first_handle) {
319 first_handle = h->next;
320 if (h == cur_handle) {
321 /* h was the first and last handle: the buffer is now empty */
322 cur_handle = NULL;
323 buf_ridx = buf_widx = 0;
324 } else {
325 /* update buf_ridx to point to the new first handle */
326 buf_ridx = (void *)first_handle - (void *)buffer;
328 } else {
329 struct memory_handle *m = first_handle;
330 /* Find the previous handle */
331 while (m && m->next != h) {
332 m = m->next;
334 if (m && m->next == h) {
335 m->next = h->next;
336 if (h == cur_handle) {
337 cur_handle = m;
338 buf_widx = cur_handle->widx;
340 } else {
341 mutex_unlock(&llist_mutex);
342 return false;
346 /* Invalidate the cache to prevent it from keeping the old location of h */
347 if (h == cached_handle)
348 cached_handle = NULL;
350 num_handles--;
352 mutex_unlock(&llist_mutex);
353 return true;
356 /* Return a pointer to the memory handle of given ID.
357 NULL if the handle wasn't found */
358 static struct memory_handle *find_handle(int handle_id)
360 if (handle_id < 0)
361 return NULL;
363 mutex_lock(&llist_mutex);
365 /* simple caching because most of the time the requested handle
366 will either be the same as the last, or the one after the last */
367 if (cached_handle)
369 if (cached_handle->id == handle_id) {
370 mutex_unlock(&llist_mutex);
371 return cached_handle;
372 } else if (cached_handle->next &&
373 (cached_handle->next->id == handle_id)) {
374 cached_handle = cached_handle->next;
375 mutex_unlock(&llist_mutex);
376 return cached_handle;
380 struct memory_handle *m = first_handle;
381 while (m && m->id != handle_id) {
382 m = m->next;
384 /* This condition can only be reached with !m or m->id == handle_id */
385 if (m)
386 cached_handle = m;
388 mutex_unlock(&llist_mutex);
389 return m;
392 /* Move a memory handle and data_size of its data delta bytes along the buffer.
393 delta maximum bytes available to move the handle. If the move is performed
394 it is set to the actual distance moved.
395 data_size is the amount of data to move along with the struct.
396 returns a valid memory_handle if the move is successful
397 NULL if the handle is NULL, the move would be less than the size of
398 a memory_handle after correcting for wraps or if the handle is not
399 found in the linked list for adjustment. This function has no side
400 effects if NULL is returned. */
401 static bool move_handle(struct memory_handle **h, size_t *delta,
402 size_t data_size, bool can_wrap)
404 struct memory_handle *dest;
405 const struct memory_handle *src;
406 size_t newpos;
407 size_t size_to_move;
408 size_t final_delta = *delta;
409 int overlap;
411 if (h == NULL || (src = *h) == NULL)
412 return false;
414 size_to_move = sizeof(struct memory_handle) + data_size;
416 /* Align to four bytes, down */
417 final_delta &= ~3;
418 if (final_delta < sizeof(struct memory_handle)) {
419 /* It's not legal to move less than the size of the struct */
420 return false;
423 mutex_lock(&llist_mutex);
425 newpos = RINGBUF_ADD((void *)src - (void *)buffer, final_delta);
426 overlap = RINGBUF_ADD_CROSS(newpos, size_to_move, buffer_len - 1);
428 if (overlap > 0) {
429 /* Some part of the struct + data would wrap, maybe ok */
430 size_t correction = 0;
431 /* If the overlap lands inside the memory_handle */
432 if ((unsigned)overlap > data_size) {
433 /* Correct the position and real delta to prevent the struct from
434 * wrapping, this guarantees an aligned delta, I think */
435 correction = overlap - data_size;
436 } else if (!can_wrap) {
437 /* Otherwise the overlap falls in the data area and must all be
438 * backed out. This may become conditional if ever we move
439 * data that is allowed to wrap (ie audio) */
440 correction = overlap;
441 /* Align correction to four bytes, up */
442 correction = (correction+3) & ~3;
444 if (correction) {
445 if (final_delta < correction + sizeof(struct memory_handle)) {
446 /* Delta cannot end up less than the size of the struct */
447 mutex_unlock(&llist_mutex);
448 return false;
451 newpos -= correction;
452 overlap -= correction;/* Used below to know how to split the data */
453 final_delta -= correction;
457 dest = (struct memory_handle *)(&buffer[newpos]);
459 if (src == first_handle) {
460 first_handle = dest;
461 buf_ridx = newpos;
462 } else {
463 struct memory_handle *m = first_handle;
464 while (m && m->next != src) {
465 m = m->next;
467 if (m && m->next == src) {
468 m->next = dest;
469 } else {
470 mutex_unlock(&llist_mutex);
471 return false;
476 /* Update the cache to prevent it from keeping the old location of h */
477 if (src == cached_handle)
478 cached_handle = dest;
480 /* the cur_handle pointer might need updating */
481 if (src == cur_handle)
482 cur_handle = dest;
484 if (overlap > 0) {
485 size_t first_part = size_to_move - overlap;
486 memmove(dest, src, first_part);
487 memmove(buffer, (const char *)src + first_part, overlap);
488 } else {
489 memmove(dest, src, size_to_move);
492 /* Update the caller with the new location of h and the distance moved */
493 *h = dest;
494 *delta = final_delta;
495 mutex_unlock(&llist_mutex);
496 return dest;
501 BUFFER SPACE MANAGEMENT
502 =======================
504 update_data_counters: Updates the values in data_counters
505 buffer_is_low : Returns true if the amount of useful data in the buffer is low
506 buffer_handle : Buffer data for a handle
507 reset_handle : Reset write position and data buffer of a handle to its offset
508 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
509 shrink_handle : Free buffer space by moving a handle
510 fill_buffer : Call buffer_handle for all handles that have data to buffer
512 These functions are used by the buffering thread to manage buffer space.
515 static void update_data_counters(void)
517 struct memory_handle *m = find_handle(base_handle_id);
518 bool is_useful = m==NULL;
520 size_t buffered = 0;
521 size_t wasted = 0;
522 size_t remaining = 0;
523 size_t useful = 0;
525 m = first_handle;
526 while (m) {
527 buffered += m->available;
528 wasted += RINGBUF_SUB(m->ridx, m->data);
529 remaining += m->filerem;
531 if (m->id == base_handle_id)
532 is_useful = true;
534 if (is_useful)
535 useful += RINGBUF_SUB(m->widx, m->ridx);
537 m = m->next;
540 data_counters.buffered = buffered;
541 data_counters.wasted = wasted;
542 data_counters.remaining = remaining;
543 data_counters.useful = useful;
546 static inline bool buffer_is_low(void)
548 update_data_counters();
549 return data_counters.useful < BUFFERING_CRITICAL_LEVEL;
552 /* Buffer data for the given handle.
553 Return whether or not the buffering should continue explicitly. */
554 static bool buffer_handle(int handle_id)
556 logf("buffer_handle(%d)", handle_id);
557 struct memory_handle *h = find_handle(handle_id);
558 if (!h)
559 return true;
561 if (h->filerem == 0) {
562 /* nothing left to buffer */
563 return true;
566 if (h->fd < 0) /* file closed, reopen */
568 if (*h->path)
569 h->fd = open(h->path, O_RDONLY);
571 if (h->fd < 0)
573 /* could not open the file, truncate it where it is */
574 h->filesize -= h->filerem;
575 h->filerem = 0;
576 return true;
579 if (h->offset)
580 lseek(h->fd, h->offset, SEEK_SET);
583 trigger_cpu_boost();
585 if (h->type == TYPE_ID3)
587 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
589 /* metadata parsing failed: clear the buffer. */
590 memset(buffer + h->data, 0, sizeof(struct mp3entry));
592 close(h->fd);
593 h->fd = -1;
594 h->filerem = 0;
595 h->available = sizeof(struct mp3entry);
596 h->widx += sizeof(struct mp3entry);
597 send_event(EVENT_HANDLE_FINISHED, &h->id);
598 return true;
601 while (h->filerem > 0)
603 /* max amount to copy */
604 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
605 buffer_len - h->widx);
607 /* stop copying if it would overwrite the reading position */
608 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
609 return false;
611 /* This would read into the next handle, this is broken */
612 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
613 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
614 /* Try to recover by truncating this file */
615 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
616 (unsigned)((void *)h->next - (void *)buffer));
617 h->filerem -= copy_n;
618 h->filesize -= copy_n;
619 logf("buf alloc short %ld", (long)copy_n);
620 if (h->filerem)
621 continue;
622 else
623 break;
626 /* rc is the actual amount read */
627 int rc = read(h->fd, &buffer[h->widx], copy_n);
629 if (rc < 0)
631 /* Some kind of filesystem error, maybe recoverable if not codec */
632 if (h->type == TYPE_CODEC) {
633 logf("Partial codec");
634 break;
637 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
638 h->filesize -= h->filerem;
639 h->filerem = 0;
640 break;
643 /* Advance buffer */
644 h->widx = RINGBUF_ADD(h->widx, rc);
645 if (h == cur_handle)
646 buf_widx = h->widx;
647 h->available += rc;
648 h->filerem -= rc;
650 /* If this is a large file, see if we need to break or give the codec
651 * more time */
652 if (h->type == TYPE_PACKET_AUDIO &&
653 pcmbuf_is_lowdata() && !buffer_is_low())
655 sleep(1);
657 else
659 yield();
662 if (!queue_empty(&buffering_queue))
663 break;
666 if (h->filerem == 0) {
667 /* finished buffering the file */
668 close(h->fd);
669 h->fd = -1;
670 send_event(EVENT_HANDLE_FINISHED, &h->id);
673 return true;
676 /* Reset writing position and data buffer of a handle to its current offset.
677 Use this after having set the new offset to use. */
678 static void reset_handle(int handle_id)
680 logf("reset_handle(%d)", handle_id);
682 struct memory_handle *h = find_handle(handle_id);
683 if (!h)
684 return;
686 h->widx = h->data;
687 if (h == cur_handle)
688 buf_widx = h->widx;
689 h->available = 0;
690 h->filerem = h->filesize - h->offset;
692 if (h->fd >= 0) {
693 lseek(h->fd, h->offset, SEEK_SET);
697 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
698 static void rebuffer_handle(int handle_id, size_t newpos)
700 struct memory_handle *h = find_handle(handle_id);
701 if (!h)
702 return;
704 /* When seeking foward off of the buffer, if it is a short seek don't
705 rebuffer the whole track, just read enough to satisfy */
706 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
708 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
709 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
710 h->ridx = h->data + newpos;
711 return;
714 h->offset = newpos;
716 /* Reset the handle to its new offset */
717 LOGFQUEUE("buffering >| Q_RESET_HANDLE");
718 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
720 size_t next = (unsigned)((void *)h->next - (void *)buffer);
721 if (next - h->data < h->filesize - newpos)
723 /* There isn't enough space to rebuffer all of the track from its new
724 offset, so we ask the user to free some */
725 DEBUGF("rebuffer_handle: space is needed\n");
726 send_event(EVENT_HANDLE_REBUFFER, &handle_id);
729 /* Now we ask for a rebuffer */
730 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
731 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
733 h->ridx = h->data;
736 static bool close_handle(int handle_id)
738 struct memory_handle *h = find_handle(handle_id);
740 /* If the handle is not found, it is closed */
741 if (!h)
742 return true;
744 if (h->fd >= 0) {
745 close(h->fd);
746 h->fd = -1;
749 /* rm_handle returns true unless the handle somehow persists after exit */
750 return rm_handle(h);
753 /* Free buffer space by moving the handle struct right before the useful
754 part of its data buffer or by moving all the data. */
755 static void shrink_handle(struct memory_handle *h)
757 size_t delta;
759 if (!h)
760 return;
762 if (h->next && h->filerem == 0 &&
763 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
764 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
765 h->type == TYPE_ATOMIC_AUDIO))
767 /* metadata handle: we can move all of it */
768 size_t handle_distance =
769 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
770 delta = handle_distance - h->available;
772 /* The value of delta might change for alignment reasons */
773 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
774 return;
776 size_t olddata = h->data;
777 h->data = RINGBUF_ADD(h->data, delta);
778 h->ridx = RINGBUF_ADD(h->ridx, delta);
779 h->widx = RINGBUF_ADD(h->widx, delta);
781 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
782 /* when moving an mp3entry we need to readjust its pointers. */
783 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
784 (void *)&buffer[h->data],
785 (const void *)&buffer[olddata]);
786 } else if (h->type == TYPE_BITMAP) {
787 /* adjust the bitmap's pointer */
788 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
789 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
792 else
794 /* only move the handle struct */
795 delta = RINGBUF_SUB(h->ridx, h->data);
796 if (!move_handle(&h, &delta, 0, true))
797 return;
799 h->data = RINGBUF_ADD(h->data, delta);
800 h->available -= delta;
801 h->offset += delta;
805 /* Fill the buffer by buffering as much data as possible for handles that still
806 have data left to buffer
807 Return whether or not to continue filling after this */
808 static bool fill_buffer(void)
810 logf("fill_buffer()");
811 struct memory_handle *m = first_handle;
812 shrink_handle(m);
813 while (queue_empty(&buffering_queue) && m) {
814 if (m->filerem > 0) {
815 if (!buffer_handle(m->id)) {
816 m = NULL;
817 break;
820 m = m->next;
823 if (m) {
824 return true;
826 else
828 /* only spin the disk down if the filling wasn't interrupted by an
829 event arriving in the queue. */
830 ata_sleep();
831 return false;
835 #ifdef HAVE_ALBUMART
836 /* Given a file descriptor to a bitmap file, write the bitmap data to the
837 buffer, with a struct bitmap and the actual data immediately following.
838 Return value is the total size (struct + data). */
839 static int load_bitmap(int fd)
841 int rc;
842 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
843 /* FIXME: alignment may be needed for the data buffer. */
844 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
846 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
847 bmp->maskdata = NULL;
848 #endif
850 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx);
851 rc = read_bmp_fd(fd, bmp, free, FORMAT_ANY|FORMAT_DITHER);
852 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
854 #endif
858 MAIN BUFFERING API CALLS
859 ========================
861 bufopen : Request the opening of a new handle for a file
862 bufalloc : Open a new handle for data other than a file.
863 bufclose : Close an open handle
864 bufseek : Set the read pointer in a handle
865 bufadvance : Move the read pointer in a handle
866 bufread : Copy data from a handle into a given buffer
867 bufgetdata : Give a pointer to the handle's data
869 These functions are exported, to allow interaction with the buffer.
870 They take care of the content of the structs, and rely on the linked list
871 management functions for all the actual handle management work.
875 /* Reserve space in the buffer for a file.
876 filename: name of the file to open
877 offset: offset at which to start buffering the file, useful when the first
878 (offset-1) bytes of the file aren't needed.
879 return value: <0 if the file cannot be opened, or one file already
880 queued to be opened, otherwise the handle for the file in the buffer
882 int bufopen(const char *file, size_t offset, enum data_type type)
884 if (type == TYPE_ID3)
886 /* ID3 case: allocate space, init the handle and return. */
888 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
889 if (!h)
890 return ERR_BUFFER_FULL;
892 h->fd = -1;
893 h->filesize = sizeof(struct mp3entry);
894 h->filerem = sizeof(struct mp3entry);
895 h->offset = 0;
896 h->data = buf_widx;
897 h->ridx = buf_widx;
898 h->widx = buf_widx;
899 h->available = 0;
900 h->type = type;
901 strncpy(h->path, file, MAX_PATH);
903 buf_widx += sizeof(struct mp3entry); /* safe because the handle
904 can't wrap */
905 return h->id;
908 /* Other cases: there is a little more work. */
910 int fd = open(file, O_RDONLY);
911 if (fd < 0)
912 return ERR_FILE_ERROR;
914 size_t size = filesize(fd);
915 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
917 size_t adjusted_offset = offset;
918 if (adjusted_offset > size)
919 adjusted_offset = 0;
921 struct memory_handle *h = add_handle(size-adjusted_offset, can_wrap, false);
922 if (!h)
924 DEBUGF("bufopen: failed to add handle\n");
925 close(fd);
926 return ERR_BUFFER_FULL;
929 strncpy(h->path, file, MAX_PATH);
930 h->offset = adjusted_offset;
931 h->ridx = buf_widx;
932 h->data = buf_widx;
933 h->type = type;
935 #ifdef HAVE_ALBUMART
936 if (type == TYPE_BITMAP)
938 /* Bitmap file: we load the data instead of the file */
939 int rc;
940 mutex_lock(&llist_mutex); /* Lock because load_bitmap yields */
941 rc = load_bitmap(fd);
942 if (rc <= 0)
944 rm_handle(h);
945 close(fd);
946 mutex_unlock(&llist_mutex);
947 return ERR_FILE_ERROR;
949 h->filerem = 0;
950 h->filesize = rc;
951 h->available = rc;
952 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
953 buf_widx += rc; /* safe too */
954 mutex_unlock(&llist_mutex);
956 else
957 #endif
959 h->filerem = size - adjusted_offset;
960 h->filesize = size;
961 h->available = 0;
962 h->widx = buf_widx;
965 if (type == TYPE_CUESHEET) {
966 h->fd = fd;
967 /* Immediately start buffering those */
968 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
969 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
970 } else {
971 /* Other types will get buffered in the course of normal operations */
972 h->fd = -1;
973 close(fd);
975 /* Inform the buffering thread that we added a handle */
976 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
977 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
980 logf("bufopen: new hdl %d", h->id);
981 return h->id;
984 /* Open a new handle from data that needs to be copied from memory.
985 src is the source buffer from which to copy data. It can be NULL to simply
986 reserve buffer space.
987 size is the requested size. The call will only be successful if the
988 requested amount of data can entirely fit in the buffer without wrapping.
989 Return value is the handle id for success or <0 for failure.
991 int bufalloc(const void *src, size_t size, enum data_type type)
993 struct memory_handle *h = add_handle(size, false, true);
995 if (!h)
996 return ERR_BUFFER_FULL;
998 if (src) {
999 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1000 /* specially take care of struct mp3entry */
1001 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1002 (const struct mp3entry *)src);
1003 } else {
1004 memcpy(&buffer[buf_widx], src, size);
1008 h->fd = -1;
1009 *h->path = 0;
1010 h->filesize = size;
1011 h->filerem = 0;
1012 h->offset = 0;
1013 h->ridx = buf_widx;
1014 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1015 h->data = buf_widx;
1016 h->available = size;
1017 h->type = type;
1019 buf_widx += size; /* safe too */
1021 logf("bufalloc: new hdl %d", h->id);
1022 return h->id;
1025 /* Close the handle. Return true for success and false for failure */
1026 bool bufclose(int handle_id)
1028 logf("bufclose(%d)", handle_id);
1030 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1031 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1034 /* Set reading index in handle (relatively to the start of the file).
1035 Access before the available data will trigger a rebuffer.
1036 Return 0 for success and < 0 for failure:
1037 -1 if the handle wasn't found
1038 -2 if the new requested position was beyond the end of the file
1040 int bufseek(int handle_id, size_t newpos)
1042 struct memory_handle *h = find_handle(handle_id);
1043 if (!h)
1044 return ERR_HANDLE_NOT_FOUND;
1046 if (newpos > h->filesize) {
1047 /* access beyond the end of the file */
1048 return ERR_INVALID_VALUE;
1050 else if (newpos < h->offset || h->offset + h->available < newpos) {
1051 /* access before or after buffered data. A rebuffer is needed. */
1052 rebuffer_handle(handle_id, newpos);
1054 else {
1055 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1057 return 0;
1060 /* Advance the reading index in a handle (relatively to its current position).
1061 Return 0 for success and < 0 for failure */
1062 int bufadvance(int handle_id, off_t offset)
1064 const struct memory_handle *h = find_handle(handle_id);
1065 if (!h)
1066 return ERR_HANDLE_NOT_FOUND;
1068 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1069 return bufseek(handle_id, newpos);
1072 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1073 * actual amount of data available for reading. This function explicitly
1074 * does not check the validity of the input handle. It does do range checks
1075 * on size and returns a valid (and explicit) amount of data for reading */
1076 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1077 bool guardbuf_limit)
1079 struct memory_handle *h = find_handle(handle_id);
1080 if (!h)
1081 return NULL;
1083 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1085 if (avail == 0 && h->filerem == 0)
1087 /* File is finished reading */
1088 *size = 0;
1089 return h;
1092 if (*size == 0 || *size > avail + h->filerem)
1093 *size = avail + h->filerem;
1095 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1097 logf("data request > guardbuf");
1098 /* If more than the size of the guardbuf is requested and this is a
1099 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1100 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1101 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1104 if (h->filerem > 0 && avail < *size)
1106 /* Data isn't ready. Request buffering */
1107 buf_request_buffer_handle(handle_id);
1108 /* Wait for the data to be ready */
1111 sleep(1);
1112 /* it is not safe for a non-buffering thread to sleep while
1113 * holding a handle */
1114 h = find_handle(handle_id);
1115 if (!h)
1116 return NULL;
1117 avail = RINGBUF_SUB(h->widx, h->ridx);
1119 while (h->filerem > 0 && avail < *size);
1122 *size = MIN(*size,avail);
1123 return h;
1126 /* Copy data from the given handle to the dest buffer.
1127 Return the number of bytes copied or < 0 for failure (handle not found).
1128 The caller is blocked until the requested amount of data is available.
1130 ssize_t bufread(int handle_id, size_t size, void *dest)
1132 const struct memory_handle *h;
1133 size_t adjusted_size = size;
1135 h = prep_bufdata(handle_id, &adjusted_size, false);
1136 if (!h)
1137 return ERR_HANDLE_NOT_FOUND;
1139 if (h->ridx + adjusted_size > buffer_len)
1141 /* the data wraps around the end of the buffer */
1142 size_t read = buffer_len - h->ridx;
1143 memcpy(dest, &buffer[h->ridx], read);
1144 memcpy(dest+read, buffer, adjusted_size - read);
1146 else
1148 memcpy(dest, &buffer[h->ridx], adjusted_size);
1151 return adjusted_size;
1154 /* Update the "data" pointer to make the handle's data available to the caller.
1155 Return the length of the available linear data or < 0 for failure (handle
1156 not found).
1157 The caller is blocked until the requested amount of data is available.
1158 size is the amount of linear data requested. it can be 0 to get as
1159 much as possible.
1160 The guard buffer may be used to provide the requested size. This means it's
1161 unsafe to request more than the size of the guard buffer.
1163 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1165 const struct memory_handle *h;
1166 size_t adjusted_size = size;
1168 h = prep_bufdata(handle_id, &adjusted_size, true);
1169 if (!h)
1170 return ERR_HANDLE_NOT_FOUND;
1172 if (h->ridx + adjusted_size > buffer_len)
1174 /* the data wraps around the end of the buffer :
1175 use the guard buffer to provide the requested amount of data. */
1176 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1177 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1178 so copy_n <= GUARD_BUFSIZE */
1179 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1182 if (data)
1183 *data = &buffer[h->ridx];
1185 return adjusted_size;
1188 ssize_t bufgettail(int handle_id, size_t size, void **data)
1190 size_t tidx;
1192 const struct memory_handle *h;
1194 h = find_handle(handle_id);
1196 if (!h)
1197 return ERR_HANDLE_NOT_FOUND;
1199 if (h->filerem)
1200 return ERR_HANDLE_NOT_DONE;
1202 /* We don't support tail requests of > guardbuf_size, for simplicity */
1203 if (size > GUARD_BUFSIZE)
1204 return ERR_INVALID_VALUE;
1206 tidx = RINGBUF_SUB(h->widx, size);
1208 if (tidx + size > buffer_len)
1210 size_t copy_n = tidx + size - buffer_len;
1211 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1214 *data = &buffer[tidx];
1215 return size;
1218 ssize_t bufcuttail(int handle_id, size_t size)
1220 struct memory_handle *h;
1221 size_t adjusted_size = size;
1223 h = find_handle(handle_id);
1225 if (!h)
1226 return ERR_HANDLE_NOT_FOUND;
1228 if (h->filerem)
1229 return ERR_HANDLE_NOT_DONE;
1231 if (h->available < adjusted_size)
1232 adjusted_size = h->available;
1234 h->available -= adjusted_size;
1235 h->filesize -= adjusted_size;
1236 h->widx = RINGBUF_SUB(h->widx, adjusted_size);
1237 if (h == cur_handle)
1238 buf_widx = h->widx;
1240 return adjusted_size;
1245 SECONDARY EXPORTED FUNCTIONS
1246 ============================
1248 buf_get_offset
1249 buf_handle_offset
1250 buf_request_buffer_handle
1251 buf_set_base_handle
1252 buf_used
1253 register_buffering_callback
1254 unregister_buffering_callback
1256 These functions are exported, to allow interaction with the buffer.
1257 They take care of the content of the structs, and rely on the linked list
1258 management functions for all the actual handle management work.
1261 /* Get a handle offset from a pointer */
1262 ssize_t buf_get_offset(int handle_id, void *ptr)
1264 const struct memory_handle *h = find_handle(handle_id);
1265 if (!h)
1266 return ERR_HANDLE_NOT_FOUND;
1268 return (size_t)ptr - (size_t)&buffer[h->ridx];
1271 ssize_t buf_handle_offset(int handle_id)
1273 const struct memory_handle *h = find_handle(handle_id);
1274 if (!h)
1275 return ERR_HANDLE_NOT_FOUND;
1276 return h->offset;
1279 void buf_request_buffer_handle(int handle_id)
1281 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1282 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1285 void buf_set_base_handle(int handle_id)
1287 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1288 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1291 /* Return the amount of buffer space used */
1292 size_t buf_used(void)
1294 return BUF_USED;
1297 void buf_set_watermark(size_t bytes)
1299 LOGFQUEUE("buffering > Q_SET_WATERMARK %ld", (long)bytes);
1300 queue_post(&buffering_queue, Q_SET_WATERMARK, bytes);
1303 static void shrink_buffer_inner(struct memory_handle *h)
1305 if (h == NULL)
1306 return;
1308 shrink_buffer_inner(h->next);
1310 shrink_handle(h);
1313 static void shrink_buffer(void)
1315 logf("shrink_buffer()");
1316 shrink_buffer_inner(first_handle);
1319 void buffering_thread(void)
1321 bool filling = false;
1322 struct queue_event ev;
1324 while (true)
1326 if (!filling) {
1327 cancel_cpu_boost();
1330 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1332 switch (ev.id)
1334 case Q_START_FILL:
1335 LOGFQUEUE("buffering < Q_START_FILL");
1336 /* Call buffer callbacks here because this is one of two ways
1337 * to begin a full buffer fill */
1338 send_event(EVENT_BUFFER_LOW, 0);
1339 shrink_buffer();
1340 queue_reply(&buffering_queue, 1);
1341 filling |= buffer_handle((int)ev.data);
1342 break;
1344 case Q_BUFFER_HANDLE:
1345 LOGFQUEUE("buffering < Q_BUFFER_HANDLE");
1346 queue_reply(&buffering_queue, 1);
1347 buffer_handle((int)ev.data);
1348 break;
1350 case Q_RESET_HANDLE:
1351 LOGFQUEUE("buffering < Q_RESET_HANDLE");
1352 queue_reply(&buffering_queue, 1);
1353 reset_handle((int)ev.data);
1354 break;
1356 case Q_CLOSE_HANDLE:
1357 LOGFQUEUE("buffering < Q_CLOSE_HANDLE");
1358 queue_reply(&buffering_queue, close_handle((int)ev.data));
1359 break;
1361 case Q_HANDLE_ADDED:
1362 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1363 /* A handle was added: the disk is spinning, so we can fill */
1364 filling = true;
1365 break;
1367 case Q_BASE_HANDLE:
1368 LOGFQUEUE("buffering < Q_BASE_HANDLE");
1369 base_handle_id = (int)ev.data;
1370 break;
1372 case Q_SET_WATERMARK:
1373 LOGFQUEUE("buffering < Q_SET_WATERMARK");
1374 conf_watermark = (size_t)ev.data;
1375 if (conf_watermark < BUFFERING_DEFAULT_FILECHUNK)
1377 logf("wmark<chunk %ld<%d",
1378 (long)conf_watermark, BUFFERING_DEFAULT_FILECHUNK);
1379 conf_watermark = BUFFERING_DEFAULT_FILECHUNK;
1381 break;
1383 #ifndef SIMULATOR
1384 case SYS_USB_CONNECTED:
1385 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1386 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1387 usb_wait_for_disconnect(&buffering_queue);
1388 break;
1389 #endif
1391 case SYS_TIMEOUT:
1392 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1393 break;
1396 update_data_counters();
1398 /* If the buffer is low, call the callbacks to get new data */
1399 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1400 send_event(EVENT_BUFFER_LOW, 0);
1402 #if 0
1403 /* TODO: This needs to be fixed to use the idle callback, disable it
1404 * for simplicity until its done right */
1405 #if MEM > 8
1406 /* If the disk is spinning, take advantage by filling the buffer */
1407 else if (ata_disk_is_active() && queue_empty(&buffering_queue))
1409 if (num_handles > 0 && data_counters.useful <= high_watermark)
1410 send_event(EVENT_BUFFER_LOW, 0);
1412 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1414 /* This is a new fill, shrink the buffer up first */
1415 if (!filling)
1416 shrink_buffer();
1417 filling = fill_buffer();
1418 update_data_counters();
1421 #endif
1422 #endif
1424 if (queue_empty(&buffering_queue)) {
1425 if (filling) {
1426 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1427 filling = fill_buffer();
1429 else if (ev.id == SYS_TIMEOUT)
1431 if (data_counters.remaining > 0 &&
1432 data_counters.useful <= conf_watermark) {
1433 shrink_buffer();
1434 filling = fill_buffer();
1441 void buffering_init(void)
1443 mutex_init(&llist_mutex);
1444 #ifdef HAVE_PRIORITY_SCHEDULING
1445 /* This behavior not safe atm */
1446 mutex_set_preempt(&llist_mutex, false);
1447 #endif
1449 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1451 queue_init(&buffering_queue, true);
1452 buffering_thread_p = create_thread( buffering_thread, buffering_stack,
1453 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1454 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1455 IF_COP(, CPU));
1457 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1458 buffering_thread_p);
1461 /* Initialise the buffering subsystem */
1462 bool buffering_reset(char *buf, size_t buflen)
1464 if (!buf || !buflen)
1465 return false;
1467 buffer = buf;
1468 buffer_len = buflen;
1469 guard_buffer = buf + buflen;
1471 buf_widx = 0;
1472 buf_ridx = 0;
1474 first_handle = NULL;
1475 cur_handle = NULL;
1476 cached_handle = NULL;
1477 num_handles = 0;
1478 base_handle_id = -1;
1480 /* Set the high watermark as 75% full...or 25% empty :) */
1481 #if MEM > 8
1482 high_watermark = 3*buflen / 4;
1483 #endif
1485 thread_thaw(buffering_thread_p);
1487 return true;
1490 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1492 update_data_counters();
1493 dbgdata->num_handles = num_handles;
1494 dbgdata->data_rem = data_counters.remaining;
1495 dbgdata->wasted_space = data_counters.wasted;
1496 dbgdata->buffered_data = data_counters.buffered;
1497 dbgdata->useful_data = data_counters.useful;