Code cleanup in codec_thread, playback and pcmbuf; more elegant solution to leftover...
[kugel-rb.git] / apps / pcmbuf.c
blob3ec0c114daf4a043117a4c9e45548ddc0457942a
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 3 major logical parts (separated by brackets both for
139 * readability and variable scoping). The first part performs the
140 * operations related to finishing off the last buffer we fed to the DMA.
141 * The second part detects the end of playlist condition when the pcm
142 * buffer is empty except for uncommitted samples. Then they are committed.
143 * The third part performs the operations involved in sending a new buffer
144 * to the DMA. */
145 static void pcmbuf_callback(unsigned char** start, size_t* size) ICODE_ATTR;
146 static void pcmbuf_callback(unsigned char** start, size_t* size)
149 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
150 /* Take the finished buffer out of circulation */
151 pcmbuf_read = pcmbuf_current->link;
153 /* The buffer is finished, call the callback functions */
154 CALL_IF_EXISTS(position_callback, last_chunksize);
155 CALL_IF_EXISTS(pcmbuf_current->callback);
157 /* Put the finished buffer back into circulation */
158 pcmbuf_write_end->link = pcmbuf_current;
159 pcmbuf_write_end = pcmbuf_current;
161 /* If we've read over the mix chunk while it's still mixing there */
162 if (pcmbuf_current == pcmbuf_mix_chunk)
163 pcmbuf_mix_chunk = NULL;
164 /* If we've read over the crossfade chunk while it's still fading */
165 if (pcmbuf_current == crossfade_chunk)
166 crossfade_chunk = pcmbuf_read;
170 /* Commit last samples at end of playlist */
171 if (audiobuffer_fillpos && !pcmbuf_read)
173 logf("pcmbuf callback: commit last samples");
174 pcmbuf_flush_fillpos();
179 /* Send the new buffer to the pcm */
180 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
181 size_t *realsize = size;
182 unsigned char** realstart = start;
183 if(pcmbuf_new)
185 size_t current_size = pcmbuf_new->size;
187 pcmbuf_unplayed_bytes -= current_size;
188 last_chunksize = current_size;
189 *realsize = current_size;
190 *realstart = pcmbuf_new->addr;
192 else
194 /* No more buffers */
195 last_chunksize = 0;
196 *realsize = 0;
197 *realstart = NULL;
198 CALL_IF_EXISTS(pcmbuf_event_handler);
203 void pcmbuf_set_position_callback(void (*callback)(size_t size))
205 position_callback = callback;
208 static void pcmbuf_set_watermark_bytes(void)
210 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
211 /* If crossfading, try to keep the buffer full other than 1 second */
212 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
213 /* Otherwise, just use the default */
214 PCMBUF_WATERMARK;
217 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
218 * in a separate function for the moment */
219 static inline void pcmbuf_add_chunk(void)
221 register size_t size = audiobuffer_fillpos;
222 /* Grab the next description to write, and change the write pointer */
223 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
224 pcmbuf_write = pcmbuf_current->link;
225 /* Fill in the values in the new buffer chunk */
226 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
227 pcmbuf_current->size = size;
228 pcmbuf_current->callback = pcmbuf_event_handler;
229 pcmbuf_current->link = NULL;
230 /* This is single use only */
231 pcmbuf_event_handler = NULL;
232 if (pcmbuf_read != NULL) {
233 if (pcmbuf_flush)
235 pcmbuf_write_end->link = pcmbuf_read->link;
236 pcmbuf_read->link = pcmbuf_current;
237 while (pcmbuf_write_end->link)
239 pcmbuf_write_end = pcmbuf_write_end->link;
240 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
242 pcmbuf_flush = false;
244 /* If there is already a read buffer setup, add to it */
245 else
246 pcmbuf_read_end->link = pcmbuf_current;
247 } else {
248 /* Otherwise create the buffer */
249 pcmbuf_read = pcmbuf_current;
251 /* This is now the last buffer to read */
252 pcmbuf_read_end = pcmbuf_current;
254 /* Update bytes counters */
255 pcmbuf_unplayed_bytes += size;
257 audiobuffer_pos += size;
258 if (audiobuffer_pos >= pcmbuf_size)
259 audiobuffer_pos -= pcmbuf_size;
261 audiobuffer_fillpos = 0;
264 #ifdef HAVE_PRIORITY_SCHEDULING
265 static void boost_codec_thread(bool boost)
267 /* Keep voice and codec threads at the same priority or else voice
268 * will starve if the codec thread's priority is boosted. */
269 if (boost)
271 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
272 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
274 if (priority != codec_thread_priority)
276 codec_thread_priority = priority;
277 thread_set_priority(codec_thread_id, priority);
278 voice_thread_set_priority(priority);
281 else if (codec_thread_priority != PRIORITY_PLAYBACK)
283 thread_set_priority(codec_thread_id, PRIORITY_PLAYBACK);
284 voice_thread_set_priority(PRIORITY_PLAYBACK);
285 codec_thread_priority = PRIORITY_PLAYBACK;
288 #endif /* HAVE_PRIORITY_SCHEDULING */
290 static void pcmbuf_under_watermark(bool under)
292 /* Only codec thread initiates boost - voice boosts the cpu when playing
293 a clip */
294 #ifndef SIMULATOR
295 if (thread_get_current() == codec_thread_id)
296 #endif /* SIMULATOR */
298 if (under)
300 /* Fill audio buffer by boosting cpu */
301 trigger_cpu_boost();
302 #ifdef HAVE_PRIORITY_SCHEDULING
303 /* If buffer is critically low, override UI priority, else
304 set back to the original priority. */
305 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
306 #endif
308 else
310 #ifdef HAVE_PRIORITY_SCHEDULING
311 boost_codec_thread(false);
312 #endif
316 /* Disable crossfade if < .5s of audio */
317 if (LOW_DATA(2))
319 crossfade_active = false;
323 void pcmbuf_set_event_handler(void (*event_handler)(void))
325 pcmbuf_event_handler = event_handler;
328 unsigned int pcmbuf_get_latency(void)
330 /* Be careful how this calculation is rearranged, it's easy to overflow */
331 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
332 return bytes / 4 / (NATIVE_FREQUENCY/1000);
335 void pcmbuf_set_low_latency(bool state)
337 low_latency_mode = state;
340 bool pcmbuf_is_lowdata(void)
342 if (!pcm_is_playing() || pcm_is_paused() ||
343 crossfade_init || crossfade_active)
344 return false;
346 #if MEMORYSIZE > 2
347 /* 1 seconds of buffer is low data */
348 return LOW_DATA(4);
349 #else
350 /* under watermark is low data */
351 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
352 #endif
355 /* Amount of bytes left in the buffer. */
356 inline size_t pcmbuf_free(void)
358 if (pcmbuf_read != NULL)
360 void *read = pcmbuf_read->addr;
361 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
362 if (read < write)
363 return (size_t)(read - write) + pcmbuf_size;
364 else
365 return (size_t) (read - write);
367 return pcmbuf_size;
370 bool pcmbuf_crossfade_init(bool manual_skip)
372 /* Can't do two crossfades at once and, no fade if pcm is off now */
373 if (crossfade_init || crossfade_active || !pcm_is_playing())
375 pcmbuf_play_stop();
376 return false;
379 trigger_cpu_boost();
381 /* Not enough data, or crossfade disabled, flush the old data instead */
382 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
384 pcmbuf_flush_fillpos();
385 pcmbuf_flush = true;
386 return false;
389 /* Don't enable mix mode when skipping tracks manually. */
390 if (manual_skip)
391 crossfade_mixmode = false;
392 else
393 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
395 crossfade_init = true;
397 return true;
401 void pcmbuf_play_stop(void)
403 pcm_play_stop();
405 pcmbuf_unplayed_bytes = 0;
406 pcmbuf_mix_chunk = NULL;
407 if (pcmbuf_read) {
408 pcmbuf_write_end->link = pcmbuf_read;
409 pcmbuf_write_end = pcmbuf_read_end;
410 pcmbuf_read = pcmbuf_read_end = NULL;
412 audiobuffer_pos = 0;
413 audiobuffer_fillpos = 0;
414 crossfade_init = false;
415 crossfade_active = false;
416 pcmbuf_flush = false;
418 #ifdef HAVE_PRIORITY_SCHEDULING
419 /* Can unboost the codec thread here no matter who's calling */
420 boost_codec_thread(false);
421 #endif
424 int pcmbuf_used_descs(void)
426 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
427 unsigned int i = 0;
428 while (pcmbuf_temp) {
429 pcmbuf_temp = pcmbuf_temp->link;
430 i++;
432 return i;
435 int pcmbuf_descs(void)
437 return PCMBUF_DESCS(pcmbuf_size);
440 static void pcmbuf_init_pcmbuffers(void)
442 struct pcmbufdesc *next = pcmbuf_write;
443 next++;
444 pcmbuf_write_end = pcmbuf_write;
445 while ((void *)next < (void *)pcmbuf_bufend) {
446 pcmbuf_write_end->link=next;
447 pcmbuf_write_end=next;
448 next++;
452 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
454 size_t seconds = 1;
456 if (crossfade_enabled_pending)
457 seconds += global_settings.crossfade_fade_out_delay
458 + global_settings.crossfade_fade_out_duration;
460 #if MEMORYSIZE > 2
461 /* Buffer has to be at least 2s long. */
462 seconds += 2;
463 #endif
464 logf("pcmbuf len: %ld", (long)seconds);
465 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
468 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
470 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
471 PCMBUF_DESCS_SIZE(bufsize));
474 bool pcmbuf_is_same_size(void)
476 if (audiobuffer == NULL)
477 return true; /* Not set up yet even once so always */
479 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
480 return pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
483 /* Initialize the pcmbuffer the structure looks like this:
484 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
485 size_t pcmbuf_init(unsigned char *bufend)
487 pcmbuf_bufend = bufend;
488 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
489 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
490 fadebuf = &audiobuffer[pcmbuf_size];
491 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
492 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
494 pcmbuf_init_pcmbuffers();
496 position_callback = NULL;
497 pcmbuf_event_handler = NULL;
499 pcmbuf_crossfade_enable_finished();
501 pcmbuf_play_stop();
503 return pcmbuf_bufend - audiobuffer;
506 size_t pcmbuf_get_bufsize(void)
508 return pcmbuf_size;
511 #ifdef ROCKBOX_HAS_LOGF
512 unsigned char * pcmbuf_get_meminfo(size_t *length)
514 *length = pcmbuf_bufend - audiobuffer;
515 return audiobuffer;
517 #endif
519 void pcmbuf_pause(bool pause)
521 if (pcm_is_playing())
522 pcm_play_pause(!pause);
523 else if (!pause)
524 pcmbuf_play_start();
527 /* Force playback. */
528 void pcmbuf_play_start(void)
530 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && pcmbuf_read != NULL)
532 last_chunksize = pcmbuf_read->size;
533 pcmbuf_unplayed_bytes -= last_chunksize;
534 pcm_play_data(pcmbuf_callback,
535 (unsigned char *)pcmbuf_read->addr, last_chunksize);
540 * Commit samples waiting to the pcm buffer.
542 static bool pcmbuf_flush_fillpos(void)
544 if (audiobuffer_fillpos) {
545 /* Never use the last buffer descriptor */
546 while (pcmbuf_write == pcmbuf_write_end) {
547 /* If this happens, something is being stupid */
548 if (!pcm_is_playing()) {
549 logf("pcmbuf_flush_fillpos error");
550 pcmbuf_play_start();
552 /* Let approximately one chunk of data playback */
553 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
555 pcmbuf_add_chunk();
556 return true;
558 return false;
561 /**
562 * Low memory targets don't have crossfade, so don't compile crossfade
563 * specific code in order to save some memory. */
565 #ifdef HAVE_CROSSFADE
567 * Completely process the crossfade fade out effect with current pcm buffer.
569 static void crossfade_process_buffer(size_t fade_in_delay,
570 size_t fade_out_delay, size_t fade_out_rem)
572 if (!crossfade_mixmode)
574 /* Fade out the specified amount of the already processed audio */
575 size_t total_fade_out = fade_out_rem;
576 size_t fade_out_sample;
577 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
579 /* Find the right chunk to start fading out */
580 fade_out_delay += crossfade_sample * 2;
581 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
583 fade_out_delay -= fade_out_chunk->size;
584 fade_out_chunk = fade_out_chunk->link;
586 /* The start sample within the chunk */
587 fade_out_sample = fade_out_delay / 2;
589 while (fade_out_rem > 0)
591 /* Each 1/10 second of audio will have the same fade applied */
592 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
593 int factor = (fade_out_rem << 8) / total_fade_out;
595 fade_out_rem -= block_rem;
597 /* Fade this block */
598 while (block_rem > 0 && fade_out_chunk != NULL)
600 /* Fade one sample */
601 int16_t *buf = (int16_t *)fade_out_chunk->addr;
602 int32_t sample = buf[fade_out_sample];
603 buf[fade_out_sample++] = (sample * factor) >> 8;
605 block_rem -= 2;
606 /* Move to the next chunk as needed */
607 if (fade_out_sample * 2 >= fade_out_chunk->size)
609 fade_out_chunk = fade_out_chunk->link;
610 fade_out_sample = 0;
616 /* Find the right chunk and sample to start fading in */
617 fade_in_delay += crossfade_sample * 2;
618 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
620 fade_in_delay -= crossfade_chunk->size;
621 crossfade_chunk = crossfade_chunk->link;
623 crossfade_sample = fade_in_delay / 2;
624 logf("process done!");
627 /* Initializes crossfader, calculates all necessary parameters and
628 * performs fade-out with the pcm buffer. */
629 static void crossfade_start(void)
631 size_t crossfade_rem;
632 size_t crossfade_need;
633 size_t fade_out_rem;
634 size_t fade_out_delay;
635 size_t fade_in_delay;
637 crossfade_init = false;
638 /* Reject crossfade if less than .5s of data */
639 if (LOW_DATA(2)) {
640 logf("crossfade rejected");
641 pcmbuf_play_stop();
642 return ;
645 logf("crossfade_start");
646 pcmbuf_flush_fillpos();
647 crossfade_active = true;
649 /* Initialize the crossfade buffer size to all of the buffered data that
650 * has not yet been sent to the DMA */
651 crossfade_rem = pcmbuf_unplayed_bytes;
652 crossfade_chunk = pcmbuf_read->link;
653 crossfade_sample = 0;
655 /* Get fade out delay from settings. */
656 fade_out_delay =
657 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
659 /* Get fade out duration from settings. */
660 fade_out_rem =
661 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
663 crossfade_need = fade_out_delay + fade_out_rem;
664 /* We want only to modify the last part of the buffer. */
665 if (crossfade_rem > crossfade_need)
667 size_t crossfade_extra = crossfade_rem - crossfade_need;
668 while (crossfade_extra > crossfade_chunk->size)
670 crossfade_extra -= crossfade_chunk->size;
671 crossfade_chunk = crossfade_chunk->link;
673 crossfade_sample = crossfade_extra / 2;
675 /* Truncate fade out duration if necessary. */
676 else if (crossfade_rem < crossfade_need)
678 size_t crossfade_short = crossfade_need - crossfade_rem;
679 if (fade_out_rem >= crossfade_short)
680 fade_out_rem -= crossfade_short;
681 else
683 fade_out_delay -= crossfade_short - fade_out_rem;
684 fade_out_rem = 0;
688 /* Get also fade in duration and delays from settings. */
689 crossfade_fade_in_total =
690 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
691 crossfade_fade_in_rem = crossfade_fade_in_total;
693 fade_in_delay =
694 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
696 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
699 /* Returns the number of bytes _NOT_ mixed */
700 static size_t crossfade_mix(int factor, const char *buf, size_t length)
702 const int16_t *input_buf = (const int16_t *)buf;
703 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
704 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
705 output_buf = &output_buf[crossfade_sample];
706 int32_t sample;
708 while (length)
710 /* fade left and right channel at once to keep buffer alignment */
711 int i;
712 for (i = 0; i < 2; i++)
714 sample = *input_buf++;
715 sample = ((sample * factor) >> 8) + *output_buf;
716 *output_buf++ = clip_sample_16(sample);
719 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
721 if (output_buf >= chunk_end)
723 crossfade_chunk = crossfade_chunk->link;
724 if (!crossfade_chunk)
725 return length;
726 output_buf = (int16_t *)crossfade_chunk->addr;
727 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
730 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
731 return 0;
734 static void pcmbuf_flush_buffer(const char *buf, size_t length)
736 size_t copy_n;
737 while (length > 0) {
738 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
739 if (NEED_FLUSH(audiobuffer_index))
741 pcmbuf_flush_fillpos();
742 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
744 copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
745 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
746 buf += copy_n;
747 audiobuffer_fillpos += copy_n;
748 length -= copy_n;
752 static void flush_crossfade(char *buf, size_t length)
754 if (length)
756 if (crossfade_fade_in_rem)
758 size_t samples;
759 int16_t *input_buf;
761 /* Fade factor for this packet */
762 int factor =
763 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
764 crossfade_fade_in_total;
765 /* Bytes to fade */
766 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
768 /* We _will_ fade this many bytes */
769 crossfade_fade_in_rem -= fade_rem;
771 if (crossfade_chunk)
773 /* Mix the data */
774 size_t fade_total = fade_rem;
775 fade_rem = crossfade_mix(factor, buf, fade_rem);
776 length -= fade_total - fade_rem;
777 buf += fade_total - fade_rem;
778 if (!length)
779 return;
782 samples = fade_rem / 2;
783 input_buf = (int16_t *)buf;
784 /* Fade remaining samples in place */
785 while (samples--)
787 int32_t sample = *input_buf;
788 *input_buf++ = (sample * factor) >> 8;
792 if (crossfade_chunk)
794 /* Mix the data */
795 size_t mix_total = length;
796 length = crossfade_mix(256, buf, length);
797 buf += mix_total - length;
798 if (!length)
799 return;
802 /* Flush samples to the buffer */
803 while (!prepare_insert(length))
804 sleep(1);
805 pcmbuf_flush_buffer(buf, length);
809 #endif
811 static bool prepare_insert(size_t length)
813 if (low_latency_mode)
815 /* 1/4s latency. */
816 if (!LOW_DATA(1) && pcm_is_playing())
817 return false;
820 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
821 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
822 return false;
824 if (!pcm_is_playing())
826 trigger_cpu_boost();
828 /* Pre-buffer up to watermark */
829 #if MEMORYSIZE > 2
830 if (!LOW_DATA(4))
831 #else
832 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
833 #endif
835 logf("pcm starting");
836 if (!(audio_status() & AUDIO_STATUS_PAUSE))
837 pcmbuf_play_start();
840 else
841 pcmbuf_under_watermark(pcmbuf_unplayed_bytes <= pcmbuf_watermark);
843 return true;
846 void* pcmbuf_request_buffer(int *count)
848 #ifdef HAVE_CROSSFADE
849 if (crossfade_init)
850 crossfade_start();
851 #endif
853 if (crossfade_active) {
854 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
855 return fadebuf;
857 else
859 if(prepare_insert(*count << 2))
861 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
862 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
864 /* Usual case, there's space here */
865 return &audiobuffer[audiobuffer_index];
867 else
869 /* Flush and wrap the buffer */
870 pcmbuf_flush_fillpos();
871 audiobuffer_pos = 0;
872 return &audiobuffer[0];
875 else
877 return NULL;
882 void * pcmbuf_request_voice_buffer(int *count)
884 /* A get-it-to-work-for-now hack (audio status could change by
885 completion) */
886 if (audio_status() & AUDIO_STATUS_PLAY)
888 if (pcmbuf_read == NULL)
890 return NULL;
892 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
893 (pcmbuf_mix_chunk || pcmbuf_read->link))
895 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
896 return voicebuf;
898 else
900 return NULL;
903 else
905 return pcmbuf_request_buffer(count);
909 bool pcmbuf_is_crossfade_active(void)
911 return crossfade_active || crossfade_init;
914 void pcmbuf_write_complete(int count)
916 size_t length = (size_t)(unsigned int)count << 2;
917 #ifdef HAVE_CROSSFADE
918 if (crossfade_active)
920 flush_crossfade(fadebuf, length);
921 if (!(crossfade_fade_in_rem || crossfade_chunk))
922 crossfade_active = false;
924 else
925 #endif
927 audiobuffer_fillpos += length;
929 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
930 pcmbuf_flush_fillpos();
934 #ifndef HAVE_HARDWARE_BEEP
935 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
936 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
938 /* Generates a constant square wave sound with a given frequency
939 in Hertz for a duration in milliseconds. */
940 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
942 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
943 int32_t phase = 0;
944 int16_t *bufptr, *bufstart, *bufend;
945 int32_t sample;
946 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
947 bool mix = pcmbuf_read != NULL && pcmbuf_read->link != NULL;
948 int i;
950 bufend = SKIPBYTES((int16_t *)audiobuffer, pcmbuf_size);
952 /* Find the insertion point and set bufstart to the start of it */
953 if (mix)
955 /* Get the currently playing chunk at the current position. */
956 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
958 /* If above isn't implemented or pcm is stopped, no beepeth. */
959 if (!bufstart || !pcm_is_playing())
960 return;
962 /* Give 5ms clearance. */
963 bufstart += NATIVE_FREQUENCY * 4 / 200;
965 #ifdef HAVE_PCM_DMA_ADDRESS
966 /* Returned peak addresses are DMA addresses */
967 bufend = pcm_dma_addr(bufend);
968 #endif
970 /* Wrapped above? */
971 if (bufstart >= bufend)
972 bufstart -= pcmbuf_size;
974 /* NOTE: On some targets using hardware DMA, cache range flushing may
975 * be required or the writes may not be picked up by the controller.
976 * An incremental flush should be done periodically during the mixdown. */
978 else if (nsamples <= MINIBUF_SAMPLES)
980 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
981 /* Use mini buffer */
982 bufstart = minibuf;
983 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
985 else if (audio_buffer_state() != AUDIOBUF_STATE_TRASHED)
987 /* Use audiobuffer */
988 bufstart = (int16_t *)audiobuffer;
990 else
992 /* No place */
993 return;
996 bufptr = bufstart;
998 /* Mix square wave into buffer */
999 for (i = 0; i < nsamples; ++i)
1001 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
1002 sample = mix ? *bufptr : 0;
1003 *bufptr++ = clip_sample_16(sample + amp);
1004 if (bufptr >= bufend)
1005 bufptr = (int16_t *)audiobuffer;
1006 sample = mix ? *bufptr : 0;
1007 *bufptr++ = clip_sample_16(sample + amp);
1008 if (bufptr >= bufend)
1009 bufptr = (int16_t *)audiobuffer;
1011 phase += step;
1014 pcm_play_lock();
1015 #ifdef HAVE_RECORDING
1016 pcm_rec_lock();
1017 #endif
1019 /* Kick off playback if required and it won't interfere */
1020 if (!pcm_is_playing()
1021 #ifdef HAVE_RECORDING
1022 && !pcm_is_recording()
1023 #endif
1026 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1029 pcm_play_unlock();
1030 #ifdef HAVE_RECORDING
1031 pcm_rec_unlock();
1032 #endif
1034 #endif /* HAVE_HARDWARE_BEEP */
1036 /* Returns pcm buffer usage in percents (0 to 100). */
1037 int pcmbuf_usage(void)
1039 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1042 int pcmbuf_mix_free(void)
1044 if (pcmbuf_mix_chunk)
1046 size_t my_mix_end =
1047 (size_t)&((int16_t *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1048 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1049 if (my_write_pos < my_mix_end)
1050 my_write_pos += pcmbuf_size;
1051 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1053 return 100;
1056 void pcmbuf_write_voice_complete(int count)
1058 /* A get-it-to-work-for-now hack (audio status could have changed) */
1059 if (!(audio_status() & AUDIO_STATUS_PLAY))
1061 pcmbuf_write_complete(count);
1062 return;
1065 int16_t *ibuf = (int16_t *)voicebuf;
1066 int16_t *obuf;
1067 size_t chunk_samples;
1069 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1071 pcmbuf_mix_chunk = pcmbuf_read->link;
1072 /* Start 1/8s into the next chunk */
1073 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1076 if (!pcmbuf_mix_chunk)
1077 return;
1079 obuf = (int16_t *)pcmbuf_mix_chunk->addr;
1080 chunk_samples = pcmbuf_mix_chunk->size / sizeof (int16_t);
1082 count <<= 1;
1084 while (count-- > 0)
1086 int32_t sample = *ibuf++;
1088 if (pcmbuf_mix_sample >= chunk_samples)
1090 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1091 if (!pcmbuf_mix_chunk)
1092 return;
1093 pcmbuf_mix_sample = 0;
1094 obuf = pcmbuf_mix_chunk->addr;
1095 chunk_samples = pcmbuf_mix_chunk->size / 2;
1097 sample += obuf[pcmbuf_mix_sample] >> 2;
1098 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1102 void pcmbuf_crossfade_enable(bool on_off)
1104 /* Next setting to be used, not applied now */
1105 crossfade_enabled_pending = on_off;
1108 void pcmbuf_crossfade_enable_finished(void)
1110 /* Copy the pending setting over now */
1111 crossfade_enabled = crossfade_enabled_pending;
1112 pcmbuf_set_watermark_bytes();
1115 bool pcmbuf_is_crossfade_enabled(void)
1117 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
1118 return global_settings.playlist_shuffle;
1120 return crossfade_enabled;