Revert "Replace yield_codec() with a call to queue_wait_w_tmo()" and the related...
[Rockbox.git] / apps / pcmbuf.c
bloba6b82baf25eb60ca4182b59167f4c28272f3a0a1
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 "dsp.h"
38 #include "thread.h"
40 /* Define PCMBUF_MUTING if the codec requires muting to prevent pops */
41 #if !defined(HAVE_UDA1380) && !defined(HAVE_TLV320) && !defined(HAVE_AS3514)
42 #define PCMBUF_MUTING
43 #endif
45 /* Keep watermark high for iPods at least (2s) */
46 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
48 /* Structure we can use to queue pcm chunks in memory to be played
49 * by the driver code. */
50 struct pcmbufdesc
52 void *addr;
53 size_t size;
54 struct pcmbufdesc* link;
55 /* Call this when the buffer has been played */
56 void (*callback)(void);
59 #define PCMBUF_DESCS(bufsize) \
60 ((bufsize) / PCMBUF_MINAVG_CHUNK)
61 #define PCMBUF_DESCS_SIZE(bufsize) \
62 (PCMBUF_DESCS(bufsize)*sizeof(struct pcmbufdesc))
64 /* Size of the PCM buffer. */
65 static size_t pcmbuf_size IDATA_ATTR = 0;
66 static char *pcmbuf_bufend IDATA_ATTR;
67 static char *audiobuffer IDATA_ATTR;
68 /* Current audio buffer write index. */
69 static size_t audiobuffer_pos IDATA_ATTR;
70 /* Amount audiobuffer_pos will be increased.*/
71 static size_t audiobuffer_fillpos IDATA_ATTR;
72 static char *fadebuf IDATA_ATTR;
73 static char *voicebuf IDATA_ATTR;
75 static void (*pcmbuf_event_handler)(void) IDATA_ATTR;
76 static void (*position_callback)(size_t size) IDATA_ATTR;
78 /* Crossfade related state */
79 static bool crossfade_enabled;
80 static bool crossfade_enabled_pending;
81 static bool crossfade_mixmode;
82 static bool crossfade_active IDATA_ATTR;
83 static bool crossfade_init IDATA_ATTR;
85 /* Track the current location for processing crossfade */
86 static struct pcmbufdesc *crossfade_chunk IDATA_ATTR;
87 static size_t crossfade_sample IDATA_ATTR;
89 /* Counters for fading in new data */
90 static size_t crossfade_fade_in_total IDATA_ATTR;
91 static size_t crossfade_fade_in_rem IDATA_ATTR;
93 static size_t pcmbuf_descsize;
94 static struct pcmbufdesc *pcmbuf_read IDATA_ATTR;
95 static struct pcmbufdesc *pcmbuf_read_end IDATA_ATTR;
96 static struct pcmbufdesc *pcmbuf_write IDATA_ATTR;
97 static struct pcmbufdesc *pcmbuf_write_end IDATA_ATTR;
98 static size_t last_chunksize IDATA_ATTR;
100 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
101 static size_t pcmbuf_watermark IDATA_ATTR;
103 static struct pcmbufdesc *pcmbuf_mix_chunk IDATA_ATTR;
104 static size_t pcmbuf_mix_sample IDATA_ATTR;
106 static bool low_latency_mode = false;
107 static bool pcmbuf_flush;
109 #ifdef HAVE_PRIORITY_SCHEDULING
110 static int codec_thread_priority = 0;
111 #endif
113 extern struct thread_entry *codec_thread_p;
115 /* Helpful macros for use in conditionals this assumes some of the above
116 * static variable names */
117 #define NEED_FLUSH(position) \
118 (audiobuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
119 #define LOW_DATA(quarter_secs) \
120 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
122 static bool prepare_insert(size_t length);
123 static void pcmbuf_under_watermark(void);
124 static bool pcmbuf_flush_fillpos(void);
126 #define CALL_IF_EXISTS(function, args...) if (function) function(args)
127 /* This function has 2 major logical parts (separated by brackets both for
128 * readability and variable scoping). The first part performs the
129 * operastions related to finishing off the last buffer we fed to the DMA.
130 * The second part performs the operations involved in sending a new buffer
131 * to the DMA. Finally the function checks the status of the buffer and
132 * boosts if necessary */
133 static void pcmbuf_callback(unsigned char** start, size_t* size) ICODE_ATTR;
134 static void pcmbuf_callback(unsigned char** start, size_t* size)
137 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
138 /* Take the finished buffer out of circulation */
139 pcmbuf_read = pcmbuf_current->link;
141 /* The buffer is finished, call the callback functions */
142 CALL_IF_EXISTS(position_callback, last_chunksize);
143 CALL_IF_EXISTS(pcmbuf_current->callback);
145 /* Put the finished buffer back into circulation */
146 pcmbuf_write_end->link = pcmbuf_current;
147 pcmbuf_write_end = pcmbuf_current;
149 /* If we've read over the mix chunk while it's still mixing there */
150 if (pcmbuf_current == pcmbuf_mix_chunk)
151 pcmbuf_mix_chunk = NULL;
152 /* If we've read over the crossfade chunk while it's still fading */
153 if (pcmbuf_current == crossfade_chunk)
154 crossfade_chunk = pcmbuf_read;
158 /* Send the new buffer to the pcm */
159 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
160 size_t *realsize = size;
161 unsigned char** realstart = start;
162 if(pcmbuf_new)
164 size_t current_size = pcmbuf_new->size;
166 pcmbuf_unplayed_bytes -= current_size;
167 last_chunksize = current_size;
168 *realsize = current_size;
169 *realstart = pcmbuf_new->addr;
171 else
173 /* No more buffers */
174 last_chunksize = 0;
175 *realsize = 0;
176 *realstart = NULL;
177 CALL_IF_EXISTS(pcmbuf_event_handler);
182 void pcmbuf_set_position_callback(void (*callback)(size_t size))
184 position_callback = callback;
187 static void pcmbuf_set_watermark_bytes(void)
189 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
190 /* If crossfading, try to keep the buffer full other than 1 second */
191 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
192 /* Otherwise, just keep it above 2 second */
193 PCMBUF_WATERMARK;
196 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
197 * in a separate function for the moment */
198 static inline void pcmbuf_add_chunk(void)
200 register size_t size = audiobuffer_fillpos;
201 /* Grab the next description to write, and change the write pointer */
202 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
203 pcmbuf_write = pcmbuf_current->link;
204 /* Fill in the values in the new buffer chunk */
205 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
206 pcmbuf_current->size = size;
207 pcmbuf_current->callback = pcmbuf_event_handler;
208 pcmbuf_current->link = NULL;
209 /* This is single use only */
210 pcmbuf_event_handler = NULL;
211 if (pcmbuf_read != NULL) {
212 if (pcmbuf_flush)
214 pcmbuf_write_end->link = pcmbuf_read->link;
215 pcmbuf_read->link = pcmbuf_current;
216 while (pcmbuf_write_end->link)
218 pcmbuf_write_end = pcmbuf_write_end->link;
219 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
221 pcmbuf_flush = false;
223 /* If there is already a read buffer setup, add to it */
224 else
225 pcmbuf_read_end->link = pcmbuf_current;
226 } else {
227 /* Otherwise create the buffer */
228 pcmbuf_read = pcmbuf_current;
230 /* This is now the last buffer to read */
231 pcmbuf_read_end = pcmbuf_current;
233 /* Update bytes counters */
234 pcmbuf_unplayed_bytes += size;
236 audiobuffer_pos += size;
237 if (audiobuffer_pos >= pcmbuf_size)
238 audiobuffer_pos -= pcmbuf_size;
240 audiobuffer_fillpos = 0;
243 #ifdef HAVE_PRIORITY_SCHEDULING
244 static void boost_codec_thread(bool boost)
246 if (boost)
248 if (codec_thread_priority == 0)
249 codec_thread_priority = thread_set_priority(
250 codec_thread_p, PRIORITY_REALTIME);
252 else if (codec_thread_priority != 0)
254 thread_set_priority(codec_thread_p, codec_thread_priority);
255 codec_thread_priority = 0;
258 #endif /* HAVE_PRIORITY_SCHEDULING */
260 static void pcmbuf_under_watermark(void)
262 /* Only codec thread initiates boost - voice boosts the cpu when playing
263 a clip */
264 #ifndef SIMULATOR
265 if (thread_get_current() == codec_thread_p)
266 #endif /* SIMULATOR */
268 #ifdef HAVE_PRIORITY_SCHEDULING
269 /* If buffer is critically low, override UI priority, else
270 set back to the original priority. */
271 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
272 #endif
273 /* Fill audio buffer by boosting cpu */
274 trigger_cpu_boost();
277 /* Disable crossfade if < .5s of audio */
278 if (LOW_DATA(2))
280 crossfade_active = false;
284 void pcmbuf_set_event_handler(void (*event_handler)(void))
286 pcmbuf_event_handler = event_handler;
289 unsigned int pcmbuf_get_latency(void)
291 /* Be careful how this calculation is rearranted, it's easy to overflow */
292 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
293 return bytes / 4 / (NATIVE_FREQUENCY/1000);
296 void pcmbuf_set_low_latency(bool state)
298 low_latency_mode = state;
301 bool pcmbuf_is_lowdata(void)
303 if (!pcm_is_playing() || pcm_is_paused() ||
304 crossfade_init || crossfade_active)
305 return false;
307 /* 1 seconds of buffer is low data */
308 return LOW_DATA(4);
311 /* Amount of bytes left in the buffer. */
312 inline size_t pcmbuf_free(void)
314 if (pcmbuf_read != NULL)
316 void *read = pcmbuf_read->addr;
317 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
318 if (read < write)
319 return (size_t)(read - write) + pcmbuf_size;
320 else
321 return (size_t) (read - write);
323 return pcmbuf_size;
326 bool pcmbuf_crossfade_init(bool manual_skip)
328 /* Can't do two crossfades at once and, no fade if pcm is off now */
329 if (crossfade_init || crossfade_active || !pcm_is_playing())
331 pcmbuf_play_stop();
332 return false;
335 trigger_cpu_boost();
337 /* Not enough data, or crossfade disabled, flush the old data instead */
338 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
340 pcmbuf_flush_fillpos();
341 pcmbuf_flush = true;
342 return false;
345 /* Don't enable mix mode when skipping tracks manually. */
346 if (manual_skip)
347 crossfade_mixmode = false;
348 else
349 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
351 crossfade_init = true;
353 return true;
357 void pcmbuf_play_stop(void)
359 pcm_play_stop();
361 pcmbuf_unplayed_bytes = 0;
362 pcmbuf_mix_chunk = NULL;
363 if (pcmbuf_read) {
364 pcmbuf_write_end->link = pcmbuf_read;
365 pcmbuf_write_end = pcmbuf_read_end;
366 pcmbuf_read = pcmbuf_read_end = NULL;
368 audiobuffer_pos = 0;
369 audiobuffer_fillpos = 0;
370 crossfade_init = false;
371 crossfade_active = false;
372 pcmbuf_flush = false;
374 #ifdef HAVE_PRIORITY_SCHEDULING
375 /* Can unboost the codec thread here no matter who's calling */
376 boost_codec_thread(false);
377 #endif
380 int pcmbuf_used_descs(void) {
381 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
382 unsigned int i = 0;
383 while (pcmbuf_temp) {
384 pcmbuf_temp = pcmbuf_temp->link;
385 i++;
387 return i;
390 int pcmbuf_descs(void) {
391 return PCMBUF_DESCS(pcmbuf_size);
394 size_t get_pcmbuf_descsize(void) {
395 return pcmbuf_descsize;
398 static void pcmbuf_init_pcmbuffers(void) {
399 struct pcmbufdesc *next = pcmbuf_write;
400 next++;
401 pcmbuf_write_end = pcmbuf_write;
402 while ((void *)next < (void *)pcmbuf_bufend) {
403 pcmbuf_write_end->link=next;
404 pcmbuf_write_end=next;
405 next++;
409 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
411 #if MEM > 1
412 size_t seconds = 1;
414 if (crossfade_enabled_pending)
415 seconds += global_settings.crossfade_fade_out_delay
416 + global_settings.crossfade_fade_out_duration;
418 /* Buffer has to be at least 2s long. */
419 seconds += 2;
420 logf("pcmbuf len: %ld", seconds);
421 return seconds * (NATIVE_FREQUENCY*4);
422 #else
423 return NATIVE_FREQUENCY*2;
424 #endif
427 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
429 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
430 PCMBUF_DESCS_SIZE(bufsize));
433 bool pcmbuf_is_same_size(void)
435 if (audiobuffer == NULL)
436 return true; /* Not set up yet even once so always */
438 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
439 return pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
442 /* Initialize the pcmbuffer the structure looks like this:
443 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
444 size_t pcmbuf_init(unsigned char *bufend)
446 pcmbuf_bufend = bufend;
447 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
448 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
449 fadebuf = &audiobuffer[pcmbuf_size];
450 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
451 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
453 pcmbuf_descsize = PCMBUF_DESCS_SIZE(pcmbuf_size);
454 pcmbuf_init_pcmbuffers();
456 position_callback = NULL;
457 pcmbuf_event_handler = NULL;
459 pcmbuf_crossfade_enable_finished();
461 pcmbuf_play_stop();
463 return pcmbuf_bufend - audiobuffer;
466 size_t pcmbuf_get_bufsize(void)
468 return pcmbuf_size;
471 #ifdef ROCKBOX_HAS_LOGF
472 unsigned char * pcmbuf_get_meminfo(size_t *length)
474 *length = pcmbuf_bufend - audiobuffer;
475 return audiobuffer;
477 #endif
479 void pcmbuf_pause(bool pause)
481 #ifdef PCMBUF_MUTING
482 if (pause)
483 pcm_mute(true);
484 #endif
486 if (pcm_is_playing())
487 pcm_play_pause(!pause);
488 else if (!pause)
489 pcmbuf_play_start();
491 #ifdef PCMBUF_MUTING
492 if (!pause)
493 pcm_mute(false);
494 #endif
495 trigger_cpu_boost();
498 /* Force playback. */
499 void pcmbuf_play_start(void)
501 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && pcmbuf_read != NULL)
503 last_chunksize = pcmbuf_read->size;
504 pcmbuf_unplayed_bytes -= last_chunksize;
505 pcm_play_data(pcmbuf_callback,
506 (unsigned char *)pcmbuf_read->addr, last_chunksize);
511 * Commit samples waiting to the pcm buffer.
513 static bool pcmbuf_flush_fillpos(void)
515 if (audiobuffer_fillpos) {
516 /* Never use the last buffer descriptor */
517 while (pcmbuf_write == pcmbuf_write_end) {
518 /* If this happens, something is being stupid */
519 if (!pcm_is_playing()) {
520 logf("pcmbuf_flush_fillpos error");
521 pcmbuf_play_start();
523 /* Let approximately one chunk of data playback */
524 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
526 pcmbuf_add_chunk();
527 return true;
529 return false;
533 * Completely process the crossfade fade out effect with current pcm buffer.
535 static void crossfade_process_buffer(size_t fade_in_delay,
536 size_t fade_out_delay, size_t fade_out_rem)
538 if (!crossfade_mixmode)
540 /* Fade out the specified amount of the already processed audio */
541 size_t total_fade_out = fade_out_rem;
542 size_t fade_out_sample;
543 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
545 /* Find the right chunk to start fading out */
546 fade_out_delay += crossfade_sample * 2;
547 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
549 fade_out_delay -= fade_out_chunk->size;
550 fade_out_chunk = fade_out_chunk->link;
552 /* The start sample within the chunk */
553 fade_out_sample = fade_out_delay / 2;
555 while (fade_out_rem > 0)
557 /* Each 1/10 second of audio will have the same fade applied */
558 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
559 int factor = (fade_out_rem << 8) / total_fade_out;
561 fade_out_rem -= block_rem;
563 /* Fade this block */
564 while (block_rem > 0 && fade_out_chunk != NULL)
566 /* Fade one sample */
567 short *buf = (short *)(fade_out_chunk->addr);
568 int sample = buf[fade_out_sample];
569 buf[fade_out_sample++] = (sample * factor) >> 8;
571 block_rem -= 2;
572 /* Move to the next chunk as needed */
573 if (fade_out_sample * 2 >= fade_out_chunk->size)
575 fade_out_chunk = fade_out_chunk->link;
576 fade_out_sample = 0;
582 /* Find the right chunk and sample to start fading in */
583 fade_in_delay += crossfade_sample * 2;
584 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
586 fade_in_delay -= crossfade_chunk->size;
587 crossfade_chunk = crossfade_chunk->link;
589 crossfade_sample = fade_in_delay / 2;
590 logf("process done!");
593 /* Initializes crossfader, calculates all necessary parameters and
594 * performs fade-out with the pcm buffer. */
595 static void crossfade_start(void)
597 size_t crossfade_rem;
598 size_t crossfade_need;
599 size_t fade_out_rem;
600 size_t fade_out_delay;
601 size_t fade_in_delay;
603 crossfade_init = false;
604 /* Reject crossfade if less than .5s of data */
605 if (LOW_DATA(2)) {
606 logf("crossfade rejected");
607 pcmbuf_play_stop();
608 return ;
611 logf("crossfade_start");
612 pcmbuf_flush_fillpos();
613 crossfade_active = true;
615 /* Initialize the crossfade buffer size to all of the buffered data that
616 * has not yet been sent to the DMA */
617 crossfade_rem = pcmbuf_unplayed_bytes;
618 crossfade_chunk = pcmbuf_read->link;
619 crossfade_sample = 0;
621 /* Get fade out delay from settings. */
622 fade_out_delay =
623 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
625 /* Get fade out duration from settings. */
626 fade_out_rem =
627 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
629 crossfade_need = fade_out_delay + fade_out_rem;
630 /* We want only to modify the last part of the buffer. */
631 if (crossfade_rem > crossfade_need)
633 size_t crossfade_extra = crossfade_rem - crossfade_need;
634 while (crossfade_extra > crossfade_chunk->size)
636 crossfade_extra -= crossfade_chunk->size;
637 crossfade_chunk = crossfade_chunk->link;
639 crossfade_sample = crossfade_extra / 2;
641 /* Truncate fade out duration if necessary. */
642 else if (crossfade_rem < crossfade_need)
644 size_t crossfade_short = crossfade_need - crossfade_rem;
645 if (fade_out_rem >= crossfade_short)
646 fade_out_rem -= crossfade_short;
647 else
649 fade_out_delay -= crossfade_short - fade_out_rem;
650 fade_out_rem = 0;
654 /* Get also fade in duration and delays from settings. */
655 crossfade_fade_in_total =
656 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
657 crossfade_fade_in_rem = crossfade_fade_in_total;
659 fade_in_delay =
660 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
662 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
665 /* Returns the number of bytes _NOT_ mixed */
666 static size_t crossfade_fade_mix(int factor, const char *buf, size_t fade_rem)
668 const short *input_buf = (const short *)buf;
669 short *output_buf = (short *)(crossfade_chunk->addr);
670 short *chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
671 output_buf = &output_buf[crossfade_sample];
673 while (fade_rem)
675 int sample = *input_buf++;
676 sample = ((sample * factor) >> 8) + *output_buf;
677 *output_buf++ = MIN(32767, MAX(-32768, sample));
678 fade_rem -= 2;
680 if (output_buf >= chunk_end)
682 crossfade_chunk = crossfade_chunk->link;
683 if (!crossfade_chunk)
684 return fade_rem;
685 output_buf = (short *)(crossfade_chunk->addr);
686 chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
689 crossfade_sample = (size_t)(output_buf - (short *)(crossfade_chunk->addr));
690 return 0;
693 /* Returns the number of bytes _NOT_ mixed */
694 static size_t crossfade_mix(const char *buf, size_t length)
696 const short *input_buf = (const short *)buf;
697 short *output_buf = (short *)(crossfade_chunk->addr);
698 short *chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
699 output_buf = &output_buf[crossfade_sample];
701 while (length)
703 int sample = *input_buf++ + *output_buf;
704 *output_buf++ = MIN(32767, MAX(-32768, sample));
705 length -= 2;
707 if (output_buf >= chunk_end)
709 crossfade_chunk = crossfade_chunk->link;
710 if (!crossfade_chunk)
711 return length;
712 output_buf = (short *)(crossfade_chunk->addr);
713 chunk_end = (short *)((size_t)output_buf + crossfade_chunk->size);
716 crossfade_sample = (size_t)(output_buf - (short *)(crossfade_chunk->addr));
717 return 0;
720 static void pcmbuf_flush_buffer(const char *buf, size_t length)
722 size_t copy_n;
723 while (length > 0) {
724 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
725 if (NEED_FLUSH(audiobuffer_index))
727 pcmbuf_flush_fillpos();
728 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
730 copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
731 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
732 buf += copy_n;
733 audiobuffer_fillpos += copy_n;
734 length -= copy_n;
738 static void flush_crossfade(char *buf, size_t length)
740 if (length)
742 if (crossfade_fade_in_rem)
744 size_t samples;
745 short *input_buf;
747 /* Fade factor for this packet */
748 int factor =
749 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
750 crossfade_fade_in_total;
751 /* Bytes to fade */
752 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
754 /* We _will_ fade this many bytes */
755 crossfade_fade_in_rem -= fade_rem;
757 if (crossfade_chunk)
759 /* Mix the data */
760 size_t fade_total = fade_rem;
761 fade_rem = crossfade_fade_mix(factor, buf, fade_rem);
762 length -= fade_total - fade_rem;
763 buf += fade_total - fade_rem;
764 if (!length)
765 return;
766 if (!fade_rem)
767 goto fade_done;
770 samples = fade_rem / 2;
771 input_buf = (short *)buf;
772 /* Fade remaining samples in place */
773 while (samples)
775 int sample = *input_buf;
776 *input_buf++ = (sample * factor) >> 8;
777 samples--;
781 fade_done:
782 if (crossfade_chunk)
784 /* Mix the data */
785 size_t mix_total = length;
786 length = crossfade_mix(buf, length);
787 buf += mix_total - length;
788 if (!length)
789 return;
792 /* Flush samples to the buffer */
793 while (!prepare_insert(length))
794 sleep(1);
795 pcmbuf_flush_buffer(buf, length);
800 static bool prepare_insert(size_t length)
802 if (low_latency_mode)
804 /* 1/4s latency. */
805 if (pcmbuf_unplayed_bytes > NATIVE_FREQUENCY * 4 / 4
806 && pcm_is_playing())
807 return false;
810 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
811 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
812 return false;
814 if (!pcm_is_playing())
816 trigger_cpu_boost();
818 /* Pre-buffer 1s. */
819 #if MEM <= 1
820 if (!LOW_DATA(1))
821 #else
822 if (!LOW_DATA(4))
823 #endif
825 logf("pcm starting");
826 if (!(audio_status() & AUDIO_STATUS_PAUSE))
827 pcmbuf_play_start();
830 else if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
831 pcmbuf_under_watermark();
833 return true;
836 void* pcmbuf_request_buffer(int *count)
838 if (crossfade_init)
839 crossfade_start();
841 if (crossfade_active) {
842 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
843 return fadebuf;
845 else
847 if(prepare_insert(*count << 2))
849 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
850 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
852 /* Usual case, there's space here */
853 return &audiobuffer[audiobuffer_index];
855 else
857 /* Flush and wrap the buffer */
858 pcmbuf_flush_fillpos();
859 audiobuffer_pos = 0;
860 return &audiobuffer[0];
863 else
865 return NULL;
870 void* pcmbuf_request_voice_buffer(int *count, bool mix)
872 if (mix)
874 if (pcmbuf_read == NULL)
876 return NULL;
878 else if (pcmbuf_mix_chunk || pcmbuf_read->link)
880 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
881 return voicebuf;
883 else
885 return NULL;
888 else
889 return pcmbuf_request_buffer(count);
892 bool pcmbuf_is_crossfade_active(void)
894 return crossfade_active || crossfade_init;
897 void pcmbuf_write_complete(int count)
899 size_t length = (size_t)(unsigned int)count << 2;
901 if (crossfade_active)
903 flush_crossfade(fadebuf, length);
904 if (!(crossfade_fade_in_rem || crossfade_chunk))
905 crossfade_active = false;
907 else
909 audiobuffer_fillpos += length;
911 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
912 pcmbuf_flush_fillpos();
916 #if 0
917 bool pcmbuf_insert_buffer(char *buf, int count)
919 size_t length = (size_t)(unsigned int)count << 2;
921 if (crossfade_active)
923 flush_crossfade(buf, length);
924 if (!(crossfade_fade_in_rem || crossfade_chunk))
925 crossfade_active = false;
927 else
929 if (!prepare_insert(length))
930 return false;
931 pcmbuf_flush_buffer(buf, length);
933 return true;
935 #endif
937 /* Generates a constant square wave sound with a given frequency
938 in Hertz for a duration in milliseconds. */
939 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
941 unsigned int count = 0, i = 0;
942 unsigned int interval = NATIVE_FREQUENCY / frequency;
943 long sample;
944 short *buf;
945 short *pcmbuf_end = (short *)fadebuf;
946 size_t samples = NATIVE_FREQUENCY / 1000 * duration;
948 if (pcm_is_playing() && pcmbuf_read != NULL)
950 if (pcmbuf_read->link)
952 /* Get the next chunk */
953 char *pcmbuf_mix_buf = pcmbuf_read->link->addr;
954 /* Give at least 1/8s clearance. */
955 buf = (short *)&pcmbuf_mix_buf[NATIVE_FREQUENCY * 4 / 8];
957 else
959 logf("No place to beep");
960 return;
963 while (i++ < samples)
965 sample = *buf;
966 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
967 if (buf > pcmbuf_end)
968 buf = (short *)audiobuffer;
969 sample = *buf;
970 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
972 /* Toggle square wav side */
973 if (++count >= interval)
975 count = 0;
976 amplitude = -amplitude;
978 if (buf > pcmbuf_end)
979 buf = (short *)audiobuffer;
982 else
984 buf = (short *)audiobuffer;
985 while (i++ < samples)
987 *buf++ = amplitude;
988 if (buf > pcmbuf_end)
989 buf = (short *)audiobuffer;
990 *buf++ = amplitude;
992 /* Toggle square wav side */
993 if (++count >= interval)
995 count = 0;
996 amplitude = -amplitude;
998 if (buf > pcmbuf_end)
999 buf = (short *)audiobuffer;
1001 pcm_play_data(NULL, (unsigned char *)audiobuffer, samples * 4);
1005 /* Returns pcm buffer usage in percents (0 to 100). */
1006 int pcmbuf_usage(void)
1008 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1011 int pcmbuf_mix_free(void)
1013 if (pcmbuf_mix_chunk)
1015 size_t my_mix_end =
1016 (size_t)&((short *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1017 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1018 if (my_write_pos < my_mix_end)
1019 my_write_pos += pcmbuf_size;
1020 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1022 return 100;
1025 void pcmbuf_mix_voice(int count)
1027 short *ibuf = (short *)voicebuf;
1028 short *obuf;
1029 size_t chunk_samples;
1031 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1033 pcmbuf_mix_chunk = pcmbuf_read->link;
1034 /* Start 1/8s into the next chunk */
1035 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1037 if (!pcmbuf_mix_chunk)
1038 return;
1040 obuf = (short *)pcmbuf_mix_chunk->addr;
1041 chunk_samples = pcmbuf_mix_chunk->size / 2;
1043 count <<= 1;
1045 while (count-- > 0) {
1046 int sample = *ibuf++;
1047 if (pcmbuf_mix_sample >= chunk_samples)
1049 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1050 if (!pcmbuf_mix_chunk)
1051 return;
1052 pcmbuf_mix_sample = 0;
1053 obuf = pcmbuf_mix_chunk->addr;
1054 chunk_samples = pcmbuf_mix_chunk->size / 2;
1056 sample += obuf[pcmbuf_mix_sample] >> 2;
1057 obuf[pcmbuf_mix_sample++] = MIN(MAX(sample, -32768), 32767);
1061 void pcmbuf_crossfade_enable(bool on_off)
1063 #if MEM > 1
1064 /* Next setting to be used, not applied now */
1065 crossfade_enabled_pending = on_off;
1066 #endif
1067 (void)on_off;
1070 void pcmbuf_crossfade_enable_finished(void)
1072 /* Copy the pending setting over now */
1073 crossfade_enabled = crossfade_enabled_pending;
1074 pcmbuf_set_watermark_bytes();
1077 bool pcmbuf_is_crossfade_enabled(void)
1079 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
1080 return global_settings.playlist_shuffle;
1082 return crossfade_enabled;