Fix Free and Disk size display when SECTOR_SIZE!=512
[kugel-rb.git] / apps / pcmbuf.c
blob975d25442460b1cf1a847c92fae0942450ac93ec
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
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 ****************************************************************************/
21 #include <stdio.h>
22 #include "config.h"
23 #include "system.h"
24 #include "debug.h"
25 #include <kernel.h>
26 #include "pcmbuf.h"
27 #include "pcm.h"
28 #include "playback.h"
30 /* Define LOGF_ENABLE to enable logf output in this file */
31 /*#define LOGF_ENABLE*/
32 #include "logf.h"
33 #ifndef SIMULATOR
34 #include "cpu.h"
35 #endif
36 #include <string.h>
37 #include "settings.h"
38 #include "audio.h"
39 #include "voice_thread.h"
40 #include "dsp.h"
42 #define PCMBUF_TARGET_CHUNK 32768 /* This is the target fill size of chunks
43 on the pcm buffer */
44 #define PCMBUF_MINAVG_CHUNK 24576 /* This is the minimum average size of
45 chunks on the pcm buffer (or we run out
46 of buffer descriptors, which is
47 non-fatal) */
48 #define PCMBUF_MIN_CHUNK 4096 /* We try to never feed a chunk smaller than
49 this to the DMA */
50 #define PCMBUF_MIX_CHUNK 8192 /* This is the maximum size of one packet
51 for mixing (crossfade or voice) */
53 #if MEMORYSIZE > 2
54 /* Keep watermark high for iPods at least (2s) */
55 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
56 #else
57 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 1) /* 0.25 seconds */
58 #endif
60 /* Structure we can use to queue pcm chunks in memory to be played
61 * by the driver code. */
62 struct chunkdesc
64 void *addr;
65 size_t size;
66 struct chunkdesc* link;
67 /* true if last chunk in the track */
68 bool end_of_track;
71 #define NUM_CHUNK_DESCS(bufsize) \
72 ((bufsize) / PCMBUF_MINAVG_CHUNK)
74 /* Size of the PCM buffer. */
75 static size_t pcmbuf_size IDATA_ATTR = 0;
76 static char *pcmbuf_bufend IDATA_ATTR;
77 static char *pcmbuffer IDATA_ATTR;
78 /* Current PCM buffer write index. */
79 static size_t pcmbuffer_pos IDATA_ATTR;
80 /* Amount pcmbuffer_pos will be increased.*/
81 static size_t pcmbuffer_fillpos IDATA_ATTR;
82 static char *fadebuf IDATA_ATTR;
83 static char *voicebuf IDATA_ATTR;
85 static bool end_of_track IDATA_ATTR;
86 bool track_transition IDATA_ATTR;
88 /* Crossfade related state */
89 static bool crossfade_enabled;
90 static bool crossfade_enable_request;
91 static bool crossfade_mixmode;
92 static bool crossfade_active IDATA_ATTR;
93 static bool crossfade_track_change_started IDATA_ATTR;
95 /* Track the current location for processing crossfade */
96 static struct chunkdesc *crossfade_chunk IDATA_ATTR;
97 #ifdef HAVE_CROSSFADE
98 static size_t crossfade_sample IDATA_ATTR;
100 /* Counters for fading in new data */
101 static size_t crossfade_fade_in_total IDATA_ATTR;
102 static size_t crossfade_fade_in_rem IDATA_ATTR;
103 #endif
105 static struct chunkdesc *read_chunk IDATA_ATTR;
106 static struct chunkdesc *read_end_chunk IDATA_ATTR;
107 static struct chunkdesc *write_chunk IDATA_ATTR;
108 static struct chunkdesc *write_end_chunk IDATA_ATTR;
109 static size_t last_chunksize IDATA_ATTR;
111 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
112 static size_t pcmbuf_watermark IDATA_ATTR;
114 static struct chunkdesc *mix_chunk IDATA_ATTR;
115 static size_t pcmbuf_mix_sample IDATA_ATTR;
117 static bool low_latency_mode = false;
118 static bool flush_pcmbuf;
120 #ifdef HAVE_PRIORITY_SCHEDULING
121 static int codec_thread_priority = PRIORITY_PLAYBACK;
122 #endif
124 extern unsigned int codec_thread_id;
126 /* Helpful macros for use in conditionals this assumes some of the above
127 * static variable names */
128 #define NEED_FLUSH(position) \
129 (pcmbuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
130 #define LOW_DATA(quarter_secs) \
131 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
133 #ifdef HAVE_CROSSFADE
134 static void crossfade_start(void);
135 static void flush_crossfade(char *buf, size_t length);
136 #endif
137 static void pcmbuf_finish_crossfade_enable(void);
138 static bool pcmbuf_is_crossfade_enabled(void);
141 /**************************************/
143 /* define this to show detailed chunkdesc usage information on the sim console */
144 /*#define DESC_DEBUG*/
146 #ifndef SIMULATOR
147 #undef DESC_DEBUG
148 #endif
149 #ifdef DESC_DEBUG
150 static struct chunkdesc *first_desc;
151 static bool show_desc_in_use = false;
152 #define DISPLAY_DESC(caller) while(!show_desc(caller))
153 #define DESC_IDX(desc) (desc ? desc - first_desc : -1)
154 #define DESCL_IDX(desc) (desc && desc->link ? desc->link - first_desc : -1)
155 #define SHOW_1ST(desc) if(DESC_IDX (desc)==-1) DEBUGF(" -- "); \
156 else DEBUGF(" %02d ", DESC_IDX(desc))
157 #define SHOW_2ND(desc) if(DESCL_IDX(desc)==-1) DEBUGF("l -- "); \
158 else DEBUGF("l %02d ", DESCL_IDX(desc))
159 #define DESC_SHOW(tag, desc) DEBUGF(tag);SHOW_1ST(desc); \
160 DEBUGF(tag);SHOW_2ND(desc)
162 static bool show_desc(char *caller)
164 if (show_desc_in_use) return false;
165 show_desc_in_use = true;
166 DEBUGF("%-14s\t", caller);
167 DESC_SHOW("r", read_chunk);
168 DESC_SHOW("re", read_end_chunk);
169 DEBUGF(" ");
170 DESC_SHOW("w", write_chunk);
171 DESC_SHOW("we", write_end_chunk);
172 DEBUGF("\n");
173 show_desc_in_use = false;
174 return true;
176 #else
177 #define DISPLAY_DESC(caller) do{}while(0)
178 #endif
181 /* Commit PCM data */
184 * Commit samples waiting to the pcm buffer.
186 static void commit_chunk(void)
188 if (!pcmbuffer_fillpos)
189 return;
191 /* Never use the last buffer descriptor */
192 while (write_chunk == write_end_chunk) {
193 /* If this happens, something is being stupid */
194 if (!pcm_is_playing()) {
195 logf("commit_chunk error");
196 pcmbuf_play_start();
198 /* Let approximately one chunk of data playback */
199 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
202 /* commit the chunk */
204 register size_t size = pcmbuffer_fillpos;
205 /* Grab the next description to write, and change the write pointer */
206 register struct chunkdesc *pcmbuf_current = write_chunk;
207 write_chunk = pcmbuf_current->link;
208 /* Fill in the values in the new buffer chunk */
209 pcmbuf_current->addr = &pcmbuffer[pcmbuffer_pos];
210 pcmbuf_current->size = size;
211 pcmbuf_current->end_of_track = end_of_track;
212 pcmbuf_current->link = NULL;
213 end_of_track = false; /* This is single use only */
215 if (read_chunk != NULL)
217 if (flush_pcmbuf)
219 /* flush! discard all data after the currently playing chunk,
220 and make the current chunk play next */
221 write_end_chunk->link = read_chunk->link;
222 read_chunk->link = pcmbuf_current;
223 while (write_end_chunk->link)
225 write_end_chunk = write_end_chunk->link;
226 pcmbuf_unplayed_bytes -= write_end_chunk->size;
228 flush_pcmbuf = false;
230 /* If there is already a read buffer setup, add to it */
231 else
232 read_end_chunk->link = pcmbuf_current;
234 else
236 /* Otherwise create the buffer */
237 read_chunk = pcmbuf_current;
240 /* This is now the last buffer to read */
241 read_end_chunk = pcmbuf_current;
243 /* Update bytes counters */
244 pcmbuf_unplayed_bytes += size;
246 pcmbuffer_pos += size;
247 if (pcmbuffer_pos >= pcmbuf_size)
248 pcmbuffer_pos -= pcmbuf_size;
250 pcmbuffer_fillpos = 0;
251 DISPLAY_DESC("commit_chunk");
254 #ifdef HAVE_PRIORITY_SCHEDULING
255 static void boost_codec_thread(bool boost)
257 /* Keep voice and codec threads at the same priority or else voice
258 * will starve if the codec thread's priority is boosted. */
259 if (boost)
261 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
262 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
264 if (priority != codec_thread_priority)
266 codec_thread_priority = priority;
267 thread_set_priority(codec_thread_id, priority);
268 voice_thread_set_priority(priority);
271 else if (codec_thread_priority != PRIORITY_PLAYBACK)
273 thread_set_priority(codec_thread_id, PRIORITY_PLAYBACK);
274 voice_thread_set_priority(PRIORITY_PLAYBACK);
275 codec_thread_priority = PRIORITY_PLAYBACK;
278 #else
279 #define boost_codec_thread(boost) do{}while(0)
280 #endif /* HAVE_PRIORITY_SCHEDULING */
282 static bool prepare_insert(size_t length)
284 if (low_latency_mode)
286 /* 1/4s latency. */
287 if (!LOW_DATA(1) && pcm_is_playing())
288 return false;
291 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
292 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
293 return false;
295 /* boost CPU if needed to either fill to watermark or for pre-buffer */
296 if (pcm_is_playing())
298 /* Only codec thread initiates boost - voice boosts the cpu when playing
299 a clip */
300 #ifndef SIMULATOR
301 if (thread_get_current() == codec_thread_id)
302 #endif /* SIMULATOR */
304 if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
306 /* Fill PCM buffer by boosting cpu */
307 trigger_cpu_boost();
308 /* If buffer is critically low, override UI priority, else
309 set back to the original priority. */
310 boost_codec_thread(LOW_DATA(2));
312 else
314 boost_codec_thread(false);
318 /* Disable crossfade if < .5s of audio */
319 if (LOW_DATA(2))
321 crossfade_active = false;
324 else /* pcm_is_playing */
326 trigger_cpu_boost();
328 /* Pre-buffer up to watermark */
329 #if MEMORYSIZE > 2
330 if (!LOW_DATA(4))
331 #else
332 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
333 #endif
335 logf("pcm starting");
336 if (!(audio_status() & AUDIO_STATUS_PAUSE))
337 pcmbuf_play_start();
341 return true;
344 void *pcmbuf_request_buffer(int *count)
346 #ifdef HAVE_CROSSFADE
347 if (crossfade_track_change_started)
348 crossfade_start();
349 #endif
351 if (crossfade_active) {
352 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
353 return fadebuf;
355 else
357 if(prepare_insert(*count << 2))
359 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
360 if (pcmbuf_size - pcmbuffer_index >= PCMBUF_MIN_CHUNK)
362 /* Usual case, there's space here */
363 return &pcmbuffer[pcmbuffer_index];
365 else
367 /* Flush and wrap the buffer */
368 commit_chunk();
369 pcmbuffer_pos = 0;
370 return &pcmbuffer[0];
374 return NULL;
377 void pcmbuf_write_complete(int count)
379 size_t length = (size_t)(unsigned int)count << 2;
380 #ifdef HAVE_CROSSFADE
381 if (crossfade_active)
383 flush_crossfade(fadebuf, length);
384 if (!(crossfade_fade_in_rem || crossfade_chunk))
385 crossfade_active = false;
387 else
388 #endif
390 pcmbuffer_fillpos += length;
392 if (NEED_FLUSH(pcmbuffer_pos + pcmbuffer_fillpos))
393 commit_chunk();
398 /* Init */
400 static inline void init_pcmbuffers(void)
402 #ifdef DESC_DEBUG
403 first_desc = write_chunk;
404 #endif
405 struct chunkdesc *next = write_chunk;
406 next++;
407 write_end_chunk = write_chunk;
408 while ((void *)next < (void *)pcmbuf_bufend) {
409 write_end_chunk->link=next;
410 write_end_chunk=next;
411 next++;
413 DISPLAY_DESC("init");
416 static size_t get_next_required_pcmbuf_size(void)
418 size_t seconds = 1;
420 if (crossfade_enable_request)
421 seconds += global_settings.crossfade_fade_out_delay
422 + global_settings.crossfade_fade_out_duration;
424 #if MEMORYSIZE > 2
425 /* Buffer has to be at least 2s long. */
426 seconds += 2;
427 #endif
428 logf("pcmbuf len: %ld", (long)seconds);
429 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
432 /* Initialize the pcmbuffer the structure looks like this:
433 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
434 size_t pcmbuf_init(unsigned char *bufend)
436 pcmbuf_bufend = bufend;
437 pcmbuf_size = get_next_required_pcmbuf_size();
438 write_chunk = (struct chunkdesc *)pcmbuf_bufend -
439 NUM_CHUNK_DESCS(pcmbuf_size);
440 voicebuf = (char *)write_chunk - PCMBUF_MIX_CHUNK;
441 fadebuf = voicebuf - PCMBUF_MIX_CHUNK;
442 pcmbuffer = fadebuf - pcmbuf_size;
444 init_pcmbuffers();
446 if(track_transition){logf("pcmbuf: (init) track transition false");}
447 end_of_track = false;
448 track_transition = false;
450 pcmbuf_finish_crossfade_enable();
452 pcmbuf_play_stop();
454 return pcmbuf_bufend - pcmbuffer;
458 /* Track change */
460 /* The codec is moving on to the next track, but the current track is
461 * still playing. Set flags to make sure the elapsed time of the current
462 * track is updated properly, and mark the currently written chunk as the
463 * last one in the track. */
464 static void start_gapless_track_change(void)
466 /* we're starting a track transition */
467 track_transition = true;
469 /* mark the last chunk in the track */
470 end_of_track = true;
473 static void start_crossfade_track_change(bool auto_skip)
475 /* Notify the wps that the track change starts now */
476 audio_post_track_change(false);
478 /* Can't do two crossfades at once and, no fade if pcm is off now */
479 if (pcmbuf_is_crossfade_active() || !pcm_is_playing())
481 pcmbuf_play_stop();
482 return;
485 trigger_cpu_boost();
487 /* Not enough data, or crossfade disabled, flush the old data instead */
488 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
490 /* commit everything to this point and keep going, but... */
491 commit_chunk();
492 /* ... when the next chunk commits, throw away everything but itself */
493 flush_pcmbuf = true;
494 return;
497 /* Don't enable mix mode when skipping tracks manually. */
498 crossfade_mixmode = auto_skip && global_settings.crossfade_fade_out_mixmode;
500 crossfade_track_change_started = true;
503 void pcmbuf_start_track_change(bool auto_skip)
505 bool crossfade = false;
506 /* Manual track change (always crossfade or flush audio). */
507 if (!auto_skip)
508 crossfade = true;
510 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
511 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
512 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
514 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
516 if (global_settings.playlist_shuffle)
517 crossfade = true;
519 else
520 crossfade = true;
523 if (crossfade)
524 /* crossfade to next track */
525 start_crossfade_track_change(auto_skip);
526 else
527 /* normal gapless playback. */
528 start_gapless_track_change();
531 /* Called when the last chunk in the track has been played */
532 static void finish_gapless_track_change(void)
534 /* not in a track transition anymore */
535 if(track_transition){logf("pcmbuf: (finish change) track transition false");}
536 track_transition = false;
538 /* notify playback that the track has just finished */
539 audio_post_track_change(true);
543 /* Playback */
545 /** PCM driver callback
546 * This function has 3 major logical parts (separated by brackets both for
547 * readability and variable scoping). The first part performs the
548 * operations related to finishing off the last buffer we fed to the DMA.
549 * The second part detects the end of playlist condition when the pcm
550 * buffer is empty except for uncommitted samples. Then they are committed.
551 * The third part performs the operations involved in sending a new buffer
552 * to the DMA. */
553 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size) ICODE_ATTR;
554 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size)
557 struct chunkdesc *pcmbuf_current = read_chunk;
558 /* Take the finished buffer out of circulation */
559 read_chunk = pcmbuf_current->link;
561 /* if during a track transition, update the elapsed time */
562 if (track_transition)
563 audio_pcmbuf_position_callback(last_chunksize);
565 /* if last buffer in the track, let the audio thread know */
566 if (pcmbuf_current->end_of_track)
567 finish_gapless_track_change();
569 /* Put the finished buffer back into circulation */
570 write_end_chunk->link = pcmbuf_current;
571 write_end_chunk = pcmbuf_current;
573 /* If we've read over the mix chunk while it's still mixing there */
574 if (pcmbuf_current == mix_chunk)
575 mix_chunk = NULL;
576 /* If we've read over the crossfade chunk while it's still fading */
577 if (pcmbuf_current == crossfade_chunk)
578 crossfade_chunk = read_chunk;
582 /* Commit last samples at end of playlist */
583 if (pcmbuffer_fillpos && !read_chunk)
585 logf("pcmbuf_pcm_callback: commit last samples");
586 commit_chunk();
591 /* Send the new buffer to the pcm */
592 if(read_chunk)
594 size_t current_size = read_chunk->size;
596 pcmbuf_unplayed_bytes -= current_size;
597 last_chunksize = current_size;
598 *size = current_size;
599 *start = read_chunk->addr;
601 else
603 /* No more buffers */
604 last_chunksize = 0;
605 *size = 0;
606 *start = NULL;
607 if (end_of_track)
608 finish_gapless_track_change();
611 DISPLAY_DESC("callback");
614 /* Force playback. */
615 void pcmbuf_play_start(void)
617 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && read_chunk != NULL)
619 last_chunksize = read_chunk->size;
620 pcmbuf_unplayed_bytes -= last_chunksize;
621 pcm_play_data(pcmbuf_pcm_callback,
622 (unsigned char *)read_chunk->addr, last_chunksize);
626 void pcmbuf_play_stop(void)
628 pcm_play_stop();
630 pcmbuf_unplayed_bytes = 0;
631 mix_chunk = NULL;
632 if (read_chunk) {
633 write_end_chunk->link = read_chunk;
634 write_end_chunk = read_end_chunk;
635 read_chunk = read_end_chunk = NULL;
637 pcmbuffer_pos = 0;
638 pcmbuffer_fillpos = 0;
639 crossfade_track_change_started = false;
640 crossfade_active = false;
641 flush_pcmbuf = false;
642 DISPLAY_DESC("play_stop");
644 /* Can unboost the codec thread here no matter who's calling */
645 boost_codec_thread(false);
648 void pcmbuf_pause(bool pause)
650 if (pcm_is_playing())
651 pcm_play_pause(!pause);
652 else if (!pause)
653 pcmbuf_play_start();
657 /* Crossfade */
659 /* Clip sample to signed 16 bit range */
660 static inline int32_t clip_sample_16(int32_t sample)
662 if ((int16_t)sample != sample)
663 sample = 0x7fff ^ (sample >> 31);
664 return sample;
667 /**
668 * Low memory targets don't have crossfade, so don't compile crossfade
669 * specific code in order to save some memory. */
671 #ifdef HAVE_CROSSFADE
673 * Completely process the crossfade fade out effect with current pcm buffer.
675 static void crossfade_process_buffer(size_t fade_in_delay,
676 size_t fade_out_delay, size_t fade_out_rem)
678 if (!crossfade_mixmode)
680 /* Fade out the specified amount of the already processed audio */
681 size_t total_fade_out = fade_out_rem;
682 size_t fade_out_sample;
683 struct chunkdesc *fade_out_chunk = crossfade_chunk;
685 /* Find the right chunk to start fading out */
686 fade_out_delay += crossfade_sample * 2;
687 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
689 fade_out_delay -= fade_out_chunk->size;
690 fade_out_chunk = fade_out_chunk->link;
692 /* The start sample within the chunk */
693 fade_out_sample = fade_out_delay / 2;
695 while (fade_out_rem > 0)
697 /* Each 1/10 second of audio will have the same fade applied */
698 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
699 int factor = (fade_out_rem << 8) / total_fade_out;
701 fade_out_rem -= block_rem;
703 /* Fade this block */
704 while (block_rem > 0 && fade_out_chunk != NULL)
706 /* Fade one sample */
707 int16_t *buf = (int16_t *)fade_out_chunk->addr;
708 int32_t sample = buf[fade_out_sample];
709 buf[fade_out_sample++] = (sample * factor) >> 8;
711 block_rem -= 2;
712 /* Move to the next chunk as needed */
713 if (fade_out_sample * 2 >= fade_out_chunk->size)
715 fade_out_chunk = fade_out_chunk->link;
716 fade_out_sample = 0;
722 /* Find the right chunk and sample to start fading in */
723 fade_in_delay += crossfade_sample * 2;
724 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
726 fade_in_delay -= crossfade_chunk->size;
727 crossfade_chunk = crossfade_chunk->link;
729 crossfade_sample = fade_in_delay / 2;
730 logf("process done!");
733 /* Initializes crossfader, calculates all necessary parameters and
734 * performs fade-out with the pcm buffer. */
735 static void crossfade_start(void)
737 size_t crossfade_rem;
738 size_t crossfade_need;
739 size_t fade_out_rem;
740 size_t fade_out_delay;
741 size_t fade_in_delay;
743 crossfade_track_change_started = false;
744 /* Reject crossfade if less than .5s of data */
745 if (LOW_DATA(2)) {
746 logf("crossfade rejected");
747 pcmbuf_play_stop();
748 return ;
751 logf("crossfade_start");
752 commit_chunk();
753 crossfade_active = true;
755 /* Initialize the crossfade buffer size to all of the buffered data that
756 * has not yet been sent to the DMA */
757 crossfade_rem = pcmbuf_unplayed_bytes;
758 crossfade_chunk = read_chunk->link;
759 crossfade_sample = 0;
761 /* Get fade out delay from settings. */
762 fade_out_delay =
763 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
765 /* Get fade out duration from settings. */
766 fade_out_rem =
767 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
769 crossfade_need = fade_out_delay + fade_out_rem;
770 /* We want only to modify the last part of the buffer. */
771 if (crossfade_rem > crossfade_need)
773 size_t crossfade_extra = crossfade_rem - crossfade_need;
774 while (crossfade_extra > crossfade_chunk->size)
776 crossfade_extra -= crossfade_chunk->size;
777 crossfade_chunk = crossfade_chunk->link;
779 crossfade_sample = crossfade_extra / 2;
781 /* Truncate fade out duration if necessary. */
782 else if (crossfade_rem < crossfade_need)
784 size_t crossfade_short = crossfade_need - crossfade_rem;
785 if (fade_out_rem >= crossfade_short)
786 fade_out_rem -= crossfade_short;
787 else
789 fade_out_delay -= crossfade_short - fade_out_rem;
790 fade_out_rem = 0;
794 /* Get also fade in duration and delays from settings. */
795 crossfade_fade_in_total =
796 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
797 crossfade_fade_in_rem = crossfade_fade_in_total;
799 fade_in_delay =
800 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
802 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
805 /* Returns the number of bytes _NOT_ mixed */
806 static size_t crossfade_mix(int factor, const char *buf, size_t length)
808 const int16_t *input_buf = (const int16_t *)buf;
809 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
810 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
811 output_buf = &output_buf[crossfade_sample];
812 int32_t sample;
814 while (length)
816 /* fade left and right channel at once to keep buffer alignment */
817 int i;
818 for (i = 0; i < 2; i++)
820 sample = *input_buf++;
821 sample = ((sample * factor) >> 8) + *output_buf;
822 *output_buf++ = clip_sample_16(sample);
825 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
827 if (output_buf >= chunk_end)
829 crossfade_chunk = crossfade_chunk->link;
830 if (!crossfade_chunk)
831 return length;
832 output_buf = (int16_t *)crossfade_chunk->addr;
833 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
836 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
837 return 0;
840 static void flush_crossfade(char *buf, size_t length)
842 if (length)
844 if (crossfade_fade_in_rem)
846 size_t samples;
847 int16_t *input_buf;
849 /* Fade factor for this packet */
850 int factor =
851 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
852 crossfade_fade_in_total;
853 /* Bytes to fade */
854 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
856 /* We _will_ fade this many bytes */
857 crossfade_fade_in_rem -= fade_rem;
859 if (crossfade_chunk)
861 /* Mix the data */
862 size_t fade_total = fade_rem;
863 fade_rem = crossfade_mix(factor, buf, fade_rem);
864 length -= fade_total - fade_rem;
865 buf += fade_total - fade_rem;
866 if (!length)
867 return;
870 samples = fade_rem / 2;
871 input_buf = (int16_t *)buf;
872 /* Fade remaining samples in place */
873 while (samples--)
875 int32_t sample = *input_buf;
876 *input_buf++ = (sample * factor) >> 8;
880 if (crossfade_chunk)
882 /* Mix the data */
883 size_t mix_total = length;
884 length = crossfade_mix(256, buf, length);
885 buf += mix_total - length;
886 if (!length)
887 return;
890 /* Flush samples to the buffer */
891 while (!prepare_insert(length))
892 sleep(1);
893 while (length > 0)
895 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
896 if (NEED_FLUSH(pcmbuffer_index))
898 commit_chunk();
899 pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
901 size_t copy_n = MIN(length, pcmbuf_size - pcmbuffer_index);
902 memcpy(&pcmbuffer[pcmbuffer_index], buf, copy_n);
903 buf += copy_n;
904 pcmbuffer_fillpos += copy_n;
905 length -= copy_n;
909 #endif /* HAVE_CROSSFADE */
911 static void pcmbuf_finish_crossfade_enable(void)
913 /* Copy the pending setting over now */
914 crossfade_enabled = crossfade_enable_request;
916 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
917 /* If crossfading, try to keep the buffer full other than 1 second */
918 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
919 /* Otherwise, just use the default */
920 PCMBUF_WATERMARK;
923 static bool pcmbuf_is_crossfade_enabled(void)
925 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
926 return global_settings.playlist_shuffle;
928 return crossfade_enabled;
931 bool pcmbuf_is_crossfade_active(void)
933 return crossfade_active || crossfade_track_change_started;
936 void pcmbuf_request_crossfade_enable(bool on_off)
938 /* Next setting to be used, not applied now */
939 crossfade_enable_request = on_off;
942 bool pcmbuf_is_same_size(void)
944 /* if pcmbuffer is NULL, then not set up yet even once so always */
945 bool same_size = pcmbuffer ?
946 (get_next_required_pcmbuf_size() == pcmbuf_size) : true;
948 /* no buffer change needed, so finish crossfade setup now */
949 if (same_size)
950 pcmbuf_finish_crossfade_enable();
952 return same_size;
956 /* Voice */
958 /* Returns pcm buffer usage in percents (0 to 100). */
959 static int pcmbuf_usage(void)
961 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
964 static int pcmbuf_mix_free(void)
966 if (mix_chunk)
968 size_t my_mix_end =
969 (size_t)&((int16_t *)mix_chunk->addr)[pcmbuf_mix_sample];
970 size_t my_write_pos = (size_t)&pcmbuffer[pcmbuffer_pos];
971 if (my_write_pos < my_mix_end)
972 my_write_pos += pcmbuf_size;
973 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
975 return 100;
978 void *pcmbuf_request_voice_buffer(int *count)
980 /* A get-it-to-work-for-now hack (audio status could change by
981 completion) */
982 if (audio_status() & AUDIO_STATUS_PLAY)
984 if (read_chunk == NULL)
986 return NULL;
988 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
989 (mix_chunk || read_chunk->link))
991 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
992 return voicebuf;
994 else
996 return NULL;
999 else
1001 return pcmbuf_request_buffer(count);
1005 void pcmbuf_write_voice_complete(int count)
1007 /* A get-it-to-work-for-now hack (audio status could have changed) */
1008 if (!(audio_status() & AUDIO_STATUS_PLAY))
1010 pcmbuf_write_complete(count);
1011 return;
1014 int16_t *ibuf = (int16_t *)voicebuf;
1015 int16_t *obuf;
1016 size_t chunk_samples;
1018 if (mix_chunk == NULL && read_chunk != NULL)
1020 mix_chunk = read_chunk->link;
1021 /* Start 1/8s into the next chunk */
1022 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1025 if (!mix_chunk)
1026 return;
1028 obuf = (int16_t *)mix_chunk->addr;
1029 chunk_samples = mix_chunk->size / sizeof (int16_t);
1031 count <<= 1;
1033 while (count-- > 0)
1035 int32_t sample = *ibuf++;
1037 if (pcmbuf_mix_sample >= chunk_samples)
1039 mix_chunk = mix_chunk->link;
1040 if (!mix_chunk)
1041 return;
1042 pcmbuf_mix_sample = 0;
1043 obuf = mix_chunk->addr;
1044 chunk_samples = mix_chunk->size / 2;
1046 sample += obuf[pcmbuf_mix_sample] >> 2;
1047 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1052 /* Debug menu, other metrics */
1054 /* Amount of bytes left in the buffer. */
1055 size_t pcmbuf_free(void)
1057 if (read_chunk != NULL)
1059 void *read = read_chunk->addr;
1060 void *write = &pcmbuffer[pcmbuffer_pos + pcmbuffer_fillpos];
1061 if (read < write)
1062 return (size_t)(read - write) + pcmbuf_size;
1063 else
1064 return (size_t) (read - write);
1066 return pcmbuf_size;
1069 size_t pcmbuf_get_bufsize(void)
1071 return pcmbuf_size;
1074 int pcmbuf_used_descs(void)
1076 struct chunkdesc *temp = read_chunk;
1077 unsigned int i = 0;
1078 while (temp) {
1079 temp = temp->link;
1080 i++;
1082 return i;
1085 int pcmbuf_descs(void)
1087 return NUM_CHUNK_DESCS(pcmbuf_size);
1090 #ifdef ROCKBOX_HAS_LOGF
1091 unsigned char * pcmbuf_get_meminfo(size_t *length)
1093 *length = pcmbuf_bufend - pcmbuffer;
1094 return pcmbuffer;
1096 #endif
1099 /* Misc */
1101 bool pcmbuf_is_lowdata(void)
1103 if (!pcm_is_playing() || pcm_is_paused() || pcmbuf_is_crossfade_active())
1104 return false;
1106 #if MEMORYSIZE > 2
1107 /* 1 seconds of buffer is low data */
1108 return LOW_DATA(4);
1109 #else
1110 /* under watermark is low data */
1111 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
1112 #endif
1115 void pcmbuf_set_low_latency(bool state)
1117 low_latency_mode = state;
1120 unsigned long pcmbuf_get_latency(void)
1122 /* Be careful how this calculation is rearranged, it's easy to overflow */
1123 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
1124 return bytes / 4 * 1000 / NATIVE_FREQUENCY;
1127 #ifndef HAVE_HARDWARE_BEEP
1128 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
1129 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
1131 /* Generates a constant square wave sound with a given frequency
1132 in Hertz for a duration in milliseconds. */
1133 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
1135 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
1136 int32_t phase = 0;
1137 int16_t *bufptr, *bufstart, *bufend;
1138 int32_t sample;
1139 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
1140 bool mix = read_chunk != NULL && read_chunk->link != NULL;
1141 int i;
1143 bufend = SKIPBYTES((int16_t *)pcmbuffer, pcmbuf_size);
1145 /* Find the insertion point and set bufstart to the start of it */
1146 if (mix)
1148 /* Get the currently playing chunk at the current position. */
1149 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
1151 /* If above isn't implemented or pcm is stopped, no beepeth. */
1152 if (!bufstart || !pcm_is_playing())
1153 return;
1155 /* Give 5ms clearance. */
1156 bufstart += NATIVE_FREQUENCY * 4 / 200;
1158 #ifdef HAVE_PCM_DMA_ADDRESS
1159 /* Returned peak addresses are DMA addresses */
1160 bufend = pcm_dma_addr(bufend);
1161 #endif
1163 /* Wrapped above? */
1164 if (bufstart >= bufend)
1165 bufstart -= pcmbuf_size;
1167 /* NOTE: On some targets using hardware DMA, cache range flushing may
1168 * be required or the writes may not be picked up by the controller.
1169 * An incremental flush should be done periodically during the mixdown. */
1171 else if (nsamples <= MINIBUF_SAMPLES)
1173 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
1174 /* Use mini buffer */
1175 bufstart = minibuf;
1176 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
1178 else if (audio_buffer_state() != AUDIOBUF_STATE_TRASHED)
1180 /* Use pcmbuffer */
1181 bufstart = (int16_t *)pcmbuffer;
1183 else
1185 /* No place */
1186 return;
1189 bufptr = bufstart;
1191 /* Mix square wave into buffer */
1192 for (i = 0; i < nsamples; ++i)
1194 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
1195 sample = mix ? *bufptr : 0;
1196 *bufptr++ = clip_sample_16(sample + amp);
1197 if (bufptr >= bufend)
1198 bufptr = (int16_t *)pcmbuffer;
1199 sample = mix ? *bufptr : 0;
1200 *bufptr++ = clip_sample_16(sample + amp);
1201 if (bufptr >= bufend)
1202 bufptr = (int16_t *)pcmbuffer;
1204 phase += step;
1207 pcm_play_lock();
1208 #ifdef HAVE_RECORDING
1209 pcm_rec_lock();
1210 #endif
1212 /* Kick off playback if required and it won't interfere */
1213 if (!pcm_is_playing()
1214 #ifdef HAVE_RECORDING
1215 && !pcm_is_recording()
1216 #endif
1219 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1222 pcm_play_unlock();
1223 #ifdef HAVE_RECORDING
1224 pcm_rec_unlock();
1225 #endif
1227 #endif /* HAVE_HARDWARE_BEEP */