pcmbuf: consolidated some crossfade code
[kugel-rb.git] / apps / pcmbuf.c
blob9bf4c96233d65fc23e5ca0059dba4575081cfe76
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include <stdio.h>
22 #include "config.h"
23 #include "system.h"
24 #include "debug.h"
25 #include <kernel.h>
26 #include "pcmbuf.h"
27 #include "pcm.h"
28 #include "playback.h"
30 /* Define LOGF_ENABLE to enable logf output in this file */
31 /*#define LOGF_ENABLE*/
32 #include "logf.h"
33 #ifndef SIMULATOR
34 #include "cpu.h"
35 #endif
36 #include <string.h>
37 #include "settings.h"
38 #include "audio.h"
39 #include "voice_thread.h"
40 #include "dsp.h"
42 #define PCMBUF_TARGET_CHUNK 32768 /* This is the target fill size of chunks
43 on the pcm buffer */
44 #define PCMBUF_MINAVG_CHUNK 24576 /* This is the minimum average size of
45 chunks on the pcm buffer (or we run out
46 of buffer descriptors, which is
47 non-fatal) */
48 #define PCMBUF_MIN_CHUNK 4096 /* We try to never feed a chunk smaller than
49 this to the DMA */
50 #define PCMBUF_MIX_CHUNK 8192 /* This is the maximum size of one packet
51 for mixing (crossfade or voice) */
53 #if MEMORYSIZE > 2
54 /* Keep watermark high for iPods at least (2s) */
55 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
56 #else
57 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 1) /* 0.25 seconds */
58 #endif
60 /* Structure we can use to queue pcm chunks in memory to be played
61 * by the driver code. */
62 struct chunkdesc
64 void *addr;
65 size_t size;
66 struct chunkdesc* link;
67 /* true if last chunk in the track */
68 bool end_of_track;
71 #define NUM_CHUNK_DESCS(bufsize) \
72 ((bufsize) / PCMBUF_MINAVG_CHUNK)
74 /* Size of the PCM buffer. */
75 static size_t pcmbuf_size IDATA_ATTR = 0;
76 static char *pcmbuf_bufend IDATA_ATTR;
77 static char *pcmbuffer IDATA_ATTR;
78 /* Current PCM buffer write index. */
79 static size_t pcmbuffer_pos IDATA_ATTR;
80 /* Amount pcmbuffer_pos will be increased.*/
81 static size_t pcmbuffer_fillpos IDATA_ATTR;
83 /* Gapless playback */
84 static bool end_of_track IDATA_ATTR;
85 bool track_transition IDATA_ATTR;
87 #ifdef HAVE_CROSSFADE
88 /* Crossfade buffer */
89 static char *fadebuf IDATA_ATTR;
91 /* Crossfade related state */
92 static bool crossfade_enabled;
93 static bool crossfade_enable_request;
94 static bool crossfade_mixmode;
95 static bool crossfade_active IDATA_ATTR;
96 static bool crossfade_track_change_started IDATA_ATTR;
98 /* Track the current location for processing crossfade */
99 static struct chunkdesc *crossfade_chunk IDATA_ATTR;
100 static size_t crossfade_sample IDATA_ATTR;
102 /* Counters for fading in new data */
103 static size_t crossfade_fade_in_total IDATA_ATTR;
104 static size_t crossfade_fade_in_rem IDATA_ATTR;
105 #endif
107 static struct chunkdesc *read_chunk IDATA_ATTR;
108 static struct chunkdesc *read_end_chunk IDATA_ATTR;
109 static struct chunkdesc *write_chunk IDATA_ATTR;
110 static struct chunkdesc *write_end_chunk IDATA_ATTR;
111 static size_t last_chunksize IDATA_ATTR;
113 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
114 static size_t pcmbuf_watermark IDATA_ATTR;
116 /* Voice */
117 static char *voicebuf IDATA_ATTR;
118 static struct chunkdesc *mix_chunk IDATA_ATTR;
119 static size_t pcmbuf_mix_sample IDATA_ATTR;
121 static bool low_latency_mode = false;
122 static bool flush_pcmbuf = false;
124 #ifdef HAVE_PRIORITY_SCHEDULING
125 static int codec_thread_priority = PRIORITY_PLAYBACK;
126 #endif
128 extern unsigned int codec_thread_id;
130 /* Helpful macros for use in conditionals this assumes some of the above
131 * static variable names */
132 #define COMMIT_IF_NEEDED if(pcmbuffer_fillpos > PCMBUF_TARGET_CHUNK || \
133 (pcmbuffer_pos + pcmbuffer_fillpos) >= pcmbuf_size) commit_chunk(false)
134 #define LOW_DATA(quarter_secs) \
135 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
137 #ifdef HAVE_CROSSFADE
138 static void crossfade_start(void);
139 static void write_to_crossfade(char *buf, size_t length);
140 static void pcmbuf_finish_crossfade_enable(void);
141 #endif
144 /**************************************/
146 /* define this to show detailed chunkdesc usage information on the sim console */
147 /*#define DESC_DEBUG*/
149 #ifndef SIMULATOR
150 #undef DESC_DEBUG
151 #endif
152 #ifdef DESC_DEBUG
153 static struct chunkdesc *first_desc;
154 static bool show_desc_in_use = false;
155 #define DISPLAY_DESC(caller) while(!show_desc(caller))
156 #define DESC_IDX(desc) (desc ? desc - first_desc : -1)
157 #define DESCL_IDX(desc) (desc && desc->link ? desc->link - first_desc : -1)
158 #define SHOW_1ST(desc) if(DESC_IDX (desc)==-1) DEBUGF(" -- "); \
159 else DEBUGF(" %02d ", DESC_IDX(desc))
160 #define SHOW_2ND(desc) if(DESCL_IDX(desc)==-1) DEBUGF("l -- "); \
161 else DEBUGF("l %02d ", DESCL_IDX(desc))
162 #define DESC_SHOW(tag, desc) DEBUGF(tag);SHOW_1ST(desc); \
163 DEBUGF(tag);SHOW_2ND(desc)
165 static bool show_desc(char *caller)
167 if (show_desc_in_use) return false;
168 show_desc_in_use = true;
169 DEBUGF("%-14s\t", caller);
170 DESC_SHOW("r", read_chunk);
171 DESC_SHOW("re", read_end_chunk);
172 DEBUGF(" ");
173 DESC_SHOW("w", write_chunk);
174 DESC_SHOW("we", write_end_chunk);
175 DEBUGF("\n");
176 show_desc_in_use = false;
177 return true;
179 #else
180 #define DISPLAY_DESC(caller) do{}while(0)
181 #endif
184 /** Accept new PCM data */
186 /* Commit PCM buffer samples as a new chunk for playback */
187 static void commit_chunk(bool flush_next_time)
189 if (!pcmbuffer_fillpos)
190 return;
192 /* Never use the last buffer descriptor */
193 while (write_chunk == write_end_chunk) {
194 /* If this happens, something is being stupid */
195 if (!pcm_is_playing()) {
196 logf("commit_chunk error");
197 pcmbuf_play_start();
199 /* Let approximately one chunk of data playback */
200 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
203 /* commit the chunk */
205 register size_t size = pcmbuffer_fillpos;
206 /* Grab the next description to write, and change the write pointer */
207 register struct chunkdesc *pcmbuf_current = write_chunk;
208 write_chunk = pcmbuf_current->link;
209 /* Fill in the values in the new buffer chunk */
210 pcmbuf_current->addr = &pcmbuffer[pcmbuffer_pos];
211 pcmbuf_current->size = size;
212 pcmbuf_current->end_of_track = end_of_track;
213 pcmbuf_current->link = NULL;
214 end_of_track = false; /* This is single use only */
216 if (read_chunk != NULL)
218 if (flush_pcmbuf)
220 /* Flush! Discard all data after the currently playing chunk,
221 and make the current chunk play next */
222 write_end_chunk->link = read_chunk->link;
223 read_chunk->link = pcmbuf_current;
224 while (write_end_chunk->link)
226 write_end_chunk = write_end_chunk->link;
227 pcmbuf_unplayed_bytes -= write_end_chunk->size;
230 /* If there is already a read buffer setup, add to it */
231 else
232 read_end_chunk->link = pcmbuf_current;
234 else
236 /* Otherwise create the buffer */
237 read_chunk = pcmbuf_current;
240 /* If flush_next_time is true, then the current chunk will be thrown out
241 * and the next chunk to be committed will be the next to be played.
242 * This is used to empty the PCM buffer for a track change. */
243 flush_pcmbuf = flush_next_time;
245 /* This is now the last buffer to read */
246 read_end_chunk = pcmbuf_current;
248 /* Update bytes counters */
249 pcmbuf_unplayed_bytes += size;
251 pcmbuffer_pos += size;
252 if (pcmbuffer_pos >= pcmbuf_size)
253 pcmbuffer_pos -= pcmbuf_size;
255 pcmbuffer_fillpos = 0;
256 DISPLAY_DESC("commit_chunk");
259 /* Set priority of the codec thread */
260 #ifdef HAVE_PRIORITY_SCHEDULING
261 static void boost_codec_thread(bool boost)
263 /* Keep voice and codec threads at the same priority or else voice
264 * will starve if the codec thread's priority is boosted. */
265 if (boost)
267 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
268 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
270 if (priority != codec_thread_priority)
272 codec_thread_priority = priority;
273 thread_set_priority(codec_thread_id, priority);
274 voice_thread_set_priority(priority);
277 else if (codec_thread_priority != PRIORITY_PLAYBACK)
279 thread_set_priority(codec_thread_id, PRIORITY_PLAYBACK);
280 voice_thread_set_priority(PRIORITY_PLAYBACK);
281 codec_thread_priority = PRIORITY_PLAYBACK;
284 #else
285 #define boost_codec_thread(boost) do{}while(0)
286 #endif /* HAVE_PRIORITY_SCHEDULING */
288 /* Return true if the PCM buffer is able to receive new data.
289 * Also maintain buffer level above the watermark. */
290 static bool prepare_insert(size_t length)
292 if (low_latency_mode)
294 /* 1/4s latency. */
295 if (!LOW_DATA(1) && pcm_is_playing())
296 return false;
299 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
300 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
301 return false;
303 /* Maintain the buffer level above the watermark */
304 if (pcm_is_playing())
306 /* Only codec thread initiates boost - voice boosts the cpu when playing
307 a clip */
308 #ifndef SIMULATOR
309 if (thread_get_current() == codec_thread_id)
310 #endif /* SIMULATOR */
312 if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
314 /* Fill PCM buffer by boosting cpu */
315 trigger_cpu_boost();
316 /* If buffer is critically low, override UI priority, else
317 set back to the original priority. */
318 boost_codec_thread(LOW_DATA(2));
320 else
322 boost_codec_thread(false);
326 #ifdef HAVE_CROSSFADE
327 /* Disable crossfade if < .5s of audio */
328 if (LOW_DATA(2))
330 crossfade_active = false;
332 #endif
334 else /* pcm_is_playing */
336 /* Boost CPU for pre-buffer */
337 trigger_cpu_boost();
339 /* If pre-buffered to the watermark, start playback */
340 #if MEMORYSIZE > 2
341 if (!LOW_DATA(4))
342 #else
343 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
344 #endif
346 logf("pcm starting");
347 if (!(audio_status() & AUDIO_STATUS_PAUSE))
348 pcmbuf_play_start();
352 return true;
355 /* Request space in the buffer for writing output samples */
356 void *pcmbuf_request_buffer(int *count)
358 #ifdef HAVE_CROSSFADE
359 /* we're going to crossfade to a new track, which is now on its way */
360 if (crossfade_track_change_started)
361 crossfade_start();
363 /* crossfade has begun, put the new track samples in fadebuf */
364 if (crossfade_active)
366 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
367 return fadebuf;
369 else
370 #endif
371 /* if possible, reserve room in the PCM buffer for new samples */
373 if(prepare_insert(*count << 2))
375 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
376 if (pcmbuf_size - pcmbuffer_index >= PCMBUF_MIN_CHUNK)
378 /* Usual case, there's space here */
379 return &pcmbuffer[pcmbuffer_index];
381 else
383 /* Wrap the buffer, the new samples go at the beginning */
384 commit_chunk(false);
385 pcmbuffer_pos = 0;
386 return &pcmbuffer[0];
390 /* PCM buffer not ready to receive new data yet */
391 return NULL;
394 /* Handle new samples to the buffer */
395 void pcmbuf_write_complete(int count)
397 size_t length = (size_t)(unsigned int)count << 2;
398 #ifdef HAVE_CROSSFADE
399 if (crossfade_active)
400 write_to_crossfade(fadebuf, length);
401 else
402 #endif
404 pcmbuffer_fillpos += length;
405 COMMIT_IF_NEEDED;
410 /** Init */
412 static inline void init_pcmbuffers(void)
414 #ifdef DESC_DEBUG
415 first_desc = write_chunk;
416 #endif
417 struct chunkdesc *next = write_chunk;
418 next++;
419 write_end_chunk = write_chunk;
420 while ((void *)next < (void *)pcmbuf_bufend) {
421 write_end_chunk->link=next;
422 write_end_chunk=next;
423 next++;
425 DISPLAY_DESC("init");
428 static size_t get_next_required_pcmbuf_size(void)
430 size_t seconds = 1;
432 #ifdef HAVE_CROSSFADE
433 if (crossfade_enable_request)
434 seconds += global_settings.crossfade_fade_out_delay +
435 global_settings.crossfade_fade_out_duration;
436 #endif
438 #if MEMORYSIZE > 2
439 /* Buffer has to be at least 2s long. */
440 seconds += 2;
441 #endif
442 logf("pcmbuf len: %ld", (long)seconds);
443 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
446 /* Initialize the pcmbuffer the structure looks like this:
447 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
448 size_t pcmbuf_init(unsigned char *bufend)
450 pcmbuf_bufend = bufend;
451 pcmbuf_size = get_next_required_pcmbuf_size();
452 write_chunk = (struct chunkdesc *)pcmbuf_bufend -
453 NUM_CHUNK_DESCS(pcmbuf_size);
454 voicebuf = (char *)write_chunk - PCMBUF_MIX_CHUNK;
455 #ifdef HAVE_CROSSFADE
456 fadebuf = voicebuf - PCMBUF_MIX_CHUNK;
457 pcmbuffer = fadebuf - pcmbuf_size;
458 #else
459 pcmbuffer = voicebuf - pcmbuf_size;
460 #endif
462 init_pcmbuffers();
464 #ifdef HAVE_CROSSFADE
465 pcmbuf_finish_crossfade_enable();
466 #else
467 pcmbuf_watermark = PCMBUF_WATERMARK;
468 #endif
470 pcmbuf_play_stop();
472 return pcmbuf_bufend - pcmbuffer;
476 /** Track change */
478 void pcmbuf_start_track_change(bool auto_skip)
480 bool crossfade = false;
481 #ifdef HAVE_CROSSFADE
482 /* Determine whether this track change needs to crossfade */
483 if(crossfade_enabled && !pcmbuf_is_crossfade_active())
485 switch(global_settings.crossfade)
487 case CROSSFADE_ENABLE_AUTOSKIP:
488 crossfade = auto_skip;
489 break;
490 case CROSSFADE_ENABLE_MANSKIP:
491 crossfade = !auto_skip;
492 break;
493 case CROSSFADE_ENABLE_SHUFFLE:
494 crossfade = global_settings.playlist_shuffle;
495 break;
496 case CROSSFADE_ENABLE_SHUFFLE_AND_MANSKIP:
497 crossfade = global_settings.playlist_shuffle && !auto_skip;
498 break;
499 case CROSSFADE_ENABLE_ALWAYS:
500 crossfade = true;
501 break;
504 #endif
506 if (!auto_skip || crossfade)
507 /* manual skip or crossfade */
509 if (crossfade)
510 { logf(" crossfade track change"); }
511 else
512 { logf(" manual track change"); }
514 /* Notify the wps that the track change starts now */
515 audio_post_track_change(false);
517 /* Can't do two crossfades at once and, no fade if pcm is off now */
518 if (
519 #ifdef HAVE_CROSSFADE
520 pcmbuf_is_crossfade_active() ||
521 #endif
522 !pcm_is_playing())
524 pcmbuf_play_stop();
525 return;
528 trigger_cpu_boost();
530 /* Not enough data, or not crossfading, flush the old data instead */
531 if (LOW_DATA(2) || !crossfade || low_latency_mode)
533 commit_chunk(true);
534 return;
537 #ifdef HAVE_CROSSFADE
538 /* Don't enable mix mode when skipping tracks manually. */
539 crossfade_mixmode = auto_skip && global_settings.crossfade_fade_out_mixmode;
541 crossfade_track_change_started = crossfade;
542 #endif
544 else /* automatic and not crossfading, so do gapless track change */
546 /* The codec is moving on to the next track, but the current track will
547 * continue to play. Set a flag to make sure the elapsed time of the
548 * current track will be updated properly, and mark the current chunk
549 * as the last one in the track. */
550 logf(" gapless track change");
551 track_transition = true;
552 end_of_track = true;
557 /** Playback */
559 /* PCM driver callback
560 * This function has 3 major logical parts (separated by brackets both for
561 * readability and variable scoping). The first part performs the
562 * operations related to finishing off the last chunk we fed to the DMA.
563 * The second part detects the end of playlist condition when the PCM
564 * buffer is empty except for uncommitted samples. Then they are committed
565 * and sent to the PCM driver for playback. The third part performs the
566 * operations involved in sending a new chunk to the DMA. */
567 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size) ICODE_ATTR;
568 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size)
571 struct chunkdesc *pcmbuf_current = read_chunk;
572 /* Take the finished chunk out of circulation */
573 read_chunk = pcmbuf_current->link;
575 /* if during a track transition, update the elapsed time */
576 if (track_transition)
577 audio_pcmbuf_position_callback(last_chunksize);
579 /* if last chunk in the track, stop updates and notify audio thread */
580 if (pcmbuf_current->end_of_track)
582 track_transition = false;
583 audio_post_track_change(true);
586 /* Put the finished chunk back into circulation */
587 write_end_chunk->link = pcmbuf_current;
588 write_end_chunk = pcmbuf_current;
590 /* If we've read over the mix chunk while it's still mixing there */
591 if (pcmbuf_current == mix_chunk)
592 mix_chunk = NULL;
594 #ifdef HAVE_CROSSFADE
595 /* If we've read over the crossfade chunk while it's still fading */
596 if (pcmbuf_current == crossfade_chunk)
597 crossfade_chunk = read_chunk;
598 #endif
602 /* Commit last samples at end of playlist */
603 if (pcmbuffer_fillpos && !read_chunk)
605 logf("pcmbuf_pcm_callback: commit last samples");
606 commit_chunk(false);
611 /* Send the new chunk to the PCM */
612 if(read_chunk)
614 size_t current_size = read_chunk->size;
616 pcmbuf_unplayed_bytes -= current_size;
617 last_chunksize = current_size;
618 *size = current_size;
619 *start = read_chunk->addr;
621 else
623 /* No more chunks */
624 logf("pcmbuf_pcm_callback: no more chunks");
625 last_chunksize = 0;
626 *size = 0;
627 *start = NULL;
630 DISPLAY_DESC("callback");
633 /* Force playback */
634 void pcmbuf_play_start(void)
636 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && read_chunk != NULL)
638 logf("pcmbuf_play_start");
639 last_chunksize = read_chunk->size;
640 pcmbuf_unplayed_bytes -= last_chunksize;
641 pcm_play_data(pcmbuf_pcm_callback,
642 (unsigned char *)read_chunk->addr, last_chunksize);
646 void pcmbuf_play_stop(void)
648 logf("pcmbuf_play_stop");
649 pcm_play_stop();
651 pcmbuf_unplayed_bytes = 0;
652 mix_chunk = NULL;
653 if (read_chunk) {
654 write_end_chunk->link = read_chunk;
655 write_end_chunk = read_end_chunk;
656 read_chunk = read_end_chunk = NULL;
658 pcmbuffer_pos = 0;
659 pcmbuffer_fillpos = 0;
660 #ifdef HAVE_CROSSFADE
661 crossfade_track_change_started = false;
662 crossfade_active = false;
663 #endif
664 end_of_track = false;
665 track_transition = false;
666 DISPLAY_DESC("play_stop");
668 /* Can unboost the codec thread here no matter who's calling */
669 boost_codec_thread(false);
672 void pcmbuf_pause(bool pause)
674 logf("pcmbuf_pause: %s", pause?"pause":"play");
675 if (pcm_is_playing())
676 pcm_play_pause(!pause);
677 else if (!pause)
678 pcmbuf_play_start();
682 /** Crossfade */
684 /* Clip sample to signed 16 bit range */
685 static inline int32_t clip_sample_16(int32_t sample)
687 if ((int16_t)sample != sample)
688 sample = 0x7fff ^ (sample >> 31);
689 return sample;
692 #ifdef HAVE_CROSSFADE
693 /* Find the chunk that's (length) deep in the list. Return the position within
694 * the chunk, and leave the chunkdesc pointer pointing to the chunk. */
695 static size_t find_chunk(size_t length, struct chunkdesc **chunk)
697 while (*chunk && length >= (*chunk)->size)
699 length -= (*chunk)->size;
700 *chunk = (*chunk)->link;
702 return length / 2;
705 /* Initializes crossfader, calculates all necessary parameters and performs
706 * fade-out with the PCM buffer. */
707 static void crossfade_start(void)
709 size_t crossfade_rem;
710 size_t crossfade_need;
711 size_t fade_out_rem;
712 size_t fade_out_delay;
713 size_t fade_in_delay;
715 crossfade_track_change_started = false;
716 /* Reject crossfade if less than .5s of data */
717 if (LOW_DATA(2)) {
718 logf("crossfade rejected");
719 pcmbuf_play_stop();
720 return ;
723 logf("crossfade_start");
724 commit_chunk(false);
725 crossfade_active = true;
727 /* Initialize the crossfade buffer size to all of the buffered data that
728 * has not yet been sent to the DMA */
729 crossfade_rem = pcmbuf_unplayed_bytes;
730 crossfade_chunk = read_chunk->link;
731 crossfade_sample = 0;
733 /* Get fade out info from settings. */
734 fade_out_delay =
735 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
736 fade_out_rem =
737 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
739 crossfade_need = fade_out_delay + fade_out_rem;
740 /* We want only to modify the last part of the buffer, so find
741 * the right chunk and sample to start the crossfade */
742 if (crossfade_rem > crossfade_need)
744 crossfade_sample = find_chunk(crossfade_rem - crossfade_need,
745 &crossfade_chunk);
747 /* Truncate fade out duration if necessary. */
748 else if (crossfade_rem < crossfade_need)
750 size_t crossfade_short = crossfade_need - crossfade_rem;
751 if (fade_out_rem >= crossfade_short)
752 fade_out_rem -= crossfade_short;
753 else
755 fade_out_delay -= crossfade_short - fade_out_rem;
756 fade_out_rem = 0;
760 /* Completely process the crossfade fade-out effect with current PCM buffer */
761 if (!crossfade_mixmode)
763 /* Fade out the specified amount of the already processed audio */
764 size_t total_fade_out = fade_out_rem;
765 size_t fade_out_sample;
766 struct chunkdesc *fade_out_chunk = crossfade_chunk;
768 /* Find the right chunk and sample to start fading out */
769 fade_out_delay += crossfade_sample * 2;
770 fade_out_sample = find_chunk(fade_out_delay, &fade_out_chunk);
772 while (fade_out_rem > 0)
774 /* Each 1/10 second of audio will have the same fade applied */
775 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
776 int factor = (fade_out_rem << 8) / total_fade_out;
778 fade_out_rem -= block_rem;
780 /* Fade this block */
781 while (block_rem > 0 && fade_out_chunk != NULL)
783 /* Fade one sample */
784 int16_t *buf = (int16_t *)fade_out_chunk->addr;
785 int32_t sample = buf[fade_out_sample];
786 buf[fade_out_sample++] = (sample * factor) >> 8;
788 block_rem -= 2;
789 /* Move to the next chunk as needed */
790 if (fade_out_sample * 2 >= fade_out_chunk->size)
792 fade_out_chunk = fade_out_chunk->link;
793 fade_out_sample = 0;
799 /* Initialize fade-in counters */
800 crossfade_fade_in_total =
801 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
802 crossfade_fade_in_rem = crossfade_fade_in_total;
804 fade_in_delay =
805 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
807 /* Find the right chunk and sample to start fading in */
808 fade_in_delay += crossfade_sample * 2;
809 crossfade_sample = find_chunk(fade_in_delay, &crossfade_chunk);
810 logf("crossfade_start done!");
813 /* Returns the number of bytes _NOT_ mixed */
814 static size_t crossfade_mix(int factor, const char *buf, size_t length)
816 const int16_t *input_buf = (const int16_t *)buf;
817 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
818 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
819 output_buf = &output_buf[crossfade_sample];
820 int32_t sample;
822 while (length)
824 /* fade left and right channel at once to keep buffer alignment */
825 int i;
826 for (i = 0; i < 2; i++)
828 sample = *input_buf++;
829 sample = ((sample * factor) >> 8) + *output_buf;
830 *output_buf++ = clip_sample_16(sample);
833 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
835 if (output_buf >= chunk_end)
837 crossfade_chunk = crossfade_chunk->link;
838 if (!crossfade_chunk)
839 return length;
840 output_buf = (int16_t *)crossfade_chunk->addr;
841 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
844 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
845 return 0;
848 /* Perform fade-in of new track */
849 static void write_to_crossfade(char *buf, size_t length)
851 if (length)
853 if (crossfade_fade_in_rem)
855 size_t samples;
856 int16_t *input_buf;
858 /* Fade factor for this packet */
859 int factor =
860 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
861 crossfade_fade_in_total;
862 /* Bytes to fade */
863 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
865 /* We _will_ fade this many bytes */
866 crossfade_fade_in_rem -= fade_rem;
868 if (crossfade_chunk)
870 /* Mix the data */
871 size_t fade_total = fade_rem;
872 fade_rem = crossfade_mix(factor, buf, fade_rem);
873 length -= fade_total - fade_rem;
874 buf += fade_total - fade_rem;
875 if (!length)
876 return;
879 samples = fade_rem / 2;
880 input_buf = (int16_t *)buf;
881 /* Fade remaining samples in place */
882 while (samples--)
884 int32_t sample = *input_buf;
885 *input_buf++ = (sample * factor) >> 8;
889 if (crossfade_chunk)
891 /* Mix the data */
892 size_t mix_total = length;
893 length = crossfade_mix(256, buf, length);
894 buf += mix_total - length;
895 if (!length)
896 return;
899 /* Commit samples to the buffer */
900 while (!prepare_insert(length))
901 sleep(1);
902 while (length > 0)
904 COMMIT_IF_NEEDED;
905 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
906 size_t copy_n = MIN(length, pcmbuf_size - pcmbuffer_index);
907 memcpy(&pcmbuffer[pcmbuffer_index], buf, copy_n);
908 buf += copy_n;
909 pcmbuffer_fillpos += copy_n;
910 length -= copy_n;
913 /* if no more fading-in to do, stop the crossfade */
914 if (!(crossfade_fade_in_rem || crossfade_chunk))
915 crossfade_active = false;
918 static void pcmbuf_finish_crossfade_enable(void)
920 /* Copy the pending setting over now */
921 crossfade_enabled = crossfade_enable_request;
923 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
924 /* If crossfading, try to keep the buffer full other than 1 second */
925 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
926 /* Otherwise, just use the default */
927 PCMBUF_WATERMARK;
930 bool pcmbuf_is_crossfade_active(void)
932 return crossfade_active || crossfade_track_change_started;
935 void pcmbuf_request_crossfade_enable(bool on_off)
937 /* Next setting to be used, not applied now */
938 crossfade_enable_request = on_off;
941 bool pcmbuf_is_same_size(void)
943 /* if pcmbuffer is NULL, then not set up yet even once so always */
944 bool same_size = pcmbuffer ?
945 (get_next_required_pcmbuf_size() == pcmbuf_size) : true;
947 /* no buffer change needed, so finish crossfade setup now */
948 if (same_size)
949 pcmbuf_finish_crossfade_enable();
951 return same_size;
953 #endif /* HAVE_CROSSFADE */
956 /** Voice */
958 /* Returns pcm buffer usage in percents (0 to 100). */
959 static int pcmbuf_usage(void)
961 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
964 static int pcmbuf_mix_free(void)
966 if (mix_chunk)
968 size_t my_mix_end =
969 (size_t)&((int16_t *)mix_chunk->addr)[pcmbuf_mix_sample];
970 size_t my_write_pos = (size_t)&pcmbuffer[pcmbuffer_pos];
971 if (my_write_pos < my_mix_end)
972 my_write_pos += pcmbuf_size;
973 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
975 return 100;
978 void *pcmbuf_request_voice_buffer(int *count)
980 /* A get-it-to-work-for-now hack (audio status could change by
981 completion) */
982 if (audio_status() & AUDIO_STATUS_PLAY)
984 if (read_chunk == NULL)
986 return NULL;
988 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
989 (mix_chunk || read_chunk->link))
991 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
992 return voicebuf;
994 else
996 return NULL;
999 else
1001 return pcmbuf_request_buffer(count);
1005 void pcmbuf_write_voice_complete(int count)
1007 /* A get-it-to-work-for-now hack (audio status could have changed) */
1008 if (!(audio_status() & AUDIO_STATUS_PLAY))
1010 pcmbuf_write_complete(count);
1011 return;
1014 int16_t *ibuf = (int16_t *)voicebuf;
1015 int16_t *obuf;
1016 size_t chunk_samples;
1018 if (mix_chunk == NULL && read_chunk != NULL)
1020 mix_chunk = read_chunk->link;
1021 /* Start 1/8s into the next chunk */
1022 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1025 if (!mix_chunk)
1026 return;
1028 obuf = (int16_t *)mix_chunk->addr;
1029 chunk_samples = mix_chunk->size / sizeof (int16_t);
1031 count <<= 1;
1033 while (count-- > 0)
1035 int32_t sample = *ibuf++;
1037 if (pcmbuf_mix_sample >= chunk_samples)
1039 mix_chunk = mix_chunk->link;
1040 if (!mix_chunk)
1041 return;
1042 pcmbuf_mix_sample = 0;
1043 obuf = mix_chunk->addr;
1044 chunk_samples = mix_chunk->size / 2;
1046 sample += obuf[pcmbuf_mix_sample] >> 2;
1047 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1052 /** Debug menu, other metrics */
1054 /* Amount of bytes left in the buffer. */
1055 size_t pcmbuf_free(void)
1057 if (read_chunk != NULL)
1059 void *read = read_chunk->addr;
1060 void *write = &pcmbuffer[pcmbuffer_pos + pcmbuffer_fillpos];
1061 if (read < write)
1062 return (size_t)(read - write) + pcmbuf_size;
1063 else
1064 return (size_t) (read - write);
1066 return pcmbuf_size - pcmbuffer_fillpos;
1069 size_t pcmbuf_get_bufsize(void)
1071 return pcmbuf_size;
1074 int pcmbuf_used_descs(void)
1076 struct chunkdesc *temp = read_chunk;
1077 unsigned int i = 0;
1078 while (temp) {
1079 temp = temp->link;
1080 i++;
1082 return i;
1085 int pcmbuf_descs(void)
1087 return NUM_CHUNK_DESCS(pcmbuf_size);
1090 #ifdef ROCKBOX_HAS_LOGF
1091 unsigned char *pcmbuf_get_meminfo(size_t *length)
1093 *length = pcmbuf_bufend - pcmbuffer;
1094 return pcmbuffer;
1096 #endif
1099 /** Misc */
1101 bool pcmbuf_is_lowdata(void)
1103 if (!pcm_is_playing() || pcm_is_paused()
1104 #ifdef HAVE_CROSSFADE
1105 || pcmbuf_is_crossfade_active()
1106 #endif
1108 return false;
1110 #if MEMORYSIZE > 2
1111 /* 1 seconds of buffer is low data */
1112 return LOW_DATA(4);
1113 #else
1114 /* under watermark is low data */
1115 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
1116 #endif
1119 void pcmbuf_set_low_latency(bool state)
1121 low_latency_mode = state;
1124 unsigned long pcmbuf_get_latency(void)
1126 /* Be careful how this calculation is rearranged, it's easy to overflow */
1127 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
1128 return bytes / 4 * 1000 / NATIVE_FREQUENCY;
1131 #ifndef HAVE_HARDWARE_BEEP
1132 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
1133 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
1135 /* Generates a constant square wave sound with a given frequency
1136 in Hertz for a duration in milliseconds. */
1137 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
1139 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
1140 int32_t phase = 0;
1141 int16_t *bufptr, *bufstart, *bufend;
1142 int32_t sample;
1143 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
1144 bool mix = read_chunk != NULL && read_chunk->link != NULL;
1145 int i;
1147 bufend = SKIPBYTES((int16_t *)pcmbuffer, pcmbuf_size);
1149 /* Find the insertion point and set bufstart to the start of it */
1150 if (mix)
1152 /* Get the currently playing chunk at the current position. */
1153 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
1155 /* If above isn't implemented or pcm is stopped, no beepeth. */
1156 if (!bufstart || !pcm_is_playing())
1157 return;
1159 /* Give 5ms clearance. */
1160 bufstart += NATIVE_FREQUENCY * 4 / 200;
1162 #ifdef HAVE_PCM_DMA_ADDRESS
1163 /* Returned peak addresses are DMA addresses */
1164 bufend = pcm_dma_addr(bufend);
1165 #endif
1167 /* Wrapped above? */
1168 if (bufstart >= bufend)
1169 bufstart -= pcmbuf_size;
1171 /* NOTE: On some targets using hardware DMA, cache range flushing may
1172 * be required or the writes may not be picked up by the controller.
1173 * An incremental flush should be done periodically during the mixdown. */
1175 else if (nsamples <= MINIBUF_SAMPLES)
1177 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
1178 /* Use mini buffer */
1179 bufstart = minibuf;
1180 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
1182 else if (audio_buffer_state() != AUDIOBUF_STATE_TRASHED)
1184 /* Use pcmbuffer */
1185 bufstart = (int16_t *)pcmbuffer;
1187 else
1189 /* No place */
1190 return;
1193 bufptr = bufstart;
1195 /* Mix square wave into buffer */
1196 for (i = 0; i < nsamples; ++i)
1198 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
1199 sample = mix ? *bufptr : 0;
1200 *bufptr++ = clip_sample_16(sample + amp);
1201 if (bufptr >= bufend)
1202 bufptr = (int16_t *)pcmbuffer;
1203 sample = mix ? *bufptr : 0;
1204 *bufptr++ = clip_sample_16(sample + amp);
1205 if (bufptr >= bufend)
1206 bufptr = (int16_t *)pcmbuffer;
1208 phase += step;
1211 pcm_play_lock();
1212 #ifdef HAVE_RECORDING
1213 pcm_rec_lock();
1214 #endif
1216 /* Kick off playback if required and it won't interfere */
1217 if (!pcm_is_playing()
1218 #ifdef HAVE_RECORDING
1219 && !pcm_is_recording()
1220 #endif
1223 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1226 pcm_play_unlock();
1227 #ifdef HAVE_RECORDING
1228 pcm_rec_unlock();
1229 #endif
1231 #endif /* HAVE_HARDWARE_BEEP */