1 is the correct value here. Not that it makes any difference... :)
[kugel-rb.git] / apps / pcmbuf.c
blobb18d411db6f68fab553c6c15f78867cd73b55b1c
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_playback.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 "dsp.h"
39 /* 1.5s low mark */
40 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 6)
42 /* Structure we can use to queue pcm chunks in memory to be played
43 * by the driver code. */
44 struct pcmbufdesc
46 void *addr;
47 size_t size;
48 struct pcmbufdesc* link;
49 /* Call this when the buffer has been played */
50 void (*callback)(void);
53 /* Size of the PCM buffer. */
54 static size_t pcmbuf_size IDATA_ATTR = 0;
56 static char *audiobuffer IDATA_ATTR;
57 /* Current audio buffer write index. */
58 static size_t audiobuffer_pos IDATA_ATTR;
59 /* Amount audiobuffer_pos will be increased.*/
60 static size_t audiobuffer_fillpos IDATA_ATTR;
61 static char *fadebuf IDATA_ATTR;
62 static char *voicebuf IDATA_ATTR;
64 static void (*pcmbuf_event_handler)(void) IDATA_ATTR;
65 static void (*position_callback)(size_t size) IDATA_ATTR;
67 /* Crossfade related state */
68 static bool crossfade_enabled;
69 static bool crossfade_mixmode;
70 static bool crossfade_active IDATA_ATTR;
71 static bool crossfade_init IDATA_ATTR;
73 /* Track the current location for processing crossfade */
74 static struct pcmbufdesc *crossfade_chunk IDATA_ATTR;
75 static size_t crossfade_sample IDATA_ATTR;
77 /* Counters for fading in new data */
78 static size_t crossfade_fade_in_total IDATA_ATTR;
79 static size_t crossfade_fade_in_rem IDATA_ATTR;
81 static size_t pcmbuf_descsize;
82 static struct pcmbufdesc *pcmbuf_read IDATA_ATTR;
83 static struct pcmbufdesc *pcmbuf_read_end IDATA_ATTR;
84 static struct pcmbufdesc *pcmbuf_write IDATA_ATTR;
85 static struct pcmbufdesc *pcmbuf_write_end IDATA_ATTR;
86 static size_t last_chunksize IDATA_ATTR;
88 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
89 static size_t pcmbuf_watermark IDATA_ATTR;
91 static struct pcmbufdesc *pcmbuf_mix_chunk IDATA_ATTR;
92 static size_t pcmbuf_mix_sample IDATA_ATTR;
94 static bool low_latency_mode = false;
95 static bool pcmbuf_flush;
97 /* Helpful macros for use in conditionals this assumes some of the above
98 * static variable names */
99 #define NEED_FLUSH(position) \
100 (audiobuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
101 #define LOW_DATA(quarter_secs) \
102 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
104 static bool prepare_insert(size_t length);
105 static void pcmbuf_under_watermark(void);
106 static bool pcmbuf_flush_fillpos(void);
108 #if defined(HAVE_ADJUSTABLE_CPU_FREQ) && !defined(SIMULATOR)
109 void pcmbuf_boost(bool state)
111 static bool boost_state = false;
113 if (crossfade_init || crossfade_active)
114 return;
116 if (state != boost_state) {
117 cpu_boost(state);
118 boost_state = state;
121 #endif
123 #define CALL_IF_EXISTS(function, args...) if (function) function(args)
124 /* This function has 2 major logical parts (separated by brackets both for
125 * readability and variable scoping). The first part performs the
126 * operastions related to finishing off the last buffer we fed to the DMA.
127 * The second part performs the operations involved in sending a new buffer
128 * to the DMA. Finally the function checks the status of the buffer and
129 * boosts if necessary */
130 static void pcmbuf_callback(unsigned char** start, size_t* size) ICODE_ATTR;
131 static void pcmbuf_callback(unsigned char** start, size_t* size)
134 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
135 /* Take the finished buffer out of circulation */
136 pcmbuf_read = pcmbuf_current->link;
138 /* The buffer is finished, call the callback functions */
139 CALL_IF_EXISTS(position_callback, last_chunksize);
140 CALL_IF_EXISTS(pcmbuf_current->callback);
142 /* Put the finished buffer back into circulation */
143 pcmbuf_write_end->link = pcmbuf_current;
144 pcmbuf_write_end = pcmbuf_current;
146 /* If we've read over the mix chunk while it's still mixing there */
147 if (pcmbuf_current == pcmbuf_mix_chunk)
148 pcmbuf_mix_chunk = NULL;
149 /* If we've read over the crossfade chunk while it's still fading */
150 if (pcmbuf_current == crossfade_chunk)
151 crossfade_chunk = pcmbuf_read;
154 process_new_buffer:
156 /* Send the new buffer to the pcm */
157 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
158 size_t *realsize = size;
159 unsigned char** realstart = start;
160 if(pcmbuf_new)
162 size_t current_size = pcmbuf_new->size;
164 pcmbuf_unplayed_bytes -= current_size;
165 last_chunksize = current_size;
166 *realsize = current_size;
167 *realstart = pcmbuf_new->addr;
169 else
171 /* There may be more data waiting to flush, try to use it */
172 if (pcmbuf_flush_fillpos())
173 goto process_new_buffer;
175 /* No more buffers */
176 last_chunksize = 0;
177 *realsize = 0;
178 *realstart = NULL;
179 CALL_IF_EXISTS(pcmbuf_event_handler);
184 void pcmbuf_set_position_callback(void (*callback)(size_t size))
186 position_callback = callback;
189 static void pcmbuf_set_watermark_bytes(size_t numbytes)
191 pcmbuf_watermark = numbytes;
194 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
195 * in a separate function for the moment */
196 static inline void pcmbuf_add_chunk(void)
198 register size_t size = audiobuffer_fillpos;
199 /* Grab the next description to write, and change the write pointer */
200 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
201 pcmbuf_write = pcmbuf_current->link;
202 /* Fill in the values in the new buffer chunk */
203 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
204 pcmbuf_current->size = size;
205 pcmbuf_current->callback = pcmbuf_event_handler;
206 pcmbuf_current->link = NULL;
207 /* This is single use only */
208 pcmbuf_event_handler = NULL;
209 if (pcmbuf_read) {
210 if (pcmbuf_flush)
212 pcmbuf_write_end->link = pcmbuf_read->link;
213 pcmbuf_read->link = pcmbuf_current;
214 while (pcmbuf_write_end->link)
216 pcmbuf_write_end = pcmbuf_write_end->link;
217 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
219 pcmbuf_flush = false;
221 /* If there is already a read buffer setup, add to it */
222 else
223 pcmbuf_read_end->link = pcmbuf_current;
224 } else {
225 /* Otherwise create the buffer */
226 pcmbuf_read = pcmbuf_current;
228 /* This is now the last buffer to read */
229 pcmbuf_read_end = pcmbuf_current;
231 /* Update bytes counters */
232 pcmbuf_unplayed_bytes += size;
234 audiobuffer_pos += size;
235 if (audiobuffer_pos >= pcmbuf_size)
236 audiobuffer_pos -= pcmbuf_size;
238 audiobuffer_fillpos = 0;
241 static void pcmbuf_under_watermark(void)
243 /* Fill audio buffer by boosting cpu */
244 pcmbuf_boost(true);
245 /* Disable crossfade if < .5s of audio */
246 if (LOW_DATA(2))
247 crossfade_active = false;
250 void pcmbuf_set_event_handler(void (*event_handler)(void))
252 pcmbuf_event_handler = event_handler;
255 unsigned int pcmbuf_get_latency(void)
257 /* Be careful how this calculation is rearranted, it's easy to overflow */
258 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
259 return bytes / 4 / (NATIVE_FREQUENCY/1000);
262 void pcmbuf_set_low_latency(bool state)
264 low_latency_mode = state;
267 bool pcmbuf_is_lowdata(void)
269 if (!pcm_is_playing() || pcm_is_paused() ||
270 crossfade_init || crossfade_active)
271 return false;
273 /* 0.5 seconds of buffer is low data */
274 return LOW_DATA(2);
277 /* Amount of bytes left in the buffer. */
278 inline size_t pcmbuf_free(void)
280 if (pcmbuf_read)
282 size_t read = (size_t)pcmbuf_read->addr;
283 size_t write =
284 (size_t)&audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
285 if (read < write)
286 read += pcmbuf_size;
287 return read - write;
289 return pcmbuf_size;
292 bool pcmbuf_crossfade_init(bool manual_skip)
294 /* Can't do two crossfades at once and, no fade if pcm is off now */
295 if (crossfade_init || crossfade_active || !pcm_is_playing())
297 pcmbuf_play_stop();
298 return false;
301 /* Not enough data, or crossfade disabled, flush the old data instead */
302 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
304 pcmbuf_boost(true);
305 pcmbuf_flush_fillpos();
306 pcmbuf_flush = true;
307 return false;
310 logf("pcmbuf_crossfade_init");
311 pcmbuf_boost(true);
313 /* Don't enable mix mode when skipping tracks manually. */
314 if (manual_skip)
315 crossfade_mixmode = false;
316 else
317 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
319 crossfade_init = true;
321 return true;
325 void pcmbuf_play_stop(void)
327 /** Prevent a very tiny pop from happening by muting audio
328 * until dma has been initialized. */
329 pcm_mute(true);
330 pcm_play_stop();
331 pcm_mute(false);
333 pcmbuf_unplayed_bytes = 0;
334 pcmbuf_mix_chunk = NULL;
335 if (pcmbuf_read) {
336 pcmbuf_write_end->link = pcmbuf_read;
337 pcmbuf_write_end = pcmbuf_read_end;
338 pcmbuf_read = pcmbuf_read_end = NULL;
340 audiobuffer_pos = 0;
341 audiobuffer_fillpos = 0;
342 crossfade_init = false;
343 crossfade_active = false;
344 pcmbuf_flush = false;
346 pcmbuf_boost(false);
350 int pcmbuf_used_descs(void) {
351 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
352 unsigned int i = 0;
353 while (pcmbuf_temp) {
354 pcmbuf_temp = pcmbuf_temp->link;
355 i++;
357 return i;
360 int pcmbuf_descs(void) {
361 return pcmbuf_size / PCMBUF_MINAVG_CHUNK;
364 size_t get_pcmbuf_descsize(void) {
365 return pcmbuf_descsize;
368 static void pcmbuf_init_pcmbuffers(void) {
369 struct pcmbufdesc *next = pcmbuf_write;
370 next++;
371 pcmbuf_write_end = pcmbuf_write;
372 while ((void *)next < (void *)audiobufend) {
373 pcmbuf_write_end->link=next;
374 pcmbuf_write_end=next;
375 next++;
379 /* Initialize the pcmbuffer the structure looks like this:
380 * ...CODECBUFFER|---------PCMBUF---------|GUARDBUF|DESCS| */
381 void pcmbuf_init(size_t bufsize)
383 pcmbuf_size = bufsize;
384 pcmbuf_descsize = pcmbuf_descs()*sizeof(struct pcmbufdesc);
385 audiobuffer = (char *)&audiobuf[(audiobufend - audiobuf) -
386 (pcmbuf_size + PCMBUF_MIX_CHUNK * 2 + pcmbuf_descsize)];
387 fadebuf = &audiobuffer[pcmbuf_size];
388 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
389 pcmbuf_write = (struct pcmbufdesc *)(&voicebuf[PCMBUF_MIX_CHUNK]);
390 pcmbuf_init_pcmbuffers();
391 position_callback = NULL;
392 pcmbuf_event_handler = NULL;
393 pcmbuf_play_stop();
396 size_t pcmbuf_get_bufsize(void)
398 return pcmbuf_size;
401 void pcmbuf_pause(bool pause) {
402 if (pause)
403 pcm_mute(true);
404 pcm_play_pause(!pause);
405 if (!pause)
406 pcm_mute(false);
407 pcmbuf_boost(!pause && pcm_is_playing());
410 /* Force playback. */
411 void pcmbuf_play_start(void)
413 if (!pcm_is_playing() && pcmbuf_unplayed_bytes)
415 /** Prevent a very tiny pop from happening by muting audio
416 * until dma has been initialized. */
417 pcm_mute(true);
419 last_chunksize = pcmbuf_read->size;
420 pcmbuf_unplayed_bytes -= last_chunksize;
421 pcm_play_data(pcmbuf_callback,
422 (unsigned char *)pcmbuf_read->addr, last_chunksize);
424 /* Now unmute the audio. */
425 pcm_mute(false);
430 * Commit samples waiting to the pcm buffer.
432 static bool pcmbuf_flush_fillpos(void)
434 if (audiobuffer_fillpos) {
435 /* Never use the last buffer descriptor */
436 while (pcmbuf_write == pcmbuf_write_end) {
437 logf("pcmbuf_flush_fillpos no descriptors");
438 /* Deboost to let the playback catchup */
439 pcmbuf_boost(false);
440 /* If this happens, something is being stupid */
441 if (!pcm_is_playing()) {
442 logf("pcmbuf_flush_fillpos error");
443 pcmbuf_play_start();
445 /* Let approximately one chunk of data playback */
446 sleep(PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY * 4) / 5);
448 pcmbuf_add_chunk();
449 return true;
451 return false;
455 * Completely process the crossfade fade out effect with current pcm buffer.
457 static void crossfade_process_buffer(size_t fade_in_delay,
458 size_t fade_out_delay, size_t fade_out_rem)
460 if (!crossfade_mixmode)
462 /* Fade out the specified amount of the already processed audio */
463 size_t total_fade_out = fade_out_rem;
464 size_t fade_out_sample;
465 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
467 /* Find the right chunk to start fading out */
468 fade_out_delay += crossfade_sample * 2;
469 while (fade_out_delay >= fade_out_chunk->size)
471 fade_out_delay -= fade_out_chunk->size;
472 fade_out_chunk = fade_out_chunk->link;
474 /* The start sample within the chunk */
475 fade_out_sample = fade_out_delay / 2;
477 while (fade_out_rem > 0)
479 /* Each 1/10 second of audio will have the same fade applied */
480 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
481 int factor = (fade_out_rem << 8) / total_fade_out;
483 fade_out_rem -= block_rem;
485 /* Fade this block */
486 while (block_rem > 0)
488 /* Fade one sample */
489 short *buf = (short *)(fade_out_chunk->addr);
490 int sample = buf[fade_out_sample];
491 buf[fade_out_sample++] = (sample * factor) >> 8;
493 block_rem -= 2;
494 /* Move to the next chunk as needed */
495 if (fade_out_sample * 2 >= fade_out_chunk->size)
497 fade_out_chunk = fade_out_chunk->link;
498 fade_out_sample = 0;
504 /* Find the right chunk and sample to start fading in */
505 fade_in_delay += crossfade_sample * 2;
506 while (fade_in_delay >= crossfade_chunk->size)
508 fade_in_delay -= crossfade_chunk->size;
509 crossfade_chunk = crossfade_chunk->link;
511 crossfade_sample = fade_in_delay / 2;
512 logf("process done!");
515 /* Initializes crossfader, calculates all necessary parameters and
516 * performs fade-out with the pcm buffer. */
517 static void crossfade_start(void)
519 size_t crossfade_rem;
520 size_t crossfade_need;
521 size_t fade_out_rem;
522 size_t fade_out_delay;
523 size_t fade_in_delay;
525 crossfade_init = false;
526 /* Reject crossfade if less than .5s of data */
527 if (LOW_DATA(2)) {
528 logf("crossfade rejected");
529 pcmbuf_play_stop();
530 return ;
533 logf("crossfade_start");
534 pcmbuf_flush_fillpos();
535 crossfade_active = true;
537 /* Initialize the crossfade buffer size to all of the buffered data that
538 * has not yet been sent to the DMA */
539 crossfade_rem = pcmbuf_unplayed_bytes;
540 crossfade_chunk = pcmbuf_read->link;
541 crossfade_sample = 0;
543 /* Get fade out delay from settings. */
544 fade_out_delay =
545 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
547 /* Get fade out duration from settings. */
548 fade_out_rem =
549 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
551 crossfade_need = fade_out_delay + fade_out_rem;
552 /* We want only to modify the last part of the buffer. */
553 if (crossfade_rem > crossfade_need)
555 size_t crossfade_extra = crossfade_rem - crossfade_need;
556 while (crossfade_extra > crossfade_chunk->size)
558 crossfade_extra -= crossfade_chunk->size;
559 crossfade_chunk = crossfade_chunk->link;
561 crossfade_sample = crossfade_extra / 2;
563 /* Truncate fade out duration if necessary. */
564 else if (crossfade_rem < crossfade_need)
566 size_t crossfade_short = crossfade_need - crossfade_rem;
567 if (fade_out_rem >= crossfade_short)
568 fade_out_rem -= crossfade_short;
569 else
571 fade_out_delay -= crossfade_short - fade_out_rem;
572 fade_out_rem = 0;
576 /* Get also fade in duration and delays from settings. */
577 crossfade_fade_in_total =
578 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
579 crossfade_fade_in_rem = crossfade_fade_in_total;
581 fade_in_delay =
582 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
584 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
587 /* Returns the number of bytes _NOT_ mixed */
588 static size_t crossfade_fade_mix(int factor, const char *buf, size_t fade_rem)
590 const short *input_buf = (const short *)buf;
591 short *output_buf = (short *)(crossfade_chunk->addr);
592 short *chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
593 output_buf = &output_buf[crossfade_sample];
595 while (fade_rem)
597 int sample = *input_buf++;
598 sample = ((sample * factor) >> 8) + *output_buf;
599 *output_buf++ = MIN(32767, MAX(-32768, sample));
600 fade_rem -= 2;
602 if (output_buf >= chunk_end)
604 crossfade_chunk = crossfade_chunk->link;
605 if (!crossfade_chunk)
606 return fade_rem;
607 output_buf = (short *)(crossfade_chunk->addr);
608 chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
611 crossfade_sample = (size_t)(output_buf - (short *)(crossfade_chunk->addr));
612 return 0;
615 /* Returns the number of bytes _NOT_ mixed */
616 static size_t crossfade_mix(const char *buf, size_t length)
618 const short *input_buf = (const short *)buf;
619 short *output_buf = (short *)(crossfade_chunk->addr);
620 short *chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
621 output_buf = &output_buf[crossfade_sample];
623 while (length)
625 int sample = *input_buf++ + *output_buf;
626 *output_buf++ = MIN(32767, MAX(-32768, sample));
627 length -= 2;
629 if (output_buf >= chunk_end)
631 crossfade_chunk = crossfade_chunk->link;
632 if (!crossfade_chunk)
633 return length;
634 output_buf = (short *)(crossfade_chunk->addr);
635 chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
638 crossfade_sample = (size_t)(output_buf - (short *)(crossfade_chunk->addr));
639 return 0;
642 static void pcmbuf_flush_buffer(const char *buf, size_t length)
644 size_t copy_n;
645 while (length > 0) {
646 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
647 if (NEED_FLUSH(audiobuffer_index))
649 pcmbuf_flush_fillpos();
650 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
652 copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
653 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
654 buf += copy_n;
655 audiobuffer_fillpos += copy_n;
656 length -= copy_n;
660 static void flush_crossfade(char *buf, size_t length)
662 if (length)
664 if (crossfade_fade_in_rem)
666 size_t samples;
667 short *input_buf;
669 /* Fade factor for this packet */
670 int factor =
671 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
672 crossfade_fade_in_total;
673 /* Bytes to fade */
674 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
676 /* We _will_ fade this many bytes */
677 crossfade_fade_in_rem -= fade_rem;
679 if (crossfade_chunk)
681 /* Mix the data */
682 size_t fade_total = fade_rem;
683 fade_rem = crossfade_fade_mix(factor, buf, fade_rem);
684 length -= fade_total - fade_rem;
685 buf += fade_total - fade_rem;
686 if (!length)
687 return;
688 if (!fade_rem)
689 goto fade_done;
692 samples = fade_rem / 2;
693 input_buf = (short *)buf;
694 /* Fade remaining samples in place */
695 while (samples)
697 int sample = *input_buf;
698 *input_buf++ = (sample * factor) >> 8;
699 samples--;
703 fade_done:
704 if (crossfade_chunk)
706 /* Mix the data */
707 size_t mix_total = length;
708 length = crossfade_mix(buf, length);
709 buf += mix_total - length;
710 if (!length)
711 return;
714 /* Flush samples to the buffer */
715 while (!prepare_insert(length))
716 sleep(1);
717 pcmbuf_flush_buffer(buf, length);
722 static bool prepare_insert(size_t length)
724 if (low_latency_mode)
726 /* 1/4s latency. */
727 if (pcmbuf_unplayed_bytes > NATIVE_FREQUENCY * 4 / 4
728 && pcm_is_playing())
729 return false;
732 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
733 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
735 pcmbuf_boost(false);
736 return false;
739 if (!pcm_is_playing())
741 pcmbuf_boost(true);
742 /* Pre-buffer 1s. */
743 #if MEM <= 1
744 if (!LOW_DATA(1))
745 #else
746 if (!LOW_DATA(4))
747 #endif
749 logf("pcm starting");
750 pcmbuf_play_start();
752 } else if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
753 pcmbuf_under_watermark();
755 return true;
758 void* pcmbuf_request_buffer(size_t length, size_t *realsize)
760 if (crossfade_init)
761 crossfade_start();
763 if (crossfade_active) {
764 *realsize = MIN(length, PCMBUF_MIX_CHUNK);
765 return fadebuf;
767 else
769 if(prepare_insert(length))
771 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
772 *realsize = length;
773 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
775 /* Usual case, there's space here */
776 return &audiobuffer[audiobuffer_index];
778 else
780 /* Flush and wrap the buffer */
781 pcmbuf_flush_fillpos();
782 audiobuffer_pos = 0;
783 return &audiobuffer[0];
786 else
788 *realsize = 0;
789 return NULL;
794 void* pcmbuf_request_voice_buffer(size_t length, size_t *realsize, bool mix)
796 if (mix)
798 if (pcmbuf_mix_chunk || pcmbuf_read->link)
800 *realsize = MIN(length, PCMBUF_MIX_CHUNK);
801 return voicebuf;
803 else
805 *realsize = 0;
806 return NULL;
809 else
810 return pcmbuf_request_buffer(length, realsize);
813 bool pcmbuf_is_crossfade_active(void)
815 return crossfade_active || crossfade_init;
818 void pcmbuf_write_complete(size_t length)
820 if (crossfade_active)
822 flush_crossfade(fadebuf, length);
823 if (!(crossfade_fade_in_rem || crossfade_chunk))
824 crossfade_active = false;
826 else
828 audiobuffer_fillpos += length;
830 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
831 pcmbuf_flush_fillpos();
835 bool pcmbuf_insert_buffer(char *buf, size_t length)
837 if (crossfade_active)
839 flush_crossfade(buf, length);
840 if (!(crossfade_fade_in_rem || crossfade_chunk))
841 crossfade_active = false;
843 else
845 if (!prepare_insert(length))
846 return false;
847 pcmbuf_flush_buffer(buf, length);
849 return true;
852 /* Generates a constant square wave sound with a given frequency
853 in Hertz for a duration in milliseconds. */
854 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
856 unsigned int count = 0, i = 0;
857 unsigned int interval = NATIVE_FREQUENCY / frequency;
858 long sample;
859 short *buf;
860 short *pcmbuf_end = (short *)fadebuf;
861 size_t samples = NATIVE_FREQUENCY / 1000 * duration;
863 if (pcm_is_playing())
865 if (pcmbuf_read->link)
867 /* Get the next chunk */
868 char *pcmbuf_mix_buf = pcmbuf_read->link->addr;
869 /* Give at least 1/8s clearance. */
870 buf = (short *)&pcmbuf_mix_buf[NATIVE_FREQUENCY * 4 / 8];
872 else
874 logf("No place to beep");
875 return;
878 while (i++ < samples)
880 sample = *buf;
881 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
882 if (buf > pcmbuf_end)
883 buf = (short *)audiobuffer;
884 sample = *buf;
885 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
887 /* Toggle square wav side */
888 if (++count >= interval)
890 count = 0;
891 amplitude = -amplitude;
893 if (buf > pcmbuf_end)
894 buf = (short *)audiobuffer;
897 else
899 buf = (short *)audiobuffer;
900 while (i++ < samples)
902 *buf++ = amplitude;
903 if (buf > pcmbuf_end)
904 buf = (short *)audiobuffer;
905 *buf++ = amplitude;
907 /* Toggle square wav side */
908 if (++count >= interval)
910 count = 0;
911 amplitude = -amplitude;
913 if (buf > pcmbuf_end)
914 buf = (short *)audiobuffer;
916 pcm_play_data(NULL, (unsigned char *)audiobuffer, samples * 4);
920 /* Returns pcm buffer usage in percents (0 to 100). */
921 int pcmbuf_usage(void)
923 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
926 int pcmbuf_mix_free(void)
928 if (pcmbuf_mix_chunk)
930 size_t my_mix_end =
931 (size_t)&((short *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
932 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
933 if (my_write_pos < my_mix_end)
934 my_write_pos += pcmbuf_size;
935 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
937 return 100;
940 void pcmbuf_mix_voice(size_t length)
942 short *ibuf = (short *)voicebuf;
943 short *obuf;
944 size_t chunk_samples;
946 if (!pcmbuf_mix_chunk && pcmbuf_read)
948 pcmbuf_mix_chunk = pcmbuf_read->link;
949 /* Start 1/8s into the next chunk */
950 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
952 if (!pcmbuf_mix_chunk)
953 return;
955 obuf = (short *)pcmbuf_mix_chunk->addr;
956 chunk_samples = pcmbuf_mix_chunk->size / 2;
958 length /= 2;
960 while (length-- > 0) {
961 int sample = *ibuf++;
962 if (pcmbuf_mix_sample >= chunk_samples)
964 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
965 if (!pcmbuf_mix_chunk)
966 return;
967 pcmbuf_mix_sample = 0;
968 obuf = pcmbuf_mix_chunk->addr;
969 chunk_samples = pcmbuf_mix_chunk->size / 2;
971 sample += obuf[pcmbuf_mix_sample] >> 2;
972 obuf[pcmbuf_mix_sample++] = MIN(MAX(sample, -32768), 32767);
976 void pcmbuf_crossfade_enable(bool on_off)
978 crossfade_enabled = on_off;
980 if (crossfade_enabled) {
981 /* If crossfading, try to keep the buffer full other than 1 second */
982 pcmbuf_set_watermark_bytes(pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1));
983 } else {
984 /* Otherwise, just keep it above 2 second */
985 pcmbuf_set_watermark_bytes(PCMBUF_WATERMARK);
989 bool pcmbuf_is_crossfade_enabled(void)
991 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
992 return global_settings.playlist_shuffle;
994 return crossfade_enabled;