Gigabeat F can easily manage 60fps in pacbox.
[kugel-rb.git] / apps / pcmbuf.c
blob93ce4266c1e5d3625f1b93c689069177173190c1
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 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
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 CROSSFADE_BUFSIZE 8192 /* Size of the crossfade buffer */
51 #define AUX_BUFSIZE 512 /* Size of the aux buffer; can be 512 if no
52 resampling or timestretching is allowed in
53 the aux channel, must be 2048 otherwise */
55 /* number of bytes played per second (sample rate * 2 channels * 2 bytes/sample) */
56 #define BYTERATE (NATIVE_FREQUENCY * 4)
58 #if MEMORYSIZE > 2
59 /* Keep watermark high for iPods at least (2s) */
60 #define PCMBUF_WATERMARK (BYTERATE * 2)
61 #else
62 #define PCMBUF_WATERMARK (BYTERATE / 4) /* 0.25 seconds */
63 #endif
65 /* Structure we can use to queue pcm chunks in memory to be played
66 * by the driver code. */
67 struct chunkdesc
69 unsigned char *addr;
70 size_t size;
71 struct chunkdesc* link;
72 /* true if last chunk in the track */
73 bool end_of_track;
76 #define NUM_CHUNK_DESCS(bufsize) \
77 ((bufsize) / PCMBUF_MINAVG_CHUNK)
79 /* Size of the PCM buffer. */
80 static size_t pcmbuf_size IDATA_ATTR = 0;
81 static char *pcmbuf_bufend IDATA_ATTR;
82 static char *pcmbuffer IDATA_ATTR;
83 /* Current PCM buffer write index. */
84 static size_t pcmbuffer_pos IDATA_ATTR;
85 /* Amount pcmbuffer_pos will be increased.*/
86 static size_t pcmbuffer_fillpos IDATA_ATTR;
88 /* Gapless playback */
89 static bool end_of_track IDATA_ATTR;
90 bool track_transition IDATA_ATTR;
92 #ifdef HAVE_CROSSFADE
93 /* Crossfade buffer */
94 static char *fadebuf IDATA_ATTR;
96 /* Crossfade related state */
97 static bool crossfade_enabled;
98 static bool crossfade_enable_request;
99 static bool crossfade_mixmode;
100 static bool crossfade_auto_skip;
101 static bool crossfade_active IDATA_ATTR;
102 static bool crossfade_track_change_started IDATA_ATTR;
104 /* Track the current location for processing crossfade */
105 static struct chunkdesc *crossfade_chunk IDATA_ATTR;
106 static size_t crossfade_sample IDATA_ATTR;
108 /* Counters for fading in new data */
109 static size_t crossfade_fade_in_total IDATA_ATTR;
110 static size_t crossfade_fade_in_rem IDATA_ATTR;
111 #endif
113 static struct chunkdesc *read_chunk IDATA_ATTR;
114 static struct chunkdesc *read_end_chunk IDATA_ATTR;
115 static struct chunkdesc *write_chunk IDATA_ATTR;
116 static struct chunkdesc *write_end_chunk IDATA_ATTR;
117 static size_t last_chunksize IDATA_ATTR;
119 static size_t pcmbuf_unplayed_bytes IDATA_ATTR;
120 static size_t pcmbuf_watermark IDATA_ATTR;
122 /* Voice */
123 static char *voicebuf IDATA_ATTR;
124 static struct chunkdesc *mix_chunk IDATA_ATTR;
125 static size_t pcmbuf_mix_sample IDATA_ATTR;
127 static bool low_latency_mode = false;
128 static bool flush_pcmbuf = false;
130 #ifdef HAVE_PRIORITY_SCHEDULING
131 static int codec_thread_priority = PRIORITY_PLAYBACK;
132 #endif
134 extern unsigned int codec_thread_id;
136 /* Helpful macros for use in conditionals this assumes some of the above
137 * static variable names */
138 #define COMMIT_IF_NEEDED if(pcmbuffer_fillpos > PCMBUF_TARGET_CHUNK || \
139 (pcmbuffer_pos + pcmbuffer_fillpos) >= pcmbuf_size) commit_chunk(false)
140 #define LOW_DATA(quarter_secs) \
141 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
143 #ifdef HAVE_CROSSFADE
144 static void crossfade_start(void);
145 static void write_to_crossfade(size_t length);
146 static void pcmbuf_finish_crossfade_enable(void);
147 #endif
150 /**************************************/
152 /* define this to show detailed chunkdesc usage information on the sim console */
153 /*#define DESC_DEBUG*/
155 #ifndef SIMULATOR
156 #undef DESC_DEBUG
157 #endif
158 #ifdef DESC_DEBUG
159 static struct chunkdesc *first_desc;
160 static bool show_desc_in_use = false;
161 #define DISPLAY_DESC(caller) while(!show_desc(caller))
162 #define DESC_IDX(desc) (desc ? desc - first_desc : -1)
163 #define SHOW_DESC(desc) if(DESC_IDX(desc)==-1) DEBUGF("--"); \
164 else DEBUGF("%02d", DESC_IDX(desc))
165 #define SHOW_DESC_LINK(desc) if(desc){SHOW_DESC(desc->link);DEBUGF(" ");} \
166 else DEBUGF("-- ")
167 #define SHOW_DETAIL(desc) DEBUGF(":");SHOW_DESC(desc); DEBUGF(">"); \
168 SHOW_DESC_LINK(desc)
169 #define SHOW_POINT(tag,desc) DEBUGF("%s",tag);SHOW_DETAIL(desc)
170 #define SHOW_NUM(num,desc) DEBUGF("%02d>",num);SHOW_DESC_LINK(desc)
172 static bool show_desc(char *caller)
174 if (show_desc_in_use) return false;
175 show_desc_in_use = true;
176 DEBUGF("%-14s\t", caller);
177 SHOW_POINT("r", read_chunk);
178 SHOW_POINT("re", read_end_chunk);
179 DEBUGF(" ");
180 SHOW_POINT("w", write_chunk);
181 SHOW_POINT("we", write_end_chunk);
182 DEBUGF("\n");
183 int i;
184 for (i = 0; i < pcmbuf_descs(); i++)
186 SHOW_NUM(i, (first_desc + i));
187 if (i%10 == 9) DEBUGF("\n");
189 DEBUGF("\n\n");
190 show_desc_in_use = false;
191 return true;
193 #else
194 #define DISPLAY_DESC(caller) do{}while(0)
195 #endif
198 /** Accept new PCM data */
200 /* Commit PCM buffer samples as a new chunk for playback */
201 static void commit_chunk(bool flush_next_time)
203 if (!pcmbuffer_fillpos)
204 return;
206 /* Never use the last buffer descriptor */
207 while (write_chunk == write_end_chunk) {
208 /* If this happens, something is being stupid */
209 if (!pcm_is_playing()) {
210 logf("commit_chunk error");
211 pcmbuf_play_start();
213 /* Let approximately one chunk of data playback */
214 sleep(HZ * PCMBUF_TARGET_CHUNK / BYTERATE);
217 /* commit the chunk */
219 register size_t size = pcmbuffer_fillpos;
220 /* Grab the next description to write, and change the write pointer */
221 register struct chunkdesc *pcmbuf_current = write_chunk;
222 write_chunk = pcmbuf_current->link;
223 /* Fill in the values in the new buffer chunk */
224 pcmbuf_current->addr = &pcmbuffer[pcmbuffer_pos];
225 pcmbuf_current->size = size;
226 pcmbuf_current->end_of_track = end_of_track;
227 pcmbuf_current->link = NULL;
228 end_of_track = false; /* This is single use only */
230 if (read_chunk != NULL)
232 if (flush_pcmbuf)
234 /* Flush! Discard all data after the currently playing chunk,
235 and make the current chunk play next */
236 logf("commit_chunk: flush");
237 write_end_chunk->link = read_chunk->link;
238 read_chunk->link = pcmbuf_current;
239 while (write_end_chunk->link)
241 write_end_chunk = write_end_chunk->link;
242 pcmbuf_unplayed_bytes -= write_end_chunk->size;
245 /* If there is already a read buffer setup, add to it */
246 else
247 read_end_chunk->link = pcmbuf_current;
249 else
251 /* Otherwise create the buffer */
252 read_chunk = pcmbuf_current;
255 /* If flush_next_time is true, then the current chunk will be thrown out
256 * and the next chunk to be committed will be the next to be played.
257 * This is used to empty the PCM buffer for a track change. */
258 flush_pcmbuf = flush_next_time;
260 /* This is now the last buffer to read */
261 read_end_chunk = pcmbuf_current;
263 /* Update bytes counters */
264 pcmbuf_unplayed_bytes += size;
266 pcmbuffer_pos += size;
267 if (pcmbuffer_pos >= pcmbuf_size)
268 pcmbuffer_pos -= pcmbuf_size;
270 pcmbuffer_fillpos = 0;
271 DISPLAY_DESC("commit_chunk");
274 /* Set priority of the codec thread */
275 #ifdef HAVE_PRIORITY_SCHEDULING
277 * expects pcm_fill_state in tenth-% units (e.g. full pcm buffer is 10) */
278 static void boost_codec_thread(int pcm_fill_state)
280 static const int prios[11] = {
281 PRIORITY_PLAYBACK_MAX, /* 0 - 10% */
282 PRIORITY_PLAYBACK_MAX+1, /* 10 - 20% */
283 PRIORITY_PLAYBACK_MAX+3, /* 20 - 30% */
284 PRIORITY_PLAYBACK_MAX+5, /* 30 - 40% */
285 PRIORITY_PLAYBACK_MAX+7, /* 40 - 50% */
286 PRIORITY_PLAYBACK_MAX+8, /* 50 - 60% */
287 PRIORITY_PLAYBACK_MAX+9, /* 60 - 70% */
288 /* raiseing priority above 70% shouldn't be needed */
289 PRIORITY_PLAYBACK, /* 70 - 80% */
290 PRIORITY_PLAYBACK, /* 80 - 90% */
291 PRIORITY_PLAYBACK, /* 90 -100% */
292 PRIORITY_PLAYBACK, /* 100% */
294 int new_prio = prios[pcm_fill_state];
296 /* Keep voice and codec threads at the same priority or else voice
297 * will starve if the codec thread's priority is boosted. */
298 if (new_prio != codec_thread_priority)
300 thread_set_priority(codec_thread_id, new_prio);
301 voice_thread_set_priority(new_prio);
302 codec_thread_priority = new_prio;
305 #else
306 #define boost_codec_thread(pcm_fill_state) do{}while(0)
307 #endif /* HAVE_PRIORITY_SCHEDULING */
309 /* Return true if the PCM buffer is able to receive new data.
310 * Also maintain buffer level above the watermark. */
311 static bool prepare_insert(size_t length)
313 if (low_latency_mode)
315 /* 1/4s latency. */
316 if (!LOW_DATA(1) && pcm_is_playing())
317 return false;
320 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
321 if (pcmbuf_free() < length + PCMBUF_MIN_CHUNK)
322 return false;
324 /* Maintain the buffer level above the watermark */
325 if (pcm_is_playing())
327 /* Only codec thread initiates boost - voice boosts the cpu when playing
328 a clip */
329 #ifndef SIMULATOR
330 if (thread_get_current() == codec_thread_id)
331 #endif /* SIMULATOR */
333 /* boost cpu if necessary */
334 if (pcmbuf_unplayed_bytes < pcmbuf_watermark)
335 trigger_cpu_boost();
336 boost_codec_thread(pcmbuf_unplayed_bytes*10/pcmbuf_size);
339 #ifdef HAVE_CROSSFADE
340 /* Disable crossfade if < .5s of audio */
341 if (LOW_DATA(2))
343 crossfade_active = false;
345 #endif
347 else /* pcm_is_playing */
349 /* Boost CPU for pre-buffer */
350 trigger_cpu_boost();
352 /* If pre-buffered to the watermark, start playback */
353 #if MEMORYSIZE > 2
354 if (!LOW_DATA(4))
355 #else
356 if (pcmbuf_unplayed_bytes > pcmbuf_watermark)
357 #endif
359 logf("pcm starting");
360 if (!(audio_status() & AUDIO_STATUS_PAUSE))
361 pcmbuf_play_start();
365 return true;
368 /* Request space in the buffer for writing output samples */
369 void *pcmbuf_request_buffer(int *count)
371 #ifdef HAVE_CROSSFADE
372 /* we're going to crossfade to a new track, which is now on its way */
373 if (crossfade_track_change_started)
374 crossfade_start();
376 /* crossfade has begun, put the new track samples in fadebuf */
377 if (crossfade_active)
379 *count = MIN(*count, CROSSFADE_BUFSIZE/4);
380 return fadebuf;
382 else
383 #endif
384 /* if possible, reserve room in the PCM buffer for new samples */
386 if(prepare_insert(*count << 2))
388 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
389 if (pcmbuf_size - pcmbuffer_index >= PCMBUF_MIN_CHUNK)
391 /* Usual case, there's space here */
392 return &pcmbuffer[pcmbuffer_index];
394 else
396 /* Wrap the buffer, the new samples go at the beginning */
397 commit_chunk(false);
398 pcmbuffer_pos = 0;
399 return &pcmbuffer[0];
403 /* PCM buffer not ready to receive new data yet */
404 return NULL;
407 /* Handle new samples to the buffer */
408 void pcmbuf_write_complete(int count)
410 size_t length = (size_t)(unsigned int)count << 2;
411 #ifdef HAVE_CROSSFADE
412 if (crossfade_active)
413 write_to_crossfade(length);
414 else
415 #endif
417 pcmbuffer_fillpos += length;
418 COMMIT_IF_NEEDED;
423 /** Init */
425 static inline void init_pcmbuffers(void)
427 #ifdef DESC_DEBUG
428 first_desc = write_chunk;
429 #endif
430 struct chunkdesc *next = write_chunk;
431 next++;
432 write_end_chunk = write_chunk;
433 while ((void *)next < (void *)pcmbuf_bufend) {
434 write_end_chunk->link=next;
435 write_end_chunk=next;
436 next++;
438 DISPLAY_DESC("init");
441 static size_t get_next_required_pcmbuf_size(void)
443 size_t seconds = 1;
445 #ifdef HAVE_CROSSFADE
446 if (crossfade_enable_request)
447 seconds += global_settings.crossfade_fade_out_delay +
448 global_settings.crossfade_fade_out_duration;
449 #endif
451 #if MEMORYSIZE > 2
452 /* Buffer has to be at least 2s long. */
453 seconds += 2;
454 #endif
455 logf("pcmbuf len: %ld", (long)seconds);
456 return seconds * BYTERATE;
459 /* Initialize the pcmbuffer the structure looks like this:
460 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
461 size_t pcmbuf_init(unsigned char *bufend)
463 pcmbuf_bufend = bufend;
464 pcmbuf_size = get_next_required_pcmbuf_size();
465 write_chunk = (struct chunkdesc *)pcmbuf_bufend -
466 NUM_CHUNK_DESCS(pcmbuf_size);
467 voicebuf = (char *)write_chunk - AUX_BUFSIZE;
468 #ifdef HAVE_CROSSFADE
469 fadebuf = voicebuf - CROSSFADE_BUFSIZE;
470 pcmbuffer = fadebuf - pcmbuf_size;
471 #else
472 pcmbuffer = voicebuf - pcmbuf_size;
473 #endif
475 init_pcmbuffers();
477 #ifdef HAVE_CROSSFADE
478 pcmbuf_finish_crossfade_enable();
479 #else
480 pcmbuf_watermark = PCMBUF_WATERMARK;
481 #endif
483 pcmbuf_play_stop();
485 return pcmbuf_bufend - pcmbuffer;
489 /** Track change */
491 void pcmbuf_start_track_change(bool auto_skip)
493 bool crossfade = false;
494 #ifdef HAVE_CROSSFADE
495 /* Determine whether this track change needs to crossfade */
496 if(crossfade_enabled && !pcmbuf_is_crossfade_active())
498 switch(global_settings.crossfade)
500 case CROSSFADE_ENABLE_AUTOSKIP:
501 crossfade = auto_skip;
502 break;
503 case CROSSFADE_ENABLE_MANSKIP:
504 crossfade = !auto_skip;
505 break;
506 case CROSSFADE_ENABLE_SHUFFLE:
507 crossfade = global_settings.playlist_shuffle;
508 break;
509 case CROSSFADE_ENABLE_SHUFFLE_OR_MANSKIP:
510 crossfade = global_settings.playlist_shuffle || !auto_skip;
511 break;
512 case CROSSFADE_ENABLE_ALWAYS:
513 crossfade = true;
514 break;
517 #endif
519 if (!auto_skip || crossfade)
520 /* manual skip or crossfade */
522 if (crossfade)
523 { logf(" crossfade track change"); }
524 else
525 { logf(" manual track change"); }
527 /* Notify the wps that the track change starts now */
528 audio_post_track_change(false);
530 /* Can't do two crossfades at once and, no fade if pcm is off now */
531 if (
532 #ifdef HAVE_CROSSFADE
533 pcmbuf_is_crossfade_active() ||
534 #endif
535 !pcm_is_playing())
537 pcmbuf_play_stop();
538 return;
541 trigger_cpu_boost();
543 /* Not enough data, or not crossfading, flush the old data instead */
544 if (LOW_DATA(2) || !crossfade || low_latency_mode)
546 commit_chunk(true);
547 return;
550 #ifdef HAVE_CROSSFADE
551 /* Don't enable mix mode when skipping tracks manually. */
552 crossfade_mixmode = auto_skip && global_settings.crossfade_fade_out_mixmode;
554 crossfade_auto_skip = auto_skip;
556 crossfade_track_change_started = crossfade;
557 #endif
559 else /* automatic and not crossfading, so do gapless track change */
561 /* The codec is moving on to the next track, but the current track will
562 * continue to play. Set a flag to make sure the elapsed time of the
563 * current track will be updated properly, and mark the current chunk
564 * as the last one in the track. */
565 logf(" gapless track change");
566 track_transition = true;
567 end_of_track = true;
572 /** Playback */
574 /* PCM driver callback
575 * This function has 3 major logical parts (separated by brackets both for
576 * readability and variable scoping). The first part performs the
577 * operations related to finishing off the last chunk we fed to the DMA.
578 * The second part detects the end of playlist condition when the PCM
579 * buffer is empty except for uncommitted samples. Then they are committed
580 * and sent to the PCM driver for playback. The third part performs the
581 * operations involved in sending a new chunk to the DMA. */
582 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size) ICODE_ATTR;
583 static void pcmbuf_pcm_callback(unsigned char** start, size_t* size)
586 struct chunkdesc *pcmbuf_current = read_chunk;
587 /* Take the finished chunk out of circulation */
588 read_chunk = pcmbuf_current->link;
590 /* if during a track transition, update the elapsed time in ms */
591 if (track_transition)
592 audio_pcmbuf_position_callback(last_chunksize * 1000 / BYTERATE);
594 /* if last chunk in the track, stop updates and notify audio thread */
595 if (pcmbuf_current->end_of_track)
597 track_transition = false;
598 audio_post_track_change(true);
601 /* Put the finished chunk back into circulation */
602 write_end_chunk->link = pcmbuf_current;
603 write_end_chunk = pcmbuf_current;
605 /* If we've read over the mix chunk while it's still mixing there */
606 if (pcmbuf_current == mix_chunk)
607 mix_chunk = NULL;
609 #ifdef HAVE_CROSSFADE
610 /* If we've read over the crossfade chunk while it's still fading */
611 if (pcmbuf_current == crossfade_chunk)
612 crossfade_chunk = read_chunk;
613 #endif
617 /* Commit last samples at end of playlist */
618 if (pcmbuffer_fillpos && !read_chunk)
620 logf("pcmbuf_pcm_callback: commit last samples");
621 commit_chunk(false);
626 /* Send the new chunk to the DMA */
627 if(read_chunk)
629 last_chunksize = read_chunk->size;
630 pcmbuf_unplayed_bytes -= last_chunksize;
631 *size = last_chunksize;
632 *start = read_chunk->addr;
634 else
636 /* No more chunks */
637 logf("pcmbuf_pcm_callback: no more chunks");
638 last_chunksize = 0;
639 *size = 0;
640 *start = NULL;
643 DISPLAY_DESC("callback");
646 /* Force playback */
647 void pcmbuf_play_start(void)
649 if (!pcm_is_playing() && pcmbuf_unplayed_bytes && read_chunk != NULL)
651 logf("pcmbuf_play_start");
652 last_chunksize = read_chunk->size;
653 pcmbuf_unplayed_bytes -= last_chunksize;
654 pcm_play_data(pcmbuf_pcm_callback,
655 read_chunk->addr, last_chunksize);
659 void pcmbuf_play_stop(void)
661 logf("pcmbuf_play_stop");
662 pcm_play_stop();
664 pcmbuf_unplayed_bytes = 0;
665 mix_chunk = NULL;
666 if (read_chunk) {
667 write_end_chunk->link = read_chunk;
668 write_end_chunk = read_end_chunk;
669 read_chunk = read_end_chunk = NULL;
671 pcmbuffer_pos = 0;
672 pcmbuffer_fillpos = 0;
673 #ifdef HAVE_CROSSFADE
674 crossfade_track_change_started = false;
675 crossfade_active = false;
676 #endif
677 end_of_track = false;
678 track_transition = false;
679 flush_pcmbuf = false;
680 DISPLAY_DESC("play_stop");
682 /* Can unboost the codec thread here no matter who's calling,
683 * pretend full pcm buffer to unboost */
684 boost_codec_thread(10);
687 void pcmbuf_pause(bool pause)
689 logf("pcmbuf_pause: %s", pause?"pause":"play");
690 if (pcm_is_playing())
691 pcm_play_pause(!pause);
692 else if (!pause)
693 pcmbuf_play_start();
697 /** Crossfade */
699 /* Clip sample to signed 16 bit range */
700 static inline int32_t clip_sample_16(int32_t sample)
702 if ((int16_t)sample != sample)
703 sample = 0x7fff ^ (sample >> 31);
704 return sample;
707 #ifdef HAVE_CROSSFADE
708 /* Find the chunk that's (length) deep in the list. Return the position within
709 * the chunk, and leave the chunkdesc pointer pointing to the chunk. */
710 static size_t find_chunk(size_t length, struct chunkdesc **chunk)
712 while (*chunk && length >= (*chunk)->size)
714 length -= (*chunk)->size;
715 *chunk = (*chunk)->link;
717 return length;
720 /* Returns the number of bytes _NOT_ mixed/faded */
721 static size_t crossfade_mix_fade(int factor, size_t length, const char *buf,
722 size_t *out_sample, struct chunkdesc **out_chunk)
724 if (length == 0)
725 return 0;
727 const int16_t *input_buf = (const int16_t *)buf;
728 int16_t *output_buf = (int16_t *)((*out_chunk)->addr);
729 int16_t *chunk_end = SKIPBYTES(output_buf, (*out_chunk)->size);
730 output_buf = &output_buf[*out_sample];
731 int32_t sample;
733 while (length)
735 /* fade left and right channel at once to keep buffer alignment */
736 int i;
737 for (i = 0; i < 2; i++)
739 if (input_buf)
740 /* fade the input buffer and mix into the chunk */
742 sample = *input_buf++;
743 sample = ((sample * factor) >> 8) + *output_buf;
744 *output_buf++ = clip_sample_16(sample);
746 else
747 /* fade the chunk only */
749 sample = *output_buf;
750 *output_buf++ = (sample * factor) >> 8;
754 length -= 4; /* 2 samples, each 16 bit -> 4 bytes */
756 /* move to next chunk as needed */
757 if (output_buf >= chunk_end)
759 *out_chunk = (*out_chunk)->link;
760 if (!(*out_chunk))
761 return length;
762 output_buf = (int16_t *)((*out_chunk)->addr);
763 chunk_end = SKIPBYTES(output_buf, (*out_chunk)->size);
766 *out_sample = output_buf - (int16_t *)((*out_chunk)->addr);
767 return 0;
770 /* Initializes crossfader, calculates all necessary parameters and performs
771 * fade-out with the PCM buffer. */
772 static void crossfade_start(void)
774 size_t crossfade_rem;
775 size_t crossfade_need;
776 size_t fade_out_rem;
777 size_t fade_out_delay;
778 size_t fade_in_delay;
780 crossfade_track_change_started = false;
781 /* Reject crossfade if less than .5s of data */
782 if (LOW_DATA(2)) {
783 logf("crossfade rejected");
784 pcmbuf_play_stop();
785 return ;
788 logf("crossfade_start");
789 commit_chunk(false);
790 crossfade_active = true;
792 /* Initialize the crossfade buffer size to all of the buffered data that
793 * has not yet been sent to the DMA */
794 crossfade_rem = pcmbuf_unplayed_bytes;
795 crossfade_chunk = read_chunk->link;
796 crossfade_sample = 0;
798 /* Get fade out info from settings. */
799 fade_out_delay = global_settings.crossfade_fade_out_delay * BYTERATE;
800 fade_out_rem = global_settings.crossfade_fade_out_duration * BYTERATE;
802 crossfade_need = fade_out_delay + fade_out_rem;
803 if (crossfade_rem > crossfade_need)
805 if (crossfade_auto_skip)
806 /* Automatic track changes only modify the last part of the buffer,
807 * so find the right chunk and sample to start the crossfade */
809 crossfade_sample = find_chunk(crossfade_rem - crossfade_need,
810 &crossfade_chunk) / 2;
811 crossfade_rem = crossfade_need;
813 else
814 /* Manual skips occur immediately, but give time to process */
816 crossfade_rem -= crossfade_chunk->size;
817 crossfade_chunk = crossfade_chunk->link;
820 /* Truncate fade out duration if necessary. */
821 if (crossfade_rem < crossfade_need)
823 size_t crossfade_short = crossfade_need - crossfade_rem;
824 if (fade_out_rem >= crossfade_short)
825 fade_out_rem -= crossfade_short;
826 else
828 fade_out_delay -= crossfade_short - fade_out_rem;
829 fade_out_rem = 0;
832 crossfade_rem -= fade_out_delay + fade_out_rem;
834 /* Completely process the crossfade fade-out effect with current PCM buffer */
835 if (!crossfade_mixmode)
837 /* Fade out the specified amount of the already processed audio */
838 size_t total_fade_out = fade_out_rem;
839 size_t fade_out_sample;
840 struct chunkdesc *fade_out_chunk = crossfade_chunk;
842 /* Find the right chunk and sample to start fading out */
843 fade_out_delay += crossfade_sample * 2;
844 fade_out_sample = find_chunk(fade_out_delay, &fade_out_chunk) / 2;
846 while (fade_out_rem > 0)
848 /* Each 1/10 second of audio will have the same fade applied */
849 size_t block_rem = MIN(BYTERATE / 10, fade_out_rem);
850 int factor = (fade_out_rem << 8) / total_fade_out;
852 fade_out_rem -= block_rem;
854 crossfade_mix_fade(factor, block_rem, NULL,
855 &fade_out_sample, &fade_out_chunk);
858 /* zero out the rest of the buffer */
859 crossfade_mix_fade(0, crossfade_rem, NULL,
860 &fade_out_sample, &fade_out_chunk);
863 /* Initialize fade-in counters */
864 crossfade_fade_in_total = global_settings.crossfade_fade_in_duration * BYTERATE;
865 crossfade_fade_in_rem = crossfade_fade_in_total;
867 fade_in_delay = global_settings.crossfade_fade_in_delay * BYTERATE;
869 /* Find the right chunk and sample to start fading in */
870 fade_in_delay += crossfade_sample * 2;
871 crossfade_sample = find_chunk(fade_in_delay, &crossfade_chunk) / 2;
872 logf("crossfade_start done!");
875 /* Perform fade-in of new track */
876 static void write_to_crossfade(size_t length)
878 if (length)
880 char *buf = fadebuf;
881 if (crossfade_fade_in_rem)
883 size_t samples;
884 int16_t *input_buf;
886 /* Fade factor for this packet */
887 int factor =
888 ((crossfade_fade_in_total - crossfade_fade_in_rem) << 8) /
889 crossfade_fade_in_total;
890 /* Bytes to fade */
891 size_t fade_rem = MIN(length, crossfade_fade_in_rem);
893 /* We _will_ fade this many bytes */
894 crossfade_fade_in_rem -= fade_rem;
896 if (crossfade_chunk)
898 /* Mix the data */
899 size_t fade_total = fade_rem;
900 fade_rem = crossfade_mix_fade(factor, fade_rem, buf,
901 &crossfade_sample, &crossfade_chunk);
902 length -= fade_total - fade_rem;
903 buf += fade_total - fade_rem;
904 if (!length)
905 return;
908 samples = fade_rem / 2;
909 input_buf = (int16_t *)buf;
910 /* Fade remaining samples in place */
911 while (samples--)
913 int32_t sample = *input_buf;
914 *input_buf++ = (sample * factor) >> 8;
918 if (crossfade_chunk)
920 /* Mix the data */
921 size_t mix_total = length;
922 /* A factor of 256 means mix only, no fading */
923 length = crossfade_mix_fade(256, length, buf,
924 &crossfade_sample, &crossfade_chunk);
925 buf += mix_total - length;
926 if (!length)
927 return;
930 /* Commit samples to the buffer */
931 while (!prepare_insert(length))
932 sleep(1);
933 while (length > 0)
935 COMMIT_IF_NEEDED;
936 size_t pcmbuffer_index = pcmbuffer_pos + pcmbuffer_fillpos;
937 size_t copy_n = MIN(length, pcmbuf_size - pcmbuffer_index);
938 memcpy(&pcmbuffer[pcmbuffer_index], buf, copy_n);
939 buf += copy_n;
940 pcmbuffer_fillpos += copy_n;
941 length -= copy_n;
944 /* if no more fading-in to do, stop the crossfade */
945 if (!(crossfade_fade_in_rem || crossfade_chunk))
946 crossfade_active = false;
949 static void pcmbuf_finish_crossfade_enable(void)
951 /* Copy the pending setting over now */
952 crossfade_enabled = crossfade_enable_request;
954 pcmbuf_watermark = (crossfade_enabled && pcmbuf_size) ?
955 /* If crossfading, try to keep the buffer full other than 1 second */
956 (pcmbuf_size - BYTERATE) :
957 /* Otherwise, just use the default */
958 PCMBUF_WATERMARK;
961 bool pcmbuf_is_crossfade_active(void)
963 return crossfade_active || crossfade_track_change_started;
966 void pcmbuf_request_crossfade_enable(bool on_off)
968 /* Next setting to be used, not applied now */
969 crossfade_enable_request = on_off;
972 bool pcmbuf_is_same_size(void)
974 /* if pcmbuffer is NULL, then not set up yet even once so always */
975 bool same_size = pcmbuffer ?
976 (get_next_required_pcmbuf_size() == pcmbuf_size) : true;
978 /* no buffer change needed, so finish crossfade setup now */
979 if (same_size)
980 pcmbuf_finish_crossfade_enable();
982 return same_size;
984 #endif /* HAVE_CROSSFADE */
987 /** Voice */
989 /* Returns pcm buffer usage in percents (0 to 100). */
990 static int pcmbuf_usage(void)
992 return pcmbuf_unplayed_bytes * 100 / pcmbuf_size;
995 static int pcmbuf_mix_free(void)
997 if (mix_chunk)
999 size_t my_mix_end =
1000 (size_t)&((int16_t *)mix_chunk->addr)[pcmbuf_mix_sample];
1001 size_t my_write_pos = (size_t)&pcmbuffer[pcmbuffer_pos];
1002 if (my_write_pos < my_mix_end)
1003 my_write_pos += pcmbuf_size;
1004 return (my_write_pos - my_mix_end) * 100 / pcmbuf_unplayed_bytes;
1006 return 100;
1009 void *pcmbuf_request_voice_buffer(int *count)
1011 /* A get-it-to-work-for-now hack (audio status could change by
1012 completion) */
1013 if (audio_status() & AUDIO_STATUS_PLAY)
1015 if (read_chunk == NULL)
1017 return NULL;
1019 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
1020 (mix_chunk || read_chunk->link))
1022 *count = MIN(*count, AUX_BUFSIZE/4);
1023 return voicebuf;
1025 else
1027 return NULL;
1030 else
1032 return pcmbuf_request_buffer(count);
1036 void pcmbuf_write_voice_complete(int count)
1038 /* A get-it-to-work-for-now hack (audio status could have changed) */
1039 if (!(audio_status() & AUDIO_STATUS_PLAY))
1041 pcmbuf_write_complete(count);
1042 return;
1045 int16_t *ibuf = (int16_t *)voicebuf;
1046 int16_t *obuf;
1047 size_t chunk_samples;
1049 if (mix_chunk == NULL && read_chunk != NULL)
1051 mix_chunk = read_chunk->link;
1052 /* Start 1/8s into the next chunk */
1053 pcmbuf_mix_sample = BYTERATE / 16;
1056 if (!mix_chunk)
1057 return;
1059 obuf = (int16_t *)mix_chunk->addr;
1060 chunk_samples = mix_chunk->size / sizeof (int16_t);
1062 count <<= 1;
1064 while (count-- > 0)
1066 int32_t sample = *ibuf++;
1068 if (pcmbuf_mix_sample >= chunk_samples)
1070 mix_chunk = mix_chunk->link;
1071 if (!mix_chunk)
1072 return;
1073 pcmbuf_mix_sample = 0;
1074 obuf = (int16_t *)mix_chunk->addr;
1075 chunk_samples = mix_chunk->size / 2;
1077 sample += obuf[pcmbuf_mix_sample] >> 2;
1078 obuf[pcmbuf_mix_sample++] = clip_sample_16(sample);
1083 /** Debug menu, other metrics */
1085 /* Amount of bytes left in the buffer. */
1086 size_t pcmbuf_free(void)
1088 if (read_chunk != NULL)
1090 void *read = (void *)read_chunk->addr;
1091 void *write = &pcmbuffer[pcmbuffer_pos + pcmbuffer_fillpos];
1092 if (read < write)
1093 return (size_t)(read - write) + pcmbuf_size;
1094 else
1095 return (size_t) (read - write);
1097 return pcmbuf_size - pcmbuffer_fillpos;
1100 size_t pcmbuf_get_bufsize(void)
1102 return pcmbuf_size;
1105 int pcmbuf_used_descs(void)
1107 struct chunkdesc *temp = read_chunk;
1108 unsigned int i = 0;
1109 while (temp) {
1110 temp = temp->link;
1111 i++;
1113 return i;
1116 int pcmbuf_descs(void)
1118 return NUM_CHUNK_DESCS(pcmbuf_size);
1121 #ifdef ROCKBOX_HAS_LOGF
1122 unsigned char *pcmbuf_get_meminfo(size_t *length)
1124 *length = pcmbuf_bufend - pcmbuffer;
1125 return pcmbuffer;
1127 #endif
1130 /** Misc */
1132 bool pcmbuf_is_lowdata(void)
1134 if (!pcm_is_playing() || pcm_is_paused()
1135 #ifdef HAVE_CROSSFADE
1136 || pcmbuf_is_crossfade_active()
1137 #endif
1139 return false;
1141 #if MEMORYSIZE > 2
1142 /* 1 seconds of buffer is low data */
1143 return LOW_DATA(4);
1144 #else
1145 /* under watermark is low data */
1146 return (pcmbuf_unplayed_bytes < pcmbuf_watermark);
1147 #endif
1150 void pcmbuf_set_low_latency(bool state)
1152 low_latency_mode = state;
1155 unsigned long pcmbuf_get_latency(void)
1157 return (pcmbuf_unplayed_bytes + pcm_get_bytes_waiting()) * 1000 / BYTERATE;
1160 #ifndef HAVE_HARDWARE_BEEP
1161 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
1162 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
1164 /* Generates a constant square wave sound with a given frequency
1165 in Hertz for a duration in milliseconds. */
1166 void pcmbuf_beep(unsigned int frequency, size_t duration, int amplitude)
1168 unsigned int step = 0xffffffffu / NATIVE_FREQUENCY * frequency;
1169 int32_t phase = 0;
1170 int16_t *bufptr, *bufstart, *bufend;
1171 int32_t sample;
1172 int nsamples = NATIVE_FREQUENCY / 1000 * duration;
1173 bool mix = read_chunk != NULL && read_chunk->link != NULL;
1174 int i;
1176 bufend = SKIPBYTES((int16_t *)pcmbuffer, pcmbuf_size);
1178 /* Find the insertion point and set bufstart to the start of it */
1179 if (mix)
1181 /* Get the currently playing chunk at the current position. */
1182 bufstart = (int16_t *)pcm_play_dma_get_peak_buffer(&i);
1184 /* If above isn't implemented or pcm is stopped, no beepeth. */
1185 if (!bufstart || !pcm_is_playing())
1186 return;
1188 /* Give 5ms clearance. */
1189 bufstart += BYTERATE / 200;
1191 #ifdef HAVE_PCM_DMA_ADDRESS
1192 /* Returned peak addresses are DMA addresses */
1193 bufend = pcm_dma_addr(bufend);
1194 #endif
1196 /* Wrapped above? */
1197 if (bufstart >= bufend)
1198 bufstart -= pcmbuf_size;
1200 /* NOTE: On some targets using hardware DMA, cache range flushing may
1201 * be required or the writes may not be picked up by the controller.
1202 * An incremental flush should be done periodically during the mixdown. */
1204 else if (nsamples <= MINIBUF_SAMPLES)
1206 static int16_t minibuf[MINIBUF_SAMPLES*2] __attribute__((aligned(4)));
1207 /* Use mini buffer */
1208 bufstart = minibuf;
1209 bufend = SKIPBYTES(bufstart, MINIBUF_SIZE);
1211 else if (!audio_buffer_state_trashed())
1213 /* Use pcmbuffer */
1214 bufstart = (int16_t *)pcmbuffer;
1216 else
1218 /* No place */
1219 return;
1222 bufptr = bufstart;
1224 /* Mix square wave into buffer */
1225 for (i = 0; i < nsamples; ++i)
1227 int32_t amp = (phase >> 31) ^ (int32_t)amplitude;
1228 sample = mix ? *bufptr : 0;
1229 *bufptr++ = clip_sample_16(sample + amp);
1230 if (bufptr >= bufend)
1231 bufptr = (int16_t *)pcmbuffer;
1232 sample = mix ? *bufptr : 0;
1233 *bufptr++ = clip_sample_16(sample + amp);
1234 if (bufptr >= bufend)
1235 bufptr = (int16_t *)pcmbuffer;
1237 phase += step;
1240 pcm_play_lock();
1241 #ifdef HAVE_RECORDING
1242 pcm_rec_lock();
1243 #endif
1245 /* Kick off playback if required and it won't interfere */
1246 if (!pcm_is_playing()
1247 #ifdef HAVE_RECORDING
1248 && !pcm_is_recording()
1249 #endif
1252 pcm_play_data(NULL, (unsigned char *)bufstart, nsamples * 4);
1255 pcm_play_unlock();
1256 #ifdef HAVE_RECORDING
1257 pcm_rec_unlock();
1258 #endif
1260 #endif /* HAVE_HARDWARE_BEEP */