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"
51 #include "appevents.h"
55 #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 /* assert(sizeof(struct memory_handle)%4==0) */
95 struct memory_handle
{
96 int id
; /* A unique ID for the handle */
97 enum data_type type
; /* Type of data buffered with this handle */
98 char path
[MAX_PATH
]; /* Path if data originated in a file */
99 int fd
; /* File descriptor to path (-1 if closed) */
100 size_t start
; /* Start index of the handle's data buffer,
101 for use by reset_handle. */
102 size_t data
; /* Start index of the handle's data */
103 volatile size_t ridx
; /* Read pointer, relative to the main buffer */
104 size_t widx
; /* Write pointer */
105 size_t filesize
; /* File total length */
106 size_t filerem
; /* Remaining bytes of file NOT in buffer */
107 volatile size_t available
; /* Available bytes to read from buffer */
108 size_t offset
; /* Offset at which we started reading the file */
109 struct memory_handle
*next
;
111 /* invariant: filesize == offset + available + filerem */
114 static char *guard_buffer
;
116 static size_t buffer_len
;
118 static volatile size_t buf_widx
; /* current writing position */
119 static volatile size_t buf_ridx
; /* current reading position */
120 /* buf_*idx are values relative to the buffer, not real pointers. */
123 static size_t conf_watermark
= 0; /* Level to trigger filebuf fill */
125 static size_t high_watermark
= 0; /* High watermark for rebuffer */
128 /* current memory handle in the linked list. NULL when the list is empty. */
129 static struct memory_handle
*cur_handle
;
130 /* first memory handle in the linked list. NULL when the list is empty. */
131 static struct memory_handle
*first_handle
;
133 static int num_handles
; /* number of handles in the list */
135 static int base_handle_id
;
137 static struct mutex llist_mutex
;
138 static struct mutex llist_mod_mutex
;
140 /* Handle cache (makes find_handle faster).
141 This is global so that move_handle and rm_handle can invalidate it. */
142 static struct memory_handle
*cached_handle
= NULL
;
145 size_t remaining
; /* Amount of data needing to be buffered */
146 size_t wasted
; /* Amount of space available for freeing */
147 size_t buffered
; /* Amount of data currently in the buffer */
148 size_t useful
; /* Amount of data still useful to the user */
152 /* Messages available to communicate with the buffering thread */
154 Q_BUFFER_HANDLE
= 1, /* Request buffering of a handle, this should not be
155 used in a low buffer situation. */
156 Q_RESET_HANDLE
, /* (internal) Request resetting of a handle to its
157 offset (the offset has to be set beforehand) */
158 Q_CLOSE_HANDLE
, /* Request closing a handle */
159 Q_BASE_HANDLE
, /* Set the reference handle for buf_useful_data */
162 Q_START_FILL
, /* Request that the buffering thread initiate a buffer
163 fill at its earliest convenience */
164 Q_HANDLE_ADDED
, /* Inform the buffering thread that a handle was added,
165 (which means the disk is spinning) */
168 /* Buffering thread */
169 static void buffering_thread(void);
170 static long buffering_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)];
171 static const char buffering_thread_name
[] = "buffering";
172 static unsigned int buffering_thread_id
= 0;
173 static struct event_queue buffering_queue
;
174 static struct queue_sender_list buffering_queue_sender_list
;
178 /* Ring buffer helper functions */
180 static inline uintptr_t ringbuf_offset(const void *ptr
)
182 return (uintptr_t)(ptr
- (void*)buffer
);
185 /* Buffer pointer (p) plus value (v), wrapped if necessary */
186 static inline uintptr_t ringbuf_add(uintptr_t p
, size_t v
)
188 uintptr_t res
= p
+ v
;
189 if (res
>= buffer_len
)
190 res
-= buffer_len
; /* wrap if necssary */
195 /* Buffer pointer (p) minus value (v), wrapped if necessary */
196 static inline uintptr_t ringbuf_sub(uintptr_t p
, size_t v
)
200 res
+= buffer_len
; /* wrap */
206 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
207 static inline ssize_t
ringbuf_add_cross(uintptr_t p1
, size_t v
, uintptr_t p2
)
209 ssize_t res
= p1
+ v
- p2
;
210 if (p1
>= p2
) /* wrap if necessary */
216 /* Bytes available in the buffer */
217 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
220 LINKED LIST MANAGEMENT
221 ======================
223 add_handle : Add a handle to the list
224 rm_handle : Remove a handle from the list
225 find_handle : Get a handle pointer from an ID
226 move_handle : Move a handle in the buffer (with or without its data)
228 These functions only handle the linked list structure. They don't touch the
229 contents of the struct memory_handle headers. They also change the buf_*idx
230 pointers when necessary and manage the handle IDs.
232 The first and current (== last) handle are kept track of.
233 A new handle is added at buf_widx and becomes the current one.
234 buf_widx always points to the current writing position for the current handle
235 buf_ridx always points to the location of the first handle.
236 buf_ridx == buf_widx means the buffer is empty.
240 /* Add a new handle to the linked list and return it. It will have become the
242 data_size must contain the size of what will be in the handle.
243 can_wrap tells us whether this type of data may wrap on buffer
244 alloc_all tells us if we must immediately be able to allocate data_size
245 returns a valid memory handle if all conditions for allocation are met.
246 NULL if there memory_handle itself cannot be allocated or if the
247 data_size cannot be allocated and alloc_all is set. This function's
248 only potential side effect is to allocate space for the cur_handle
251 static struct memory_handle
*add_handle(size_t data_size
, bool can_wrap
,
254 /* gives each handle a unique id */
255 static int cur_handle_id
= 0;
261 if (num_handles
>= BUF_MAX_HANDLES
)
264 mutex_lock(&llist_mutex
);
265 mutex_lock(&llist_mod_mutex
);
267 if (cur_handle
&& cur_handle
->filerem
> 0) {
268 /* the current handle hasn't finished buffering. We can only add
269 a new one if there is already enough free space to finish
271 size_t req
= cur_handle
->filerem
+ sizeof(struct memory_handle
);
272 if (ringbuf_add_cross(cur_handle
->widx
, req
, buf_ridx
) >= 0) {
273 /* Not enough space */
274 mutex_unlock(&llist_mod_mutex
);
275 mutex_unlock(&llist_mutex
);
278 /* Allocate the remainder of the space for the current handle */
279 buf_widx
= ringbuf_add(cur_handle
->widx
, cur_handle
->filerem
);
283 /* align to 4 bytes up */
284 new_widx
= ringbuf_add(buf_widx
, 3) & ~3;
286 len
= data_size
+ sizeof(struct memory_handle
);
288 /* First, will the handle wrap? */
289 /* If the handle would wrap, move to the beginning of the buffer,
290 * or if the data must not but would wrap, move it to the beginning */
291 if( (new_widx
+ sizeof(struct memory_handle
) > buffer_len
) ||
292 (!can_wrap
&& (new_widx
+ len
> buffer_len
)) ) {
296 /* How far we shifted buf_widx to align things, must be < buffer_len */
297 shift
= ringbuf_sub(new_widx
, buf_widx
);
299 /* How much space are we short in the actual ring buffer? */
300 overlap
= ringbuf_add_cross(buf_widx
, shift
+ len
, buf_ridx
);
301 if (overlap
>= 0 && (alloc_all
|| (unsigned)overlap
> data_size
)) {
302 /* Not enough space for required allocations */
303 mutex_unlock(&llist_mod_mutex
);
304 mutex_unlock(&llist_mutex
);
308 /* There is enough space for the required data, advance the buf_widx and
309 * initialize the struct */
312 struct memory_handle
*new_handle
=
313 (struct memory_handle
*)(&buffer
[buf_widx
]);
315 /* only advance the buffer write index of the size of the struct */
316 buf_widx
= ringbuf_add(buf_widx
, sizeof(struct memory_handle
));
318 new_handle
->id
= cur_handle_id
;
319 /* Wrap signed int is safe and 0 doesn't happen */
320 cur_handle_id
= (cur_handle_id
+ 1) & BUF_HANDLE_MASK
;
321 new_handle
->next
= NULL
;
325 /* the new handle is the first one */
326 first_handle
= new_handle
;
329 cur_handle
->next
= new_handle
;
331 cur_handle
= new_handle
;
333 mutex_unlock(&llist_mod_mutex
);
334 mutex_unlock(&llist_mutex
);
338 /* Delete a given memory handle from the linked list
339 and return true for success. Nothing is actually erased from memory. */
340 static bool rm_handle(const struct memory_handle
*h
)
345 mutex_lock(&llist_mutex
);
346 mutex_lock(&llist_mod_mutex
);
348 if (h
== first_handle
) {
349 first_handle
= h
->next
;
350 if (h
== cur_handle
) {
351 /* h was the first and last handle: the buffer is now empty */
353 buf_ridx
= buf_widx
= 0;
355 /* update buf_ridx to point to the new first handle */
356 buf_ridx
= (size_t)ringbuf_offset(first_handle
);
359 struct memory_handle
*m
= first_handle
;
360 /* Find the previous handle */
361 while (m
&& m
->next
!= h
) {
364 if (m
&& m
->next
== h
) {
366 if (h
== cur_handle
) {
368 buf_widx
= cur_handle
->widx
;
371 mutex_unlock(&llist_mod_mutex
);
372 mutex_unlock(&llist_mutex
);
377 /* Invalidate the cache to prevent it from keeping the old location of h */
378 if (h
== cached_handle
)
379 cached_handle
= NULL
;
383 mutex_unlock(&llist_mod_mutex
);
384 mutex_unlock(&llist_mutex
);
388 /* Return a pointer to the memory handle of given ID.
389 NULL if the handle wasn't found */
390 static struct memory_handle
*find_handle(int handle_id
)
395 mutex_lock(&llist_mutex
);
397 /* simple caching because most of the time the requested handle
398 will either be the same as the last, or the one after the last */
401 if (cached_handle
->id
== handle_id
) {
402 mutex_unlock(&llist_mutex
);
403 return cached_handle
;
404 } else if (cached_handle
->next
&&
405 (cached_handle
->next
->id
== handle_id
)) {
406 cached_handle
= cached_handle
->next
;
407 mutex_unlock(&llist_mutex
);
408 return cached_handle
;
412 struct memory_handle
*m
= first_handle
;
413 while (m
&& m
->id
!= handle_id
) {
416 /* This condition can only be reached with !m or m->id == handle_id */
420 mutex_unlock(&llist_mutex
);
424 /* Move a memory handle and data_size of its data delta bytes along the buffer.
425 delta maximum bytes available to move the handle. If the move is performed
426 it is set to the actual distance moved.
427 data_size is the amount of data to move along with the struct.
428 returns a valid memory_handle if the move is successful
429 NULL if the handle is NULL, the move would be less than the size of
430 a memory_handle after correcting for wraps or if the handle is not
431 found in the linked list for adjustment. This function has no side
432 effects if NULL is returned. */
433 static bool move_handle(struct memory_handle
**h
, size_t *delta
,
434 size_t data_size
, bool can_wrap
)
436 struct memory_handle
*dest
;
437 const struct memory_handle
*src
;
442 size_t final_delta
= *delta
, size_to_move
, n
;
443 uintptr_t oldpos
, newpos
;
444 intptr_t overlap
, overlap_old
;
446 if (h
== NULL
|| (src
= *h
) == NULL
)
449 size_to_move
= sizeof(struct memory_handle
) + data_size
;
451 /* Align to four bytes, down */
453 if (final_delta
< sizeof(struct memory_handle
)) {
454 /* It's not legal to move less than the size of the struct */
458 mutex_lock(&llist_mutex
);
459 mutex_lock(&llist_mod_mutex
);
461 oldpos
= ringbuf_offset(src
);
462 newpos
= ringbuf_add(oldpos
, final_delta
);
463 overlap
= ringbuf_add_cross(newpos
, size_to_move
, buffer_len
- 1);
464 overlap_old
= ringbuf_add_cross(oldpos
, size_to_move
, buffer_len
-1);
467 /* Some part of the struct + data would wrap, maybe ok */
468 size_t correction
= 0;
469 /* If the overlap lands inside the memory_handle */
471 /* Otherwise the overlap falls in the data area and must all be
472 * backed out. This may become conditional if ever we move
473 * data that is allowed to wrap (ie audio) */
474 correction
= overlap
;
475 } else if ((uintptr_t)overlap
> data_size
) {
476 /* Correct the position and real delta to prevent the struct from
477 * wrapping, this guarantees an aligned delta, I think */
478 correction
= overlap
- data_size
;
481 /* Align correction to four bytes up */
482 correction
= (correction
+ 3) & ~3;
483 if (final_delta
< correction
+ sizeof(struct memory_handle
)) {
484 /* Delta cannot end up less than the size of the struct */
485 mutex_unlock(&llist_mod_mutex
);
486 mutex_unlock(&llist_mutex
);
489 newpos
-= correction
;
490 overlap
-= correction
;/* Used below to know how to split the data */
491 final_delta
-= correction
;
495 dest
= (struct memory_handle
*)(&buffer
[newpos
]);
497 if (src
== first_handle
) {
501 struct memory_handle
*m
= first_handle
;
502 while (m
&& m
->next
!= src
) {
505 if (m
&& m
->next
== src
) {
508 mutex_unlock(&llist_mod_mutex
);
509 mutex_unlock(&llist_mutex
);
515 /* Update the cache to prevent it from keeping the old location of h */
516 if (src
== cached_handle
)
517 cached_handle
= dest
;
519 /* the cur_handle pointer might need updating */
520 if (src
== cur_handle
)
524 /* Copying routine takes into account that the handles have a
525 * distance between each other which is a multiple of four. Faster 2 word
526 * copy may be ok but do this for safety and because wrapped copies should
527 * be fairly uncommon */
529 here
= (int32_t *)((ringbuf_add(oldpos
, size_to_move
- 1) & ~3)+ (intptr_t)buffer
);
530 there
=(int32_t *)((ringbuf_add(newpos
, size_to_move
- 1) & ~3)+ (intptr_t)buffer
);
531 end
= (int32_t *)(( intptr_t)buffer
+ buffer_len
- 4);
532 begin
=(int32_t *)buffer
;
534 n
= (size_to_move
& ~3)/4;
536 if ( overlap_old
> 0 || overlap
> 0 ) {
537 /* Old or moved handle wraps */
546 /* both handles do not wrap */
547 memmove(dest
,src
,size_to_move
);
551 /* Update the caller with the new location of h and the distance moved */
553 *delta
= final_delta
;
554 mutex_unlock(&llist_mod_mutex
);
555 mutex_unlock(&llist_mutex
);
561 BUFFER SPACE MANAGEMENT
562 =======================
564 update_data_counters: Updates the values in data_counters
565 buffer_is_low : Returns true if the amount of useful data in the buffer is low
566 buffer_handle : Buffer data for a handle
567 reset_handle : Reset write position and data buffer of a handle to its offset
568 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
569 shrink_handle : Free buffer space by moving a handle
570 fill_buffer : Call buffer_handle for all handles that have data to buffer
572 These functions are used by the buffering thread to manage buffer space.
575 static void update_data_counters(void)
577 struct memory_handle
*m
= find_handle(base_handle_id
);
578 bool is_useful
= m
==NULL
;
582 size_t remaining
= 0;
585 mutex_lock(&llist_mutex
);
589 buffered
+= m
->available
;
590 wasted
+= ringbuf_sub(m
->ridx
, m
->data
);
591 remaining
+= m
->filerem
;
593 if (m
->id
== base_handle_id
)
597 useful
+= ringbuf_sub(m
->widx
, m
->ridx
);
602 mutex_unlock(&llist_mutex
);
604 data_counters
.buffered
= buffered
;
605 data_counters
.wasted
= wasted
;
606 data_counters
.remaining
= remaining
;
607 data_counters
.useful
= useful
;
610 static inline bool buffer_is_low(void)
612 update_data_counters();
613 return data_counters
.useful
< (conf_watermark
/ 2);
616 /* Buffer data for the given handle.
617 Return whether or not the buffering should continue explicitly. */
618 static bool buffer_handle(int handle_id
)
620 logf("buffer_handle(%d)", handle_id
);
621 struct memory_handle
*h
= find_handle(handle_id
);
627 if (h
->filerem
== 0) {
628 /* nothing left to buffer */
632 if (h
->fd
< 0) /* file closed, reopen */
635 h
->fd
= open(h
->path
, O_RDONLY
);
639 /* could not open the file, truncate it where it is */
640 h
->filesize
-= h
->filerem
;
646 lseek(h
->fd
, h
->offset
, SEEK_SET
);
651 if (h
->type
== TYPE_ID3
)
653 if (!get_metadata((struct mp3entry
*)(buffer
+ h
->data
), h
->fd
, h
->path
))
655 /* metadata parsing failed: clear the buffer. */
656 memset(buffer
+ h
->data
, 0, sizeof(struct mp3entry
));
661 h
->available
= sizeof(struct mp3entry
);
662 h
->widx
+= sizeof(struct mp3entry
);
663 send_event(BUFFER_EVENT_FINISHED
, &h
->id
);
667 while (h
->filerem
> 0 && !stop
)
669 /* max amount to copy */
670 size_t copy_n
= MIN( MIN(h
->filerem
, BUFFERING_DEFAULT_FILECHUNK
),
671 buffer_len
- h
->widx
);
674 uintptr_t next_handle
= ringbuf_offset(h
->next
);
676 /* stop copying if it would overwrite the reading position */
677 if (ringbuf_add_cross(h
->widx
, copy_n
, buf_ridx
) >= 0)
680 /* FIXME: This would overwrite the next handle
681 * If this is true, then there's a handle even though we have still
682 * data to buffer. This should NEVER EVER happen! (but it does :( ) */
683 if (h
->next
&& (overlap
684 = ringbuf_add_cross(h
->widx
, copy_n
, next_handle
)) > 0)
686 /* stop buffering data for now and post-pone buffering the rest */
688 DEBUGF( "%s(): Preventing handle corruption: h1.id:%d h2.id:%d"
689 " copy_n:%lu overlap:%ld h1.filerem:%lu\n", __func__
,
690 h
->id
, h
->next
->id
, (unsigned long)copy_n
, overlap
,
691 (unsigned long)h
->filerem
);
695 /* rc is the actual amount read */
696 int rc
= read(h
->fd
, &buffer
[h
->widx
], copy_n
);
700 /* Some kind of filesystem error, maybe recoverable if not codec */
701 if (h
->type
== TYPE_CODEC
) {
702 logf("Partial codec");
706 DEBUGF("File ended %ld bytes early\n", (long)h
->filerem
);
707 h
->filesize
-= h
->filerem
;
713 h
->widx
= ringbuf_add(h
->widx
, rc
);
719 /* If this is a large file, see if we need to break or give the codec
721 if (h
->type
== TYPE_PACKET_AUDIO
&&
722 pcmbuf_is_lowdata() && !buffer_is_low())
731 if (!queue_empty(&buffering_queue
))
735 if (h
->filerem
== 0) {
736 /* finished buffering the file */
739 send_event(BUFFER_EVENT_FINISHED
, &h
->id
);
745 /* Reset writing position and data buffer of a handle to its current offset.
746 Use this after having set the new offset to use. */
747 static void reset_handle(int handle_id
)
749 size_t alignment_pad
;
751 logf("reset_handle(%d)", handle_id
);
753 struct memory_handle
*h
= find_handle(handle_id
);
757 /* Align to desired storage alignment */
758 alignment_pad
= STORAGE_OVERLAP(h
->offset
- (size_t)(&buffer
[h
->start
]));
759 h
->ridx
= h
->widx
= h
->data
= ringbuf_add(h
->start
, alignment_pad
);
764 h
->filerem
= h
->filesize
- h
->offset
;
767 lseek(h
->fd
, h
->offset
, SEEK_SET
);
771 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
772 static void rebuffer_handle(int handle_id
, size_t newpos
)
774 struct memory_handle
*h
= find_handle(handle_id
);
778 /* When seeking foward off of the buffer, if it is a short seek don't
779 rebuffer the whole track, just read enough to satisfy */
780 if (newpos
> h
->offset
&& newpos
- h
->offset
< BUFFERING_DEFAULT_FILECHUNK
)
782 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id
);
783 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, handle_id
);
784 h
->ridx
= h
->data
+ newpos
;
790 /* Reset the handle to its new offset */
791 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id
);
792 queue_send(&buffering_queue
, Q_RESET_HANDLE
, handle_id
);
794 uintptr_t next
= ringbuf_offset(h
->next
);
795 if (ringbuf_sub(next
, h
->data
) < h
->filesize
- newpos
)
797 /* There isn't enough space to rebuffer all of the track from its new
798 offset, so we ask the user to free some */
799 DEBUGF("%s(): space is needed\n", __func__
);
800 send_event(BUFFER_EVENT_REBUFFER
, &handle_id
);
803 /* Now we ask for a rebuffer */
804 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id
);
805 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, handle_id
);
808 static bool close_handle(int handle_id
)
810 struct memory_handle
*h
= find_handle(handle_id
);
812 /* If the handle is not found, it is closed */
821 /* rm_handle returns true unless the handle somehow persists after exit */
825 /* Free buffer space by moving the handle struct right before the useful
826 part of its data buffer or by moving all the data. */
827 static void shrink_handle(struct memory_handle
*h
)
834 if (h
->next
&& h
->filerem
== 0 &&
835 (h
->type
== TYPE_ID3
|| h
->type
== TYPE_CUESHEET
||
836 h
->type
== TYPE_BITMAP
|| h
->type
== TYPE_CODEC
||
837 h
->type
== TYPE_ATOMIC_AUDIO
))
839 /* metadata handle: we can move all of it */
840 uintptr_t handle_distance
=
841 ringbuf_sub(ringbuf_offset(h
->next
), h
->data
);
842 delta
= handle_distance
- h
->available
;
844 /* The value of delta might change for alignment reasons */
845 if (!move_handle(&h
, &delta
, h
->available
, h
->type
==TYPE_CODEC
))
848 size_t olddata
= h
->data
;
849 h
->data
= ringbuf_add(h
->data
, delta
);
850 h
->ridx
= ringbuf_add(h
->ridx
, delta
);
851 h
->widx
= ringbuf_add(h
->widx
, delta
);
853 if (h
->type
== TYPE_ID3
&& h
->filesize
== sizeof(struct mp3entry
)) {
854 /* when moving an mp3entry we need to readjust its pointers. */
855 adjust_mp3entry((struct mp3entry
*)&buffer
[h
->data
],
856 (void *)&buffer
[h
->data
],
857 (const void *)&buffer
[olddata
]);
858 } else if (h
->type
== TYPE_BITMAP
) {
859 /* adjust the bitmap's pointer */
860 struct bitmap
*bmp
= (struct bitmap
*)&buffer
[h
->data
];
861 bmp
->data
= &buffer
[h
->data
+ sizeof(struct bitmap
)];
866 /* only move the handle struct */
867 delta
= ringbuf_sub(h
->ridx
, h
->data
);
868 if (!move_handle(&h
, &delta
, 0, true))
871 h
->data
= ringbuf_add(h
->data
, delta
);
872 h
->start
= ringbuf_add(h
->start
, delta
);
873 h
->available
-= delta
;
878 /* Fill the buffer by buffering as much data as possible for handles that still
879 have data left to buffer
880 Return whether or not to continue filling after this */
881 static bool fill_buffer(void)
883 logf("fill_buffer()");
884 struct memory_handle
*m
;
885 shrink_handle(first_handle
);
887 while (queue_empty(&buffering_queue
) && m
) {
888 if (m
->filerem
> 0) {
889 if (!buffer_handle(m
->id
)) {
902 /* only spin the disk down if the filling wasn't interrupted by an
903 event arriving in the queue. */
910 /* Given a file descriptor to a bitmap file, write the bitmap data to the
911 buffer, with a struct bitmap and the actual data immediately following.
912 Return value is the total size (struct + data). */
913 static int load_image(int fd
, const char *path
, struct dim
*dim
)
916 struct bitmap
*bmp
= (struct bitmap
*)&buffer
[buf_widx
];
918 /* get the desired image size */
919 bmp
->width
= dim
->width
, bmp
->height
= dim
->height
;
920 /* FIXME: alignment may be needed for the data buffer. */
921 bmp
->data
= &buffer
[buf_widx
+ sizeof(struct bitmap
)];
925 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
926 bmp
->maskdata
= NULL
;
929 int free
= (int)MIN(buffer_len
- BUF_USED
, buffer_len
- buf_widx
)
930 - sizeof(struct bitmap
);
933 int pathlen
= strlen(path
);
934 if (strcmp(path
+ pathlen
- 4, ".bmp"))
935 rc
= read_jpeg_fd(fd
, bmp
, free
, FORMAT_NATIVE
|FORMAT_DITHER
|
936 FORMAT_RESIZE
|FORMAT_KEEP_ASPECT
, NULL
);
939 rc
= read_bmp_fd(fd
, bmp
, free
, FORMAT_NATIVE
|FORMAT_DITHER
|
940 FORMAT_RESIZE
|FORMAT_KEEP_ASPECT
, NULL
);
941 return rc
+ (rc
> 0 ? sizeof(struct bitmap
) : 0);
947 MAIN BUFFERING API CALLS
948 ========================
950 bufopen : Request the opening of a new handle for a file
951 bufalloc : Open a new handle for data other than a file.
952 bufclose : Close an open handle
953 bufseek : Set the read pointer in a handle
954 bufadvance : Move the read pointer in a handle
955 bufread : Copy data from a handle into a given buffer
956 bufgetdata : Give a pointer to the handle's data
958 These functions are exported, to allow interaction with the buffer.
959 They take care of the content of the structs, and rely on the linked list
960 management functions for all the actual handle management work.
964 /* Reserve space in the buffer for a file.
965 filename: name of the file to open
966 offset: offset at which to start buffering the file, useful when the first
967 (offset-1) bytes of the file aren't needed.
968 type: one of the data types supported (audio, image, cuesheet, others
969 user_data: user data passed possibly passed in subcalls specific to a
970 data_type (only used for image (albumart) buffering so far )
971 return value: <0 if the file cannot be opened, or one file already
972 queued to be opened, otherwise the handle for the file in the buffer
974 int bufopen(const char *file
, size_t offset
, enum data_type type
,
977 #ifndef HAVE_ALBUMART
978 /* currently only used for aa loading */
981 if (type
== TYPE_ID3
)
983 /* ID3 case: allocate space, init the handle and return. */
985 struct memory_handle
*h
= add_handle(sizeof(struct mp3entry
), false, true);
987 return ERR_BUFFER_FULL
;
990 h
->filesize
= sizeof(struct mp3entry
);
991 h
->filerem
= sizeof(struct mp3entry
);
998 strlcpy(h
->path
, file
, MAX_PATH
);
1000 buf_widx
+= sizeof(struct mp3entry
); /* safe because the handle
1003 /* Inform the buffering thread that we added a handle */
1004 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
1005 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
1010 /* Other cases: there is a little more work. */
1012 int fd
= open(file
, O_RDONLY
);
1014 return ERR_FILE_ERROR
;
1016 size_t size
= filesize(fd
);
1017 bool can_wrap
= type
==TYPE_PACKET_AUDIO
|| type
==TYPE_CODEC
;
1019 size_t adjusted_offset
= offset
;
1020 if (adjusted_offset
> size
)
1021 adjusted_offset
= 0;
1023 /* Reserve extra space because alignment can move data forward */
1024 size_t padded_size
= STORAGE_PAD(size
-adjusted_offset
);
1025 struct memory_handle
*h
= add_handle(padded_size
, can_wrap
, false);
1028 DEBUGF("%s(): failed to add handle\n", __func__
);
1030 return ERR_BUFFER_FULL
;
1033 strlcpy(h
->path
, file
, MAX_PATH
);
1034 h
->offset
= adjusted_offset
;
1036 /* Don't bother to storage align bitmaps because they are not
1037 * loaded directly into the buffer.
1039 if (type
!= TYPE_BITMAP
)
1041 size_t alignment_pad
;
1043 /* Remember where data area starts, for use by reset_handle */
1044 h
->start
= buf_widx
;
1046 /* Align to desired storage alignment */
1047 alignment_pad
= STORAGE_OVERLAP(adjusted_offset
- (size_t)(&buffer
[buf_widx
]));
1048 buf_widx
= ringbuf_add(buf_widx
, alignment_pad
);
1058 #ifdef HAVE_ALBUMART
1059 if (type
== TYPE_BITMAP
)
1061 /* Bitmap file: we load the data instead of the file */
1063 mutex_lock(&llist_mod_mutex
); /* Lock because load_bitmap yields */
1064 rc
= load_image(fd
, file
, (struct dim
*)user_data
);
1065 mutex_unlock(&llist_mod_mutex
);
1070 return ERR_FILE_ERROR
;
1075 h
->widx
= buf_widx
+ rc
; /* safe because the data doesn't wrap */
1076 buf_widx
+= rc
; /* safe too */
1081 h
->filerem
= size
- adjusted_offset
;
1087 if (type
== TYPE_CUESHEET
) {
1089 /* Immediately start buffering those */
1090 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h
->id
);
1091 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, h
->id
);
1093 /* Other types will get buffered in the course of normal operations */
1097 /* Inform the buffering thread that we added a handle */
1098 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
1099 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
1102 logf("bufopen: new hdl %d", h
->id
);
1106 /* Open a new handle from data that needs to be copied from memory.
1107 src is the source buffer from which to copy data. It can be NULL to simply
1108 reserve buffer space.
1109 size is the requested size. The call will only be successful if the
1110 requested amount of data can entirely fit in the buffer without wrapping.
1111 Return value is the handle id for success or <0 for failure.
1113 int bufalloc(const void *src
, size_t size
, enum data_type type
)
1115 struct memory_handle
*h
= add_handle(size
, false, true);
1118 return ERR_BUFFER_FULL
;
1121 if (type
== TYPE_ID3
&& size
== sizeof(struct mp3entry
)) {
1122 /* specially take care of struct mp3entry */
1123 copy_mp3entry((struct mp3entry
*)&buffer
[buf_widx
],
1124 (const struct mp3entry
*)src
);
1126 memcpy(&buffer
[buf_widx
], src
, size
);
1136 h
->widx
= buf_widx
+ size
; /* this is safe because the data doesn't wrap */
1138 h
->available
= size
;
1141 buf_widx
+= size
; /* safe too */
1143 logf("bufalloc: new hdl %d", h
->id
);
1147 /* Close the handle. Return true for success and false for failure */
1148 bool bufclose(int handle_id
)
1150 logf("bufclose(%d)", handle_id
);
1152 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id
);
1153 return queue_send(&buffering_queue
, Q_CLOSE_HANDLE
, handle_id
);
1156 /* Set reading index in handle (relatively to the start of the file).
1157 Access before the available data will trigger a rebuffer.
1158 Return 0 for success and < 0 for failure:
1159 -1 if the handle wasn't found
1160 -2 if the new requested position was beyond the end of the file
1162 int bufseek(int handle_id
, size_t newpos
)
1164 struct memory_handle
*h
= find_handle(handle_id
);
1166 return ERR_HANDLE_NOT_FOUND
;
1168 if (newpos
> h
->filesize
) {
1169 /* access beyond the end of the file */
1170 return ERR_INVALID_VALUE
;
1172 else if (newpos
< h
->offset
|| h
->offset
+ h
->available
< newpos
) {
1173 /* access before or after buffered data. A rebuffer is needed. */
1174 rebuffer_handle(handle_id
, newpos
);
1177 h
->ridx
= ringbuf_add(h
->data
, newpos
- h
->offset
);
1182 /* Advance the reading index in a handle (relatively to its current position).
1183 Return 0 for success and < 0 for failure */
1184 int bufadvance(int handle_id
, off_t offset
)
1186 const struct memory_handle
*h
= find_handle(handle_id
);
1188 return ERR_HANDLE_NOT_FOUND
;
1190 size_t newpos
= h
->offset
+ ringbuf_sub(h
->ridx
, h
->data
) + offset
;
1191 return bufseek(handle_id
, newpos
);
1194 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1195 * actual amount of data available for reading. This function explicitly
1196 * does not check the validity of the input handle. It does do range checks
1197 * on size and returns a valid (and explicit) amount of data for reading */
1198 static struct memory_handle
*prep_bufdata(int handle_id
, size_t *size
,
1199 bool guardbuf_limit
)
1201 struct memory_handle
*h
= find_handle(handle_id
);
1205 size_t avail
= ringbuf_sub(h
->widx
, h
->ridx
);
1207 if (avail
== 0 && h
->filerem
== 0)
1209 /* File is finished reading */
1214 if (*size
== 0 || *size
> avail
+ h
->filerem
)
1215 *size
= avail
+ h
->filerem
;
1217 if (guardbuf_limit
&& h
->type
== TYPE_PACKET_AUDIO
&& *size
> GUARD_BUFSIZE
)
1219 logf("data request > guardbuf");
1220 /* If more than the size of the guardbuf is requested and this is a
1221 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1222 *size
= MIN(*size
, buffer_len
- h
->ridx
+ GUARD_BUFSIZE
);
1223 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1226 if (h
->filerem
> 0 && avail
< *size
)
1228 /* Data isn't ready. Request buffering */
1229 buf_request_buffer_handle(handle_id
);
1230 /* Wait for the data to be ready */
1234 /* it is not safe for a non-buffering thread to sleep while
1235 * holding a handle */
1236 h
= find_handle(handle_id
);
1239 avail
= ringbuf_sub(h
->widx
, h
->ridx
);
1241 while (h
->filerem
> 0 && avail
< *size
);
1244 *size
= MIN(*size
,avail
);
1248 /* Copy data from the given handle to the dest buffer.
1249 Return the number of bytes copied or < 0 for failure (handle not found).
1250 The caller is blocked until the requested amount of data is available.
1252 ssize_t
bufread(int handle_id
, size_t size
, void *dest
)
1254 const struct memory_handle
*h
;
1255 size_t adjusted_size
= size
;
1257 h
= prep_bufdata(handle_id
, &adjusted_size
, false);
1259 return ERR_HANDLE_NOT_FOUND
;
1261 if (h
->ridx
+ adjusted_size
> buffer_len
)
1263 /* the data wraps around the end of the buffer */
1264 size_t read
= buffer_len
- h
->ridx
;
1265 memcpy(dest
, &buffer
[h
->ridx
], read
);
1266 memcpy(dest
+read
, buffer
, adjusted_size
- read
);
1270 memcpy(dest
, &buffer
[h
->ridx
], adjusted_size
);
1273 return adjusted_size
;
1276 /* Update the "data" pointer to make the handle's data available to the caller.
1277 Return the length of the available linear data or < 0 for failure (handle
1279 The caller is blocked until the requested amount of data is available.
1280 size is the amount of linear data requested. it can be 0 to get as
1282 The guard buffer may be used to provide the requested size. This means it's
1283 unsafe to request more than the size of the guard buffer.
1285 ssize_t
bufgetdata(int handle_id
, size_t size
, void **data
)
1287 const struct memory_handle
*h
;
1288 size_t adjusted_size
= size
;
1290 h
= prep_bufdata(handle_id
, &adjusted_size
, true);
1292 return ERR_HANDLE_NOT_FOUND
;
1294 if (h
->ridx
+ adjusted_size
> buffer_len
)
1296 /* the data wraps around the end of the buffer :
1297 use the guard buffer to provide the requested amount of data. */
1298 size_t copy_n
= h
->ridx
+ adjusted_size
- buffer_len
;
1299 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1300 so copy_n <= GUARD_BUFSIZE */
1301 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1305 *data
= &buffer
[h
->ridx
];
1307 return adjusted_size
;
1310 ssize_t
bufgettail(int handle_id
, size_t size
, void **data
)
1314 const struct memory_handle
*h
;
1316 h
= find_handle(handle_id
);
1319 return ERR_HANDLE_NOT_FOUND
;
1322 return ERR_HANDLE_NOT_DONE
;
1324 /* We don't support tail requests of > guardbuf_size, for simplicity */
1325 if (size
> GUARD_BUFSIZE
)
1326 return ERR_INVALID_VALUE
;
1328 tidx
= ringbuf_sub(h
->widx
, size
);
1330 if (tidx
+ size
> buffer_len
)
1332 size_t copy_n
= tidx
+ size
- buffer_len
;
1333 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1336 *data
= &buffer
[tidx
];
1340 ssize_t
bufcuttail(int handle_id
, size_t size
)
1342 struct memory_handle
*h
;
1343 size_t adjusted_size
= size
;
1345 h
= find_handle(handle_id
);
1348 return ERR_HANDLE_NOT_FOUND
;
1351 return ERR_HANDLE_NOT_DONE
;
1353 if (h
->available
< adjusted_size
)
1354 adjusted_size
= h
->available
;
1356 h
->available
-= adjusted_size
;
1357 h
->filesize
-= adjusted_size
;
1358 h
->widx
= ringbuf_sub(h
->widx
, adjusted_size
);
1359 if (h
== cur_handle
)
1362 return adjusted_size
;
1367 SECONDARY EXPORTED FUNCTIONS
1368 ============================
1372 buf_request_buffer_handle
1375 register_buffering_callback
1376 unregister_buffering_callback
1378 These functions are exported, to allow interaction with the buffer.
1379 They take care of the content of the structs, and rely on the linked list
1380 management functions for all the actual handle management work.
1383 /* Get a handle offset from a pointer */
1384 ssize_t
buf_get_offset(int handle_id
, void *ptr
)
1386 const struct memory_handle
*h
= find_handle(handle_id
);
1388 return ERR_HANDLE_NOT_FOUND
;
1390 return (size_t)ptr
- (size_t)&buffer
[h
->ridx
];
1393 ssize_t
buf_handle_offset(int handle_id
)
1395 const struct memory_handle
*h
= find_handle(handle_id
);
1397 return ERR_HANDLE_NOT_FOUND
;
1401 void buf_request_buffer_handle(int handle_id
)
1403 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id
);
1404 queue_send(&buffering_queue
, Q_START_FILL
, handle_id
);
1407 void buf_set_base_handle(int handle_id
)
1409 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id
);
1410 queue_post(&buffering_queue
, Q_BASE_HANDLE
, handle_id
);
1413 /* Return the amount of buffer space used */
1414 size_t buf_used(void)
1419 void buf_set_watermark(size_t bytes
)
1421 conf_watermark
= bytes
;
1424 static void shrink_buffer_inner(struct memory_handle
*h
)
1429 shrink_buffer_inner(h
->next
);
1434 static void shrink_buffer(void)
1436 logf("shrink_buffer()");
1437 shrink_buffer_inner(first_handle
);
1440 void buffering_thread(void)
1442 bool filling
= false;
1443 struct queue_event ev
;
1451 queue_wait_w_tmo(&buffering_queue
, &ev
, filling
? 5 : HZ
/2);
1456 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev
.data
);
1457 /* Call buffer callbacks here because this is one of two ways
1458 * to begin a full buffer fill */
1459 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1461 queue_reply(&buffering_queue
, 1);
1462 filling
|= buffer_handle((int)ev
.data
);
1465 case Q_BUFFER_HANDLE
:
1466 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev
.data
);
1467 queue_reply(&buffering_queue
, 1);
1468 buffer_handle((int)ev
.data
);
1471 case Q_RESET_HANDLE
:
1472 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev
.data
);
1473 queue_reply(&buffering_queue
, 1);
1474 reset_handle((int)ev
.data
);
1477 case Q_CLOSE_HANDLE
:
1478 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev
.data
);
1479 queue_reply(&buffering_queue
, close_handle((int)ev
.data
));
1482 case Q_HANDLE_ADDED
:
1483 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev
.data
);
1484 /* A handle was added: the disk is spinning, so we can fill */
1489 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev
.data
);
1490 base_handle_id
= (int)ev
.data
;
1494 case SYS_USB_CONNECTED
:
1495 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1496 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
1497 usb_wait_for_disconnect(&buffering_queue
);
1502 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1506 update_data_counters();
1508 /* If the buffer is low, call the callbacks to get new data */
1509 if (num_handles
> 0 && data_counters
.useful
<= conf_watermark
)
1510 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1513 /* TODO: This needs to be fixed to use the idle callback, disable it
1514 * for simplicity until its done right */
1516 /* If the disk is spinning, take advantage by filling the buffer */
1517 else if (storage_disk_is_active() && queue_empty(&buffering_queue
))
1519 if (num_handles
> 0 && data_counters
.useful
<= high_watermark
)
1520 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1522 if (data_counters
.remaining
> 0 && BUF_USED
<= high_watermark
)
1524 /* This is a new fill, shrink the buffer up first */
1527 filling
= fill_buffer();
1528 update_data_counters();
1534 if (queue_empty(&buffering_queue
)) {
1536 if (data_counters
.remaining
> 0 && BUF_USED
< buffer_len
)
1537 filling
= fill_buffer();
1538 else if (data_counters
.remaining
== 0)
1541 else if (ev
.id
== SYS_TIMEOUT
)
1543 if (data_counters
.remaining
> 0 &&
1544 data_counters
.useful
<= conf_watermark
) {
1546 filling
= fill_buffer();
1553 void buffering_init(void)
1555 mutex_init(&llist_mutex
);
1556 mutex_init(&llist_mod_mutex
);
1557 #ifdef HAVE_PRIORITY_SCHEDULING
1558 /* This behavior not safe atm */
1559 mutex_set_preempt(&llist_mutex
, false);
1560 mutex_set_preempt(&llist_mod_mutex
, false);
1563 conf_watermark
= BUFFERING_DEFAULT_WATERMARK
;
1565 queue_init(&buffering_queue
, true);
1566 buffering_thread_id
= create_thread( buffering_thread
, buffering_stack
,
1567 sizeof(buffering_stack
), CREATE_THREAD_FROZEN
,
1568 buffering_thread_name
IF_PRIO(, PRIORITY_BUFFERING
)
1571 queue_enable_queue_send(&buffering_queue
, &buffering_queue_sender_list
,
1572 buffering_thread_id
);
1575 /* Initialise the buffering subsystem */
1576 bool buffering_reset(char *buf
, size_t buflen
)
1578 if (!buf
|| !buflen
)
1582 /* Preserve alignment when wrapping around */
1583 buffer_len
= STORAGE_ALIGN_DOWN(buflen
);
1584 guard_buffer
= buf
+ buflen
;
1589 first_handle
= NULL
;
1591 cached_handle
= NULL
;
1593 base_handle_id
= -1;
1595 /* Set the high watermark as 75% full...or 25% empty :) */
1597 high_watermark
= 3*buflen
/ 4;
1600 thread_thaw(buffering_thread_id
);
1605 void buffering_get_debugdata(struct buffering_debug
*dbgdata
)
1607 update_data_counters();
1608 dbgdata
->num_handles
= num_handles
;
1609 dbgdata
->data_rem
= data_counters
.remaining
;
1610 dbgdata
->wasted_space
= data_counters
.wasted
;
1611 dbgdata
->buffered_data
= data_counters
.buffered
;
1612 dbgdata
->useful_data
= data_counters
.useful
;
1613 dbgdata
->watermark
= conf_watermark
;