pcmbuf: refactoring, renamed confusing variables, moved some code around, but still...
[kugel-rb.git] / apps / pcmbuf.c
blobf1fee3745240065b807a81dbdfca77cba5012983
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 "dsp.h"
41 #define PCMBUF_TARGET_CHUNK 32768 /* This is the target fill size of chunks
42 on the pcm buffer */
43 #define PCMBUF_MINAVG_CHUNK 24576 /* This is the minimum average size of
44 chunks on the pcm buffer (or we run out
45 of buffer descriptors, which is
46 non-fatal) */
47 #define PCMBUF_MIN_CHUNK 4096 /* We try to never feed a chunk smaller than
48 this to the DMA */
49 #define PCMBUF_MIX_CHUNK 8192 /* This is the maximum size of one packet
50 for mixing (crossfade or voice) */
52 #if MEMORYSIZE > 2
53 /* Keep watermark high for iPods at least (2s) */
54 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 4 * 2)
55 #else
56 #define PCMBUF_WATERMARK (NATIVE_FREQUENCY * 1) /* 0.25 seconds */
57 #endif
59 /* Structure we can use to queue pcm chunks in memory to be played
60 * by the driver code. */
61 struct chunkdesc
63 void *addr;
64 size_t size;
65 struct chunkdesc* link;
66 /* true if last chunk in the track */
67 bool end_of_track;
70 #define CHUNK_DESCS(bufsize) \
71 ((bufsize) / PCMBUF_MINAVG_CHUNK)
72 #define CHUNK_DESCS_SIZE(bufsize) \
73 (CHUNK_DESCS(bufsize)*sizeof(struct chunkdesc))
75 /* Size of the PCM buffer. */
76 static size_t pcmbuf_size IDATA_ATTR = 0;
77 static char *pcmbuf_bufend IDATA_ATTR;
78 static char *pcmbuffer IDATA_ATTR;
79 /* Current PCM buffer write index. */
80 static size_t pcmbuffer_pos IDATA_ATTR;
81 /* Amount pcmbuffer_pos will be increased.*/
82 static size_t pcmbuffer_fillpos IDATA_ATTR;
83 static char *fadebuf IDATA_ATTR;
84 static char *voicebuf IDATA_ATTR;
86 static bool end_of_track IDATA_ATTR;
87 bool track_transition IDATA_ATTR;
89 /* Crossfade related state */
90 static bool crossfade_enabled;
91 static bool crossfade_enable_request;
92 static bool crossfade_mixmode;
93 static bool crossfade_active IDATA_ATTR;
94 static bool crossfade_init IDATA_ATTR;
96 /* Track the current location for processing crossfade */
97 static struct chunkdesc *crossfade_chunk IDATA_ATTR;
98 #ifdef HAVE_CROSSFADE
99 static size_t crossfade_sample IDATA_ATTR;
101 /* Counters for fading in new data */
102 static size_t crossfade_fade_in_total IDATA_ATTR;
103 static size_t crossfade_fade_in_rem IDATA_ATTR;
104 #endif
106 static struct chunkdesc *read_chunk IDATA_ATTR;
107 static struct chunkdesc *read_end_chunk IDATA_ATTR;
108 static struct chunkdesc *write_chunk IDATA_ATTR;
109 static struct chunkdesc *write_end_chunk IDATA_ATTR;
110 static size_t last_chunksize IDATA_ATTR;
112 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
113 static size_t pcmbuf_watermark IDATA_ATTR;
115 static struct chunkdesc *mix_chunk IDATA_ATTR;
116 static size_t pcmbuf_mix_sample IDATA_ATTR;
118 static bool low_latency_mode = false;
119 static bool pcmbuf_flush;
121 #ifdef HAVE_PRIORITY_SCHEDULING
122 static int codec_thread_priority = PRIORITY_PLAYBACK;
123 #endif
125 extern unsigned int codec_thread_id;
127 /* Helpful macros for use in conditionals this assumes some of the above
128 * static variable names */
129 #define NEED_FLUSH(position) \
130 (pcmbuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
131 #define LOW_DATA(quarter_secs) \
132 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
134 static void pcmbuf_finish_track_change(void);
135 #ifdef HAVE_CROSSFADE
136 static void crossfade_start(void);
137 static void flush_crossfade(char *buf, size_t length);
138 #endif
139 static bool pcmbuf_crossfade_init(bool manual_skip);
140 static void pcmbuf_finish_crossfade_enable(void);
141 static bool pcmbuf_is_crossfade_enabled(void);
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 /* Commit PCM data */
186 /* This is really just part of pcmbuf_flush_fillpos, but is easier to keep
187 * in a separate function for the moment */
188 static inline void pcmbuf_add_chunk(void)
190 register size_t size = pcmbuffer_fillpos;
191 /* Grab the next description to write, and change the write pointer */
192 register struct chunkdesc *pcmbuf_current = write_chunk;
193 write_chunk = pcmbuf_current->link;
194 /* Fill in the values in the new buffer chunk */
195 pcmbuf_current->addr = &pcmbuffer[pcmbuffer_pos];
196 pcmbuf_current->size = size;
197 pcmbuf_current->end_of_track = end_of_track;
198 pcmbuf_current->link = NULL;
199 end_of_track = false; /* This is single use only */
200 if (read_chunk != NULL) {
201 if (pcmbuf_flush)
203 write_end_chunk->link = read_chunk->link;
204 read_chunk->link = pcmbuf_current;
205 while (write_end_chunk->link)
207 write_end_chunk = write_end_chunk->link;
208 pcmbuf_unplayed_bytes -= write_end_chunk->size;
210 pcmbuf_flush = false;
212 /* If there is already a read buffer setup, add to it */
213 else
214 read_end_chunk->link = pcmbuf_current;
215 } else {
216 /* Otherwise create the buffer */
217 read_chunk = pcmbuf_current;
219 /* This is now the last buffer to read */
220 read_end_chunk = pcmbuf_current;
222 /* Update bytes counters */
223 pcmbuf_unplayed_bytes += size;
225 pcmbuffer_pos += size;
226 if (pcmbuffer_pos >= pcmbuf_size)
227 pcmbuffer_pos -= pcmbuf_size;
229 pcmbuffer_fillpos = 0;
230 DISPLAY_DESC("add_chunk");
234 * Commit samples waiting to the pcm buffer.
236 static bool pcmbuf_flush_fillpos(void)
238 if (pcmbuffer_fillpos) {
239 /* Never use the last buffer descriptor */
240 while (write_chunk == write_end_chunk) {
241 /* If this happens, something is being stupid */
242 if (!pcm_is_playing()) {
243 logf("pcmbuf_flush_fillpos error");
244 pcmbuf_play_start();
246 /* Let approximately one chunk of data playback */
247 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
249 pcmbuf_add_chunk();
250 return true;
252 return false;
255 #ifdef HAVE_PRIORITY_SCHEDULING
256 static void boost_codec_thread(bool boost)
258 /* Keep voice and codec threads at the same priority or else voice
259 * will starve if the codec thread's priority is boosted. */
260 if (boost)
262 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
263 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
265 if (priority != codec_thread_priority)
267 codec_thread_priority = priority;
268 thread_set_priority(codec_thread_id, priority);
269 voice_thread_set_priority(priority);
272 else if (codec_thread_priority != PRIORITY_PLAYBACK)
274 thread_set_priority(codec_thread_id, PRIORITY_PLAYBACK);
275 voice_thread_set_priority(PRIORITY_PLAYBACK);
276 codec_thread_priority = PRIORITY_PLAYBACK;
279 #else
280 #define boost_codec_thread(boost) do{}while(0)
281 #endif /* HAVE_PRIORITY_SCHEDULING */
283 static bool prepare_insert(size_t length)
285 if (low_latency_mode)
287 /* 1/4s latency. */
288 if (!LOW_DATA(1) && pcm_is_playing())
289 return false;
292 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
293 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
294 return false;
296 /* boost CPU if needed to either fill to watermark or for pre-buffer */
297 if (pcm_is_playing())
299 /* Only codec thread initiates boost - voice boosts the cpu when playing
300 a clip */
301 #ifndef SIMULATOR
302 if (thread_get_current() == codec_thread_id)
303 #endif /* SIMULATOR */
305 if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
307 /* Fill PCM buffer by boosting cpu */
308 trigger_cpu_boost();
309 /* If buffer is critically low, override UI priority, else
310 set back to the original priority. */
311 boost_codec_thread(LOW_DATA(2));
313 else
315 boost_codec_thread(false);
319 /* Disable crossfade if < .5s of audio */
320 if (LOW_DATA(2))
322 crossfade_active = false;
325 else /* pcm_is_playing */
327 trigger_cpu_boost();
329 /* Pre-buffer up to watermark */
330 #if MEMORYSIZE > 2
331 if (!LOW_DATA(4))
332 #else
333 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
334 #endif
336 logf("pcm starting");
337 if (!(audio_status() & AUDIO_STATUS_PAUSE))
338 pcmbuf_play_start();
342 return true;
345 void *pcmbuf_request_buffer(int *count)
347 #ifdef HAVE_CROSSFADE
348 if (crossfade_init)
349 crossfade_start();
350 #endif
352 if (crossfade_active) {
353 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
354 return fadebuf;
356 else
358 if(prepare_insert(*count << 2))
360 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
361 if (pcmbuf_size - pcmbuffer_index >= PCMBUF_MIN_CHUNK)
363 /* Usual case, there's space here */
364 return &pcmbuffer[pcmbuffer_index];
366 else
368 /* Flush and wrap the buffer */
369 pcmbuf_flush_fillpos();
370 pcmbuffer_pos = 0;
371 return &pcmbuffer[0];
374 else
376 return NULL;
381 void pcmbuf_write_complete(int count)
383 size_t length = (size_t)(unsigned int)count << 2;
384 #ifdef HAVE_CROSSFADE
385 if (crossfade_active)
387 flush_crossfade(fadebuf, length);
388 if (!(crossfade_fade_in_rem || crossfade_chunk))
389 crossfade_active = false;
391 else
392 #endif
394 pcmbuffer_fillpos += length;
396 if (NEED_FLUSH(pcmbuffer_pos + pcmbuffer_fillpos))
397 pcmbuf_flush_fillpos();
402 /* Init */
404 static void pcmbuf_init_pcmbuffers(void)
406 #ifdef DESC_DEBUG
407 first_desc = write_chunk;
408 #endif
409 struct chunkdesc *next = write_chunk;
410 next++;
411 write_end_chunk = write_chunk;
412 while ((void *)next < (void *)pcmbuf_bufend) {
413 write_end_chunk->link=next;
414 write_end_chunk=next;
415 next++;
417 DISPLAY_DESC("init");
420 static size_t pcmbuf_get_next_required_pcmbuf_size(void)
422 size_t seconds = 1;
424 if (crossfade_enable_request)
425 seconds += global_settings.crossfade_fade_out_delay
426 + global_settings.crossfade_fade_out_duration;
428 #if MEMORYSIZE > 2
429 /* Buffer has to be at least 2s long. */
430 seconds += 2;
431 #endif
432 logf("pcmbuf len: %ld", (long)seconds);
433 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
436 static char *pcmbuf_calc_pcmbuffer_ptr(size_t bufsize)
438 return pcmbuf_bufend - (bufsize + PCMBUF_MIX_CHUNK * 2 +
439 CHUNK_DESCS_SIZE(bufsize));
442 /* Initialize the pcmbuffer the structure looks like this:
443 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
444 size_t pcmbuf_init(unsigned char *bufend)
446 pcmbuf_bufend = bufend;
447 pcmbuf_size = pcmbuf_get_next_required_pcmbuf_size();
448 pcmbuffer = pcmbuf_calc_pcmbuffer_ptr(pcmbuf_size);
449 fadebuf = &pcmbuffer[pcmbuf_size];
450 voicebuf = &fadebuf[PCMBUF_MIX_CHUNK];
451 write_chunk = (struct chunkdesc *)&voicebuf[PCMBUF_MIX_CHUNK];
453 pcmbuf_init_pcmbuffers();
455 if(track_transition){logf("pcmbuf: (init) track transition false");}
456 end_of_track = false;
457 track_transition = false;
459 pcmbuf_finish_crossfade_enable();
461 pcmbuf_play_stop();
463 return pcmbuf_bufend - pcmbuffer;
467 /* Playback */
469 /** PCM driver callback
470 * This function has 3 major logical parts (separated by brackets both for
471 * readability and variable scoping). The first part performs the
472 * operations related to finishing off the last buffer we fed to the DMA.
473 * The second part detects the end of playlist condition when the pcm
474 * buffer is empty except for uncommitted samples. Then they are committed.
475 * The third part performs the operations involved in sending a new buffer
476 * to the DMA. */
477 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size) ICODE_ATTR;
478 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size)
481 struct chunkdesc *pcmbuf_current = read_chunk;
482 /* Take the finished buffer out of circulation */
483 read_chunk = pcmbuf_current->link;
485 /* if during a track transition, update the elapsed time */
486 if (track_transition)
487 audio_pcmbuf_position_callback(last_chunksize);
489 /* if last buffer in the track, let the audio thread know */
490 if (pcmbuf_current->end_of_track)
491 pcmbuf_finish_track_change();
493 /* Put the finished buffer back into circulation */
494 write_end_chunk->link = pcmbuf_current;
495 write_end_chunk = pcmbuf_current;
497 /* If we've read over the mix chunk while it's still mixing there */
498 if (pcmbuf_current == mix_chunk)
499 mix_chunk = NULL;
500 /* If we've read over the crossfade chunk while it's still fading */
501 if (pcmbuf_current == crossfade_chunk)
502 crossfade_chunk = read_chunk;
506 /* Commit last samples at end of playlist */
507 if (pcmbuffer_fillpos && !read_chunk)
509 logf("pcmbuf_pcm_callback: commit last samples");
510 pcmbuf_flush_fillpos();
515 /* Send the new buffer to the pcm */
516 struct chunkdesc *pcmbuf_new = read_chunk;
517 size_t *realsize = size;
518 unsigned char** realstart = start;
519 if(pcmbuf_new)
521 size_t current_size = pcmbuf_new->size;
523 pcmbuf_unplayed_bytes -= current_size;
524 last_chunksize = current_size;
525 *realsize = current_size;
526 *realstart = pcmbuf_new->addr;
528 else
530 /* No more buffers */
531 last_chunksize = 0;
532 *realsize = 0;
533 *realstart = NULL;
534 if (end_of_track)
535 pcmbuf_finish_track_change();
538 DISPLAY_DESC("callback");
541 /* Force playback. */
542 void pcmbuf_play_start(void)
544 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && read_chunk != NULL)
546 last_chunksize = read_chunk->size;
547 pcmbuf_unplayed_bytes -= last_chunksize;
548 pcm_play_data(pcmbuf_pcm_callback,
549 (unsigned char *)read_chunk->addr, last_chunksize);
553 void pcmbuf_play_stop(void)
555 pcm_play_stop();
557 pcmbuf_unplayed_bytes = 0;
558 mix_chunk = NULL;
559 if (read_chunk) {
560 write_end_chunk->link = read_chunk;
561 write_end_chunk = read_end_chunk;
562 read_chunk = read_end_chunk = NULL;
564 pcmbuffer_pos = 0;
565 pcmbuffer_fillpos = 0;
566 crossfade_init = false;
567 crossfade_active = false;
568 pcmbuf_flush = false;
569 DISPLAY_DESC("play_stop");
571 /* Can unboost the codec thread here no matter who's calling */
572 boost_codec_thread(false);
575 void pcmbuf_pause(bool pause)
577 if (pcm_is_playing())
578 pcm_play_pause(!pause);
579 else if (!pause)
580 pcmbuf_play_start();
584 /* Track change */
586 /* The codec is moving on to the next track, but the current track is
587 * still playing. Set flags to make sure the elapsed time of the current
588 * track is updated properly, and mark the currently written chunk as the
589 * last one in the track. */
590 static void pcmbuf_gapless_track_change(void)
592 /* we're starting a track transition */
593 track_transition = true;
595 /* mark the last chunk in the track */
596 end_of_track = true;
599 static void pcmbuf_crossfade_track_change(void)
601 /* Initiate automatic crossfade mode */
602 pcmbuf_crossfade_init(false);
603 /* Notify the wps that the track change starts now */
604 audio_post_track_change(false);
607 void pcmbuf_start_track_change(bool manual_skip)
609 /* Manual track change (always crossfade or flush audio). */
610 if (manual_skip)
612 pcmbuf_crossfade_init(true);
613 audio_post_track_change(false);
615 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
616 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
617 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
619 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
621 if (global_settings.playlist_shuffle)
622 /* shuffle mode is on, so crossfade: */
623 pcmbuf_crossfade_track_change();
624 else
625 /* shuffle mode is off, so normal gapless playback */
626 pcmbuf_gapless_track_change();
628 else
629 /* normal crossfade: */
630 pcmbuf_crossfade_track_change();
632 else
633 /* normal gapless playback. */
634 pcmbuf_gapless_track_change();
637 /* Called when the last chunk in the track has been played */
638 static void pcmbuf_finish_track_change(void)
640 /* not in a track transition anymore */
641 if(track_transition){logf("pcmbuf: (finish change) track transition false");}
642 track_transition = false;
644 /* notify playback that the track has just finished */
645 audio_post_track_change(true);
649 /* Crossfade */
651 /* Clip sample to signed 16 bit range */
652 static inline int32_t clip_sample_16(int32_t sample)
654 if ((int16_t)sample != sample)
655 sample = 0x7fff ^ (sample >> 31);
656 return sample;
659 /**
660 * Low memory targets don't have crossfade, so don't compile crossfade
661 * specific code in order to save some memory. */
663 #ifdef HAVE_CROSSFADE
665 * Completely process the crossfade fade out effect with current pcm buffer.
667 static void crossfade_process_buffer(size_t fade_in_delay,
668 size_t fade_out_delay, size_t fade_out_rem)
670 if (!crossfade_mixmode)
672 /* Fade out the specified amount of the already processed audio */
673 size_t total_fade_out = fade_out_rem;
674 size_t fade_out_sample;
675 struct chunkdesc *fade_out_chunk = crossfade_chunk;
677 /* Find the right chunk to start fading out */
678 fade_out_delay += crossfade_sample * 2;
679 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
681 fade_out_delay -= fade_out_chunk->size;
682 fade_out_chunk = fade_out_chunk->link;
684 /* The start sample within the chunk */
685 fade_out_sample = fade_out_delay / 2;
687 while (fade_out_rem > 0)
689 /* Each 1/10 second of audio will have the same fade applied */
690 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
691 int factor = (fade_out_rem << 8) / total_fade_out;
693 fade_out_rem -= block_rem;
695 /* Fade this block */
696 while (block_rem > 0 && fade_out_chunk != NULL)
698 /* Fade one sample */
699 int16_t *buf = (int16_t *)fade_out_chunk->addr;
700 int32_t sample = buf[fade_out_sample];
701 buf[fade_out_sample++] = (sample * factor) >> 8;
703 block_rem -= 2;
704 /* Move to the next chunk as needed */
705 if (fade_out_sample * 2 >= fade_out_chunk->size)
707 fade_out_chunk = fade_out_chunk->link;
708 fade_out_sample = 0;
714 /* Find the right chunk and sample to start fading in */
715 fade_in_delay += crossfade_sample * 2;
716 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
718 fade_in_delay -= crossfade_chunk->size;
719 crossfade_chunk = crossfade_chunk->link;
721 crossfade_sample = fade_in_delay / 2;
722 logf("process done!");
725 /* Initializes crossfader, calculates all necessary parameters and
726 * performs fade-out with the pcm buffer. */
727 static void crossfade_start(void)
729 size_t crossfade_rem;
730 size_t crossfade_need;
731 size_t fade_out_rem;
732 size_t fade_out_delay;
733 size_t fade_in_delay;
735 crossfade_init = false;
736 /* Reject crossfade if less than .5s of data */
737 if (LOW_DATA(2)) {
738 logf("crossfade rejected");
739 pcmbuf_play_stop();
740 return ;
743 logf("crossfade_start");
744 pcmbuf_flush_fillpos();
745 crossfade_active = true;
747 /* Initialize the crossfade buffer size to all of the buffered data that
748 * has not yet been sent to the DMA */
749 crossfade_rem = pcmbuf_unplayed_bytes;
750 crossfade_chunk = read_chunk->link;
751 crossfade_sample = 0;
753 /* Get fade out delay from settings. */
754 fade_out_delay =
755 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
757 /* Get fade out duration from settings. */
758 fade_out_rem =
759 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
761 crossfade_need = fade_out_delay + fade_out_rem;
762 /* We want only to modify the last part of the buffer. */
763 if (crossfade_rem > crossfade_need)
765 size_t crossfade_extra = crossfade_rem - crossfade_need;
766 while (crossfade_extra > crossfade_chunk->size)
768 crossfade_extra -= crossfade_chunk->size;
769 crossfade_chunk = crossfade_chunk->link;
771 crossfade_sample = crossfade_extra / 2;
773 /* Truncate fade out duration if necessary. */
774 else if (crossfade_rem < crossfade_need)
776 size_t crossfade_short = crossfade_need - crossfade_rem;
777 if (fade_out_rem >= crossfade_short)
778 fade_out_rem -= crossfade_short;
779 else
781 fade_out_delay -= crossfade_short - fade_out_rem;
782 fade_out_rem = 0;
786 /* Get also fade in duration and delays from settings. */
787 crossfade_fade_in_total =
788 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
789 crossfade_fade_in_rem = crossfade_fade_in_total;
791 fade_in_delay =
792 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
794 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
797 /* Returns the number of bytes _NOT_ mixed */
798 static size_t crossfade_mix(int factor, const char *buf, size_t length)
800 const int16_t *input_buf = (const int16_t *)buf;
801 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
802 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
803 output_buf = &output_buf[crossfade_sample];
804 int32_t sample;
806 while (length)
808 /* fade left and right channel at once to keep buffer alignment */
809 int i;
810 for (i = 0; i < 2; i++)
812 sample = *input_buf++;
813 sample = ((sample * factor) >> 8) + *output_buf;
814 *output_buf++ = clip_sample_16(sample);
817 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
819 if (output_buf >= chunk_end)
821 crossfade_chunk = crossfade_chunk->link;
822 if (!crossfade_chunk)
823 return length;
824 output_buf = (int16_t *)crossfade_chunk->addr;
825 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
828 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
829 return 0;
832 static void flush_crossfade(char *buf, size_t length)
834 if (length)
836 if (crossfade_fade_in_rem)
838 size_t samples;
839 int16_t *input_buf;
841 /* Fade factor for this packet */
842 int factor =
843 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
844 crossfade_fade_in_total;
845 /* Bytes to fade */
846 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
848 /* We _will_ fade this many bytes */
849 crossfade_fade_in_rem -= fade_rem;
851 if (crossfade_chunk)
853 /* Mix the data */
854 size_t fade_total = fade_rem;
855 fade_rem = crossfade_mix(factor, buf, fade_rem);
856 length -= fade_total - fade_rem;
857 buf += fade_total - fade_rem;
858 if (!length)
859 return;
862 samples = fade_rem / 2;
863 input_buf = (int16_t *)buf;
864 /* Fade remaining samples in place */
865 while (samples--)
867 int32_t sample = *input_buf;
868 *input_buf++ = (sample * factor) >> 8;
872 if (crossfade_chunk)
874 /* Mix the data */
875 size_t mix_total = length;
876 length = crossfade_mix(256, buf, length);
877 buf += mix_total - length;
878 if (!length)
879 return;
882 /* Flush samples to the buffer */
883 while (!prepare_insert(length))
884 sleep(1);
885 while (length > 0)
887 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
888 if (NEED_FLUSH(pcmbuffer_index))
890 pcmbuf_flush_fillpos();
891 pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
893 size_t copy_n = MIN(length, pcmbuf_size - pcmbuffer_index);
894 memcpy(&pcmbuffer[pcmbuffer_index], buf, copy_n);
895 buf += copy_n;
896 pcmbuffer_fillpos += copy_n;
897 length -= copy_n;
901 #endif /* HAVE_CROSSFADE */
903 static bool pcmbuf_crossfade_init(bool manual_skip)
905 /* Can't do two crossfades at once and, no fade if pcm is off now */
906 if (crossfade_init || crossfade_active || !pcm_is_playing())
908 pcmbuf_play_stop();
909 return false;
912 trigger_cpu_boost();
914 /* Not enough data, or crossfade disabled, flush the old data instead */
915 if (LOW_DATA(2) || !pcmbuf_is_crossfade_enabled() || low_latency_mode)
917 pcmbuf_flush_fillpos();
918 pcmbuf_flush = true;
919 return false;
922 /* Don't enable mix mode when skipping tracks manually. */
923 if (manual_skip)
924 crossfade_mixmode = false;
925 else
926 crossfade_mixmode = global_settings.crossfade_fade_out_mixmode;
928 crossfade_init = true;
930 return true;
934 static void pcmbuf_finish_crossfade_enable(void)
936 /* Copy the pending setting over now */
937 crossfade_enabled = crossfade_enable_request;
939 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
940 /* If crossfading, try to keep the buffer full other than 1 second */
941 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
942 /* Otherwise, just use the default */
943 PCMBUF_WATERMARK;
946 static bool pcmbuf_is_crossfade_enabled(void)
948 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
949 return global_settings.playlist_shuffle;
951 return crossfade_enabled;
954 bool pcmbuf_is_crossfade_active(void)
956 return crossfade_active || crossfade_init;
959 void pcmbuf_request_crossfade_enable(bool on_off)
961 /* Next setting to be used, not applied now */
962 crossfade_enable_request = on_off;
965 bool pcmbuf_is_same_size(void)
967 bool same_size;
969 if (pcmbuffer == NULL)
970 same_size = true; /* Not set up yet even once so always */
971 else
973 size_t bufsize = pcmbuf_get_next_required_pcmbuf_size();
974 same_size = pcmbuf_calc_pcmbuffer_ptr(bufsize) == pcmbuffer;
977 if (same_size)
978 pcmbuf_finish_crossfade_enable();
980 return same_size;
984 /* Voice */
986 /* Returns pcm buffer usage in percents (0 to 100). */
987 static int pcmbuf_usage(void)
989 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
992 static int pcmbuf_mix_free(void)
994 if (mix_chunk)
996 size_t my_mix_end =
997 (size_t)&((int16_t *)mix_chunk->addr)[pcmbuf_mix_sample];
998 size_t my_write_pos = (size_t)&pcmbuffer[pcmbuffer_pos];
999 if (my_write_pos < my_mix_end)
1000 my_write_pos += pcmbuf_size;
1001 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1003 return 100;
1006 void *pcmbuf_request_voice_buffer(int *count)
1008 /* A get-it-to-work-for-now hack (audio status could change by
1009 completion) */
1010 if (audio_status() & AUDIO_STATUS_PLAY)
1012 if (read_chunk == NULL)
1014 return NULL;
1016 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
1017 (mix_chunk || read_chunk->link))
1019 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
1020 return voicebuf;
1022 else
1024 return NULL;
1027 else
1029 return pcmbuf_request_buffer(count);
1033 void pcmbuf_write_voice_complete(int count)
1035 /* A get-it-to-work-for-now hack (audio status could have changed) */
1036 if (!(audio_status() & AUDIO_STATUS_PLAY))
1038 pcmbuf_write_complete(count);
1039 return;
1042 int16_t *ibuf = (int16_t *)voicebuf;
1043 int16_t *obuf;
1044 size_t chunk_samples;
1046 if (mix_chunk == NULL && read_chunk != NULL)
1048 mix_chunk = read_chunk->link;
1049 /* Start 1/8s into the next chunk */
1050 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1053 if (!mix_chunk)
1054 return;
1056 obuf = (int16_t *)mix_chunk->addr;
1057 chunk_samples = mix_chunk->size / sizeof (int16_t);
1059 count <<= 1;
1061 while (count-- > 0)
1063 int32_t sample = *ibuf++;
1065 if (pcmbuf_mix_sample >= chunk_samples)
1067 mix_chunk = mix_chunk->link;
1068 if (!mix_chunk)
1069 return;
1070 pcmbuf_mix_sample = 0;
1071 obuf = mix_chunk->addr;
1072 chunk_samples = mix_chunk->size / 2;
1074 sample += obuf[pcmbuf_mix_sample] >> 2;
1075 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1080 /* Debug menu, other metrics */
1082 /* Amount of bytes left in the buffer. */
1083 size_t pcmbuf_free(void)
1085 if (read_chunk != NULL)
1087 void *read = read_chunk->addr;
1088 void *write = &pcmbuffer[pcmbuffer_pos + pcmbuffer_fillpos];
1089 if (read < write)
1090 return (size_t)(read - write) + pcmbuf_size;
1091 else
1092 return (size_t) (read - write);
1094 return pcmbuf_size;
1097 size_t pcmbuf_get_bufsize(void)
1099 return pcmbuf_size;
1102 int pcmbuf_used_descs(void)
1104 struct chunkdesc *temp = read_chunk;
1105 unsigned int i = 0;
1106 while (temp) {
1107 temp = temp->link;
1108 i++;
1110 return i;
1113 int pcmbuf_descs(void)
1115 return CHUNK_DESCS(pcmbuf_size);
1118 #ifdef ROCKBOX_HAS_LOGF
1119 unsigned char * pcmbuf_get_meminfo(size_t *length)
1121 *length = pcmbuf_bufend - pcmbuffer;
1122 return pcmbuffer;
1124 #endif
1127 /* Misc */
1129 bool pcmbuf_is_lowdata(void)
1131 if (!pcm_is_playing() || pcm_is_paused() ||
1132 crossfade_init || crossfade_active)
1133 return false;
1135 #if MEMORYSIZE > 2
1136 /* 1 seconds of buffer is low data */
1137 return LOW_DATA(4);
1138 #else
1139 /* under watermark is low data */
1140 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
1141 #endif
1144 void pcmbuf_set_low_latency(bool state)
1146 low_latency_mode = state;
1149 unsigned long pcmbuf_get_latency(void)
1151 /* Be careful how this calculation is rearranged, it's easy to overflow */
1152 size_t bytes = pcmbuf_unplayed_bytes + pcm_get_bytes_waiting();
1153 return bytes / 4 * 1000 / NATIVE_FREQUENCY;
1156 #ifndef HAVE_HARDWARE_BEEP
1157 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
1158 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
1160 /* Generates a constant square wave sound with a given frequency
1161 in Hertz for a duration in milliseconds. */
1162 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
1164 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
1165 int32_t phase = 0;
1166 int16_t *bufptr, *bufstart, *bufend;
1167 int32_t sample;
1168 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
1169 bool mix = read_chunk != NULL && read_chunk->link != NULL;
1170 int i;
1172 bufend = SKIPBYTES((int16_t *)pcmbuffer, pcmbuf_size);
1174 /* Find the insertion point and set bufstart to the start of it */
1175 if (mix)
1177 /* Get the currently playing chunk at the current position. */
1178 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
1180 /* If above isn't implemented or pcm is stopped, no beepeth. */
1181 if (!bufstart || !pcm_is_playing())
1182 return;
1184 /* Give 5ms clearance. */
1185 bufstart += NATIVE_FREQUENCY * 4 / 200;
1187 #ifdef HAVE_PCM_DMA_ADDRESS
1188 /* Returned peak addresses are DMA addresses */
1189 bufend = pcm_dma_addr(bufend);
1190 #endif
1192 /* Wrapped above? */
1193 if (bufstart >= bufend)
1194 bufstart -= pcmbuf_size;
1196 /* NOTE: On some targets using hardware DMA, cache range flushing may
1197 * be required or the writes may not be picked up by the controller.
1198 * An incremental flush should be done periodically during the mixdown. */
1200 else if (nsamples <= MINIBUF_SAMPLES)
1202 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
1203 /* Use mini buffer */
1204 bufstart = minibuf;
1205 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
1207 else if (audio_buffer_state() != AUDIOBUF_STATE_TRASHED)
1209 /* Use pcmbuffer */
1210 bufstart = (int16_t *)pcmbuffer;
1212 else
1214 /* No place */
1215 return;
1218 bufptr = bufstart;
1220 /* Mix square wave into buffer */
1221 for (i = 0; i < nsamples; ++i)
1223 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
1224 sample = mix ? *bufptr : 0;
1225 *bufptr++ = clip_sample_16(sample + amp);
1226 if (bufptr >= bufend)
1227 bufptr = (int16_t *)pcmbuffer;
1228 sample = mix ? *bufptr : 0;
1229 *bufptr++ = clip_sample_16(sample + amp);
1230 if (bufptr >= bufend)
1231 bufptr = (int16_t *)pcmbuffer;
1233 phase += step;
1236 pcm_play_lock();
1237 #ifdef HAVE_RECORDING
1238 pcm_rec_lock();
1239 #endif
1241 /* Kick off playback if required and it won't interfere */
1242 if (!pcm_is_playing()
1243 #ifdef HAVE_RECORDING
1244 && !pcm_is_recording()
1245 #endif
1248 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1251 pcm_play_unlock();
1252 #ifdef HAVE_RECORDING
1253 pcm_rec_unlock();
1254 #endif
1256 #endif /* HAVE_HARDWARE_BEEP */