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"
44 #include "mp3_playback.h"
50 #include "appevents.h"
54 #include "jpeg_load.h"
58 #define GUARD_BUFSIZE (32*1024)
60 /* Define LOGF_ENABLE to enable logf output in this file */
61 /*#define LOGF_ENABLE*/
64 /* macros to enable logf for queues
65 logging on SYS_TIMEOUT can be disabled */
67 /* Define this for logf output of all queuing except SYS_TIMEOUT */
68 #define BUFFERING_LOGQUEUES
69 /* Define this to logf SYS_TIMEOUT messages */
70 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
73 #ifdef BUFFERING_LOGQUEUES
74 #define LOGFQUEUE logf
76 #define LOGFQUEUE(...)
79 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
80 #define LOGFQUEUE_SYS_TIMEOUT logf
82 #define LOGFQUEUE_SYS_TIMEOUT(...)
85 /* default point to start buffer refill */
86 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
87 /* amount of data to read in one read() call */
88 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
90 #define BUF_HANDLE_MASK 0x7FFFFFFF
93 /* assert(sizeof(struct memory_handle)%4==0) */
94 struct memory_handle
{
95 int id
; /* A unique ID for the handle */
96 enum data_type type
; /* Type of data buffered with this handle */
97 char path
[MAX_PATH
]; /* Path if data originated in a file */
98 int fd
; /* File descriptor to path (-1 if closed) */
99 size_t start
; /* Start index of the handle's data buffer,
100 for use by reset_handle. */
101 size_t data
; /* Start index of the handle's data */
102 volatile size_t ridx
; /* Read pointer, relative to the main buffer */
103 size_t widx
; /* Write pointer */
104 size_t filesize
; /* File total length */
105 size_t filerem
; /* Remaining bytes of file NOT in buffer */
106 volatile size_t available
; /* Available bytes to read from buffer */
107 size_t offset
; /* Offset at which we started reading the file */
108 struct memory_handle
*next
;
110 /* invariant: filesize == offset + available + filerem */
113 static char *guard_buffer
;
115 static size_t buffer_len
;
117 static volatile size_t buf_widx
; /* current writing position */
118 static volatile size_t buf_ridx
; /* current reading position */
119 /* buf_*idx are values relative to the buffer, not real pointers. */
122 static size_t conf_watermark
= 0; /* Level to trigger filebuf fill */
124 static size_t high_watermark
= 0; /* High watermark for rebuffer */
127 /* current memory handle in the linked list. NULL when the list is empty. */
128 static struct memory_handle
*cur_handle
;
129 /* first memory handle in the linked list. NULL when the list is empty. */
130 static struct memory_handle
*first_handle
;
132 static int num_handles
; /* number of handles in the list */
134 static int base_handle_id
;
136 static struct mutex llist_mutex
;
137 static struct mutex llist_mod_mutex
;
139 /* Handle cache (makes find_handle faster).
140 This is global so that move_handle and rm_handle can invalidate it. */
141 static struct memory_handle
*cached_handle
= NULL
;
144 size_t remaining
; /* Amount of data needing to be buffered */
145 size_t wasted
; /* Amount of space available for freeing */
146 size_t buffered
; /* Amount of data currently in the buffer */
147 size_t useful
; /* Amount of data still useful to the user */
151 /* Messages available to communicate with the buffering thread */
153 Q_BUFFER_HANDLE
= 1, /* Request buffering of a handle, this should not be
154 used in a low buffer situation. */
155 Q_RESET_HANDLE
, /* (internal) Request resetting of a handle to its
156 offset (the offset has to be set beforehand) */
157 Q_CLOSE_HANDLE
, /* Request closing a handle */
158 Q_BASE_HANDLE
, /* Set the reference handle for buf_useful_data */
161 Q_START_FILL
, /* Request that the buffering thread initiate a buffer
162 fill at its earliest convenience */
163 Q_HANDLE_ADDED
, /* Inform the buffering thread that a handle was added,
164 (which means the disk is spinning) */
167 /* Buffering thread */
168 static void buffering_thread(void);
169 static long buffering_stack
[(DEFAULT_STACK_SIZE
+ 0x2000)/sizeof(long)];
170 static const char buffering_thread_name
[] = "buffering";
171 static unsigned int buffering_thread_id
= 0;
172 static struct event_queue buffering_queue
;
173 static struct queue_sender_list buffering_queue_sender_list
;
177 /* Ring buffer helper functions */
179 static inline uintptr_t ringbuf_offset(const void *ptr
)
181 return (uintptr_t)(ptr
- (void*)buffer
);
184 /* Buffer pointer (p) plus value (v), wrapped if necessary */
185 static inline uintptr_t ringbuf_add(uintptr_t p
, size_t v
)
187 uintptr_t res
= p
+ v
;
188 if (res
>= buffer_len
)
189 res
-= buffer_len
; /* wrap if necssary */
194 /* Buffer pointer (p) minus value (v), wrapped if necessary */
195 static inline uintptr_t ringbuf_sub(uintptr_t p
, size_t v
)
199 res
+= buffer_len
; /* wrap */
205 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
206 static inline ssize_t
ringbuf_add_cross(uintptr_t p1
, size_t v
, uintptr_t p2
)
208 ssize_t res
= p1
+ v
- p2
;
209 if (p1
>= p2
) /* wrap if necessary */
215 /* Bytes available in the buffer */
216 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
219 LINKED LIST MANAGEMENT
220 ======================
222 add_handle : Add a handle to the list
223 rm_handle : Remove a handle from the list
224 find_handle : Get a handle pointer from an ID
225 move_handle : Move a handle in the buffer (with or without its data)
227 These functions only handle the linked list structure. They don't touch the
228 contents of the struct memory_handle headers. They also change the buf_*idx
229 pointers when necessary and manage the handle IDs.
231 The first and current (== last) handle are kept track of.
232 A new handle is added at buf_widx and becomes the current one.
233 buf_widx always points to the current writing position for the current handle
234 buf_ridx always points to the location of the first handle.
235 buf_ridx == buf_widx means the buffer is empty.
239 /* Add a new handle to the linked list and return it. It will have become the
241 data_size must contain the size of what will be in the handle.
242 can_wrap tells us whether this type of data may wrap on buffer
243 alloc_all tells us if we must immediately be able to allocate data_size
244 returns a valid memory handle if all conditions for allocation are met.
245 NULL if there memory_handle itself cannot be allocated or if the
246 data_size cannot be allocated and alloc_all is set. This function's
247 only potential side effect is to allocate space for the cur_handle
250 static struct memory_handle
*add_handle(size_t data_size
, bool can_wrap
,
253 /* gives each handle a unique id */
254 static int cur_handle_id
= 0;
260 if (num_handles
>= BUF_MAX_HANDLES
)
263 mutex_lock(&llist_mutex
);
264 mutex_lock(&llist_mod_mutex
);
266 if (cur_handle
&& cur_handle
->filerem
> 0) {
267 /* the current handle hasn't finished buffering. We can only add
268 a new one if there is already enough free space to finish
270 size_t req
= cur_handle
->filerem
+ sizeof(struct memory_handle
);
271 if (ringbuf_add_cross(cur_handle
->widx
, req
, buf_ridx
) >= 0) {
272 /* Not enough space */
273 mutex_unlock(&llist_mod_mutex
);
274 mutex_unlock(&llist_mutex
);
277 /* Allocate the remainder of the space for the current handle */
278 buf_widx
= ringbuf_add(cur_handle
->widx
, cur_handle
->filerem
);
282 /* align to 4 bytes up */
283 new_widx
= ringbuf_add(buf_widx
, 3) & ~3;
285 len
= data_size
+ sizeof(struct memory_handle
);
287 /* First, will the handle wrap? */
288 /* If the handle would wrap, move to the beginning of the buffer,
289 * or if the data must not but would wrap, move it to the beginning */
290 if( (new_widx
+ sizeof(struct memory_handle
) > buffer_len
) ||
291 (!can_wrap
&& (new_widx
+ len
> buffer_len
)) ) {
295 /* How far we shifted buf_widx to align things, must be < buffer_len */
296 shift
= ringbuf_sub(new_widx
, buf_widx
);
298 /* How much space are we short in the actual ring buffer? */
299 overlap
= ringbuf_add_cross(buf_widx
, shift
+ len
, buf_ridx
);
300 if (overlap
>= 0 && (alloc_all
|| (unsigned)overlap
> data_size
)) {
301 /* Not enough space for required allocations */
302 mutex_unlock(&llist_mod_mutex
);
303 mutex_unlock(&llist_mutex
);
307 /* There is enough space for the required data, advance the buf_widx and
308 * initialize the struct */
311 struct memory_handle
*new_handle
=
312 (struct memory_handle
*)(&buffer
[buf_widx
]);
314 /* only advance the buffer write index of the size of the struct */
315 buf_widx
= ringbuf_add(buf_widx
, sizeof(struct memory_handle
));
317 new_handle
->id
= cur_handle_id
;
318 /* Wrap signed int is safe and 0 doesn't happen */
319 cur_handle_id
= (cur_handle_id
+ 1) & BUF_HANDLE_MASK
;
320 new_handle
->next
= NULL
;
324 /* the new handle is the first one */
325 first_handle
= new_handle
;
328 cur_handle
->next
= new_handle
;
330 cur_handle
= new_handle
;
332 mutex_unlock(&llist_mod_mutex
);
333 mutex_unlock(&llist_mutex
);
337 /* Delete a given memory handle from the linked list
338 and return true for success. Nothing is actually erased from memory. */
339 static bool rm_handle(const struct memory_handle
*h
)
344 mutex_lock(&llist_mutex
);
345 mutex_lock(&llist_mod_mutex
);
347 if (h
== first_handle
) {
348 first_handle
= h
->next
;
349 if (h
== cur_handle
) {
350 /* h was the first and last handle: the buffer is now empty */
352 buf_ridx
= buf_widx
= 0;
354 /* update buf_ridx to point to the new first handle */
355 buf_ridx
= (size_t)ringbuf_offset(first_handle
);
358 struct memory_handle
*m
= first_handle
;
359 /* Find the previous handle */
360 while (m
&& m
->next
!= h
) {
363 if (m
&& m
->next
== h
) {
365 if (h
== cur_handle
) {
367 buf_widx
= cur_handle
->widx
;
370 mutex_unlock(&llist_mod_mutex
);
371 mutex_unlock(&llist_mutex
);
376 /* Invalidate the cache to prevent it from keeping the old location of h */
377 if (h
== cached_handle
)
378 cached_handle
= NULL
;
382 mutex_unlock(&llist_mod_mutex
);
383 mutex_unlock(&llist_mutex
);
387 /* Return a pointer to the memory handle of given ID.
388 NULL if the handle wasn't found */
389 static struct memory_handle
*find_handle(int handle_id
)
394 mutex_lock(&llist_mutex
);
396 /* simple caching because most of the time the requested handle
397 will either be the same as the last, or the one after the last */
400 if (cached_handle
->id
== handle_id
) {
401 mutex_unlock(&llist_mutex
);
402 return cached_handle
;
403 } else if (cached_handle
->next
&&
404 (cached_handle
->next
->id
== handle_id
)) {
405 cached_handle
= cached_handle
->next
;
406 mutex_unlock(&llist_mutex
);
407 return cached_handle
;
411 struct memory_handle
*m
= first_handle
;
412 while (m
&& m
->id
!= handle_id
) {
415 /* This condition can only be reached with !m or m->id == handle_id */
419 mutex_unlock(&llist_mutex
);
423 /* Move a memory handle and data_size of its data delta bytes along the buffer.
424 delta maximum bytes available to move the handle. If the move is performed
425 it is set to the actual distance moved.
426 data_size is the amount of data to move along with the struct.
427 returns true if the move is successful and false if the handle is NULL,
428 the move would be less than the size of a memory_handle after
429 correcting for wraps or if the handle is not found in the linked
430 list for adjustment. This function has no side effects if false
432 static bool move_handle(struct memory_handle
**h
, size_t *delta
,
433 size_t data_size
, bool can_wrap
)
435 struct memory_handle
*dest
;
436 const struct memory_handle
*src
;
441 size_t final_delta
= *delta
, size_to_move
, n
;
442 uintptr_t oldpos
, newpos
;
443 intptr_t overlap
, overlap_old
;
445 if (h
== NULL
|| (src
= *h
) == NULL
)
448 size_to_move
= sizeof(struct memory_handle
) + data_size
;
450 /* Align to four bytes, down */
452 if (final_delta
< sizeof(struct memory_handle
)) {
453 /* It's not legal to move less than the size of the struct */
457 mutex_lock(&llist_mutex
);
458 mutex_lock(&llist_mod_mutex
);
460 oldpos
= ringbuf_offset(src
);
461 newpos
= ringbuf_add(oldpos
, final_delta
);
462 overlap
= ringbuf_add_cross(newpos
, size_to_move
, buffer_len
- 1);
463 overlap_old
= ringbuf_add_cross(oldpos
, size_to_move
, buffer_len
-1);
466 /* Some part of the struct + data would wrap, maybe ok */
467 size_t correction
= 0;
468 /* If the overlap lands inside the memory_handle */
470 /* Otherwise the overlap falls in the data area and must all be
471 * backed out. This may become conditional if ever we move
472 * data that is allowed to wrap (ie audio) */
473 correction
= overlap
;
474 } else if ((uintptr_t)overlap
> data_size
) {
475 /* Correct the position and real delta to prevent the struct from
476 * wrapping, this guarantees an aligned delta, I think */
477 correction
= overlap
- data_size
;
480 /* Align correction to four bytes up */
481 correction
= (correction
+ 3) & ~3;
482 if (final_delta
< correction
+ sizeof(struct memory_handle
)) {
483 /* Delta cannot end up less than the size of the struct */
484 mutex_unlock(&llist_mod_mutex
);
485 mutex_unlock(&llist_mutex
);
488 newpos
-= correction
;
489 overlap
-= correction
;/* Used below to know how to split the data */
490 final_delta
-= correction
;
494 dest
= (struct memory_handle
*)(&buffer
[newpos
]);
496 if (src
== first_handle
) {
500 struct memory_handle
*m
= first_handle
;
501 while (m
&& m
->next
!= src
) {
504 if (m
&& m
->next
== src
) {
507 mutex_unlock(&llist_mod_mutex
);
508 mutex_unlock(&llist_mutex
);
514 /* Update the cache to prevent it from keeping the old location of h */
515 if (src
== cached_handle
)
516 cached_handle
= dest
;
518 /* the cur_handle pointer might need updating */
519 if (src
== cur_handle
)
523 /* Copying routine takes into account that the handles have a
524 * distance between each other which is a multiple of four. Faster 2 word
525 * copy may be ok but do this for safety and because wrapped copies should
526 * be fairly uncommon */
528 here
= (int32_t *)((ringbuf_add(oldpos
, size_to_move
- 1) & ~3)+ (intptr_t)buffer
);
529 there
=(int32_t *)((ringbuf_add(newpos
, size_to_move
- 1) & ~3)+ (intptr_t)buffer
);
530 end
= (int32_t *)(( intptr_t)buffer
+ buffer_len
- 4);
531 begin
=(int32_t *)buffer
;
533 n
= (size_to_move
& ~3)/4;
535 if ( overlap_old
> 0 || overlap
> 0 ) {
536 /* Old or moved handle wraps */
545 /* both handles do not wrap */
546 memmove(dest
,src
,size_to_move
);
550 /* Update the caller with the new location of h and the distance moved */
552 *delta
= final_delta
;
553 mutex_unlock(&llist_mod_mutex
);
554 mutex_unlock(&llist_mutex
);
560 BUFFER SPACE MANAGEMENT
561 =======================
563 update_data_counters: Updates the values in data_counters
564 buffer_is_low : Returns true if the amount of useful data in the buffer is low
565 buffer_handle : Buffer data for a handle
566 reset_handle : Reset write position and data buffer of a handle to its offset
567 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
568 shrink_handle : Free buffer space by moving a handle
569 fill_buffer : Call buffer_handle for all handles that have data to buffer
571 These functions are used by the buffering thread to manage buffer space.
574 static void update_data_counters(void)
576 struct memory_handle
*m
= find_handle(base_handle_id
);
577 bool is_useful
= m
==NULL
;
581 size_t remaining
= 0;
584 mutex_lock(&llist_mutex
);
588 buffered
+= m
->available
;
589 wasted
+= ringbuf_sub(m
->ridx
, m
->data
);
590 remaining
+= m
->filerem
;
592 if (m
->id
== base_handle_id
)
596 useful
+= ringbuf_sub(m
->widx
, m
->ridx
);
601 mutex_unlock(&llist_mutex
);
603 data_counters
.buffered
= buffered
;
604 data_counters
.wasted
= wasted
;
605 data_counters
.remaining
= remaining
;
606 data_counters
.useful
= useful
;
609 static inline bool buffer_is_low(void)
611 update_data_counters();
612 return data_counters
.useful
< (conf_watermark
/ 2);
615 /* Buffer data for the given handle.
616 Return whether or not the buffering should continue explicitly. */
617 static bool buffer_handle(int handle_id
)
619 logf("buffer_handle(%d)", handle_id
);
620 struct memory_handle
*h
= find_handle(handle_id
);
626 if (h
->filerem
== 0) {
627 /* nothing left to buffer */
631 if (h
->fd
< 0) /* file closed, reopen */
634 h
->fd
= open(h
->path
, O_RDONLY
);
638 /* could not open the file, truncate it where it is */
639 h
->filesize
-= h
->filerem
;
645 lseek(h
->fd
, h
->offset
, SEEK_SET
);
650 if (h
->type
== TYPE_ID3
)
652 if (!get_metadata((struct mp3entry
*)(buffer
+ h
->data
), h
->fd
, h
->path
))
654 /* metadata parsing failed: clear the buffer. */
655 memset(buffer
+ h
->data
, 0, sizeof(struct mp3entry
));
660 h
->available
= sizeof(struct mp3entry
);
661 h
->widx
+= sizeof(struct mp3entry
);
662 send_event(BUFFER_EVENT_FINISHED
, &h
->id
);
666 while (h
->filerem
> 0 && !stop
)
668 /* max amount to copy */
669 size_t copy_n
= MIN( MIN(h
->filerem
, BUFFERING_DEFAULT_FILECHUNK
),
670 buffer_len
- h
->widx
);
673 uintptr_t next_handle
= ringbuf_offset(h
->next
);
675 /* stop copying if it would overwrite the reading position */
676 if (ringbuf_add_cross(h
->widx
, copy_n
, buf_ridx
) >= 0)
679 /* FIXME: This would overwrite the next handle
680 * If this is true, then there's a handle even though we have still
681 * data to buffer. This should NEVER EVER happen! (but it does :( ) */
682 if (h
->next
&& (overlap
683 = ringbuf_add_cross(h
->widx
, copy_n
, next_handle
)) > 0)
685 /* stop buffering data for now and post-pone buffering the rest */
687 DEBUGF( "%s(): Preventing handle corruption: h1.id:%d h2.id:%d"
688 " copy_n:%lu overlap:%ld h1.filerem:%lu\n", __func__
,
689 h
->id
, h
->next
->id
, (unsigned long)copy_n
, (long)overlap
,
690 (unsigned long)h
->filerem
);
694 /* rc is the actual amount read */
695 int rc
= read(h
->fd
, &buffer
[h
->widx
], copy_n
);
699 /* Some kind of filesystem error, maybe recoverable if not codec */
700 if (h
->type
== TYPE_CODEC
) {
701 logf("Partial codec");
705 DEBUGF("File ended %ld bytes early\n", (long)h
->filerem
);
706 h
->filesize
-= h
->filerem
;
712 h
->widx
= ringbuf_add(h
->widx
, rc
);
718 /* If this is a large file, see if we need to break or give the codec
720 if (h
->type
== TYPE_PACKET_AUDIO
&&
721 pcmbuf_is_lowdata() && !buffer_is_low())
730 if (!queue_empty(&buffering_queue
))
734 if (h
->filerem
== 0) {
735 /* finished buffering the file */
738 send_event(BUFFER_EVENT_FINISHED
, &h
->id
);
744 /* Reset writing position and data buffer of a handle to its current offset.
745 Use this after having set the new offset to use. */
746 static void reset_handle(int handle_id
)
748 size_t alignment_pad
;
750 logf("reset_handle(%d)", handle_id
);
752 struct memory_handle
*h
= find_handle(handle_id
);
756 /* Align to desired storage alignment */
757 alignment_pad
= STORAGE_OVERLAP(h
->offset
- (size_t)(&buffer
[h
->start
]));
758 h
->ridx
= h
->widx
= h
->data
= ringbuf_add(h
->start
, alignment_pad
);
763 h
->filerem
= h
->filesize
- h
->offset
;
766 lseek(h
->fd
, h
->offset
, SEEK_SET
);
770 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
771 static void rebuffer_handle(int handle_id
, size_t newpos
)
773 struct memory_handle
*h
= find_handle(handle_id
);
777 /* When seeking foward off of the buffer, if it is a short seek don't
778 rebuffer the whole track, just read enough to satisfy */
779 if (newpos
> h
->offset
&& newpos
- h
->offset
< BUFFERING_DEFAULT_FILECHUNK
)
781 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id
);
782 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, handle_id
);
783 h
->ridx
= h
->data
+ newpos
;
789 /* Reset the handle to its new offset */
790 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id
);
791 queue_send(&buffering_queue
, Q_RESET_HANDLE
, handle_id
);
793 uintptr_t next
= ringbuf_offset(h
->next
);
794 if (ringbuf_sub(next
, h
->data
) < h
->filesize
- newpos
)
796 /* There isn't enough space to rebuffer all of the track from its new
797 offset, so we ask the user to free some */
798 DEBUGF("%s(): space is needed\n", __func__
);
799 send_event(BUFFER_EVENT_REBUFFER
, &handle_id
);
802 /* Now we ask for a rebuffer */
803 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id
);
804 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, handle_id
);
807 static bool close_handle(int handle_id
)
809 struct memory_handle
*h
= find_handle(handle_id
);
811 /* If the handle is not found, it is closed */
820 /* rm_handle returns true unless the handle somehow persists after exit */
824 /* Free buffer space by moving the handle struct right before the useful
825 part of its data buffer or by moving all the data. */
826 static void shrink_handle(struct memory_handle
*h
)
833 if (h
->next
&& h
->filerem
== 0 &&
834 (h
->type
== TYPE_ID3
|| h
->type
== TYPE_CUESHEET
||
835 h
->type
== TYPE_BITMAP
|| h
->type
== TYPE_CODEC
||
836 h
->type
== TYPE_ATOMIC_AUDIO
))
838 /* metadata handle: we can move all of it */
839 uintptr_t handle_distance
=
840 ringbuf_sub(ringbuf_offset(h
->next
), h
->data
);
841 delta
= handle_distance
- h
->available
;
843 /* The value of delta might change for alignment reasons */
844 if (!move_handle(&h
, &delta
, h
->available
, h
->type
==TYPE_CODEC
))
847 size_t olddata
= h
->data
;
848 h
->data
= ringbuf_add(h
->data
, delta
);
849 h
->ridx
= ringbuf_add(h
->ridx
, delta
);
850 h
->widx
= ringbuf_add(h
->widx
, delta
);
852 if (h
->type
== TYPE_ID3
&& h
->filesize
== sizeof(struct mp3entry
)) {
853 /* when moving an mp3entry we need to readjust its pointers. */
854 adjust_mp3entry((struct mp3entry
*)&buffer
[h
->data
],
855 (void *)&buffer
[h
->data
],
856 (const void *)&buffer
[olddata
]);
857 } else if (h
->type
== TYPE_BITMAP
) {
858 /* adjust the bitmap's pointer */
859 struct bitmap
*bmp
= (struct bitmap
*)&buffer
[h
->data
];
860 bmp
->data
= &buffer
[h
->data
+ sizeof(struct bitmap
)];
865 /* only move the handle struct */
866 delta
= ringbuf_sub(h
->ridx
, h
->data
);
867 if (!move_handle(&h
, &delta
, 0, true))
870 h
->data
= ringbuf_add(h
->data
, delta
);
871 h
->start
= ringbuf_add(h
->start
, delta
);
872 h
->available
-= delta
;
877 /* Fill the buffer by buffering as much data as possible for handles that still
878 have data left to buffer
879 Return whether or not to continue filling after this */
880 static bool fill_buffer(void)
882 logf("fill_buffer()");
883 struct memory_handle
*m
;
884 shrink_handle(first_handle
);
886 while (queue_empty(&buffering_queue
) && m
) {
887 if (m
->filerem
> 0) {
888 if (!buffer_handle(m
->id
)) {
901 /* only spin the disk down if the filling wasn't interrupted by an
902 event arriving in the queue. */
909 /* Given a file descriptor to a bitmap file, write the bitmap data to the
910 buffer, with a struct bitmap and the actual data immediately following.
911 Return value is the total size (struct + data). */
912 static int load_image(int fd
, const char *path
, struct dim
*dim
)
915 struct bitmap
*bmp
= (struct bitmap
*)&buffer
[buf_widx
];
917 /* get the desired image size */
918 bmp
->width
= dim
->width
, bmp
->height
= dim
->height
;
919 /* FIXME: alignment may be needed for the data buffer. */
920 bmp
->data
= &buffer
[buf_widx
+ sizeof(struct bitmap
)];
924 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
925 bmp
->maskdata
= NULL
;
928 int free
= (int)MIN(buffer_len
- BUF_USED
, buffer_len
- buf_widx
)
929 - sizeof(struct bitmap
);
932 int pathlen
= strlen(path
);
933 if (strcmp(path
+ pathlen
- 4, ".bmp"))
934 rc
= read_jpeg_fd(fd
, bmp
, free
, FORMAT_NATIVE
|FORMAT_DITHER
|
935 FORMAT_RESIZE
|FORMAT_KEEP_ASPECT
, NULL
);
938 rc
= read_bmp_fd(fd
, bmp
, free
, FORMAT_NATIVE
|FORMAT_DITHER
|
939 FORMAT_RESIZE
|FORMAT_KEEP_ASPECT
, NULL
);
940 return rc
+ (rc
> 0 ? sizeof(struct bitmap
) : 0);
946 MAIN BUFFERING API CALLS
947 ========================
949 bufopen : Request the opening of a new handle for a file
950 bufalloc : Open a new handle for data other than a file.
951 bufclose : Close an open handle
952 bufseek : Set the read pointer in a handle
953 bufadvance : Move the read pointer in a handle
954 bufread : Copy data from a handle into a given buffer
955 bufgetdata : Give a pointer to the handle's data
957 These functions are exported, to allow interaction with the buffer.
958 They take care of the content of the structs, and rely on the linked list
959 management functions for all the actual handle management work.
963 /* Reserve space in the buffer for a file.
964 filename: name of the file to open
965 offset: offset at which to start buffering the file, useful when the first
966 (offset-1) bytes of the file aren't needed.
967 type: one of the data types supported (audio, image, cuesheet, others
968 user_data: user data passed possibly passed in subcalls specific to a
969 data_type (only used for image (albumart) buffering so far )
970 return value: <0 if the file cannot be opened, or one file already
971 queued to be opened, otherwise the handle for the file in the buffer
973 int bufopen(const char *file
, size_t offset
, enum data_type type
,
976 #ifndef HAVE_ALBUMART
977 /* currently only used for aa loading */
980 if (type
== TYPE_ID3
)
982 /* ID3 case: allocate space, init the handle and return. */
984 struct memory_handle
*h
= add_handle(sizeof(struct mp3entry
), false, true);
986 return ERR_BUFFER_FULL
;
989 h
->filesize
= sizeof(struct mp3entry
);
990 h
->filerem
= sizeof(struct mp3entry
);
997 strlcpy(h
->path
, file
, MAX_PATH
);
999 buf_widx
+= sizeof(struct mp3entry
); /* safe because the handle
1002 /* Inform the buffering thread that we added a handle */
1003 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
1004 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
1009 /* Other cases: there is a little more work. */
1010 int fd
= open(file
, O_RDONLY
);
1012 return ERR_FILE_ERROR
;
1014 size_t size
= filesize(fd
);
1015 bool can_wrap
= type
==TYPE_PACKET_AUDIO
|| type
==TYPE_CODEC
;
1017 size_t adjusted_offset
= offset
;
1018 if (adjusted_offset
> size
)
1019 adjusted_offset
= 0;
1021 /* Reserve extra space because alignment can move data forward */
1022 size_t padded_size
= STORAGE_PAD(size
-adjusted_offset
);
1023 struct memory_handle
*h
= add_handle(padded_size
, can_wrap
, false);
1026 DEBUGF("%s(): failed to add handle\n", __func__
);
1028 return ERR_BUFFER_FULL
;
1031 strlcpy(h
->path
, file
, MAX_PATH
);
1032 h
->offset
= adjusted_offset
;
1034 /* Don't bother to storage align bitmaps because they are not
1035 * loaded directly into the buffer.
1037 if (type
!= TYPE_BITMAP
)
1039 size_t alignment_pad
;
1041 /* Remember where data area starts, for use by reset_handle */
1042 h
->start
= buf_widx
;
1044 /* Align to desired storage alignment */
1045 alignment_pad
= STORAGE_OVERLAP(adjusted_offset
- (size_t)(&buffer
[buf_widx
]));
1046 buf_widx
= ringbuf_add(buf_widx
, alignment_pad
);
1056 #ifdef HAVE_ALBUMART
1057 if (type
== TYPE_BITMAP
)
1059 /* Bitmap file: we load the data instead of the file */
1061 mutex_lock(&llist_mod_mutex
); /* Lock because load_bitmap yields */
1062 rc
= load_image(fd
, file
, (struct dim
*)user_data
);
1063 mutex_unlock(&llist_mod_mutex
);
1068 return ERR_FILE_ERROR
;
1073 h
->widx
= buf_widx
+ rc
; /* safe because the data doesn't wrap */
1074 buf_widx
+= rc
; /* safe too */
1079 h
->filerem
= size
- adjusted_offset
;
1085 if (type
== TYPE_CUESHEET
) {
1087 /* Immediately start buffering those */
1088 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h
->id
);
1089 queue_send(&buffering_queue
, Q_BUFFER_HANDLE
, h
->id
);
1091 /* Other types will get buffered in the course of normal operations */
1095 /* Inform the buffering thread that we added a handle */
1096 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h
->id
);
1097 queue_post(&buffering_queue
, Q_HANDLE_ADDED
, h
->id
);
1100 logf("bufopen: new hdl %d", h
->id
);
1104 /* Open a new handle from data that needs to be copied from memory.
1105 src is the source buffer from which to copy data. It can be NULL to simply
1106 reserve buffer space.
1107 size is the requested size. The call will only be successful if the
1108 requested amount of data can entirely fit in the buffer without wrapping.
1109 Return value is the handle id for success or <0 for failure.
1111 int bufalloc(const void *src
, size_t size
, enum data_type type
)
1113 struct memory_handle
*h
= add_handle(size
, false, true);
1116 return ERR_BUFFER_FULL
;
1119 if (type
== TYPE_ID3
&& size
== sizeof(struct mp3entry
)) {
1120 /* specially take care of struct mp3entry */
1121 copy_mp3entry((struct mp3entry
*)&buffer
[buf_widx
],
1122 (const struct mp3entry
*)src
);
1124 memcpy(&buffer
[buf_widx
], src
, size
);
1134 h
->widx
= buf_widx
+ size
; /* this is safe because the data doesn't wrap */
1136 h
->available
= size
;
1139 buf_widx
+= size
; /* safe too */
1141 logf("bufalloc: new hdl %d", h
->id
);
1145 /* Close the handle. Return true for success and false for failure */
1146 bool bufclose(int handle_id
)
1148 logf("bufclose(%d)", handle_id
);
1150 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id
);
1151 return queue_send(&buffering_queue
, Q_CLOSE_HANDLE
, handle_id
);
1154 /* Set reading index in handle (relatively to the start of the file).
1155 Access before the available data will trigger a rebuffer.
1156 Return 0 for success and < 0 for failure:
1157 -1 if the handle wasn't found
1158 -2 if the new requested position was beyond the end of the file
1160 int bufseek(int handle_id
, size_t newpos
)
1162 struct memory_handle
*h
= find_handle(handle_id
);
1164 return ERR_HANDLE_NOT_FOUND
;
1166 if (newpos
> h
->filesize
) {
1167 /* access beyond the end of the file */
1168 return ERR_INVALID_VALUE
;
1170 else if (newpos
< h
->offset
|| h
->offset
+ h
->available
< newpos
) {
1171 /* access before or after buffered data. A rebuffer is needed. */
1172 rebuffer_handle(handle_id
, newpos
);
1175 h
->ridx
= ringbuf_add(h
->data
, newpos
- h
->offset
);
1180 /* Advance the reading index in a handle (relatively to its current position).
1181 Return 0 for success and < 0 for failure */
1182 int bufadvance(int handle_id
, off_t offset
)
1184 const struct memory_handle
*h
= find_handle(handle_id
);
1186 return ERR_HANDLE_NOT_FOUND
;
1188 size_t newpos
= h
->offset
+ ringbuf_sub(h
->ridx
, h
->data
) + offset
;
1189 return bufseek(handle_id
, newpos
);
1192 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1193 * actual amount of data available for reading. This function explicitly
1194 * does not check the validity of the input handle. It does do range checks
1195 * on size and returns a valid (and explicit) amount of data for reading */
1196 static struct memory_handle
*prep_bufdata(int handle_id
, size_t *size
,
1197 bool guardbuf_limit
)
1199 struct memory_handle
*h
= find_handle(handle_id
);
1203 size_t avail
= ringbuf_sub(h
->widx
, h
->ridx
);
1205 if (avail
== 0 && h
->filerem
== 0)
1207 /* File is finished reading */
1212 if (*size
== 0 || *size
> avail
+ h
->filerem
)
1213 *size
= avail
+ h
->filerem
;
1215 if (guardbuf_limit
&& h
->type
== TYPE_PACKET_AUDIO
&& *size
> GUARD_BUFSIZE
)
1217 logf("data request > guardbuf");
1218 /* If more than the size of the guardbuf is requested and this is a
1219 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1220 *size
= MIN(*size
, buffer_len
- h
->ridx
+ GUARD_BUFSIZE
);
1221 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1224 if (h
->filerem
> 0 && avail
< *size
)
1226 /* Data isn't ready. Request buffering */
1227 buf_request_buffer_handle(handle_id
);
1228 /* Wait for the data to be ready */
1232 /* it is not safe for a non-buffering thread to sleep while
1233 * holding a handle */
1234 h
= find_handle(handle_id
);
1237 avail
= ringbuf_sub(h
->widx
, h
->ridx
);
1239 while (h
->filerem
> 0 && avail
< *size
);
1242 *size
= MIN(*size
,avail
);
1246 /* Copy data from the given handle to the dest buffer.
1247 Return the number of bytes copied or < 0 for failure (handle not found).
1248 The caller is blocked until the requested amount of data is available.
1250 ssize_t
bufread(int handle_id
, size_t size
, void *dest
)
1252 const struct memory_handle
*h
;
1253 size_t adjusted_size
= size
;
1255 h
= prep_bufdata(handle_id
, &adjusted_size
, false);
1257 return ERR_HANDLE_NOT_FOUND
;
1259 if (h
->ridx
+ adjusted_size
> buffer_len
)
1261 /* the data wraps around the end of the buffer */
1262 size_t read
= buffer_len
- h
->ridx
;
1263 memcpy(dest
, &buffer
[h
->ridx
], read
);
1264 memcpy(dest
+read
, buffer
, adjusted_size
- read
);
1268 memcpy(dest
, &buffer
[h
->ridx
], adjusted_size
);
1271 return adjusted_size
;
1274 /* Update the "data" pointer to make the handle's data available to the caller.
1275 Return the length of the available linear data or < 0 for failure (handle
1277 The caller is blocked until the requested amount of data is available.
1278 size is the amount of linear data requested. it can be 0 to get as
1280 The guard buffer may be used to provide the requested size. This means it's
1281 unsafe to request more than the size of the guard buffer.
1283 ssize_t
bufgetdata(int handle_id
, size_t size
, void **data
)
1285 const struct memory_handle
*h
;
1286 size_t adjusted_size
= size
;
1288 h
= prep_bufdata(handle_id
, &adjusted_size
, true);
1290 return ERR_HANDLE_NOT_FOUND
;
1292 if (h
->ridx
+ adjusted_size
> buffer_len
)
1294 /* the data wraps around the end of the buffer :
1295 use the guard buffer to provide the requested amount of data. */
1296 size_t copy_n
= h
->ridx
+ adjusted_size
- buffer_len
;
1297 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1298 so copy_n <= GUARD_BUFSIZE */
1299 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1303 *data
= &buffer
[h
->ridx
];
1305 return adjusted_size
;
1308 ssize_t
bufgettail(int handle_id
, size_t size
, void **data
)
1312 const struct memory_handle
*h
;
1314 h
= find_handle(handle_id
);
1317 return ERR_HANDLE_NOT_FOUND
;
1320 return ERR_HANDLE_NOT_DONE
;
1322 /* We don't support tail requests of > guardbuf_size, for simplicity */
1323 if (size
> GUARD_BUFSIZE
)
1324 return ERR_INVALID_VALUE
;
1326 tidx
= ringbuf_sub(h
->widx
, size
);
1328 if (tidx
+ size
> buffer_len
)
1330 size_t copy_n
= tidx
+ size
- buffer_len
;
1331 memcpy(guard_buffer
, (const unsigned char *)buffer
, copy_n
);
1334 *data
= &buffer
[tidx
];
1338 ssize_t
bufcuttail(int handle_id
, size_t size
)
1340 struct memory_handle
*h
;
1341 size_t adjusted_size
= size
;
1343 h
= find_handle(handle_id
);
1346 return ERR_HANDLE_NOT_FOUND
;
1349 return ERR_HANDLE_NOT_DONE
;
1351 if (h
->available
< adjusted_size
)
1352 adjusted_size
= h
->available
;
1354 h
->available
-= adjusted_size
;
1355 h
->filesize
-= adjusted_size
;
1356 h
->widx
= ringbuf_sub(h
->widx
, adjusted_size
);
1357 if (h
== cur_handle
)
1360 return adjusted_size
;
1365 SECONDARY EXPORTED FUNCTIONS
1366 ============================
1370 buf_request_buffer_handle
1373 register_buffering_callback
1374 unregister_buffering_callback
1376 These functions are exported, to allow interaction with the buffer.
1377 They take care of the content of the structs, and rely on the linked list
1378 management functions for all the actual handle management work.
1381 /* Get a handle offset from a pointer */
1382 ssize_t
buf_get_offset(int handle_id
, void *ptr
)
1384 const struct memory_handle
*h
= find_handle(handle_id
);
1386 return ERR_HANDLE_NOT_FOUND
;
1388 return (size_t)ptr
- (size_t)&buffer
[h
->ridx
];
1391 ssize_t
buf_handle_offset(int handle_id
)
1393 const struct memory_handle
*h
= find_handle(handle_id
);
1395 return ERR_HANDLE_NOT_FOUND
;
1399 void buf_request_buffer_handle(int handle_id
)
1401 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id
);
1402 queue_send(&buffering_queue
, Q_START_FILL
, handle_id
);
1405 void buf_set_base_handle(int handle_id
)
1407 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id
);
1408 queue_post(&buffering_queue
, Q_BASE_HANDLE
, handle_id
);
1411 /* Return the amount of buffer space used */
1412 size_t buf_used(void)
1417 void buf_set_watermark(size_t bytes
)
1419 conf_watermark
= bytes
;
1422 static void shrink_buffer_inner(struct memory_handle
*h
)
1427 shrink_buffer_inner(h
->next
);
1432 static void shrink_buffer(void)
1434 logf("shrink_buffer()");
1435 shrink_buffer_inner(first_handle
);
1438 void buffering_thread(void)
1440 bool filling
= false;
1441 struct queue_event ev
;
1449 queue_wait_w_tmo(&buffering_queue
, &ev
, filling
? 5 : HZ
/2);
1454 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev
.data
);
1455 /* Call buffer callbacks here because this is one of two ways
1456 * to begin a full buffer fill */
1457 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1459 queue_reply(&buffering_queue
, 1);
1460 filling
|= buffer_handle((int)ev
.data
);
1463 case Q_BUFFER_HANDLE
:
1464 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev
.data
);
1465 queue_reply(&buffering_queue
, 1);
1466 buffer_handle((int)ev
.data
);
1469 case Q_RESET_HANDLE
:
1470 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev
.data
);
1471 queue_reply(&buffering_queue
, 1);
1472 reset_handle((int)ev
.data
);
1475 case Q_CLOSE_HANDLE
:
1476 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev
.data
);
1477 queue_reply(&buffering_queue
, close_handle((int)ev
.data
));
1480 case Q_HANDLE_ADDED
:
1481 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev
.data
);
1482 /* A handle was added: the disk is spinning, so we can fill */
1487 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev
.data
);
1488 base_handle_id
= (int)ev
.data
;
1491 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
1492 case SYS_USB_CONNECTED
:
1493 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1494 usb_acknowledge(SYS_USB_CONNECTED_ACK
);
1495 usb_wait_for_disconnect(&buffering_queue
);
1500 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1504 update_data_counters();
1506 /* If the buffer is low, call the callbacks to get new data */
1507 if (num_handles
> 0 && data_counters
.useful
<= conf_watermark
)
1508 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1511 /* TODO: This needs to be fixed to use the idle callback, disable it
1512 * for simplicity until its done right */
1514 /* If the disk is spinning, take advantage by filling the buffer */
1515 else if (storage_disk_is_active() && queue_empty(&buffering_queue
))
1517 if (num_handles
> 0 && data_counters
.useful
<= high_watermark
)
1518 send_event(BUFFER_EVENT_BUFFER_LOW
, 0);
1520 if (data_counters
.remaining
> 0 && BUF_USED
<= high_watermark
)
1522 /* This is a new fill, shrink the buffer up first */
1525 filling
= fill_buffer();
1526 update_data_counters();
1532 if (queue_empty(&buffering_queue
)) {
1534 if (data_counters
.remaining
> 0 && BUF_USED
< buffer_len
)
1535 filling
= fill_buffer();
1536 else if (data_counters
.remaining
== 0)
1539 else if (ev
.id
== SYS_TIMEOUT
)
1541 if (data_counters
.remaining
> 0 &&
1542 data_counters
.useful
<= conf_watermark
) {
1544 filling
= fill_buffer();
1551 void buffering_init(void)
1553 mutex_init(&llist_mutex
);
1554 mutex_init(&llist_mod_mutex
);
1555 #ifdef HAVE_PRIORITY_SCHEDULING
1556 /* This behavior not safe atm */
1557 mutex_set_preempt(&llist_mutex
, false);
1558 mutex_set_preempt(&llist_mod_mutex
, false);
1561 conf_watermark
= BUFFERING_DEFAULT_WATERMARK
;
1563 queue_init(&buffering_queue
, true);
1564 buffering_thread_id
= create_thread( buffering_thread
, buffering_stack
,
1565 sizeof(buffering_stack
), CREATE_THREAD_FROZEN
,
1566 buffering_thread_name
IF_PRIO(, PRIORITY_BUFFERING
)
1569 queue_enable_queue_send(&buffering_queue
, &buffering_queue_sender_list
,
1570 buffering_thread_id
);
1573 /* Initialise the buffering subsystem */
1574 bool buffering_reset(char *buf
, size_t buflen
)
1576 if (!buf
|| !buflen
)
1580 buffer_len
= buflen
;
1581 guard_buffer
= buf
+ buflen
;
1586 first_handle
= NULL
;
1588 cached_handle
= NULL
;
1590 base_handle_id
= -1;
1592 /* Set the high watermark as 75% full...or 25% empty :) */
1594 high_watermark
= 3*buflen
/ 4;
1597 thread_thaw(buffering_thread_id
);
1602 void buffering_get_debugdata(struct buffering_debug
*dbgdata
)
1604 update_data_counters();
1605 dbgdata
->num_handles
= num_handles
;
1606 dbgdata
->data_rem
= data_counters
.remaining
;
1607 dbgdata
->wasted_space
= data_counters
.wasted
;
1608 dbgdata
->buffered_data
= data_counters
.buffered
;
1609 dbgdata
->useful_data
= data_counters
.useful
;
1610 dbgdata
->watermark
= conf_watermark
;