Fix red
[Rockbox.git] / apps / buffering.c
blob64f522c52f5cc7bdc4e6b3be190ef4a701db13b6
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 "playback.h"
49 #include "pcmbuf.h"
50 #include "buffer.h"
51 #include "bmp.h"
53 #ifdef SIMULATOR
54 #define ata_disk_is_active() 1
55 #endif
57 #if MEM > 1
58 #define GUARD_BUFSIZE (32*1024)
59 #else
60 #define GUARD_BUFSIZE (8*1024)
61 #endif
63 /* Define LOGF_ENABLE to enable logf output in this file */
64 /*#define LOGF_ENABLE*/
65 #include "logf.h"
67 /* macros to enable logf for queues
68 logging on SYS_TIMEOUT can be disabled */
69 #ifdef SIMULATOR
70 /* Define this for logf output of all queuing except SYS_TIMEOUT */
71 #define BUFFERING_LOGQUEUES
72 /* Define this to logf SYS_TIMEOUT messages */
73 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
74 #endif
76 #ifdef BUFFERING_LOGQUEUES
77 #define LOGFQUEUE logf
78 #else
79 #define LOGFQUEUE(...)
80 #endif
82 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
83 #define LOGFQUEUE_SYS_TIMEOUT logf
84 #else
85 #define LOGFQUEUE_SYS_TIMEOUT(...)
86 #endif
88 /* default point to start buffer refill */
89 #define BUFFERING_DEFAULT_WATERMARK (1024*512)
90 /* amount of data to read in one read() call */
91 #define BUFFERING_DEFAULT_FILECHUNK (1024*16)
92 /* point at which the file buffer will fight for CPU time */
93 #define BUFFERING_CRITICAL_LEVEL (1024*128)
95 #define BUF_HANDLE_MASK 0x7FFFFFFF
98 /* Ring buffer helper macros */
99 /* Buffer pointer (p) plus value (v), wrapped if necessary */
100 #define RINGBUF_ADD(p,v) (((p)+(v))<buffer_len ? (p)+(v) : (p)+(v)-buffer_len)
101 /* Buffer pointer (p) minus value (v), wrapped if necessary */
102 #define RINGBUF_SUB(p,v) ((p>=v) ? (p)-(v) : (p)+buffer_len-(v))
103 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
104 #define RINGBUF_ADD_CROSS(p1,v,p2) \
105 ((p1<p2) ? (int)((p1)+(v))-(int)(p2) : (int)((p1)+(v)-(p2))-(int)buffer_len)
106 /* Bytes available in the buffer */
107 #define BUF_USED RINGBUF_SUB(buf_widx, buf_ridx)
109 /* assert(sizeof(struct memory_handle)%4==0) */
110 struct memory_handle {
111 int id; /* A unique ID for the handle */
112 enum data_type type; /* Type of data buffered with this handle */
113 char path[MAX_PATH]; /* Path if data originated in a file */
114 int fd; /* File descriptor to path (-1 if closed) */
115 size_t data; /* Start index of the handle's data buffer */
116 volatile size_t ridx; /* Read pointer, relative to the main buffer */
117 size_t widx; /* Write pointer */
118 size_t filesize; /* File total length */
119 size_t filerem; /* Remaining bytes of file NOT in buffer */
120 volatile size_t available; /* Available bytes to read from buffer */
121 size_t offset; /* Offset at which we started reading the file */
122 struct memory_handle *next;
124 /* invariant: filesize == offset + available + filerem */
126 static char *buffer;
127 static char *guard_buffer;
129 static size_t buffer_len;
131 static volatile size_t buf_widx; /* current writing position */
132 static volatile size_t buf_ridx; /* current reading position */
133 /* buf_*idx are values relative to the buffer, not real pointers. */
135 /* Configuration */
136 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
137 #if MEM > 8
138 static size_t high_watermark = 0; /* High watermark for rebuffer */
139 #endif
141 /* current memory handle in the linked list. NULL when the list is empty. */
142 static struct memory_handle *cur_handle;
143 /* first memory handle in the linked list. NULL when the list is empty. */
144 static struct memory_handle *first_handle;
146 static int num_handles; /* number of handles in the list */
148 static int base_handle_id;
150 static struct mutex llist_mutex;
152 /* Handle cache (makes find_handle faster).
153 This is global so that move_handle and rm_handle can invalidate it. */
154 static struct memory_handle *cached_handle = NULL;
156 static buffering_callback buffering_callback_funcs[MAX_BUF_CALLBACKS];
157 static int buffer_callback_count = 0;
159 static struct {
160 size_t remaining; /* Amount of data needing to be buffered */
161 size_t wasted; /* Amount of space available for freeing */
162 size_t buffered; /* Amount of data currently in the buffer */
163 size_t useful; /* Amount of data still useful to the user */
164 } data_counters;
167 /* Messages available to communicate with the buffering thread */
168 enum {
169 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
170 used in a low buffer situation. */
171 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
172 offset (the offset has to be set beforehand) */
173 Q_CLOSE_HANDLE, /* Request closing a handle */
174 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
176 /* Configuration: */
177 Q_SET_WATERMARK,
178 Q_START_FILL, /* Request that the buffering thread initiate a buffer
179 fill at its earliest convenience */
180 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
181 (which means the disk is spinning) */
184 /* Buffering thread */
185 void buffering_thread(void);
186 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
187 static const char buffering_thread_name[] = "buffering";
188 static struct thread_entry *buffering_thread_p;
189 static struct event_queue buffering_queue;
190 static struct queue_sender_list buffering_queue_sender_list;
193 static void call_buffering_callbacks(enum callback_event ev, int value);
197 LINKED LIST MANAGEMENT
198 ======================
200 add_handle : Add a handle to the list
201 rm_handle : Remove a handle from the list
202 find_handle : Get a handle pointer from an ID
203 move_handle : Move a handle in the buffer (with or without its data)
205 These functions only handle the linked list structure. They don't touch the
206 contents of the struct memory_handle headers. They also change the buf_*idx
207 pointers when necessary and manage the handle IDs.
209 The first and current (== last) handle are kept track of.
210 A new handle is added at buf_widx and becomes the current one.
211 buf_widx always points to the current writing position for the current handle
212 buf_ridx always points to the location of the first handle.
213 buf_ridx == buf_widx means the buffer is empty.
217 /* Add a new handle to the linked list and return it. It will have become the
218 new current handle.
219 data_size must contain the size of what will be in the handle.
220 can_wrap tells us whether this type of data may wrap on buffer
221 alloc_all tells us if we must immediately be able to allocate data_size
222 returns a valid memory handle if all conditions for allocation are met.
223 NULL if there memory_handle itself cannot be allocated or if the
224 data_size cannot be allocated and alloc_all is set. This function's
225 only potential side effect is to allocate space for the cur_handle
226 if it returns NULL.
228 static struct memory_handle *add_handle(size_t data_size, const bool can_wrap,
229 const bool alloc_all)
231 /* gives each handle a unique id */
232 static int cur_handle_id = 0;
233 size_t shift;
234 size_t new_widx;
235 size_t len;
236 int overlap;
238 if (num_handles >= BUF_MAX_HANDLES)
239 return NULL;
241 mutex_lock(&llist_mutex);
243 if (cur_handle && cur_handle->filerem > 0) {
244 /* the current handle hasn't finished buffering. We can only add
245 a new one if there is already enough free space to finish
246 the buffering. */
247 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
248 if (RINGBUF_ADD_CROSS(cur_handle->widx, req, buf_ridx) >= 0) {
249 /* Not enough space */
250 mutex_unlock(&llist_mutex);
251 return NULL;
252 } else {
253 /* Allocate the remainder of the space for the current handle */
254 buf_widx = RINGBUF_ADD(cur_handle->widx, cur_handle->filerem);
258 /* align to 4 bytes up */
259 new_widx = RINGBUF_ADD(buf_widx, 3) & ~3;
261 len = data_size + sizeof(struct memory_handle);
263 /* First, will the handle wrap? */
264 overlap = RINGBUF_ADD_CROSS(new_widx, sizeof(struct memory_handle),
265 buffer_len - 1);
266 /* If the handle would wrap, move to the beginning of the buffer,
267 * otherwise check if the data can/would wrap and move it to the
268 * beginning if needed */
269 if (overlap > 0) {
270 new_widx = 0;
271 } else if (!can_wrap) {
272 overlap = RINGBUF_ADD_CROSS(new_widx, len, buffer_len - 1);
273 if (overlap > 0)
274 new_widx += data_size - overlap;
277 /* How far we shifted buf_widx to align things, must be < buffer_len */
278 shift = RINGBUF_SUB(new_widx, buf_widx);
280 /* How much space are we short in the actual ring buffer? */
281 overlap = RINGBUF_ADD_CROSS(buf_widx, shift + len, buf_ridx);
282 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
283 /* Not enough space for required allocations */
284 mutex_unlock(&llist_mutex);
285 return NULL;
288 /* There is enough space for the required data, advance the buf_widx and
289 * initialize the struct */
290 buf_widx = new_widx;
292 struct memory_handle *new_handle =
293 (struct memory_handle *)(&buffer[buf_widx]);
295 /* only advance the buffer write index of the size of the struct */
296 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
298 new_handle->id = cur_handle_id;
299 /* Wrap signed int is safe and 0 doesn't happen */
300 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
301 new_handle->next = NULL;
302 num_handles++;
304 if (!first_handle)
305 /* the new handle is the first one */
306 first_handle = new_handle;
308 if (cur_handle)
309 cur_handle->next = new_handle;
311 cur_handle = new_handle;
313 mutex_unlock(&llist_mutex);
314 return new_handle;
317 /* Delete a given memory handle from the linked list
318 and return true for success. Nothing is actually erased from memory. */
319 static bool rm_handle(const struct memory_handle *h)
321 if (h == NULL)
322 return true;
324 mutex_lock(&llist_mutex);
326 if (h == first_handle) {
327 first_handle = h->next;
328 if (h == cur_handle) {
329 /* h was the first and last handle: the buffer is now empty */
330 cur_handle = NULL;
331 buf_ridx = buf_widx = 0;
332 } else {
333 /* update buf_ridx to point to the new first handle */
334 buf_ridx = (void *)first_handle - (void *)buffer;
336 } else {
337 struct memory_handle *m = first_handle;
338 /* Find the previous handle */
339 while (m && m->next != h) {
340 m = m->next;
342 if (m && m->next == h) {
343 m->next = h->next;
344 if (h == cur_handle) {
345 cur_handle = m;
346 buf_widx = cur_handle->widx;
348 } else {
349 mutex_unlock(&llist_mutex);
350 return false;
354 /* Invalidate the cache to prevent it from keeping the old location of h */
355 if (h == cached_handle)
356 cached_handle = NULL;
358 num_handles--;
360 mutex_unlock(&llist_mutex);
361 return true;
364 /* Return a pointer to the memory handle of given ID.
365 NULL if the handle wasn't found */
366 static struct memory_handle *find_handle(const int handle_id)
368 if (handle_id < 0)
369 return NULL;
371 mutex_lock(&llist_mutex);
373 /* simple caching because most of the time the requested handle
374 will either be the same as the last, or the one after the last */
375 if (cached_handle)
377 if (cached_handle->id == handle_id) {
378 mutex_unlock(&llist_mutex);
379 return cached_handle;
380 } else if (cached_handle->next &&
381 (cached_handle->next->id == handle_id)) {
382 cached_handle = cached_handle->next;
383 mutex_unlock(&llist_mutex);
384 return cached_handle;
388 struct memory_handle *m = first_handle;
389 while (m && m->id != handle_id) {
390 m = m->next;
392 /* This condition can only be reached with !m or m->id == handle_id */
393 if (m)
394 cached_handle = m;
396 mutex_unlock(&llist_mutex);
397 return m;
400 /* Move a memory handle and data_size of its data delta bytes along the buffer.
401 delta maximum bytes available to move the handle. If the move is performed
402 it is set to the actual distance moved.
403 data_size is the amount of data to move along with the struct.
404 returns a valid memory_handle if the move is successful
405 NULL if the handle is NULL, the move would be less than the size of
406 a memory_handle after correcting for wraps or if the handle is not
407 found in the linked list for adjustment. This function has no side
408 effects if NULL is returned. */
409 static bool move_handle(struct memory_handle **h, size_t *delta,
410 const size_t data_size, bool can_wrap)
412 struct memory_handle *dest;
413 const struct memory_handle *src;
414 size_t newpos;
415 size_t size_to_move;
416 size_t final_delta = *delta;
417 int overlap;
419 if (h == NULL || (src = *h) == NULL)
420 return false;
422 size_to_move = sizeof(struct memory_handle) + data_size;
424 /* Align to four bytes, down */
425 final_delta &= ~3;
426 if (final_delta < sizeof(struct memory_handle)) {
427 /* It's not legal to move less than the size of the struct */
428 return false;
431 mutex_lock(&llist_mutex);
433 newpos = RINGBUF_ADD((void *)src - (void *)buffer, final_delta);
434 overlap = RINGBUF_ADD_CROSS(newpos, size_to_move, buffer_len - 1);
436 if (overlap > 0) {
437 /* Some part of the struct + data would wrap, maybe ok */
438 size_t correction = 0;
439 /* If the overlap lands inside the memory_handle */
440 if ((unsigned)overlap > data_size) {
441 /* Correct the position and real delta to prevent the struct from
442 * wrapping, this guarantees an aligned delta, I think */
443 correction = overlap - data_size;
444 } else if (!can_wrap) {
445 /* Otherwise the overlap falls in the data area and must all be
446 * backed out. This may become conditional if ever we move
447 * data that is allowed to wrap (ie audio) */
448 correction = overlap;
449 /* Align correction to four bytes, up */
450 correction = (correction+3) & ~3;
452 if (correction) {
453 if (final_delta < correction + sizeof(struct memory_handle)) {
454 /* Delta cannot end up less than the size of the struct */
455 mutex_unlock(&llist_mutex);
456 return false;
459 newpos -= correction;
460 overlap -= correction;/* Used below to know how to split the data */
461 final_delta -= correction;
465 dest = (struct memory_handle *)(&buffer[newpos]);
467 if (src == first_handle) {
468 first_handle = dest;
469 buf_ridx = newpos;
470 } else {
471 struct memory_handle *m = first_handle;
472 while (m && m->next != src) {
473 m = m->next;
475 if (m && m->next == src) {
476 m->next = dest;
477 } else {
478 mutex_unlock(&llist_mutex);
479 return false;
484 /* Update the cache to prevent it from keeping the old location of h */
485 if (src == cached_handle)
486 cached_handle = dest;
488 /* the cur_handle pointer might need updating */
489 if (src == cur_handle)
490 cur_handle = dest;
492 if (overlap > 0) {
493 size_t first_part = size_to_move - overlap;
494 memmove(dest, src, first_part);
495 memmove(buffer, (char *)src + first_part, overlap);
496 } else {
497 memmove(dest, src, size_to_move);
500 /* Update the caller with the new location of h and the distance moved */
501 *h = dest;
502 *delta = final_delta;
503 mutex_unlock(&llist_mutex);
504 return dest;
509 BUFFER SPACE MANAGEMENT
510 =======================
512 update_data_counters: Updates the values in data_counters
513 buffer_is_low : Returns true if the amount of useful data in the buffer is low
514 buffer_handle : Buffer data for a handle
515 reset_handle : Reset write position and data buffer of a handle to its offset
516 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
517 shrink_handle : Free buffer space by moving a handle
518 fill_buffer : Call buffer_handle for all handles that have data to buffer
520 These functions are used by the buffering thread to manage buffer space.
523 static void update_data_counters(void)
525 struct memory_handle *m = find_handle(base_handle_id);
526 bool is_useful = m==NULL;
528 size_t buffered = 0;
529 size_t wasted = 0;
530 size_t remaining = 0;
531 size_t useful = 0;
533 m = first_handle;
534 while (m) {
535 buffered += m->available;
536 wasted += RINGBUF_SUB(m->ridx, m->data);
537 remaining += m->filerem;
539 if (m->id == base_handle_id)
540 is_useful = true;
542 if (is_useful)
543 useful += RINGBUF_SUB(m->widx, m->ridx);
545 m = m->next;
548 data_counters.buffered = buffered;
549 data_counters.wasted = wasted;
550 data_counters.remaining = remaining;
551 data_counters.useful = useful;
554 static inline bool buffer_is_low(void)
556 update_data_counters();
557 return data_counters.useful < BUFFERING_CRITICAL_LEVEL;
560 /* Buffer data for the given handle.
561 Return whether or not the buffering should continue explicitly. */
562 static bool buffer_handle(int handle_id)
564 logf("buffer_handle(%d)", handle_id);
565 struct memory_handle *h = find_handle(handle_id);
566 if (!h)
567 return true;
569 if (h->filerem == 0) {
570 /* nothing left to buffer */
571 return true;
574 if (h->fd < 0) /* file closed, reopen */
576 if (*h->path)
577 h->fd = open(h->path, O_RDONLY);
579 if (h->fd < 0)
581 /* could not open the file, truncate it where it is */
582 h->filesize -= h->filerem;
583 h->filerem = 0;
584 return true;
587 if (h->offset)
588 lseek(h->fd, h->offset, SEEK_SET);
591 trigger_cpu_boost();
593 while (h->filerem > 0)
595 /* max amount to copy */
596 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
597 buffer_len - h->widx);
599 /* stop copying if it would overwrite the reading position */
600 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
601 return false;
603 /* This would read into the next handle, this is broken */
604 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
605 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
606 /* Try to recover by truncating this file */
607 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
608 (unsigned)((void *)h->next - (void *)buffer));
609 h->filerem -= copy_n;
610 h->filesize -= copy_n;
611 logf("buf alloc short %ld", (long)copy_n);
612 if (h->filerem)
613 continue;
614 else
615 break;
618 /* rc is the actual amount read */
619 int rc = read(h->fd, &buffer[h->widx], copy_n);
621 if (rc < 0)
623 /* Some kind of filesystem error, maybe recoverable if not codec */
624 if (h->type == TYPE_CODEC) {
625 logf("Partial codec");
626 break;
629 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
630 h->filesize -= h->filerem;
631 h->filerem = 0;
632 break;
635 /* Advance buffer */
636 h->widx = RINGBUF_ADD(h->widx, rc);
637 if (h == cur_handle)
638 buf_widx = h->widx;
639 h->available += rc;
640 h->filerem -= rc;
642 /* If this is a large file, see if we need to break or give the codec
643 * more time */
644 if (h->type == TYPE_PACKET_AUDIO &&
645 pcmbuf_is_lowdata() && !buffer_is_low())
647 sleep(1);
649 else
651 yield();
654 if (!queue_empty(&buffering_queue))
655 break;
658 if (h->filerem == 0) {
659 /* finished buffering the file */
660 close(h->fd);
661 h->fd = -1;
662 call_buffering_callbacks(EVENT_HANDLE_FINISHED, h->id);
665 return true;
668 /* Reset writing position and data buffer of a handle to its current offset.
669 Use this after having set the new offset to use. */
670 static void reset_handle(int handle_id)
672 logf("reset_handle(%d)", handle_id);
674 struct memory_handle *h = find_handle(handle_id);
675 if (!h)
676 return;
678 h->widx = h->data;
679 if (h == cur_handle)
680 buf_widx = h->widx;
681 h->available = 0;
682 h->filerem = h->filesize - h->offset;
684 if (h->fd >= 0) {
685 lseek(h->fd, h->offset, SEEK_SET);
689 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
690 static void rebuffer_handle(int handle_id, size_t newpos)
692 struct memory_handle *h = find_handle(handle_id);
693 if (!h)
694 return;
696 /* When seeking foward off of the buffer, if it is a short seek don't
697 rebuffer the whole track, just read enough to satisfy */
698 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
700 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
701 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
702 h->ridx = h->data + newpos;
703 return;
706 h->offset = newpos;
708 /* Reset the handle to its new offset */
709 LOGFQUEUE("buffering >| Q_RESET_HANDLE");
710 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
712 size_t next = (unsigned)((void *)h->next - (void *)buffer);
713 if (next - h->data < h->filesize - newpos)
715 /* There isn't enough space to rebuffer all of the track from its new
716 offset, so we ask the user to free some */
717 DEBUGF("rebuffer_handle: space is needed\n");
718 call_buffering_callbacks(EVENT_HANDLE_REBUFFER, handle_id);
721 /* Now we ask for a rebuffer */
722 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
723 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
725 h->ridx = h->data;
728 static bool close_handle(int handle_id)
730 struct memory_handle *h = find_handle(handle_id);
732 /* If the handle is not found, it is closed */
733 if (!h)
734 return true;
736 if (h->fd >= 0) {
737 close(h->fd);
738 h->fd = -1;
741 /* rm_handle returns true unless the handle somehow persists after exit */
742 return rm_handle(h);
745 /* Free buffer space by moving the handle struct right before the useful
746 part of its data buffer or by moving all the data. */
747 static void shrink_handle(struct memory_handle *h)
749 size_t delta;
751 if (!h)
752 return;
754 if (h->next && h->filerem == 0 &&
755 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
756 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
757 h->type == TYPE_ATOMIC_AUDIO))
759 /* metadata handle: we can move all of it */
760 size_t handle_distance =
761 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
762 delta = handle_distance - h->available;
764 /* The value of delta might change for alignment reasons */
765 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
766 return;
768 size_t olddata = h->data;
769 h->data = RINGBUF_ADD(h->data, delta);
770 h->ridx = RINGBUF_ADD(h->ridx, delta);
771 h->widx = RINGBUF_ADD(h->widx, delta);
773 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
774 /* when moving an mp3entry we need to readjust its pointers. */
775 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
776 (void *)&buffer[h->data],
777 (void *)&buffer[olddata]);
778 } else if (h->type == TYPE_BITMAP) {
779 /* adjust the bitmap's pointer */
780 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
781 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
784 else
786 /* only move the handle struct */
787 delta = RINGBUF_SUB(h->ridx, h->data);
788 if (!move_handle(&h, &delta, 0, true))
789 return;
791 h->data = RINGBUF_ADD(h->data, delta);
792 h->available -= delta;
793 h->offset += delta;
797 /* Fill the buffer by buffering as much data as possible for handles that still
798 have data left to buffer
799 Return whether or not to continue filling after this */
800 static bool fill_buffer(void)
802 logf("fill_buffer()");
803 struct memory_handle *m = first_handle;
804 shrink_handle(m);
805 while (queue_empty(&buffering_queue) && m) {
806 if (m->filerem > 0) {
807 if (!buffer_handle(m->id)) {
808 m = NULL;
809 break;
812 m = m->next;
815 if (m) {
816 return true;
818 else
820 #ifndef SIMULATOR
821 /* only spin the disk down if the filling wasn't interrupted by an
822 event arriving in the queue. */
823 ata_sleep();
824 #endif
825 return false;
829 #ifdef HAVE_ALBUMART
830 /* Given a file descriptor to a bitmap file, write the bitmap data to the
831 buffer, with a struct bitmap and the actual data immediately following.
832 Return value is the total size (struct + data). */
833 static int load_bitmap(const int fd)
835 int rc;
836 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
837 /* FIXME: alignment may be needed for the data buffer. */
838 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
840 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
841 bmp->maskdata = NULL;
842 #endif
844 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx);
845 rc = read_bmp_fd(fd, bmp, free, FORMAT_ANY|FORMAT_DITHER);
846 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
848 #endif
852 MAIN BUFFERING API CALLS
853 ========================
855 bufopen : Request the opening of a new handle for a file
856 bufalloc : Open a new handle for data other than a file.
857 bufclose : Close an open handle
858 bufseek : Set the read pointer in a handle
859 bufadvance : Move the read pointer in a handle
860 bufread : Copy data from a handle into a given buffer
861 bufgetdata : Give a pointer to the handle's data
863 These functions are exported, to allow interaction with the buffer.
864 They take care of the content of the structs, and rely on the linked list
865 management functions for all the actual handle management work.
869 /* Reserve space in the buffer for a file.
870 filename: name of the file to open
871 offset: offset at which to start buffering the file, useful when the first
872 (offset-1) bytes of the file aren't needed.
873 return value: <0 if the file cannot be opened, or one file already
874 queued to be opened, otherwise the handle for the file in the buffer
876 int bufopen(const char *file, size_t offset, enum data_type type)
878 int fd = open(file, O_RDONLY);
879 if (fd < 0)
880 return ERR_FILE_ERROR;
882 size_t size = filesize(fd);
883 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
885 if (offset > size)
886 offset = 0;
888 struct memory_handle *h = add_handle(size-offset, can_wrap, false);
889 if (!h)
891 DEBUGF("bufopen: failed to add handle\n");
892 close(fd);
893 return ERR_BUFFER_FULL;
896 strncpy(h->path, file, MAX_PATH);
897 h->offset = offset;
898 h->ridx = buf_widx;
899 h->data = buf_widx;
900 h->type = type;
902 #ifdef HAVE_ALBUMART
903 if (type == TYPE_BITMAP)
905 /* Bitmap file: we load the data instead of the file */
906 int rc;
907 mutex_lock(&llist_mutex); /* Lock because load_bitmap yields */
908 rc = load_bitmap(fd);
909 if (rc <= 0)
911 rm_handle(h);
912 close(fd);
913 mutex_unlock(&llist_mutex);
914 return ERR_FILE_ERROR;
916 h->filerem = 0;
917 h->filesize = rc;
918 h->available = rc;
919 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
920 buf_widx += rc; /* safe too */
921 mutex_unlock(&llist_mutex);
923 else
924 #endif
926 h->filerem = size - offset;
927 h->filesize = size;
928 h->available = 0;
929 h->widx = buf_widx;
932 if (type == TYPE_CUESHEET) {
933 h->fd = fd;
934 /* Immediately start buffering those */
935 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
936 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
937 } else {
938 /* Other types will get buffered in the course of normal operations */
939 h->fd = -1;
940 close(fd);
942 /* Inform the buffering thread that we added a handle */
943 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
944 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
947 logf("bufopen: new hdl %d", h->id);
948 return h->id;
951 /* Open a new handle from data that needs to be copied from memory.
952 src is the source buffer from which to copy data. It can be NULL to simply
953 reserve buffer space.
954 size is the requested size. The call will only be successful if the
955 requested amount of data can entirely fit in the buffer without wrapping.
956 Return value is the handle id for success or <0 for failure.
958 int bufalloc(const void *src, size_t size, enum data_type type)
960 struct memory_handle *h = add_handle(size, false, true);
962 if (!h)
963 return ERR_BUFFER_FULL;
965 if (src) {
966 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
967 /* specially take care of struct mp3entry */
968 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
969 (struct mp3entry *)src);
970 } else {
971 memcpy(&buffer[buf_widx], src, size);
975 h->fd = -1;
976 *h->path = 0;
977 h->filesize = size;
978 h->filerem = 0;
979 h->offset = 0;
980 h->ridx = buf_widx;
981 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
982 h->data = buf_widx;
983 h->available = size;
984 h->type = type;
986 buf_widx += size; /* safe too */
988 logf("bufalloc: new hdl %d", h->id);
989 return h->id;
992 /* Close the handle. Return true for success and false for failure */
993 bool bufclose(int handle_id)
995 logf("bufclose(%d)", handle_id);
997 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
998 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1001 /* Set reading index in handle (relatively to the start of the file).
1002 Access before the available data will trigger a rebuffer.
1003 Return 0 for success and < 0 for failure:
1004 -1 if the handle wasn't found
1005 -2 if the new requested position was beyond the end of the file
1007 int bufseek(int handle_id, size_t newpos)
1009 struct memory_handle *h = find_handle(handle_id);
1010 if (!h)
1011 return ERR_HANDLE_NOT_FOUND;
1013 if (newpos > h->filesize) {
1014 /* access beyond the end of the file */
1015 return ERR_INVALID_VALUE;
1017 else if (newpos < h->offset || h->offset + h->available < newpos) {
1018 /* access before or after buffered data. A rebuffer is needed. */
1019 rebuffer_handle(handle_id, newpos);
1021 else {
1022 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1024 return 0;
1027 /* Advance the reading index in a handle (relatively to its current position).
1028 Return 0 for success and < 0 for failure */
1029 int bufadvance(int handle_id, off_t offset)
1031 const struct memory_handle *h = find_handle(handle_id);
1032 if (!h)
1033 return ERR_HANDLE_NOT_FOUND;
1035 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1036 return bufseek(handle_id, newpos);
1039 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1040 * actual amount of data available for reading. This function explicitly
1041 * does not check the validity of the input handle. It does do range checks
1042 * on size and returns a valid (and explicit) amount of data for reading */
1043 static struct memory_handle *prep_bufdata(const int handle_id, size_t *size,
1044 const bool guardbuf_limit)
1046 struct memory_handle *h = find_handle(handle_id);
1047 if (!h)
1048 return NULL;
1050 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1052 if (avail == 0 && h->filerem == 0)
1054 /* File is finished reading */
1055 *size = 0;
1056 return h;
1059 if (*size == 0 || *size > avail + h->filerem)
1060 *size = avail + h->filerem;
1062 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1064 logf("data request > guardbuf");
1065 /* If more than the size of the guardbuf is requested and this is a
1066 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1067 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1068 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1071 if (h->filerem > 0 && avail < *size)
1073 /* Data isn't ready. Request buffering */
1074 buf_request_buffer_handle(handle_id);
1075 /* Wait for the data to be ready */
1078 sleep(1);
1079 /* it is not safe for a non-buffering thread to sleep while
1080 * holding a handle */
1081 h = find_handle(handle_id);
1082 if (!h)
1083 return NULL;
1084 avail = RINGBUF_SUB(h->widx, h->ridx);
1086 while (h->filerem > 0 && avail < *size);
1089 *size = MIN(*size,avail);
1090 return h;
1093 /* Copy data from the given handle to the dest buffer.
1094 Return the number of bytes copied or < 0 for failure (handle not found).
1095 The caller is blocked until the requested amount of data is available.
1097 ssize_t bufread(int handle_id, size_t size, void *dest)
1099 const struct memory_handle *h;
1101 h = prep_bufdata(handle_id, &size, false);
1102 if (!h)
1103 return ERR_HANDLE_NOT_FOUND;
1105 if (h->ridx + size > buffer_len)
1107 /* the data wraps around the end of the buffer */
1108 size_t read = buffer_len - h->ridx;
1109 memcpy(dest, &buffer[h->ridx], read);
1110 memcpy(dest+read, buffer, size - read);
1112 else
1114 memcpy(dest, &buffer[h->ridx], size);
1117 return size;
1120 /* Update the "data" pointer to make the handle's data available to the caller.
1121 Return the length of the available linear data or < 0 for failure (handle
1122 not found).
1123 The caller is blocked until the requested amount of data is available.
1124 size is the amount of linear data requested. it can be 0 to get as
1125 much as possible.
1126 The guard buffer may be used to provide the requested size. This means it's
1127 unsafe to request more than the size of the guard buffer.
1129 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1131 const struct memory_handle *h;
1133 h = prep_bufdata(handle_id, &size, true);
1134 if (!h)
1135 return ERR_HANDLE_NOT_FOUND;
1137 if (h->ridx + size > buffer_len)
1139 /* the data wraps around the end of the buffer :
1140 use the guard buffer to provide the requested amount of data. */
1141 size_t copy_n = h->ridx + size - buffer_len;
1142 /* prep_bufdata ensures size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1143 so copy_n <= GUARD_BUFSIZE */
1144 memcpy(guard_buffer, (unsigned char *)buffer, copy_n);
1147 if (data)
1148 *data = &buffer[h->ridx];
1150 return size;
1153 ssize_t bufgettail(int handle_id, size_t size, void **data)
1155 size_t tidx;
1157 const struct memory_handle *h;
1159 h = find_handle(handle_id);
1161 if (!h)
1162 return ERR_HANDLE_NOT_FOUND;
1164 if (h->filerem)
1165 return ERR_HANDLE_NOT_DONE;
1167 /* We don't support tail requests of > guardbuf_size, for simplicity */
1168 if (size > GUARD_BUFSIZE)
1169 return ERR_INVALID_VALUE;
1171 tidx = RINGBUF_SUB(h->widx, size);
1173 if (tidx + size > buffer_len)
1175 size_t copy_n = tidx + size - buffer_len;
1176 memcpy(guard_buffer, (unsigned char *)buffer, copy_n);
1179 *data = &buffer[tidx];
1180 return size;
1183 ssize_t bufcuttail(int handle_id, size_t size)
1185 struct memory_handle *h;
1187 h = find_handle(handle_id);
1189 if (!h)
1190 return ERR_HANDLE_NOT_FOUND;
1192 if (h->filerem)
1193 return ERR_HANDLE_NOT_DONE;
1195 if (h->available < size)
1196 size = h->available;
1198 h->available -= size;
1199 h->filesize -= size;
1200 h->widx = RINGBUF_SUB(h->widx, size);
1201 if (h == cur_handle) {
1202 buf_widx = h->widx;
1204 return size;
1209 SECONDARY EXPORTED FUNCTIONS
1210 ============================
1212 buf_get_offset
1213 buf_handle_offset
1214 buf_request_buffer_handle
1215 buf_set_base_handle
1216 buf_used
1217 register_buffering_callback
1218 unregister_buffering_callback
1220 These functions are exported, to allow interaction with the buffer.
1221 They take care of the content of the structs, and rely on the linked list
1222 management functions for all the actual handle management work.
1225 /* Get a handle offset from a pointer */
1226 ssize_t buf_get_offset(int handle_id, void *ptr)
1228 const struct memory_handle *h = find_handle(handle_id);
1229 if (!h)
1230 return ERR_HANDLE_NOT_FOUND;
1232 return (size_t)ptr - (size_t)&buffer[h->ridx];
1235 ssize_t buf_handle_offset(int handle_id)
1237 const struct memory_handle *h = find_handle(handle_id);
1238 if (!h)
1239 return ERR_HANDLE_NOT_FOUND;
1240 return h->offset;
1243 void buf_request_buffer_handle(int handle_id)
1245 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1246 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1249 void buf_set_base_handle(int handle_id)
1251 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1252 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1255 /* Return the amount of buffer space used */
1256 size_t buf_used(void)
1258 return BUF_USED;
1261 void buf_set_watermark(size_t bytes)
1263 LOGFQUEUE("buffering > Q_SET_WATERMARK %ld", (long)bytes);
1264 queue_post(&buffering_queue, Q_SET_WATERMARK, bytes);
1267 bool register_buffering_callback(buffering_callback func)
1269 int i;
1270 if (buffer_callback_count >= MAX_BUF_CALLBACKS)
1271 return false;
1272 for (i = 0; i < MAX_BUF_CALLBACKS; i++)
1274 if (buffering_callback_funcs[i] == NULL)
1276 buffering_callback_funcs[i] = func;
1277 buffer_callback_count++;
1278 return true;
1280 else if (buffering_callback_funcs[i] == func)
1281 return true;
1283 return false;
1286 void unregister_buffering_callback(buffering_callback func)
1288 int i;
1289 for (i = 0; i < MAX_BUF_CALLBACKS; i++)
1291 if (buffering_callback_funcs[i] == func)
1293 buffering_callback_funcs[i] = NULL;
1294 buffer_callback_count--;
1297 return;
1300 static void call_buffering_callbacks(enum callback_event ev, int value)
1302 logf("call_buffering_callbacks()");
1303 int i;
1304 for (i = 0; i < MAX_BUF_CALLBACKS; i++)
1306 if (buffering_callback_funcs[i])
1308 buffering_callback_funcs[i](ev, value);
1313 static void shrink_buffer_inner(struct memory_handle *h) {
1315 if (h == NULL)
1316 return;
1318 shrink_buffer_inner(h->next);
1320 shrink_handle(h);
1323 static void shrink_buffer(void) {
1324 logf("shrink_buffer()");
1325 shrink_buffer_inner(first_handle);
1328 void buffering_thread(void)
1330 bool filling = false;
1331 struct queue_event ev;
1333 while (true)
1335 cancel_cpu_boost();
1336 queue_wait_w_tmo(&buffering_queue, &ev, filling?5:HZ/2);
1338 switch (ev.id)
1340 case Q_START_FILL:
1341 LOGFQUEUE("buffering < Q_START_FILL");
1342 /* Call buffer callbacks here because this is one of two ways
1343 * to begin a full buffer fill */
1344 call_buffering_callbacks(EVENT_BUFFER_LOW, 0);
1345 shrink_buffer();
1346 queue_reply(&buffering_queue, 1);
1347 filling |= buffer_handle((int)ev.data);
1348 break;
1350 case Q_BUFFER_HANDLE:
1351 LOGFQUEUE("buffering < Q_BUFFER_HANDLE");
1352 queue_reply(&buffering_queue, 1);
1353 buffer_handle((int)ev.data);
1354 break;
1356 case Q_RESET_HANDLE:
1357 LOGFQUEUE("buffering < Q_RESET_HANDLE");
1358 queue_reply(&buffering_queue, 1);
1359 reset_handle((int)ev.data);
1360 break;
1362 case Q_CLOSE_HANDLE:
1363 LOGFQUEUE("buffering < Q_CLOSE_HANDLE");
1364 queue_reply(&buffering_queue, close_handle((int)ev.data));
1365 break;
1367 case Q_HANDLE_ADDED:
1368 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1369 /* A handle was added: the disk is spinning, so we can fill */
1370 filling = true;
1371 break;
1373 case Q_BASE_HANDLE:
1374 LOGFQUEUE("buffering < Q_BASE_HANDLE");
1375 base_handle_id = (int)ev.data;
1376 break;
1378 case Q_SET_WATERMARK:
1379 LOGFQUEUE("buffering < Q_SET_WATERMARK");
1380 conf_watermark = (size_t)ev.data;
1381 if (conf_watermark < BUFFERING_DEFAULT_FILECHUNK)
1383 logf("wmark<chunk %ld<%d",
1384 (long)conf_watermark, BUFFERING_DEFAULT_FILECHUNK);
1385 conf_watermark = BUFFERING_DEFAULT_FILECHUNK;
1387 break;
1389 #ifndef SIMULATOR
1390 case SYS_USB_CONNECTED:
1391 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1392 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1393 usb_wait_for_disconnect(&buffering_queue);
1394 break;
1395 #endif
1397 case SYS_TIMEOUT:
1398 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1399 break;
1402 update_data_counters();
1404 /* If the buffer is low, call the callbacks to get new data */
1405 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1406 call_buffering_callbacks(EVENT_BUFFER_LOW, 0);
1408 #if 0
1409 /* TODO: This needs to be fixed to use the idle callback, disable it
1410 * for simplicity until its done right */
1411 #if MEM > 8
1412 /* If the disk is spinning, take advantage by filling the buffer */
1413 else if (ata_disk_is_active() && queue_empty(&buffering_queue))
1415 if (num_handles > 0 && data_counters.useful <= high_watermark)
1416 call_buffering_callbacks(EVENT_BUFFER_LOW, 0);
1418 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1420 /* This is a new fill, shrink the buffer up first */
1421 if (!filling)
1422 shrink_buffer();
1423 filling = fill_buffer();
1424 update_data_counters();
1427 #endif
1428 #endif
1430 if (queue_empty(&buffering_queue)) {
1431 if (filling) {
1432 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1433 filling = fill_buffer();
1435 else if (ev.id == SYS_TIMEOUT)
1437 if (data_counters.remaining > 0 &&
1438 data_counters.useful <= conf_watermark) {
1439 shrink_buffer();
1440 filling = fill_buffer();
1447 void buffering_init(void) {
1448 mutex_init(&llist_mutex);
1450 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1452 queue_init(&buffering_queue, true);
1453 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list);
1455 buffering_thread_p = create_thread( buffering_thread, buffering_stack,
1456 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1457 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1458 IF_COP(, CPU));
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 buffer_callback_count = 0;
1481 memset(buffering_callback_funcs, 0, sizeof(buffering_callback_funcs));
1483 /* Set the high watermark as 75% full...or 25% empty :) */
1484 #if MEM > 8
1485 high_watermark = 3*buflen / 4;
1486 #endif
1488 thread_thaw(buffering_thread_p);
1490 return true;
1493 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1495 update_data_counters();
1496 dbgdata->num_handles = num_handles;
1497 dbgdata->data_rem = data_counters.remaining;
1498 dbgdata->wasted_space = data_counters.wasted;
1499 dbgdata->buffered_data = data_counters.buffered;
1500 dbgdata->useful_data = data_counters.useful;