1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2007 Nicolas Pennequin
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
27 #include "buffering.h"
45 #include "mp3_playback.h"
52 #include "appevents.h"
56 #include "jpeg_load.h"
59 #define GUARD_BUFSIZE (32*1024)
61 /* Define LOGF_ENABLE to enable logf output in this file */
62 /*#define LOGF_ENABLE*/
65 /* macros to enable logf for queues
66 logging on SYS_TIMEOUT can be disabled */
68 /* Define this for logf output of all queuing except SYS_TIMEOUT */
69 #define BUFFERING_LOGQUEUES
70 /* Define this to logf SYS_TIMEOUT messages */
71 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
74 #ifdef BUFFERING_LOGQUEUES
75 #define LOGFQUEUE logf
77 #define LOGFQUEUE(...)
80 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
81 #define LOGFQUEUE_SYS_TIMEOUT logf
83 #define LOGFQUEUE_SYS_TIMEOUT(...)
86 /* default point to start buffer refill */
87 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
88 /* amount of data to read in one read() call */
89 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
91 #define BUF_HANDLE_MASK 0x7FFFFFFF
94 /* Ring buffer helper macros */
95 /* Buffer pointer (p) plus value (v), wrapped if necessary */
96 #define RINGBUF_ADD(p,v) (((p)+(v))<buffer_len ? (p)+(v) : (p)+(v)-buffer_len)
97 /* Buffer pointer (p) minus value (v), wrapped if necessary */
98 #define RINGBUF_SUB(p,v) ((p>=v) ? (p)-(v) : (p)+buffer_len-(v))
99 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
100 #define RINGBUF_ADD_CROSS(p1,v,p2) \
101 ((p1<p2) ? (int)((p1)+(v))-(int)(p2) : (int)((p1)+(v)-(p2))-(int)buffer_len)
102 /* Bytes available in the buffer */
103 #define BUF_USED RINGBUF_SUB(buf_widx, buf_ridx)
105 /* assert(sizeof(struct memory_handle)%4==0) */
106 struct memory_handle
{
107 int id
; /* A unique ID for the handle */
108 enum data_type type
; /* Type of data buffered with this handle */
109 char path
[MAX_PATH
]; /* Path if data originated in a file */
110 int fd
; /* File descriptor to path (-1 if closed) */
111 size_t data
; /* Start index of the handle's data buffer */
112 volatile size_t ridx
; /* Read pointer, relative to the main buffer */
113 size_t widx
; /* Write pointer */
114 size_t filesize
; /* File total length */
115 size_t filerem
; /* Remaining bytes of file NOT in buffer */
116 volatile size_t available
; /* Available bytes to read from buffer */
117 size_t offset
; /* Offset at which we started reading the file */
118 struct memory_handle
*next
;
120 /* invariant: filesize == offset + available + filerem */
123 static char *guard_buffer
;
125 static size_t buffer_len
;
127 static volatile size_t buf_widx
; /* current writing position */
128 static volatile size_t buf_ridx
; /* current reading position */
129 /* buf_*idx are values relative to the buffer, not real pointers. */
132 static size_t conf_watermark
= 0; /* Level to trigger filebuf fill */
134 static size_t high_watermark
= 0; /* High watermark for rebuffer */
137 /* current memory handle in the linked list. NULL when the list is empty. */
138 static struct memory_handle
*cur_handle
;
139 /* first memory handle in the linked list. NULL when the list is empty. */
140 static struct memory_handle
*first_handle
;
142 static int num_handles
; /* number of handles in the list */
144 static int base_handle_id
;
146 static struct mutex llist_mutex
;
147 static struct mutex llist_mod_mutex
;
149 /* Handle cache (makes find_handle faster).
150 This is global so that move_handle and rm_handle can invalidate it. */
151 static struct memory_handle
*cached_handle
= NULL
;
154 size_t remaining
; /* Amount of data needing to be buffered */
155 size_t wasted
; /* Amount of space available for freeing */
156 size_t buffered
; /* Amount of data currently in the buffer */
157 size_t useful
; /* Amount of data still useful to the user */
161 /* Messages available to communicate with the buffering thread */
163 Q_BUFFER_HANDLE
= 1, /* Request buffering of a handle, this should not be
164 used in a low buffer situation. */
165 Q_RESET_HANDLE
, /* (internal) Request resetting of a handle to its
166 offset (the offset has to be set beforehand) */
167 Q_CLOSE_HANDLE
, /* Request closing a handle */
168 Q_BASE_HANDLE
, /* Set the reference handle for buf_useful_data */
171 Q_START_FILL
, /* Request that the buffering thread initiate a buffer
172 fill at its earliest convenience */
173 Q_HANDLE_ADDED
, /* Inform the buffering thread that a handle was added,
174 (which means the disk is spinning) */
177 /* Buffering thread */
178 static void buffering_thread(void);
179 static long buffering_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)];
180 static const char buffering_thread_name
[] = "buffering";
181 static unsigned int buffering_thread_id
= 0;
182 static struct event_queue buffering_queue
;
183 static struct queue_sender_list buffering_queue_sender_list
;
188 LINKED LIST MANAGEMENT
189 ======================
191 add_handle : Add a handle to the list
192 rm_handle : Remove a handle from the list
193 find_handle : Get a handle pointer from an ID
194 move_handle : Move a handle in the buffer (with or without its data)
196 These functions only handle the linked list structure. They don't touch the
197 contents of the struct memory_handle headers. They also change the buf_*idx
198 pointers when necessary and manage the handle IDs.
200 The first and current (== last) handle are kept track of.
201 A new handle is added at buf_widx and becomes the current one.
202 buf_widx always points to the current writing position for the current handle
203 buf_ridx always points to the location of the first handle.
204 buf_ridx == buf_widx means the buffer is empty.
208 /* Add a new handle to the linked list and return it. It will have become the
210 data_size must contain the size of what will be in the handle.
211 can_wrap tells us whether this type of data may wrap on buffer
212 alloc_all tells us if we must immediately be able to allocate data_size
213 returns a valid memory handle if all conditions for allocation are met.
214 NULL if there memory_handle itself cannot be allocated or if the
215 data_size cannot be allocated and alloc_all is set. This function's
216 only potential side effect is to allocate space for the cur_handle
219 static struct memory_handle
*add_handle(size_t data_size
, bool can_wrap
,
222 /* gives each handle a unique id */
223 static int cur_handle_id
= 0;
229 if (num_handles
>= BUF_MAX_HANDLES
)
232 mutex_lock(&llist_mutex
);
233 mutex_lock(&llist_mod_mutex
);
235 if (cur_handle
&& cur_handle
->filerem
> 0) {
236 /* the current handle hasn't finished buffering. We can only add
237 a new one if there is already enough free space to finish
239 size_t req
= cur_handle
->filerem
+ sizeof(struct memory_handle
);
240 if (RINGBUF_ADD_CROSS(cur_handle
->widx
, req
, buf_ridx
) >= 0) {
241 /* Not enough space */
242 mutex_unlock(&llist_mod_mutex
);
243 mutex_unlock(&llist_mutex
);
246 /* Allocate the remainder of the space for the current handle */
247 buf_widx
= RINGBUF_ADD(cur_handle
->widx
, cur_handle
->filerem
);
251 /* align to 4 bytes up */
252 new_widx
= RINGBUF_ADD(buf_widx
, 3) & ~3;
254 len
= data_size
+ sizeof(struct memory_handle
);
256 /* First, will the handle wrap? */
257 /* If the handle would wrap, move to the beginning of the buffer,
258 * or if the data must not but would wrap, move it to the beginning */
259 if( (new_widx
+ sizeof(struct memory_handle
) > buffer_len
) ||
260 (!can_wrap
&& (new_widx
+ len
> buffer_len
)) ) {
264 /* How far we shifted buf_widx to align things, must be < buffer_len */
265 shift
= RINGBUF_SUB(new_widx
, buf_widx
);
267 /* How much space are we short in the actual ring buffer? */
268 overlap
= RINGBUF_ADD_CROSS(buf_widx
, shift
+ len
, buf_ridx
);
269 if (overlap
>= 0 && (alloc_all
|| (unsigned)overlap
> data_size
)) {
270 /* Not enough space for required allocations */
271 mutex_unlock(&llist_mod_mutex
);
272 mutex_unlock(&llist_mutex
);
276 /* There is enough space for the required data, advance the buf_widx and
277 * initialize the struct */
280 struct memory_handle
*new_handle
=
281 (struct memory_handle
*)(&buffer
[buf_widx
]);
283 /* only advance the buffer write index of the size of the struct */
284 buf_widx
= RINGBUF_ADD(buf_widx
, sizeof(struct memory_handle
));
286 new_handle
->id
= cur_handle_id
;
287 /* Wrap signed int is safe and 0 doesn't happen */
288 cur_handle_id
= (cur_handle_id
+ 1) & BUF_HANDLE_MASK
;
289 new_handle
->next
= NULL
;
293 /* the new handle is the first one */
294 first_handle
= new_handle
;
297 cur_handle
->next
= new_handle
;
299 cur_handle
= new_handle
;
301 mutex_unlock(&llist_mod_mutex
);
302 mutex_unlock(&llist_mutex
);
306 /* Delete a given memory handle from the linked list
307 and return true for success. Nothing is actually erased from memory. */
308 static bool rm_handle(const struct memory_handle
*h
)
313 mutex_lock(&llist_mutex
);
314 mutex_lock(&llist_mod_mutex
);
316 if (h
== first_handle
) {
317 first_handle
= h
->next
;
318 if (h
== cur_handle
) {
319 /* h was the first and last handle: the buffer is now empty */
321 buf_ridx
= buf_widx
= 0;
323 /* update buf_ridx to point to the new first handle */
324 buf_ridx
= (void *)first_handle
- (void *)buffer
;
327 struct memory_handle
*m
= first_handle
;
328 /* Find the previous handle */
329 while (m
&& m
->next
!= h
) {
332 if (m
&& m
->next
== h
) {
334 if (h
== cur_handle
) {
336 buf_widx
= cur_handle
->widx
;
339 mutex_unlock(&llist_mod_mutex
);
340 mutex_unlock(&llist_mutex
);
345 /* Invalidate the cache to prevent it from keeping the old location of h */
346 if (h
== cached_handle
)
347 cached_handle
= NULL
;
351 mutex_unlock(&llist_mod_mutex
);
352 mutex_unlock(&llist_mutex
);
356 /* Return a pointer to the memory handle of given ID.
357 NULL if the handle wasn't found */
358 static struct memory_handle
*find_handle(int handle_id
)
363 mutex_lock(&llist_mutex
);
365 /* simple caching because most of the time the requested handle
366 will either be the same as the last, or the one after the last */
369 if (cached_handle
->id
== handle_id
) {
370 mutex_unlock(&llist_mutex
);
371 return cached_handle
;
372 } else if (cached_handle
->next
&&
373 (cached_handle
->next
->id
== handle_id
)) {
374 cached_handle
= cached_handle
->next
;
375 mutex_unlock(&llist_mutex
);
376 return cached_handle
;
380 struct memory_handle
*m
= first_handle
;
381 while (m
&& m
->id
!= handle_id
) {
384 /* This condition can only be reached with !m or m->id == handle_id */
388 mutex_unlock(&llist_mutex
);
392 /* Move a memory handle and data_size of its data delta bytes along the buffer.
393 delta maximum bytes available to move the handle. If the move is performed
394 it is set to the actual distance moved.
395 data_size is the amount of data to move along with the struct.
396 returns a valid memory_handle if the move is successful
397 NULL if the handle is NULL, the move would be less than the size of
398 a memory_handle after correcting for wraps or if the handle is not
399 found in the linked list for adjustment. This function has no side
400 effects if NULL is returned. */
401 static bool move_handle(struct memory_handle
**h
, size_t *delta
,
402 size_t data_size
, bool can_wrap
)
404 struct memory_handle
*dest
;
405 const struct memory_handle
*src
;
408 size_t final_delta
= *delta
;
411 if (h
== NULL
|| (src
= *h
) == NULL
)
414 size_to_move
= sizeof(struct memory_handle
) + data_size
;
416 /* Align to four bytes, down */
418 if (final_delta
< sizeof(struct memory_handle
)) {
419 /* It's not legal to move less than the size of the struct */
423 mutex_lock(&llist_mutex
);
424 mutex_lock(&llist_mod_mutex
);
426 newpos
= RINGBUF_ADD((void *)src
- (void *)buffer
, final_delta
);
427 overlap
= RINGBUF_ADD_CROSS(newpos
, size_to_move
, buffer_len
- 1);
430 /* Some part of the struct + data would wrap, maybe ok */
431 size_t correction
= 0;
432 /* If the overlap lands inside the memory_handle */
433 if ((unsigned)overlap
> data_size
) {
434 /* Correct the position and real delta to prevent the struct from
435 * wrapping, this guarantees an aligned delta, I think */
436 correction
= overlap
- data_size
;
437 } else if (!can_wrap
) {
438 /* Otherwise the overlap falls in the data area and must all be
439 * backed out. This may become conditional if ever we move
440 * data that is allowed to wrap (ie audio) */
441 correction
= overlap
;
442 /* Align correction to four bytes, up */
443 correction
= (correction
+3) & ~3;
446 if (final_delta
< correction
+ sizeof(struct memory_handle
)) {
447 /* Delta cannot end up less than the size of the struct */
448 mutex_unlock(&llist_mod_mutex
);
449 mutex_unlock(&llist_mutex
);
453 newpos
-= correction
;
454 overlap
-= correction
;/* Used below to know how to split the data */
455 final_delta
-= correction
;
459 dest
= (struct memory_handle
*)(&buffer
[newpos
]);
461 if (src
== first_handle
) {
465 struct memory_handle
*m
= first_handle
;
466 while (m
&& m
->next
!= src
) {
469 if (m
&& m
->next
== src
) {
472 mutex_unlock(&llist_mod_mutex
);
473 mutex_unlock(&llist_mutex
);
479 /* Update the cache to prevent it from keeping the old location of h */
480 if (src
== cached_handle
)
481 cached_handle
= dest
;
483 /* the cur_handle pointer might need updating */
484 if (src
== cur_handle
)
488 size_t first_part
= size_to_move
- overlap
;
489 memmove(dest
, src
, first_part
);
490 memmove(buffer
, (const char *)src
+ first_part
, overlap
);
492 memmove(dest
, src
, size_to_move
);
495 /* Update the caller with the new location of h and the distance moved */
497 *delta
= final_delta
;
498 mutex_unlock(&llist_mod_mutex
);
499 mutex_unlock(&llist_mutex
);
505 BUFFER SPACE MANAGEMENT
506 =======================
508 update_data_counters: Updates the values in data_counters
509 buffer_is_low : Returns true if the amount of useful data in the buffer is low
510 buffer_handle : Buffer data for a handle
511 reset_handle : Reset write position and data buffer of a handle to its offset
512 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
513 shrink_handle : Free buffer space by moving a handle
514 fill_buffer : Call buffer_handle for all handles that have data to buffer
516 These functions are used by the buffering thread to manage buffer space.
519 static void update_data_counters(void)
521 struct memory_handle
*m
= find_handle(base_handle_id
);
522 bool is_useful
= m
==NULL
;
526 size_t remaining
= 0;
529 mutex_lock(&llist_mutex
);
533 buffered
+= m
->available
;
534 wasted
+= RINGBUF_SUB(m
->ridx
, m
->data
);
535 remaining
+= m
->filerem
;
537 if (m
->id
== base_handle_id
)
541 useful
+= RINGBUF_SUB(m
->widx
, m
->ridx
);
546 mutex_unlock(&llist_mutex
);
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
< (conf_watermark
/ 2);
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 if (h
->type
== TYPE_ID3
)
595 if (!get_metadata((struct mp3entry
*)(buffer
+ h
->data
), h
->fd
, h
->path
))
597 /* metadata parsing failed: clear the buffer. */
598 memset(buffer
+ h
->data
, 0, sizeof(struct mp3entry
));
603 h
->available
= sizeof(struct mp3entry
);
604 h
->widx
+= sizeof(struct mp3entry
);
605 send_event(BUFFER_EVENT_FINISHED
, &h
->id
);
609 while (h
->filerem
> 0)
611 /* max amount to copy */
612 size_t copy_n
= MIN( MIN(h
->filerem
, BUFFERING_DEFAULT_FILECHUNK
),
613 buffer_len
- h
->widx
);
615 /* stop copying if it would overwrite the reading position */
616 if (RINGBUF_ADD_CROSS(h
->widx
, copy_n
, buf_ridx
) >= 0)
619 /* This would read into the next handle, this is broken */
620 if (h
->next
&& RINGBUF_ADD_CROSS(h
->widx
, copy_n
,
621 (unsigned)((void *)h
->next
- (void *)buffer
)) > 0) {
622 /* Try to recover by truncating this file */
623 copy_n
= RINGBUF_ADD_CROSS(h
->widx
, copy_n
,
624 (unsigned)((void *)h
->next
- (void *)buffer
));
625 h
->filerem
-= copy_n
;
626 h
->filesize
-= copy_n
;
627 logf("buf alloc short %ld", (long)copy_n
);
634 /* rc is the actual amount read */
635 int rc
= read(h
->fd
, &buffer
[h
->widx
], copy_n
);
639 /* Some kind of filesystem error, maybe recoverable if not codec */
640 if (h
->type
== TYPE_CODEC
) {
641 logf("Partial codec");
645 DEBUGF("File ended %ld bytes early\n", (long)h
->filerem
);
646 h
->filesize
-= h
->filerem
;
652 h
->widx
= RINGBUF_ADD(h
->widx
, rc
);
658 /* If this is a large file, see if we need to break or give the codec
660 if (h
->type
== TYPE_PACKET_AUDIO
&&
661 pcmbuf_is_lowdata() && !buffer_is_low())
670 if (!queue_empty(&buffering_queue
))
674 if (h
->filerem
== 0) {
675 /* finished buffering the file */
678 send_event(BUFFER_EVENT_FINISHED
, &h
->id
);
684 /* Reset writing position and data buffer of a handle to its current offset.
685 Use this after having set the new offset to use. */
686 static void reset_handle(int handle_id
)
688 logf("reset_handle(%d)", handle_id
);
690 struct memory_handle
*h
= find_handle(handle_id
);
694 h
->ridx
= h
->widx
= h
->data
;
698 h
->filerem
= h
->filesize
- h
->offset
;
701 lseek(h
->fd
, h
->offset
, SEEK_SET
);
705 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
706 static void rebuffer_handle(int handle_id
, size_t newpos
)
708 struct memory_handle
*h
= find_handle(handle_id
);
712 /* When seeking foward off of the buffer, if it is a short seek don't
713 rebuffer the whole track, just read enough to satisfy */
714 if (newpos
> h
->offset
&& newpos
- h
->offset
< BUFFERING_DEFAULT_FILECHUNK
)
716 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id
);
717 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, handle_id
);
718 h
->ridx
= h
->data
+ newpos
;
724 /* Reset the handle to its new offset */
725 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id
);
726 queue_send(&buffering_queue
, Q_RESET_HANDLE
, handle_id
);
728 size_t next
= (unsigned)((void *)h
->next
- (void *)buffer
);
729 if (RINGBUF_SUB(next
, h
->data
) < h
->filesize
- newpos
)
731 /* There isn't enough space to rebuffer all of the track from its new
732 offset, so we ask the user to free some */
733 DEBUGF("rebuffer_handle: space is needed\n");
734 send_event(BUFFER_EVENT_REBUFFER
, &handle_id
);
737 /* Now we ask for a rebuffer */
738 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id
);
739 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, handle_id
);
742 static bool close_handle(int handle_id
)
744 struct memory_handle
*h
= find_handle(handle_id
);
746 /* If the handle is not found, it is closed */
755 /* rm_handle returns true unless the handle somehow persists after exit */
759 /* Free buffer space by moving the handle struct right before the useful
760 part of its data buffer or by moving all the data. */
761 static void shrink_handle(struct memory_handle
*h
)
768 if (h
->next
&& h
->filerem
== 0 &&
769 (h
->type
== TYPE_ID3
|| h
->type
== TYPE_CUESHEET
||
770 h
->type
== TYPE_BITMAP
|| h
->type
== TYPE_CODEC
||
771 h
->type
== TYPE_ATOMIC_AUDIO
))
773 /* metadata handle: we can move all of it */
774 size_t handle_distance
=
775 RINGBUF_SUB((unsigned)((void *)h
->next
- (void*)buffer
), h
->data
);
776 delta
= handle_distance
- h
->available
;
778 /* The value of delta might change for alignment reasons */
779 if (!move_handle(&h
, &delta
, h
->available
, h
->type
==TYPE_CODEC
))
782 size_t olddata
= h
->data
;
783 h
->data
= RINGBUF_ADD(h
->data
, delta
);
784 h
->ridx
= RINGBUF_ADD(h
->ridx
, delta
);
785 h
->widx
= RINGBUF_ADD(h
->widx
, delta
);
787 if (h
->type
== TYPE_ID3
&& h
->filesize
== sizeof(struct mp3entry
)) {
788 /* when moving an mp3entry we need to readjust its pointers. */
789 adjust_mp3entry((struct mp3entry
*)&buffer
[h
->data
],
790 (void *)&buffer
[h
->data
],
791 (const void *)&buffer
[olddata
]);
792 } else if (h
->type
== TYPE_BITMAP
) {
793 /* adjust the bitmap's pointer */
794 struct bitmap
*bmp
= (struct bitmap
*)&buffer
[h
->data
];
795 bmp
->data
= &buffer
[h
->data
+ sizeof(struct bitmap
)];
800 /* only move the handle struct */
801 delta
= RINGBUF_SUB(h
->ridx
, h
->data
);
802 if (!move_handle(&h
, &delta
, 0, true))
805 h
->data
= RINGBUF_ADD(h
->data
, delta
);
806 h
->available
-= delta
;
811 /* Fill the buffer by buffering as much data as possible for handles that still
812 have data left to buffer
813 Return whether or not to continue filling after this */
814 static bool fill_buffer(void)
816 logf("fill_buffer()");
817 struct memory_handle
*m
;
818 shrink_handle(first_handle
);
820 while (queue_empty(&buffering_queue
) && m
) {
821 if (m
->filerem
> 0) {
822 if (!buffer_handle(m
->id
)) {
835 /* only spin the disk down if the filling wasn't interrupted by an
836 event arriving in the queue. */
843 /* Given a file descriptor to a bitmap file, write the bitmap data to the
844 buffer, with a struct bitmap and the actual data immediately following.
845 Return value is the total size (struct + data). */
846 static int load_image(int fd
, const char *path
)
849 struct bitmap
*bmp
= (struct bitmap
*)&buffer
[buf_widx
];
850 /* FIXME: alignment may be needed for the data buffer. */
851 bmp
->data
= &buffer
[buf_widx
+ sizeof(struct bitmap
)];
853 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
854 bmp
->maskdata
= NULL
;
857 int free
= (int)MIN(buffer_len
- BUF_USED
, buffer_len
- buf_widx
)
858 - sizeof(struct bitmap
);
860 get_albumart_size(bmp
);
863 int pathlen
= strlen(path
);
864 if (strcmp(path
+ pathlen
- 4, ".bmp"))
865 rc
= read_jpeg_fd(fd
, bmp
, free
, FORMAT_NATIVE
|FORMAT_DITHER
|
866 FORMAT_RESIZE
|FORMAT_KEEP_ASPECT
, NULL
);
869 rc
= read_bmp_fd(fd
, bmp
, free
, FORMAT_NATIVE
|FORMAT_DITHER
|
870 FORMAT_RESIZE
|FORMAT_KEEP_ASPECT
, NULL
);
871 return rc
+ (rc
> 0 ? sizeof(struct bitmap
) : 0);
877 MAIN BUFFERING API CALLS
878 ========================
880 bufopen : Request the opening of a new handle for a file
881 bufalloc : Open a new handle for data other than a file.
882 bufclose : Close an open handle
883 bufseek : Set the read pointer in a handle
884 bufadvance : Move the read pointer in a handle
885 bufread : Copy data from a handle into a given buffer
886 bufgetdata : Give a pointer to the handle's data
888 These functions are exported, to allow interaction with the buffer.
889 They take care of the content of the structs, and rely on the linked list
890 management functions for all the actual handle management work.
894 /* Reserve space in the buffer for a file.
895 filename: name of the file to open
896 offset: offset at which to start buffering the file, useful when the first
897 (offset-1) bytes of the file aren't needed.
898 return value: <0 if the file cannot be opened, or one file already
899 queued to be opened, otherwise the handle for the file in the buffer
901 int bufopen(const char *file
, size_t offset
, enum data_type type
)
903 if (type
== TYPE_ID3
)
905 /* ID3 case: allocate space, init the handle and return. */
907 struct memory_handle
*h
= add_handle(sizeof(struct mp3entry
), false, true);
909 return ERR_BUFFER_FULL
;
912 h
->filesize
= sizeof(struct mp3entry
);
913 h
->filerem
= sizeof(struct mp3entry
);
920 strncpy(h
->path
, file
, MAX_PATH
);
922 buf_widx
+= sizeof(struct mp3entry
); /* safe because the handle
925 /* Inform the buffering thread that we added a handle */
926 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
927 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
932 /* Other cases: there is a little more work. */
934 int fd
= open(file
, O_RDONLY
);
936 return ERR_FILE_ERROR
;
938 size_t size
= filesize(fd
);
939 bool can_wrap
= type
==TYPE_PACKET_AUDIO
|| type
==TYPE_CODEC
;
941 size_t adjusted_offset
= offset
;
942 if (adjusted_offset
> size
)
945 struct memory_handle
*h
= add_handle(size
-adjusted_offset
, can_wrap
, false);
948 DEBUGF("bufopen: failed to add handle\n");
950 return ERR_BUFFER_FULL
;
953 strncpy(h
->path
, file
, MAX_PATH
);
954 h
->offset
= adjusted_offset
;
963 if (type
== TYPE_BITMAP
)
965 /* Bitmap file: we load the data instead of the file */
967 mutex_lock(&llist_mod_mutex
); /* Lock because load_bitmap yields */
968 rc
= load_image(fd
, file
);
969 mutex_unlock(&llist_mod_mutex
);
974 return ERR_FILE_ERROR
;
979 h
->widx
= buf_widx
+ rc
; /* safe because the data doesn't wrap */
980 buf_widx
+= rc
; /* safe too */
985 h
->filerem
= size
- adjusted_offset
;
991 if (type
== TYPE_CUESHEET
) {
993 /* Immediately start buffering those */
994 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h
->id
);
995 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, h
->id
);
997 /* Other types will get buffered in the course of normal operations */
1001 /* Inform the buffering thread that we added a handle */
1002 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
1003 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
1006 logf("bufopen: new hdl %d", h
->id
);
1010 /* Open a new handle from data that needs to be copied from memory.
1011 src is the source buffer from which to copy data. It can be NULL to simply
1012 reserve buffer space.
1013 size is the requested size. The call will only be successful if the
1014 requested amount of data can entirely fit in the buffer without wrapping.
1015 Return value is the handle id for success or <0 for failure.
1017 int bufalloc(const void *src
, size_t size
, enum data_type type
)
1019 struct memory_handle
*h
= add_handle(size
, false, true);
1022 return ERR_BUFFER_FULL
;
1025 if (type
== TYPE_ID3
&& size
== sizeof(struct mp3entry
)) {
1026 /* specially take care of struct mp3entry */
1027 copy_mp3entry((struct mp3entry
*)&buffer
[buf_widx
],
1028 (const struct mp3entry
*)src
);
1030 memcpy(&buffer
[buf_widx
], src
, size
);
1040 h
->widx
= buf_widx
+ size
; /* this is safe because the data doesn't wrap */
1042 h
->available
= size
;
1045 buf_widx
+= size
; /* safe too */
1047 logf("bufalloc: new hdl %d", h
->id
);
1051 /* Close the handle. Return true for success and false for failure */
1052 bool bufclose(int handle_id
)
1054 logf("bufclose(%d)", handle_id
);
1056 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id
);
1057 return queue_send(&buffering_queue
, Q_CLOSE_HANDLE
, handle_id
);
1060 /* Set reading index in handle (relatively to the start of the file).
1061 Access before the available data will trigger a rebuffer.
1062 Return 0 for success and < 0 for failure:
1063 -1 if the handle wasn't found
1064 -2 if the new requested position was beyond the end of the file
1066 int bufseek(int handle_id
, size_t newpos
)
1068 struct memory_handle
*h
= find_handle(handle_id
);
1070 return ERR_HANDLE_NOT_FOUND
;
1072 if (newpos
> h
->filesize
) {
1073 /* access beyond the end of the file */
1074 return ERR_INVALID_VALUE
;
1076 else if (newpos
< h
->offset
|| h
->offset
+ h
->available
< newpos
) {
1077 /* access before or after buffered data. A rebuffer is needed. */
1078 rebuffer_handle(handle_id
, newpos
);
1081 h
->ridx
= RINGBUF_ADD(h
->data
, newpos
- h
->offset
);
1086 /* Advance the reading index in a handle (relatively to its current position).
1087 Return 0 for success and < 0 for failure */
1088 int bufadvance(int handle_id
, off_t offset
)
1090 const struct memory_handle
*h
= find_handle(handle_id
);
1092 return ERR_HANDLE_NOT_FOUND
;
1094 size_t newpos
= h
->offset
+ RINGBUF_SUB(h
->ridx
, h
->data
) + offset
;
1095 return bufseek(handle_id
, newpos
);
1098 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1099 * actual amount of data available for reading. This function explicitly
1100 * does not check the validity of the input handle. It does do range checks
1101 * on size and returns a valid (and explicit) amount of data for reading */
1102 static struct memory_handle
*prep_bufdata(int handle_id
, size_t *size
,
1103 bool guardbuf_limit
)
1105 struct memory_handle
*h
= find_handle(handle_id
);
1109 size_t avail
= RINGBUF_SUB(h
->widx
, h
->ridx
);
1111 if (avail
== 0 && h
->filerem
== 0)
1113 /* File is finished reading */
1118 if (*size
== 0 || *size
> avail
+ h
->filerem
)
1119 *size
= avail
+ h
->filerem
;
1121 if (guardbuf_limit
&& h
->type
== TYPE_PACKET_AUDIO
&& *size
> GUARD_BUFSIZE
)
1123 logf("data request > guardbuf");
1124 /* If more than the size of the guardbuf is requested and this is a
1125 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1126 *size
= MIN(*size
, buffer_len
- h
->ridx
+ GUARD_BUFSIZE
);
1127 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1130 if (h
->filerem
> 0 && avail
< *size
)
1132 /* Data isn't ready. Request buffering */
1133 buf_request_buffer_handle(handle_id
);
1134 /* Wait for the data to be ready */
1138 /* it is not safe for a non-buffering thread to sleep while
1139 * holding a handle */
1140 h
= find_handle(handle_id
);
1143 avail
= RINGBUF_SUB(h
->widx
, h
->ridx
);
1145 while (h
->filerem
> 0 && avail
< *size
);
1148 *size
= MIN(*size
,avail
);
1152 /* Copy data from the given handle to the dest buffer.
1153 Return the number of bytes copied or < 0 for failure (handle not found).
1154 The caller is blocked until the requested amount of data is available.
1156 ssize_t
bufread(int handle_id
, size_t size
, void *dest
)
1158 const struct memory_handle
*h
;
1159 size_t adjusted_size
= size
;
1161 h
= prep_bufdata(handle_id
, &adjusted_size
, false);
1163 return ERR_HANDLE_NOT_FOUND
;
1165 if (h
->ridx
+ adjusted_size
> buffer_len
)
1167 /* the data wraps around the end of the buffer */
1168 size_t read
= buffer_len
- h
->ridx
;
1169 memcpy(dest
, &buffer
[h
->ridx
], read
);
1170 memcpy(dest
+read
, buffer
, adjusted_size
- read
);
1174 memcpy(dest
, &buffer
[h
->ridx
], adjusted_size
);
1177 return adjusted_size
;
1180 /* Update the "data" pointer to make the handle's data available to the caller.
1181 Return the length of the available linear data or < 0 for failure (handle
1183 The caller is blocked until the requested amount of data is available.
1184 size is the amount of linear data requested. it can be 0 to get as
1186 The guard buffer may be used to provide the requested size. This means it's
1187 unsafe to request more than the size of the guard buffer.
1189 ssize_t
bufgetdata(int handle_id
, size_t size
, void **data
)
1191 const struct memory_handle
*h
;
1192 size_t adjusted_size
= size
;
1194 h
= prep_bufdata(handle_id
, &adjusted_size
, true);
1196 return ERR_HANDLE_NOT_FOUND
;
1198 if (h
->ridx
+ adjusted_size
> buffer_len
)
1200 /* the data wraps around the end of the buffer :
1201 use the guard buffer to provide the requested amount of data. */
1202 size_t copy_n
= h
->ridx
+ adjusted_size
- buffer_len
;
1203 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1204 so copy_n <= GUARD_BUFSIZE */
1205 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1209 *data
= &buffer
[h
->ridx
];
1211 return adjusted_size
;
1214 ssize_t
bufgettail(int handle_id
, size_t size
, void **data
)
1218 const struct memory_handle
*h
;
1220 h
= find_handle(handle_id
);
1223 return ERR_HANDLE_NOT_FOUND
;
1226 return ERR_HANDLE_NOT_DONE
;
1228 /* We don't support tail requests of > guardbuf_size, for simplicity */
1229 if (size
> GUARD_BUFSIZE
)
1230 return ERR_INVALID_VALUE
;
1232 tidx
= RINGBUF_SUB(h
->widx
, size
);
1234 if (tidx
+ size
> buffer_len
)
1236 size_t copy_n
= tidx
+ size
- buffer_len
;
1237 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1240 *data
= &buffer
[tidx
];
1244 ssize_t
bufcuttail(int handle_id
, size_t size
)
1246 struct memory_handle
*h
;
1247 size_t adjusted_size
= size
;
1249 h
= find_handle(handle_id
);
1252 return ERR_HANDLE_NOT_FOUND
;
1255 return ERR_HANDLE_NOT_DONE
;
1257 if (h
->available
< adjusted_size
)
1258 adjusted_size
= h
->available
;
1260 h
->available
-= adjusted_size
;
1261 h
->filesize
-= adjusted_size
;
1262 h
->widx
= RINGBUF_SUB(h
->widx
, adjusted_size
);
1263 if (h
== cur_handle
)
1266 return adjusted_size
;
1271 SECONDARY EXPORTED FUNCTIONS
1272 ============================
1276 buf_request_buffer_handle
1279 register_buffering_callback
1280 unregister_buffering_callback
1282 These functions are exported, to allow interaction with the buffer.
1283 They take care of the content of the structs, and rely on the linked list
1284 management functions for all the actual handle management work.
1287 /* Get a handle offset from a pointer */
1288 ssize_t
buf_get_offset(int handle_id
, void *ptr
)
1290 const struct memory_handle
*h
= find_handle(handle_id
);
1292 return ERR_HANDLE_NOT_FOUND
;
1294 return (size_t)ptr
- (size_t)&buffer
[h
->ridx
];
1297 ssize_t
buf_handle_offset(int handle_id
)
1299 const struct memory_handle
*h
= find_handle(handle_id
);
1301 return ERR_HANDLE_NOT_FOUND
;
1305 void buf_request_buffer_handle(int handle_id
)
1307 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id
);
1308 queue_send(&buffering_queue
, Q_START_FILL
, handle_id
);
1311 void buf_set_base_handle(int handle_id
)
1313 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id
);
1314 queue_post(&buffering_queue
, Q_BASE_HANDLE
, handle_id
);
1317 /* Return the amount of buffer space used */
1318 size_t buf_used(void)
1323 void buf_set_watermark(size_t bytes
)
1325 conf_watermark
= bytes
;
1328 static void shrink_buffer_inner(struct memory_handle
*h
)
1333 shrink_buffer_inner(h
->next
);
1338 static void shrink_buffer(void)
1340 logf("shrink_buffer()");
1341 shrink_buffer_inner(first_handle
);
1344 void buffering_thread(void)
1346 bool filling
= false;
1347 struct queue_event ev
;
1355 queue_wait_w_tmo(&buffering_queue
, &ev
, filling
? 5 : HZ
/2);
1360 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev
.data
);
1361 /* Call buffer callbacks here because this is one of two ways
1362 * to begin a full buffer fill */
1363 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1365 queue_reply(&buffering_queue
, 1);
1366 filling
|= buffer_handle((int)ev
.data
);
1369 case Q_BUFFER_HANDLE
:
1370 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev
.data
);
1371 queue_reply(&buffering_queue
, 1);
1372 buffer_handle((int)ev
.data
);
1375 case Q_RESET_HANDLE
:
1376 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev
.data
);
1377 queue_reply(&buffering_queue
, 1);
1378 reset_handle((int)ev
.data
);
1381 case Q_CLOSE_HANDLE
:
1382 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev
.data
);
1383 queue_reply(&buffering_queue
, close_handle((int)ev
.data
));
1386 case Q_HANDLE_ADDED
:
1387 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev
.data
);
1388 /* A handle was added: the disk is spinning, so we can fill */
1393 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev
.data
);
1394 base_handle_id
= (int)ev
.data
;
1398 case SYS_USB_CONNECTED
:
1399 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1400 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
1401 usb_wait_for_disconnect(&buffering_queue
);
1406 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1410 update_data_counters();
1412 /* If the buffer is low, call the callbacks to get new data */
1413 if (num_handles
> 0 && data_counters
.useful
<= conf_watermark
)
1414 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1417 /* TODO: This needs to be fixed to use the idle callback, disable it
1418 * for simplicity until its done right */
1420 /* If the disk is spinning, take advantage by filling the buffer */
1421 else if (storage_disk_is_active() && queue_empty(&buffering_queue
))
1423 if (num_handles
> 0 && data_counters
.useful
<= high_watermark
)
1424 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1426 if (data_counters
.remaining
> 0 && BUF_USED
<= high_watermark
)
1428 /* This is a new fill, shrink the buffer up first */
1431 filling
= fill_buffer();
1432 update_data_counters();
1438 if (queue_empty(&buffering_queue
)) {
1440 if (data_counters
.remaining
> 0 && BUF_USED
< buffer_len
)
1441 filling
= fill_buffer();
1442 else if (data_counters
.remaining
== 0)
1445 else if (ev
.id
== SYS_TIMEOUT
)
1447 if (data_counters
.remaining
> 0 &&
1448 data_counters
.useful
<= conf_watermark
) {
1450 filling
= fill_buffer();
1457 void buffering_init(void)
1459 mutex_init(&llist_mutex
);
1460 mutex_init(&llist_mod_mutex
);
1461 #ifdef HAVE_PRIORITY_SCHEDULING
1462 /* This behavior not safe atm */
1463 mutex_set_preempt(&llist_mutex
, false);
1464 mutex_set_preempt(&llist_mod_mutex
, false);
1467 conf_watermark
= BUFFERING_DEFAULT_WATERMARK
;
1469 queue_init(&buffering_queue
, true);
1470 buffering_thread_id
= create_thread( buffering_thread
, buffering_stack
,
1471 sizeof(buffering_stack
), CREATE_THREAD_FROZEN
,
1472 buffering_thread_name
IF_PRIO(, PRIORITY_BUFFERING
)
1475 queue_enable_queue_send(&buffering_queue
, &buffering_queue_sender_list
,
1476 buffering_thread_id
);
1479 /* Initialise the buffering subsystem */
1480 bool buffering_reset(char *buf
, size_t buflen
)
1482 if (!buf
|| !buflen
)
1486 buffer_len
= buflen
;
1487 guard_buffer
= buf
+ buflen
;
1492 first_handle
= NULL
;
1494 cached_handle
= NULL
;
1496 base_handle_id
= -1;
1498 /* Set the high watermark as 75% full...or 25% empty :) */
1500 high_watermark
= 3*buflen
/ 4;
1503 thread_thaw(buffering_thread_id
);
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
;
1516 dbgdata
->watermark
= conf_watermark
;