Simulate the effects of sector caching a bit. Bypass I/O yield if a byte counter...
[Rockbox.git] / apps / buffering.c
blob1567a6ea9135b49e9bf39d19b6d2bd952e90003f
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 */
182 /* Buffering thread */
183 void buffering_thread(void);
184 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
185 static const char buffering_thread_name[] = "buffering";
186 static struct thread_entry *buffering_thread_p;
187 static struct event_queue buffering_queue;
188 static struct queue_sender_list buffering_queue_sender_list;
191 static void call_buffering_callbacks(enum callback_event ev, int value);
195 LINKED LIST MANAGEMENT
196 ======================
198 add_handle : Add a handle to the list
199 rm_handle : Remove a handle from the list
200 find_handle : Get a handle pointer from an ID
201 move_handle : Move a handle in the buffer (with or without its data)
203 These functions only handle the linked list structure. They don't touch the
204 contents of the struct memory_handle headers. They also change the buf_*idx
205 pointers when necessary and manage the handle IDs.
207 The first and current (== last) handle are kept track of.
208 A new handle is added at buf_widx and becomes the current one.
209 buf_widx always points to the current writing position for the current handle
210 buf_ridx always points to the location of the first handle.
211 buf_ridx == buf_widx means the buffer is empty.
215 /* Add a new handle to the linked list and return it. It will have become the
216 new current handle.
217 data_size must contain the size of what will be in the handle.
218 can_wrap tells us whether this type of data may wrap on buffer
219 alloc_all tells us if we must immediately be able to allocate data_size
220 returns a valid memory handle if all conditions for allocation are met.
221 NULL if there memory_handle itself cannot be allocated or if the
222 data_size cannot be allocated and alloc_all is set. This function's
223 only potential side effect is to allocate space for the cur_handle
224 if it returns NULL.
226 static struct memory_handle *add_handle(size_t data_size, const bool can_wrap,
227 const bool alloc_all)
229 /* gives each handle a unique id */
230 static int cur_handle_id = 0;
231 size_t shift;
232 size_t new_widx;
233 size_t len;
234 int overlap;
236 if (num_handles >= BUF_MAX_HANDLES)
237 return NULL;
239 mutex_lock(&llist_mutex);
241 if (cur_handle && cur_handle->filerem > 0) {
242 /* the current handle hasn't finished buffering. We can only add
243 a new one if there is already enough free space to finish
244 the buffering. */
245 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
246 if (RINGBUF_ADD_CROSS(cur_handle->widx, req, buf_ridx) >= 0) {
247 /* Not enough space */
248 mutex_unlock(&llist_mutex);
249 return NULL;
250 } else {
251 /* Allocate the remainder of the space for the current handle */
252 buf_widx = RINGBUF_ADD(cur_handle->widx, cur_handle->filerem);
256 /* align to 4 bytes up */
257 new_widx = RINGBUF_ADD(buf_widx, 3) & ~3;
259 len = data_size + sizeof(struct memory_handle);
261 /* First, will the handle wrap? */
262 overlap = RINGBUF_ADD_CROSS(new_widx, sizeof(struct memory_handle),
263 buffer_len - 1);
264 /* If the handle would wrap, move to the beginning of the buffer,
265 * otherwise check if the data can/would wrap and move it to the
266 * beginning if needed */
267 if (overlap > 0) {
268 new_widx = 0;
269 } else if (!can_wrap) {
270 overlap = RINGBUF_ADD_CROSS(new_widx, len, buffer_len - 1);
271 if (overlap > 0)
272 new_widx += data_size - overlap;
275 /* How far we shifted buf_widx to align things, must be < buffer_len */
276 shift = RINGBUF_SUB(new_widx, buf_widx);
278 /* How much space are we short in the actual ring buffer? */
279 overlap = RINGBUF_ADD_CROSS(buf_widx, shift + len, buf_ridx);
280 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
281 /* Not enough space for required allocations */
282 mutex_unlock(&llist_mutex);
283 return NULL;
286 /* There is enough space for the required data, advance the buf_widx and
287 * initialize the struct */
288 buf_widx = new_widx;
290 struct memory_handle *new_handle =
291 (struct memory_handle *)(&buffer[buf_widx]);
293 /* only advance the buffer write index of the size of the struct */
294 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
296 new_handle->id = cur_handle_id;
297 /* Wrap signed int is safe and 0 doesn't happen */
298 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
299 new_handle->next = NULL;
300 num_handles++;
302 if (!first_handle)
303 /* the new handle is the first one */
304 first_handle = new_handle;
306 if (cur_handle)
307 cur_handle->next = new_handle;
309 cur_handle = new_handle;
311 mutex_unlock(&llist_mutex);
312 return new_handle;
315 /* Delete a given memory handle from the linked list
316 and return true for success. Nothing is actually erased from memory. */
317 static bool rm_handle(const struct memory_handle *h)
319 if (h == NULL)
320 return true;
322 mutex_lock(&llist_mutex);
324 if (h == first_handle) {
325 first_handle = h->next;
326 if (h == cur_handle) {
327 /* h was the first and last handle: the buffer is now empty */
328 cur_handle = NULL;
329 buf_ridx = buf_widx = 0;
330 } else {
331 /* update buf_ridx to point to the new first handle */
332 buf_ridx = (void *)first_handle - (void *)buffer;
334 } else {
335 struct memory_handle *m = first_handle;
336 /* Find the previous handle */
337 while (m && m->next != h) {
338 m = m->next;
340 if (m && m->next == h) {
341 m->next = h->next;
342 if (h == cur_handle) {
343 cur_handle = m;
344 buf_widx = cur_handle->widx;
346 } else {
347 mutex_unlock(&llist_mutex);
348 return false;
352 /* Invalidate the cache to prevent it from keeping the old location of h */
353 if (h == cached_handle)
354 cached_handle = NULL;
356 num_handles--;
358 mutex_unlock(&llist_mutex);
359 return true;
362 /* Return a pointer to the memory handle of given ID.
363 NULL if the handle wasn't found */
364 static struct memory_handle *find_handle(const int handle_id)
366 if (handle_id < 0)
367 return NULL;
369 mutex_lock(&llist_mutex);
371 /* simple caching because most of the time the requested handle
372 will either be the same as the last, or the one after the last */
373 if (cached_handle)
375 if (cached_handle->id == handle_id) {
376 mutex_unlock(&llist_mutex);
377 return cached_handle;
378 } else if (cached_handle->next &&
379 (cached_handle->next->id == handle_id)) {
380 cached_handle = cached_handle->next;
381 mutex_unlock(&llist_mutex);
382 return cached_handle;
386 struct memory_handle *m = first_handle;
387 while (m && m->id != handle_id) {
388 m = m->next;
390 /* This condition can only be reached with !m or m->id == handle_id */
391 if (m)
392 cached_handle = m;
394 mutex_unlock(&llist_mutex);
395 return m;
398 /* Move a memory handle and data_size of its data delta bytes along the buffer.
399 delta maximum bytes available to move the handle. If the move is performed
400 it is set to the actual distance moved.
401 data_size is the amount of data to move along with the struct.
402 returns a valid memory_handle if the move is successful
403 NULL if the handle is NULL, the move would be less than the size of
404 a memory_handle after correcting for wraps or if the handle is not
405 found in the linked list for adjustment. This function has no side
406 effects if NULL is returned. */
407 static bool move_handle(struct memory_handle **h, size_t *delta,
408 const size_t data_size, bool can_wrap)
410 struct memory_handle *dest;
411 const struct memory_handle *src;
412 size_t newpos;
413 size_t size_to_move;
414 size_t final_delta = *delta;
415 int overlap;
417 if (h == NULL || (src = *h) == NULL)
418 return false;
420 size_to_move = sizeof(struct memory_handle) + data_size;
422 /* Align to four bytes, down */
423 final_delta &= ~3;
424 if (final_delta < sizeof(struct memory_handle)) {
425 /* It's not legal to move less than the size of the struct */
426 return false;
429 mutex_lock(&llist_mutex);
431 newpos = RINGBUF_ADD((void *)src - (void *)buffer, final_delta);
432 overlap = RINGBUF_ADD_CROSS(newpos, size_to_move, buffer_len - 1);
434 if (overlap > 0) {
435 /* Some part of the struct + data would wrap, maybe ok */
436 size_t correction = 0;
437 /* If the overlap lands inside the memory_handle */
438 if ((unsigned)overlap > data_size) {
439 /* Correct the position and real delta to prevent the struct from
440 * wrapping, this guarantees an aligned delta, I think */
441 correction = overlap - data_size;
442 } else if (!can_wrap) {
443 /* Otherwise the overlap falls in the data area and must all be
444 * backed out. This may become conditional if ever we move
445 * data that is allowed to wrap (ie audio) */
446 correction = overlap;
447 /* Align correction to four bytes, up */
448 correction = (correction+3) & ~3;
450 if (correction) {
451 if (final_delta < correction + sizeof(struct memory_handle)) {
452 /* Delta cannot end up less than the size of the struct */
453 mutex_unlock(&llist_mutex);
454 return false;
457 newpos -= correction;
458 overlap -= correction;/* Used below to know how to split the data */
459 final_delta -= correction;
463 dest = (struct memory_handle *)(&buffer[newpos]);
465 if (src == first_handle) {
466 first_handle = dest;
467 buf_ridx = newpos;
468 } else {
469 struct memory_handle *m = first_handle;
470 while (m && m->next != src) {
471 m = m->next;
473 if (m && m->next == src) {
474 m->next = dest;
475 } else {
476 mutex_unlock(&llist_mutex);
477 return false;
482 /* Update the cache to prevent it from keeping the old location of h */
483 if (src == cached_handle)
484 cached_handle = dest;
486 /* the cur_handle pointer might need updating */
487 if (src == cur_handle)
488 cur_handle = dest;
490 if (overlap > 0) {
491 size_t first_part = size_to_move - overlap;
492 memmove(dest, src, first_part);
493 memmove(buffer, (char *)src + first_part, overlap);
494 } else {
495 memmove(dest, src, size_to_move);
498 /* Update the caller with the new location of h and the distance moved */
499 *h = dest;
500 *delta = final_delta;
501 mutex_unlock(&llist_mutex);
502 return dest;
507 BUFFER SPACE MANAGEMENT
508 =======================
510 update_data_counters: Updates the values in data_counters
511 buffer_is_low : Returns true if the amount of useful data in the buffer is low
512 buffer_handle : Buffer data for a handle
513 reset_handle : Reset write position and data buffer of a handle to its offset
514 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
515 shrink_handle : Free buffer space by moving a handle
516 fill_buffer : Call buffer_handle for all handles that have data to buffer
518 These functions are used by the buffering thread to manage buffer space.
521 static void update_data_counters(void)
523 struct memory_handle *m = find_handle(base_handle_id);
524 bool is_useful = m==NULL;
526 size_t buffered = 0;
527 size_t wasted = 0;
528 size_t remaining = 0;
529 size_t useful = 0;
531 m = first_handle;
532 while (m) {
533 buffered += m->available;
534 wasted += RINGBUF_SUB(m->ridx, m->data);
535 remaining += m->filerem;
537 if (m->id == base_handle_id)
538 is_useful = true;
540 if (is_useful)
541 useful += RINGBUF_SUB(m->widx, m->ridx);
543 m = m->next;
546 data_counters.buffered = buffered;
547 data_counters.wasted = wasted;
548 data_counters.remaining = remaining;
549 data_counters.useful = useful;
552 static inline bool buffer_is_low(void)
554 update_data_counters();
555 return data_counters.useful < BUFFERING_CRITICAL_LEVEL;
558 /* Buffer data for the given handle.
559 Return whether or not the buffering should continue explicitly. */
560 static bool buffer_handle(int handle_id)
562 logf("buffer_handle(%d)", handle_id);
563 struct memory_handle *h = find_handle(handle_id);
564 if (!h)
565 return true;
567 if (h->filerem == 0) {
568 /* nothing left to buffer */
569 return true;
572 if (h->fd < 0) /* file closed, reopen */
574 if (*h->path)
575 h->fd = open(h->path, O_RDONLY);
577 if (h->fd < 0)
579 /* could not open the file, truncate it where it is */
580 h->filesize -= h->filerem;
581 h->filerem = 0;
582 return true;
585 if (h->offset)
586 lseek(h->fd, h->offset, SEEK_SET);
589 trigger_cpu_boost();
591 while (h->filerem > 0)
593 /* max amount to copy */
594 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
595 buffer_len - h->widx);
597 /* stop copying if it would overwrite the reading position */
598 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
599 return false;
601 /* This would read into the next handle, this is broken */
602 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
603 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
604 /* Try to recover by truncating this file */
605 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
606 (unsigned)((void *)h->next - (void *)buffer));
607 h->filerem -= copy_n;
608 h->filesize -= copy_n;
609 logf("buf alloc short %ld", (long)copy_n);
610 if (h->filerem)
611 continue;
612 else
613 break;
616 /* rc is the actual amount read */
617 int rc = read(h->fd, &buffer[h->widx], copy_n);
619 if (rc < 0)
621 /* Some kind of filesystem error, maybe recoverable if not codec */
622 if (h->type == TYPE_CODEC) {
623 logf("Partial codec");
624 break;
627 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
628 h->filesize -= h->filerem;
629 h->filerem = 0;
630 break;
633 /* Advance buffer */
634 h->widx = RINGBUF_ADD(h->widx, rc);
635 if (h == cur_handle)
636 buf_widx = h->widx;
637 h->available += rc;
638 h->filerem -= rc;
640 /* If this is a large file, see if we need to break or give the codec
641 * more time */
642 if (h->type == TYPE_PACKET_AUDIO &&
643 pcmbuf_is_lowdata() && !buffer_is_low())
645 sleep(1);
647 else
649 yield();
652 if (!queue_empty(&buffering_queue))
653 break;
656 if (h->filerem == 0) {
657 /* finished buffering the file */
658 close(h->fd);
659 h->fd = -1;
660 call_buffering_callbacks(EVENT_HANDLE_FINISHED, h->id);
663 return true;
666 /* Reset writing position and data buffer of a handle to its current offset.
667 Use this after having set the new offset to use. */
668 static void reset_handle(int handle_id)
670 logf("reset_handle(%d)", handle_id);
672 struct memory_handle *h = find_handle(handle_id);
673 if (!h)
674 return;
676 h->widx = h->data;
677 if (h == cur_handle)
678 buf_widx = h->widx;
679 h->available = 0;
680 h->filerem = h->filesize - h->offset;
682 if (h->fd >= 0) {
683 lseek(h->fd, h->offset, SEEK_SET);
687 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
688 static void rebuffer_handle(int handle_id, size_t newpos)
690 struct memory_handle *h = find_handle(handle_id);
691 if (!h)
692 return;
694 /* When seeking foward off of the buffer, if it is a short seek don't
695 rebuffer the whole track, just read enough to satisfy */
696 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
698 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
699 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
700 h->ridx = h->data + newpos;
701 return;
704 h->offset = newpos;
706 /* Reset the handle to its new offset */
707 LOGFQUEUE("buffering >| Q_RESET_HANDLE");
708 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
710 size_t next = (unsigned)((void *)h->next - (void *)buffer);
711 if (next - h->data < h->filesize - newpos)
713 /* There isn't enough space to rebuffer all of the track from its new
714 offset, so we ask the user to free some */
715 DEBUGF("rebuffer_handle: space is needed\n");
716 call_buffering_callbacks(EVENT_HANDLE_REBUFFER, handle_id);
719 /* Now we ask for a rebuffer */
720 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
721 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
723 h->ridx = h->data;
726 static bool close_handle(int handle_id)
728 struct memory_handle *h = find_handle(handle_id);
730 /* If the handle is not found, it is closed */
731 if (!h)
732 return true;
734 if (h->fd >= 0) {
735 close(h->fd);
736 h->fd = -1;
739 /* rm_handle returns true unless the handle somehow persists after exit */
740 return rm_handle(h);
743 /* Free buffer space by moving the handle struct right before the useful
744 part of its data buffer or by moving all the data. */
745 static void shrink_handle(struct memory_handle *h)
747 size_t delta;
749 if (!h)
750 return;
752 if (h->next && h->filerem == 0 &&
753 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
754 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
755 h->type == TYPE_ATOMIC_AUDIO))
757 /* metadata handle: we can move all of it */
758 size_t handle_distance =
759 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
760 delta = handle_distance - h->available;
762 /* The value of delta might change for alignment reasons */
763 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
764 return;
766 size_t olddata = h->data;
767 h->data = RINGBUF_ADD(h->data, delta);
768 h->ridx = RINGBUF_ADD(h->ridx, delta);
769 h->widx = RINGBUF_ADD(h->widx, delta);
771 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
772 /* when moving an mp3entry we need to readjust its pointers. */
773 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
774 (void *)&buffer[h->data],
775 (void *)&buffer[olddata]);
776 } else if (h->type == TYPE_BITMAP) {
777 /* adjust the bitmap's pointer */
778 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
779 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
782 else
784 /* only move the handle struct */
785 delta = RINGBUF_SUB(h->ridx, h->data);
786 if (!move_handle(&h, &delta, 0, true))
787 return;
789 h->data = RINGBUF_ADD(h->data, delta);
790 h->available -= delta;
791 h->offset += delta;
795 /* Fill the buffer by buffering as much data as possible for handles that still
796 have data left to buffer
797 Return whether or not to continue filling after this */
798 static bool fill_buffer(void)
800 logf("fill_buffer()");
801 struct memory_handle *m = first_handle;
802 shrink_handle(m);
803 while (queue_empty(&buffering_queue) && m) {
804 if (m->filerem > 0) {
805 if (!buffer_handle(m->id)) {
806 m = NULL;
807 break;
810 m = m->next;
813 if (m) {
814 return true;
816 else
818 #ifndef SIMULATOR
819 /* only spin the disk down if the filling wasn't interrupted by an
820 event arriving in the queue. */
821 ata_sleep();
822 #endif
823 return false;
827 #ifdef HAVE_ALBUMART
828 /* Given a file descriptor to a bitmap file, write the bitmap data to the
829 buffer, with a struct bitmap and the actual data immediately following.
830 Return value is the total size (struct + data). */
831 static int load_bitmap(const int fd)
833 int rc;
834 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
835 /* FIXME: alignment may be needed for the data buffer. */
836 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
838 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
839 bmp->maskdata = NULL;
840 #endif
842 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx);
843 rc = read_bmp_fd(fd, bmp, free, FORMAT_ANY|FORMAT_DITHER);
844 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
846 #endif
850 MAIN BUFFERING API CALLS
851 ========================
853 bufopen : Request the opening of a new handle for a file
854 bufalloc : Open a new handle for data other than a file.
855 bufclose : Close an open handle
856 bufseek : Set the read pointer in a handle
857 bufadvance : Move the read pointer in a handle
858 bufread : Copy data from a handle into a given buffer
859 bufgetdata : Give a pointer to the handle's data
861 These functions are exported, to allow interaction with the buffer.
862 They take care of the content of the structs, and rely on the linked list
863 management functions for all the actual handle management work.
867 /* Reserve space in the buffer for a file.
868 filename: name of the file to open
869 offset: offset at which to start buffering the file, useful when the first
870 (offset-1) bytes of the file aren't needed.
871 return value: <0 if the file cannot be opened, or one file already
872 queued to be opened, otherwise the handle for the file in the buffer
874 int bufopen(const char *file, size_t offset, enum data_type type)
876 int fd = open(file, O_RDONLY);
877 if (fd < 0)
878 return ERR_FILE_ERROR;
880 size_t size = filesize(fd);
881 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
883 struct memory_handle *h = add_handle(size-offset, can_wrap, false);
884 if (!h)
886 DEBUGF("bufopen: failed to add handle\n");
887 close(fd);
888 return ERR_BUFFER_FULL;
891 strncpy(h->path, file, MAX_PATH);
892 h->offset = offset;
893 h->ridx = buf_widx;
894 h->data = buf_widx;
895 h->type = type;
897 #ifdef HAVE_ALBUMART
898 if (type == TYPE_BITMAP)
900 /* Bitmap file: we load the data instead of the file */
901 int rc;
902 mutex_lock(&llist_mutex); /* Lock because load_bitmap yields */
903 rc = load_bitmap(fd);
904 if (rc <= 0)
906 rm_handle(h);
907 close(fd);
908 mutex_unlock(&llist_mutex);
909 return ERR_FILE_ERROR;
911 h->filerem = 0;
912 h->filesize = rc;
913 h->available = rc;
914 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
915 buf_widx += rc; /* safe too */
916 mutex_unlock(&llist_mutex);
918 else
919 #endif
921 h->filerem = size - offset;
922 h->filesize = size;
923 h->available = 0;
924 h->widx = buf_widx;
927 if (type == TYPE_CUESHEET) {
928 h->fd = fd;
929 /* Immediately start buffering those */
930 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
931 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
932 } else {
933 /* Other types will get buffered in the course of normal operations */
934 h->fd = -1;
935 close(fd);
938 logf("bufopen: new hdl %d", h->id);
939 return h->id;
942 /* Open a new handle from data that needs to be copied from memory.
943 src is the source buffer from which to copy data. It can be NULL to simply
944 reserve buffer space.
945 size is the requested size. The call will only be successful if the
946 requested amount of data can entirely fit in the buffer without wrapping.
947 Return value is the handle id for success or <0 for failure.
949 int bufalloc(const void *src, size_t size, enum data_type type)
951 struct memory_handle *h = add_handle(size, false, true);
953 if (!h)
954 return ERR_BUFFER_FULL;
956 if (src) {
957 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
958 /* specially take care of struct mp3entry */
959 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
960 (struct mp3entry *)src);
961 } else {
962 memcpy(&buffer[buf_widx], src, size);
966 h->fd = -1;
967 *h->path = 0;
968 h->filesize = size;
969 h->filerem = 0;
970 h->offset = 0;
971 h->ridx = buf_widx;
972 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
973 h->data = buf_widx;
974 h->available = size;
975 h->type = type;
977 buf_widx += size; /* safe too */
979 logf("bufalloc: new hdl %d", h->id);
980 return h->id;
983 /* Close the handle. Return true for success and false for failure */
984 bool bufclose(int handle_id)
986 logf("bufclose(%d)", handle_id);
988 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
989 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
992 /* Set reading index in handle (relatively to the start of the file).
993 Access before the available data will trigger a rebuffer.
994 Return 0 for success and < 0 for failure:
995 -1 if the handle wasn't found
996 -2 if the new requested position was beyond the end of the file
998 int bufseek(int handle_id, size_t newpos)
1000 struct memory_handle *h = find_handle(handle_id);
1001 if (!h)
1002 return ERR_HANDLE_NOT_FOUND;
1004 if (newpos > h->filesize) {
1005 /* access beyond the end of the file */
1006 return ERR_INVALID_VALUE;
1008 else if (newpos < h->offset || h->offset + h->available < newpos) {
1009 /* access before or after buffered data. A rebuffer is needed. */
1010 rebuffer_handle(handle_id, newpos);
1012 else {
1013 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1015 return 0;
1018 /* Advance the reading index in a handle (relatively to its current position).
1019 Return 0 for success and < 0 for failure */
1020 int bufadvance(int handle_id, off_t offset)
1022 const struct memory_handle *h = find_handle(handle_id);
1023 if (!h)
1024 return ERR_HANDLE_NOT_FOUND;
1026 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1027 return bufseek(handle_id, newpos);
1030 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1031 * actual amount of data available for reading. This function explicitly
1032 * does not check the validity of the input handle. It does do range checks
1033 * on size and returns a valid (and explicit) amount of data for reading */
1034 static struct memory_handle *prep_bufdata(const int handle_id, size_t *size,
1035 const bool guardbuf_limit)
1037 struct memory_handle *h = find_handle(handle_id);
1038 if (!h)
1039 return NULL;
1041 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1043 if (avail == 0 && h->filerem == 0)
1045 /* File is finished reading */
1046 *size = 0;
1047 return h;
1050 if (*size == 0 || *size > avail + h->filerem)
1051 *size = avail + h->filerem;
1053 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1055 logf("data request > guardbuf");
1056 /* If more than the size of the guardbuf is requested and this is a
1057 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1058 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1059 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1062 if (h->filerem > 0 && avail < *size)
1064 /* Data isn't ready. Request buffering */
1065 buf_request_buffer_handle(handle_id);
1066 /* Wait for the data to be ready */
1069 sleep(1);
1070 /* it is not safe for a non-buffering thread to sleep while
1071 * holding a handle */
1072 h = find_handle(handle_id);
1073 if (!h)
1074 return NULL;
1075 avail = RINGBUF_SUB(h->widx, h->ridx);
1077 while (h->filerem > 0 && avail < *size);
1080 *size = MIN(*size,avail);
1081 return h;
1084 /* Copy data from the given handle to the dest buffer.
1085 Return the number of bytes copied or < 0 for failure (handle not found).
1086 The caller is blocked until the requested amount of data is available.
1088 ssize_t bufread(int handle_id, size_t size, void *dest)
1090 const struct memory_handle *h;
1092 h = prep_bufdata(handle_id, &size, false);
1093 if (!h)
1094 return ERR_HANDLE_NOT_FOUND;
1096 if (h->ridx + size > buffer_len)
1098 /* the data wraps around the end of the buffer */
1099 size_t read = buffer_len - h->ridx;
1100 memcpy(dest, &buffer[h->ridx], read);
1101 memcpy(dest+read, buffer, size - read);
1103 else
1105 memcpy(dest, &buffer[h->ridx], size);
1108 return size;
1111 /* Update the "data" pointer to make the handle's data available to the caller.
1112 Return the length of the available linear data or < 0 for failure (handle
1113 not found).
1114 The caller is blocked until the requested amount of data is available.
1115 size is the amount of linear data requested. it can be 0 to get as
1116 much as possible.
1117 The guard buffer may be used to provide the requested size. This means it's
1118 unsafe to request more than the size of the guard buffer.
1120 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1122 const struct memory_handle *h;
1124 h = prep_bufdata(handle_id, &size, true);
1125 if (!h)
1126 return ERR_HANDLE_NOT_FOUND;
1128 if (h->ridx + size > buffer_len)
1130 /* the data wraps around the end of the buffer :
1131 use the guard buffer to provide the requested amount of data. */
1132 size_t copy_n = h->ridx + size - buffer_len;
1133 /* prep_bufdata ensures size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1134 so copy_n <= GUARD_BUFSIZE */
1135 memcpy(guard_buffer, (unsigned char *)buffer, copy_n);
1138 *data = &buffer[h->ridx];
1139 return size;
1142 ssize_t bufgettail(int handle_id, size_t size, void **data)
1144 size_t tidx;
1146 const struct memory_handle *h;
1148 h = find_handle(handle_id);
1150 if (!h)
1151 return ERR_HANDLE_NOT_FOUND;
1153 if (h->filerem)
1154 return ERR_HANDLE_NOT_DONE;
1156 /* We don't support tail requests of > guardbuf_size, for simplicity */
1157 if (size > GUARD_BUFSIZE)
1158 return ERR_INVALID_VALUE;
1160 tidx = RINGBUF_SUB(h->widx, size);
1162 if (tidx + size > buffer_len)
1164 size_t copy_n = tidx + size - buffer_len;
1165 memcpy(guard_buffer, (unsigned char *)buffer, copy_n);
1168 *data = &buffer[tidx];
1169 return size;
1172 ssize_t bufcuttail(int handle_id, size_t size)
1174 struct memory_handle *h;
1176 h = find_handle(handle_id);
1178 if (!h)
1179 return ERR_HANDLE_NOT_FOUND;
1181 if (h->filerem)
1182 return ERR_HANDLE_NOT_DONE;
1184 if (h->available < size)
1185 size = h->available;
1187 h->available -= size;
1188 h->filesize -= size;
1189 h->widx = RINGBUF_SUB(h->widx, size);
1190 if (h == cur_handle) {
1191 buf_widx = h->widx;
1193 return size;
1198 SECONDARY EXPORTED FUNCTIONS
1199 ============================
1201 buf_get_offset
1202 buf_handle_offset
1203 buf_request_buffer_handle
1204 buf_set_base_handle
1205 buf_used
1206 register_buffering_callback
1207 unregister_buffering_callback
1209 These functions are exported, to allow interaction with the buffer.
1210 They take care of the content of the structs, and rely on the linked list
1211 management functions for all the actual handle management work.
1214 /* Get a handle offset from a pointer */
1215 ssize_t buf_get_offset(int handle_id, void *ptr)
1217 const struct memory_handle *h = find_handle(handle_id);
1218 if (!h)
1219 return ERR_HANDLE_NOT_FOUND;
1221 return (size_t)ptr - (size_t)&buffer[h->ridx];
1224 ssize_t buf_handle_offset(int handle_id)
1226 const struct memory_handle *h = find_handle(handle_id);
1227 if (!h)
1228 return ERR_HANDLE_NOT_FOUND;
1229 return h->offset;
1232 void buf_request_buffer_handle(int handle_id)
1234 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1235 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1238 void buf_set_base_handle(int handle_id)
1240 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1241 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1244 /* Return the amount of buffer space used */
1245 size_t buf_used(void)
1247 return BUF_USED;
1250 void buf_set_watermark(size_t bytes)
1252 LOGFQUEUE("buffering > Q_SET_WATERMARK %ld", (long)bytes);
1253 queue_post(&buffering_queue, Q_SET_WATERMARK, bytes);
1256 bool register_buffering_callback(buffering_callback func)
1258 int i;
1259 if (buffer_callback_count >= MAX_BUF_CALLBACKS)
1260 return false;
1261 for (i = 0; i < MAX_BUF_CALLBACKS; i++)
1263 if (buffering_callback_funcs[i] == NULL)
1265 buffering_callback_funcs[i] = func;
1266 buffer_callback_count++;
1267 return true;
1269 else if (buffering_callback_funcs[i] == func)
1270 return true;
1272 return false;
1275 void unregister_buffering_callback(buffering_callback func)
1277 int i;
1278 for (i = 0; i < MAX_BUF_CALLBACKS; i++)
1280 if (buffering_callback_funcs[i] == func)
1282 buffering_callback_funcs[i] = NULL;
1283 buffer_callback_count--;
1286 return;
1289 static void call_buffering_callbacks(enum callback_event ev, int value)
1291 logf("call_buffering_callbacks()");
1292 int i;
1293 for (i = 0; i < MAX_BUF_CALLBACKS; i++)
1295 if (buffering_callback_funcs[i])
1297 buffering_callback_funcs[i](ev, value);
1302 static void shrink_buffer_inner(struct memory_handle *h) {
1304 if (h == NULL)
1305 return;
1307 shrink_buffer_inner(h->next);
1309 shrink_handle(h);
1312 static void shrink_buffer(void) {
1313 logf("shrink_buffer()");
1314 shrink_buffer_inner(first_handle);
1317 void buffering_thread(void)
1319 bool filling = false;
1320 struct queue_event ev;
1322 while (true)
1324 cancel_cpu_boost();
1325 queue_wait_w_tmo(&buffering_queue, &ev, filling?5:HZ/2);
1327 switch (ev.id)
1329 case Q_START_FILL:
1330 LOGFQUEUE("buffering < Q_START_FILL");
1331 /* Call buffer callbacks here because this is one of two ways
1332 * to begin a full buffer fill */
1333 call_buffering_callbacks(EVENT_BUFFER_LOW, 0);
1334 shrink_buffer();
1335 queue_reply(&buffering_queue, 1);
1336 filling |= buffer_handle((int)ev.data);
1337 break;
1339 case Q_BUFFER_HANDLE:
1340 LOGFQUEUE("buffering < Q_BUFFER_HANDLE");
1341 queue_reply(&buffering_queue, 1);
1342 buffer_handle((int)ev.data);
1343 break;
1345 case Q_RESET_HANDLE:
1346 LOGFQUEUE("buffering < Q_RESET_HANDLE");
1347 queue_reply(&buffering_queue, 1);
1348 reset_handle((int)ev.data);
1349 break;
1351 case Q_CLOSE_HANDLE:
1352 LOGFQUEUE("buffering < Q_CLOSE_HANDLE");
1353 queue_reply(&buffering_queue, close_handle((int)ev.data));
1354 break;
1356 case Q_BASE_HANDLE:
1357 LOGFQUEUE("buffering < Q_BASE_HANDLE");
1358 base_handle_id = (int)ev.data;
1359 break;
1361 case Q_SET_WATERMARK:
1362 LOGFQUEUE("buffering < Q_SET_WATERMARK");
1363 conf_watermark = (size_t)ev.data;
1364 if (conf_watermark < BUFFERING_DEFAULT_FILECHUNK)
1366 logf("wmark<chunk %ld<%d",
1367 (long)conf_watermark, BUFFERING_DEFAULT_FILECHUNK);
1368 conf_watermark = BUFFERING_DEFAULT_FILECHUNK;
1370 break;
1372 #ifndef SIMULATOR
1373 case SYS_USB_CONNECTED:
1374 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1375 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1376 usb_wait_for_disconnect(&buffering_queue);
1377 break;
1378 #endif
1380 case SYS_TIMEOUT:
1381 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1382 break;
1385 update_data_counters();
1387 /* If the buffer is low, call the callbacks to get new data */
1388 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1389 call_buffering_callbacks(EVENT_BUFFER_LOW, 0);
1391 #if 0
1392 /* TODO: This needs to be fixed to use the idle callback, disable it
1393 * for simplicity until its done right */
1394 #if MEM > 8
1395 /* If the disk is spinning, take advantage by filling the buffer */
1396 else if (ata_disk_is_active() && queue_empty(&buffering_queue))
1398 if (num_handles > 0 && data_counters.useful <= high_watermark)
1399 call_buffering_callbacks(EVENT_BUFFER_LOW, 0);
1401 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1403 /* This is a new fill, shrink the buffer up first */
1404 if (!filling)
1405 shrink_buffer();
1406 filling = fill_buffer();
1407 update_data_counters();
1410 #endif
1411 #endif
1413 if (queue_empty(&buffering_queue)) {
1414 if (filling) {
1415 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1416 filling = fill_buffer();
1418 else if (ev.id == SYS_TIMEOUT)
1420 if (data_counters.remaining > 0 &&
1421 data_counters.useful <= conf_watermark) {
1422 shrink_buffer();
1423 filling = fill_buffer();
1430 void buffering_init(void) {
1431 mutex_init(&llist_mutex);
1433 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1435 queue_init(&buffering_queue, true);
1436 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list);
1438 buffering_thread_p = create_thread( buffering_thread, buffering_stack,
1439 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1440 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1441 IF_COP(, CPU));
1444 /* Initialise the buffering subsystem */
1445 bool buffering_reset(char *buf, size_t buflen)
1447 if (!buf || !buflen)
1448 return false;
1450 buffer = buf;
1451 buffer_len = buflen;
1452 guard_buffer = buf + buflen;
1454 buf_widx = 0;
1455 buf_ridx = 0;
1457 first_handle = NULL;
1458 cur_handle = NULL;
1459 cached_handle = NULL;
1460 num_handles = 0;
1461 base_handle_id = -1;
1463 buffer_callback_count = 0;
1464 memset(buffering_callback_funcs, 0, sizeof(buffering_callback_funcs));
1466 /* Set the high watermark as 75% full...or 25% empty :) */
1467 #if MEM > 8
1468 high_watermark = 3*buflen / 4;
1469 #endif
1471 thread_thaw(buffering_thread_p);
1473 return true;
1476 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1478 update_data_counters();
1479 dbgdata->num_handles = num_handles;
1480 dbgdata->data_rem = data_counters.remaining;
1481 dbgdata->wasted_space = data_counters.wasted;
1482 dbgdata->buffered_data = data_counters.buffered;
1483 dbgdata->useful_data = data_counters.useful;