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*32)
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 static 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
, bool can_wrap
,
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(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 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
, (const 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 (const 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(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 size_t adjusted_offset
= offset
;
880 int fd
= open(file
, O_RDONLY
);
882 return ERR_FILE_ERROR
;
884 size_t size
= filesize(fd
);
885 bool can_wrap
= type
==TYPE_PACKET_AUDIO
|| type
==TYPE_CODEC
;
887 if (adjusted_offset
> size
)
890 struct memory_handle
*h
= add_handle(size
-adjusted_offset
, can_wrap
, false);
893 DEBUGF("bufopen: failed to add handle\n");
895 return ERR_BUFFER_FULL
;
898 strncpy(h
->path
, file
, MAX_PATH
);
899 h
->offset
= adjusted_offset
;
905 if (type
== TYPE_BITMAP
)
907 /* Bitmap file: we load the data instead of the file */
909 mutex_lock(&llist_mutex
); /* Lock because load_bitmap yields */
910 rc
= load_bitmap(fd
);
915 mutex_unlock(&llist_mutex
);
916 return ERR_FILE_ERROR
;
921 h
->widx
= buf_widx
+ rc
; /* safe because the data doesn't wrap */
922 buf_widx
+= rc
; /* safe too */
923 mutex_unlock(&llist_mutex
);
928 h
->filerem
= size
- adjusted_offset
;
934 if (type
== TYPE_CUESHEET
) {
936 /* Immediately start buffering those */
937 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE");
938 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, h
->id
);
940 /* Other types will get buffered in the course of normal operations */
944 /* Inform the buffering thread that we added a handle */
945 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
946 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
949 logf("bufopen: new hdl %d", h
->id
);
953 /* Open a new handle from data that needs to be copied from memory.
954 src is the source buffer from which to copy data. It can be NULL to simply
955 reserve buffer space.
956 size is the requested size. The call will only be successful if the
957 requested amount of data can entirely fit in the buffer without wrapping.
958 Return value is the handle id for success or <0 for failure.
960 int bufalloc(const void *src
, size_t size
, enum data_type type
)
962 struct memory_handle
*h
= add_handle(size
, false, true);
965 return ERR_BUFFER_FULL
;
968 if (type
== TYPE_ID3
&& size
== sizeof(struct mp3entry
)) {
969 /* specially take care of struct mp3entry */
970 copy_mp3entry((struct mp3entry
*)&buffer
[buf_widx
],
971 (const struct mp3entry
*)src
);
973 memcpy(&buffer
[buf_widx
], src
, size
);
983 h
->widx
= buf_widx
+ size
; /* this is safe because the data doesn't wrap */
988 buf_widx
+= size
; /* safe too */
990 logf("bufalloc: new hdl %d", h
->id
);
994 /* Close the handle. Return true for success and false for failure */
995 bool bufclose(int handle_id
)
997 logf("bufclose(%d)", handle_id
);
999 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id
);
1000 return queue_send(&buffering_queue
, Q_CLOSE_HANDLE
, handle_id
);
1003 /* Set reading index in handle (relatively to the start of the file).
1004 Access before the available data will trigger a rebuffer.
1005 Return 0 for success and < 0 for failure:
1006 -1 if the handle wasn't found
1007 -2 if the new requested position was beyond the end of the file
1009 int bufseek(int handle_id
, size_t newpos
)
1011 struct memory_handle
*h
= find_handle(handle_id
);
1013 return ERR_HANDLE_NOT_FOUND
;
1015 if (newpos
> h
->filesize
) {
1016 /* access beyond the end of the file */
1017 return ERR_INVALID_VALUE
;
1019 else if (newpos
< h
->offset
|| h
->offset
+ h
->available
< newpos
) {
1020 /* access before or after buffered data. A rebuffer is needed. */
1021 rebuffer_handle(handle_id
, newpos
);
1024 h
->ridx
= RINGBUF_ADD(h
->data
, newpos
- h
->offset
);
1029 /* Advance the reading index in a handle (relatively to its current position).
1030 Return 0 for success and < 0 for failure */
1031 int bufadvance(int handle_id
, off_t offset
)
1033 const struct memory_handle
*h
= find_handle(handle_id
);
1035 return ERR_HANDLE_NOT_FOUND
;
1037 size_t newpos
= h
->offset
+ RINGBUF_SUB(h
->ridx
, h
->data
) + offset
;
1038 return bufseek(handle_id
, newpos
);
1041 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1042 * actual amount of data available for reading. This function explicitly
1043 * does not check the validity of the input handle. It does do range checks
1044 * on size and returns a valid (and explicit) amount of data for reading */
1045 static struct memory_handle
*prep_bufdata(int handle_id
, size_t *size
,
1046 bool guardbuf_limit
)
1048 struct memory_handle
*h
= find_handle(handle_id
);
1052 size_t avail
= RINGBUF_SUB(h
->widx
, h
->ridx
);
1054 if (avail
== 0 && h
->filerem
== 0)
1056 /* File is finished reading */
1061 if (*size
== 0 || *size
> avail
+ h
->filerem
)
1062 *size
= avail
+ h
->filerem
;
1064 if (guardbuf_limit
&& h
->type
== TYPE_PACKET_AUDIO
&& *size
> GUARD_BUFSIZE
)
1066 logf("data request > guardbuf");
1067 /* If more than the size of the guardbuf is requested and this is a
1068 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1069 *size
= MIN(*size
, buffer_len
- h
->ridx
+ GUARD_BUFSIZE
);
1070 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1073 if (h
->filerem
> 0 && avail
< *size
)
1075 /* Data isn't ready. Request buffering */
1076 buf_request_buffer_handle(handle_id
);
1077 /* Wait for the data to be ready */
1081 /* it is not safe for a non-buffering thread to sleep while
1082 * holding a handle */
1083 h
= find_handle(handle_id
);
1086 avail
= RINGBUF_SUB(h
->widx
, h
->ridx
);
1088 while (h
->filerem
> 0 && avail
< *size
);
1091 *size
= MIN(*size
,avail
);
1095 /* Copy data from the given handle to the dest buffer.
1096 Return the number of bytes copied or < 0 for failure (handle not found).
1097 The caller is blocked until the requested amount of data is available.
1099 ssize_t
bufread(int handle_id
, size_t size
, void *dest
)
1101 const struct memory_handle
*h
;
1102 size_t adjusted_size
= size
;
1104 h
= prep_bufdata(handle_id
, &adjusted_size
, false);
1106 return ERR_HANDLE_NOT_FOUND
;
1108 if (h
->ridx
+ adjusted_size
> buffer_len
)
1110 /* the data wraps around the end of the buffer */
1111 size_t read
= buffer_len
- h
->ridx
;
1112 memcpy(dest
, &buffer
[h
->ridx
], read
);
1113 memcpy(dest
+read
, buffer
, adjusted_size
- read
);
1117 memcpy(dest
, &buffer
[h
->ridx
], adjusted_size
);
1120 return adjusted_size
;
1123 /* Update the "data" pointer to make the handle's data available to the caller.
1124 Return the length of the available linear data or < 0 for failure (handle
1126 The caller is blocked until the requested amount of data is available.
1127 size is the amount of linear data requested. it can be 0 to get as
1129 The guard buffer may be used to provide the requested size. This means it's
1130 unsafe to request more than the size of the guard buffer.
1132 ssize_t
bufgetdata(int handle_id
, size_t size
, void **data
)
1134 const struct memory_handle
*h
;
1135 size_t adjusted_size
= size
;
1137 h
= prep_bufdata(handle_id
, &adjusted_size
, true);
1139 return ERR_HANDLE_NOT_FOUND
;
1141 if (h
->ridx
+ adjusted_size
> buffer_len
)
1143 /* the data wraps around the end of the buffer :
1144 use the guard buffer to provide the requested amount of data. */
1145 size_t copy_n
= h
->ridx
+ adjusted_size
- buffer_len
;
1146 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1147 so copy_n <= GUARD_BUFSIZE */
1148 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1152 *data
= &buffer
[h
->ridx
];
1154 return adjusted_size
;
1157 ssize_t
bufgettail(int handle_id
, size_t size
, void **data
)
1161 const struct memory_handle
*h
;
1163 h
= find_handle(handle_id
);
1166 return ERR_HANDLE_NOT_FOUND
;
1169 return ERR_HANDLE_NOT_DONE
;
1171 /* We don't support tail requests of > guardbuf_size, for simplicity */
1172 if (size
> GUARD_BUFSIZE
)
1173 return ERR_INVALID_VALUE
;
1175 tidx
= RINGBUF_SUB(h
->widx
, size
);
1177 if (tidx
+ size
> buffer_len
)
1179 size_t copy_n
= tidx
+ size
- buffer_len
;
1180 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1183 *data
= &buffer
[tidx
];
1187 ssize_t
bufcuttail(int handle_id
, size_t size
)
1189 struct memory_handle
*h
;
1190 size_t adjusted_size
= size
;
1192 h
= find_handle(handle_id
);
1195 return ERR_HANDLE_NOT_FOUND
;
1198 return ERR_HANDLE_NOT_DONE
;
1200 if (h
->available
< adjusted_size
)
1201 adjusted_size
= h
->available
;
1203 h
->available
-= adjusted_size
;
1204 h
->filesize
-= adjusted_size
;
1205 h
->widx
= RINGBUF_SUB(h
->widx
, adjusted_size
);
1206 if (h
== cur_handle
)
1209 return adjusted_size
;
1214 SECONDARY EXPORTED FUNCTIONS
1215 ============================
1219 buf_request_buffer_handle
1222 register_buffering_callback
1223 unregister_buffering_callback
1225 These functions are exported, to allow interaction with the buffer.
1226 They take care of the content of the structs, and rely on the linked list
1227 management functions for all the actual handle management work.
1230 /* Get a handle offset from a pointer */
1231 ssize_t
buf_get_offset(int handle_id
, void *ptr
)
1233 const struct memory_handle
*h
= find_handle(handle_id
);
1235 return ERR_HANDLE_NOT_FOUND
;
1237 return (size_t)ptr
- (size_t)&buffer
[h
->ridx
];
1240 ssize_t
buf_handle_offset(int handle_id
)
1242 const struct memory_handle
*h
= find_handle(handle_id
);
1244 return ERR_HANDLE_NOT_FOUND
;
1248 void buf_request_buffer_handle(int handle_id
)
1250 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id
);
1251 queue_send(&buffering_queue
, Q_START_FILL
, handle_id
);
1254 void buf_set_base_handle(int handle_id
)
1256 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id
);
1257 queue_post(&buffering_queue
, Q_BASE_HANDLE
, handle_id
);
1260 /* Return the amount of buffer space used */
1261 size_t buf_used(void)
1266 void buf_set_watermark(size_t bytes
)
1268 LOGFQUEUE("buffering > Q_SET_WATERMARK %ld", (long)bytes
);
1269 queue_post(&buffering_queue
, Q_SET_WATERMARK
, bytes
);
1272 bool register_buffering_callback(buffering_callback func
)
1275 if (buffer_callback_count
>= MAX_BUF_CALLBACKS
)
1277 for (i
= 0; i
< MAX_BUF_CALLBACKS
; i
++)
1279 if (buffering_callback_funcs
[i
] == NULL
)
1281 buffering_callback_funcs
[i
] = func
;
1282 buffer_callback_count
++;
1285 else if (buffering_callback_funcs
[i
] == func
)
1291 void unregister_buffering_callback(buffering_callback func
)
1294 for (i
= 0; i
< MAX_BUF_CALLBACKS
; i
++)
1296 if (buffering_callback_funcs
[i
] == func
)
1298 buffering_callback_funcs
[i
] = NULL
;
1299 buffer_callback_count
--;
1305 static void call_buffering_callbacks(enum callback_event ev
, int value
)
1307 logf("call_buffering_callbacks()");
1309 for (i
= 0; i
< MAX_BUF_CALLBACKS
; i
++)
1311 if (buffering_callback_funcs
[i
])
1313 buffering_callback_funcs
[i
](ev
, value
);
1318 static void shrink_buffer_inner(struct memory_handle
*h
)
1323 shrink_buffer_inner(h
->next
);
1328 static void shrink_buffer(void)
1330 logf("shrink_buffer()");
1331 shrink_buffer_inner(first_handle
);
1334 void buffering_thread(void)
1336 bool filling
= false;
1337 struct queue_event ev
;
1345 queue_wait_w_tmo(&buffering_queue
, &ev
, filling
? 5 : HZ
/2);
1350 LOGFQUEUE("buffering < Q_START_FILL");
1351 /* Call buffer callbacks here because this is one of two ways
1352 * to begin a full buffer fill */
1353 call_buffering_callbacks(EVENT_BUFFER_LOW
, 0);
1355 queue_reply(&buffering_queue
, 1);
1356 filling
|= buffer_handle((int)ev
.data
);
1359 case Q_BUFFER_HANDLE
:
1360 LOGFQUEUE("buffering < Q_BUFFER_HANDLE");
1361 queue_reply(&buffering_queue
, 1);
1362 buffer_handle((int)ev
.data
);
1365 case Q_RESET_HANDLE
:
1366 LOGFQUEUE("buffering < Q_RESET_HANDLE");
1367 queue_reply(&buffering_queue
, 1);
1368 reset_handle((int)ev
.data
);
1371 case Q_CLOSE_HANDLE
:
1372 LOGFQUEUE("buffering < Q_CLOSE_HANDLE");
1373 queue_reply(&buffering_queue
, close_handle((int)ev
.data
));
1376 case Q_HANDLE_ADDED
:
1377 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev
.data
);
1378 /* A handle was added: the disk is spinning, so we can fill */
1383 LOGFQUEUE("buffering < Q_BASE_HANDLE");
1384 base_handle_id
= (int)ev
.data
;
1387 case Q_SET_WATERMARK
:
1388 LOGFQUEUE("buffering < Q_SET_WATERMARK");
1389 conf_watermark
= (size_t)ev
.data
;
1390 if (conf_watermark
< BUFFERING_DEFAULT_FILECHUNK
)
1392 logf("wmark<chunk %ld<%d",
1393 (long)conf_watermark
, BUFFERING_DEFAULT_FILECHUNK
);
1394 conf_watermark
= BUFFERING_DEFAULT_FILECHUNK
;
1399 case SYS_USB_CONNECTED
:
1400 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1401 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
1402 usb_wait_for_disconnect(&buffering_queue
);
1407 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1411 update_data_counters();
1413 /* If the buffer is low, call the callbacks to get new data */
1414 if (num_handles
> 0 && data_counters
.useful
<= conf_watermark
)
1415 call_buffering_callbacks(EVENT_BUFFER_LOW
, 0);
1418 /* TODO: This needs to be fixed to use the idle callback, disable it
1419 * for simplicity until its done right */
1421 /* If the disk is spinning, take advantage by filling the buffer */
1422 else if (ata_disk_is_active() && queue_empty(&buffering_queue
))
1424 if (num_handles
> 0 && data_counters
.useful
<= high_watermark
)
1425 call_buffering_callbacks(EVENT_BUFFER_LOW
, 0);
1427 if (data_counters
.remaining
> 0 && BUF_USED
<= high_watermark
)
1429 /* This is a new fill, shrink the buffer up first */
1432 filling
= fill_buffer();
1433 update_data_counters();
1439 if (queue_empty(&buffering_queue
)) {
1441 if (data_counters
.remaining
> 0 && BUF_USED
< buffer_len
)
1442 filling
= fill_buffer();
1444 else if (ev
.id
== SYS_TIMEOUT
)
1446 if (data_counters
.remaining
> 0 &&
1447 data_counters
.useful
<= conf_watermark
) {
1449 filling
= fill_buffer();
1456 void buffering_init(void)
1458 mutex_init(&llist_mutex
);
1459 #ifdef HAVE_PRIORITY_SCHEDULING
1460 /* This behavior not safe atm */
1461 mutex_set_preempt(&llist_mutex
, false);
1464 conf_watermark
= BUFFERING_DEFAULT_WATERMARK
;
1466 queue_init(&buffering_queue
, true);
1467 buffering_thread_p
= create_thread( buffering_thread
, buffering_stack
,
1468 sizeof(buffering_stack
), CREATE_THREAD_FROZEN
,
1469 buffering_thread_name
IF_PRIO(, PRIORITY_BUFFERING
)
1472 queue_enable_queue_send(&buffering_queue
, &buffering_queue_sender_list
,
1473 buffering_thread_p
);
1476 /* Initialise the buffering subsystem */
1477 bool buffering_reset(char *buf
, size_t buflen
)
1479 if (!buf
|| !buflen
)
1483 buffer_len
= buflen
;
1484 guard_buffer
= buf
+ buflen
;
1489 first_handle
= NULL
;
1491 cached_handle
= NULL
;
1493 base_handle_id
= -1;
1495 buffer_callback_count
= 0;
1496 memset(buffering_callback_funcs
, 0, sizeof(buffering_callback_funcs
));
1498 /* Set the high watermark as 75% full...or 25% empty :) */
1500 high_watermark
= 3*buflen
/ 4;
1503 thread_thaw(buffering_thread_p
);
1508 void buffering_get_debugdata(struct buffering_debug
*dbgdata
)
1510 update_data_counters();
1511 dbgdata
->num_handles
= num_handles
;
1512 dbgdata
->data_rem
= data_counters
.remaining
;
1513 dbgdata
->wasted_space
= data_counters
.wasted
;
1514 dbgdata
->buffered_data
= data_counters
.buffered
;
1515 dbgdata
->useful_data
= data_counters
.useful
;