Explicitly set the dialog's result code for TTS / Encoder windows. Fixes an issue...
[Rockbox.git] / apps / buffering.c
blobe2057d17ab96146924c4b926e893195b4fd15183
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 mutex_lock(&llist_mutex);
527 m = first_handle;
528 while (m) {
529 buffered += m->available;
530 wasted += RINGBUF_SUB(m->ridx, m->data);
531 remaining += m->filerem;
533 if (m->id == base_handle_id)
534 is_useful = true;
536 if (is_useful)
537 useful += RINGBUF_SUB(m->widx, m->ridx);
539 m = m->next;
542 mutex_unlock(&llist_mutex);
544 data_counters.buffered = buffered;
545 data_counters.wasted = wasted;
546 data_counters.remaining = remaining;
547 data_counters.useful = useful;
550 static inline bool buffer_is_low(void)
552 update_data_counters();
553 return data_counters.useful < BUFFERING_CRITICAL_LEVEL;
556 /* Buffer data for the given handle.
557 Return whether or not the buffering should continue explicitly. */
558 static bool buffer_handle(int handle_id)
560 logf("buffer_handle(%d)", handle_id);
561 struct memory_handle *h = find_handle(handle_id);
562 if (!h)
563 return true;
565 if (h->filerem == 0) {
566 /* nothing left to buffer */
567 return true;
570 if (h->fd < 0) /* file closed, reopen */
572 if (*h->path)
573 h->fd = open(h->path, O_RDONLY);
575 if (h->fd < 0)
577 /* could not open the file, truncate it where it is */
578 h->filesize -= h->filerem;
579 h->filerem = 0;
580 return true;
583 if (h->offset)
584 lseek(h->fd, h->offset, SEEK_SET);
587 trigger_cpu_boost();
589 if (h->type == TYPE_ID3)
591 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
593 /* metadata parsing failed: clear the buffer. */
594 memset(buffer + h->data, 0, sizeof(struct mp3entry));
596 close(h->fd);
597 h->fd = -1;
598 h->filerem = 0;
599 h->available = sizeof(struct mp3entry);
600 h->widx += sizeof(struct mp3entry);
601 send_event(EVENT_HANDLE_FINISHED, &h->id);
602 return true;
605 while (h->filerem > 0)
607 /* max amount to copy */
608 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
609 buffer_len - h->widx);
611 /* stop copying if it would overwrite the reading position */
612 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
613 return false;
615 /* This would read into the next handle, this is broken */
616 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
617 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
618 /* Try to recover by truncating this file */
619 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
620 (unsigned)((void *)h->next - (void *)buffer));
621 h->filerem -= copy_n;
622 h->filesize -= copy_n;
623 logf("buf alloc short %ld", (long)copy_n);
624 if (h->filerem)
625 continue;
626 else
627 break;
630 /* rc is the actual amount read */
631 int rc = read(h->fd, &buffer[h->widx], copy_n);
633 if (rc < 0)
635 /* Some kind of filesystem error, maybe recoverable if not codec */
636 if (h->type == TYPE_CODEC) {
637 logf("Partial codec");
638 break;
641 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
642 h->filesize -= h->filerem;
643 h->filerem = 0;
644 break;
647 /* Advance buffer */
648 h->widx = RINGBUF_ADD(h->widx, rc);
649 if (h == cur_handle)
650 buf_widx = h->widx;
651 h->available += rc;
652 h->filerem -= rc;
654 /* If this is a large file, see if we need to break or give the codec
655 * more time */
656 if (h->type == TYPE_PACKET_AUDIO &&
657 pcmbuf_is_lowdata() && !buffer_is_low())
659 sleep(1);
661 else
663 yield();
666 if (!queue_empty(&buffering_queue))
667 break;
670 if (h->filerem == 0) {
671 /* finished buffering the file */
672 close(h->fd);
673 h->fd = -1;
674 send_event(EVENT_HANDLE_FINISHED, &h->id);
677 return true;
680 /* Reset writing position and data buffer of a handle to its current offset.
681 Use this after having set the new offset to use. */
682 static void reset_handle(int handle_id)
684 logf("reset_handle(%d)", handle_id);
686 struct memory_handle *h = find_handle(handle_id);
687 if (!h)
688 return;
690 h->widx = h->data;
691 if (h == cur_handle)
692 buf_widx = h->widx;
693 h->available = 0;
694 h->filerem = h->filesize - h->offset;
696 if (h->fd >= 0) {
697 lseek(h->fd, h->offset, SEEK_SET);
701 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
702 static void rebuffer_handle(int handle_id, size_t newpos)
704 struct memory_handle *h = find_handle(handle_id);
705 if (!h)
706 return;
708 /* When seeking foward off of the buffer, if it is a short seek don't
709 rebuffer the whole track, just read enough to satisfy */
710 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
712 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
713 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
714 h->ridx = h->data + newpos;
715 return;
718 h->offset = newpos;
720 /* Reset the handle to its new offset */
721 LOGFQUEUE("buffering >| Q_RESET_HANDLE");
722 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
724 size_t next = (unsigned)((void *)h->next - (void *)buffer);
725 if (next - h->data < h->filesize - newpos)
727 /* There isn't enough space to rebuffer all of the track from its new
728 offset, so we ask the user to free some */
729 DEBUGF("rebuffer_handle: space is needed\n");
730 send_event(EVENT_HANDLE_REBUFFER, &handle_id);
733 /* Now we ask for a rebuffer */
734 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
735 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
737 h->ridx = h->data;
740 static bool close_handle(int handle_id)
742 struct memory_handle *h = find_handle(handle_id);
744 /* If the handle is not found, it is closed */
745 if (!h)
746 return true;
748 if (h->fd >= 0) {
749 close(h->fd);
750 h->fd = -1;
753 /* rm_handle returns true unless the handle somehow persists after exit */
754 return rm_handle(h);
757 /* Free buffer space by moving the handle struct right before the useful
758 part of its data buffer or by moving all the data. */
759 static void shrink_handle(struct memory_handle *h)
761 size_t delta;
763 if (!h)
764 return;
766 if (h->next && h->filerem == 0 &&
767 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
768 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
769 h->type == TYPE_ATOMIC_AUDIO))
771 /* metadata handle: we can move all of it */
772 size_t handle_distance =
773 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
774 delta = handle_distance - h->available;
776 /* The value of delta might change for alignment reasons */
777 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
778 return;
780 size_t olddata = h->data;
781 h->data = RINGBUF_ADD(h->data, delta);
782 h->ridx = RINGBUF_ADD(h->ridx, delta);
783 h->widx = RINGBUF_ADD(h->widx, delta);
785 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
786 /* when moving an mp3entry we need to readjust its pointers. */
787 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
788 (void *)&buffer[h->data],
789 (const void *)&buffer[olddata]);
790 } else if (h->type == TYPE_BITMAP) {
791 /* adjust the bitmap's pointer */
792 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
793 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
796 else
798 /* only move the handle struct */
799 delta = RINGBUF_SUB(h->ridx, h->data);
800 if (!move_handle(&h, &delta, 0, true))
801 return;
803 h->data = RINGBUF_ADD(h->data, delta);
804 h->available -= delta;
805 h->offset += delta;
809 /* Fill the buffer by buffering as much data as possible for handles that still
810 have data left to buffer
811 Return whether or not to continue filling after this */
812 static bool fill_buffer(void)
814 logf("fill_buffer()");
815 struct memory_handle *m = first_handle;
816 shrink_handle(m);
817 while (queue_empty(&buffering_queue) && m) {
818 if (m->filerem > 0) {
819 if (!buffer_handle(m->id)) {
820 m = NULL;
821 break;
824 m = m->next;
827 if (m) {
828 return true;
830 else
832 /* only spin the disk down if the filling wasn't interrupted by an
833 event arriving in the queue. */
834 ata_sleep();
835 return false;
839 #ifdef HAVE_ALBUMART
840 /* Given a file descriptor to a bitmap file, write the bitmap data to the
841 buffer, with a struct bitmap and the actual data immediately following.
842 Return value is the total size (struct + data). */
843 static int load_bitmap(int fd)
845 int rc;
846 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
847 /* FIXME: alignment may be needed for the data buffer. */
848 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
850 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
851 bmp->maskdata = NULL;
852 #endif
854 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx);
855 rc = read_bmp_fd(fd, bmp, free, FORMAT_ANY|FORMAT_DITHER);
856 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
858 #endif
862 MAIN BUFFERING API CALLS
863 ========================
865 bufopen : Request the opening of a new handle for a file
866 bufalloc : Open a new handle for data other than a file.
867 bufclose : Close an open handle
868 bufseek : Set the read pointer in a handle
869 bufadvance : Move the read pointer in a handle
870 bufread : Copy data from a handle into a given buffer
871 bufgetdata : Give a pointer to the handle's data
873 These functions are exported, to allow interaction with the buffer.
874 They take care of the content of the structs, and rely on the linked list
875 management functions for all the actual handle management work.
879 /* Reserve space in the buffer for a file.
880 filename: name of the file to open
881 offset: offset at which to start buffering the file, useful when the first
882 (offset-1) bytes of the file aren't needed.
883 return value: <0 if the file cannot be opened, or one file already
884 queued to be opened, otherwise the handle for the file in the buffer
886 int bufopen(const char *file, size_t offset, enum data_type type)
888 if (type == TYPE_ID3)
890 /* ID3 case: allocate space, init the handle and return. */
892 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
893 if (!h)
894 return ERR_BUFFER_FULL;
896 h->fd = -1;
897 h->filesize = sizeof(struct mp3entry);
898 h->filerem = sizeof(struct mp3entry);
899 h->offset = 0;
900 h->data = buf_widx;
901 h->ridx = buf_widx;
902 h->widx = buf_widx;
903 h->available = 0;
904 h->type = type;
905 strncpy(h->path, file, MAX_PATH);
907 buf_widx += sizeof(struct mp3entry); /* safe because the handle
908 can't wrap */
909 return h->id;
912 /* Other cases: there is a little more work. */
914 int fd = open(file, O_RDONLY);
915 if (fd < 0)
916 return ERR_FILE_ERROR;
918 size_t size = filesize(fd);
919 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
921 size_t adjusted_offset = offset;
922 if (adjusted_offset > size)
923 adjusted_offset = 0;
925 struct memory_handle *h = add_handle(size-adjusted_offset, can_wrap, false);
926 if (!h)
928 DEBUGF("bufopen: failed to add handle\n");
929 close(fd);
930 return ERR_BUFFER_FULL;
933 strncpy(h->path, file, MAX_PATH);
934 h->offset = adjusted_offset;
935 h->ridx = buf_widx;
936 h->data = buf_widx;
937 h->type = type;
939 #ifdef HAVE_ALBUMART
940 if (type == TYPE_BITMAP)
942 /* Bitmap file: we load the data instead of the file */
943 int rc;
944 mutex_lock(&llist_mutex); /* Lock because load_bitmap yields */
945 rc = load_bitmap(fd);
946 if (rc <= 0)
948 rm_handle(h);
949 close(fd);
950 mutex_unlock(&llist_mutex);
951 return ERR_FILE_ERROR;
953 h->filerem = 0;
954 h->filesize = rc;
955 h->available = rc;
956 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
957 buf_widx += rc; /* safe too */
958 mutex_unlock(&llist_mutex);
960 else
961 #endif
963 h->filerem = size - adjusted_offset;
964 h->filesize = size;
965 h->available = 0;
966 h->widx = buf_widx;
969 if (type == TYPE_CUESHEET) {
970 h->fd = fd;
971 /* Immediately start buffering those */
972 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
973 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
974 } else {
975 /* Other types will get buffered in the course of normal operations */
976 h->fd = -1;
977 close(fd);
979 /* Inform the buffering thread that we added a handle */
980 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
981 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
984 logf("bufopen: new hdl %d", h->id);
985 return h->id;
988 /* Open a new handle from data that needs to be copied from memory.
989 src is the source buffer from which to copy data. It can be NULL to simply
990 reserve buffer space.
991 size is the requested size. The call will only be successful if the
992 requested amount of data can entirely fit in the buffer without wrapping.
993 Return value is the handle id for success or <0 for failure.
995 int bufalloc(const void *src, size_t size, enum data_type type)
997 struct memory_handle *h = add_handle(size, false, true);
999 if (!h)
1000 return ERR_BUFFER_FULL;
1002 if (src) {
1003 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1004 /* specially take care of struct mp3entry */
1005 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1006 (const struct mp3entry *)src);
1007 } else {
1008 memcpy(&buffer[buf_widx], src, size);
1012 h->fd = -1;
1013 *h->path = 0;
1014 h->filesize = size;
1015 h->filerem = 0;
1016 h->offset = 0;
1017 h->ridx = buf_widx;
1018 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1019 h->data = buf_widx;
1020 h->available = size;
1021 h->type = type;
1023 buf_widx += size; /* safe too */
1025 logf("bufalloc: new hdl %d", h->id);
1026 return h->id;
1029 /* Close the handle. Return true for success and false for failure */
1030 bool bufclose(int handle_id)
1032 logf("bufclose(%d)", handle_id);
1034 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1035 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1038 /* Set reading index in handle (relatively to the start of the file).
1039 Access before the available data will trigger a rebuffer.
1040 Return 0 for success and < 0 for failure:
1041 -1 if the handle wasn't found
1042 -2 if the new requested position was beyond the end of the file
1044 int bufseek(int handle_id, size_t newpos)
1046 struct memory_handle *h = find_handle(handle_id);
1047 if (!h)
1048 return ERR_HANDLE_NOT_FOUND;
1050 if (newpos > h->filesize) {
1051 /* access beyond the end of the file */
1052 return ERR_INVALID_VALUE;
1054 else if (newpos < h->offset || h->offset + h->available < newpos) {
1055 /* access before or after buffered data. A rebuffer is needed. */
1056 rebuffer_handle(handle_id, newpos);
1058 else {
1059 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1061 return 0;
1064 /* Advance the reading index in a handle (relatively to its current position).
1065 Return 0 for success and < 0 for failure */
1066 int bufadvance(int handle_id, off_t offset)
1068 const struct memory_handle *h = find_handle(handle_id);
1069 if (!h)
1070 return ERR_HANDLE_NOT_FOUND;
1072 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1073 return bufseek(handle_id, newpos);
1076 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1077 * actual amount of data available for reading. This function explicitly
1078 * does not check the validity of the input handle. It does do range checks
1079 * on size and returns a valid (and explicit) amount of data for reading */
1080 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1081 bool guardbuf_limit)
1083 struct memory_handle *h = find_handle(handle_id);
1084 if (!h)
1085 return NULL;
1087 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1089 if (avail == 0 && h->filerem == 0)
1091 /* File is finished reading */
1092 *size = 0;
1093 return h;
1096 if (*size == 0 || *size > avail + h->filerem)
1097 *size = avail + h->filerem;
1099 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1101 logf("data request > guardbuf");
1102 /* If more than the size of the guardbuf is requested and this is a
1103 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1104 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1105 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1108 if (h->filerem > 0 && avail < *size)
1110 /* Data isn't ready. Request buffering */
1111 buf_request_buffer_handle(handle_id);
1112 /* Wait for the data to be ready */
1115 sleep(1);
1116 /* it is not safe for a non-buffering thread to sleep while
1117 * holding a handle */
1118 h = find_handle(handle_id);
1119 if (!h)
1120 return NULL;
1121 avail = RINGBUF_SUB(h->widx, h->ridx);
1123 while (h->filerem > 0 && avail < *size);
1126 *size = MIN(*size,avail);
1127 return h;
1130 /* Copy data from the given handle to the dest buffer.
1131 Return the number of bytes copied or < 0 for failure (handle not found).
1132 The caller is blocked until the requested amount of data is available.
1134 ssize_t bufread(int handle_id, size_t size, void *dest)
1136 const struct memory_handle *h;
1137 size_t adjusted_size = size;
1139 h = prep_bufdata(handle_id, &adjusted_size, false);
1140 if (!h)
1141 return ERR_HANDLE_NOT_FOUND;
1143 if (h->ridx + adjusted_size > buffer_len)
1145 /* the data wraps around the end of the buffer */
1146 size_t read = buffer_len - h->ridx;
1147 memcpy(dest, &buffer[h->ridx], read);
1148 memcpy(dest+read, buffer, adjusted_size - read);
1150 else
1152 memcpy(dest, &buffer[h->ridx], adjusted_size);
1155 return adjusted_size;
1158 /* Update the "data" pointer to make the handle's data available to the caller.
1159 Return the length of the available linear data or < 0 for failure (handle
1160 not found).
1161 The caller is blocked until the requested amount of data is available.
1162 size is the amount of linear data requested. it can be 0 to get as
1163 much as possible.
1164 The guard buffer may be used to provide the requested size. This means it's
1165 unsafe to request more than the size of the guard buffer.
1167 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1169 const struct memory_handle *h;
1170 size_t adjusted_size = size;
1172 h = prep_bufdata(handle_id, &adjusted_size, true);
1173 if (!h)
1174 return ERR_HANDLE_NOT_FOUND;
1176 if (h->ridx + adjusted_size > buffer_len)
1178 /* the data wraps around the end of the buffer :
1179 use the guard buffer to provide the requested amount of data. */
1180 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1181 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1182 so copy_n <= GUARD_BUFSIZE */
1183 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1186 if (data)
1187 *data = &buffer[h->ridx];
1189 return adjusted_size;
1192 ssize_t bufgettail(int handle_id, size_t size, void **data)
1194 size_t tidx;
1196 const struct memory_handle *h;
1198 h = find_handle(handle_id);
1200 if (!h)
1201 return ERR_HANDLE_NOT_FOUND;
1203 if (h->filerem)
1204 return ERR_HANDLE_NOT_DONE;
1206 /* We don't support tail requests of > guardbuf_size, for simplicity */
1207 if (size > GUARD_BUFSIZE)
1208 return ERR_INVALID_VALUE;
1210 tidx = RINGBUF_SUB(h->widx, size);
1212 if (tidx + size > buffer_len)
1214 size_t copy_n = tidx + size - buffer_len;
1215 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1218 *data = &buffer[tidx];
1219 return size;
1222 ssize_t bufcuttail(int handle_id, size_t size)
1224 struct memory_handle *h;
1225 size_t adjusted_size = size;
1227 h = find_handle(handle_id);
1229 if (!h)
1230 return ERR_HANDLE_NOT_FOUND;
1232 if (h->filerem)
1233 return ERR_HANDLE_NOT_DONE;
1235 if (h->available < adjusted_size)
1236 adjusted_size = h->available;
1238 h->available -= adjusted_size;
1239 h->filesize -= adjusted_size;
1240 h->widx = RINGBUF_SUB(h->widx, adjusted_size);
1241 if (h == cur_handle)
1242 buf_widx = h->widx;
1244 return adjusted_size;
1249 SECONDARY EXPORTED FUNCTIONS
1250 ============================
1252 buf_get_offset
1253 buf_handle_offset
1254 buf_request_buffer_handle
1255 buf_set_base_handle
1256 buf_used
1257 register_buffering_callback
1258 unregister_buffering_callback
1260 These functions are exported, to allow interaction with the buffer.
1261 They take care of the content of the structs, and rely on the linked list
1262 management functions for all the actual handle management work.
1265 /* Get a handle offset from a pointer */
1266 ssize_t buf_get_offset(int handle_id, void *ptr)
1268 const struct memory_handle *h = find_handle(handle_id);
1269 if (!h)
1270 return ERR_HANDLE_NOT_FOUND;
1272 return (size_t)ptr - (size_t)&buffer[h->ridx];
1275 ssize_t buf_handle_offset(int handle_id)
1277 const struct memory_handle *h = find_handle(handle_id);
1278 if (!h)
1279 return ERR_HANDLE_NOT_FOUND;
1280 return h->offset;
1283 void buf_request_buffer_handle(int handle_id)
1285 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1286 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1289 void buf_set_base_handle(int handle_id)
1291 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1292 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1295 /* Return the amount of buffer space used */
1296 size_t buf_used(void)
1298 return BUF_USED;
1301 void buf_set_watermark(size_t bytes)
1303 LOGFQUEUE("buffering > Q_SET_WATERMARK %ld", (long)bytes);
1304 queue_post(&buffering_queue, Q_SET_WATERMARK, bytes);
1307 static void shrink_buffer_inner(struct memory_handle *h)
1309 if (h == NULL)
1310 return;
1312 shrink_buffer_inner(h->next);
1314 shrink_handle(h);
1317 static void shrink_buffer(void)
1319 logf("shrink_buffer()");
1320 shrink_buffer_inner(first_handle);
1323 void buffering_thread(void)
1325 bool filling = false;
1326 struct queue_event ev;
1328 while (true)
1330 if (!filling) {
1331 cancel_cpu_boost();
1334 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1336 switch (ev.id)
1338 case Q_START_FILL:
1339 LOGFQUEUE("buffering < Q_START_FILL");
1340 /* Call buffer callbacks here because this is one of two ways
1341 * to begin a full buffer fill */
1342 send_event(EVENT_BUFFER_LOW, 0);
1343 shrink_buffer();
1344 queue_reply(&buffering_queue, 1);
1345 filling |= buffer_handle((int)ev.data);
1346 break;
1348 case Q_BUFFER_HANDLE:
1349 LOGFQUEUE("buffering < Q_BUFFER_HANDLE");
1350 queue_reply(&buffering_queue, 1);
1351 buffer_handle((int)ev.data);
1352 break;
1354 case Q_RESET_HANDLE:
1355 LOGFQUEUE("buffering < Q_RESET_HANDLE");
1356 queue_reply(&buffering_queue, 1);
1357 reset_handle((int)ev.data);
1358 break;
1360 case Q_CLOSE_HANDLE:
1361 LOGFQUEUE("buffering < Q_CLOSE_HANDLE");
1362 queue_reply(&buffering_queue, close_handle((int)ev.data));
1363 break;
1365 case Q_HANDLE_ADDED:
1366 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1367 /* A handle was added: the disk is spinning, so we can fill */
1368 filling = true;
1369 break;
1371 case Q_BASE_HANDLE:
1372 LOGFQUEUE("buffering < Q_BASE_HANDLE");
1373 base_handle_id = (int)ev.data;
1374 break;
1376 case Q_SET_WATERMARK:
1377 LOGFQUEUE("buffering < Q_SET_WATERMARK");
1378 conf_watermark = (size_t)ev.data;
1379 if (conf_watermark < BUFFERING_DEFAULT_FILECHUNK)
1381 logf("wmark<chunk %ld<%d",
1382 (long)conf_watermark, BUFFERING_DEFAULT_FILECHUNK);
1383 conf_watermark = BUFFERING_DEFAULT_FILECHUNK;
1385 break;
1387 #ifndef SIMULATOR
1388 case SYS_USB_CONNECTED:
1389 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1390 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1391 usb_wait_for_disconnect(&buffering_queue);
1392 break;
1393 #endif
1395 case SYS_TIMEOUT:
1396 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1397 break;
1400 update_data_counters();
1402 /* If the buffer is low, call the callbacks to get new data */
1403 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1404 send_event(EVENT_BUFFER_LOW, 0);
1406 #if 0
1407 /* TODO: This needs to be fixed to use the idle callback, disable it
1408 * for simplicity until its done right */
1409 #if MEM > 8
1410 /* If the disk is spinning, take advantage by filling the buffer */
1411 else if (ata_disk_is_active() && queue_empty(&buffering_queue))
1413 if (num_handles > 0 && data_counters.useful <= high_watermark)
1414 send_event(EVENT_BUFFER_LOW, 0);
1416 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1418 /* This is a new fill, shrink the buffer up first */
1419 if (!filling)
1420 shrink_buffer();
1421 filling = fill_buffer();
1422 update_data_counters();
1425 #endif
1426 #endif
1428 if (queue_empty(&buffering_queue)) {
1429 if (filling) {
1430 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1431 filling = fill_buffer();
1433 else if (ev.id == SYS_TIMEOUT)
1435 if (data_counters.remaining > 0 &&
1436 data_counters.useful <= conf_watermark) {
1437 shrink_buffer();
1438 filling = fill_buffer();
1445 void buffering_init(void)
1447 mutex_init(&llist_mutex);
1448 #ifdef HAVE_PRIORITY_SCHEDULING
1449 /* This behavior not safe atm */
1450 mutex_set_preempt(&llist_mutex, false);
1451 #endif
1453 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1455 queue_init(&buffering_queue, true);
1456 buffering_thread_p = create_thread( buffering_thread, buffering_stack,
1457 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1458 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1459 IF_COP(, CPU));
1461 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1462 buffering_thread_p);
1465 /* Initialise the buffering subsystem */
1466 bool buffering_reset(char *buf, size_t buflen)
1468 if (!buf || !buflen)
1469 return false;
1471 buffer = buf;
1472 buffer_len = buflen;
1473 guard_buffer = buf + buflen;
1475 buf_widx = 0;
1476 buf_ridx = 0;
1478 first_handle = NULL;
1479 cur_handle = NULL;
1480 cached_handle = NULL;
1481 num_handles = 0;
1482 base_handle_id = -1;
1484 /* Set the high watermark as 75% full...or 25% empty :) */
1485 #if MEM > 8
1486 high_watermark = 3*buflen / 4;
1487 #endif
1489 thread_thaw(buffering_thread_p);
1491 return true;
1494 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1496 update_data_counters();
1497 dbgdata->num_handles = num_handles;
1498 dbgdata->data_rem = data_counters.remaining;
1499 dbgdata->wasted_space = data_counters.wasted;
1500 dbgdata->buffered_data = data_counters.buffered;
1501 dbgdata->useful_data = data_counters.useful;