Calculate watermark from bitrate and harddisk spinup time.
[kugel-rb.git] / apps / buffering.c
blobd715456efbd3367430b6028cdbb21f491d292978
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2007 Nicolas Pennequin
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 #include "config.h"
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include "buffering.h"
29 #include "storage.h"
30 #include "system.h"
31 #include "thread.h"
32 #include "file.h"
33 #include "panic.h"
34 #include "memory.h"
35 #include "lcd.h"
36 #include "font.h"
37 #include "button.h"
38 #include "kernel.h"
39 #include "tree.h"
40 #include "debug.h"
41 #include "sprintf.h"
42 #include "settings.h"
43 #include "codecs.h"
44 #include "audio.h"
45 #include "mp3_playback.h"
46 #include "usb.h"
47 #include "status.h"
48 #include "screens.h"
49 #include "playlist.h"
50 #include "pcmbuf.h"
51 #include "buffer.h"
52 #include "bmp.h"
53 #include "appevents.h"
54 #include "metadata.h"
55 #ifdef HAVE_ALBUMART
56 #include "albumart.h"
57 #endif
59 #define GUARD_BUFSIZE (32*1024)
61 /* Define LOGF_ENABLE to enable logf output in this file */
62 /*#define LOGF_ENABLE*/
63 #include "logf.h"
65 /* macros to enable logf for queues
66 logging on SYS_TIMEOUT can be disabled */
67 #ifdef SIMULATOR
68 /* Define this for logf output of all queuing except SYS_TIMEOUT */
69 #define BUFFERING_LOGQUEUES
70 /* Define this to logf SYS_TIMEOUT messages */
71 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
72 #endif
74 #ifdef BUFFERING_LOGQUEUES
75 #define LOGFQUEUE logf
76 #else
77 #define LOGFQUEUE(...)
78 #endif
80 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
81 #define LOGFQUEUE_SYS_TIMEOUT logf
82 #else
83 #define LOGFQUEUE_SYS_TIMEOUT(...)
84 #endif
86 /* default point to start buffer refill */
87 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
88 /* amount of data to read in one read() call */
89 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
91 #define BUF_HANDLE_MASK 0x7FFFFFFF
94 /* Ring buffer helper macros */
95 /* Buffer pointer (p) plus value (v), wrapped if necessary */
96 #define RINGBUF_ADD(p,v) (((p)+(v))<buffer_len ? (p)+(v) : (p)+(v)-buffer_len)
97 /* Buffer pointer (p) minus value (v), wrapped if necessary */
98 #define RINGBUF_SUB(p,v) ((p>=v) ? (p)-(v) : (p)+buffer_len-(v))
99 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
100 #define RINGBUF_ADD_CROSS(p1,v,p2) \
101 ((p1<p2) ? (int)((p1)+(v))-(int)(p2) : (int)((p1)+(v)-(p2))-(int)buffer_len)
102 /* Bytes available in the buffer */
103 #define BUF_USED RINGBUF_SUB(buf_widx, buf_ridx)
105 /* assert(sizeof(struct memory_handle)%4==0) */
106 struct memory_handle {
107 int id; /* A unique ID for the handle */
108 enum data_type type; /* Type of data buffered with this handle */
109 char path[MAX_PATH]; /* Path if data originated in a file */
110 int fd; /* File descriptor to path (-1 if closed) */
111 size_t data; /* Start index of the handle's data buffer */
112 volatile size_t ridx; /* Read pointer, relative to the main buffer */
113 size_t widx; /* Write pointer */
114 size_t filesize; /* File total length */
115 size_t filerem; /* Remaining bytes of file NOT in buffer */
116 volatile size_t available; /* Available bytes to read from buffer */
117 size_t offset; /* Offset at which we started reading the file */
118 struct memory_handle *next;
120 /* invariant: filesize == offset + available + filerem */
122 static char *buffer;
123 static char *guard_buffer;
125 static size_t buffer_len;
127 static volatile size_t buf_widx; /* current writing position */
128 static volatile size_t buf_ridx; /* current reading position */
129 /* buf_*idx are values relative to the buffer, not real pointers. */
131 /* Configuration */
132 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
133 #if MEM > 8
134 static size_t high_watermark = 0; /* High watermark for rebuffer */
135 #endif
137 /* current memory handle in the linked list. NULL when the list is empty. */
138 static struct memory_handle *cur_handle;
139 /* first memory handle in the linked list. NULL when the list is empty. */
140 static struct memory_handle *first_handle;
142 static int num_handles; /* number of handles in the list */
144 static int base_handle_id;
146 static struct mutex llist_mutex;
148 /* Handle cache (makes find_handle faster).
149 This is global so that move_handle and rm_handle can invalidate it. */
150 static struct memory_handle *cached_handle = NULL;
152 static struct {
153 size_t remaining; /* Amount of data needing to be buffered */
154 size_t wasted; /* Amount of space available for freeing */
155 size_t buffered; /* Amount of data currently in the buffer */
156 size_t useful; /* Amount of data still useful to the user */
157 } data_counters;
160 /* Messages available to communicate with the buffering thread */
161 enum {
162 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
163 used in a low buffer situation. */
164 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
165 offset (the offset has to be set beforehand) */
166 Q_CLOSE_HANDLE, /* Request closing a handle */
167 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
169 /* Configuration: */
170 Q_START_FILL, /* Request that the buffering thread initiate a buffer
171 fill at its earliest convenience */
172 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
173 (which means the disk is spinning) */
176 /* Buffering thread */
177 static void buffering_thread(void);
178 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
179 static const char buffering_thread_name[] = "buffering";
180 static unsigned int buffering_thread_id = 0;
181 static struct event_queue buffering_queue;
182 static struct queue_sender_list buffering_queue_sender_list;
187 LINKED LIST MANAGEMENT
188 ======================
190 add_handle : Add a handle to the list
191 rm_handle : Remove a handle from the list
192 find_handle : Get a handle pointer from an ID
193 move_handle : Move a handle in the buffer (with or without its data)
195 These functions only handle the linked list structure. They don't touch the
196 contents of the struct memory_handle headers. They also change the buf_*idx
197 pointers when necessary and manage the handle IDs.
199 The first and current (== last) handle are kept track of.
200 A new handle is added at buf_widx and becomes the current one.
201 buf_widx always points to the current writing position for the current handle
202 buf_ridx always points to the location of the first handle.
203 buf_ridx == buf_widx means the buffer is empty.
207 /* Add a new handle to the linked list and return it. It will have become the
208 new current handle.
209 data_size must contain the size of what will be in the handle.
210 can_wrap tells us whether this type of data may wrap on buffer
211 alloc_all tells us if we must immediately be able to allocate data_size
212 returns a valid memory handle if all conditions for allocation are met.
213 NULL if there memory_handle itself cannot be allocated or if the
214 data_size cannot be allocated and alloc_all is set. This function's
215 only potential side effect is to allocate space for the cur_handle
216 if it returns NULL.
218 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
219 bool alloc_all)
221 /* gives each handle a unique id */
222 static int cur_handle_id = 0;
223 size_t shift;
224 size_t new_widx;
225 size_t len;
226 int overlap;
228 if (num_handles >= BUF_MAX_HANDLES)
229 return NULL;
231 mutex_lock(&llist_mutex);
233 if (cur_handle && cur_handle->filerem > 0) {
234 /* the current handle hasn't finished buffering. We can only add
235 a new one if there is already enough free space to finish
236 the buffering. */
237 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
238 if (RINGBUF_ADD_CROSS(cur_handle->widx, req, buf_ridx) >= 0) {
239 /* Not enough space */
240 mutex_unlock(&llist_mutex);
241 return NULL;
242 } else {
243 /* Allocate the remainder of the space for the current handle */
244 buf_widx = RINGBUF_ADD(cur_handle->widx, cur_handle->filerem);
248 /* align to 4 bytes up */
249 new_widx = RINGBUF_ADD(buf_widx, 3) & ~3;
251 len = data_size + sizeof(struct memory_handle);
253 /* First, will the handle wrap? */
254 overlap = RINGBUF_ADD_CROSS(new_widx, sizeof(struct memory_handle),
255 buffer_len - 1);
256 /* If the handle would wrap, move to the beginning of the buffer,
257 * otherwise check if the data can/would wrap and move it to the
258 * beginning if needed */
259 if (overlap > 0) {
260 new_widx = 0;
261 } else if (!can_wrap) {
262 overlap = RINGBUF_ADD_CROSS(new_widx, len, buffer_len - 1);
263 if (overlap > 0)
264 new_widx += data_size - overlap;
267 /* How far we shifted buf_widx to align things, must be < buffer_len */
268 shift = RINGBUF_SUB(new_widx, buf_widx);
270 /* How much space are we short in the actual ring buffer? */
271 overlap = RINGBUF_ADD_CROSS(buf_widx, shift + len, buf_ridx);
272 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
273 /* Not enough space for required allocations */
274 mutex_unlock(&llist_mutex);
275 return NULL;
278 /* There is enough space for the required data, advance the buf_widx and
279 * initialize the struct */
280 buf_widx = new_widx;
282 struct memory_handle *new_handle =
283 (struct memory_handle *)(&buffer[buf_widx]);
285 /* only advance the buffer write index of the size of the struct */
286 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
288 new_handle->id = cur_handle_id;
289 /* Wrap signed int is safe and 0 doesn't happen */
290 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
291 new_handle->next = NULL;
292 num_handles++;
294 if (!first_handle)
295 /* the new handle is the first one */
296 first_handle = new_handle;
298 if (cur_handle)
299 cur_handle->next = new_handle;
301 cur_handle = new_handle;
303 mutex_unlock(&llist_mutex);
304 return new_handle;
307 /* Delete a given memory handle from the linked list
308 and return true for success. Nothing is actually erased from memory. */
309 static bool rm_handle(const struct memory_handle *h)
311 if (h == NULL)
312 return true;
314 mutex_lock(&llist_mutex);
316 if (h == first_handle) {
317 first_handle = h->next;
318 if (h == cur_handle) {
319 /* h was the first and last handle: the buffer is now empty */
320 cur_handle = NULL;
321 buf_ridx = buf_widx = 0;
322 } else {
323 /* update buf_ridx to point to the new first handle */
324 buf_ridx = (void *)first_handle - (void *)buffer;
326 } else {
327 struct memory_handle *m = first_handle;
328 /* Find the previous handle */
329 while (m && m->next != h) {
330 m = m->next;
332 if (m && m->next == h) {
333 m->next = h->next;
334 if (h == cur_handle) {
335 cur_handle = m;
336 buf_widx = cur_handle->widx;
338 } else {
339 mutex_unlock(&llist_mutex);
340 return false;
344 /* Invalidate the cache to prevent it from keeping the old location of h */
345 if (h == cached_handle)
346 cached_handle = NULL;
348 num_handles--;
350 mutex_unlock(&llist_mutex);
351 return true;
354 /* Return a pointer to the memory handle of given ID.
355 NULL if the handle wasn't found */
356 static struct memory_handle *find_handle(int handle_id)
358 if (handle_id < 0)
359 return NULL;
361 mutex_lock(&llist_mutex);
363 /* simple caching because most of the time the requested handle
364 will either be the same as the last, or the one after the last */
365 if (cached_handle)
367 if (cached_handle->id == handle_id) {
368 mutex_unlock(&llist_mutex);
369 return cached_handle;
370 } else if (cached_handle->next &&
371 (cached_handle->next->id == handle_id)) {
372 cached_handle = cached_handle->next;
373 mutex_unlock(&llist_mutex);
374 return cached_handle;
378 struct memory_handle *m = first_handle;
379 while (m && m->id != handle_id) {
380 m = m->next;
382 /* This condition can only be reached with !m or m->id == handle_id */
383 if (m)
384 cached_handle = m;
386 mutex_unlock(&llist_mutex);
387 return m;
390 /* Move a memory handle and data_size of its data delta bytes along the buffer.
391 delta maximum bytes available to move the handle. If the move is performed
392 it is set to the actual distance moved.
393 data_size is the amount of data to move along with the struct.
394 returns a valid memory_handle if the move is successful
395 NULL if the handle is NULL, the move would be less than the size of
396 a memory_handle after correcting for wraps or if the handle is not
397 found in the linked list for adjustment. This function has no side
398 effects if NULL is returned. */
399 static bool move_handle(struct memory_handle **h, size_t *delta,
400 size_t data_size, bool can_wrap)
402 struct memory_handle *dest;
403 const struct memory_handle *src;
404 size_t newpos;
405 size_t size_to_move;
406 size_t final_delta = *delta;
407 int overlap;
409 if (h == NULL || (src = *h) == NULL)
410 return false;
412 size_to_move = sizeof(struct memory_handle) + data_size;
414 /* Align to four bytes, down */
415 final_delta &= ~3;
416 if (final_delta < sizeof(struct memory_handle)) {
417 /* It's not legal to move less than the size of the struct */
418 return false;
421 mutex_lock(&llist_mutex);
423 newpos = RINGBUF_ADD((void *)src - (void *)buffer, final_delta);
424 overlap = RINGBUF_ADD_CROSS(newpos, size_to_move, buffer_len - 1);
426 if (overlap > 0) {
427 /* Some part of the struct + data would wrap, maybe ok */
428 size_t correction = 0;
429 /* If the overlap lands inside the memory_handle */
430 if ((unsigned)overlap > data_size) {
431 /* Correct the position and real delta to prevent the struct from
432 * wrapping, this guarantees an aligned delta, I think */
433 correction = overlap - data_size;
434 } else if (!can_wrap) {
435 /* Otherwise the overlap falls in the data area and must all be
436 * backed out. This may become conditional if ever we move
437 * data that is allowed to wrap (ie audio) */
438 correction = overlap;
439 /* Align correction to four bytes, up */
440 correction = (correction+3) & ~3;
442 if (correction) {
443 if (final_delta < correction + sizeof(struct memory_handle)) {
444 /* Delta cannot end up less than the size of the struct */
445 mutex_unlock(&llist_mutex);
446 return false;
449 newpos -= correction;
450 overlap -= correction;/* Used below to know how to split the data */
451 final_delta -= correction;
455 dest = (struct memory_handle *)(&buffer[newpos]);
457 if (src == first_handle) {
458 first_handle = dest;
459 buf_ridx = newpos;
460 } else {
461 struct memory_handle *m = first_handle;
462 while (m && m->next != src) {
463 m = m->next;
465 if (m && m->next == src) {
466 m->next = dest;
467 } else {
468 mutex_unlock(&llist_mutex);
469 return false;
474 /* Update the cache to prevent it from keeping the old location of h */
475 if (src == cached_handle)
476 cached_handle = dest;
478 /* the cur_handle pointer might need updating */
479 if (src == cur_handle)
480 cur_handle = dest;
482 if (overlap > 0) {
483 size_t first_part = size_to_move - overlap;
484 memmove(dest, src, first_part);
485 memmove(buffer, (const char *)src + first_part, overlap);
486 } else {
487 memmove(dest, src, size_to_move);
490 /* Update the caller with the new location of h and the distance moved */
491 *h = dest;
492 *delta = final_delta;
493 mutex_unlock(&llist_mutex);
494 return dest;
499 BUFFER SPACE MANAGEMENT
500 =======================
502 update_data_counters: Updates the values in data_counters
503 buffer_is_low : Returns true if the amount of useful data in the buffer is low
504 buffer_handle : Buffer data for a handle
505 reset_handle : Reset write position and data buffer of a handle to its offset
506 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
507 shrink_handle : Free buffer space by moving a handle
508 fill_buffer : Call buffer_handle for all handles that have data to buffer
510 These functions are used by the buffering thread to manage buffer space.
513 static void update_data_counters(void)
515 struct memory_handle *m = find_handle(base_handle_id);
516 bool is_useful = m==NULL;
518 size_t buffered = 0;
519 size_t wasted = 0;
520 size_t remaining = 0;
521 size_t useful = 0;
523 mutex_lock(&llist_mutex);
525 m = first_handle;
526 while (m) {
527 buffered += m->available;
528 wasted += RINGBUF_SUB(m->ridx, m->data);
529 remaining += m->filerem;
531 if (m->id == base_handle_id)
532 is_useful = true;
534 if (is_useful)
535 useful += RINGBUF_SUB(m->widx, m->ridx);
537 m = m->next;
540 mutex_unlock(&llist_mutex);
542 data_counters.buffered = buffered;
543 data_counters.wasted = wasted;
544 data_counters.remaining = remaining;
545 data_counters.useful = useful;
548 static inline bool buffer_is_low(void)
550 update_data_counters();
551 return data_counters.useful < (conf_watermark / 2);
554 /* Buffer data for the given handle.
555 Return whether or not the buffering should continue explicitly. */
556 static bool buffer_handle(int handle_id)
558 logf("buffer_handle(%d)", handle_id);
559 struct memory_handle *h = find_handle(handle_id);
560 if (!h)
561 return true;
563 if (h->filerem == 0) {
564 /* nothing left to buffer */
565 return true;
568 if (h->fd < 0) /* file closed, reopen */
570 if (*h->path)
571 h->fd = open(h->path, O_RDONLY);
573 if (h->fd < 0)
575 /* could not open the file, truncate it where it is */
576 h->filesize -= h->filerem;
577 h->filerem = 0;
578 return true;
581 if (h->offset)
582 lseek(h->fd, h->offset, SEEK_SET);
585 trigger_cpu_boost();
587 if (h->type == TYPE_ID3)
589 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
591 /* metadata parsing failed: clear the buffer. */
592 memset(buffer + h->data, 0, sizeof(struct mp3entry));
594 close(h->fd);
595 h->fd = -1;
596 h->filerem = 0;
597 h->available = sizeof(struct mp3entry);
598 h->widx += sizeof(struct mp3entry);
599 send_event(BUFFER_EVENT_FINISHED, &h->id);
600 return true;
603 while (h->filerem > 0)
605 /* max amount to copy */
606 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
607 buffer_len - h->widx);
609 /* stop copying if it would overwrite the reading position */
610 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
611 return false;
613 /* This would read into the next handle, this is broken */
614 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
615 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
616 /* Try to recover by truncating this file */
617 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
618 (unsigned)((void *)h->next - (void *)buffer));
619 h->filerem -= copy_n;
620 h->filesize -= copy_n;
621 logf("buf alloc short %ld", (long)copy_n);
622 if (h->filerem)
623 continue;
624 else
625 break;
628 /* rc is the actual amount read */
629 int rc = read(h->fd, &buffer[h->widx], copy_n);
631 if (rc < 0)
633 /* Some kind of filesystem error, maybe recoverable if not codec */
634 if (h->type == TYPE_CODEC) {
635 logf("Partial codec");
636 break;
639 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
640 h->filesize -= h->filerem;
641 h->filerem = 0;
642 break;
645 /* Advance buffer */
646 h->widx = RINGBUF_ADD(h->widx, rc);
647 if (h == cur_handle)
648 buf_widx = h->widx;
649 h->available += rc;
650 h->filerem -= rc;
652 /* If this is a large file, see if we need to break or give the codec
653 * more time */
654 if (h->type == TYPE_PACKET_AUDIO &&
655 pcmbuf_is_lowdata() && !buffer_is_low())
657 sleep(1);
659 else
661 yield();
664 if (!queue_empty(&buffering_queue))
665 break;
668 if (h->filerem == 0) {
669 /* finished buffering the file */
670 close(h->fd);
671 h->fd = -1;
672 send_event(BUFFER_EVENT_FINISHED, &h->id);
675 return true;
678 /* Reset writing position and data buffer of a handle to its current offset.
679 Use this after having set the new offset to use. */
680 static void reset_handle(int handle_id)
682 logf("reset_handle(%d)", handle_id);
684 struct memory_handle *h = find_handle(handle_id);
685 if (!h)
686 return;
688 h->ridx = h->widx = h->data;
689 if (h == cur_handle)
690 buf_widx = h->widx;
691 h->available = 0;
692 h->filerem = h->filesize - h->offset;
694 if (h->fd >= 0) {
695 lseek(h->fd, h->offset, SEEK_SET);
699 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
700 static void rebuffer_handle(int handle_id, size_t newpos)
702 struct memory_handle *h = find_handle(handle_id);
703 if (!h)
704 return;
706 /* When seeking foward off of the buffer, if it is a short seek don't
707 rebuffer the whole track, just read enough to satisfy */
708 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
710 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
711 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
712 h->ridx = h->data + newpos;
713 return;
716 h->offset = newpos;
718 /* Reset the handle to its new offset */
719 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
720 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
722 size_t next = (unsigned)((void *)h->next - (void *)buffer);
723 if (RINGBUF_SUB(next, h->data) < h->filesize - newpos)
725 /* There isn't enough space to rebuffer all of the track from its new
726 offset, so we ask the user to free some */
727 DEBUGF("rebuffer_handle: space is needed\n");
728 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
731 /* Now we ask for a rebuffer */
732 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
733 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
736 static bool close_handle(int handle_id)
738 struct memory_handle *h = find_handle(handle_id);
740 /* If the handle is not found, it is closed */
741 if (!h)
742 return true;
744 if (h->fd >= 0) {
745 close(h->fd);
746 h->fd = -1;
749 /* rm_handle returns true unless the handle somehow persists after exit */
750 return rm_handle(h);
753 /* Free buffer space by moving the handle struct right before the useful
754 part of its data buffer or by moving all the data. */
755 static void shrink_handle(struct memory_handle *h)
757 size_t delta;
759 if (!h)
760 return;
762 if (h->next && h->filerem == 0 &&
763 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
764 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
765 h->type == TYPE_ATOMIC_AUDIO))
767 /* metadata handle: we can move all of it */
768 size_t handle_distance =
769 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
770 delta = handle_distance - h->available;
772 /* The value of delta might change for alignment reasons */
773 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
774 return;
776 size_t olddata = h->data;
777 h->data = RINGBUF_ADD(h->data, delta);
778 h->ridx = RINGBUF_ADD(h->ridx, delta);
779 h->widx = RINGBUF_ADD(h->widx, delta);
781 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
782 /* when moving an mp3entry we need to readjust its pointers. */
783 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
784 (void *)&buffer[h->data],
785 (const void *)&buffer[olddata]);
786 } else if (h->type == TYPE_BITMAP) {
787 /* adjust the bitmap's pointer */
788 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
789 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
792 else
794 /* only move the handle struct */
795 delta = RINGBUF_SUB(h->ridx, h->data);
796 if (!move_handle(&h, &delta, 0, true))
797 return;
799 h->data = RINGBUF_ADD(h->data, delta);
800 h->available -= delta;
801 h->offset += delta;
805 /* Fill the buffer by buffering as much data as possible for handles that still
806 have data left to buffer
807 Return whether or not to continue filling after this */
808 static bool fill_buffer(void)
810 logf("fill_buffer()");
811 struct memory_handle *m;
812 shrink_handle(first_handle);
813 m = first_handle;
814 while (queue_empty(&buffering_queue) && m) {
815 if (m->filerem > 0) {
816 if (!buffer_handle(m->id)) {
817 m = NULL;
818 break;
821 m = m->next;
824 if (m) {
825 return true;
827 else
829 /* only spin the disk down if the filling wasn't interrupted by an
830 event arriving in the queue. */
831 storage_sleep();
832 return false;
836 #ifdef HAVE_ALBUMART
837 /* Given a file descriptor to a bitmap file, write the bitmap data to the
838 buffer, with a struct bitmap and the actual data immediately following.
839 Return value is the total size (struct + data). */
840 static int load_bitmap(int fd)
842 int rc;
843 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
844 /* FIXME: alignment may be needed for the data buffer. */
845 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
847 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
848 bmp->maskdata = NULL;
849 #endif
851 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
852 - sizeof(struct bitmap);
854 get_albumart_size(bmp);
856 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
857 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
858 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
860 #endif
864 MAIN BUFFERING API CALLS
865 ========================
867 bufopen : Request the opening of a new handle for a file
868 bufalloc : Open a new handle for data other than a file.
869 bufclose : Close an open handle
870 bufseek : Set the read pointer in a handle
871 bufadvance : Move the read pointer in a handle
872 bufread : Copy data from a handle into a given buffer
873 bufgetdata : Give a pointer to the handle's data
875 These functions are exported, to allow interaction with the buffer.
876 They take care of the content of the structs, and rely on the linked list
877 management functions for all the actual handle management work.
881 /* Reserve space in the buffer for a file.
882 filename: name of the file to open
883 offset: offset at which to start buffering the file, useful when the first
884 (offset-1) bytes of the file aren't needed.
885 return value: <0 if the file cannot be opened, or one file already
886 queued to be opened, otherwise the handle for the file in the buffer
888 int bufopen(const char *file, size_t offset, enum data_type type)
890 if (type == TYPE_ID3)
892 /* ID3 case: allocate space, init the handle and return. */
894 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
895 if (!h)
896 return ERR_BUFFER_FULL;
898 h->fd = -1;
899 h->filesize = sizeof(struct mp3entry);
900 h->filerem = sizeof(struct mp3entry);
901 h->offset = 0;
902 h->data = buf_widx;
903 h->ridx = buf_widx;
904 h->widx = buf_widx;
905 h->available = 0;
906 h->type = type;
907 strncpy(h->path, file, MAX_PATH);
909 buf_widx += sizeof(struct mp3entry); /* safe because the handle
910 can't wrap */
912 /* Inform the buffering thread that we added a handle */
913 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
914 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
916 return h->id;
919 /* Other cases: there is a little more work. */
921 int fd = open(file, O_RDONLY);
922 if (fd < 0)
923 return ERR_FILE_ERROR;
925 size_t size = filesize(fd);
926 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
928 size_t adjusted_offset = offset;
929 if (adjusted_offset > size)
930 adjusted_offset = 0;
932 struct memory_handle *h = add_handle(size-adjusted_offset, can_wrap, false);
933 if (!h)
935 DEBUGF("bufopen: failed to add handle\n");
936 close(fd);
937 return ERR_BUFFER_FULL;
940 strncpy(h->path, file, MAX_PATH);
941 h->offset = adjusted_offset;
942 h->ridx = buf_widx;
943 h->data = buf_widx;
944 h->type = type;
946 #ifdef HAVE_ALBUMART
947 if (type == TYPE_BITMAP)
949 /* Bitmap file: we load the data instead of the file */
950 int rc;
951 mutex_lock(&llist_mutex); /* Lock because load_bitmap yields */
952 rc = load_bitmap(fd);
953 mutex_unlock(&llist_mutex);
954 if (rc <= 0)
956 rm_handle(h);
957 close(fd);
958 return ERR_FILE_ERROR;
960 h->filerem = 0;
961 h->filesize = rc;
962 h->available = rc;
963 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
964 buf_widx += rc; /* safe too */
966 else
967 #endif
969 h->filerem = size - adjusted_offset;
970 h->filesize = size;
971 h->available = 0;
972 h->widx = buf_widx;
975 if (type == TYPE_CUESHEET) {
976 h->fd = fd;
977 /* Immediately start buffering those */
978 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
979 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
980 } else {
981 /* Other types will get buffered in the course of normal operations */
982 h->fd = -1;
983 close(fd);
985 /* Inform the buffering thread that we added a handle */
986 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
987 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
990 logf("bufopen: new hdl %d", h->id);
991 return h->id;
994 /* Open a new handle from data that needs to be copied from memory.
995 src is the source buffer from which to copy data. It can be NULL to simply
996 reserve buffer space.
997 size is the requested size. The call will only be successful if the
998 requested amount of data can entirely fit in the buffer without wrapping.
999 Return value is the handle id for success or <0 for failure.
1001 int bufalloc(const void *src, size_t size, enum data_type type)
1003 struct memory_handle *h = add_handle(size, false, true);
1005 if (!h)
1006 return ERR_BUFFER_FULL;
1008 if (src) {
1009 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1010 /* specially take care of struct mp3entry */
1011 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1012 (const struct mp3entry *)src);
1013 } else {
1014 memcpy(&buffer[buf_widx], src, size);
1018 h->fd = -1;
1019 *h->path = 0;
1020 h->filesize = size;
1021 h->filerem = 0;
1022 h->offset = 0;
1023 h->ridx = buf_widx;
1024 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1025 h->data = buf_widx;
1026 h->available = size;
1027 h->type = type;
1029 buf_widx += size; /* safe too */
1031 logf("bufalloc: new hdl %d", h->id);
1032 return h->id;
1035 /* Close the handle. Return true for success and false for failure */
1036 bool bufclose(int handle_id)
1038 logf("bufclose(%d)", handle_id);
1040 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1041 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1044 /* Set reading index in handle (relatively to the start of the file).
1045 Access before the available data will trigger a rebuffer.
1046 Return 0 for success and < 0 for failure:
1047 -1 if the handle wasn't found
1048 -2 if the new requested position was beyond the end of the file
1050 int bufseek(int handle_id, size_t newpos)
1052 struct memory_handle *h = find_handle(handle_id);
1053 if (!h)
1054 return ERR_HANDLE_NOT_FOUND;
1056 if (newpos > h->filesize) {
1057 /* access beyond the end of the file */
1058 return ERR_INVALID_VALUE;
1060 else if (newpos < h->offset || h->offset + h->available < newpos) {
1061 /* access before or after buffered data. A rebuffer is needed. */
1062 rebuffer_handle(handle_id, newpos);
1064 else {
1065 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1067 return 0;
1070 /* Advance the reading index in a handle (relatively to its current position).
1071 Return 0 for success and < 0 for failure */
1072 int bufadvance(int handle_id, off_t offset)
1074 const struct memory_handle *h = find_handle(handle_id);
1075 if (!h)
1076 return ERR_HANDLE_NOT_FOUND;
1078 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1079 return bufseek(handle_id, newpos);
1082 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1083 * actual amount of data available for reading. This function explicitly
1084 * does not check the validity of the input handle. It does do range checks
1085 * on size and returns a valid (and explicit) amount of data for reading */
1086 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1087 bool guardbuf_limit)
1089 struct memory_handle *h = find_handle(handle_id);
1090 if (!h)
1091 return NULL;
1093 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1095 if (avail == 0 && h->filerem == 0)
1097 /* File is finished reading */
1098 *size = 0;
1099 return h;
1102 if (*size == 0 || *size > avail + h->filerem)
1103 *size = avail + h->filerem;
1105 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1107 logf("data request > guardbuf");
1108 /* If more than the size of the guardbuf is requested and this is a
1109 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1110 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1111 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1114 if (h->filerem > 0 && avail < *size)
1116 /* Data isn't ready. Request buffering */
1117 buf_request_buffer_handle(handle_id);
1118 /* Wait for the data to be ready */
1121 sleep(1);
1122 /* it is not safe for a non-buffering thread to sleep while
1123 * holding a handle */
1124 h = find_handle(handle_id);
1125 if (!h)
1126 return NULL;
1127 avail = RINGBUF_SUB(h->widx, h->ridx);
1129 while (h->filerem > 0 && avail < *size);
1132 *size = MIN(*size,avail);
1133 return h;
1136 /* Copy data from the given handle to the dest buffer.
1137 Return the number of bytes copied or < 0 for failure (handle not found).
1138 The caller is blocked until the requested amount of data is available.
1140 ssize_t bufread(int handle_id, size_t size, void *dest)
1142 const struct memory_handle *h;
1143 size_t adjusted_size = size;
1145 h = prep_bufdata(handle_id, &adjusted_size, false);
1146 if (!h)
1147 return ERR_HANDLE_NOT_FOUND;
1149 if (h->ridx + adjusted_size > buffer_len)
1151 /* the data wraps around the end of the buffer */
1152 size_t read = buffer_len - h->ridx;
1153 memcpy(dest, &buffer[h->ridx], read);
1154 memcpy(dest+read, buffer, adjusted_size - read);
1156 else
1158 memcpy(dest, &buffer[h->ridx], adjusted_size);
1161 return adjusted_size;
1164 /* Update the "data" pointer to make the handle's data available to the caller.
1165 Return the length of the available linear data or < 0 for failure (handle
1166 not found).
1167 The caller is blocked until the requested amount of data is available.
1168 size is the amount of linear data requested. it can be 0 to get as
1169 much as possible.
1170 The guard buffer may be used to provide the requested size. This means it's
1171 unsafe to request more than the size of the guard buffer.
1173 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1175 const struct memory_handle *h;
1176 size_t adjusted_size = size;
1178 h = prep_bufdata(handle_id, &adjusted_size, true);
1179 if (!h)
1180 return ERR_HANDLE_NOT_FOUND;
1182 if (h->ridx + adjusted_size > buffer_len)
1184 /* the data wraps around the end of the buffer :
1185 use the guard buffer to provide the requested amount of data. */
1186 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1187 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1188 so copy_n <= GUARD_BUFSIZE */
1189 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1192 if (data)
1193 *data = &buffer[h->ridx];
1195 return adjusted_size;
1198 ssize_t bufgettail(int handle_id, size_t size, void **data)
1200 size_t tidx;
1202 const struct memory_handle *h;
1204 h = find_handle(handle_id);
1206 if (!h)
1207 return ERR_HANDLE_NOT_FOUND;
1209 if (h->filerem)
1210 return ERR_HANDLE_NOT_DONE;
1212 /* We don't support tail requests of > guardbuf_size, for simplicity */
1213 if (size > GUARD_BUFSIZE)
1214 return ERR_INVALID_VALUE;
1216 tidx = RINGBUF_SUB(h->widx, size);
1218 if (tidx + size > buffer_len)
1220 size_t copy_n = tidx + size - buffer_len;
1221 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1224 *data = &buffer[tidx];
1225 return size;
1228 ssize_t bufcuttail(int handle_id, size_t size)
1230 struct memory_handle *h;
1231 size_t adjusted_size = size;
1233 h = find_handle(handle_id);
1235 if (!h)
1236 return ERR_HANDLE_NOT_FOUND;
1238 if (h->filerem)
1239 return ERR_HANDLE_NOT_DONE;
1241 if (h->available < adjusted_size)
1242 adjusted_size = h->available;
1244 h->available -= adjusted_size;
1245 h->filesize -= adjusted_size;
1246 h->widx = RINGBUF_SUB(h->widx, adjusted_size);
1247 if (h == cur_handle)
1248 buf_widx = h->widx;
1250 return adjusted_size;
1255 SECONDARY EXPORTED FUNCTIONS
1256 ============================
1258 buf_get_offset
1259 buf_handle_offset
1260 buf_request_buffer_handle
1261 buf_set_base_handle
1262 buf_used
1263 register_buffering_callback
1264 unregister_buffering_callback
1266 These functions are exported, to allow interaction with the buffer.
1267 They take care of the content of the structs, and rely on the linked list
1268 management functions for all the actual handle management work.
1271 /* Get a handle offset from a pointer */
1272 ssize_t buf_get_offset(int handle_id, void *ptr)
1274 const struct memory_handle *h = find_handle(handle_id);
1275 if (!h)
1276 return ERR_HANDLE_NOT_FOUND;
1278 return (size_t)ptr - (size_t)&buffer[h->ridx];
1281 ssize_t buf_handle_offset(int handle_id)
1283 const struct memory_handle *h = find_handle(handle_id);
1284 if (!h)
1285 return ERR_HANDLE_NOT_FOUND;
1286 return h->offset;
1289 void buf_request_buffer_handle(int handle_id)
1291 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1292 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1295 void buf_set_base_handle(int handle_id)
1297 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1298 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1301 /* Return the amount of buffer space used */
1302 size_t buf_used(void)
1304 return BUF_USED;
1307 void buf_set_watermark(size_t bytes)
1309 conf_watermark = bytes;
1312 static void shrink_buffer_inner(struct memory_handle *h)
1314 if (h == NULL)
1315 return;
1317 shrink_buffer_inner(h->next);
1319 shrink_handle(h);
1322 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 if (!filling) {
1336 cancel_cpu_boost();
1339 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1341 switch (ev.id)
1343 case Q_START_FILL:
1344 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1345 /* Call buffer callbacks here because this is one of two ways
1346 * to begin a full buffer fill */
1347 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1348 shrink_buffer();
1349 queue_reply(&buffering_queue, 1);
1350 filling |= buffer_handle((int)ev.data);
1351 break;
1353 case Q_BUFFER_HANDLE:
1354 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1355 queue_reply(&buffering_queue, 1);
1356 buffer_handle((int)ev.data);
1357 break;
1359 case Q_RESET_HANDLE:
1360 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1361 queue_reply(&buffering_queue, 1);
1362 reset_handle((int)ev.data);
1363 break;
1365 case Q_CLOSE_HANDLE:
1366 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1367 queue_reply(&buffering_queue, close_handle((int)ev.data));
1368 break;
1370 case Q_HANDLE_ADDED:
1371 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1372 /* A handle was added: the disk is spinning, so we can fill */
1373 filling = true;
1374 break;
1376 case Q_BASE_HANDLE:
1377 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1378 base_handle_id = (int)ev.data;
1379 break;
1381 #ifndef SIMULATOR
1382 case SYS_USB_CONNECTED:
1383 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1384 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1385 usb_wait_for_disconnect(&buffering_queue);
1386 break;
1387 #endif
1389 case SYS_TIMEOUT:
1390 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1391 break;
1394 update_data_counters();
1396 /* If the buffer is low, call the callbacks to get new data */
1397 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1398 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1400 #if 0
1401 /* TODO: This needs to be fixed to use the idle callback, disable it
1402 * for simplicity until its done right */
1403 #if MEM > 8
1404 /* If the disk is spinning, take advantage by filling the buffer */
1405 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1407 if (num_handles > 0 && data_counters.useful <= high_watermark)
1408 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1410 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1412 /* This is a new fill, shrink the buffer up first */
1413 if (!filling)
1414 shrink_buffer();
1415 filling = fill_buffer();
1416 update_data_counters();
1419 #endif
1420 #endif
1422 if (queue_empty(&buffering_queue)) {
1423 if (filling) {
1424 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1425 filling = fill_buffer();
1426 else if (data_counters.remaining == 0)
1427 filling = false;
1429 else if (ev.id == SYS_TIMEOUT)
1431 if (data_counters.remaining > 0 &&
1432 data_counters.useful <= conf_watermark) {
1433 shrink_buffer();
1434 filling = fill_buffer();
1441 void buffering_init(void)
1443 mutex_init(&llist_mutex);
1444 #ifdef HAVE_PRIORITY_SCHEDULING
1445 /* This behavior not safe atm */
1446 mutex_set_preempt(&llist_mutex, false);
1447 #endif
1449 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1451 queue_init(&buffering_queue, true);
1452 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1453 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1454 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1455 IF_COP(, CPU));
1457 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1458 buffering_thread_id);
1461 /* Initialise the buffering subsystem */
1462 bool buffering_reset(char *buf, size_t buflen)
1464 if (!buf || !buflen)
1465 return false;
1467 buffer = buf;
1468 buffer_len = buflen;
1469 guard_buffer = buf + buflen;
1471 buf_widx = 0;
1472 buf_ridx = 0;
1474 first_handle = NULL;
1475 cur_handle = NULL;
1476 cached_handle = NULL;
1477 num_handles = 0;
1478 base_handle_id = -1;
1480 /* Set the high watermark as 75% full...or 25% empty :) */
1481 #if MEM > 8
1482 high_watermark = 3*buflen / 4;
1483 #endif
1485 thread_thaw(buffering_thread_id);
1487 return true;
1490 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1492 update_data_counters();
1493 dbgdata->num_handles = num_handles;
1494 dbgdata->data_rem = data_counters.remaining;
1495 dbgdata->wasted_space = data_counters.wasted;
1496 dbgdata->buffered_data = data_counters.buffered;
1497 dbgdata->useful_data = data_counters.useful;