usb screen: show logo at center of ui viewport and try to fit logo and title to the...
[kugel-rb.git] / apps / pcmbuf.c
blob75d8152f7ef86119eec24e79c94f790f5e3f6528
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;
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 (pcmbuffer_fillpos > PCMBUF_TARGET_CHUNK || position >= pcmbuf_size)
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 flush_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 /* Commit PCM data */
187 * Commit samples waiting to the pcm buffer.
189 static void commit_chunk(void)
191 if (!pcmbuffer_fillpos)
192 return;
194 /* Never use the last buffer descriptor */
195 while (write_chunk == write_end_chunk) {
196 /* If this happens, something is being stupid */
197 if (!pcm_is_playing()) {
198 logf("commit_chunk error");
199 pcmbuf_play_start();
201 /* Let approximately one chunk of data playback */
202 sleep(HZ*PCMBUF_TARGET_CHUNK/(NATIVE_FREQUENCY*4));
205 /* commit the chunk */
207 register size_t size = pcmbuffer_fillpos;
208 /* Grab the next description to write, and change the write pointer */
209 register struct chunkdesc *pcmbuf_current = write_chunk;
210 write_chunk = pcmbuf_current->link;
211 /* Fill in the values in the new buffer chunk */
212 pcmbuf_current->addr = &pcmbuffer[pcmbuffer_pos];
213 pcmbuf_current->size = size;
214 pcmbuf_current->end_of_track = end_of_track;
215 pcmbuf_current->link = NULL;
216 end_of_track = false; /* This is single use only */
218 if (read_chunk != NULL)
220 if (flush_pcmbuf)
222 /* flush! discard all data after the currently playing chunk,
223 and make the current chunk play next */
224 write_end_chunk->link = read_chunk->link;
225 read_chunk->link = pcmbuf_current;
226 while (write_end_chunk->link)
228 write_end_chunk = write_end_chunk->link;
229 pcmbuf_unplayed_bytes -= write_end_chunk->size;
231 flush_pcmbuf = false;
233 /* If there is already a read buffer setup, add to it */
234 else
235 read_end_chunk->link = pcmbuf_current;
237 else
239 /* Otherwise create the buffer */
240 read_chunk = pcmbuf_current;
243 /* This is now the last buffer to read */
244 read_end_chunk = pcmbuf_current;
246 /* Update bytes counters */
247 pcmbuf_unplayed_bytes += size;
249 pcmbuffer_pos += size;
250 if (pcmbuffer_pos >= pcmbuf_size)
251 pcmbuffer_pos -= pcmbuf_size;
253 pcmbuffer_fillpos = 0;
254 DISPLAY_DESC("commit_chunk");
257 #ifdef HAVE_PRIORITY_SCHEDULING
258 static void boost_codec_thread(bool boost)
260 /* Keep voice and codec threads at the same priority or else voice
261 * will starve if the codec thread's priority is boosted. */
262 if (boost)
264 int priority = (PRIORITY_PLAYBACK - PRIORITY_PLAYBACK_MAX)*pcmbuf_unplayed_bytes
265 / (2*NATIVE_FREQUENCY) + PRIORITY_PLAYBACK_MAX;
267 if (priority != codec_thread_priority)
269 codec_thread_priority = priority;
270 thread_set_priority(codec_thread_id, priority);
271 voice_thread_set_priority(priority);
274 else if (codec_thread_priority != PRIORITY_PLAYBACK)
276 thread_set_priority(codec_thread_id, PRIORITY_PLAYBACK);
277 voice_thread_set_priority(PRIORITY_PLAYBACK);
278 codec_thread_priority = PRIORITY_PLAYBACK;
281 #else
282 #define boost_codec_thread(boost) do{}while(0)
283 #endif /* HAVE_PRIORITY_SCHEDULING */
285 static bool prepare_insert(size_t length)
287 if (low_latency_mode)
289 /* 1/4s latency. */
290 if (!LOW_DATA(1) && pcm_is_playing())
291 return false;
294 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
295 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
296 return false;
298 /* boost CPU if needed to either fill to watermark or for pre-buffer */
299 if (pcm_is_playing())
301 /* Only codec thread initiates boost - voice boosts the cpu when playing
302 a clip */
303 #ifndef SIMULATOR
304 if (thread_get_current() == codec_thread_id)
305 #endif /* SIMULATOR */
307 if (pcmbuf_unplayed_bytes <= pcmbuf_watermark)
309 /* Fill PCM buffer by boosting cpu */
310 trigger_cpu_boost();
311 /* If buffer is critically low, override UI priority, else
312 set back to the original priority. */
313 boost_codec_thread(LOW_DATA(2));
315 else
317 boost_codec_thread(false);
321 #ifdef HAVE_CROSSFADE
322 /* Disable crossfade if < .5s of audio */
323 if (LOW_DATA(2))
325 crossfade_active = false;
327 #endif
329 else /* pcm_is_playing */
331 trigger_cpu_boost();
333 /* Pre-buffer up to watermark */
334 #if MEMORYSIZE > 2
335 if (!LOW_DATA(4))
336 #else
337 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
338 #endif
340 logf("pcm starting");
341 if (!(audio_status() & AUDIO_STATUS_PAUSE))
342 pcmbuf_play_start();
346 return true;
349 void *pcmbuf_request_buffer(int *count)
351 #ifdef HAVE_CROSSFADE
352 if (crossfade_track_change_started)
353 crossfade_start();
355 if (crossfade_active) {
356 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
357 return fadebuf;
359 else
360 #endif
362 if(prepare_insert(*count << 2))
364 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
365 if (pcmbuf_size - pcmbuffer_index >= PCMBUF_MIN_CHUNK)
367 /* Usual case, there's space here */
368 return &pcmbuffer[pcmbuffer_index];
370 else
372 /* Flush and wrap the buffer */
373 commit_chunk();
374 pcmbuffer_pos = 0;
375 return &pcmbuffer[0];
379 return NULL;
382 void pcmbuf_write_complete(int count)
384 size_t length = (size_t)(unsigned int)count << 2;
385 #ifdef HAVE_CROSSFADE
386 if (crossfade_active)
388 flush_crossfade(fadebuf, length);
389 if (!(crossfade_fade_in_rem || crossfade_chunk))
390 crossfade_active = false;
392 else
393 #endif
395 pcmbuffer_fillpos += length;
397 if (NEED_FLUSH(pcmbuffer_pos + pcmbuffer_fillpos))
398 commit_chunk();
403 /* Init */
405 static inline void init_pcmbuffers(void)
407 #ifdef DESC_DEBUG
408 first_desc = write_chunk;
409 #endif
410 struct chunkdesc *next = write_chunk;
411 next++;
412 write_end_chunk = write_chunk;
413 while ((void *)next < (void *)pcmbuf_bufend) {
414 write_end_chunk->link=next;
415 write_end_chunk=next;
416 next++;
418 DISPLAY_DESC("init");
421 static size_t get_next_required_pcmbuf_size(void)
423 size_t seconds = 1;
425 #ifdef HAVE_CROSSFADE
426 if (crossfade_enable_request)
427 seconds += global_settings.crossfade_fade_out_delay +
428 global_settings.crossfade_fade_out_duration;
429 #endif
431 #if MEMORYSIZE > 2
432 /* Buffer has to be at least 2s long. */
433 seconds += 2;
434 #endif
435 logf("pcmbuf len: %ld", (long)seconds);
436 return seconds * (NATIVE_FREQUENCY*4); /* 2 channels + 2 bytes/sample */
439 /* Initialize the pcmbuffer the structure looks like this:
440 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
441 size_t pcmbuf_init(unsigned char *bufend)
443 pcmbuf_bufend = bufend;
444 pcmbuf_size = get_next_required_pcmbuf_size();
445 write_chunk = (struct chunkdesc *)pcmbuf_bufend -
446 NUM_CHUNK_DESCS(pcmbuf_size);
447 voicebuf = (char *)write_chunk - PCMBUF_MIX_CHUNK;
448 #ifdef HAVE_CROSSFADE
449 fadebuf = voicebuf - PCMBUF_MIX_CHUNK;
450 pcmbuffer = fadebuf - pcmbuf_size;
451 #else
452 pcmbuffer = voicebuf - pcmbuf_size;
453 #endif
455 init_pcmbuffers();
457 if(track_transition){logf("pcmbuf: (init) track transition false");}
458 end_of_track = false;
459 track_transition = false;
461 #ifdef HAVE_CROSSFADE
462 pcmbuf_finish_crossfade_enable();
463 #else
464 pcmbuf_watermark = PCMBUF_WATERMARK;
465 #endif
467 pcmbuf_play_stop();
469 return pcmbuf_bufend - pcmbuffer;
473 /* Track change */
475 /* The codec is moving on to the next track, but the current track is
476 * still playing. Set flags to make sure the elapsed time of the current
477 * track is updated properly, and mark the currently written chunk as the
478 * last one in the track. */
479 static void start_gapless_track_change(void)
481 logf(" gapless track change");
482 /* we're starting a track transition */
483 track_transition = true;
485 /* mark the last chunk in the track */
486 end_of_track = true;
489 #ifdef HAVE_CROSSFADE
490 static bool pcmbuf_is_crossfade_enabled(void)
492 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE)
493 return global_settings.playlist_shuffle;
495 return crossfade_enabled;
497 #endif
499 static void start_processed_track_change(bool auto_skip)
501 logf(" processed track change");
502 /* Notify the wps that the track change starts now */
503 audio_post_track_change(false);
505 /* Can't do two crossfades at once and, no fade if pcm is off now */
506 if (
507 #ifdef HAVE_CROSSFADE
508 pcmbuf_is_crossfade_active() ||
509 #endif
510 !pcm_is_playing())
512 pcmbuf_play_stop();
513 return;
516 trigger_cpu_boost();
518 /* Not enough data, or crossfade disabled, flush the old data instead */
519 if (LOW_DATA(2) ||
520 #ifdef HAVE_CROSSFADE
521 !pcmbuf_is_crossfade_enabled() ||
522 #endif
523 low_latency_mode)
525 /* commit everything to this point and keep going, but... */
526 commit_chunk();
527 /* ... when the next chunk commits, throw away everything but itself */
528 flush_pcmbuf = true;
529 return;
532 #ifdef HAVE_CROSSFADE
533 /* Don't enable mix mode when skipping tracks manually. */
534 crossfade_mixmode = auto_skip && global_settings.crossfade_fade_out_mixmode;
536 crossfade_track_change_started = true;
537 #else
538 (void)auto_skip;
539 #endif
542 void pcmbuf_start_track_change(bool auto_skip)
544 bool process = false;
545 /* Manual track change (always crossfade or flush audio). */
546 if (!auto_skip)
547 process = true;
549 #ifdef HAVE_CROSSFADE
550 /* Automatic track change w/crossfade, if not in "Track Skip Only" mode. */
551 else if (pcmbuf_is_crossfade_enabled() && !pcmbuf_is_crossfade_active()
552 && global_settings.crossfade != CROSSFADE_ENABLE_TRACKSKIP)
554 if (global_settings.crossfade == CROSSFADE_ENABLE_SHUFFLE_AND_TRACKSKIP)
556 if (global_settings.playlist_shuffle)
557 process = true;
559 else
560 process = true;
562 #endif
564 if (process)
565 /* process track change (manual skip or crossfade) */
566 start_processed_track_change(auto_skip);
567 else
568 /* normal gapless playback */
569 start_gapless_track_change();
572 /* Called when the last chunk in the track has been played */
573 static void finish_gapless_track_change(void)
575 /* not in a track transition anymore */
576 if(track_transition){logf("pcmbuf: (finish change) track transition false");}
577 track_transition = false;
579 /* notify playback that the track has just finished */
580 audio_post_track_change(true);
584 /* Playback */
586 /** PCM driver callback
587 * This function has 3 major logical parts (separated by brackets both for
588 * readability and variable scoping). The first part performs the
589 * operations related to finishing off the last buffer we fed to the DMA.
590 * The second part detects the end of playlist condition when the pcm
591 * buffer is empty except for uncommitted samples. Then they are committed.
592 * The third part performs the operations involved in sending a new buffer
593 * to the DMA. */
594 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size) ICODE_ATTR;
595 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size)
598 struct chunkdesc *pcmbuf_current = read_chunk;
599 /* Take the finished buffer out of circulation */
600 read_chunk = pcmbuf_current->link;
602 /* if during a track transition, update the elapsed time */
603 if (track_transition)
604 audio_pcmbuf_position_callback(last_chunksize);
606 /* if last buffer in the track, let the audio thread know */
607 if (pcmbuf_current->end_of_track)
608 finish_gapless_track_change();
610 /* Put the finished buffer back into circulation */
611 write_end_chunk->link = pcmbuf_current;
612 write_end_chunk = pcmbuf_current;
614 /* If we've read over the mix chunk while it's still mixing there */
615 if (pcmbuf_current == mix_chunk)
616 mix_chunk = NULL;
618 #ifdef HAVE_CROSSFADE
619 /* If we've read over the crossfade chunk while it's still fading */
620 if (pcmbuf_current == crossfade_chunk)
621 crossfade_chunk = read_chunk;
622 #endif
626 /* Commit last samples at end of playlist */
627 if (pcmbuffer_fillpos && !read_chunk)
629 logf("pcmbuf_pcm_callback: commit last samples");
630 commit_chunk();
635 /* Send the new buffer to the pcm */
636 if(read_chunk)
638 size_t current_size = read_chunk->size;
640 pcmbuf_unplayed_bytes -= current_size;
641 last_chunksize = current_size;
642 *size = current_size;
643 *start = read_chunk->addr;
645 else
647 /* No more buffers */
648 last_chunksize = 0;
649 *size = 0;
650 *start = NULL;
651 if (end_of_track)
652 finish_gapless_track_change();
655 DISPLAY_DESC("callback");
658 /* Force playback. */
659 void pcmbuf_play_start(void)
661 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && read_chunk != NULL)
663 last_chunksize = read_chunk->size;
664 pcmbuf_unplayed_bytes -= last_chunksize;
665 pcm_play_data(pcmbuf_pcm_callback,
666 (unsigned char *)read_chunk->addr, last_chunksize);
670 void pcmbuf_play_stop(void)
672 pcm_play_stop();
674 pcmbuf_unplayed_bytes = 0;
675 mix_chunk = NULL;
676 if (read_chunk) {
677 write_end_chunk->link = read_chunk;
678 write_end_chunk = read_end_chunk;
679 read_chunk = read_end_chunk = NULL;
681 pcmbuffer_pos = 0;
682 pcmbuffer_fillpos = 0;
683 #ifdef HAVE_CROSSFADE
684 crossfade_track_change_started = false;
685 crossfade_active = false;
686 #endif
687 flush_pcmbuf = false;
688 DISPLAY_DESC("play_stop");
690 /* Can unboost the codec thread here no matter who's calling */
691 boost_codec_thread(false);
694 void pcmbuf_pause(bool pause)
696 if (pcm_is_playing())
697 pcm_play_pause(!pause);
698 else if (!pause)
699 pcmbuf_play_start();
703 /* Crossfade */
705 /* Clip sample to signed 16 bit range */
706 static inline int32_t clip_sample_16(int32_t sample)
708 if ((int16_t)sample != sample)
709 sample = 0x7fff ^ (sample >> 31);
710 return sample;
713 #ifdef HAVE_CROSSFADE
715 * Completely process the crossfade fade out effect with current pcm buffer.
717 static void crossfade_process_buffer(size_t fade_in_delay,
718 size_t fade_out_delay, size_t fade_out_rem)
720 if (!crossfade_mixmode)
722 /* Fade out the specified amount of the already processed audio */
723 size_t total_fade_out = fade_out_rem;
724 size_t fade_out_sample;
725 struct chunkdesc *fade_out_chunk = crossfade_chunk;
727 /* Find the right chunk to start fading out */
728 fade_out_delay += crossfade_sample * 2;
729 while (fade_out_delay != 0 && fade_out_delay >= fade_out_chunk->size)
731 fade_out_delay -= fade_out_chunk->size;
732 fade_out_chunk = fade_out_chunk->link;
734 /* The start sample within the chunk */
735 fade_out_sample = fade_out_delay / 2;
737 while (fade_out_rem > 0)
739 /* Each 1/10 second of audio will have the same fade applied */
740 size_t block_rem = MIN(NATIVE_FREQUENCY * 4 / 10, fade_out_rem);
741 int factor = (fade_out_rem << 8) / total_fade_out;
743 fade_out_rem -= block_rem;
745 /* Fade this block */
746 while (block_rem > 0 && fade_out_chunk != NULL)
748 /* Fade one sample */
749 int16_t *buf = (int16_t *)fade_out_chunk->addr;
750 int32_t sample = buf[fade_out_sample];
751 buf[fade_out_sample++] = (sample * factor) >> 8;
753 block_rem -= 2;
754 /* Move to the next chunk as needed */
755 if (fade_out_sample * 2 >= fade_out_chunk->size)
757 fade_out_chunk = fade_out_chunk->link;
758 fade_out_sample = 0;
764 /* Find the right chunk and sample to start fading in */
765 fade_in_delay += crossfade_sample * 2;
766 while (fade_in_delay != 0 && fade_in_delay >= crossfade_chunk->size)
768 fade_in_delay -= crossfade_chunk->size;
769 crossfade_chunk = crossfade_chunk->link;
771 crossfade_sample = fade_in_delay / 2;
772 logf("process done!");
775 /* Initializes crossfader, calculates all necessary parameters and
776 * performs fade-out with the pcm buffer. */
777 static void crossfade_start(void)
779 size_t crossfade_rem;
780 size_t crossfade_need;
781 size_t fade_out_rem;
782 size_t fade_out_delay;
783 size_t fade_in_delay;
785 crossfade_track_change_started = false;
786 /* Reject crossfade if less than .5s of data */
787 if (LOW_DATA(2)) {
788 logf("crossfade rejected");
789 pcmbuf_play_stop();
790 return ;
793 logf("crossfade_start");
794 commit_chunk();
795 crossfade_active = true;
797 /* Initialize the crossfade buffer size to all of the buffered data that
798 * has not yet been sent to the DMA */
799 crossfade_rem = pcmbuf_unplayed_bytes;
800 crossfade_chunk = read_chunk->link;
801 crossfade_sample = 0;
803 /* Get fade out delay from settings. */
804 fade_out_delay =
805 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_delay * 4;
807 /* Get fade out duration from settings. */
808 fade_out_rem =
809 NATIVE_FREQUENCY * global_settings.crossfade_fade_out_duration * 4;
811 crossfade_need = fade_out_delay + fade_out_rem;
812 /* We want only to modify the last part of the buffer. */
813 if (crossfade_rem > crossfade_need)
815 size_t crossfade_extra = crossfade_rem - crossfade_need;
816 while (crossfade_extra > crossfade_chunk->size)
818 crossfade_extra -= crossfade_chunk->size;
819 crossfade_chunk = crossfade_chunk->link;
821 crossfade_sample = crossfade_extra / 2;
823 /* Truncate fade out duration if necessary. */
824 else if (crossfade_rem < crossfade_need)
826 size_t crossfade_short = crossfade_need - crossfade_rem;
827 if (fade_out_rem >= crossfade_short)
828 fade_out_rem -= crossfade_short;
829 else
831 fade_out_delay -= crossfade_short - fade_out_rem;
832 fade_out_rem = 0;
836 /* Get also fade in duration and delays from settings. */
837 crossfade_fade_in_total =
838 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_duration * 4;
839 crossfade_fade_in_rem = crossfade_fade_in_total;
841 fade_in_delay =
842 NATIVE_FREQUENCY * global_settings.crossfade_fade_in_delay * 4;
844 crossfade_process_buffer(fade_in_delay, fade_out_delay, fade_out_rem);
847 /* Returns the number of bytes _NOT_ mixed */
848 static size_t crossfade_mix(int factor, const char *buf, size_t length)
850 const int16_t *input_buf = (const int16_t *)buf;
851 int16_t *output_buf = (int16_t *)(crossfade_chunk->addr);
852 int16_t *chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
853 output_buf = &output_buf[crossfade_sample];
854 int32_t sample;
856 while (length)
858 /* fade left and right channel at once to keep buffer alignment */
859 int i;
860 for (i = 0; i < 2; i++)
862 sample = *input_buf++;
863 sample = ((sample * factor) >> 8) + *output_buf;
864 *output_buf++ = clip_sample_16(sample);
867 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
869 if (output_buf >= chunk_end)
871 crossfade_chunk = crossfade_chunk->link;
872 if (!crossfade_chunk)
873 return length;
874 output_buf = (int16_t *)crossfade_chunk->addr;
875 chunk_end = SKIPBYTES(output_buf, crossfade_chunk->size);
878 crossfade_sample = output_buf - (int16_t *)crossfade_chunk->addr;
879 return 0;
882 static void flush_crossfade(char *buf, size_t length)
884 if (length)
886 if (crossfade_fade_in_rem)
888 size_t samples;
889 int16_t *input_buf;
891 /* Fade factor for this packet */
892 int factor =
893 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
894 crossfade_fade_in_total;
895 /* Bytes to fade */
896 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
898 /* We _will_ fade this many bytes */
899 crossfade_fade_in_rem -= fade_rem;
901 if (crossfade_chunk)
903 /* Mix the data */
904 size_t fade_total = fade_rem;
905 fade_rem = crossfade_mix(factor, buf, fade_rem);
906 length -= fade_total - fade_rem;
907 buf += fade_total - fade_rem;
908 if (!length)
909 return;
912 samples = fade_rem / 2;
913 input_buf = (int16_t *)buf;
914 /* Fade remaining samples in place */
915 while (samples--)
917 int32_t sample = *input_buf;
918 *input_buf++ = (sample * factor) >> 8;
922 if (crossfade_chunk)
924 /* Mix the data */
925 size_t mix_total = length;
926 length = crossfade_mix(256, buf, length);
927 buf += mix_total - length;
928 if (!length)
929 return;
932 /* Flush samples to the buffer */
933 while (!prepare_insert(length))
934 sleep(1);
935 while (length > 0)
937 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
938 if (NEED_FLUSH(pcmbuffer_index))
940 commit_chunk();
941 pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
943 size_t copy_n = MIN(length, pcmbuf_size - pcmbuffer_index);
944 memcpy(&pcmbuffer[pcmbuffer_index], buf, copy_n);
945 buf += copy_n;
946 pcmbuffer_fillpos += copy_n;
947 length -= copy_n;
952 static void pcmbuf_finish_crossfade_enable(void)
954 /* Copy the pending setting over now */
955 crossfade_enabled = crossfade_enable_request;
957 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
958 /* If crossfading, try to keep the buffer full other than 1 second */
959 (pcmbuf_size - (NATIVE_FREQUENCY * 4 * 1)) :
960 /* Otherwise, just use the default */
961 PCMBUF_WATERMARK;
964 bool pcmbuf_is_crossfade_active(void)
966 return crossfade_active || crossfade_track_change_started;
969 void pcmbuf_request_crossfade_enable(bool on_off)
971 /* Next setting to be used, not applied now */
972 crossfade_enable_request = on_off;
975 bool pcmbuf_is_same_size(void)
977 /* if pcmbuffer is NULL, then not set up yet even once so always */
978 bool same_size = pcmbuffer ?
979 (get_next_required_pcmbuf_size() == pcmbuf_size) : true;
981 /* no buffer change needed, so finish crossfade setup now */
982 if (same_size)
983 pcmbuf_finish_crossfade_enable();
985 return same_size;
987 #endif /* HAVE_CROSSFADE */
990 /* Voice */
992 /* Returns pcm buffer usage in percents (0 to 100). */
993 static int pcmbuf_usage(void)
995 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
998 static int pcmbuf_mix_free(void)
1000 if (mix_chunk)
1002 size_t my_mix_end =
1003 (size_t)&((int16_t *)mix_chunk->addr)[pcmbuf_mix_sample];
1004 size_t my_write_pos = (size_t)&pcmbuffer[pcmbuffer_pos];
1005 if (my_write_pos < my_mix_end)
1006 my_write_pos += pcmbuf_size;
1007 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1009 return 100;
1012 void *pcmbuf_request_voice_buffer(int *count)
1014 /* A get-it-to-work-for-now hack (audio status could change by
1015 completion) */
1016 if (audio_status() & AUDIO_STATUS_PLAY)
1018 if (read_chunk == NULL)
1020 return NULL;
1022 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
1023 (mix_chunk || read_chunk->link))
1025 *count = MIN(*count, PCMBUF_MIX_CHUNK/4);
1026 return voicebuf;
1028 else
1030 return NULL;
1033 else
1035 return pcmbuf_request_buffer(count);
1039 void pcmbuf_write_voice_complete(int count)
1041 /* A get-it-to-work-for-now hack (audio status could have changed) */
1042 if (!(audio_status() & AUDIO_STATUS_PLAY))
1044 pcmbuf_write_complete(count);
1045 return;
1048 int16_t *ibuf = (int16_t *)voicebuf;
1049 int16_t *obuf;
1050 size_t chunk_samples;
1052 if (mix_chunk == NULL && read_chunk != NULL)
1054 mix_chunk = read_chunk->link;
1055 /* Start 1/8s into the next chunk */
1056 pcmbuf_mix_sample = NATIVE_FREQUENCY * 4 / 16;
1059 if (!mix_chunk)
1060 return;
1062 obuf = (int16_t *)mix_chunk->addr;
1063 chunk_samples = mix_chunk->size / sizeof (int16_t);
1065 count <<= 1;
1067 while (count-- > 0)
1069 int32_t sample = *ibuf++;
1071 if (pcmbuf_mix_sample >= chunk_samples)
1073 mix_chunk = mix_chunk->link;
1074 if (!mix_chunk)
1075 return;
1076 pcmbuf_mix_sample = 0;
1077 obuf = mix_chunk->addr;
1078 chunk_samples = mix_chunk->size / 2;
1080 sample += obuf[pcmbuf_mix_sample] >> 2;
1081 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1086 /* Debug menu, other metrics */
1088 /* Amount of bytes left in the buffer. */
1089 size_t pcmbuf_free(void)
1091 if (read_chunk != NULL)
1093 void *read = read_chunk->addr;
1094 void *write = &pcmbuffer[pcmbuffer_pos + pcmbuffer_fillpos];
1095 if (read < write)
1096 return (size_t)(read - write) + pcmbuf_size;
1097 else
1098 return (size_t) (read - write);
1100 return pcmbuf_size;
1103 size_t pcmbuf_get_bufsize(void)
1105 return pcmbuf_size;
1108 int pcmbuf_used_descs(void)
1110 struct chunkdesc *temp = read_chunk;
1111 unsigned int i = 0;
1112 while (temp) {
1113 temp = temp->link;
1114 i++;
1116 return i;
1119 int pcmbuf_descs(void)
1121 return NUM_CHUNK_DESCS(pcmbuf_size);
1124 #ifdef ROCKBOX_HAS_LOGF
1125 unsigned char * pcmbuf_get_meminfo(size_t *length)
1127 *length = pcmbuf_bufend - pcmbuffer;
1128 return pcmbuffer;
1130 #endif
1133 /* Misc */
1135 bool pcmbuf_is_lowdata(void)
1137 if (!pcm_is_playing() || pcm_is_paused()
1138 #ifdef HAVE_CROSSFADE
1139 || pcmbuf_is_crossfade_active()
1140 #endif
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 = read_chunk != NULL && read_chunk->link != NULL;
1179 int i;
1181 bufend = SKIPBYTES((int16_t *)pcmbuffer, 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 pcmbuffer */
1219 bufstart = (int16_t *)pcmbuffer;
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 *)pcmbuffer;
1237 sample = mix ? *bufptr : 0;
1238 *bufptr++ = clip_sample_16(sample + amp);
1239 if (bufptr >= bufend)
1240 bufptr = (int16_t *)pcmbuffer;
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 */