make sure closing the application aborts the remaining HttpGet objects. Should fix...
[Rockbox.git] / apps / pcmbuf.c
blob7e6954c280ef0dd1a9d788def649e7d7ceb6d39f
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 #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;
157 process_new_buffer:
159 /* Send the new buffer to the pcm */
160 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
161 size_t *realsize = size;
162 unsigned char** realstart = start;
163 if(pcmbuf_new)
165 size_t current_size = pcmbuf_new->size;
167 pcmbuf_unplayed_bytes -= current_size;
168 last_chunksize = current_size;
169 *realsize = current_size;
170 *realstart = pcmbuf_new->addr;
172 else
174 /* There may be more data waiting to flush, try to use it */
175 if (pcmbuf_flush_fillpos())
176 goto process_new_buffer;
178 /* No more buffers */
179 last_chunksize = 0;
180 *realsize = 0;
181 *realstart = NULL;
182 CALL_IF_EXISTS(pcmbuf_event_handler);
187 void pcmbuf_set_position_callback(void (*callback)(size_t size))
189 position_callback = callback;
192 static void pcmbuf_set_watermark_bytes(void)
194 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
195 /* If crossfading, try to keep the buffer full other than 1 second */
196 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
197 /* Otherwise, just keep it above 2 second */
198 PCMBUF_WATERMARK;
201 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
202 * in a separate function for the moment */
203 static inline void pcmbuf_add_chunk(void)
205 register size_t size = audiobuffer_fillpos;
206 /* Grab the next description to write, and change the write pointer */
207 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
208 pcmbuf_write = pcmbuf_current->link;
209 /* Fill in the values in the new buffer chunk */
210 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
211 pcmbuf_current->size = size;
212 pcmbuf_current->callback = pcmbuf_event_handler;
213 pcmbuf_current->link = NULL;
214 /* This is single use only */
215 pcmbuf_event_handler = NULL;
216 if (pcmbuf_read != NULL) {
217 if (pcmbuf_flush)
219 pcmbuf_write_end->link = pcmbuf_read->link;
220 pcmbuf_read->link = pcmbuf_current;
221 while (pcmbuf_write_end->link)
223 pcmbuf_write_end = pcmbuf_write_end->link;
224 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
226 pcmbuf_flush = false;
228 /* If there is already a read buffer setup, add to it */
229 else
230 pcmbuf_read_end->link = pcmbuf_current;
231 } else {
232 /* Otherwise create the buffer */
233 pcmbuf_read = pcmbuf_current;
235 /* This is now the last buffer to read */
236 pcmbuf_read_end = pcmbuf_current;
238 /* Update bytes counters */
239 pcmbuf_unplayed_bytes += size;
241 audiobuffer_pos += size;
242 if (audiobuffer_pos >= pcmbuf_size)
243 audiobuffer_pos -= pcmbuf_size;
245 audiobuffer_fillpos = 0;
248 #ifdef HAVE_PRIORITY_SCHEDULING
249 static void boost_codec_thread(bool boost)
251 if (boost)
253 if (codec_thread_priority == 0)
254 codec_thread_priority = thread_set_priority(
255 codec_thread_p, PRIORITY_REALTIME);
257 else if (codec_thread_priority != 0)
259 thread_set_priority(codec_thread_p, codec_thread_priority);
260 codec_thread_priority = 0;
263 #endif /* HAVE_PRIORITY_SCHEDULING */
265 static void pcmbuf_under_watermark(void)
267 /* Only codec thread initiates boost - voice boosts the cpu when playing
268 a clip */
269 #ifndef SIMULATOR
270 if (thread_get_current() == codec_thread_p)
271 #endif /* SIMULATOR */
273 #ifdef HAVE_PRIORITY_SCHEDULING
274 /* If buffer is critically low, override UI priority, else
275 set back to the original priority. */
276 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
277 #endif
278 /* Fill audio buffer by boosting cpu */
279 trigger_cpu_boost();
282 /* Disable crossfade if < .5s of audio */
283 if (LOW_DATA(2))
285 crossfade_active = false;
289 void pcmbuf_set_event_handler(void (*event_handler)(void))
291 pcmbuf_event_handler = event_handler;
294 unsigned int pcmbuf_get_latency(void)
296 /* Be careful how this calculation is rearranted, it's easy to overflow */
297 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
298 return bytes / 4 / (NATIVE_FREQUENCY/1000);
301 void pcmbuf_set_low_latency(bool state)
303 low_latency_mode = state;
306 bool pcmbuf_is_lowdata(void)
308 if (!pcm_is_playing() || pcm_is_paused() ||
309 crossfade_init || crossfade_active)
310 return false;
312 /* 1 seconds of buffer is low data */
313 return LOW_DATA(4);
316 /* Amount of bytes left in the buffer. */
317 inline size_t pcmbuf_free(void)
319 if (pcmbuf_read != NULL)
321 void *read = pcmbuf_read->addr;
322 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
323 if (read < write)
324 return (size_t)(read - write) + pcmbuf_size;
325 else
326 return (size_t) (read - write);
328 return pcmbuf_size;
331 bool pcmbuf_crossfade_init(bool manual_skip)
333 /* Can't do two crossfades at once and, no fade if pcm is off now */
334 if (crossfade_init || crossfade_active || !pcm_is_playing())
336 pcmbuf_play_stop();
337 return false;
340 trigger_cpu_boost();
342 /* Not enough data, or crossfade disabled, flush the old data instead */
343 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
345 pcmbuf_flush_fillpos();
346 pcmbuf_flush = true;
347 return false;
350 /* Don't enable mix mode when skipping tracks manually. */
351 if (manual_skip)
352 crossfade_mixmode = false;
353 else
354 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
356 crossfade_init = true;
358 return true;
362 void pcmbuf_play_stop(void)
364 pcm_play_stop();
366 pcmbuf_unplayed_bytes = 0;
367 pcmbuf_mix_chunk = NULL;
368 if (pcmbuf_read) {
369 pcmbuf_write_end->link = pcmbuf_read;
370 pcmbuf_write_end = pcmbuf_read_end;
371 pcmbuf_read = pcmbuf_read_end = NULL;
373 audiobuffer_pos = 0;
374 audiobuffer_fillpos = 0;
375 crossfade_init = false;
376 crossfade_active = false;
377 pcmbuf_flush = false;
379 #ifdef HAVE_PRIORITY_SCHEDULING
380 /* Can unboost the codec thread here no matter who's calling */
381 boost_codec_thread(false);
382 #endif
385 int pcmbuf_used_descs(void) {
386 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
387 unsigned int i = 0;
388 while (pcmbuf_temp) {
389 pcmbuf_temp = pcmbuf_temp->link;
390 i++;
392 return i;
395 int pcmbuf_descs(void) {
396 return PCMBUF_DESCS(pcmbuf_size);
399 size_t get_pcmbuf_descsize(void) {
400 return pcmbuf_descsize;
403 static void pcmbuf_init_pcmbuffers(void) {
404 struct pcmbufdesc *next = pcmbuf_write;
405 next++;
406 pcmbuf_write_end = pcmbuf_write;
407 while ((void *)next < (void *)pcmbuf_bufend) {
408 pcmbuf_write_end->link=next;
409 pcmbuf_write_end=next;
410 next++;
414 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
416 #if MEM > 1
417 size_t seconds = 1;
419 if (crossfade_enabled_pending)
420 seconds += global_settings.crossfade_fade_out_delay
421 + global_settings.crossfade_fade_out_duration;
423 /* Buffer has to be at least 2s long. */
424 seconds += 2;
425 logf("pcmbuf len: %ld", seconds);
426 return seconds * (NATIVE_FREQUENCY*4);
427 #else
428 return NATIVE_FREQUENCY*2;
429 #endif
432 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
434 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
435 PCMBUF_DESCS_SIZE(bufsize));
438 bool pcmbuf_is_same_size(void)
440 if (audiobuffer == NULL)
441 return true; /* Not set up yet even once so always */
443 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
444 return pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
447 /* Initialize the pcmbuffer the structure looks like this:
448 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
449 size_t pcmbuf_init(unsigned char *bufend)
451 pcmbuf_bufend = bufend;
452 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
453 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
454 fadebuf = &audiobuffer[pcmbuf_size];
455 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
456 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
458 pcmbuf_descsize = PCMBUF_DESCS_SIZE(pcmbuf_size);
459 pcmbuf_init_pcmbuffers();
461 position_callback = NULL;
462 pcmbuf_event_handler = NULL;
464 pcmbuf_crossfade_enable_finished();
466 pcmbuf_play_stop();
468 return pcmbuf_bufend - audiobuffer;
471 size_t pcmbuf_get_bufsize(void)
473 return pcmbuf_size;
476 #ifdef ROCKBOX_HAS_LOGF
477 unsigned char * pcmbuf_get_meminfo(size_t *length)
479 *length = pcmbuf_bufend - audiobuffer;
480 return audiobuffer;
482 #endif
484 void pcmbuf_pause(bool pause)
486 #ifdef PCMBUF_MUTING
487 if (pause)
488 pcm_mute(true);
489 #endif
490 pcm_play_pause(!pause);
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 pcmbuf_play_start();
829 else if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
830 pcmbuf_under_watermark();
832 return true;
835 void* pcmbuf_request_buffer(int *count)
837 if (crossfade_init)
838 crossfade_start();
840 if (crossfade_active) {
841 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
842 return fadebuf;
844 else
846 if(prepare_insert(*count << 2))
848 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
849 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
851 /* Usual case, there's space here */
852 return &audiobuffer[audiobuffer_index];
854 else
856 /* Flush and wrap the buffer */
857 pcmbuf_flush_fillpos();
858 audiobuffer_pos = 0;
859 return &audiobuffer[0];
862 else
864 return NULL;
869 void* pcmbuf_request_voice_buffer(int *count, bool mix)
871 if (mix)
873 if (pcmbuf_read == NULL)
875 return NULL;
877 else if (pcmbuf_mix_chunk || pcmbuf_read->link)
879 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
880 return voicebuf;
882 else
884 return NULL;
887 else
888 return pcmbuf_request_buffer(count);
891 bool pcmbuf_is_crossfade_active(void)
893 return crossfade_active || crossfade_init;
896 void pcmbuf_write_complete(int count)
898 size_t length = (size_t)(unsigned int)count << 2;
900 if (crossfade_active)
902 flush_crossfade(fadebuf, length);
903 if (!(crossfade_fade_in_rem || crossfade_chunk))
904 crossfade_active = false;
906 else
908 audiobuffer_fillpos += length;
910 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
911 pcmbuf_flush_fillpos();
915 #if 0
916 bool pcmbuf_insert_buffer(char *buf, int count)
918 size_t length = (size_t)(unsigned int)count << 2;
920 if (crossfade_active)
922 flush_crossfade(buf, length);
923 if (!(crossfade_fade_in_rem || crossfade_chunk))
924 crossfade_active = false;
926 else
928 if (!prepare_insert(length))
929 return false;
930 pcmbuf_flush_buffer(buf, length);
932 return true;
934 #endif
936 /* Generates a constant square wave sound with a given frequency
937 in Hertz for a duration in milliseconds. */
938 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
940 unsigned int count = 0, i = 0;
941 unsigned int interval = NATIVE_FREQUENCY / frequency;
942 long sample;
943 short *buf;
944 short *pcmbuf_end = (short *)fadebuf;
945 size_t samples = NATIVE_FREQUENCY / 1000 * duration;
947 if (pcm_is_playing() && pcmbuf_read != NULL)
949 if (pcmbuf_read->link)
951 /* Get the next chunk */
952 char *pcmbuf_mix_buf = pcmbuf_read->link->addr;
953 /* Give at least 1/8s clearance. */
954 buf = (short *)&pcmbuf_mix_buf[NATIVE_FREQUENCY * 4 / 8];
956 else
958 logf("No place to beep");
959 return;
962 while (i++ < samples)
964 sample = *buf;
965 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
966 if (buf > pcmbuf_end)
967 buf = (short *)audiobuffer;
968 sample = *buf;
969 *buf++ = MIN(MAX(sample + amplitude, -32768), 32767);
971 /* Toggle square wav side */
972 if (++count >= interval)
974 count = 0;
975 amplitude = -amplitude;
977 if (buf > pcmbuf_end)
978 buf = (short *)audiobuffer;
981 else
983 buf = (short *)audiobuffer;
984 while (i++ < samples)
986 *buf++ = amplitude;
987 if (buf > pcmbuf_end)
988 buf = (short *)audiobuffer;
989 *buf++ = amplitude;
991 /* Toggle square wav side */
992 if (++count >= interval)
994 count = 0;
995 amplitude = -amplitude;
997 if (buf > pcmbuf_end)
998 buf = (short *)audiobuffer;
1000 pcm_play_data(NULL, (unsigned char *)audiobuffer, samples * 4);
1004 /* Returns pcm buffer usage in percents (0 to 100). */
1005 int pcmbuf_usage(void)
1007 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1010 int pcmbuf_mix_free(void)
1012 if (pcmbuf_mix_chunk)
1014 size_t my_mix_end =
1015 (size_t)&((short *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1016 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1017 if (my_write_pos < my_mix_end)
1018 my_write_pos += pcmbuf_size;
1019 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1021 return 100;
1024 void pcmbuf_mix_voice(int count)
1026 short *ibuf = (short *)voicebuf;
1027 short *obuf;
1028 size_t chunk_samples;
1030 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1032 pcmbuf_mix_chunk = pcmbuf_read->link;
1033 /* Start 1/8s into the next chunk */
1034 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1036 if (!pcmbuf_mix_chunk)
1037 return;
1039 obuf = (short *)pcmbuf_mix_chunk->addr;
1040 chunk_samples = pcmbuf_mix_chunk->size / 2;
1042 count <<= 1;
1044 while (count-- > 0) {
1045 int sample = *ibuf++;
1046 if (pcmbuf_mix_sample >= chunk_samples)
1048 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1049 if (!pcmbuf_mix_chunk)
1050 return;
1051 pcmbuf_mix_sample = 0;
1052 obuf = pcmbuf_mix_chunk->addr;
1053 chunk_samples = pcmbuf_mix_chunk->size / 2;
1055 sample += obuf[pcmbuf_mix_sample] >> 2;
1056 obuf[pcmbuf_mix_sample++] = MIN(MAX(sample, -32768), 32767);
1060 void pcmbuf_crossfade_enable(bool on_off)
1062 #if MEM > 1
1063 /* Next setting to be used, not applied now */
1064 crossfade_enabled_pending = on_off;
1065 #endif
1066 (void)on_off;
1069 void pcmbuf_crossfade_enable_finished(void)
1071 /* Copy the pending setting over now */
1072 crossfade_enabled = crossfade_enabled_pending;
1073 pcmbuf_set_watermark_bytes();
1076 bool pcmbuf_is_crossfade_enabled(void)
1078 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
1079 return global_settings.playlist_shuffle;
1081 return crossfade_enabled;