fix red and remove tabs
[kugel-rb.git] / apps / pcmbuf.c
blob03a5752e9d2bc9216fca763cb58f521081d65a43
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
20 #include <stdbool.h>
21 #include <stdio.h>
22 #include "config.h"
23 #include "debug.h"
24 #include "panic.h"
25 #include <kernel.h>
26 #include "pcmbuf.h"
27 #include "pcm.h"
28 #include "logf.h"
29 #ifndef SIMULATOR
30 #include "cpu.h"
31 #endif
32 #include "system.h"
33 #include <string.h>
34 #include "buffer.h"
35 #include "settings.h"
36 #include "audio.h"
37 #include "voice_thread.h"
38 #include "dsp.h"
39 #include "thread.h"
41 /* Define PCMBUF_MUTING if the codec requires muting to prevent pops */
42 #if !defined(HAVE_UDA1380) && !defined(HAVE_TLV320) && !defined(HAVE_AS3514)
43 #define PCMBUF_MUTING
44 #endif
46 /* Clip sample to signed 16 bit range */
47 static inline int32_t clip_sample_16(int32_t sample)
49 if ((int16_t)sample != sample)
50 sample = 0x7fff ^ (sample >> 31);
51 return sample;
54 /* Keep watermark high for iPods at least (2s) */
55 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
57 /* Structure we can use to queue pcm chunks in memory to be played
58 * by the driver code. */
59 struct pcmbufdesc
61 void *addr;
62 size_t size;
63 struct pcmbufdesc* link;
64 /* Call this when the buffer has been played */
65 void (*callback)(void);
68 #define PCMBUF_DESCS(bufsize) \
69 ((bufsize) / PCMBUF_MINAVG_CHUNK)
70 #define PCMBUF_DESCS_SIZE(bufsize) \
71 (PCMBUF_DESCS(bufsize)*sizeof(struct pcmbufdesc))
73 /* Size of the PCM buffer. */
74 static size_t pcmbuf_size IDATA_ATTR = 0;
75 static char *pcmbuf_bufend IDATA_ATTR;
76 static char *audiobuffer IDATA_ATTR;
77 /* Current audio buffer write index. */
78 static size_t audiobuffer_pos IDATA_ATTR;
79 /* Amount audiobuffer_pos will be increased.*/
80 static size_t audiobuffer_fillpos IDATA_ATTR;
81 static char *fadebuf IDATA_ATTR;
82 static char *voicebuf IDATA_ATTR;
84 static void (*pcmbuf_event_handler)(void) IDATA_ATTR;
85 static void (*position_callback)(size_t size) IDATA_ATTR;
87 /* Crossfade related state */
88 static bool crossfade_enabled;
89 static bool crossfade_enabled_pending;
90 static bool crossfade_mixmode;
91 static bool crossfade_active IDATA_ATTR;
92 static bool crossfade_init IDATA_ATTR;
94 /* Track the current location for processing crossfade */
95 static struct pcmbufdesc *crossfade_chunk IDATA_ATTR;
96 static size_t crossfade_sample IDATA_ATTR;
98 /* Counters for fading in new data */
99 static size_t crossfade_fade_in_total IDATA_ATTR;
100 static size_t crossfade_fade_in_rem IDATA_ATTR;
102 static struct pcmbufdesc *pcmbuf_read IDATA_ATTR;
103 static struct pcmbufdesc *pcmbuf_read_end IDATA_ATTR;
104 static struct pcmbufdesc *pcmbuf_write IDATA_ATTR;
105 static struct pcmbufdesc *pcmbuf_write_end IDATA_ATTR;
106 static size_t last_chunksize IDATA_ATTR;
108 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
109 static size_t pcmbuf_watermark IDATA_ATTR;
111 static struct pcmbufdesc *pcmbuf_mix_chunk IDATA_ATTR;
112 static size_t pcmbuf_mix_sample IDATA_ATTR;
114 static bool low_latency_mode = false;
115 static bool pcmbuf_flush;
117 #ifdef HAVE_PRIORITY_SCHEDULING
118 static int codec_thread_priority = PRIORITY_PLAYBACK;
119 #endif
121 extern struct thread_entry *codec_thread_p;
123 /* Helpful macros for use in conditionals this assumes some of the above
124 * static variable names */
125 #define NEED_FLUSH(position) \
126 (audiobuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
127 #define LOW_DATA(quarter_secs) \
128 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
130 static bool prepare_insert(size_t length);
131 static void pcmbuf_under_watermark(void);
132 static bool pcmbuf_flush_fillpos(void);
134 #define CALL_IF_EXISTS(function, args...) if (function) function(args)
135 /* This function has 2 major logical parts (separated by brackets both for
136 * readability and variable scoping). The first part performs the
137 * operastions related to finishing off the last buffer we fed to the DMA.
138 * The second part performs the operations involved in sending a new buffer
139 * to the DMA. Finally the function checks the status of the buffer and
140 * boosts if necessary */
141 static void pcmbuf_callback(unsigned char** start, size_t* size) ICODE_ATTR;
142 static void pcmbuf_callback(unsigned char** start, size_t* size)
145 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
146 /* Take the finished buffer out of circulation */
147 pcmbuf_read = pcmbuf_current->link;
149 /* The buffer is finished, call the callback functions */
150 CALL_IF_EXISTS(position_callback, last_chunksize);
151 CALL_IF_EXISTS(pcmbuf_current->callback);
153 /* Put the finished buffer back into circulation */
154 pcmbuf_write_end->link = pcmbuf_current;
155 pcmbuf_write_end = pcmbuf_current;
157 /* If we've read over the mix chunk while it's still mixing there */
158 if (pcmbuf_current == pcmbuf_mix_chunk)
159 pcmbuf_mix_chunk = NULL;
160 /* If we've read over the crossfade chunk while it's still fading */
161 if (pcmbuf_current == crossfade_chunk)
162 crossfade_chunk = pcmbuf_read;
166 /* Send the new buffer to the pcm */
167 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
168 size_t *realsize = size;
169 unsigned char** realstart = start;
170 if(pcmbuf_new)
172 size_t current_size = pcmbuf_new->size;
174 pcmbuf_unplayed_bytes -= current_size;
175 last_chunksize = current_size;
176 *realsize = current_size;
177 *realstart = pcmbuf_new->addr;
179 else
181 /* No more buffers */
182 last_chunksize = 0;
183 *realsize = 0;
184 *realstart = NULL;
185 CALL_IF_EXISTS(pcmbuf_event_handler);
190 void pcmbuf_set_position_callback(void (*callback)(size_t size))
192 position_callback = callback;
195 static void pcmbuf_set_watermark_bytes(void)
197 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
198 /* If crossfading, try to keep the buffer full other than 1 second */
199 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
200 /* Otherwise, just keep it above 2 second */
201 PCMBUF_WATERMARK;
204 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
205 * in a separate function for the moment */
206 static inline void pcmbuf_add_chunk(void)
208 register size_t size = audiobuffer_fillpos;
209 /* Grab the next description to write, and change the write pointer */
210 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
211 pcmbuf_write = pcmbuf_current->link;
212 /* Fill in the values in the new buffer chunk */
213 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
214 pcmbuf_current->size = size;
215 pcmbuf_current->callback = pcmbuf_event_handler;
216 pcmbuf_current->link = NULL;
217 /* This is single use only */
218 pcmbuf_event_handler = NULL;
219 if (pcmbuf_read != NULL) {
220 if (pcmbuf_flush)
222 pcmbuf_write_end->link = pcmbuf_read->link;
223 pcmbuf_read->link = pcmbuf_current;
224 while (pcmbuf_write_end->link)
226 pcmbuf_write_end = pcmbuf_write_end->link;
227 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
229 pcmbuf_flush = false;
231 /* If there is already a read buffer setup, add to it */
232 else
233 pcmbuf_read_end->link = pcmbuf_current;
234 } else {
235 /* Otherwise create the buffer */
236 pcmbuf_read = pcmbuf_current;
238 /* This is now the last buffer to read */
239 pcmbuf_read_end = pcmbuf_current;
241 /* Update bytes counters */
242 pcmbuf_unplayed_bytes += size;
244 audiobuffer_pos += size;
245 if (audiobuffer_pos >= pcmbuf_size)
246 audiobuffer_pos -= pcmbuf_size;
248 audiobuffer_fillpos = 0;
251 #ifdef HAVE_PRIORITY_SCHEDULING
252 static void boost_codec_thread(bool boost)
254 /* Keep voice and codec threads at the same priority or else voice
255 * will starve if the codec thread's priority is boosted. */
256 if (boost)
258 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
259 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
261 if (priority != codec_thread_priority)
263 codec_thread_priority = priority;
264 thread_set_priority(codec_thread_p, priority);
265 voice_thread_set_priority(priority);
268 else if (codec_thread_priority != PRIORITY_PLAYBACK)
270 thread_set_priority(codec_thread_p, PRIORITY_PLAYBACK);
271 voice_thread_set_priority(PRIORITY_PLAYBACK);
272 codec_thread_priority = PRIORITY_PLAYBACK;
275 #endif /* HAVE_PRIORITY_SCHEDULING */
277 static void pcmbuf_under_watermark(void)
279 /* Only codec thread initiates boost - voice boosts the cpu when playing
280 a clip */
281 #ifndef SIMULATOR
282 if (thread_get_current() == codec_thread_p)
283 #endif /* SIMULATOR */
285 #ifdef HAVE_PRIORITY_SCHEDULING
286 /* If buffer is critically low, override UI priority, else
287 set back to the original priority. */
288 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
289 #endif
290 /* Fill audio buffer by boosting cpu */
291 trigger_cpu_boost();
294 /* Disable crossfade if < .5s of audio */
295 if (LOW_DATA(2))
297 crossfade_active = false;
301 void pcmbuf_set_event_handler(void (*event_handler)(void))
303 pcmbuf_event_handler = event_handler;
306 unsigned int pcmbuf_get_latency(void)
308 /* Be careful how this calculation is rearranged, it's easy to overflow */
309 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
310 return bytes / 4 / (NATIVE_FREQUENCY/1000);
313 void pcmbuf_set_low_latency(bool state)
315 low_latency_mode = state;
318 bool pcmbuf_is_lowdata(void)
320 if (!pcm_is_playing() || pcm_is_paused() ||
321 crossfade_init || crossfade_active)
322 return false;
324 /* 1 seconds of buffer is low data */
325 return LOW_DATA(4);
328 /* Amount of bytes left in the buffer. */
329 inline size_t pcmbuf_free(void)
331 if (pcmbuf_read != NULL)
333 void *read = pcmbuf_read->addr;
334 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
335 if (read < write)
336 return (size_t)(read - write) + pcmbuf_size;
337 else
338 return (size_t) (read - write);
340 return pcmbuf_size;
343 bool pcmbuf_crossfade_init(bool manual_skip)
345 /* Can't do two crossfades at once and, no fade if pcm is off now */
346 if (crossfade_init || crossfade_active || !pcm_is_playing())
348 pcmbuf_play_stop();
349 return false;
352 trigger_cpu_boost();
354 /* Not enough data, or crossfade disabled, flush the old data instead */
355 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
357 pcmbuf_flush_fillpos();
358 pcmbuf_flush = true;
359 return false;
362 /* Don't enable mix mode when skipping tracks manually. */
363 if (manual_skip)
364 crossfade_mixmode = false;
365 else
366 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
368 crossfade_init = true;
370 return true;
374 void pcmbuf_play_stop(void)
376 pcm_play_stop();
378 pcmbuf_unplayed_bytes = 0;
379 pcmbuf_mix_chunk = NULL;
380 if (pcmbuf_read) {
381 pcmbuf_write_end->link = pcmbuf_read;
382 pcmbuf_write_end = pcmbuf_read_end;
383 pcmbuf_read = pcmbuf_read_end = NULL;
385 audiobuffer_pos = 0;
386 audiobuffer_fillpos = 0;
387 crossfade_init = false;
388 crossfade_active = false;
389 pcmbuf_flush = false;
391 #ifdef HAVE_PRIORITY_SCHEDULING
392 /* Can unboost the codec thread here no matter who's calling */
393 boost_codec_thread(false);
394 #endif
397 int pcmbuf_used_descs(void) {
398 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
399 unsigned int i = 0;
400 while (pcmbuf_temp) {
401 pcmbuf_temp = pcmbuf_temp->link;
402 i++;
404 return i;
407 int pcmbuf_descs(void) {
408 return PCMBUF_DESCS(pcmbuf_size);
411 static void pcmbuf_init_pcmbuffers(void) {
412 struct pcmbufdesc *next = pcmbuf_write;
413 next++;
414 pcmbuf_write_end = pcmbuf_write;
415 while ((void *)next < (void *)pcmbuf_bufend) {
416 pcmbuf_write_end->link=next;
417 pcmbuf_write_end=next;
418 next++;
422 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
424 #if MEM > 1
425 size_t seconds = 1;
427 if (crossfade_enabled_pending)
428 seconds += global_settings.crossfade_fade_out_delay
429 + global_settings.crossfade_fade_out_duration;
431 /* Buffer has to be at least 2s long. */
432 seconds += 2;
433 logf("pcmbuf len: %ld", seconds);
434 return seconds * (NATIVE_FREQUENCY*4);
435 #else
436 return NATIVE_FREQUENCY*2;
437 #endif
440 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
442 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
443 PCMBUF_DESCS_SIZE(bufsize));
446 bool pcmbuf_is_same_size(void)
448 if (audiobuffer == NULL)
449 return true; /* Not set up yet even once so always */
451 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
452 return pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
455 /* Initialize the pcmbuffer the structure looks like this:
456 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
457 size_t pcmbuf_init(unsigned char *bufend)
459 pcmbuf_bufend = bufend;
460 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
461 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
462 fadebuf = &audiobuffer[pcmbuf_size];
463 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
464 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
466 pcmbuf_init_pcmbuffers();
468 position_callback = NULL;
469 pcmbuf_event_handler = NULL;
471 pcmbuf_crossfade_enable_finished();
473 pcmbuf_play_stop();
475 return pcmbuf_bufend - audiobuffer;
478 size_t pcmbuf_get_bufsize(void)
480 return pcmbuf_size;
483 #ifdef ROCKBOX_HAS_LOGF
484 unsigned char * pcmbuf_get_meminfo(size_t *length)
486 *length = pcmbuf_bufend - audiobuffer;
487 return audiobuffer;
489 #endif
491 void pcmbuf_pause(bool pause)
493 #ifdef PCMBUF_MUTING
494 if (pause)
495 pcm_mute(true);
496 #endif
498 if (pcm_is_playing())
499 pcm_play_pause(!pause);
500 else if (!pause)
501 pcmbuf_play_start();
503 #ifdef PCMBUF_MUTING
504 if (!pause)
505 pcm_mute(false);
506 #endif
507 trigger_cpu_boost();
510 /* Force playback. */
511 void pcmbuf_play_start(void)
513 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && pcmbuf_read != NULL)
515 last_chunksize = pcmbuf_read->size;
516 pcmbuf_unplayed_bytes -= last_chunksize;
517 pcm_play_data(pcmbuf_callback,
518 (unsigned char *)pcmbuf_read->addr, last_chunksize);
523 * Commit samples waiting to the pcm buffer.
525 static bool pcmbuf_flush_fillpos(void)
527 if (audiobuffer_fillpos) {
528 /* Never use the last buffer descriptor */
529 while (pcmbuf_write == pcmbuf_write_end) {
530 /* If this happens, something is being stupid */
531 if (!pcm_is_playing()) {
532 logf("pcmbuf_flush_fillpos error");
533 pcmbuf_play_start();
535 /* Let approximately one chunk of data playback */
536 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
538 pcmbuf_add_chunk();
539 return true;
541 return false;
545 * Completely process the crossfade fade out effect with current pcm buffer.
547 static void crossfade_process_buffer(size_t fade_in_delay,
548 size_t fade_out_delay, size_t fade_out_rem)
550 if (!crossfade_mixmode)
552 /* Fade out the specified amount of the already processed audio */
553 size_t total_fade_out = fade_out_rem;
554 size_t fade_out_sample;
555 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
557 /* Find the right chunk to start fading out */
558 fade_out_delay += crossfade_sample * 2;
559 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
561 fade_out_delay -= fade_out_chunk->size;
562 fade_out_chunk = fade_out_chunk->link;
564 /* The start sample within the chunk */
565 fade_out_sample = fade_out_delay / 2;
567 while (fade_out_rem > 0)
569 /* Each 1/10 second of audio will have the same fade applied */
570 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
571 int factor = (fade_out_rem << 8) / total_fade_out;
573 fade_out_rem -= block_rem;
575 /* Fade this block */
576 while (block_rem > 0 && fade_out_chunk != NULL)
578 /* Fade one sample */
579 int16_t *buf = (int16_t *)fade_out_chunk->addr;
580 int32_t sample = buf[fade_out_sample];
581 buf[fade_out_sample++] = (sample * factor) >> 8;
583 block_rem -= 2;
584 /* Move to the next chunk as needed */
585 if (fade_out_sample * 2 >= fade_out_chunk->size)
587 fade_out_chunk = fade_out_chunk->link;
588 fade_out_sample = 0;
594 /* Find the right chunk and sample to start fading in */
595 fade_in_delay += crossfade_sample * 2;
596 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
598 fade_in_delay -= crossfade_chunk->size;
599 crossfade_chunk = crossfade_chunk->link;
601 crossfade_sample = fade_in_delay / 2;
602 logf("process done!");
605 /* Initializes crossfader, calculates all necessary parameters and
606 * performs fade-out with the pcm buffer. */
607 static void crossfade_start(void)
609 size_t crossfade_rem;
610 size_t crossfade_need;
611 size_t fade_out_rem;
612 size_t fade_out_delay;
613 size_t fade_in_delay;
615 crossfade_init = false;
616 /* Reject crossfade if less than .5s of data */
617 if (LOW_DATA(2)) {
618 logf("crossfade rejected");
619 pcmbuf_play_stop();
620 return ;
623 logf("crossfade_start");
624 pcmbuf_flush_fillpos();
625 crossfade_active = true;
627 /* Initialize the crossfade buffer size to all of the buffered data that
628 * has not yet been sent to the DMA */
629 crossfade_rem = pcmbuf_unplayed_bytes;
630 crossfade_chunk = pcmbuf_read->link;
631 crossfade_sample = 0;
633 /* Get fade out delay from settings. */
634 fade_out_delay =
635 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
637 /* Get fade out duration from settings. */
638 fade_out_rem =
639 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
641 crossfade_need = fade_out_delay + fade_out_rem;
642 /* We want only to modify the last part of the buffer. */
643 if (crossfade_rem > crossfade_need)
645 size_t crossfade_extra = crossfade_rem - crossfade_need;
646 while (crossfade_extra > crossfade_chunk->size)
648 crossfade_extra -= crossfade_chunk->size;
649 crossfade_chunk = crossfade_chunk->link;
651 crossfade_sample = crossfade_extra / 2;
653 /* Truncate fade out duration if necessary. */
654 else if (crossfade_rem < crossfade_need)
656 size_t crossfade_short = crossfade_need - crossfade_rem;
657 if (fade_out_rem >= crossfade_short)
658 fade_out_rem -= crossfade_short;
659 else
661 fade_out_delay -= crossfade_short - fade_out_rem;
662 fade_out_rem = 0;
666 /* Get also fade in duration and delays from settings. */
667 crossfade_fade_in_total =
668 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
669 crossfade_fade_in_rem = crossfade_fade_in_total;
671 fade_in_delay =
672 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
674 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
677 /* Returns the number of bytes _NOT_ mixed */
678 static size_t crossfade_fade_mix(int factor, const char *buf, size_t fade_rem)
680 const int16_t *input_buf = (const int16_t *)buf;
681 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
682 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
683 output_buf = &output_buf[crossfade_sample];
684 int32_t sample;
686 while (fade_rem)
688 /* fade left and right channel at once to keep buffer alignment */
689 sample = *input_buf++;
690 sample = ((sample * factor) >> 8) + *output_buf;
691 *output_buf++ = clip_sample_16(sample);
693 sample = *input_buf++;
694 sample = ((sample * factor) >> 8) + *output_buf;
695 *output_buf++ = clip_sample_16(sample);
697 fade_rem -= 4; /* 2 samples, each 16 bit -> 4 bytes */
699 if (output_buf >= chunk_end)
701 crossfade_chunk = crossfade_chunk->link;
702 if (!crossfade_chunk)
703 return fade_rem;
704 output_buf = (int16_t *)crossfade_chunk->addr;
705 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
708 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
709 return 0;
712 /* Returns the number of bytes _NOT_ mixed */
713 static size_t crossfade_mix(const char *buf, size_t length)
715 const int16_t *input_buf = (const int16_t *)buf;
716 int16_t *output_buf = (int16_t *)crossfade_chunk->addr;
717 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
718 output_buf = &output_buf[crossfade_sample];
719 int32_t sample;
721 while (length)
723 /* fade left and right channel at once to keep buffer alignment */
724 sample = *input_buf++ + *output_buf;
725 *output_buf++ = clip_sample_16(sample);
727 sample = *input_buf++ + *output_buf;
728 *output_buf++ = clip_sample_16(sample);
730 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
732 if (output_buf >= chunk_end)
734 crossfade_chunk = crossfade_chunk->link;
735 if (!crossfade_chunk)
736 return length;
738 output_buf = (int16_t *)crossfade_chunk->addr;
739 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
742 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
743 return 0;
746 static void pcmbuf_flush_buffer(const char *buf, size_t length)
748 size_t copy_n;
749 while (length > 0) {
750 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
751 if (NEED_FLUSH(audiobuffer_index))
753 pcmbuf_flush_fillpos();
754 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
756 copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
757 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
758 buf += copy_n;
759 audiobuffer_fillpos += copy_n;
760 length -= copy_n;
764 static void flush_crossfade(char *buf, size_t length)
766 if (length)
768 if (crossfade_fade_in_rem)
770 size_t samples;
771 int16_t *input_buf;
773 /* Fade factor for this packet */
774 int factor =
775 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
776 crossfade_fade_in_total;
777 /* Bytes to fade */
778 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
780 /* We _will_ fade this many bytes */
781 crossfade_fade_in_rem -= fade_rem;
783 if (crossfade_chunk)
785 /* Mix the data */
786 size_t fade_total = fade_rem;
787 fade_rem = crossfade_fade_mix(factor, buf, fade_rem);
788 length -= fade_total - fade_rem;
789 buf += fade_total - fade_rem;
790 if (!length)
791 return;
792 if (!fade_rem)
793 goto fade_done;
796 samples = fade_rem / 2;
797 input_buf = (int16_t *)buf;
798 /* Fade remaining samples in place */
799 while (samples)
801 int32_t sample = *input_buf;
802 *input_buf++ = (sample * factor) >> 8;
803 samples--;
807 fade_done:
808 if (crossfade_chunk)
810 /* Mix the data */
811 size_t mix_total = length;
812 length = crossfade_mix(buf, length);
813 buf += mix_total - length;
814 if (!length)
815 return;
818 /* Flush samples to the buffer */
819 while (!prepare_insert(length))
820 sleep(1);
821 pcmbuf_flush_buffer(buf, length);
826 static bool prepare_insert(size_t length)
828 if (low_latency_mode)
830 /* 1/4s latency. */
831 if (pcmbuf_unplayed_bytes > NATIVE_FREQUENCY * 4 / 2
832 && pcm_is_playing())
833 return false;
836 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
837 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
838 return false;
840 if (!pcm_is_playing())
842 trigger_cpu_boost();
844 /* Pre-buffer 1s. */
845 #if MEM <= 1
846 if (!LOW_DATA(1))
847 #else
848 if (!LOW_DATA(4))
849 #endif
851 logf("pcm starting");
852 if (!(audio_status() & AUDIO_STATUS_PAUSE))
853 pcmbuf_play_start();
856 else if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
857 pcmbuf_under_watermark();
859 return true;
862 void* pcmbuf_request_buffer(int *count)
864 if (crossfade_init)
865 crossfade_start();
867 if (crossfade_active) {
868 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
869 return fadebuf;
871 else
873 if(prepare_insert(*count << 2))
875 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
876 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
878 /* Usual case, there's space here */
879 return &audiobuffer[audiobuffer_index];
881 else
883 /* Flush and wrap the buffer */
884 pcmbuf_flush_fillpos();
885 audiobuffer_pos = 0;
886 return &audiobuffer[0];
889 else
891 return NULL;
896 void * pcmbuf_request_voice_buffer(int *count)
898 /* A get-it-to-work-for-now hack (audio status could change by
899 completion) */
900 if (audio_status() & AUDIO_STATUS_PLAY)
902 if (pcmbuf_read == NULL)
904 return NULL;
906 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
907 (pcmbuf_mix_chunk || pcmbuf_read->link))
909 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
910 return voicebuf;
912 else
914 return NULL;
917 else
919 return pcmbuf_request_buffer(count);
923 bool pcmbuf_is_crossfade_active(void)
925 return crossfade_active || crossfade_init;
928 void pcmbuf_write_complete(int count)
930 size_t length = (size_t)(unsigned int)count << 2;
932 if (crossfade_active)
934 flush_crossfade(fadebuf, length);
935 if (!(crossfade_fade_in_rem || crossfade_chunk))
936 crossfade_active = false;
938 else
940 audiobuffer_fillpos += length;
942 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
943 pcmbuf_flush_fillpos();
947 #if 0
948 bool pcmbuf_insert_buffer(char *buf, int count)
950 size_t length = (size_t)(unsigned int)count << 2;
952 if (crossfade_active)
954 flush_crossfade(buf, length);
955 if (!(crossfade_fade_in_rem || crossfade_chunk))
956 crossfade_active = false;
958 else
960 if (!prepare_insert(length))
961 return false;
962 pcmbuf_flush_buffer(buf, length);
964 return true;
966 #endif
968 /* Generates a constant square wave sound with a given frequency
969 in Hertz for a duration in milliseconds. */
970 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
972 unsigned int count = 0;
973 unsigned int i;
974 unsigned int interval = NATIVE_FREQUENCY / frequency;
975 unsigned int samples = NATIVE_FREQUENCY / 1000 * duration;
976 int32_t sample;
977 int16_t *bufstart;
978 int16_t *bufptr;
979 int16_t *pcmbuf_end = (int16_t *)fadebuf;
980 bool mix = pcmbuf_read != NULL && pcmbuf_read->link != NULL;
982 /* Find the insertion point and set bufstart to the start of it */
983 if (mix)
985 /* Get the next chunk */
986 char *pcmbuf_mix_buf = pcmbuf_read->link->addr;
987 /* Give 1/8s clearance. */
988 bufstart = (int16_t *)&pcmbuf_mix_buf[NATIVE_FREQUENCY * 4 / 8];
990 else
992 /* Use audiobuffer */
993 bufstart = (int16_t *)audiobuffer;
996 /* Mix square wave into buffer */
997 bufptr = bufstart;
998 for (i = 0; i < samples; ++i)
1000 sample = mix ? *bufptr : 0;
1001 *bufptr++ = clip_sample_16(sample + amplitude);
1002 if (bufptr > pcmbuf_end)
1003 bufptr = (int16_t *)audiobuffer;
1004 sample = mix ? *bufptr : 0;
1005 *bufptr++ = clip_sample_16(sample + amplitude);
1006 if (bufptr > pcmbuf_end)
1007 bufptr = (int16_t *)audiobuffer;
1009 /* Toggle square wave edge */
1010 if (++count >= interval)
1012 count = 0;
1013 amplitude = -amplitude;
1017 /* Kick off playback if required */
1018 if (!pcm_is_playing())
1020 pcm_play_data(NULL, (unsigned char *)bufstart, samples * 4);
1025 /* Returns pcm buffer usage in percents (0 to 100). */
1026 int pcmbuf_usage(void)
1028 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1031 int pcmbuf_mix_free(void)
1033 if (pcmbuf_mix_chunk)
1035 size_t my_mix_end =
1036 (size_t)&((int16_t *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1037 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1038 if (my_write_pos < my_mix_end)
1039 my_write_pos += pcmbuf_size;
1040 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1042 return 100;
1045 void pcmbuf_write_voice_complete(int count)
1047 /* A get-it-to-work-for-now hack (audio status could have changed) */
1048 if (!(audio_status() & AUDIO_STATUS_PLAY))
1050 pcmbuf_write_complete(count);
1051 return;
1054 int16_t *ibuf = (int16_t *)voicebuf;
1055 int16_t *obuf;
1056 size_t chunk_samples;
1058 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1060 pcmbuf_mix_chunk = pcmbuf_read->link;
1061 /* Start 1/8s into the next chunk */
1062 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1065 if (!pcmbuf_mix_chunk)
1066 return;
1068 obuf = (int16_t *)pcmbuf_mix_chunk->addr;
1069 chunk_samples = pcmbuf_mix_chunk->size / sizeof (int16_t);
1071 count <<= 1;
1073 while (count-- > 0)
1075 int32_t sample = *ibuf++;
1077 if (pcmbuf_mix_sample >= chunk_samples)
1079 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1080 if (!pcmbuf_mix_chunk)
1081 return;
1082 pcmbuf_mix_sample = 0;
1083 obuf = pcmbuf_mix_chunk->addr;
1084 chunk_samples = pcmbuf_mix_chunk->size / 2;
1086 sample += obuf[pcmbuf_mix_sample] >> 2;
1087 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1091 void pcmbuf_crossfade_enable(bool on_off)
1093 #if MEM > 1
1094 /* Next setting to be used, not applied now */
1095 crossfade_enabled_pending = on_off;
1096 #endif
1097 (void)on_off;
1100 void pcmbuf_crossfade_enable_finished(void)
1102 /* Copy the pending setting over now */
1103 crossfade_enabled = crossfade_enabled_pending;
1104 pcmbuf_set_watermark_bytes();
1107 bool pcmbuf_is_crossfade_enabled(void)
1109 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
1110 return global_settings.playlist_shuffle;
1112 return crossfade_enabled;