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