Fix the wavplay icon
[Rockbox.git] / apps / pcmbuf.c
blob89f9e27798155d46ce4049d03a42f9dd69abc12a
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"
38 #include "thread.h"
40 /* Define PCMBUF_MUTING if the codec requires muting to prevent pops
41 * Currently assumes anything other than tlv320 and uda1380 require it
43 #if !defined(HAVE_UDA1380) && !defined(HAVE_TLV320)
44 #define PCMBUF_MUTING
45 #endif
47 /* Keep watermark high for iPods at least (2s) */
48 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
50 /* Structure we can use to queue pcm chunks in memory to be played
51 * by the driver code. */
52 struct pcmbufdesc
54 void *addr;
55 size_t size;
56 struct pcmbufdesc* link;
57 /* Call this when the buffer has been played */
58 void (*callback)(void);
61 #define PCMBUF_DESCS(bufsize) \
62 ((bufsize) / PCMBUF_MINAVG_CHUNK)
63 #define PCMBUF_DESCS_SIZE(bufsize) \
64 (PCMBUF_DESCS(bufsize)*sizeof(struct pcmbufdesc))
66 /* Size of the PCM buffer. */
67 static size_t pcmbuf_size IDATA_ATTR = 0;
68 static char *pcmbuf_bufend IDATA_ATTR;
69 static char *audiobuffer IDATA_ATTR;
70 /* Current audio buffer write index. */
71 static size_t audiobuffer_pos IDATA_ATTR;
72 /* Amount audiobuffer_pos will be increased.*/
73 static size_t audiobuffer_fillpos IDATA_ATTR;
74 static char *fadebuf IDATA_ATTR;
75 static char *voicebuf IDATA_ATTR;
77 static void (*pcmbuf_event_handler)(void) IDATA_ATTR;
78 static void (*position_callback)(size_t size) IDATA_ATTR;
80 /* Crossfade related state */
81 static bool crossfade_enabled;
82 static bool crossfade_enabled_pending;
83 static bool crossfade_mixmode;
84 static bool crossfade_active IDATA_ATTR;
85 static bool crossfade_init IDATA_ATTR;
87 /* Track the current location for processing crossfade */
88 static struct pcmbufdesc *crossfade_chunk IDATA_ATTR;
89 static size_t crossfade_sample IDATA_ATTR;
91 /* Counters for fading in new data */
92 static size_t crossfade_fade_in_total IDATA_ATTR;
93 static size_t crossfade_fade_in_rem IDATA_ATTR;
95 static size_t pcmbuf_descsize;
96 static struct pcmbufdesc *pcmbuf_read IDATA_ATTR;
97 static struct pcmbufdesc *pcmbuf_read_end IDATA_ATTR;
98 static struct pcmbufdesc *pcmbuf_write IDATA_ATTR;
99 static struct pcmbufdesc *pcmbuf_write_end IDATA_ATTR;
100 static size_t last_chunksize IDATA_ATTR;
102 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
103 static size_t pcmbuf_watermark IDATA_ATTR;
105 static struct pcmbufdesc *pcmbuf_mix_chunk IDATA_ATTR;
106 static size_t pcmbuf_mix_sample IDATA_ATTR;
108 static bool low_latency_mode = false;
109 static bool pcmbuf_flush;
111 #ifdef HAVE_PRIORITY_SCHEDULING
112 static int codec_thread_priority = 0;
113 #endif
115 extern struct thread_entry *codec_thread_p;
117 /* Helpful macros for use in conditionals this assumes some of the above
118 * static variable names */
119 #define NEED_FLUSH(position) \
120 (audiobuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
121 #define LOW_DATA(quarter_secs) \
122 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
124 static bool prepare_insert(size_t length);
125 static void pcmbuf_under_watermark(void);
126 static bool pcmbuf_flush_fillpos(void);
128 #define CALL_IF_EXISTS(function, args...) if (function) function(args)
129 /* This function has 2 major logical parts (separated by brackets both for
130 * readability and variable scoping). The first part performs the
131 * operastions related to finishing off the last buffer we fed to the DMA.
132 * The second part performs the operations involved in sending a new buffer
133 * to the DMA. Finally the function checks the status of the buffer and
134 * boosts if necessary */
135 static void pcmbuf_callback(unsigned char** start, size_t* size) ICODE_ATTR;
136 static void pcmbuf_callback(unsigned char** start, size_t* size)
139 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
140 /* Take the finished buffer out of circulation */
141 pcmbuf_read = pcmbuf_current->link;
143 /* The buffer is finished, call the callback functions */
144 CALL_IF_EXISTS(position_callback, last_chunksize);
145 CALL_IF_EXISTS(pcmbuf_current->callback);
147 /* Put the finished buffer back into circulation */
148 pcmbuf_write_end->link = pcmbuf_current;
149 pcmbuf_write_end = pcmbuf_current;
151 /* If we've read over the mix chunk while it's still mixing there */
152 if (pcmbuf_current == pcmbuf_mix_chunk)
153 pcmbuf_mix_chunk = NULL;
154 /* If we've read over the crossfade chunk while it's still fading */
155 if (pcmbuf_current == crossfade_chunk)
156 crossfade_chunk = pcmbuf_read;
159 process_new_buffer:
161 /* Send the new buffer to the pcm */
162 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
163 size_t *realsize = size;
164 unsigned char** realstart = start;
165 if(pcmbuf_new)
167 size_t current_size = pcmbuf_new->size;
169 pcmbuf_unplayed_bytes -= current_size;
170 last_chunksize = current_size;
171 *realsize = current_size;
172 *realstart = pcmbuf_new->addr;
174 else
176 /* There may be more data waiting to flush, try to use it */
177 if (pcmbuf_flush_fillpos())
178 goto process_new_buffer;
180 /* No more buffers */
181 last_chunksize = 0;
182 *realsize = 0;
183 *realstart = NULL;
184 CALL_IF_EXISTS(pcmbuf_event_handler);
189 void pcmbuf_set_position_callback(void (*callback)(size_t size))
191 position_callback = callback;
194 static void pcmbuf_set_watermark_bytes(void)
196 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
197 /* If crossfading, try to keep the buffer full other than 1 second */
198 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
199 /* Otherwise, just keep it above 2 second */
200 PCMBUF_WATERMARK;
203 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
204 * in a separate function for the moment */
205 static inline void pcmbuf_add_chunk(void)
207 register size_t size = audiobuffer_fillpos;
208 /* Grab the next description to write, and change the write pointer */
209 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
210 pcmbuf_write = pcmbuf_current->link;
211 /* Fill in the values in the new buffer chunk */
212 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
213 pcmbuf_current->size = size;
214 pcmbuf_current->callback = pcmbuf_event_handler;
215 pcmbuf_current->link = NULL;
216 /* This is single use only */
217 pcmbuf_event_handler = NULL;
218 if (pcmbuf_read != NULL) {
219 if (pcmbuf_flush)
221 pcmbuf_write_end->link = pcmbuf_read->link;
222 pcmbuf_read->link = pcmbuf_current;
223 while (pcmbuf_write_end->link)
225 pcmbuf_write_end = pcmbuf_write_end->link;
226 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
228 pcmbuf_flush = false;
230 /* If there is already a read buffer setup, add to it */
231 else
232 pcmbuf_read_end->link = pcmbuf_current;
233 } else {
234 /* Otherwise create the buffer */
235 pcmbuf_read = pcmbuf_current;
237 /* This is now the last buffer to read */
238 pcmbuf_read_end = pcmbuf_current;
240 /* Update bytes counters */
241 pcmbuf_unplayed_bytes += size;
243 audiobuffer_pos += size;
244 if (audiobuffer_pos >= pcmbuf_size)
245 audiobuffer_pos -= pcmbuf_size;
247 audiobuffer_fillpos = 0;
250 #ifdef HAVE_PRIORITY_SCHEDULING
251 static void boost_codec_thread(bool boost)
253 if (boost)
255 if (codec_thread_priority == 0)
256 codec_thread_priority = thread_set_priority(
257 codec_thread_p, PRIORITY_REALTIME);
259 else if (codec_thread_priority != 0)
261 thread_set_priority(codec_thread_p, codec_thread_priority);
262 codec_thread_priority = 0;
265 #endif /* HAVE_PRIORITY_SCHEDULING */
267 static void pcmbuf_under_watermark(void)
269 /* Only codec thread initiates boost - voice boosts the cpu when playing
270 a clip */
271 #ifndef SIMULATOR
272 if (thread_get_current() == codec_thread_p)
273 #endif /* SIMULATOR */
275 #ifdef HAVE_PRIORITY_SCHEDULING
276 /* If buffer is critically low, override UI priority, else
277 set back to the original priority. */
278 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
279 #endif
280 /* Fill audio buffer by boosting cpu */
281 trigger_cpu_boost();
284 /* Disable crossfade if < .5s of audio */
285 if (LOW_DATA(2))
287 crossfade_active = false;
291 void pcmbuf_set_event_handler(void (*event_handler)(void))
293 pcmbuf_event_handler = event_handler;
296 unsigned int pcmbuf_get_latency(void)
298 /* Be careful how this calculation is rearranted, it's easy to overflow */
299 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
300 return bytes / 4 / (NATIVE_FREQUENCY/1000);
303 void pcmbuf_set_low_latency(bool state)
305 low_latency_mode = state;
308 bool pcmbuf_is_lowdata(void)
310 if (!pcm_is_playing() || pcm_is_paused() ||
311 crossfade_init || crossfade_active)
312 return false;
314 /* 1 seconds of buffer is low data */
315 return LOW_DATA(4);
318 /* Amount of bytes left in the buffer. */
319 inline size_t pcmbuf_free(void)
321 if (pcmbuf_read != NULL)
323 void *read = pcmbuf_read->addr;
324 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
325 if (read < write)
326 return (size_t)(read - write) + pcmbuf_size;
327 else
328 return (size_t) (read - write);
330 return pcmbuf_size;
333 bool pcmbuf_crossfade_init(bool manual_skip)
335 /* Can't do two crossfades at once and, no fade if pcm is off now */
336 if (crossfade_init || crossfade_active || !pcm_is_playing())
338 pcmbuf_play_stop();
339 return false;
342 trigger_cpu_boost();
344 /* Not enough data, or crossfade disabled, flush the old data instead */
345 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
347 pcmbuf_flush_fillpos();
348 pcmbuf_flush = true;
349 return false;
352 /* Don't enable mix mode when skipping tracks manually. */
353 if (manual_skip)
354 crossfade_mixmode = false;
355 else
356 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
358 crossfade_init = true;
360 return true;
364 void pcmbuf_play_stop(void)
366 /** Prevent a very tiny pop from happening by muting audio
367 * until dma has been initialized. */
368 #ifdef PCMBUF_MUTING
369 pcm_mute(true);
370 #endif
371 pcm_play_stop();
372 #ifdef PCMBUF_MUTING
373 pcm_mute(false);
374 #endif
376 pcmbuf_unplayed_bytes = 0;
377 pcmbuf_mix_chunk = NULL;
378 if (pcmbuf_read) {
379 pcmbuf_write_end->link = pcmbuf_read;
380 pcmbuf_write_end = pcmbuf_read_end;
381 pcmbuf_read = pcmbuf_read_end = NULL;
383 audiobuffer_pos = 0;
384 audiobuffer_fillpos = 0;
385 crossfade_init = false;
386 crossfade_active = false;
387 pcmbuf_flush = false;
389 #ifdef HAVE_PRIORITY_SCHEDULING
390 /* Can unboost the codec thread here no matter who's calling */
391 boost_codec_thread(false);
392 #endif
395 int pcmbuf_used_descs(void) {
396 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
397 unsigned int i = 0;
398 while (pcmbuf_temp) {
399 pcmbuf_temp = pcmbuf_temp->link;
400 i++;
402 return i;
405 int pcmbuf_descs(void) {
406 return PCMBUF_DESCS(pcmbuf_size);
409 size_t get_pcmbuf_descsize(void) {
410 return pcmbuf_descsize;
413 static void pcmbuf_init_pcmbuffers(void) {
414 struct pcmbufdesc *next = pcmbuf_write;
415 next++;
416 pcmbuf_write_end = pcmbuf_write;
417 while ((void *)next < (void *)pcmbuf_bufend) {
418 pcmbuf_write_end->link=next;
419 pcmbuf_write_end=next;
420 next++;
424 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
426 #if MEM > 1
427 size_t seconds = 1;
429 if (crossfade_enabled_pending)
430 seconds += global_settings.crossfade_fade_out_delay
431 + global_settings.crossfade_fade_out_duration;
433 /* Buffer has to be at least 2s long. */
434 seconds += 2;
435 logf("pcmbuf len: %ld", seconds);
436 return seconds * (NATIVE_FREQUENCY*4);
437 #else
438 return NATIVE_FREQUENCY*2;
439 #endif
442 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
444 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
445 PCMBUF_DESCS_SIZE(bufsize));
448 bool pcmbuf_is_same_size(void)
450 if (audiobuffer == NULL)
451 return true; /* Not set up yet even once so always */
453 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
454 return pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
457 /* Initialize the pcmbuffer the structure looks like this:
458 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
459 size_t pcmbuf_init(unsigned char *bufend)
461 pcmbuf_bufend = bufend;
462 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
463 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
464 fadebuf = &audiobuffer[pcmbuf_size];
465 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
466 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
468 pcmbuf_descsize = PCMBUF_DESCS_SIZE(pcmbuf_size);
469 pcmbuf_init_pcmbuffers();
471 position_callback = NULL;
472 pcmbuf_event_handler = NULL;
474 pcmbuf_crossfade_enable_finished();
476 pcmbuf_play_stop();
478 return pcmbuf_bufend - audiobuffer;
481 size_t pcmbuf_get_bufsize(void)
483 return pcmbuf_size;
486 #ifdef ROCKBOX_HAS_LOGF
487 unsigned char * pcmbuf_get_meminfo(size_t *length)
489 *length = pcmbuf_bufend - audiobuffer;
490 return audiobuffer;
492 #endif
494 void pcmbuf_pause(bool pause) {
495 #ifdef PCMBUF_MUTING
496 if (pause)
497 pcm_mute(true);
498 #endif
499 pcm_play_pause(!pause);
500 #ifdef PCMBUF_MUTING
501 if (!pause)
502 pcm_mute(false);
503 #endif
504 trigger_cpu_boost();
507 /* Force playback. */
508 void pcmbuf_play_start(void)
510 if (!pcm_is_playing() && pcmbuf_unplayed_bytes)
512 #ifdef PCMBUF_MUTING
513 /** Prevent a very tiny pop from happening by muting audio
514 * until dma has been initialized. */
515 pcm_mute(true);
516 #endif
518 if (pcmbuf_read != NULL)
520 last_chunksize = pcmbuf_read->size;
521 pcmbuf_unplayed_bytes -= last_chunksize;
522 pcm_play_data(pcmbuf_callback,
523 (unsigned char *)pcmbuf_read->addr, last_chunksize);
526 #ifdef PCMBUF_MUTING
527 /* Now unmute the audio. */
528 pcm_mute(false);
529 #endif
534 * Commit samples waiting to the pcm buffer.
536 static bool pcmbuf_flush_fillpos(void)
538 if (audiobuffer_fillpos) {
539 /* Never use the last buffer descriptor */
540 while (pcmbuf_write == pcmbuf_write_end) {
541 /* If this happens, something is being stupid */
542 if (!pcm_is_playing()) {
543 logf("pcmbuf_flush_fillpos error");
544 pcmbuf_play_start();
546 /* Let approximately one chunk of data playback */
547 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
549 pcmbuf_add_chunk();
550 return true;
552 return false;
556 * Completely process the crossfade fade out effect with current pcm buffer.
558 static void crossfade_process_buffer(size_t fade_in_delay,
559 size_t fade_out_delay, size_t fade_out_rem)
561 if (!crossfade_mixmode)
563 /* Fade out the specified amount of the already processed audio */
564 size_t total_fade_out = fade_out_rem;
565 size_t fade_out_sample;
566 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
568 /* Find the right chunk to start fading out */
569 fade_out_delay += crossfade_sample * 2;
570 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
572 fade_out_delay -= fade_out_chunk->size;
573 fade_out_chunk = fade_out_chunk->link;
575 /* The start sample within the chunk */
576 fade_out_sample = fade_out_delay / 2;
578 while (fade_out_rem > 0)
580 /* Each 1/10 second of audio will have the same fade applied */
581 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
582 int factor = (fade_out_rem << 8) / total_fade_out;
584 fade_out_rem -= block_rem;
586 /* Fade this block */
587 while (block_rem > 0 && fade_out_chunk != NULL)
589 /* Fade one sample */
590 short *buf = (short *)(fade_out_chunk->addr);
591 int sample = buf[fade_out_sample];
592 buf[fade_out_sample++] = (sample * factor) >> 8;
594 block_rem -= 2;
595 /* Move to the next chunk as needed */
596 if (fade_out_sample * 2 >= fade_out_chunk->size)
598 fade_out_chunk = fade_out_chunk->link;
599 fade_out_sample = 0;
605 /* Find the right chunk and sample to start fading in */
606 fade_in_delay += crossfade_sample * 2;
607 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
609 fade_in_delay -= crossfade_chunk->size;
610 crossfade_chunk = crossfade_chunk->link;
612 crossfade_sample = fade_in_delay / 2;
613 logf("process done!");
616 /* Initializes crossfader, calculates all necessary parameters and
617 * performs fade-out with the pcm buffer. */
618 static void crossfade_start(void)
620 size_t crossfade_rem;
621 size_t crossfade_need;
622 size_t fade_out_rem;
623 size_t fade_out_delay;
624 size_t fade_in_delay;
626 crossfade_init = false;
627 /* Reject crossfade if less than .5s of data */
628 if (LOW_DATA(2)) {
629 logf("crossfade rejected");
630 pcmbuf_play_stop();
631 return ;
634 logf("crossfade_start");
635 pcmbuf_flush_fillpos();
636 crossfade_active = true;
638 /* Initialize the crossfade buffer size to all of the buffered data that
639 * has not yet been sent to the DMA */
640 crossfade_rem = pcmbuf_unplayed_bytes;
641 crossfade_chunk = pcmbuf_read->link;
642 crossfade_sample = 0;
644 /* Get fade out delay from settings. */
645 fade_out_delay =
646 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
648 /* Get fade out duration from settings. */
649 fade_out_rem =
650 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
652 crossfade_need = fade_out_delay + fade_out_rem;
653 /* We want only to modify the last part of the buffer. */
654 if (crossfade_rem > crossfade_need)
656 size_t crossfade_extra = crossfade_rem - crossfade_need;
657 while (crossfade_extra > crossfade_chunk->size)
659 crossfade_extra -= crossfade_chunk->size;
660 crossfade_chunk = crossfade_chunk->link;
662 crossfade_sample = crossfade_extra / 2;
664 /* Truncate fade out duration if necessary. */
665 else if (crossfade_rem < crossfade_need)
667 size_t crossfade_short = crossfade_need - crossfade_rem;
668 if (fade_out_rem >= crossfade_short)
669 fade_out_rem -= crossfade_short;
670 else
672 fade_out_delay -= crossfade_short - fade_out_rem;
673 fade_out_rem = 0;
677 /* Get also fade in duration and delays from settings. */
678 crossfade_fade_in_total =
679 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
680 crossfade_fade_in_rem = crossfade_fade_in_total;
682 fade_in_delay =
683 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
685 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
688 /* Returns the number of bytes _NOT_ mixed */
689 static size_t crossfade_fade_mix(int factor, const char *buf, size_t fade_rem)
691 const short *input_buf = (const short *)buf;
692 short *output_buf = (short *)(crossfade_chunk->addr);
693 short *chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
694 output_buf = &output_buf[crossfade_sample];
696 while (fade_rem)
698 int sample = *input_buf++;
699 sample = ((sample * factor) >> 8) + *output_buf;
700 *output_buf++ = MIN(32767, MAX(-32768, sample));
701 fade_rem -= 2;
703 if (output_buf >= chunk_end)
705 crossfade_chunk = crossfade_chunk->link;
706 if (!crossfade_chunk)
707 return fade_rem;
708 output_buf = (short *)(crossfade_chunk->addr);
709 chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
712 crossfade_sample = (size_t)(output_buf - (short *)(crossfade_chunk->addr));
713 return 0;
716 /* Returns the number of bytes _NOT_ mixed */
717 static size_t crossfade_mix(const char *buf, size_t length)
719 const short *input_buf = (const short *)buf;
720 short *output_buf = (short *)(crossfade_chunk->addr);
721 short *chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
722 output_buf = &output_buf[crossfade_sample];
724 while (length)
726 int sample = *input_buf++ + *output_buf;
727 *output_buf++ = MIN(32767, MAX(-32768, sample));
728 length -= 2;
730 if (output_buf >= chunk_end)
732 crossfade_chunk = crossfade_chunk->link;
733 if (!crossfade_chunk)
734 return length;
735 output_buf = (short *)(crossfade_chunk->addr);
736 chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
739 crossfade_sample = (size_t)(output_buf - (short *)(crossfade_chunk->addr));
740 return 0;
743 static void pcmbuf_flush_buffer(const char *buf, size_t length)
745 size_t copy_n;
746 while (length > 0) {
747 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
748 if (NEED_FLUSH(audiobuffer_index))
750 pcmbuf_flush_fillpos();
751 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
753 copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
754 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
755 buf += copy_n;
756 audiobuffer_fillpos += copy_n;
757 length -= copy_n;
761 static void flush_crossfade(char *buf, size_t length)
763 if (length)
765 if (crossfade_fade_in_rem)
767 size_t samples;
768 short *input_buf;
770 /* Fade factor for this packet */
771 int factor =
772 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
773 crossfade_fade_in_total;
774 /* Bytes to fade */
775 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
777 /* We _will_ fade this many bytes */
778 crossfade_fade_in_rem -= fade_rem;
780 if (crossfade_chunk)
782 /* Mix the data */
783 size_t fade_total = fade_rem;
784 fade_rem = crossfade_fade_mix(factor, buf, fade_rem);
785 length -= fade_total - fade_rem;
786 buf += fade_total - fade_rem;
787 if (!length)
788 return;
789 if (!fade_rem)
790 goto fade_done;
793 samples = fade_rem / 2;
794 input_buf = (short *)buf;
795 /* Fade remaining samples in place */
796 while (samples)
798 int sample = *input_buf;
799 *input_buf++ = (sample * factor) >> 8;
800 samples--;
804 fade_done:
805 if (crossfade_chunk)
807 /* Mix the data */
808 size_t mix_total = length;
809 length = crossfade_mix(buf, length);
810 buf += mix_total - length;
811 if (!length)
812 return;
815 /* Flush samples to the buffer */
816 while (!prepare_insert(length))
817 sleep(1);
818 pcmbuf_flush_buffer(buf, length);
823 static bool prepare_insert(size_t length)
825 if (low_latency_mode)
827 /* 1/4s latency. */
828 if (pcmbuf_unplayed_bytes > NATIVE_FREQUENCY * 4 / 4
829 && pcm_is_playing())
830 return false;
833 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
834 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
835 return false;
837 if (!pcm_is_playing())
839 trigger_cpu_boost();
841 /* Pre-buffer 1s. */
842 #if MEM <= 1
843 if (!LOW_DATA(1))
844 #else
845 if (!LOW_DATA(4))
846 #endif
848 logf("pcm starting");
849 pcmbuf_play_start();
852 else if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
853 pcmbuf_under_watermark();
855 return true;
858 void* pcmbuf_request_buffer(int *count)
860 if (crossfade_init)
861 crossfade_start();
863 if (crossfade_active) {
864 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
865 return fadebuf;
867 else
869 if(prepare_insert(*count << 2))
871 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
872 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
874 /* Usual case, there's space here */
875 return &audiobuffer[audiobuffer_index];
877 else
879 /* Flush and wrap the buffer */
880 pcmbuf_flush_fillpos();
881 audiobuffer_pos = 0;
882 return &audiobuffer[0];
885 else
887 return NULL;
892 void* pcmbuf_request_voice_buffer(int *count, bool mix)
894 if (mix)
896 if (pcmbuf_read == NULL)
898 return NULL;
900 else if (pcmbuf_mix_chunk || pcmbuf_read->link)
902 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
903 return voicebuf;
905 else
907 return NULL;
910 else
911 return pcmbuf_request_buffer(count);
914 bool pcmbuf_is_crossfade_active(void)
916 return crossfade_active || crossfade_init;
919 void pcmbuf_write_complete(int count)
921 size_t length = (size_t)(unsigned int)count << 2;
923 if (crossfade_active)
925 flush_crossfade(fadebuf, length);
926 if (!(crossfade_fade_in_rem || crossfade_chunk))
927 crossfade_active = false;
929 else
931 audiobuffer_fillpos += length;
933 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
934 pcmbuf_flush_fillpos();
938 #if 0
939 bool pcmbuf_insert_buffer(char *buf, int count)
941 size_t length = (size_t)(unsigned int)count << 2;
943 if (crossfade_active)
945 flush_crossfade(buf, length);
946 if (!(crossfade_fade_in_rem || crossfade_chunk))
947 crossfade_active = false;
949 else
951 if (!prepare_insert(length))
952 return false;
953 pcmbuf_flush_buffer(buf, length);
955 return true;
957 #endif
959 /* Generates a constant square wave sound with a given frequency
960 in Hertz for a duration in milliseconds. */
961 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
963 unsigned int count = 0, i = 0;
964 unsigned int interval = NATIVE_FREQUENCY / frequency;
965 long sample;
966 short *buf;
967 short *pcmbuf_end = (short *)fadebuf;
968 size_t samples = NATIVE_FREQUENCY / 1000 * duration;
970 if (pcm_is_playing() && pcmbuf_read != NULL)
972 if (pcmbuf_read->link)
974 /* Get the next chunk */
975 char *pcmbuf_mix_buf = pcmbuf_read->link->addr;
976 /* Give at least 1/8s clearance. */
977 buf = (short *)&pcmbuf_mix_buf[NATIVE_FREQUENCY * 4 / 8];
979 else
981 logf("No place to beep");
982 return;
985 while (i++ < samples)
987 sample = *buf;
988 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
989 if (buf > pcmbuf_end)
990 buf = (short *)audiobuffer;
991 sample = *buf;
992 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
994 /* Toggle square wav side */
995 if (++count >= interval)
997 count = 0;
998 amplitude = -amplitude;
1000 if (buf > pcmbuf_end)
1001 buf = (short *)audiobuffer;
1004 else
1006 buf = (short *)audiobuffer;
1007 while (i++ < samples)
1009 *buf++ = amplitude;
1010 if (buf > pcmbuf_end)
1011 buf = (short *)audiobuffer;
1012 *buf++ = amplitude;
1014 /* Toggle square wav side */
1015 if (++count >= interval)
1017 count = 0;
1018 amplitude = -amplitude;
1020 if (buf > pcmbuf_end)
1021 buf = (short *)audiobuffer;
1023 pcm_play_data(NULL, (unsigned char *)audiobuffer, samples * 4);
1027 /* Returns pcm buffer usage in percents (0 to 100). */
1028 int pcmbuf_usage(void)
1030 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1033 int pcmbuf_mix_free(void)
1035 if (pcmbuf_mix_chunk)
1037 size_t my_mix_end =
1038 (size_t)&((short *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1039 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1040 if (my_write_pos < my_mix_end)
1041 my_write_pos += pcmbuf_size;
1042 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1044 return 100;
1047 void pcmbuf_mix_voice(int count)
1049 short *ibuf = (short *)voicebuf;
1050 short *obuf;
1051 size_t chunk_samples;
1053 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1055 pcmbuf_mix_chunk = pcmbuf_read->link;
1056 /* Start 1/8s into the next chunk */
1057 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1059 if (!pcmbuf_mix_chunk)
1060 return;
1062 obuf = (short *)pcmbuf_mix_chunk->addr;
1063 chunk_samples = pcmbuf_mix_chunk->size / 2;
1065 count <<= 1;
1067 while (count-- > 0) {
1068 int sample = *ibuf++;
1069 if (pcmbuf_mix_sample >= chunk_samples)
1071 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1072 if (!pcmbuf_mix_chunk)
1073 return;
1074 pcmbuf_mix_sample = 0;
1075 obuf = pcmbuf_mix_chunk->addr;
1076 chunk_samples = pcmbuf_mix_chunk->size / 2;
1078 sample += obuf[pcmbuf_mix_sample] >> 2;
1079 obuf[pcmbuf_mix_sample++] = MIN(MAX(sample, -32768), 32767);
1083 void pcmbuf_crossfade_enable(bool on_off)
1085 #if MEM > 1
1086 /* Next setting to be used, not applied now */
1087 crossfade_enabled_pending = on_off;
1088 #endif
1089 (void)on_off;
1092 void pcmbuf_crossfade_enable_finished(void)
1094 /* Copy the pending setting over now */
1095 crossfade_enabled = crossfade_enabled_pending;
1096 pcmbuf_set_watermark_bytes();
1099 bool pcmbuf_is_crossfade_enabled(void)
1101 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
1102 return global_settings.playlist_shuffle;
1104 return crossfade_enabled;