Fix WPS backdrop drawing, as instructed by JdGordon.
[kugel-rb.git] / apps / buffering.c
blobf261b5a7112741a692fad4a5a04491cf4620603b
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
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 ****************************************************************************/
22 #include "config.h"
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include "buffering.h"
29 #include "storage.h"
30 #include "system.h"
31 #include "thread.h"
32 #include "file.h"
33 #include "panic.h"
34 #include "memory.h"
35 #include "lcd.h"
36 #include "font.h"
37 #include "button.h"
38 #include "kernel.h"
39 #include "tree.h"
40 #include "debug.h"
41 #include "sprintf.h"
42 #include "settings.h"
43 #include "codecs.h"
44 #include "audio.h"
45 #include "mp3_playback.h"
46 #include "usb.h"
47 #include "screens.h"
48 #include "playlist.h"
49 #include "pcmbuf.h"
50 #include "bmp.h"
51 #include "appevents.h"
52 #include "metadata.h"
53 #ifdef HAVE_ALBUMART
54 #include "albumart.h"
55 #include "jpeg_load.h"
56 #include "bmp.h"
57 #endif
59 #define GUARD_BUFSIZE (32*1024)
61 /* Define LOGF_ENABLE to enable logf output in this file */
62 /*#define LOGF_ENABLE*/
63 #include "logf.h"
65 /* macros to enable logf for queues
66 logging on SYS_TIMEOUT can be disabled */
67 #ifdef SIMULATOR
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 */
72 #endif
74 #ifdef BUFFERING_LOGQUEUES
75 #define LOGFQUEUE logf
76 #else
77 #define LOGFQUEUE(...)
78 #endif
80 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
81 #define LOGFQUEUE_SYS_TIMEOUT logf
82 #else
83 #define LOGFQUEUE_SYS_TIMEOUT(...)
84 #endif
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 start; /* Start index of the handle's data buffer,
112 for use by reset_handle. */
113 size_t data; /* Start index of the handle's data */
114 volatile size_t ridx; /* Read pointer, relative to the main buffer */
115 size_t widx; /* Write pointer */
116 size_t filesize; /* File total length */
117 size_t filerem; /* Remaining bytes of file NOT in buffer */
118 volatile size_t available; /* Available bytes to read from buffer */
119 size_t offset; /* Offset at which we started reading the file */
120 struct memory_handle *next;
122 /* invariant: filesize == offset + available + filerem */
124 static char *buffer;
125 static char *guard_buffer;
127 static size_t buffer_len;
129 static volatile size_t buf_widx; /* current writing position */
130 static volatile size_t buf_ridx; /* current reading position */
131 /* buf_*idx are values relative to the buffer, not real pointers. */
133 /* Configuration */
134 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
135 #if MEM > 8
136 static size_t high_watermark = 0; /* High watermark for rebuffer */
137 #endif
139 /* current memory handle in the linked list. NULL when the list is empty. */
140 static struct memory_handle *cur_handle;
141 /* first memory handle in the linked list. NULL when the list is empty. */
142 static struct memory_handle *first_handle;
144 static int num_handles; /* number of handles in the list */
146 static int base_handle_id;
148 static struct mutex llist_mutex;
149 static struct mutex llist_mod_mutex;
151 /* Handle cache (makes find_handle faster).
152 This is global so that move_handle and rm_handle can invalidate it. */
153 static struct memory_handle *cached_handle = NULL;
155 static struct {
156 size_t remaining; /* Amount of data needing to be buffered */
157 size_t wasted; /* Amount of space available for freeing */
158 size_t buffered; /* Amount of data currently in the buffer */
159 size_t useful; /* Amount of data still useful to the user */
160 } data_counters;
163 /* Messages available to communicate with the buffering thread */
164 enum {
165 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
166 used in a low buffer situation. */
167 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
168 offset (the offset has to be set beforehand) */
169 Q_CLOSE_HANDLE, /* Request closing a handle */
170 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
172 /* Configuration: */
173 Q_START_FILL, /* Request that the buffering thread initiate a buffer
174 fill at its earliest convenience */
175 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
176 (which means the disk is spinning) */
179 /* Buffering thread */
180 static void buffering_thread(void);
181 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
182 static const char buffering_thread_name[] = "buffering";
183 static unsigned int buffering_thread_id = 0;
184 static struct event_queue buffering_queue;
185 static struct queue_sender_list buffering_queue_sender_list;
190 LINKED LIST MANAGEMENT
191 ======================
193 add_handle : Add a handle to the list
194 rm_handle : Remove a handle from the list
195 find_handle : Get a handle pointer from an ID
196 move_handle : Move a handle in the buffer (with or without its data)
198 These functions only handle the linked list structure. They don't touch the
199 contents of the struct memory_handle headers. They also change the buf_*idx
200 pointers when necessary and manage the handle IDs.
202 The first and current (== last) handle are kept track of.
203 A new handle is added at buf_widx and becomes the current one.
204 buf_widx always points to the current writing position for the current handle
205 buf_ridx always points to the location of the first handle.
206 buf_ridx == buf_widx means the buffer is empty.
210 /* Add a new handle to the linked list and return it. It will have become the
211 new current handle.
212 data_size must contain the size of what will be in the handle.
213 can_wrap tells us whether this type of data may wrap on buffer
214 alloc_all tells us if we must immediately be able to allocate data_size
215 returns a valid memory handle if all conditions for allocation are met.
216 NULL if there memory_handle itself cannot be allocated or if the
217 data_size cannot be allocated and alloc_all is set. This function's
218 only potential side effect is to allocate space for the cur_handle
219 if it returns NULL.
221 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
222 bool alloc_all)
224 /* gives each handle a unique id */
225 static int cur_handle_id = 0;
226 size_t shift;
227 size_t new_widx;
228 size_t len;
229 int overlap;
231 if (num_handles >= BUF_MAX_HANDLES)
232 return NULL;
234 mutex_lock(&llist_mutex);
235 mutex_lock(&llist_mod_mutex);
237 if (cur_handle && cur_handle->filerem > 0) {
238 /* the current handle hasn't finished buffering. We can only add
239 a new one if there is already enough free space to finish
240 the buffering. */
241 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
242 if (RINGBUF_ADD_CROSS(cur_handle->widx, req, buf_ridx) >= 0) {
243 /* Not enough space */
244 mutex_unlock(&llist_mod_mutex);
245 mutex_unlock(&llist_mutex);
246 return NULL;
247 } else {
248 /* Allocate the remainder of the space for the current handle */
249 buf_widx = RINGBUF_ADD(cur_handle->widx, cur_handle->filerem);
253 /* align to 4 bytes up */
254 new_widx = RINGBUF_ADD(buf_widx, 3) & ~3;
256 len = data_size + sizeof(struct memory_handle);
258 /* First, will the handle wrap? */
259 /* If the handle would wrap, move to the beginning of the buffer,
260 * or if the data must not but would wrap, move it to the beginning */
261 if( (new_widx + sizeof(struct memory_handle) > buffer_len) ||
262 (!can_wrap && (new_widx + len > buffer_len)) ) {
263 new_widx = 0;
266 /* How far we shifted buf_widx to align things, must be < buffer_len */
267 shift = RINGBUF_SUB(new_widx, buf_widx);
269 /* How much space are we short in the actual ring buffer? */
270 overlap = RINGBUF_ADD_CROSS(buf_widx, shift + len, buf_ridx);
271 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
272 /* Not enough space for required allocations */
273 mutex_unlock(&llist_mod_mutex);
274 mutex_unlock(&llist_mutex);
275 return NULL;
278 /* There is enough space for the required data, advance the buf_widx and
279 * initialize the struct */
280 buf_widx = new_widx;
282 struct memory_handle *new_handle =
283 (struct memory_handle *)(&buffer[buf_widx]);
285 /* only advance the buffer write index of the size of the struct */
286 buf_widx = RINGBUF_ADD(buf_widx, sizeof(struct memory_handle));
288 new_handle->id = cur_handle_id;
289 /* Wrap signed int is safe and 0 doesn't happen */
290 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
291 new_handle->next = NULL;
292 num_handles++;
294 if (!first_handle)
295 /* the new handle is the first one */
296 first_handle = new_handle;
298 if (cur_handle)
299 cur_handle->next = new_handle;
301 cur_handle = new_handle;
303 mutex_unlock(&llist_mod_mutex);
304 mutex_unlock(&llist_mutex);
305 return new_handle;
308 /* Delete a given memory handle from the linked list
309 and return true for success. Nothing is actually erased from memory. */
310 static bool rm_handle(const struct memory_handle *h)
312 if (h == NULL)
313 return true;
315 mutex_lock(&llist_mutex);
316 mutex_lock(&llist_mod_mutex);
318 if (h == first_handle) {
319 first_handle = h->next;
320 if (h == cur_handle) {
321 /* h was the first and last handle: the buffer is now empty */
322 cur_handle = NULL;
323 buf_ridx = buf_widx = 0;
324 } else {
325 /* update buf_ridx to point to the new first handle */
326 buf_ridx = (void *)first_handle - (void *)buffer;
328 } else {
329 struct memory_handle *m = first_handle;
330 /* Find the previous handle */
331 while (m && m->next != h) {
332 m = m->next;
334 if (m && m->next == h) {
335 m->next = h->next;
336 if (h == cur_handle) {
337 cur_handle = m;
338 buf_widx = cur_handle->widx;
340 } else {
341 mutex_unlock(&llist_mod_mutex);
342 mutex_unlock(&llist_mutex);
343 return false;
347 /* Invalidate the cache to prevent it from keeping the old location of h */
348 if (h == cached_handle)
349 cached_handle = NULL;
351 num_handles--;
353 mutex_unlock(&llist_mod_mutex);
354 mutex_unlock(&llist_mutex);
355 return true;
358 /* Return a pointer to the memory handle of given ID.
359 NULL if the handle wasn't found */
360 static struct memory_handle *find_handle(int handle_id)
362 if (handle_id < 0)
363 return NULL;
365 mutex_lock(&llist_mutex);
367 /* simple caching because most of the time the requested handle
368 will either be the same as the last, or the one after the last */
369 if (cached_handle)
371 if (cached_handle->id == handle_id) {
372 mutex_unlock(&llist_mutex);
373 return cached_handle;
374 } else if (cached_handle->next &&
375 (cached_handle->next->id == handle_id)) {
376 cached_handle = cached_handle->next;
377 mutex_unlock(&llist_mutex);
378 return cached_handle;
382 struct memory_handle *m = first_handle;
383 while (m && m->id != handle_id) {
384 m = m->next;
386 /* This condition can only be reached with !m or m->id == handle_id */
387 if (m)
388 cached_handle = m;
390 mutex_unlock(&llist_mutex);
391 return m;
394 /* Move a memory handle and data_size of its data delta bytes along the buffer.
395 delta maximum bytes available to move the handle. If the move is performed
396 it is set to the actual distance moved.
397 data_size is the amount of data to move along with the struct.
398 returns a valid memory_handle if the move is successful
399 NULL if the handle is NULL, the move would be less than the size of
400 a memory_handle after correcting for wraps or if the handle is not
401 found in the linked list for adjustment. This function has no side
402 effects if NULL is returned. */
403 static bool move_handle(struct memory_handle **h, size_t *delta,
404 size_t data_size, bool can_wrap)
406 struct memory_handle *dest;
407 const struct memory_handle *src;
408 int32_t *here;
409 int32_t *there;
410 int32_t *end;
411 int32_t *begin;
412 size_t oldpos;
413 size_t newpos;
414 size_t size_to_move;
415 size_t final_delta = *delta;
416 size_t n;
417 int overlap;
418 int overlap_old;
420 if (h == NULL || (src = *h) == NULL)
421 return false;
423 size_to_move = sizeof(struct memory_handle) + data_size;
425 /* Align to four bytes, down */
426 final_delta &= ~3;
427 if (final_delta < sizeof(struct memory_handle)) {
428 /* It's not legal to move less than the size of the struct */
429 return false;
432 mutex_lock(&llist_mutex);
433 mutex_lock(&llist_mod_mutex);
435 oldpos = (void *)src - (void *)buffer;
436 newpos = RINGBUF_ADD(oldpos, final_delta);
437 overlap = RINGBUF_ADD_CROSS(newpos, size_to_move, buffer_len - 1);
438 overlap_old = RINGBUF_ADD_CROSS(oldpos, size_to_move, buffer_len -1);
440 if (overlap > 0) {
441 /* Some part of the struct + data would wrap, maybe ok */
442 size_t correction = 0;
443 /* If the overlap lands inside the memory_handle */
444 if (!can_wrap) {
445 /* Otherwise the overlap falls in the data area and must all be
446 * backed out. This may become conditional if ever we move
447 * data that is allowed to wrap (ie audio) */
448 correction = overlap;
449 } else if ((unsigned)overlap > data_size) {
450 /* Correct the position and real delta to prevent the struct from
451 * wrapping, this guarantees an aligned delta, I think */
452 correction = overlap - data_size;
454 if (correction) {
455 /* Align correction to four bytes up */
456 correction = (correction + 3) & ~3;
457 if (final_delta < correction + sizeof(struct memory_handle)) {
458 /* Delta cannot end up less than the size of the struct */
459 mutex_unlock(&llist_mod_mutex);
460 mutex_unlock(&llist_mutex);
461 return false;
463 newpos -= correction;
464 overlap -= correction;/* Used below to know how to split the data */
465 final_delta -= correction;
469 dest = (struct memory_handle *)(&buffer[newpos]);
471 if (src == first_handle) {
472 first_handle = dest;
473 buf_ridx = newpos;
474 } else {
475 struct memory_handle *m = first_handle;
476 while (m && m->next != src) {
477 m = m->next;
479 if (m && m->next == src) {
480 m->next = dest;
481 } else {
482 mutex_unlock(&llist_mod_mutex);
483 mutex_unlock(&llist_mutex);
484 return false;
489 /* Update the cache to prevent it from keeping the old location of h */
490 if (src == cached_handle)
491 cached_handle = dest;
493 /* the cur_handle pointer might need updating */
494 if (src == cur_handle)
495 cur_handle = dest;
498 /* Copying routine takes into account that the handles have a
499 * distance between each other which is a multiple of four. Faster 2 word
500 * copy may be ok but do this for safety and because wrapped copies should
501 * be fairly uncommon */
503 here = (int32_t *)((RINGBUF_ADD(oldpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
504 there =(int32_t *)((RINGBUF_ADD(newpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
505 end = (int32_t *)(( intptr_t)buffer + buffer_len - 4);
506 begin =(int32_t *)buffer;
508 n = (size_to_move & ~3)/4;
510 if ( overlap_old > 0 || overlap > 0 ) {
511 /* Old or moved handle wraps */
512 while (n--) {
513 if (here < begin)
514 here = end;
515 if (there < begin)
516 there = end;
517 *there-- = *here--;
519 } else {
520 /* both handles do not wrap */
521 memmove(dest,src,size_to_move);
525 /* Update the caller with the new location of h and the distance moved */
526 *h = dest;
527 *delta = final_delta;
528 mutex_unlock(&llist_mod_mutex);
529 mutex_unlock(&llist_mutex);
530 return dest;
535 BUFFER SPACE MANAGEMENT
536 =======================
538 update_data_counters: Updates the values in data_counters
539 buffer_is_low : Returns true if the amount of useful data in the buffer is low
540 buffer_handle : Buffer data for a handle
541 reset_handle : Reset write position and data buffer of a handle to its offset
542 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
543 shrink_handle : Free buffer space by moving a handle
544 fill_buffer : Call buffer_handle for all handles that have data to buffer
546 These functions are used by the buffering thread to manage buffer space.
549 static void update_data_counters(void)
551 struct memory_handle *m = find_handle(base_handle_id);
552 bool is_useful = m==NULL;
554 size_t buffered = 0;
555 size_t wasted = 0;
556 size_t remaining = 0;
557 size_t useful = 0;
559 mutex_lock(&llist_mutex);
561 m = first_handle;
562 while (m) {
563 buffered += m->available;
564 wasted += RINGBUF_SUB(m->ridx, m->data);
565 remaining += m->filerem;
567 if (m->id == base_handle_id)
568 is_useful = true;
570 if (is_useful)
571 useful += RINGBUF_SUB(m->widx, m->ridx);
573 m = m->next;
576 mutex_unlock(&llist_mutex);
578 data_counters.buffered = buffered;
579 data_counters.wasted = wasted;
580 data_counters.remaining = remaining;
581 data_counters.useful = useful;
584 static inline bool buffer_is_low(void)
586 update_data_counters();
587 return data_counters.useful < (conf_watermark / 2);
590 /* Buffer data for the given handle.
591 Return whether or not the buffering should continue explicitly. */
592 static bool buffer_handle(int handle_id)
594 logf("buffer_handle(%d)", handle_id);
595 struct memory_handle *h = find_handle(handle_id);
596 if (!h)
597 return true;
599 if (h->filerem == 0) {
600 /* nothing left to buffer */
601 return true;
604 if (h->fd < 0) /* file closed, reopen */
606 if (*h->path)
607 h->fd = open(h->path, O_RDONLY);
609 if (h->fd < 0)
611 /* could not open the file, truncate it where it is */
612 h->filesize -= h->filerem;
613 h->filerem = 0;
614 return true;
617 if (h->offset)
618 lseek(h->fd, h->offset, SEEK_SET);
621 trigger_cpu_boost();
623 if (h->type == TYPE_ID3)
625 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
627 /* metadata parsing failed: clear the buffer. */
628 memset(buffer + h->data, 0, sizeof(struct mp3entry));
630 close(h->fd);
631 h->fd = -1;
632 h->filerem = 0;
633 h->available = sizeof(struct mp3entry);
634 h->widx += sizeof(struct mp3entry);
635 send_event(BUFFER_EVENT_FINISHED, &h->id);
636 return true;
639 while (h->filerem > 0)
641 /* max amount to copy */
642 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
643 buffer_len - h->widx);
645 /* stop copying if it would overwrite the reading position */
646 if (RINGBUF_ADD_CROSS(h->widx, copy_n, buf_ridx) >= 0)
647 return false;
649 /* This would read into the next handle, this is broken
650 if (h->next && RINGBUF_ADD_CROSS(h->widx, copy_n,
651 (unsigned)((void *)h->next - (void *)buffer)) > 0) {
652 Try to recover by truncating this file
653 copy_n = RINGBUF_ADD_CROSS(h->widx, copy_n,
654 (unsigned)((void *)h->next - (void *)buffer));
655 h->filerem -= copy_n;
656 h->filesize -= copy_n;
657 logf("buf alloc short %ld", (long)copy_n);
658 if (h->filerem)
659 continue;
660 else
661 break;
662 } */
664 /* rc is the actual amount read */
665 int rc = read(h->fd, &buffer[h->widx], copy_n);
667 if (rc < 0)
669 /* Some kind of filesystem error, maybe recoverable if not codec */
670 if (h->type == TYPE_CODEC) {
671 logf("Partial codec");
672 break;
675 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
676 h->filesize -= h->filerem;
677 h->filerem = 0;
678 break;
681 /* Advance buffer */
682 h->widx = RINGBUF_ADD(h->widx, rc);
683 if (h == cur_handle)
684 buf_widx = h->widx;
685 h->available += rc;
686 h->filerem -= rc;
688 /* If this is a large file, see if we need to break or give the codec
689 * more time */
690 if (h->type == TYPE_PACKET_AUDIO &&
691 pcmbuf_is_lowdata() && !buffer_is_low())
693 sleep(1);
695 else
697 yield();
700 if (!queue_empty(&buffering_queue))
701 break;
704 if (h->filerem == 0) {
705 /* finished buffering the file */
706 close(h->fd);
707 h->fd = -1;
708 send_event(BUFFER_EVENT_FINISHED, &h->id);
711 return true;
714 /* Reset writing position and data buffer of a handle to its current offset.
715 Use this after having set the new offset to use. */
716 static void reset_handle(int handle_id)
718 size_t alignment_pad;
720 logf("reset_handle(%d)", handle_id);
722 struct memory_handle *h = find_handle(handle_id);
723 if (!h)
724 return;
726 /* Align to desired storage alignment */
727 alignment_pad = (h->offset - (size_t)(&buffer[h->start]))
728 & STORAGE_ALIGN_MASK;
729 h->ridx = h->widx = h->data = RINGBUF_ADD(h->start, alignment_pad);
731 if (h == cur_handle)
732 buf_widx = h->widx;
733 h->available = 0;
734 h->filerem = h->filesize - h->offset;
736 if (h->fd >= 0) {
737 lseek(h->fd, h->offset, SEEK_SET);
741 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
742 static void rebuffer_handle(int handle_id, size_t newpos)
744 struct memory_handle *h = find_handle(handle_id);
745 if (!h)
746 return;
748 /* When seeking foward off of the buffer, if it is a short seek don't
749 rebuffer the whole track, just read enough to satisfy */
750 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
752 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
753 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
754 h->ridx = h->data + newpos;
755 return;
758 h->offset = newpos;
760 /* Reset the handle to its new offset */
761 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
762 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
764 size_t next = (unsigned)((void *)h->next - (void *)buffer);
765 if (RINGBUF_SUB(next, h->data) < h->filesize - newpos)
767 /* There isn't enough space to rebuffer all of the track from its new
768 offset, so we ask the user to free some */
769 DEBUGF("rebuffer_handle: space is needed\n");
770 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
773 /* Now we ask for a rebuffer */
774 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
775 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
778 static bool close_handle(int handle_id)
780 struct memory_handle *h = find_handle(handle_id);
782 /* If the handle is not found, it is closed */
783 if (!h)
784 return true;
786 if (h->fd >= 0) {
787 close(h->fd);
788 h->fd = -1;
791 /* rm_handle returns true unless the handle somehow persists after exit */
792 return rm_handle(h);
795 /* Free buffer space by moving the handle struct right before the useful
796 part of its data buffer or by moving all the data. */
797 static void shrink_handle(struct memory_handle *h)
799 size_t delta;
801 if (!h)
802 return;
804 if (h->next && h->filerem == 0 &&
805 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
806 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
807 h->type == TYPE_ATOMIC_AUDIO))
809 /* metadata handle: we can move all of it */
810 size_t handle_distance =
811 RINGBUF_SUB((unsigned)((void *)h->next - (void*)buffer), h->data);
812 delta = handle_distance - h->available;
814 /* The value of delta might change for alignment reasons */
815 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
816 return;
818 size_t olddata = h->data;
819 h->data = RINGBUF_ADD(h->data, delta);
820 h->ridx = RINGBUF_ADD(h->ridx, delta);
821 h->widx = RINGBUF_ADD(h->widx, delta);
823 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
824 /* when moving an mp3entry we need to readjust its pointers. */
825 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
826 (void *)&buffer[h->data],
827 (const void *)&buffer[olddata]);
828 } else if (h->type == TYPE_BITMAP) {
829 /* adjust the bitmap's pointer */
830 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
831 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
834 else
836 /* only move the handle struct */
837 delta = RINGBUF_SUB(h->ridx, h->data);
838 if (!move_handle(&h, &delta, 0, true))
839 return;
841 h->data = RINGBUF_ADD(h->data, delta);
842 h->start = RINGBUF_ADD(h->start, delta);
843 h->available -= delta;
844 h->offset += delta;
848 /* Fill the buffer by buffering as much data as possible for handles that still
849 have data left to buffer
850 Return whether or not to continue filling after this */
851 static bool fill_buffer(void)
853 logf("fill_buffer()");
854 struct memory_handle *m;
855 shrink_handle(first_handle);
856 m = first_handle;
857 while (queue_empty(&buffering_queue) && m) {
858 if (m->filerem > 0) {
859 if (!buffer_handle(m->id)) {
860 m = NULL;
861 break;
864 m = m->next;
867 if (m) {
868 return true;
870 else
872 /* only spin the disk down if the filling wasn't interrupted by an
873 event arriving in the queue. */
874 storage_sleep();
875 return false;
879 #ifdef HAVE_ALBUMART
880 /* Given a file descriptor to a bitmap file, write the bitmap data to the
881 buffer, with a struct bitmap and the actual data immediately following.
882 Return value is the total size (struct + data). */
883 static int load_image(int fd, const char *path, struct dim *dim)
885 int rc;
886 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
888 /* get the desired image size */
889 bmp->width = dim->width, bmp->height = dim->height;
890 /* FIXME: alignment may be needed for the data buffer. */
891 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
892 #ifndef HAVE_JPEG
893 (void) path;
894 #endif
895 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
896 bmp->maskdata = NULL;
897 #endif
899 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
900 - sizeof(struct bitmap);
902 #ifdef HAVE_JPEG
903 int pathlen = strlen(path);
904 if (strcmp(path + pathlen - 4, ".bmp"))
905 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
906 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
907 else
908 #endif
909 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
910 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
911 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
913 #endif
917 MAIN BUFFERING API CALLS
918 ========================
920 bufopen : Request the opening of a new handle for a file
921 bufalloc : Open a new handle for data other than a file.
922 bufclose : Close an open handle
923 bufseek : Set the read pointer in a handle
924 bufadvance : Move the read pointer in a handle
925 bufread : Copy data from a handle into a given buffer
926 bufgetdata : Give a pointer to the handle's data
928 These functions are exported, to allow interaction with the buffer.
929 They take care of the content of the structs, and rely on the linked list
930 management functions for all the actual handle management work.
934 /* Reserve space in the buffer for a file.
935 filename: name of the file to open
936 offset: offset at which to start buffering the file, useful when the first
937 (offset-1) bytes of the file aren't needed.
938 type: one of the data types supported (audio, image, cuesheet, others
939 user_data: user data passed possibly passed in subcalls specific to a
940 data_type (only used for image (albumart) buffering so far )
941 return value: <0 if the file cannot be opened, or one file already
942 queued to be opened, otherwise the handle for the file in the buffer
944 int bufopen(const char *file, size_t offset, enum data_type type,
945 void *user_data)
947 #ifndef HAVE_ALBUMART
948 /* currently only used for aa loading */
949 (void)user_data;
950 #endif
951 if (type == TYPE_ID3)
953 /* ID3 case: allocate space, init the handle and return. */
955 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
956 if (!h)
957 return ERR_BUFFER_FULL;
959 h->fd = -1;
960 h->filesize = sizeof(struct mp3entry);
961 h->filerem = sizeof(struct mp3entry);
962 h->offset = 0;
963 h->data = buf_widx;
964 h->ridx = buf_widx;
965 h->widx = buf_widx;
966 h->available = 0;
967 h->type = type;
968 strlcpy(h->path, file, MAX_PATH);
970 buf_widx += sizeof(struct mp3entry); /* safe because the handle
971 can't wrap */
973 /* Inform the buffering thread that we added a handle */
974 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
975 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
977 return h->id;
980 /* Other cases: there is a little more work. */
982 int fd = open(file, O_RDONLY);
983 if (fd < 0)
984 return ERR_FILE_ERROR;
986 size_t size = filesize(fd);
987 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
989 size_t adjusted_offset = offset;
990 if (adjusted_offset > size)
991 adjusted_offset = 0;
993 /* Reserve extra space because alignment can move data forward */
994 struct memory_handle *h = add_handle(size-adjusted_offset+STORAGE_ALIGN_MASK,
995 can_wrap, false);
996 if (!h)
998 DEBUGF("bufopen: failed to add handle\n");
999 close(fd);
1000 return ERR_BUFFER_FULL;
1003 strlcpy(h->path, file, MAX_PATH);
1004 h->offset = adjusted_offset;
1006 /* Don't bother to storage align bitmaps because they are not
1007 * loaded directly into the buffer.
1009 if (type != TYPE_BITMAP)
1011 size_t alignment_pad;
1013 /* Remember where data area starts, for use by reset_handle */
1014 h->start = buf_widx;
1016 /* Align to desired storage alignment */
1017 alignment_pad = (adjusted_offset - (size_t)(&buffer[buf_widx]))
1018 & STORAGE_ALIGN_MASK;
1019 buf_widx = RINGBUF_ADD(buf_widx, alignment_pad);
1022 h->ridx = buf_widx;
1023 h->widx = buf_widx;
1024 h->data = buf_widx;
1025 h->available = 0;
1026 h->filerem = 0;
1027 h->type = type;
1029 #ifdef HAVE_ALBUMART
1030 if (type == TYPE_BITMAP)
1032 /* Bitmap file: we load the data instead of the file */
1033 int rc;
1034 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1035 rc = load_image(fd, file, (struct dim*)user_data);
1036 mutex_unlock(&llist_mod_mutex);
1037 if (rc <= 0)
1039 rm_handle(h);
1040 close(fd);
1041 return ERR_FILE_ERROR;
1043 h->filerem = 0;
1044 h->filesize = rc;
1045 h->available = rc;
1046 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1047 buf_widx += rc; /* safe too */
1049 else
1050 #endif
1052 h->filerem = size - adjusted_offset;
1053 h->filesize = size;
1054 h->available = 0;
1055 h->widx = buf_widx;
1058 if (type == TYPE_CUESHEET) {
1059 h->fd = fd;
1060 /* Immediately start buffering those */
1061 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1062 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1063 } else {
1064 /* Other types will get buffered in the course of normal operations */
1065 h->fd = -1;
1066 close(fd);
1068 /* Inform the buffering thread that we added a handle */
1069 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1070 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1073 logf("bufopen: new hdl %d", h->id);
1074 return h->id;
1077 /* Open a new handle from data that needs to be copied from memory.
1078 src is the source buffer from which to copy data. It can be NULL to simply
1079 reserve buffer space.
1080 size is the requested size. The call will only be successful if the
1081 requested amount of data can entirely fit in the buffer without wrapping.
1082 Return value is the handle id for success or <0 for failure.
1084 int bufalloc(const void *src, size_t size, enum data_type type)
1086 struct memory_handle *h = add_handle(size, false, true);
1088 if (!h)
1089 return ERR_BUFFER_FULL;
1091 if (src) {
1092 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1093 /* specially take care of struct mp3entry */
1094 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1095 (const struct mp3entry *)src);
1096 } else {
1097 memcpy(&buffer[buf_widx], src, size);
1101 h->fd = -1;
1102 *h->path = 0;
1103 h->filesize = size;
1104 h->filerem = 0;
1105 h->offset = 0;
1106 h->ridx = buf_widx;
1107 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1108 h->data = buf_widx;
1109 h->available = size;
1110 h->type = type;
1112 buf_widx += size; /* safe too */
1114 logf("bufalloc: new hdl %d", h->id);
1115 return h->id;
1118 /* Close the handle. Return true for success and false for failure */
1119 bool bufclose(int handle_id)
1121 logf("bufclose(%d)", handle_id);
1123 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1124 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1127 /* Set reading index in handle (relatively to the start of the file).
1128 Access before the available data will trigger a rebuffer.
1129 Return 0 for success and < 0 for failure:
1130 -1 if the handle wasn't found
1131 -2 if the new requested position was beyond the end of the file
1133 int bufseek(int handle_id, size_t newpos)
1135 struct memory_handle *h = find_handle(handle_id);
1136 if (!h)
1137 return ERR_HANDLE_NOT_FOUND;
1139 if (newpos > h->filesize) {
1140 /* access beyond the end of the file */
1141 return ERR_INVALID_VALUE;
1143 else if (newpos < h->offset || h->offset + h->available < newpos) {
1144 /* access before or after buffered data. A rebuffer is needed. */
1145 rebuffer_handle(handle_id, newpos);
1147 else {
1148 h->ridx = RINGBUF_ADD(h->data, newpos - h->offset);
1150 return 0;
1153 /* Advance the reading index in a handle (relatively to its current position).
1154 Return 0 for success and < 0 for failure */
1155 int bufadvance(int handle_id, off_t offset)
1157 const struct memory_handle *h = find_handle(handle_id);
1158 if (!h)
1159 return ERR_HANDLE_NOT_FOUND;
1161 size_t newpos = h->offset + RINGBUF_SUB(h->ridx, h->data) + offset;
1162 return bufseek(handle_id, newpos);
1165 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1166 * actual amount of data available for reading. This function explicitly
1167 * does not check the validity of the input handle. It does do range checks
1168 * on size and returns a valid (and explicit) amount of data for reading */
1169 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1170 bool guardbuf_limit)
1172 struct memory_handle *h = find_handle(handle_id);
1173 if (!h)
1174 return NULL;
1176 size_t avail = RINGBUF_SUB(h->widx, h->ridx);
1178 if (avail == 0 && h->filerem == 0)
1180 /* File is finished reading */
1181 *size = 0;
1182 return h;
1185 if (*size == 0 || *size > avail + h->filerem)
1186 *size = avail + h->filerem;
1188 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1190 logf("data request > guardbuf");
1191 /* If more than the size of the guardbuf is requested and this is a
1192 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1193 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1194 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1197 if (h->filerem > 0 && avail < *size)
1199 /* Data isn't ready. Request buffering */
1200 buf_request_buffer_handle(handle_id);
1201 /* Wait for the data to be ready */
1204 sleep(1);
1205 /* it is not safe for a non-buffering thread to sleep while
1206 * holding a handle */
1207 h = find_handle(handle_id);
1208 if (!h)
1209 return NULL;
1210 avail = RINGBUF_SUB(h->widx, h->ridx);
1212 while (h->filerem > 0 && avail < *size);
1215 *size = MIN(*size,avail);
1216 return h;
1219 /* Copy data from the given handle to the dest buffer.
1220 Return the number of bytes copied or < 0 for failure (handle not found).
1221 The caller is blocked until the requested amount of data is available.
1223 ssize_t bufread(int handle_id, size_t size, void *dest)
1225 const struct memory_handle *h;
1226 size_t adjusted_size = size;
1228 h = prep_bufdata(handle_id, &adjusted_size, false);
1229 if (!h)
1230 return ERR_HANDLE_NOT_FOUND;
1232 if (h->ridx + adjusted_size > buffer_len)
1234 /* the data wraps around the end of the buffer */
1235 size_t read = buffer_len - h->ridx;
1236 memcpy(dest, &buffer[h->ridx], read);
1237 memcpy(dest+read, buffer, adjusted_size - read);
1239 else
1241 memcpy(dest, &buffer[h->ridx], adjusted_size);
1244 return adjusted_size;
1247 /* Update the "data" pointer to make the handle's data available to the caller.
1248 Return the length of the available linear data or < 0 for failure (handle
1249 not found).
1250 The caller is blocked until the requested amount of data is available.
1251 size is the amount of linear data requested. it can be 0 to get as
1252 much as possible.
1253 The guard buffer may be used to provide the requested size. This means it's
1254 unsafe to request more than the size of the guard buffer.
1256 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1258 const struct memory_handle *h;
1259 size_t adjusted_size = size;
1261 h = prep_bufdata(handle_id, &adjusted_size, true);
1262 if (!h)
1263 return ERR_HANDLE_NOT_FOUND;
1265 if (h->ridx + adjusted_size > buffer_len)
1267 /* the data wraps around the end of the buffer :
1268 use the guard buffer to provide the requested amount of data. */
1269 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1270 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1271 so copy_n <= GUARD_BUFSIZE */
1272 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1275 if (data)
1276 *data = &buffer[h->ridx];
1278 return adjusted_size;
1281 ssize_t bufgettail(int handle_id, size_t size, void **data)
1283 size_t tidx;
1285 const struct memory_handle *h;
1287 h = find_handle(handle_id);
1289 if (!h)
1290 return ERR_HANDLE_NOT_FOUND;
1292 if (h->filerem)
1293 return ERR_HANDLE_NOT_DONE;
1295 /* We don't support tail requests of > guardbuf_size, for simplicity */
1296 if (size > GUARD_BUFSIZE)
1297 return ERR_INVALID_VALUE;
1299 tidx = RINGBUF_SUB(h->widx, size);
1301 if (tidx + size > buffer_len)
1303 size_t copy_n = tidx + size - buffer_len;
1304 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1307 *data = &buffer[tidx];
1308 return size;
1311 ssize_t bufcuttail(int handle_id, size_t size)
1313 struct memory_handle *h;
1314 size_t adjusted_size = size;
1316 h = find_handle(handle_id);
1318 if (!h)
1319 return ERR_HANDLE_NOT_FOUND;
1321 if (h->filerem)
1322 return ERR_HANDLE_NOT_DONE;
1324 if (h->available < adjusted_size)
1325 adjusted_size = h->available;
1327 h->available -= adjusted_size;
1328 h->filesize -= adjusted_size;
1329 h->widx = RINGBUF_SUB(h->widx, adjusted_size);
1330 if (h == cur_handle)
1331 buf_widx = h->widx;
1333 return adjusted_size;
1338 SECONDARY EXPORTED FUNCTIONS
1339 ============================
1341 buf_get_offset
1342 buf_handle_offset
1343 buf_request_buffer_handle
1344 buf_set_base_handle
1345 buf_used
1346 register_buffering_callback
1347 unregister_buffering_callback
1349 These functions are exported, to allow interaction with the buffer.
1350 They take care of the content of the structs, and rely on the linked list
1351 management functions for all the actual handle management work.
1354 /* Get a handle offset from a pointer */
1355 ssize_t buf_get_offset(int handle_id, void *ptr)
1357 const struct memory_handle *h = find_handle(handle_id);
1358 if (!h)
1359 return ERR_HANDLE_NOT_FOUND;
1361 return (size_t)ptr - (size_t)&buffer[h->ridx];
1364 ssize_t buf_handle_offset(int handle_id)
1366 const struct memory_handle *h = find_handle(handle_id);
1367 if (!h)
1368 return ERR_HANDLE_NOT_FOUND;
1369 return h->offset;
1372 void buf_request_buffer_handle(int handle_id)
1374 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1375 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1378 void buf_set_base_handle(int handle_id)
1380 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1381 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1384 /* Return the amount of buffer space used */
1385 size_t buf_used(void)
1387 return BUF_USED;
1390 void buf_set_watermark(size_t bytes)
1392 conf_watermark = bytes;
1395 static void shrink_buffer_inner(struct memory_handle *h)
1397 if (h == NULL)
1398 return;
1400 shrink_buffer_inner(h->next);
1402 shrink_handle(h);
1405 static void shrink_buffer(void)
1407 logf("shrink_buffer()");
1408 shrink_buffer_inner(first_handle);
1411 void buffering_thread(void)
1413 bool filling = false;
1414 struct queue_event ev;
1416 while (true)
1418 if (!filling) {
1419 cancel_cpu_boost();
1422 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1424 switch (ev.id)
1426 case Q_START_FILL:
1427 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1428 /* Call buffer callbacks here because this is one of two ways
1429 * to begin a full buffer fill */
1430 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1431 shrink_buffer();
1432 queue_reply(&buffering_queue, 1);
1433 filling |= buffer_handle((int)ev.data);
1434 break;
1436 case Q_BUFFER_HANDLE:
1437 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1438 queue_reply(&buffering_queue, 1);
1439 buffer_handle((int)ev.data);
1440 break;
1442 case Q_RESET_HANDLE:
1443 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1444 queue_reply(&buffering_queue, 1);
1445 reset_handle((int)ev.data);
1446 break;
1448 case Q_CLOSE_HANDLE:
1449 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1450 queue_reply(&buffering_queue, close_handle((int)ev.data));
1451 break;
1453 case Q_HANDLE_ADDED:
1454 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1455 /* A handle was added: the disk is spinning, so we can fill */
1456 filling = true;
1457 break;
1459 case Q_BASE_HANDLE:
1460 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1461 base_handle_id = (int)ev.data;
1462 break;
1464 #ifndef SIMULATOR
1465 case SYS_USB_CONNECTED:
1466 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1467 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1468 usb_wait_for_disconnect(&buffering_queue);
1469 break;
1470 #endif
1472 case SYS_TIMEOUT:
1473 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1474 break;
1477 update_data_counters();
1479 /* If the buffer is low, call the callbacks to get new data */
1480 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1481 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1483 #if 0
1484 /* TODO: This needs to be fixed to use the idle callback, disable it
1485 * for simplicity until its done right */
1486 #if MEM > 8
1487 /* If the disk is spinning, take advantage by filling the buffer */
1488 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1490 if (num_handles > 0 && data_counters.useful <= high_watermark)
1491 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1493 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1495 /* This is a new fill, shrink the buffer up first */
1496 if (!filling)
1497 shrink_buffer();
1498 filling = fill_buffer();
1499 update_data_counters();
1502 #endif
1503 #endif
1505 if (queue_empty(&buffering_queue)) {
1506 if (filling) {
1507 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1508 filling = fill_buffer();
1509 else if (data_counters.remaining == 0)
1510 filling = false;
1512 else if (ev.id == SYS_TIMEOUT)
1514 if (data_counters.remaining > 0 &&
1515 data_counters.useful <= conf_watermark) {
1516 shrink_buffer();
1517 filling = fill_buffer();
1524 void buffering_init(void)
1526 mutex_init(&llist_mutex);
1527 mutex_init(&llist_mod_mutex);
1528 #ifdef HAVE_PRIORITY_SCHEDULING
1529 /* This behavior not safe atm */
1530 mutex_set_preempt(&llist_mutex, false);
1531 mutex_set_preempt(&llist_mod_mutex, false);
1532 #endif
1534 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1536 queue_init(&buffering_queue, true);
1537 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1538 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1539 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1540 IF_COP(, CPU));
1542 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1543 buffering_thread_id);
1546 /* Initialise the buffering subsystem */
1547 bool buffering_reset(char *buf, size_t buflen)
1549 if (!buf || !buflen)
1550 return false;
1552 buffer = buf;
1553 /* Preserve alignment when wrapping around */
1554 buffer_len = buflen & ~STORAGE_ALIGN_MASK;
1555 guard_buffer = buf + buflen;
1557 buf_widx = 0;
1558 buf_ridx = 0;
1560 first_handle = NULL;
1561 cur_handle = NULL;
1562 cached_handle = NULL;
1563 num_handles = 0;
1564 base_handle_id = -1;
1566 /* Set the high watermark as 75% full...or 25% empty :) */
1567 #if MEM > 8
1568 high_watermark = 3*buflen / 4;
1569 #endif
1571 thread_thaw(buffering_thread_id);
1573 return true;
1576 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1578 update_data_counters();
1579 dbgdata->num_handles = num_handles;
1580 dbgdata->data_rem = data_counters.remaining;
1581 dbgdata->wasted_space = data_counters.wasted;
1582 dbgdata->buffered_data = data_counters.buffered;
1583 dbgdata->useful_data = data_counters.useful;
1584 dbgdata->watermark = conf_watermark;