Correct beast manual install instructions in Windows.
[kugel-rb.git] / apps / pcmbuf.c
blob4a338aa900b2e54f9db79502419b47fc990694f6
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"
29 /* Define LOGF_ENABLE to enable logf output in this file */
30 /*#define LOGF_ENABLE*/
31 #include "logf.h"
32 #ifndef SIMULATOR
33 #include "cpu.h"
34 #endif
35 #include <string.h>
36 #include "buffer.h"
37 #include "settings.h"
38 #include "audio.h"
39 #include "voice_thread.h"
40 #include "dsp.h"
41 #include "thread.h"
43 /* Clip sample to signed 16 bit range */
44 static inline int32_t clip_sample_16(int32_t sample)
46 if ((int16_t)sample != sample)
47 sample = 0x7fff ^ (sample >> 31);
48 return sample;
51 #if MEMORYSIZE > 2
52 /* Keep watermark high for iPods at least (2s) */
53 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
54 #else
55 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 1) /* 0.25 seconds */
56 #endif
58 /* Structure we can use to queue pcm chunks in memory to be played
59 * by the driver code. */
60 struct pcmbufdesc
62 void *addr;
63 size_t size;
64 struct pcmbufdesc* link;
65 /* Call this when the buffer has been played */
66 void (*callback)(void);
69 #define PCMBUF_DESCS(bufsize) \
70 ((bufsize) / PCMBUF_MINAVG_CHUNK)
71 #define PCMBUF_DESCS_SIZE(bufsize) \
72 (PCMBUF_DESCS(bufsize)*sizeof(struct pcmbufdesc))
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 *audiobuffer IDATA_ATTR;
78 /* Current audio buffer write index. */
79 static size_t audiobuffer_pos IDATA_ATTR;
80 /* Amount audiobuffer_pos will be increased.*/
81 static size_t audiobuffer_fillpos IDATA_ATTR;
82 static char *fadebuf IDATA_ATTR;
83 static char *voicebuf IDATA_ATTR;
85 static void (*pcmbuf_event_handler)(void) IDATA_ATTR;
86 static void (*position_callback)(size_t size) IDATA_ATTR;
88 /* Crossfade related state */
89 static bool crossfade_enabled;
90 static bool crossfade_enabled_pending;
91 static bool crossfade_mixmode;
92 static bool crossfade_active IDATA_ATTR;
93 static bool crossfade_init IDATA_ATTR;
95 /* Track the current location for processing crossfade */
96 static struct pcmbufdesc *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 pcmbufdesc *pcmbuf_read IDATA_ATTR;
106 static struct pcmbufdesc *pcmbuf_read_end IDATA_ATTR;
107 static struct pcmbufdesc *pcmbuf_write IDATA_ATTR;
108 static struct pcmbufdesc *pcmbuf_write_end 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 pcmbufdesc *pcmbuf_mix_chunk IDATA_ATTR;
115 static size_t pcmbuf_mix_sample IDATA_ATTR;
117 static bool low_latency_mode = false;
118 static bool pcmbuf_flush;
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 (audiobuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
130 #define LOW_DATA(quarter_secs) \
131 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
133 static bool prepare_insert(size_t length);
134 static void pcmbuf_under_watermark(bool under);
135 static bool pcmbuf_flush_fillpos(void);
137 #define CALL_IF_EXISTS(function, args...) if (function) function(args)
138 /* This function has 2 major logical parts (separated by brackets both for
139 * readability and variable scoping). The first part performs the
140 * operastions related to finishing off the last buffer we fed to the DMA.
141 * The second part performs the operations involved in sending a new buffer
142 * to the DMA. Finally the function checks the status of the buffer and
143 * boosts if necessary */
144 static void pcmbuf_callback(unsigned char** start, size_t* size) ICODE_ATTR;
145 static void pcmbuf_callback(unsigned char** start, size_t* size)
148 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
149 /* Take the finished buffer out of circulation */
150 pcmbuf_read = pcmbuf_current->link;
152 /* The buffer is finished, call the callback functions */
153 CALL_IF_EXISTS(position_callback, last_chunksize);
154 CALL_IF_EXISTS(pcmbuf_current->callback);
156 /* Put the finished buffer back into circulation */
157 pcmbuf_write_end->link = pcmbuf_current;
158 pcmbuf_write_end = pcmbuf_current;
160 /* If we've read over the mix chunk while it's still mixing there */
161 if (pcmbuf_current == pcmbuf_mix_chunk)
162 pcmbuf_mix_chunk = NULL;
163 /* If we've read over the crossfade chunk while it's still fading */
164 if (pcmbuf_current == crossfade_chunk)
165 crossfade_chunk = pcmbuf_read;
169 /* Send the new buffer to the pcm */
170 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
171 size_t *realsize = size;
172 unsigned char** realstart = start;
173 if(pcmbuf_new)
175 size_t current_size = pcmbuf_new->size;
177 pcmbuf_unplayed_bytes -= current_size;
178 last_chunksize = current_size;
179 *realsize = current_size;
180 *realstart = pcmbuf_new->addr;
182 else
184 /* No more buffers */
185 last_chunksize = 0;
186 *realsize = 0;
187 *realstart = NULL;
188 CALL_IF_EXISTS(pcmbuf_event_handler);
193 void pcmbuf_set_position_callback(void (*callback)(size_t size))
195 position_callback = callback;
198 static void pcmbuf_set_watermark_bytes(void)
200 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
201 /* If crossfading, try to keep the buffer full other than 1 second */
202 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
203 /* Otherwise, just use the default */
204 PCMBUF_WATERMARK;
207 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
208 * in a separate function for the moment */
209 static inline void pcmbuf_add_chunk(void)
211 register size_t size = audiobuffer_fillpos;
212 /* Grab the next description to write, and change the write pointer */
213 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
214 pcmbuf_write = pcmbuf_current->link;
215 /* Fill in the values in the new buffer chunk */
216 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
217 pcmbuf_current->size = size;
218 pcmbuf_current->callback = pcmbuf_event_handler;
219 pcmbuf_current->link = NULL;
220 /* This is single use only */
221 pcmbuf_event_handler = NULL;
222 if (pcmbuf_read != NULL) {
223 if (pcmbuf_flush)
225 pcmbuf_write_end->link = pcmbuf_read->link;
226 pcmbuf_read->link = pcmbuf_current;
227 while (pcmbuf_write_end->link)
229 pcmbuf_write_end = pcmbuf_write_end->link;
230 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
232 pcmbuf_flush = false;
234 /* If there is already a read buffer setup, add to it */
235 else
236 pcmbuf_read_end->link = pcmbuf_current;
237 } else {
238 /* Otherwise create the buffer */
239 pcmbuf_read = pcmbuf_current;
241 /* This is now the last buffer to read */
242 pcmbuf_read_end = pcmbuf_current;
244 /* Update bytes counters */
245 pcmbuf_unplayed_bytes += size;
247 audiobuffer_pos += size;
248 if (audiobuffer_pos >= pcmbuf_size)
249 audiobuffer_pos -= pcmbuf_size;
251 audiobuffer_fillpos = 0;
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 #endif /* HAVE_PRIORITY_SCHEDULING */
280 static void pcmbuf_under_watermark(bool under)
282 /* Only codec thread initiates boost - voice boosts the cpu when playing
283 a clip */
284 #ifndef SIMULATOR
285 if (thread_get_current() == codec_thread_id)
286 #endif /* SIMULATOR */
288 if (under)
290 /* Fill audio buffer by boosting cpu */
291 trigger_cpu_boost();
292 #ifdef HAVE_PRIORITY_SCHEDULING
293 /* If buffer is critically low, override UI priority, else
294 set back to the original priority. */
295 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
296 #endif
298 else
300 #ifdef HAVE_PRIORITY_SCHEDULING
301 boost_codec_thread(false);
302 #endif
306 /* Disable crossfade if < .5s of audio */
307 if (LOW_DATA(2))
309 crossfade_active = false;
313 void pcmbuf_set_event_handler(void (*event_handler)(void))
315 pcmbuf_event_handler = event_handler;
318 unsigned int pcmbuf_get_latency(void)
320 /* Be careful how this calculation is rearranged, it's easy to overflow */
321 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
322 return bytes / 4 / (NATIVE_FREQUENCY/1000);
325 void pcmbuf_set_low_latency(bool state)
327 low_latency_mode = state;
330 bool pcmbuf_is_lowdata(void)
332 if (!pcm_is_playing() || pcm_is_paused() ||
333 crossfade_init || crossfade_active)
334 return false;
336 #if MEMORYSIZE > 2
337 /* 1 seconds of buffer is low data */
338 return LOW_DATA(4);
339 #else
340 /* under watermark is low data */
341 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
342 #endif
345 /* Amount of bytes left in the buffer. */
346 inline size_t pcmbuf_free(void)
348 if (pcmbuf_read != NULL)
350 void *read = pcmbuf_read->addr;
351 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
352 if (read < write)
353 return (size_t)(read - write) + pcmbuf_size;
354 else
355 return (size_t) (read - write);
357 return pcmbuf_size;
360 bool pcmbuf_crossfade_init(bool manual_skip)
362 /* Can't do two crossfades at once and, no fade if pcm is off now */
363 if (crossfade_init || crossfade_active || !pcm_is_playing())
365 pcmbuf_play_stop();
366 return false;
369 trigger_cpu_boost();
371 /* Not enough data, or crossfade disabled, flush the old data instead */
372 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
374 pcmbuf_flush_fillpos();
375 pcmbuf_flush = true;
376 return false;
379 /* Don't enable mix mode when skipping tracks manually. */
380 if (manual_skip)
381 crossfade_mixmode = false;
382 else
383 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
385 crossfade_init = true;
387 return true;
391 void pcmbuf_play_stop(void)
393 pcm_play_stop();
395 pcmbuf_unplayed_bytes = 0;
396 pcmbuf_mix_chunk = NULL;
397 if (pcmbuf_read) {
398 pcmbuf_write_end->link = pcmbuf_read;
399 pcmbuf_write_end = pcmbuf_read_end;
400 pcmbuf_read = pcmbuf_read_end = NULL;
402 audiobuffer_pos = 0;
403 audiobuffer_fillpos = 0;
404 crossfade_init = false;
405 crossfade_active = false;
406 pcmbuf_flush = false;
408 #ifdef HAVE_PRIORITY_SCHEDULING
409 /* Can unboost the codec thread here no matter who's calling */
410 boost_codec_thread(false);
411 #endif
414 int pcmbuf_used_descs(void)
416 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
417 unsigned int i = 0;
418 while (pcmbuf_temp) {
419 pcmbuf_temp = pcmbuf_temp->link;
420 i++;
422 return i;
425 int pcmbuf_descs(void)
427 return PCMBUF_DESCS(pcmbuf_size);
430 static void pcmbuf_init_pcmbuffers(void)
432 struct pcmbufdesc *next = pcmbuf_write;
433 next++;
434 pcmbuf_write_end = pcmbuf_write;
435 while ((void *)next < (void *)pcmbuf_bufend) {
436 pcmbuf_write_end->link=next;
437 pcmbuf_write_end=next;
438 next++;
442 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
444 size_t seconds = 1;
446 if (crossfade_enabled_pending)
447 seconds += global_settings.crossfade_fade_out_delay
448 + global_settings.crossfade_fade_out_duration;
450 #if MEMORYSIZE > 2
451 /* Buffer has to be at least 2s long. */
452 seconds += 2;
453 #endif
454 logf("pcmbuf len: %ld", (long)seconds);
455 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
458 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
460 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
461 PCMBUF_DESCS_SIZE(bufsize));
464 bool pcmbuf_is_same_size(void)
466 if (audiobuffer == NULL)
467 return true; /* Not set up yet even once so always */
469 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
470 return pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
473 /* Initialize the pcmbuffer the structure looks like this:
474 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
475 size_t pcmbuf_init(unsigned char *bufend)
477 pcmbuf_bufend = bufend;
478 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
479 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
480 fadebuf = &audiobuffer[pcmbuf_size];
481 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
482 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
484 pcmbuf_init_pcmbuffers();
486 position_callback = NULL;
487 pcmbuf_event_handler = NULL;
489 pcmbuf_crossfade_enable_finished();
491 pcmbuf_play_stop();
493 return pcmbuf_bufend - audiobuffer;
496 size_t pcmbuf_get_bufsize(void)
498 return pcmbuf_size;
501 #ifdef ROCKBOX_HAS_LOGF
502 unsigned char * pcmbuf_get_meminfo(size_t *length)
504 *length = pcmbuf_bufend - audiobuffer;
505 return audiobuffer;
507 #endif
509 void pcmbuf_pause(bool pause)
511 if (pcm_is_playing())
512 pcm_play_pause(!pause);
513 else if (!pause)
514 pcmbuf_play_start();
517 /* Force playback. */
518 void pcmbuf_play_start(void)
520 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && pcmbuf_read != NULL)
522 last_chunksize = pcmbuf_read->size;
523 pcmbuf_unplayed_bytes -= last_chunksize;
524 pcm_play_data(pcmbuf_callback,
525 (unsigned char *)pcmbuf_read->addr, last_chunksize);
530 * Commit samples waiting to the pcm buffer.
532 static bool pcmbuf_flush_fillpos(void)
534 if (audiobuffer_fillpos) {
535 /* Never use the last buffer descriptor */
536 while (pcmbuf_write == pcmbuf_write_end) {
537 /* If this happens, something is being stupid */
538 if (!pcm_is_playing()) {
539 logf("pcmbuf_flush_fillpos error");
540 pcmbuf_play_start();
542 /* Let approximately one chunk of data playback */
543 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
545 pcmbuf_add_chunk();
546 return true;
548 return false;
551 /**
552 * Low memory targets don't have crossfade, so don't compile crossfade
553 * specific code in order to save some memory. */
555 #ifdef HAVE_CROSSFADE
557 * Completely process the crossfade fade out effect with current pcm buffer.
559 static void crossfade_process_buffer(size_t fade_in_delay,
560 size_t fade_out_delay, size_t fade_out_rem)
562 if (!crossfade_mixmode)
564 /* Fade out the specified amount of the already processed audio */
565 size_t total_fade_out = fade_out_rem;
566 size_t fade_out_sample;
567 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
569 /* Find the right chunk to start fading out */
570 fade_out_delay += crossfade_sample * 2;
571 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
573 fade_out_delay -= fade_out_chunk->size;
574 fade_out_chunk = fade_out_chunk->link;
576 /* The start sample within the chunk */
577 fade_out_sample = fade_out_delay / 2;
579 while (fade_out_rem > 0)
581 /* Each 1/10 second of audio will have the same fade applied */
582 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
583 int factor = (fade_out_rem << 8) / total_fade_out;
585 fade_out_rem -= block_rem;
587 /* Fade this block */
588 while (block_rem > 0 && fade_out_chunk != NULL)
590 /* Fade one sample */
591 int16_t *buf = (int16_t *)fade_out_chunk->addr;
592 int32_t sample = buf[fade_out_sample];
593 buf[fade_out_sample++] = (sample * factor) >> 8;
595 block_rem -= 2;
596 /* Move to the next chunk as needed */
597 if (fade_out_sample * 2 >= fade_out_chunk->size)
599 fade_out_chunk = fade_out_chunk->link;
600 fade_out_sample = 0;
606 /* Find the right chunk and sample to start fading in */
607 fade_in_delay += crossfade_sample * 2;
608 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
610 fade_in_delay -= crossfade_chunk->size;
611 crossfade_chunk = crossfade_chunk->link;
613 crossfade_sample = fade_in_delay / 2;
614 logf("process done!");
617 /* Initializes crossfader, calculates all necessary parameters and
618 * performs fade-out with the pcm buffer. */
619 static void crossfade_start(void)
621 size_t crossfade_rem;
622 size_t crossfade_need;
623 size_t fade_out_rem;
624 size_t fade_out_delay;
625 size_t fade_in_delay;
627 crossfade_init = false;
628 /* Reject crossfade if less than .5s of data */
629 if (LOW_DATA(2)) {
630 logf("crossfade rejected");
631 pcmbuf_play_stop();
632 return ;
635 logf("crossfade_start");
636 pcmbuf_flush_fillpos();
637 crossfade_active = true;
639 /* Initialize the crossfade buffer size to all of the buffered data that
640 * has not yet been sent to the DMA */
641 crossfade_rem = pcmbuf_unplayed_bytes;
642 crossfade_chunk = pcmbuf_read->link;
643 crossfade_sample = 0;
645 /* Get fade out delay from settings. */
646 fade_out_delay =
647 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
649 /* Get fade out duration from settings. */
650 fade_out_rem =
651 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
653 crossfade_need = fade_out_delay + fade_out_rem;
654 /* We want only to modify the last part of the buffer. */
655 if (crossfade_rem > crossfade_need)
657 size_t crossfade_extra = crossfade_rem - crossfade_need;
658 while (crossfade_extra > crossfade_chunk->size)
660 crossfade_extra -= crossfade_chunk->size;
661 crossfade_chunk = crossfade_chunk->link;
663 crossfade_sample = crossfade_extra / 2;
665 /* Truncate fade out duration if necessary. */
666 else if (crossfade_rem < crossfade_need)
668 size_t crossfade_short = crossfade_need - crossfade_rem;
669 if (fade_out_rem >= crossfade_short)
670 fade_out_rem -= crossfade_short;
671 else
673 fade_out_delay -= crossfade_short - fade_out_rem;
674 fade_out_rem = 0;
678 /* Get also fade in duration and delays from settings. */
679 crossfade_fade_in_total =
680 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
681 crossfade_fade_in_rem = crossfade_fade_in_total;
683 fade_in_delay =
684 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
686 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
689 /* Returns the number of bytes _NOT_ mixed */
690 static size_t crossfade_mix(int factor, const char *buf, size_t length)
692 const int16_t *input_buf = (const int16_t *)buf;
693 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
694 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
695 output_buf = &output_buf[crossfade_sample];
696 int32_t sample;
698 while (length)
700 /* fade left and right channel at once to keep buffer alignment */
701 int i;
702 for (i = 0; i < 2; i++)
704 sample = *input_buf++;
705 sample = ((sample * factor) >> 8) + *output_buf;
706 *output_buf++ = clip_sample_16(sample);
709 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
711 if (output_buf >= chunk_end)
713 crossfade_chunk = crossfade_chunk->link;
714 if (!crossfade_chunk)
715 return length;
716 output_buf = (int16_t *)crossfade_chunk->addr;
717 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
720 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
721 return 0;
724 static void pcmbuf_flush_buffer(const char *buf, size_t length)
726 size_t copy_n;
727 while (length > 0) {
728 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
729 if (NEED_FLUSH(audiobuffer_index))
731 pcmbuf_flush_fillpos();
732 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
734 copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
735 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
736 buf += copy_n;
737 audiobuffer_fillpos += copy_n;
738 length -= copy_n;
742 static void flush_crossfade(char *buf, size_t length)
744 if (length)
746 if (crossfade_fade_in_rem)
748 size_t samples;
749 int16_t *input_buf;
751 /* Fade factor for this packet */
752 int factor =
753 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
754 crossfade_fade_in_total;
755 /* Bytes to fade */
756 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
758 /* We _will_ fade this many bytes */
759 crossfade_fade_in_rem -= fade_rem;
761 if (crossfade_chunk)
763 /* Mix the data */
764 size_t fade_total = fade_rem;
765 fade_rem = crossfade_mix(factor, buf, fade_rem);
766 length -= fade_total - fade_rem;
767 buf += fade_total - fade_rem;
768 if (!length)
769 return;
772 samples = fade_rem / 2;
773 input_buf = (int16_t *)buf;
774 /* Fade remaining samples in place */
775 while (samples--)
777 int32_t sample = *input_buf;
778 *input_buf++ = (sample * factor) >> 8;
782 if (crossfade_chunk)
784 /* Mix the data */
785 size_t mix_total = length;
786 length = crossfade_mix(256, buf, length);
787 buf += mix_total - length;
788 if (!length)
789 return;
792 /* Flush samples to the buffer */
793 while (!prepare_insert(length))
794 sleep(1);
795 pcmbuf_flush_buffer(buf, length);
799 #endif
801 static bool prepare_insert(size_t length)
803 if (low_latency_mode)
805 /* 1/4s latency. */
806 if (!LOW_DATA(1) && pcm_is_playing())
807 return false;
810 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
811 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
812 return false;
814 if (!pcm_is_playing())
816 trigger_cpu_boost();
818 /* Pre-buffer up to watermark */
819 #if MEMORYSIZE > 2
820 if (!LOW_DATA(4))
821 #else
822 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
823 #endif
825 logf("pcm starting");
826 if (!(audio_status() & AUDIO_STATUS_PAUSE))
827 pcmbuf_play_start();
830 else
831 pcmbuf_under_watermark(pcmbuf_unplayed_bytes <= pcmbuf_watermark);
833 return true;
836 void* pcmbuf_request_buffer(int *count)
838 #ifdef HAVE_CROSSFADE
839 if (crossfade_init)
840 crossfade_start();
841 #endif
843 if (crossfade_active) {
844 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
845 return fadebuf;
847 else
849 if(prepare_insert(*count << 2))
851 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
852 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
854 /* Usual case, there's space here */
855 return &audiobuffer[audiobuffer_index];
857 else
859 /* Flush and wrap the buffer */
860 pcmbuf_flush_fillpos();
861 audiobuffer_pos = 0;
862 return &audiobuffer[0];
865 else
867 return NULL;
872 void * pcmbuf_request_voice_buffer(int *count)
874 /* A get-it-to-work-for-now hack (audio status could change by
875 completion) */
876 if (audio_status() & AUDIO_STATUS_PLAY)
878 if (pcmbuf_read == NULL)
880 return NULL;
882 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
883 (pcmbuf_mix_chunk || pcmbuf_read->link))
885 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
886 return voicebuf;
888 else
890 return NULL;
893 else
895 return pcmbuf_request_buffer(count);
899 bool pcmbuf_is_crossfade_active(void)
901 return crossfade_active || crossfade_init;
904 void pcmbuf_write_complete(int count)
906 size_t length = (size_t)(unsigned int)count << 2;
907 #ifdef HAVE_CROSSFADE
908 if (crossfade_active)
910 flush_crossfade(fadebuf, length);
911 if (!(crossfade_fade_in_rem || crossfade_chunk))
912 crossfade_active = false;
914 else
915 #endif
917 audiobuffer_fillpos += length;
919 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
920 pcmbuf_flush_fillpos();
924 #ifndef HAVE_HARDWARE_BEEP
925 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
926 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
928 /* Generates a constant square wave sound with a given frequency
929 in Hertz for a duration in milliseconds. */
930 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
932 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
933 int32_t phase = 0;
934 int16_t *bufptr, *bufstart, *bufend;
935 int32_t sample;
936 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
937 bool mix = pcmbuf_read != NULL && pcmbuf_read->link != NULL;
938 int i;
940 bufend = SKIPBYTES((int16_t *)audiobuffer, pcmbuf_size);
942 /* Find the insertion point and set bufstart to the start of it */
943 if (mix)
945 /* Get the currently playing chunk at the current position. */
946 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
948 /* If above isn't implemented or pcm is stopped, no beepeth. */
949 if (!bufstart || !pcm_is_playing())
950 return;
952 /* Give 5ms clearance. */
953 bufstart += NATIVE_FREQUENCY * 4 / 200;
955 #ifdef HAVE_PCM_DMA_ADDRESS
956 /* Returned peak addresses are DMA addresses */
957 bufend = pcm_dma_addr(bufend);
958 #endif
960 /* Wrapped above? */
961 if (bufstart >= bufend)
962 bufstart -= pcmbuf_size;
964 /* NOTE: On some targets using hardware DMA, cache range flushing may
965 * be required or the writes may not be picked up by the controller.
966 * An incremental flush should be done periodically during the mixdown. */
968 else if (nsamples <= MINIBUF_SAMPLES)
970 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
971 /* Use mini buffer */
972 bufstart = minibuf;
973 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
975 else if (audio_buffer_state() != AUDIOBUF_STATE_TRASHED)
977 /* Use audiobuffer */
978 bufstart = (int16_t *)audiobuffer;
980 else
982 /* No place */
983 return;
986 bufptr = bufstart;
988 /* Mix square wave into buffer */
989 for (i = 0; i < nsamples; ++i)
991 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
992 sample = mix ? *bufptr : 0;
993 *bufptr++ = clip_sample_16(sample + amp);
994 if (bufptr >= bufend)
995 bufptr = (int16_t *)audiobuffer;
996 sample = mix ? *bufptr : 0;
997 *bufptr++ = clip_sample_16(sample + amp);
998 if (bufptr >= bufend)
999 bufptr = (int16_t *)audiobuffer;
1001 phase += step;
1004 pcm_play_lock();
1005 #ifdef HAVE_RECORDING
1006 pcm_rec_lock();
1007 #endif
1009 /* Kick off playback if required and it won't interfere */
1010 if (!pcm_is_playing()
1011 #ifdef HAVE_RECORDING
1012 && !pcm_is_recording()
1013 #endif
1016 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1019 pcm_play_unlock();
1020 #ifdef HAVE_RECORDING
1021 pcm_rec_unlock();
1022 #endif
1024 #endif /* HAVE_HARDWARE_BEEP */
1026 /* Returns pcm buffer usage in percents (0 to 100). */
1027 int pcmbuf_usage(void)
1029 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1032 int pcmbuf_mix_free(void)
1034 if (pcmbuf_mix_chunk)
1036 size_t my_mix_end =
1037 (size_t)&((int16_t *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1038 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1039 if (my_write_pos < my_mix_end)
1040 my_write_pos += pcmbuf_size;
1041 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1043 return 100;
1046 void pcmbuf_write_voice_complete(int count)
1048 /* A get-it-to-work-for-now hack (audio status could have changed) */
1049 if (!(audio_status() & AUDIO_STATUS_PLAY))
1051 pcmbuf_write_complete(count);
1052 return;
1055 int16_t *ibuf = (int16_t *)voicebuf;
1056 int16_t *obuf;
1057 size_t chunk_samples;
1059 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1061 pcmbuf_mix_chunk = pcmbuf_read->link;
1062 /* Start 1/8s into the next chunk */
1063 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1066 if (!pcmbuf_mix_chunk)
1067 return;
1069 obuf = (int16_t *)pcmbuf_mix_chunk->addr;
1070 chunk_samples = pcmbuf_mix_chunk->size / sizeof (int16_t);
1072 count <<= 1;
1074 while (count-- > 0)
1076 int32_t sample = *ibuf++;
1078 if (pcmbuf_mix_sample >= chunk_samples)
1080 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1081 if (!pcmbuf_mix_chunk)
1082 return;
1083 pcmbuf_mix_sample = 0;
1084 obuf = pcmbuf_mix_chunk->addr;
1085 chunk_samples = pcmbuf_mix_chunk->size / 2;
1087 sample += obuf[pcmbuf_mix_sample] >> 2;
1088 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1092 void pcmbuf_crossfade_enable(bool on_off)
1094 /* Next setting to be used, not applied now */
1095 crossfade_enabled_pending = on_off;
1098 void pcmbuf_crossfade_enable_finished(void)
1100 /* Copy the pending setting over now */
1101 crossfade_enabled = crossfade_enabled_pending;
1102 pcmbuf_set_watermark_bytes();
1105 bool pcmbuf_is_crossfade_enabled(void)
1107 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
1108 return global_settings.playlist_shuffle;
1110 return crossfade_enabled;
1113 /** PLAY LAST REMAINING SAMPLES AT END OF PLAYBACK
1114 * Commit any remaining samples in the PCM buffer for playback. */
1115 void pcmbuf_play_remainder(void)
1117 if (audiobuffer_fillpos)
1118 pcmbuf_flush_fillpos();