Add a bunch of markers into the tokens enum to make figuring out which token isnt...
[kugel-rb.git] / apps / pcmbuf.c
blob4a7608fcec03a78f2f1190ad45824f639ee539af
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 "buffer.h"
38 #include "settings.h"
39 #include "audio.h"
40 #include "voice_thread.h"
41 #include "dsp.h"
42 #include "thread.h"
44 #define PCMBUF_TARGET_CHUNK 32768 /* This is the target fill size of chunks
45 on the pcm buffer */
46 #define PCMBUF_MINAVG_CHUNK 24576 /* This is the minimum average size of
47 chunks on the pcm buffer (or we run out
48 of buffer descriptors, which is
49 non-fatal) */
50 #define PCMBUF_MIN_CHUNK 4096 /* We try to never feed a chunk smaller than
51 this to the DMA */
52 #define PCMBUF_MIX_CHUNK 8192 /* This is the maximum size of one packet
53 for mixing (crossfade or voice) */
55 #if MEMORYSIZE > 2
56 /* Keep watermark high for iPods at least (2s) */
57 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
58 #else
59 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 1) /* 0.25 seconds */
60 #endif
62 /* Structure we can use to queue pcm chunks in memory to be played
63 * by the driver code. */
64 struct pcmbufdesc
66 void *addr;
67 size_t size;
68 struct pcmbufdesc* link;
69 /* true if last chunk in the track */
70 bool end_of_track;
73 #define PCMBUF_DESCS(bufsize) \
74 ((bufsize) / PCMBUF_MINAVG_CHUNK)
75 #define PCMBUF_DESCS_SIZE(bufsize) \
76 (PCMBUF_DESCS(bufsize)*sizeof(struct pcmbufdesc))
78 /* Size of the PCM buffer. */
79 static size_t pcmbuf_size IDATA_ATTR = 0;
80 static char *pcmbuf_bufend IDATA_ATTR;
81 static char *audiobuffer IDATA_ATTR;
82 /* Current audio buffer write index. */
83 static size_t audiobuffer_pos IDATA_ATTR;
84 /* Amount audiobuffer_pos will be increased.*/
85 static size_t audiobuffer_fillpos IDATA_ATTR;
86 static char *fadebuf IDATA_ATTR;
87 static char *voicebuf IDATA_ATTR;
89 static bool end_of_track IDATA_ATTR;
90 bool track_transition IDATA_ATTR;
92 /* Crossfade related state */
93 static bool crossfade_enabled;
94 static bool crossfade_enabled_pending;
95 static bool crossfade_mixmode;
96 static bool crossfade_active IDATA_ATTR;
97 static bool crossfade_init IDATA_ATTR;
99 /* Track the current location for processing crossfade */
100 static struct pcmbufdesc *crossfade_chunk IDATA_ATTR;
101 #ifdef HAVE_CROSSFADE
102 static size_t crossfade_sample IDATA_ATTR;
104 /* Counters for fading in new data */
105 static size_t crossfade_fade_in_total IDATA_ATTR;
106 static size_t crossfade_fade_in_rem IDATA_ATTR;
107 #endif
109 static struct pcmbufdesc *pcmbuf_read IDATA_ATTR;
110 static struct pcmbufdesc *pcmbuf_read_end IDATA_ATTR;
111 static struct pcmbufdesc *pcmbuf_write IDATA_ATTR;
112 static struct pcmbufdesc *pcmbuf_write_end IDATA_ATTR;
113 static size_t last_chunksize IDATA_ATTR;
115 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
116 static size_t pcmbuf_watermark IDATA_ATTR;
118 static struct pcmbufdesc *pcmbuf_mix_chunk IDATA_ATTR;
119 static size_t pcmbuf_mix_sample IDATA_ATTR;
121 static bool low_latency_mode = false;
122 static bool pcmbuf_flush;
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 NEED_FLUSH(position) \
133 (audiobuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
134 #define LOW_DATA(quarter_secs) \
135 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
137 static void pcmbuf_finish_track_change(void);
138 #ifdef HAVE_CROSSFADE
139 static void crossfade_start(void);
140 static void flush_crossfade(char *buf, size_t length);
141 #endif
142 static bool pcmbuf_crossfade_init(bool manual_skip);
143 static void pcmbuf_finish_crossfade_enable(void);
144 static bool pcmbuf_is_crossfade_enabled(void);
147 /**************************************/
149 /* define this to show detailed pcmbufdesc usage information on the sim console */
150 /*#define DESC_DEBUG*/
152 #ifndef SIMULATOR
153 #undef DESC_DEBUG
154 #endif
155 #ifdef DESC_DEBUG
156 static struct pcmbufdesc *first_desc;
157 static bool show_desc_in_use = false;
158 #define DISPLAY_DESC(caller) while(!show_desc(caller))
159 #define DESC_IDX(desc) (desc ? desc - first_desc : -1)
160 #define DESCL_IDX(desc) (desc && desc->link ? desc->link - first_desc : -1)
161 #define SHOW_1ST(desc) if(DESC_IDX (desc)==-1) DEBUGF(" -- "); \
162 else DEBUGF(" %02d ", DESC_IDX(desc))
163 #define SHOW_2ND(desc) if(DESCL_IDX(desc)==-1) DEBUGF("l -- "); \
164 else DEBUGF("l %02d ", DESCL_IDX(desc))
165 #define DESC_SHOW(tag, desc) DEBUGF(tag);SHOW_1ST(desc); \
166 DEBUGF(tag);SHOW_2ND(desc)
168 static bool show_desc(char *caller)
170 if (show_desc_in_use) return false;
171 show_desc_in_use = true;
172 DEBUGF("%-14s\t", caller);
173 DESC_SHOW("r", pcmbuf_read);
174 DESC_SHOW("re", pcmbuf_read_end);
175 DEBUGF(" ");
176 DESC_SHOW("w", pcmbuf_write);
177 DESC_SHOW("we", pcmbuf_write_end);
178 DEBUGF("\n");
179 show_desc_in_use = false;
180 return true;
182 #else
183 #define DISPLAY_DESC(caller) do{}while(0)
184 #endif
187 /* Commit PCM data */
189 #ifdef HAVE_PRIORITY_SCHEDULING
190 static void boost_codec_thread(bool boost)
192 /* Keep voice and codec threads at the same priority or else voice
193 * will starve if the codec thread's priority is boosted. */
194 if (boost)
196 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
197 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
199 if (priority != codec_thread_priority)
201 codec_thread_priority = priority;
202 thread_set_priority(codec_thread_id, priority);
203 voice_thread_set_priority(priority);
206 else if (codec_thread_priority != PRIORITY_PLAYBACK)
208 thread_set_priority(codec_thread_id, PRIORITY_PLAYBACK);
209 voice_thread_set_priority(PRIORITY_PLAYBACK);
210 codec_thread_priority = PRIORITY_PLAYBACK;
213 #endif /* HAVE_PRIORITY_SCHEDULING */
215 static void pcmbuf_under_watermark(bool under)
217 /* Only codec thread initiates boost - voice boosts the cpu when playing
218 a clip */
219 #ifndef SIMULATOR
220 if (thread_get_current() == codec_thread_id)
221 #endif /* SIMULATOR */
223 if (under)
225 /* Fill audio buffer by boosting cpu */
226 trigger_cpu_boost();
227 #ifdef HAVE_PRIORITY_SCHEDULING
228 /* If buffer is critically low, override UI priority, else
229 set back to the original priority. */
230 boost_codec_thread(LOW_DATA(2) && pcm_is_playing());
231 #endif
233 else
235 #ifdef HAVE_PRIORITY_SCHEDULING
236 boost_codec_thread(false);
237 #endif
241 /* Disable crossfade if < .5s of audio */
242 if (LOW_DATA(2))
244 crossfade_active = false;
248 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
249 * in a separate function for the moment */
250 static inline void pcmbuf_add_chunk(void)
252 register size_t size = audiobuffer_fillpos;
253 /* Grab the next description to write, and change the write pointer */
254 register struct pcmbufdesc *pcmbuf_current = pcmbuf_write;
255 pcmbuf_write = pcmbuf_current->link;
256 /* Fill in the values in the new buffer chunk */
257 pcmbuf_current->addr = &audiobuffer[audiobuffer_pos];
258 pcmbuf_current->size = size;
259 pcmbuf_current->end_of_track = end_of_track;
260 pcmbuf_current->link = NULL;
261 end_of_track = false; /* This is single use only */
262 if (pcmbuf_read != NULL) {
263 if (pcmbuf_flush)
265 pcmbuf_write_end->link = pcmbuf_read->link;
266 pcmbuf_read->link = pcmbuf_current;
267 while (pcmbuf_write_end->link)
269 pcmbuf_write_end = pcmbuf_write_end->link;
270 pcmbuf_unplayed_bytes -= pcmbuf_write_end->size;
272 pcmbuf_flush = false;
274 /* If there is already a read buffer setup, add to it */
275 else
276 pcmbuf_read_end->link = pcmbuf_current;
277 } else {
278 /* Otherwise create the buffer */
279 pcmbuf_read = pcmbuf_current;
281 /* This is now the last buffer to read */
282 pcmbuf_read_end = pcmbuf_current;
284 /* Update bytes counters */
285 pcmbuf_unplayed_bytes += size;
287 audiobuffer_pos += size;
288 if (audiobuffer_pos >= pcmbuf_size)
289 audiobuffer_pos -= pcmbuf_size;
291 audiobuffer_fillpos = 0;
292 DISPLAY_DESC("add_chunk");
296 * Commit samples waiting to the pcm buffer.
298 static bool pcmbuf_flush_fillpos(void)
300 if (audiobuffer_fillpos) {
301 /* Never use the last buffer descriptor */
302 while (pcmbuf_write == pcmbuf_write_end) {
303 /* If this happens, something is being stupid */
304 if (!pcm_is_playing()) {
305 logf("pcmbuf_flush_fillpos error");
306 pcmbuf_play_start();
308 /* Let approximately one chunk of data playback */
309 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
311 pcmbuf_add_chunk();
312 return true;
314 return false;
317 static bool prepare_insert(size_t length)
319 if (low_latency_mode)
321 /* 1/4s latency. */
322 if (!LOW_DATA(1) && pcm_is_playing())
323 return false;
326 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
327 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
328 return false;
330 if (!pcm_is_playing())
332 trigger_cpu_boost();
334 /* Pre-buffer up to watermark */
335 #if MEMORYSIZE > 2
336 if (!LOW_DATA(4))
337 #else
338 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
339 #endif
341 logf("pcm starting");
342 if (!(audio_status() & AUDIO_STATUS_PAUSE))
343 pcmbuf_play_start();
346 else
347 pcmbuf_under_watermark(pcmbuf_unplayed_bytes <= pcmbuf_watermark);
349 return true;
352 void *pcmbuf_request_buffer(int *count)
354 #ifdef HAVE_CROSSFADE
355 if (crossfade_init)
356 crossfade_start();
357 #endif
359 if (crossfade_active) {
360 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
361 return fadebuf;
363 else
365 if(prepare_insert(*count << 2))
367 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
368 if (pcmbuf_size - audiobuffer_index >= PCMBUF_MIN_CHUNK)
370 /* Usual case, there's space here */
371 return &audiobuffer[audiobuffer_index];
373 else
375 /* Flush and wrap the buffer */
376 pcmbuf_flush_fillpos();
377 audiobuffer_pos = 0;
378 return &audiobuffer[0];
381 else
383 return NULL;
388 void pcmbuf_write_complete(int count)
390 size_t length = (size_t)(unsigned int)count << 2;
391 #ifdef HAVE_CROSSFADE
392 if (crossfade_active)
394 flush_crossfade(fadebuf, length);
395 if (!(crossfade_fade_in_rem || crossfade_chunk))
396 crossfade_active = false;
398 else
399 #endif
401 audiobuffer_fillpos += length;
403 if (NEED_FLUSH(audiobuffer_pos + audiobuffer_fillpos))
404 pcmbuf_flush_fillpos();
409 /* Init */
411 static void pcmbuf_init_pcmbuffers(void)
413 #ifdef DESC_DEBUG
414 first_desc = pcmbuf_write;
415 #endif
416 struct pcmbufdesc *next = pcmbuf_write;
417 next++;
418 pcmbuf_write_end = pcmbuf_write;
419 while ((void *)next < (void *)pcmbuf_bufend) {
420 pcmbuf_write_end->link=next;
421 pcmbuf_write_end=next;
422 next++;
424 DISPLAY_DESC("init");
427 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
429 size_t seconds = 1;
431 if (crossfade_enabled_pending)
432 seconds += global_settings.crossfade_fade_out_delay
433 + global_settings.crossfade_fade_out_duration;
435 #if MEMORYSIZE > 2
436 /* Buffer has to be at least 2s long. */
437 seconds += 2;
438 #endif
439 logf("pcmbuf len: %ld", (long)seconds);
440 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
443 static char *pcmbuf_calc_audiobuffer_ptr(size_t bufsize)
445 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
446 PCMBUF_DESCS_SIZE(bufsize));
449 /* Initialize the pcmbuffer the structure looks like this:
450 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
451 size_t pcmbuf_init(unsigned char *bufend)
453 pcmbuf_bufend = bufend;
454 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
455 audiobuffer = pcmbuf_calc_audiobuffer_ptr(pcmbuf_size);
456 fadebuf = &audiobuffer[pcmbuf_size];
457 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
458 pcmbuf_write = (struct pcmbufdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
460 pcmbuf_init_pcmbuffers();
462 if(track_transition){logf("pcmbuf: (init) track transition false");}
463 end_of_track = false;
464 track_transition = false;
466 pcmbuf_finish_crossfade_enable();
468 pcmbuf_play_stop();
470 return pcmbuf_bufend - audiobuffer;
474 /* Playback */
476 /** PCM driver callback
477 * This function has 3 major logical parts (separated by brackets both for
478 * readability and variable scoping). The first part performs the
479 * operations related to finishing off the last buffer we fed to the DMA.
480 * The second part detects the end of playlist condition when the pcm
481 * buffer is empty except for uncommitted samples. Then they are committed.
482 * The third part performs the operations involved in sending a new buffer
483 * to the DMA. */
484 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size) ICODE_ATTR;
485 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size)
488 struct pcmbufdesc *pcmbuf_current = pcmbuf_read;
489 /* Take the finished buffer out of circulation */
490 pcmbuf_read = pcmbuf_current->link;
492 /* if during a track transition, update the elapsed time */
493 if (track_transition)
494 audio_pcmbuf_position_callback(last_chunksize);
496 /* if last buffer in the track, let the audio thread know */
497 if (pcmbuf_current->end_of_track)
498 pcmbuf_finish_track_change();
500 /* Put the finished buffer back into circulation */
501 pcmbuf_write_end->link = pcmbuf_current;
502 pcmbuf_write_end = pcmbuf_current;
504 /* If we've read over the mix chunk while it's still mixing there */
505 if (pcmbuf_current == pcmbuf_mix_chunk)
506 pcmbuf_mix_chunk = NULL;
507 /* If we've read over the crossfade chunk while it's still fading */
508 if (pcmbuf_current == crossfade_chunk)
509 crossfade_chunk = pcmbuf_read;
513 /* Commit last samples at end of playlist */
514 if (audiobuffer_fillpos && !pcmbuf_read)
516 logf("pcmbuf_pcm_callback: commit last samples");
517 pcmbuf_flush_fillpos();
522 /* Send the new buffer to the pcm */
523 struct pcmbufdesc *pcmbuf_new = pcmbuf_read;
524 size_t *realsize = size;
525 unsigned char** realstart = start;
526 if(pcmbuf_new)
528 size_t current_size = pcmbuf_new->size;
530 pcmbuf_unplayed_bytes -= current_size;
531 last_chunksize = current_size;
532 *realsize = current_size;
533 *realstart = pcmbuf_new->addr;
535 else
537 /* No more buffers */
538 last_chunksize = 0;
539 *realsize = 0;
540 *realstart = NULL;
541 if (end_of_track)
542 pcmbuf_finish_track_change();
545 DISPLAY_DESC("callback");
548 /* Force playback. */
549 void pcmbuf_play_start(void)
551 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && pcmbuf_read != NULL)
553 last_chunksize = pcmbuf_read->size;
554 pcmbuf_unplayed_bytes -= last_chunksize;
555 pcm_play_data(pcmbuf_pcm_callback,
556 (unsigned char *)pcmbuf_read->addr, last_chunksize);
560 void pcmbuf_play_stop(void)
562 pcm_play_stop();
564 pcmbuf_unplayed_bytes = 0;
565 pcmbuf_mix_chunk = NULL;
566 if (pcmbuf_read) {
567 pcmbuf_write_end->link = pcmbuf_read;
568 pcmbuf_write_end = pcmbuf_read_end;
569 pcmbuf_read = pcmbuf_read_end = NULL;
571 audiobuffer_pos = 0;
572 audiobuffer_fillpos = 0;
573 crossfade_init = false;
574 crossfade_active = false;
575 pcmbuf_flush = false;
576 DISPLAY_DESC("play_stop");
578 #ifdef HAVE_PRIORITY_SCHEDULING
579 /* Can unboost the codec thread here no matter who's calling */
580 boost_codec_thread(false);
581 #endif
584 void pcmbuf_pause(bool pause)
586 if (pcm_is_playing())
587 pcm_play_pause(!pause);
588 else if (!pause)
589 pcmbuf_play_start();
593 /* Track change */
595 /* The codec is moving on to the next track, but the current track is
596 * still playing. Set flags to make sure the elapsed time of the current
597 * track is updated properly, and mark the currently written chunk as the
598 * last one in the track. */
599 static void pcmbuf_gapless_track_change(void)
601 /* we're starting a track transition */
602 track_transition = true;
604 /* mark the last chunk in the track */
605 end_of_track = true;
608 static void pcmbuf_crossfade_track_change(void)
610 /* Initiate automatic crossfade mode */
611 pcmbuf_crossfade_init(false);
612 /* Notify the wps that the track change starts now */
613 audio_post_track_change(false);
616 void pcmbuf_start_track_change(bool manual_skip)
618 /* Manual track change (always crossfade or flush audio). */
619 if (manual_skip)
621 pcmbuf_crossfade_init(true);
622 audio_post_track_change(false);
624 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
625 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
626 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
628 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
630 if (global_settings.playlist_shuffle)
631 /* shuffle mode is on, so crossfade: */
632 pcmbuf_crossfade_track_change();
633 else
634 /* shuffle mode is off, so normal gapless playback */
635 pcmbuf_gapless_track_change();
637 else
638 /* normal crossfade: */
639 pcmbuf_crossfade_track_change();
641 else
642 /* normal gapless playback. */
643 pcmbuf_gapless_track_change();
646 /* Called when the last chunk in the track has been played */
647 static void pcmbuf_finish_track_change(void)
649 /* not in a track transition anymore */
650 if(track_transition){logf("pcmbuf: (finish change) track transition false");}
651 track_transition = false;
653 /* notify playback that the track has just finished */
654 audio_post_track_change(true);
658 /* Crossfade */
660 /* Clip sample to signed 16 bit range */
661 static inline int32_t clip_sample_16(int32_t sample)
663 if ((int16_t)sample != sample)
664 sample = 0x7fff ^ (sample >> 31);
665 return sample;
668 /**
669 * Low memory targets don't have crossfade, so don't compile crossfade
670 * specific code in order to save some memory. */
672 #ifdef HAVE_CROSSFADE
674 * Completely process the crossfade fade out effect with current pcm buffer.
676 static void crossfade_process_buffer(size_t fade_in_delay,
677 size_t fade_out_delay, size_t fade_out_rem)
679 if (!crossfade_mixmode)
681 /* Fade out the specified amount of the already processed audio */
682 size_t total_fade_out = fade_out_rem;
683 size_t fade_out_sample;
684 struct pcmbufdesc *fade_out_chunk = crossfade_chunk;
686 /* Find the right chunk to start fading out */
687 fade_out_delay += crossfade_sample * 2;
688 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
690 fade_out_delay -= fade_out_chunk->size;
691 fade_out_chunk = fade_out_chunk->link;
693 /* The start sample within the chunk */
694 fade_out_sample = fade_out_delay / 2;
696 while (fade_out_rem > 0)
698 /* Each 1/10 second of audio will have the same fade applied */
699 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
700 int factor = (fade_out_rem << 8) / total_fade_out;
702 fade_out_rem -= block_rem;
704 /* Fade this block */
705 while (block_rem > 0 && fade_out_chunk != NULL)
707 /* Fade one sample */
708 int16_t *buf = (int16_t *)fade_out_chunk->addr;
709 int32_t sample = buf[fade_out_sample];
710 buf[fade_out_sample++] = (sample * factor) >> 8;
712 block_rem -= 2;
713 /* Move to the next chunk as needed */
714 if (fade_out_sample * 2 >= fade_out_chunk->size)
716 fade_out_chunk = fade_out_chunk->link;
717 fade_out_sample = 0;
723 /* Find the right chunk and sample to start fading in */
724 fade_in_delay += crossfade_sample * 2;
725 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
727 fade_in_delay -= crossfade_chunk->size;
728 crossfade_chunk = crossfade_chunk->link;
730 crossfade_sample = fade_in_delay / 2;
731 logf("process done!");
734 /* Initializes crossfader, calculates all necessary parameters and
735 * performs fade-out with the pcm buffer. */
736 static void crossfade_start(void)
738 size_t crossfade_rem;
739 size_t crossfade_need;
740 size_t fade_out_rem;
741 size_t fade_out_delay;
742 size_t fade_in_delay;
744 crossfade_init = false;
745 /* Reject crossfade if less than .5s of data */
746 if (LOW_DATA(2)) {
747 logf("crossfade rejected");
748 pcmbuf_play_stop();
749 return ;
752 logf("crossfade_start");
753 pcmbuf_flush_fillpos();
754 crossfade_active = true;
756 /* Initialize the crossfade buffer size to all of the buffered data that
757 * has not yet been sent to the DMA */
758 crossfade_rem = pcmbuf_unplayed_bytes;
759 crossfade_chunk = pcmbuf_read->link;
760 crossfade_sample = 0;
762 /* Get fade out delay from settings. */
763 fade_out_delay =
764 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
766 /* Get fade out duration from settings. */
767 fade_out_rem =
768 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
770 crossfade_need = fade_out_delay + fade_out_rem;
771 /* We want only to modify the last part of the buffer. */
772 if (crossfade_rem > crossfade_need)
774 size_t crossfade_extra = crossfade_rem - crossfade_need;
775 while (crossfade_extra > crossfade_chunk->size)
777 crossfade_extra -= crossfade_chunk->size;
778 crossfade_chunk = crossfade_chunk->link;
780 crossfade_sample = crossfade_extra / 2;
782 /* Truncate fade out duration if necessary. */
783 else if (crossfade_rem < crossfade_need)
785 size_t crossfade_short = crossfade_need - crossfade_rem;
786 if (fade_out_rem >= crossfade_short)
787 fade_out_rem -= crossfade_short;
788 else
790 fade_out_delay -= crossfade_short - fade_out_rem;
791 fade_out_rem = 0;
795 /* Get also fade in duration and delays from settings. */
796 crossfade_fade_in_total =
797 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
798 crossfade_fade_in_rem = crossfade_fade_in_total;
800 fade_in_delay =
801 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
803 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
806 /* Returns the number of bytes _NOT_ mixed */
807 static size_t crossfade_mix(int factor, const char *buf, size_t length)
809 const int16_t *input_buf = (const int16_t *)buf;
810 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
811 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
812 output_buf = &output_buf[crossfade_sample];
813 int32_t sample;
815 while (length)
817 /* fade left and right channel at once to keep buffer alignment */
818 int i;
819 for (i = 0; i < 2; i++)
821 sample = *input_buf++;
822 sample = ((sample * factor) >> 8) + *output_buf;
823 *output_buf++ = clip_sample_16(sample);
826 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
828 if (output_buf >= chunk_end)
830 crossfade_chunk = crossfade_chunk->link;
831 if (!crossfade_chunk)
832 return length;
833 output_buf = (int16_t *)crossfade_chunk->addr;
834 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
837 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
838 return 0;
841 static void flush_crossfade(char *buf, size_t length)
843 if (length)
845 if (crossfade_fade_in_rem)
847 size_t samples;
848 int16_t *input_buf;
850 /* Fade factor for this packet */
851 int factor =
852 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
853 crossfade_fade_in_total;
854 /* Bytes to fade */
855 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
857 /* We _will_ fade this many bytes */
858 crossfade_fade_in_rem -= fade_rem;
860 if (crossfade_chunk)
862 /* Mix the data */
863 size_t fade_total = fade_rem;
864 fade_rem = crossfade_mix(factor, buf, fade_rem);
865 length -= fade_total - fade_rem;
866 buf += fade_total - fade_rem;
867 if (!length)
868 return;
871 samples = fade_rem / 2;
872 input_buf = (int16_t *)buf;
873 /* Fade remaining samples in place */
874 while (samples--)
876 int32_t sample = *input_buf;
877 *input_buf++ = (sample * factor) >> 8;
881 if (crossfade_chunk)
883 /* Mix the data */
884 size_t mix_total = length;
885 length = crossfade_mix(256, buf, length);
886 buf += mix_total - length;
887 if (!length)
888 return;
891 /* Flush samples to the buffer */
892 while (!prepare_insert(length))
893 sleep(1);
894 while (length > 0)
896 size_t audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
897 if (NEED_FLUSH(audiobuffer_index))
899 pcmbuf_flush_fillpos();
900 audiobuffer_index = audiobuffer_pos + audiobuffer_fillpos;
902 size_t copy_n = MIN(length, pcmbuf_size - audiobuffer_index);
903 memcpy(&audiobuffer[audiobuffer_index], buf, copy_n);
904 buf += copy_n;
905 audiobuffer_fillpos += copy_n;
906 length -= copy_n;
910 #endif /* HAVE_CROSSFADE */
912 static bool pcmbuf_crossfade_init(bool manual_skip)
914 /* Can't do two crossfades at once and, no fade if pcm is off now */
915 if (crossfade_init || crossfade_active || !pcm_is_playing())
917 pcmbuf_play_stop();
918 return false;
921 trigger_cpu_boost();
923 /* Not enough data, or crossfade disabled, flush the old data instead */
924 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
926 pcmbuf_flush_fillpos();
927 pcmbuf_flush = true;
928 return false;
931 /* Don't enable mix mode when skipping tracks manually. */
932 if (manual_skip)
933 crossfade_mixmode = false;
934 else
935 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
937 crossfade_init = true;
939 return true;
943 static void pcmbuf_finish_crossfade_enable(void)
945 /* Copy the pending setting over now */
946 crossfade_enabled = crossfade_enabled_pending;
948 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
949 /* If crossfading, try to keep the buffer full other than 1 second */
950 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
951 /* Otherwise, just use the default */
952 PCMBUF_WATERMARK;
955 static bool pcmbuf_is_crossfade_enabled(void)
957 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
958 return global_settings.playlist_shuffle;
960 return crossfade_enabled;
963 bool pcmbuf_is_crossfade_active(void)
965 return crossfade_active || crossfade_init;
968 void pcmbuf_request_crossfade_enable(bool on_off)
970 /* Next setting to be used, not applied now */
971 crossfade_enabled_pending = on_off;
974 bool pcmbuf_is_same_size(void)
976 bool same_size;
978 if (audiobuffer == NULL)
979 same_size = true; /* Not set up yet even once so always */
980 else
982 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
983 same_size = pcmbuf_calc_audiobuffer_ptr(bufsize) == audiobuffer;
986 if (same_size)
987 pcmbuf_finish_crossfade_enable();
989 return same_size;
993 /* Voice */
995 /* Returns pcm buffer usage in percents (0 to 100). */
996 static int pcmbuf_usage(void)
998 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
1001 static int pcmbuf_mix_free(void)
1003 if (pcmbuf_mix_chunk)
1005 size_t my_mix_end =
1006 (size_t)&((int16_t *)pcmbuf_mix_chunk->addr)[pcmbuf_mix_sample];
1007 size_t my_write_pos = (size_t)&audiobuffer[audiobuffer_pos];
1008 if (my_write_pos < my_mix_end)
1009 my_write_pos += pcmbuf_size;
1010 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1012 return 100;
1015 void *pcmbuf_request_voice_buffer(int *count)
1017 /* A get-it-to-work-for-now hack (audio status could change by
1018 completion) */
1019 if (audio_status() & AUDIO_STATUS_PLAY)
1021 if (pcmbuf_read == NULL)
1023 return NULL;
1025 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
1026 (pcmbuf_mix_chunk || pcmbuf_read->link))
1028 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
1029 return voicebuf;
1031 else
1033 return NULL;
1036 else
1038 return pcmbuf_request_buffer(count);
1042 void pcmbuf_write_voice_complete(int count)
1044 /* A get-it-to-work-for-now hack (audio status could have changed) */
1045 if (!(audio_status() & AUDIO_STATUS_PLAY))
1047 pcmbuf_write_complete(count);
1048 return;
1051 int16_t *ibuf = (int16_t *)voicebuf;
1052 int16_t *obuf;
1053 size_t chunk_samples;
1055 if (pcmbuf_mix_chunk == NULL && pcmbuf_read != NULL)
1057 pcmbuf_mix_chunk = pcmbuf_read->link;
1058 /* Start 1/8s into the next chunk */
1059 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1062 if (!pcmbuf_mix_chunk)
1063 return;
1065 obuf = (int16_t *)pcmbuf_mix_chunk->addr;
1066 chunk_samples = pcmbuf_mix_chunk->size / sizeof (int16_t);
1068 count <<= 1;
1070 while (count-- > 0)
1072 int32_t sample = *ibuf++;
1074 if (pcmbuf_mix_sample >= chunk_samples)
1076 pcmbuf_mix_chunk = pcmbuf_mix_chunk->link;
1077 if (!pcmbuf_mix_chunk)
1078 return;
1079 pcmbuf_mix_sample = 0;
1080 obuf = pcmbuf_mix_chunk->addr;
1081 chunk_samples = pcmbuf_mix_chunk->size / 2;
1083 sample += obuf[pcmbuf_mix_sample] >> 2;
1084 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1089 /* Debug menu, other metrics */
1091 /* Amount of bytes left in the buffer. */
1092 size_t pcmbuf_free(void)
1094 if (pcmbuf_read != NULL)
1096 void *read = pcmbuf_read->addr;
1097 void *write = &audiobuffer[audiobuffer_pos + audiobuffer_fillpos];
1098 if (read < write)
1099 return (size_t)(read - write) + pcmbuf_size;
1100 else
1101 return (size_t) (read - write);
1103 return pcmbuf_size;
1106 size_t pcmbuf_get_bufsize(void)
1108 return pcmbuf_size;
1111 int pcmbuf_used_descs(void)
1113 struct pcmbufdesc *pcmbuf_temp = pcmbuf_read;
1114 unsigned int i = 0;
1115 while (pcmbuf_temp) {
1116 pcmbuf_temp = pcmbuf_temp->link;
1117 i++;
1119 return i;
1122 int pcmbuf_descs(void)
1124 return PCMBUF_DESCS(pcmbuf_size);
1127 #ifdef ROCKBOX_HAS_LOGF
1128 unsigned char * pcmbuf_get_meminfo(size_t *length)
1130 *length = pcmbuf_bufend - audiobuffer;
1131 return audiobuffer;
1133 #endif
1136 /* Misc */
1138 bool pcmbuf_is_lowdata(void)
1140 if (!pcm_is_playing() || pcm_is_paused() ||
1141 crossfade_init || crossfade_active)
1142 return false;
1144 #if MEMORYSIZE > 2
1145 /* 1 seconds of buffer is low data */
1146 return LOW_DATA(4);
1147 #else
1148 /* under watermark is low data */
1149 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
1150 #endif
1153 void pcmbuf_set_low_latency(bool state)
1155 low_latency_mode = state;
1158 unsigned long pcmbuf_get_latency(void)
1160 /* Be careful how this calculation is rearranged, it's easy to overflow */
1161 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
1162 return bytes / 4 * 1000 / NATIVE_FREQUENCY;
1165 #ifndef HAVE_HARDWARE_BEEP
1166 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
1167 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
1169 /* Generates a constant square wave sound with a given frequency
1170 in Hertz for a duration in milliseconds. */
1171 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
1173 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
1174 int32_t phase = 0;
1175 int16_t *bufptr, *bufstart, *bufend;
1176 int32_t sample;
1177 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
1178 bool mix = pcmbuf_read != NULL && pcmbuf_read->link != NULL;
1179 int i;
1181 bufend = SKIPBYTES((int16_t *)audiobuffer, pcmbuf_size);
1183 /* Find the insertion point and set bufstart to the start of it */
1184 if (mix)
1186 /* Get the currently playing chunk at the current position. */
1187 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
1189 /* If above isn't implemented or pcm is stopped, no beepeth. */
1190 if (!bufstart || !pcm_is_playing())
1191 return;
1193 /* Give 5ms clearance. */
1194 bufstart += NATIVE_FREQUENCY * 4 / 200;
1196 #ifdef HAVE_PCM_DMA_ADDRESS
1197 /* Returned peak addresses are DMA addresses */
1198 bufend = pcm_dma_addr(bufend);
1199 #endif
1201 /* Wrapped above? */
1202 if (bufstart >= bufend)
1203 bufstart -= pcmbuf_size;
1205 /* NOTE: On some targets using hardware DMA, cache range flushing may
1206 * be required or the writes may not be picked up by the controller.
1207 * An incremental flush should be done periodically during the mixdown. */
1209 else if (nsamples <= MINIBUF_SAMPLES)
1211 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
1212 /* Use mini buffer */
1213 bufstart = minibuf;
1214 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
1216 else if (audio_buffer_state() != AUDIOBUF_STATE_TRASHED)
1218 /* Use audiobuffer */
1219 bufstart = (int16_t *)audiobuffer;
1221 else
1223 /* No place */
1224 return;
1227 bufptr = bufstart;
1229 /* Mix square wave into buffer */
1230 for (i = 0; i < nsamples; ++i)
1232 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
1233 sample = mix ? *bufptr : 0;
1234 *bufptr++ = clip_sample_16(sample + amp);
1235 if (bufptr >= bufend)
1236 bufptr = (int16_t *)audiobuffer;
1237 sample = mix ? *bufptr : 0;
1238 *bufptr++ = clip_sample_16(sample + amp);
1239 if (bufptr >= bufend)
1240 bufptr = (int16_t *)audiobuffer;
1242 phase += step;
1245 pcm_play_lock();
1246 #ifdef HAVE_RECORDING
1247 pcm_rec_lock();
1248 #endif
1250 /* Kick off playback if required and it won't interfere */
1251 if (!pcm_is_playing()
1252 #ifdef HAVE_RECORDING
1253 && !pcm_is_recording()
1254 #endif
1257 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1260 pcm_play_unlock();
1261 #ifdef HAVE_RECORDING
1262 pcm_rec_unlock();
1263 #endif
1265 #endif /* HAVE_HARDWARE_BEEP */