bufopen: Immediately request buffering for certain filetypes.
[Rockbox.git] / apps / buffering.c
blob859a21fd269c62afee53ec084b29e027432ef4a2
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 "logf.h"
44 #include "mp3_playback.h"
45 #include "usb.h"
46 #include "status.h"
47 #include "screens.h"
48 #include "playlist.h"
49 #include "playback.h"
50 #include "pcmbuf.h"
51 #include "buffer.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 LOGFQUEUE logf
65 /* amount of data to read in one read() call */
66 #define AUDIO_DEFAULT_FILECHUNK (1024*32)
68 /* Ring buffer helper macros */
69 /* Buffer pointer (p) plus value (v), wrapped if necessary */
70 #define RINGBUF_ADD(p,v) ((p+v)<buffer_len ? p+v : p+v-buffer_len)
71 /* Buffer pointer (p) minus value (v), wrapped if necessary */
72 #define RINGBUF_SUB(p,v) ((p>=v) ? p-v : p+buffer_len-v)
73 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
74 #define RINGBUF_ADD_CROSS(p1,v,p2) \
75 ((p1<p2) ? (int)(p1+v)-(int)p2 : (int)(p1+v-p2)-(int)buffer_len)
76 /* Bytes available in the buffer */
77 #define BUF_USED RINGBUF_SUB(buf_widx, buf_ridx)
79 struct memory_handle {
80 int id; /* A unique ID for the handle */
81 enum data_type type;
82 char path[MAX_PATH];
83 int fd;
84 size_t data; /* Start index of the handle's data buffer */
85 size_t ridx; /* Current read pointer, relative to the main buffer */
86 size_t widx; /* Current write pointer */
87 size_t filesize; /* File total length */
88 size_t filerem; /* Remaining bytes of file NOT in buffer */
89 size_t available; /* Available bytes to read from buffer */
90 size_t offset; /* Offset at which we started reading the file */
91 struct memory_handle *next;
93 /* at all times, we have: filesize == offset + available + filerem */
96 static char *buffer;
97 static char *guard_buffer;
99 static size_t buffer_len;
101 static size_t buf_widx; /* current writing position */
102 static size_t buf_ridx; /* current reading position */
103 /* buf_*idx are values relative to the buffer, not real pointers. */
105 static size_t conf_filechunk;
107 /* current memory handle in the linked list. NULL when the list is empty. */
108 static struct memory_handle *cur_handle;
109 /* first memory handle in the linked list. NULL when the list is empty. */
110 static struct memory_handle *first_handle;
112 static int num_handles; /* number of handles in the list */
114 /* Handle cache (makes find_handle faster).
115 These need to be global so that move_handle can invalidate them. */
116 static int cached_handle_id = -1;
117 static struct memory_handle *cached_handle = NULL;
121 LINKED LIST MANAGEMENT
122 ======================
124 add_handle : Add a handle to the list
125 rm_handle : Remove a handle from the list
126 find_handle : Get a handle pointer from an ID
127 move_handle : Move a handle in the buffer (with or without its data)
129 These functions only handle the linked list structure. They don't touch the
130 contents of the struct memory_handle headers. They also change the buf_*idx
131 pointers when necessary and manage the handle IDs.
133 The first and current (== last) handle are kept track of.
134 A new handle is added at buf_widx and becomes the current one.
135 buf_widx always points to the current writing position for the current handle
136 buf_ridx always points to the location of the first handle.
137 buf_ridx == buf_widx means the buffer is empty.
141 /* Add a new handle to the linked list and return it. It will have become the
142 new current handle. The handle will reserve "data_size" bytes or if that's
143 not possible, decrease "data_size" to allow adding the handle. */
144 static struct memory_handle *add_handle(size_t *data_size)
146 /* this will give each handle a unique id */
147 static int cur_handle_id = 1;
149 /* make sure buf_widx is 32-bit aligned so that the handle struct is,
150 but before that we check we can actually align. */
151 if (RINGBUF_ADD_CROSS(buf_widx, 3, buf_ridx) >= 0) {
152 return NULL;
154 buf_widx = (RINGBUF_ADD(buf_widx, 3)) & ~3;
156 size_t len = (data_size ? *data_size : 0)
157 + sizeof(struct memory_handle);
159 /* check that we actually can add the handle and its data */
160 int overlap = RINGBUF_ADD_CROSS(buf_widx, len, buf_ridx);
161 if (overlap >= 0) {
162 *data_size -= overlap;
163 len -= overlap;
165 if (len < sizeof(struct memory_handle)) {
166 /* There isn't even enough space to write the struct */
167 return NULL;
170 struct memory_handle *new_handle =
171 (struct memory_handle *)(&buffer[buf_widx]);
173 /* only advance the buffer write index of the size of the struct */
174 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
176 if (!first_handle) {
177 /* the new handle is the first one */
178 first_handle = new_handle;
181 if (cur_handle) {
182 cur_handle->next = new_handle;
185 cur_handle = new_handle;
186 cur_handle->id = cur_handle_id++;
187 cur_handle->next = NULL;
188 num_handles++;
189 return cur_handle;
192 /* Delete a given memory handle from the linked list
193 and return true for success. Nothing is actually erased from memory. */
194 static bool rm_handle(struct memory_handle *h)
196 if (h == first_handle) {
197 first_handle = h->next;
198 if (h == cur_handle) {
199 /* h was the first and last handle: the buffer is now empty */
200 cur_handle = NULL;
201 buf_ridx = buf_widx;
202 } else {
203 /* update buf_ridx to point to the new first handle */
204 buf_ridx = (void *)first_handle - (void *)buffer;
206 } else {
207 struct memory_handle *m = first_handle;
208 while (m && m->next != h) {
209 m = m->next;
211 if (h && m && m->next == h) {
212 m->next = h->next;
213 if (h == cur_handle) {
214 cur_handle = m;
216 } else {
217 return false;
221 num_handles--;
222 return true;
225 /* Return a pointer to the memory handle of given ID.
226 NULL if the handle wasn't found */
227 static struct memory_handle *find_handle(int handle_id)
229 /* simple caching because most of the time the requested handle
230 will either be the same as the last, or the one after the last */
231 if (cached_handle)
233 if (cached_handle_id == handle_id &&
234 cached_handle_id == cached_handle->id)
235 return cached_handle;
236 else if (cached_handle->next && (cached_handle->next->id == handle_id))
238 /* JD's quick testing showd this block was only entered
239 2/1971 calls to find_handle.
240 8/1971 calls to find_handle resulted in a cache miss */
241 cached_handle = cached_handle->next;
242 cached_handle_id = handle_id;
243 return cached_handle;
247 struct memory_handle *m = first_handle;
248 while (m && m->id != handle_id) {
249 m = m->next;
251 cached_handle_id = handle_id;
252 cached_handle = m;
253 return (m && m->id == handle_id) ? m : NULL;
256 /* Move a memory handle and data_size of its data of delta.
257 Return a pointer to the new location of the handle.
258 delta is the value of which to move the struct data.
259 data_size is the amount of data to move along with the struct. */
260 static struct memory_handle *move_handle(struct memory_handle *h,
261 size_t *delta, size_t data_size)
263 if (*delta < 4) {
264 /* aligning backwards would yield a negative result,
265 and moving the handle of such a small amount is a waste
266 of time anyway. */
267 return NULL;
269 /* make sure delta is 32-bit aligned so that the handle struct is. */
270 *delta = (*delta - 3) & ~3;
272 size_t newpos = RINGBUF_ADD((void *)h - (void *)buffer, *delta);
274 struct memory_handle *dest = (struct memory_handle *)(&buffer[newpos]);
276 /* Invalidate the cache to prevent it from keeping the old location of h */
277 if (h == cached_handle)
278 cached_handle = NULL;
280 /* the cur_handle pointer might need updating */
281 if (h == cur_handle) {
282 cur_handle = dest;
285 if (h == first_handle) {
286 first_handle = dest;
287 buf_ridx = newpos;
288 } else {
289 struct memory_handle *m = first_handle;
290 while (m && m->next != h) {
291 m = m->next;
293 if (h && m && m->next == h) {
294 m->next = dest;
295 } else {
296 return NULL;
300 memmove(dest, h, sizeof(struct memory_handle) + data_size);
302 return dest;
307 BUFFER SPACE MANAGEMENT
308 =======================
310 buffer_handle : Buffer data for a handle
311 free_buffer : Free buffer space by moving a handle
312 fill_buffer : Call buffer_handle for all handles that have data to buffer
313 can_add_handle : Indicate whether it's safe to add a handle.
314 data_rem : Total amount of data needing to be buffered
315 wasted_space : Total amount of space available for freeing
317 These functions are used by the buffering thread to manage buffer space.
320 static bool filebuf_is_lowdata(void)
322 return BUF_USED < AUDIO_FILEBUF_CRITICAL;
325 /* Yield to the codec thread for as long as possible if it is in need of data.
326 Return true if the caller should break to let the buffering thread process
327 new queue events */
328 static bool yield_codec(void)
330 yield();
332 if (!queue_empty(&buffering_queue))
333 return true;
335 while (pcmbuf_is_lowdata() && !filebuf_is_lowdata())
337 sleep(2);
339 if (!queue_empty(&buffering_queue))
340 return true;
343 return false;
346 /* Buffer data for the given handle. Return the amount of data buffered
347 or -1 if the handle wasn't found */
348 /* TODO: add an argument for the requested amount */
349 static ssize_t buffer_handle(int handle_id)
351 DEBUGF("buffer_handle(%d)\n", handle_id);
352 struct memory_handle *h = find_handle(handle_id);
353 if (!h)
354 return -1;
356 if (h->filerem == 0) {
357 /* nothing left to buffer */
358 return 0;
361 if (h->fd < 0) /* file closed, reopen */
363 if (*h->path)
364 h->fd = open(h->path, O_RDONLY);
365 else
366 return -1;
368 if (h->fd < 0)
369 return -1;
371 if (h->offset)
372 lseek(h->fd, h->offset, SEEK_SET);
375 trigger_cpu_boost();
377 ssize_t ret = 0;
378 while (h->filerem > 0)
380 /* max amount to copy */
381 size_t copy_n = MIN( MIN(h->filerem, conf_filechunk),
382 buffer_len - h->widx);
384 /* stop copying if it would overwrite the reading position
385 or the next handle */
386 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0 || (h->next &&
387 RINGBUF_ADD_CROSS(h->widx, copy_n, (unsigned)
388 ((void *)h->next - (void *)buffer)) > 0))
389 break;
391 /* rc is the actual amount read */
392 int rc = read(h->fd, &buffer[h->widx], copy_n);
394 if (rc < 0)
396 if (h->type == TYPE_CODEC) {
397 DEBUGF("Partial codec\n");
398 break;
401 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
402 h->filesize -= h->filerem;
403 h->filerem = 0;
404 break;
407 /* Advance buffer */
408 h->widx = RINGBUF_ADD(h->widx, rc);
409 if (h == cur_handle)
410 buf_widx = h->widx;
411 h->available += rc;
412 ret += rc;
413 h->filerem -= rc;
415 /* DEBUGF("buffer_handle(%d): buffered %ld bytes. done: %ld. remaining: %ld.\n",
416 h->id, rc, h->available, h->filerem); */
418 /* Stop buffering if new queue events have arrived */
419 if (yield_codec())
420 break;
423 if (h->filerem == 0) {
424 /* finished buffering the file */
425 close(h->fd);
426 h->fd = -1;
429 DEBUGF("buffered %ld bytes (%ld of %ld available, rem: %ld, off: %ld)\n",
430 (long)ret, (long)h->available, (long)h->filesize,
431 (long)h->filerem, (long)h->offset);
433 return ret;
436 /* Reset writing position and data buffer of a handle to its current offset.
437 Use this after having set the new offset to use.
438 Returns 0 for success or -1 if the handle wasn't found. */
439 static void reset_handle(int handle_id)
441 DEBUGF("reset_handle(%d)\n", handle_id);
443 struct memory_handle *h = find_handle(handle_id);
444 if (!h)
445 return;
447 h->widx = h->data;
448 if (h == cur_handle)
449 buf_widx = h->widx;
450 h->available = 0;
451 h->filerem = h->filesize - h->offset;
453 if (h->fd >= 0) {
454 lseek(h->fd, h->offset, SEEK_SET);
458 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
459 static void rebuffer_handle(int handle_id, size_t newpos)
461 struct memory_handle *h = find_handle(handle_id);
462 if (!h)
463 return;
465 DEBUGF("rebuffer_handle: resetting the handle to offset %ld\n", (long)newpos);
466 h->offset = newpos;
468 LOGFQUEUE("? >| buffering Q_RESET_HANDLE");
469 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
471 LOGFQUEUE("? >| buffering Q_BUFFER_HANDLE");
472 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
474 h->ridx = h->data;
477 /* Free buffer space by moving the handle struct right before the useful
478 part of its data buffer or by moving all the data. */
479 static void free_buffer(int handle_id)
481 struct memory_handle *h = find_handle(handle_id);
482 if (!h)
483 return;
485 size_t delta;
486 /* The value of delta might change for alignment reasons */
488 if (h->next && (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
489 h->type == TYPE_IMAGE) && h->filerem == 0 )
491 /* metadata handle: we can move all of it */
492 delta = RINGBUF_SUB( (unsigned)((void *)h->next - (void *)buffer),
493 h->data) - h->available;
494 h = move_handle(h, &delta, h->available);
495 if (!h) return;
496 h->data = RINGBUF_ADD(h->data, delta);
497 h->ridx = RINGBUF_ADD(h->ridx, delta);
498 h->widx = RINGBUF_ADD(h->widx, delta);
500 /* when moving a struct mp3entry we need to readjust its pointers. */
501 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
502 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
503 (void *)&buffer[h->data],
504 (void *)&buffer[RINGBUF_SUB(h->data, delta)]);
507 DEBUGF("free_buffer(%d): metadata, moved by %ld bytes\n",
508 handle_id, (long)delta);
510 else
512 /* only move the handle struct */
513 delta = RINGBUF_SUB(h->ridx, h->data);
514 h = move_handle(h, &delta, 0);
515 if (!h) return;
516 h->data = RINGBUF_ADD(h->data, delta);
517 h->available -= delta;
518 h->offset += delta;
519 DEBUGF("free_buffer(%d): audio, %ld bytes freed\n",
520 handle_id, (long)delta);
524 /* Fill the buffer by buffering as much data as possible for handles that still
525 have data left to buffer */
526 static void fill_buffer(void)
528 DEBUGF("fill buffer()\n");
529 struct memory_handle *m = first_handle;
530 while (m) {
531 if (m->filerem > 0) {
532 buffer_handle(m->id);
534 m = m->next;
538 /* Check whether it's safe to add a new handle and reserve space to let the
539 current one finish buffering its data. Used by bufopen and bufalloc as
540 a preliminary check before even trying to physically add the handle.
541 Returns true if it's ok to add a new handle, false if not.
543 static bool can_add_handle(void)
545 if (cur_handle && cur_handle->filerem > 0) {
546 /* the current handle hasn't finished buffering. We can only add
547 a new one if there is already enough free space to finish
548 the buffering. */
549 if (cur_handle->filerem < (buffer_len - BUF_USED)) {
550 /* Before adding the new handle we reserve some space for the
551 current one to finish buffering its data. */
552 buf_widx = RINGBUF_ADD(buf_widx, cur_handle->filerem);
553 } else {
554 return false;
558 return true;
561 /* Return the total amount of data left to be buffered for all the handles */
562 static size_t data_rem(void)
564 size_t ret = 0;
566 struct memory_handle *m = first_handle;
567 while (m) {
568 ret += m->filerem;
569 m = m->next;
572 return ret;
575 /* Return the amount of data we have but don't need anymore. This data can be
576 safely erased to reclaim buffer space. */
577 static size_t wasted_space(void)
579 size_t ret = 0;
581 struct memory_handle *m = first_handle;
582 while (m) {
583 ret += RINGBUF_SUB(m->ridx, m->data);
584 m = m->next;
587 return ret;
592 BUFFERING API FUNCTIONS
593 =======================
595 bufopen : Request the opening of a new handle for a file
596 bufalloc : Open a new handle for data other than a file.
597 bufclose : Close an open handle
598 bufseek : Set the read pointer in a handle
599 bufadvance : Move the read pointer in a handle
600 bufread : Copy data from a handle into a given buffer
601 bufgetdata : Give a pointer to the handle's data
602 bufused : Return the amount of buffer space used
604 These functions are exported, to allow interaction with the buffer.
605 They take care of the content of the structs, and rely on the linked list
606 management functions for all the actual handle management work.
610 /* Request a file be buffered
611 filename: name of the file to open
612 offset: offset at which to start buffering the file, useful when the first
613 (offset-1) bytes of the file aren't needed.
614 return value: <0 if the file cannot be opened, or one file already
615 queued to be opened, otherwise the handle for the file in the buffer
617 int bufopen(char *file, size_t offset, enum data_type type)
619 if (!can_add_handle())
620 return -2;
622 int fd = open(file, O_RDONLY);
623 if (fd < 0)
624 return -1;
626 size_t size = filesize(fd) - offset;
628 if (type != TYPE_AUDIO &&
629 size + sizeof(struct memory_handle) > buffer_len - buf_widx)
631 /* for types other than audio, the data can't wrap, so we force it */
632 buf_widx = 0;
635 DEBUGF("bufopen: %s (offset: %ld) (%ld bytes needed)...\n",
636 file, (long)offset, (long)size);
638 struct memory_handle *h = add_handle(&size);
639 if (!h)
641 DEBUGF("bufopen: failed to add handle\n");
642 close(fd);
643 return -2;
646 strncpy(h->path, file, MAX_PATH);
647 h->fd = -1;
648 h->filesize = filesize(fd);
649 h->filerem = h->filesize - offset;
650 h->offset = offset;
651 h->ridx = buf_widx;
652 h->widx = buf_widx;
653 h->data = buf_widx;
654 h->available = 0;
655 h->type = type;
657 close(fd);
659 DEBUGF("bufopen: allocated %ld bytes. ID: %d\n", (long)size, h->id);
661 if (type == TYPE_CODEC || type == TYPE_CUESHEET || type == TYPE_IMAGE) {
662 /* Immediately buffer those */
663 LOGFQUEUE("? >| buffering Q_BUFFER_HANDLE");
664 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
667 DEBUGF("bufopen: opened handle %d\n", h->id);
668 return h->id;
671 /* Open a new handle from data that isn't in a file.
672 src is the source buffer from which to copy data. It can be NULL to simply
673 reserve buffer space.
674 size is the requested size. The call will only be successful if the
675 requested amount of data can entirely fit in the buffer without wrapping.
676 Return value is the handle id for success or <0 for failure.
678 int bufalloc(void *src, size_t size, enum data_type type)
680 if (!can_add_handle())
681 return -2;
683 if (size + sizeof(struct memory_handle) > buffer_len - buf_widx) {
684 /* The data would need to wrap. */
685 DEBUGF("bufalloc: data wrap\n");
686 return -2;
689 size_t allocsize = size;
690 struct memory_handle *h = add_handle(&allocsize);
692 if (!h || allocsize != size)
693 return -2;
695 if (src) {
696 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
697 DEBUGF("bufalloc: allocating metadata\n");
698 /* specially take care of struct mp3entry */
699 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
700 (struct mp3entry *)src);
701 } else {
702 memcpy(&buffer[buf_widx], src, size);
706 h->fd = -1;
707 *h->path = 0;
708 h->filesize = size;
709 h->filerem = 0;
710 h->offset = 0;
711 h->ridx = buf_widx;
712 h->widx = buf_widx;
713 h->data = buf_widx;
714 h->available = size;
715 h->type = type;
717 buf_widx = RINGBUF_ADD(buf_widx, size);
719 DEBUGF("bufalloc: opened handle %d\n", h->id);
720 return h->id;
723 /* Close the handle. Return 0 for success and < 0 for failure */
724 int bufclose(int handle_id)
726 DEBUGF("bufclose(%d)\n", handle_id);
727 struct memory_handle *h = find_handle(handle_id);
728 if (!h)
729 return -1;
731 if (h->fd >= 0) {
732 close(h->fd);
733 h->fd = -1;
736 rm_handle(h);
737 return 0;
740 /* Set reading index in handle (relatively to the start of the file).
741 Access before the available data will trigger a rebuffer.
742 TODO: Make it behave like bufadvance
743 TODO: Maybe force an immediate rebuffer by calling buffer_handle() ?
744 Return 0 for success and < 0 for failure:
745 -1 if the handle wasn't found
746 -2 if there is no data available at the new position
747 (the reading index is still moved)
748 -3 if the new requested position was beyond the end of the file
750 int bufseek(int handle_id, size_t newpos)
752 int ret = 0;
753 struct memory_handle *h = find_handle(handle_id);
754 if (!h)
755 return -1;
757 if (newpos > h->filesize) {
758 /* access beyond the end of the file */
759 return -3;
762 else if (newpos < h->offset) {
763 /* access before what we currently have. A rebuffer is needed. */
764 h->offset = newpos;
765 /* TODO: Add a reset_handle queue call here like in bufadvance. */
766 ret = -2;
769 else if (newpos > h->offset + h->available) {
770 /* data isn't available yet. */
771 ret = -2;
774 h->ridx = RINGBUF_ADD(h->data, newpos);
775 return ret;
778 /* Advance the reading index in a handle (relatively to its current position).
779 Return 0 for success and < 0 for failure */
780 int bufadvance(int handle_id, off_t offset)
782 struct memory_handle *h = find_handle(handle_id);
783 if (!h)
784 return -1;
786 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
788 if (offset >= 0)
790 /* check for access beyond what's available */
791 if ((size_t)offset > (h->available - RINGBUF_SUB(h->ridx, h->data)))
793 DEBUGF("bufadvance: access after data\n");
794 rebuffer_handle(handle_id, newpos);
796 else
797 h->ridx = RINGBUF_ADD(h->ridx, offset);
799 else
801 /* check for access before what's available */
802 if ((size_t)(-offset) > RINGBUF_SUB(h->ridx, h->data))
804 DEBUGF("bufadvance: access before data\n");
805 rebuffer_handle(handle_id, newpos);
807 else
808 h->ridx = RINGBUF_SUB(h->ridx, (size_t)(-offset));
811 //DEBUGF("bufadvance: %ld\n", (long)offset);
812 return 0;
815 /* Copy data from the given handle to the dest buffer.
816 Return the number of bytes copied or < 0 for failure. */
817 ssize_t bufread(int handle_id, size_t size, char *dest)
819 struct memory_handle *h = find_handle(handle_id);
820 size_t buffered_data;
821 if (!h)
822 return -1;
824 if (size == 0 && h->filerem > 0 &&
825 h->available - RINGBUF_SUB(h->ridx, h->data) == 0)
826 /* Data isn't ready */
827 return -2;
829 if (h->available - RINGBUF_SUB(h->ridx, h->data) < size && h->filerem > 0)
830 /* Data isn't ready */
831 return -2;
833 if (h->available - RINGBUF_SUB(h->ridx, h->data) == 0 && h->filerem == 0)
834 /* File is finished reading */
835 return 0;
837 buffered_data = MIN(size, h->available - RINGBUF_SUB(h->ridx, h->data));
839 if (h->ridx + buffered_data > buffer_len)
841 /* the data wraps around the end of the buffer */
842 size_t read = buffer_len - h->ridx;
843 memcpy(dest, &buffer[h->ridx], read);
844 memcpy(dest+read, buffer, buffered_data - read);
846 else memcpy(dest, &buffer[h->ridx], buffered_data);
848 return buffered_data;
851 /* Update the "data" pointer to make the handle's data available to the caller.
852 Return the length of the available linear data or < 0 for failure.
853 size is the amount of linear data requested. it can be 0 to get as
854 much as possible.
855 The guard buffer may be used to provide the requested size */
856 ssize_t bufgetdata(int handle_id, size_t size, unsigned char **data)
858 struct memory_handle *h = find_handle(handle_id);
859 if (!h)
860 return -1;
862 if (size == 0 && h->filerem > 0 &&
863 h->available - RINGBUF_SUB(h->ridx, h->data) == 0)
864 /* Data isn't ready */
865 return -2;
867 if (h->available - RINGBUF_SUB(h->ridx, h->data) < size && h->filerem > 0)
868 /* Data isn't ready */
869 return -2;
871 if (h->available - RINGBUF_SUB(h->ridx, h->data) == 0 && h->filerem == 0)
872 /* File is finished reading */
873 return 0;
875 ssize_t ret;
877 if (h->ridx + size > buffer_len &&
878 h->available - RINGBUF_SUB(h->ridx, h->data) >= size)
880 /* the data wraps around the end of the buffer :
881 use the guard buffer to provide the requested amount of data. */
882 size_t copy_n = MIN(h->ridx + size - buffer_len, GUARD_BUFSIZE);
883 memcpy(guard_buffer, (unsigned char *)buffer, copy_n);
884 ret = buffer_len - h->ridx + copy_n;
885 DEBUGF("used the guard buffer to complete\n");
887 else
889 ret = MIN(h->available - RINGBUF_SUB(h->ridx, h->data),
890 buffer_len - h->ridx);
893 *data = (unsigned char *)&buffer[h->ridx];
895 /* DEBUGF("bufgetdata(%d): h->ridx=%ld, ret=%ld\n", handle_id,
896 (long)h->ridx, ret); */
897 return ret;
900 /* Return the amount of buffer space used */
901 size_t bufused(void)
903 return BUF_USED;
906 bool buffering_init(char *filebuf, size_t filebuflen)
908 if (!filebuf || !filebuflen)
909 return false;
911 buffer = filebuf;
912 buffer_len = filebuflen;
913 guard_buffer = buffer + buffer_len;
915 buf_widx = 0;
916 buf_ridx = 0;
918 first_handle = NULL;
919 num_handles = 0;
921 conf_filechunk = AUDIO_DEFAULT_FILECHUNK;
923 queue_init(&buffering_queue, true);
924 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list);
926 return true;
929 void buffering_thread(void)
931 struct queue_event ev;
933 while (true)
935 queue_wait_w_tmo(&buffering_queue, &ev, HZ/2);
936 switch (ev.id)
938 case Q_BUFFER_HANDLE:
939 LOGFQUEUE("buffering < Q_BUFFER_HANDLE");
940 queue_reply(&buffering_queue, 1);
941 buffer_handle((int)ev.data);
942 break;
944 case Q_RESET_HANDLE:
945 LOGFQUEUE("buffering < Q_RESET_HANDLE");
946 queue_reply(&buffering_queue, 1);
947 reset_handle((int)ev.data);
948 break;
950 #ifndef SIMULATOR
951 case SYS_USB_CONNECTED:
952 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
953 usb_acknowledge(SYS_USB_CONNECTED_ACK);
954 usb_wait_for_disconnect(&buffering_queue);
955 break;
956 #endif
959 if (queue_empty(&buffering_queue) &&
960 data_rem() > 0 && wasted_space() > buffer_len/5) {
961 DEBUGF("there is %ld bytes of wasted space\n", (long)wasted_space());
963 /* free buffer from outdated audio data */
964 struct memory_handle *m = first_handle;
965 while (m) {
966 if (m->type == TYPE_AUDIO)
967 free_buffer(m->id);
968 m = m->next;
971 /* free buffer by moving metadata */
972 m = first_handle;
973 while (m) {
974 if (m->type != TYPE_AUDIO)
975 free_buffer(m->id);
976 m = m->next;
981 if (queue_empty(&buffering_queue) &&
982 data_rem() > 0 && BUF_USED < 3*buffer_len/4 /* &&
983 ata_disk_is_active() */)
985 DEBUGF("%ld bytes left to buffer and the buffer is low\n",
986 (long)data_rem());
987 fill_buffer();
988 } /* else {
989 sleep(HZ/2);
990 } */
994 ssize_t get_offset(int handle_id, void *ptr)
996 struct memory_handle *h = find_handle(handle_id);
997 if (!h)
998 return -1;
1000 return (size_t)ptr - (size_t)&buffer[h->ridx];