1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 ****************************************************************************/
29 #include "codec_thread.h"
31 /* Define LOGF_ENABLE to enable logf output in this file */
32 /*#define LOGF_ENABLE*/
34 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
40 #include "voice_thread.h"
43 #define PCMBUF_TARGET_CHUNK 32768 /* This is the target fill size of chunks
45 #define PCMBUF_MINAVG_CHUNK 24576 /* This is the minimum average size of
46 chunks on the pcm buffer (or we run out
47 of buffer descriptors, which is
49 #define PCMBUF_MIN_CHUNK 4096 /* We try to never feed a chunk smaller than
51 #define CROSSFADE_BUFSIZE 8192 /* Size of the crossfade buffer */
52 #define AUX_BUFSIZE 512 /* Size of the aux buffer; can be 512 if no
53 resampling or timestretching is allowed in
54 the aux channel, must be 2048 otherwise */
56 /* number of bytes played per second (sample rate * 2 channels * 2 bytes/sample) */
57 #define BYTERATE (NATIVE_FREQUENCY * 4)
60 /* Keep watermark high for iPods at least (2s) */
61 #define PCMBUF_WATERMARK (BYTERATE * 2)
63 #define PCMBUF_WATERMARK (BYTERATE / 4) /* 0.25 seconds */
66 /* Structure we can use to queue pcm chunks in memory to be played
67 * by the driver code. */
72 struct chunkdesc
* link
;
73 /* true if last chunk in the track */
77 #define NUM_CHUNK_DESCS(bufsize) \
78 ((bufsize) / PCMBUF_MINAVG_CHUNK)
80 /* Size of the PCM buffer. */
81 static size_t pcmbuf_size IDATA_ATTR
= 0;
82 static char *pcmbuf_bufend IDATA_ATTR
;
83 static char *pcmbuffer IDATA_ATTR
;
84 /* Current PCM buffer write index. */
85 static size_t pcmbuffer_pos IDATA_ATTR
;
86 /* Amount pcmbuffer_pos will be increased.*/
87 static size_t pcmbuffer_fillpos IDATA_ATTR
;
89 /* Gapless playback */
90 static bool track_transition IDATA_ATTR
;
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
;
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
;
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
;
134 /* Helpful macros for use in conditionals this assumes some of the above
135 * static variable names */
136 #define COMMIT_IF_NEEDED if(pcmbuffer_fillpos > PCMBUF_TARGET_CHUNK || \
137 (pcmbuffer_pos + pcmbuffer_fillpos) >= pcmbuf_size) commit_chunk(false)
138 #define LOW_DATA(quarter_secs) \
139 (pcmbuf_unplayed_bytes < NATIVE_FREQUENCY * quarter_secs)
141 #ifdef HAVE_CROSSFADE
142 static void crossfade_start(void);
143 static void write_to_crossfade(size_t length
);
144 static void pcmbuf_finish_crossfade_enable(void);
148 /**************************************/
150 /* define this to show detailed chunkdesc usage information on the sim console */
151 /*#define DESC_DEBUG*/
157 static struct chunkdesc
*first_desc
;
158 static bool show_desc_in_use
= false;
159 #define DISPLAY_DESC(caller) while(!show_desc(caller))
160 #define DESC_IDX(desc) (desc ? desc - first_desc : -1)
161 #define SHOW_DESC(desc) if(DESC_IDX(desc)==-1) DEBUGF("--"); \
162 else DEBUGF("%02d", DESC_IDX(desc))
163 #define SHOW_DESC_LINK(desc) if(desc){SHOW_DESC(desc->link);DEBUGF(" ");} \
165 #define SHOW_DETAIL(desc) DEBUGF(":");SHOW_DESC(desc); DEBUGF(">"); \
167 #define SHOW_POINT(tag,desc) DEBUGF("%s",tag);SHOW_DETAIL(desc)
168 #define SHOW_NUM(num,desc) DEBUGF("%02d>",num);SHOW_DESC_LINK(desc)
170 static bool show_desc(char *caller
)
172 if (show_desc_in_use
) return false;
173 show_desc_in_use
= true;
174 DEBUGF("%-14s\t", caller
);
175 SHOW_POINT("r", read_chunk
);
176 SHOW_POINT("re", read_end_chunk
);
178 SHOW_POINT("w", write_chunk
);
179 SHOW_POINT("we", write_end_chunk
);
182 for (i
= 0; i
< pcmbuf_descs(); i
++)
184 SHOW_NUM(i
, (first_desc
+ i
));
185 if (i
%10 == 9) DEBUGF("\n");
188 show_desc_in_use
= false;
192 #define DISPLAY_DESC(caller) do{}while(0)
196 /** Accept new PCM data */
198 /* Commit PCM buffer samples as a new chunk for playback */
199 static void commit_chunk(bool flush_next_time
)
201 if (!pcmbuffer_fillpos
)
204 /* Never use the last buffer descriptor */
205 while (write_chunk
== write_end_chunk
) {
206 /* If this happens, something is being stupid */
207 if (!pcm_is_playing()) {
208 logf("commit_chunk error");
211 /* Let approximately one chunk of data playback */
212 sleep(HZ
* PCMBUF_TARGET_CHUNK
/ BYTERATE
);
215 /* commit the chunk */
217 register size_t size
= pcmbuffer_fillpos
;
218 /* Grab the next description to write, and change the write pointer */
219 register struct chunkdesc
*pcmbuf_current
= write_chunk
;
220 write_chunk
= pcmbuf_current
->link
;
221 /* Fill in the values in the new buffer chunk */
222 pcmbuf_current
->addr
= &pcmbuffer
[pcmbuffer_pos
];
223 pcmbuf_current
->size
= size
;
224 pcmbuf_current
->end_of_track
= false;
225 pcmbuf_current
->link
= NULL
;
227 if (read_chunk
!= NULL
)
231 /* Flush! Discard all data after the currently playing chunk,
232 and make the current chunk play next */
233 logf("commit_chunk: flush");
234 write_end_chunk
->link
= read_chunk
->link
;
235 read_chunk
->link
= pcmbuf_current
;
236 while (write_end_chunk
->link
)
238 write_end_chunk
= write_end_chunk
->link
;
239 pcmbuf_unplayed_bytes
-= write_end_chunk
->size
;
242 /* If there is already a read buffer setup, add to it */
244 read_end_chunk
->link
= pcmbuf_current
;
248 /* Otherwise create the buffer */
249 read_chunk
= pcmbuf_current
;
252 /* If flush_next_time is true, then the current chunk will be thrown out
253 * and the next chunk to be committed will be the next to be played.
254 * This is used to empty the PCM buffer for a track change. */
255 flush_pcmbuf
= flush_next_time
;
257 /* This is now the last buffer to read */
258 read_end_chunk
= pcmbuf_current
;
260 /* Update bytes counters */
261 pcmbuf_unplayed_bytes
+= size
;
263 pcmbuffer_pos
+= size
;
264 if (pcmbuffer_pos
>= pcmbuf_size
)
265 pcmbuffer_pos
-= pcmbuf_size
;
267 pcmbuffer_fillpos
= 0;
268 DISPLAY_DESC("commit_chunk");
271 /* Set priority of the codec thread */
272 #ifdef HAVE_PRIORITY_SCHEDULING
274 * expects pcm_fill_state in tenth-% units (e.g. full pcm buffer is 10) */
275 static void boost_codec_thread(int pcm_fill_state
)
277 static const int prios
[11] = {
278 PRIORITY_PLAYBACK_MAX
, /* 0 - 10% */
279 PRIORITY_PLAYBACK_MAX
+1, /* 10 - 20% */
280 PRIORITY_PLAYBACK_MAX
+3, /* 20 - 30% */
281 PRIORITY_PLAYBACK_MAX
+5, /* 30 - 40% */
282 PRIORITY_PLAYBACK_MAX
+7, /* 40 - 50% */
283 PRIORITY_PLAYBACK_MAX
+8, /* 50 - 60% */
284 PRIORITY_PLAYBACK_MAX
+9, /* 60 - 70% */
285 /* raiseing priority above 70% shouldn't be needed */
286 PRIORITY_PLAYBACK
, /* 70 - 80% */
287 PRIORITY_PLAYBACK
, /* 80 - 90% */
288 PRIORITY_PLAYBACK
, /* 90 -100% */
289 PRIORITY_PLAYBACK
, /* 100% */
291 int new_prio
= prios
[pcm_fill_state
];
293 /* Keep voice and codec threads at the same priority or else voice
294 * will starve if the codec thread's priority is boosted. */
295 if (new_prio
!= codec_thread_priority
)
297 codec_thread_set_priority(new_prio
);
298 voice_thread_set_priority(new_prio
);
299 codec_thread_priority
= new_prio
;
303 #define boost_codec_thread(pcm_fill_state) do{}while(0)
304 #endif /* HAVE_PRIORITY_SCHEDULING */
306 /* Return true if the PCM buffer is able to receive new data.
307 * Also maintain buffer level above the watermark. */
308 static bool prepare_insert(size_t length
)
310 if (low_latency_mode
)
313 if (!LOW_DATA(1) && pcm_is_playing())
317 /* Need to save PCMBUF_MIN_CHUNK to prevent wrapping overwriting */
318 if (pcmbuf_free() < length
+ PCMBUF_MIN_CHUNK
)
321 /* Maintain the buffer level above the watermark */
322 if (pcm_is_playing())
324 /* Only codec thread initiates boost - voice boosts the cpu when playing
327 if (is_codec_thread())
328 #endif /* SIMULATOR */
330 /* boost cpu if necessary */
331 if (pcmbuf_unplayed_bytes
< pcmbuf_watermark
)
333 boost_codec_thread(pcmbuf_unplayed_bytes
*10/pcmbuf_size
);
336 #ifdef HAVE_CROSSFADE
337 /* Disable crossfade if < .5s of audio */
340 crossfade_active
= false;
344 else /* pcm_is_playing */
346 /* Boost CPU for pre-buffer */
349 /* If pre-buffered to the watermark, start playback */
353 if (pcmbuf_unplayed_bytes
> pcmbuf_watermark
)
356 logf("pcm starting");
357 if (!(audio_status() & AUDIO_STATUS_PAUSE
))
365 /* Request space in the buffer for writing output samples */
366 void *pcmbuf_request_buffer(int *count
)
368 #ifdef HAVE_CROSSFADE
369 /* we're going to crossfade to a new track, which is now on its way */
370 if (crossfade_track_change_started
)
373 /* crossfade has begun, put the new track samples in fadebuf */
374 if (crossfade_active
)
376 *count
= MIN(*count
, CROSSFADE_BUFSIZE
/4);
381 /* if possible, reserve room in the PCM buffer for new samples */
383 if(prepare_insert(*count
<< 2))
385 size_t pcmbuffer_index
= pcmbuffer_pos
+ pcmbuffer_fillpos
;
386 if (pcmbuf_size
- pcmbuffer_index
>= PCMBUF_MIN_CHUNK
)
388 /* Usual case, there's space here */
389 return &pcmbuffer
[pcmbuffer_index
];
393 /* Wrap the buffer, the new samples go at the beginning */
396 return &pcmbuffer
[0];
400 /* PCM buffer not ready to receive new data yet */
404 /* Handle new samples to the buffer */
405 void pcmbuf_write_complete(int count
)
407 size_t length
= (size_t)(unsigned int)count
<< 2;
408 #ifdef HAVE_CROSSFADE
409 if (crossfade_active
)
410 write_to_crossfade(length
);
414 pcmbuffer_fillpos
+= length
;
422 static inline void init_pcmbuffers(void)
425 first_desc
= write_chunk
;
427 struct chunkdesc
*next
= write_chunk
;
429 write_end_chunk
= write_chunk
;
430 while ((void *)next
< (void *)pcmbuf_bufend
) {
431 write_end_chunk
->link
=next
;
432 write_end_chunk
=next
;
435 DISPLAY_DESC("init");
438 static size_t get_next_required_pcmbuf_size(void)
442 #ifdef HAVE_CROSSFADE
443 if (crossfade_enable_request
)
444 seconds
+= global_settings
.crossfade_fade_out_delay
+
445 global_settings
.crossfade_fade_out_duration
;
449 /* Buffer has to be at least 2s long. */
452 logf("pcmbuf len: %ld", (long)seconds
);
453 return seconds
* BYTERATE
;
456 /* Initialize the pcmbuffer the structure looks like this:
457 * ...|---------PCMBUF---------|FADEBUF|VOICEBUF|DESCS|... */
458 size_t pcmbuf_init(unsigned char *bufend
)
460 pcmbuf_bufend
= bufend
;
461 pcmbuf_size
= get_next_required_pcmbuf_size();
462 write_chunk
= (struct chunkdesc
*)pcmbuf_bufend
-
463 NUM_CHUNK_DESCS(pcmbuf_size
);
464 voicebuf
= (char *)write_chunk
- AUX_BUFSIZE
;
465 #ifdef HAVE_CROSSFADE
466 fadebuf
= voicebuf
- CROSSFADE_BUFSIZE
;
467 pcmbuffer
= fadebuf
- pcmbuf_size
;
469 pcmbuffer
= voicebuf
- pcmbuf_size
;
474 #ifdef HAVE_CROSSFADE
475 pcmbuf_finish_crossfade_enable();
477 pcmbuf_watermark
= PCMBUF_WATERMARK
;
482 return pcmbuf_bufend
- pcmbuffer
;
487 void pcmbuf_monitor_track_change(bool monitor
)
491 if (last_chunksize
!= 0)
493 /* If monitoring, wait until this track runs out. Place in
494 currently playing chunk. If not, cancel notification. */
495 track_transition
= monitor
;
496 read_end_chunk
->end_of_track
= monitor
;
500 /* Post now if PCM stopped and last buffer was sent. */
501 track_transition
= false;
503 audio_post_track_change(false);
509 void pcmbuf_start_track_change(bool auto_skip
)
511 bool crossfade
= false;
512 #ifdef HAVE_CROSSFADE
513 /* Determine whether this track change needs to crossfade */
514 if(crossfade_enabled
&& !pcmbuf_is_crossfade_active())
516 switch(global_settings
.crossfade
)
518 case CROSSFADE_ENABLE_AUTOSKIP
:
519 crossfade
= auto_skip
;
521 case CROSSFADE_ENABLE_MANSKIP
:
522 crossfade
= !auto_skip
;
524 case CROSSFADE_ENABLE_SHUFFLE
:
525 crossfade
= global_settings
.playlist_shuffle
;
527 case CROSSFADE_ENABLE_SHUFFLE_OR_MANSKIP
:
528 crossfade
= global_settings
.playlist_shuffle
|| !auto_skip
;
530 case CROSSFADE_ENABLE_ALWAYS
:
537 if (!auto_skip
|| crossfade
)
538 /* manual skip or crossfade */
541 { logf(" crossfade track change"); }
543 { logf(" manual track change"); }
547 /* Cancel any pending automatic gapless transition */
548 pcmbuf_monitor_track_change(false);
550 /* Notify the wps that the track change starts now */
551 audio_post_track_change(false);
553 /* Can't do two crossfades at once and, no fade if pcm is off now */
555 #ifdef HAVE_CROSSFADE
556 pcmbuf_is_crossfade_active() ||
565 /* Not enough data, or not crossfading, flush the old data instead */
566 if (LOW_DATA(2) || !crossfade
|| low_latency_mode
)
570 #ifdef HAVE_CROSSFADE
573 /* Don't enable mix mode when skipping tracks manually. */
574 crossfade_mixmode
= auto_skip
&&
575 global_settings
.crossfade_fade_out_mixmode
;
577 crossfade_auto_skip
= auto_skip
;
579 crossfade_track_change_started
= crossfade
;
584 /* Keep trigger outside the play lock or HW FIFO underruns can happen
585 since frequency scaling is *not* always fast */
588 else /* automatic and not crossfading, so do gapless track change */
590 /* The codec is moving on to the next track, but the current track will
591 * continue to play. Set a flag to make sure the elapsed time of the
592 * current track will be updated properly, and mark the current chunk
593 * as the last one in the track. */
594 logf(" gapless track change");
595 pcmbuf_monitor_track_change(true);
602 /* PCM driver callback
603 * This function has 3 major logical parts (separated by brackets both for
604 * readability and variable scoping). The first part performs the
605 * operations related to finishing off the last chunk we fed to the DMA.
606 * The second part detects the end of playlist condition when the PCM
607 * buffer is empty except for uncommitted samples. Then they are committed
608 * and sent to the PCM driver for playback. The third part performs the
609 * operations involved in sending a new chunk to the DMA. */
610 static void pcmbuf_pcm_callback(unsigned char** start
, size_t* size
) ICODE_ATTR
;
611 static void pcmbuf_pcm_callback(unsigned char** start
, size_t* size
)
614 struct chunkdesc
*pcmbuf_current
= read_chunk
;
615 /* Take the finished chunk out of circulation */
616 read_chunk
= pcmbuf_current
->link
;
618 /* if during a track transition, update the elapsed time in ms */
619 if (track_transition
)
620 audio_pcmbuf_position_callback(last_chunksize
* 1000 / BYTERATE
);
622 /* if last chunk in the track, stop updates and notify audio thread */
623 if (pcmbuf_current
->end_of_track
)
625 track_transition
= false;
626 audio_post_track_change(true);
629 /* Put the finished chunk back into circulation */
630 write_end_chunk
->link
= pcmbuf_current
;
631 write_end_chunk
= pcmbuf_current
;
633 /* If we've read over the mix chunk while it's still mixing there */
634 if (pcmbuf_current
== mix_chunk
)
637 #ifdef HAVE_CROSSFADE
638 /* If we've read over the crossfade chunk while it's still fading */
639 if (pcmbuf_current
== crossfade_chunk
)
640 crossfade_chunk
= read_chunk
;
645 /* Commit last samples at end of playlist */
646 if (pcmbuffer_fillpos
&& !read_chunk
)
648 logf("pcmbuf_pcm_callback: commit last samples");
654 /* Send the new chunk to the DMA */
657 last_chunksize
= read_chunk
->size
;
658 pcmbuf_unplayed_bytes
-= last_chunksize
;
659 *size
= last_chunksize
;
660 *start
= read_chunk
->addr
;
665 logf("pcmbuf_pcm_callback: no more chunks");
671 DISPLAY_DESC("callback");
675 void pcmbuf_play_start(void)
677 if (!pcm_is_playing() && pcmbuf_unplayed_bytes
&& read_chunk
!= NULL
)
679 logf("pcmbuf_play_start");
680 last_chunksize
= read_chunk
->size
;
681 pcmbuf_unplayed_bytes
-= last_chunksize
;
682 pcm_play_data(pcmbuf_pcm_callback
,
683 read_chunk
->addr
, last_chunksize
);
687 void pcmbuf_play_stop(void)
689 logf("pcmbuf_play_stop");
692 pcmbuf_unplayed_bytes
= 0;
695 write_end_chunk
->link
= read_chunk
;
696 write_end_chunk
= read_end_chunk
;
697 read_chunk
= read_end_chunk
= NULL
;
700 pcmbuffer_fillpos
= 0;
701 #ifdef HAVE_CROSSFADE
702 crossfade_track_change_started
= false;
703 crossfade_active
= false;
705 track_transition
= false;
706 flush_pcmbuf
= false;
707 DISPLAY_DESC("play_stop");
709 /* Can unboost the codec thread here no matter who's calling,
710 * pretend full pcm buffer to unboost */
711 boost_codec_thread(10);
714 void pcmbuf_pause(bool pause
)
716 logf("pcmbuf_pause: %s", pause
?"pause":"play");
717 if (pcm_is_playing())
718 pcm_play_pause(!pause
);
726 /* Clip sample to signed 16 bit range */
727 static inline int32_t clip_sample_16(int32_t sample
)
729 if ((int16_t)sample
!= sample
)
730 sample
= 0x7fff ^ (sample
>> 31);
734 #ifdef HAVE_CROSSFADE
735 /* Find the chunk that's (length) deep in the list. Return the position within
736 * the chunk, and leave the chunkdesc pointer pointing to the chunk. */
737 static size_t find_chunk(size_t length
, struct chunkdesc
**chunk
)
739 while (*chunk
&& length
>= (*chunk
)->size
)
741 length
-= (*chunk
)->size
;
742 *chunk
= (*chunk
)->link
;
747 /* Returns the number of bytes _NOT_ mixed/faded */
748 static size_t crossfade_mix_fade(int factor
, size_t length
, const char *buf
,
749 size_t *out_sample
, struct chunkdesc
**out_chunk
)
754 const int16_t *input_buf
= (const int16_t *)buf
;
755 int16_t *output_buf
= (int16_t *)((*out_chunk
)->addr
);
756 int16_t *chunk_end
= SKIPBYTES(output_buf
, (*out_chunk
)->size
);
757 output_buf
= &output_buf
[*out_sample
];
762 /* fade left and right channel at once to keep buffer alignment */
764 for (i
= 0; i
< 2; i
++)
767 /* fade the input buffer and mix into the chunk */
769 sample
= *input_buf
++;
770 sample
= ((sample
* factor
) >> 8) + *output_buf
;
771 *output_buf
++ = clip_sample_16(sample
);
774 /* fade the chunk only */
776 sample
= *output_buf
;
777 *output_buf
++ = (sample
* factor
) >> 8;
781 length
-= 4; /* 2 samples, each 16 bit -> 4 bytes */
783 /* move to next chunk as needed */
784 if (output_buf
>= chunk_end
)
786 *out_chunk
= (*out_chunk
)->link
;
789 output_buf
= (int16_t *)((*out_chunk
)->addr
);
790 chunk_end
= SKIPBYTES(output_buf
, (*out_chunk
)->size
);
793 *out_sample
= output_buf
- (int16_t *)((*out_chunk
)->addr
);
797 /* Initializes crossfader, calculates all necessary parameters and performs
798 * fade-out with the PCM buffer. */
799 static void crossfade_start(void)
801 size_t crossfade_rem
;
802 size_t crossfade_need
;
804 size_t fade_out_delay
;
805 size_t fade_in_delay
;
807 crossfade_track_change_started
= false;
808 /* Reject crossfade if less than .5s of data */
810 logf("crossfade rejected");
815 logf("crossfade_start");
817 crossfade_active
= true;
819 /* Initialize the crossfade buffer size to all of the buffered data that
820 * has not yet been sent to the DMA */
821 crossfade_rem
= pcmbuf_unplayed_bytes
;
822 crossfade_chunk
= read_chunk
->link
;
823 crossfade_sample
= 0;
825 /* Get fade out info from settings. */
826 fade_out_delay
= global_settings
.crossfade_fade_out_delay
* BYTERATE
;
827 fade_out_rem
= global_settings
.crossfade_fade_out_duration
* BYTERATE
;
829 crossfade_need
= fade_out_delay
+ fade_out_rem
;
830 if (crossfade_rem
> crossfade_need
)
832 if (crossfade_auto_skip
)
833 /* Automatic track changes only modify the last part of the buffer,
834 * so find the right chunk and sample to start the crossfade */
836 crossfade_sample
= find_chunk(crossfade_rem
- crossfade_need
,
837 &crossfade_chunk
) / 2;
838 crossfade_rem
= crossfade_need
;
841 /* Manual skips occur immediately, but give time to process */
843 crossfade_rem
-= crossfade_chunk
->size
;
844 crossfade_chunk
= crossfade_chunk
->link
;
847 /* Truncate fade out duration if necessary. */
848 if (crossfade_rem
< crossfade_need
)
850 size_t crossfade_short
= crossfade_need
- crossfade_rem
;
851 if (fade_out_rem
>= crossfade_short
)
852 fade_out_rem
-= crossfade_short
;
855 fade_out_delay
-= crossfade_short
- fade_out_rem
;
859 crossfade_rem
-= fade_out_delay
+ fade_out_rem
;
861 /* Completely process the crossfade fade-out effect with current PCM buffer */
862 if (!crossfade_mixmode
)
864 /* Fade out the specified amount of the already processed audio */
865 size_t total_fade_out
= fade_out_rem
;
866 size_t fade_out_sample
;
867 struct chunkdesc
*fade_out_chunk
= crossfade_chunk
;
869 /* Find the right chunk and sample to start fading out */
870 fade_out_delay
+= crossfade_sample
* 2;
871 fade_out_sample
= find_chunk(fade_out_delay
, &fade_out_chunk
) / 2;
873 while (fade_out_rem
> 0)
875 /* Each 1/10 second of audio will have the same fade applied */
876 size_t block_rem
= MIN(BYTERATE
/ 10, fade_out_rem
);
877 int factor
= (fade_out_rem
<< 8) / total_fade_out
;
879 fade_out_rem
-= block_rem
;
881 crossfade_mix_fade(factor
, block_rem
, NULL
,
882 &fade_out_sample
, &fade_out_chunk
);
885 /* zero out the rest of the buffer */
886 crossfade_mix_fade(0, crossfade_rem
, NULL
,
887 &fade_out_sample
, &fade_out_chunk
);
890 /* Initialize fade-in counters */
891 crossfade_fade_in_total
= global_settings
.crossfade_fade_in_duration
* BYTERATE
;
892 crossfade_fade_in_rem
= crossfade_fade_in_total
;
894 fade_in_delay
= global_settings
.crossfade_fade_in_delay
* BYTERATE
;
896 /* Find the right chunk and sample to start fading in */
897 fade_in_delay
+= crossfade_sample
* 2;
898 crossfade_sample
= find_chunk(fade_in_delay
, &crossfade_chunk
) / 2;
899 logf("crossfade_start done!");
902 /* Perform fade-in of new track */
903 static void write_to_crossfade(size_t length
)
908 if (crossfade_fade_in_rem
)
913 /* Fade factor for this packet */
915 ((crossfade_fade_in_total
- crossfade_fade_in_rem
) << 8) /
916 crossfade_fade_in_total
;
918 size_t fade_rem
= MIN(length
, crossfade_fade_in_rem
);
920 /* We _will_ fade this many bytes */
921 crossfade_fade_in_rem
-= fade_rem
;
926 size_t fade_total
= fade_rem
;
927 fade_rem
= crossfade_mix_fade(factor
, fade_rem
, buf
,
928 &crossfade_sample
, &crossfade_chunk
);
929 length
-= fade_total
- fade_rem
;
930 buf
+= fade_total
- fade_rem
;
935 samples
= fade_rem
/ 2;
936 input_buf
= (int16_t *)buf
;
937 /* Fade remaining samples in place */
940 int32_t sample
= *input_buf
;
941 *input_buf
++ = (sample
* factor
) >> 8;
948 size_t mix_total
= length
;
949 /* A factor of 256 means mix only, no fading */
950 length
= crossfade_mix_fade(256, length
, buf
,
951 &crossfade_sample
, &crossfade_chunk
);
952 buf
+= mix_total
- length
;
957 /* Commit samples to the buffer */
958 while (!prepare_insert(length
))
963 size_t pcmbuffer_index
= pcmbuffer_pos
+ pcmbuffer_fillpos
;
964 size_t copy_n
= MIN(length
, pcmbuf_size
- pcmbuffer_index
);
965 memcpy(&pcmbuffer
[pcmbuffer_index
], buf
, copy_n
);
967 pcmbuffer_fillpos
+= copy_n
;
971 /* if no more fading-in to do, stop the crossfade */
972 if (!(crossfade_fade_in_rem
|| crossfade_chunk
))
973 crossfade_active
= false;
976 static void pcmbuf_finish_crossfade_enable(void)
978 /* Copy the pending setting over now */
979 crossfade_enabled
= crossfade_enable_request
;
981 pcmbuf_watermark
= (crossfade_enabled
&& pcmbuf_size
) ?
982 /* If crossfading, try to keep the buffer full other than 1 second */
983 (pcmbuf_size
- BYTERATE
) :
984 /* Otherwise, just use the default */
988 bool pcmbuf_is_crossfade_active(void)
990 return crossfade_active
|| crossfade_track_change_started
;
993 void pcmbuf_request_crossfade_enable(bool on_off
)
995 /* Next setting to be used, not applied now */
996 crossfade_enable_request
= on_off
;
999 bool pcmbuf_is_same_size(void)
1001 /* if pcmbuffer is NULL, then not set up yet even once so always */
1002 bool same_size
= pcmbuffer
?
1003 (get_next_required_pcmbuf_size() == pcmbuf_size
) : true;
1005 /* no buffer change needed, so finish crossfade setup now */
1007 pcmbuf_finish_crossfade_enable();
1011 #endif /* HAVE_CROSSFADE */
1016 /* Returns pcm buffer usage in percents (0 to 100). */
1017 static int pcmbuf_usage(void)
1019 return pcmbuf_unplayed_bytes
* 100 / pcmbuf_size
;
1022 static int pcmbuf_mix_free(void)
1027 (size_t)&((int16_t *)mix_chunk
->addr
)[pcmbuf_mix_sample
];
1028 size_t my_write_pos
= (size_t)&pcmbuffer
[pcmbuffer_pos
];
1029 if (my_write_pos
< my_mix_end
)
1030 my_write_pos
+= pcmbuf_size
;
1031 return (my_write_pos
- my_mix_end
) * 100 / pcmbuf_unplayed_bytes
;
1036 void *pcmbuf_request_voice_buffer(int *count
)
1038 /* A get-it-to-work-for-now hack (audio status could change by
1040 if (audio_status() & AUDIO_STATUS_PLAY
)
1042 if (read_chunk
== NULL
)
1046 else if (pcmbuf_usage() >= 10 && pcmbuf_mix_free() >= 30 &&
1047 (mix_chunk
|| read_chunk
->link
))
1049 *count
= MIN(*count
, AUX_BUFSIZE
/4);
1059 return pcmbuf_request_buffer(count
);
1063 void pcmbuf_write_voice_complete(int count
)
1065 /* A get-it-to-work-for-now hack (audio status could have changed) */
1066 if (!(audio_status() & AUDIO_STATUS_PLAY
))
1068 pcmbuf_write_complete(count
);
1072 int16_t *ibuf
= (int16_t *)voicebuf
;
1074 size_t chunk_samples
;
1076 if (mix_chunk
== NULL
&& read_chunk
!= NULL
)
1078 mix_chunk
= read_chunk
->link
;
1079 /* Start 1/8s into the next chunk */
1080 pcmbuf_mix_sample
= BYTERATE
/ 16;
1086 obuf
= (int16_t *)mix_chunk
->addr
;
1087 chunk_samples
= mix_chunk
->size
/ sizeof (int16_t);
1093 int32_t sample
= *ibuf
++;
1095 if (pcmbuf_mix_sample
>= chunk_samples
)
1097 mix_chunk
= mix_chunk
->link
;
1100 pcmbuf_mix_sample
= 0;
1101 obuf
= (int16_t *)mix_chunk
->addr
;
1102 chunk_samples
= mix_chunk
->size
/ 2;
1104 sample
+= obuf
[pcmbuf_mix_sample
] >> 2;
1105 obuf
[pcmbuf_mix_sample
++] = clip_sample_16(sample
);
1110 /** Debug menu, other metrics */
1112 /* Amount of bytes left in the buffer. */
1113 size_t pcmbuf_free(void)
1115 if (read_chunk
!= NULL
)
1117 void *read
= (void *)read_chunk
->addr
;
1118 void *write
= &pcmbuffer
[pcmbuffer_pos
+ pcmbuffer_fillpos
];
1120 return (size_t)(read
- write
) + pcmbuf_size
;
1122 return (size_t) (read
- write
);
1124 return pcmbuf_size
- pcmbuffer_fillpos
;
1127 size_t pcmbuf_get_bufsize(void)
1132 int pcmbuf_used_descs(void)
1134 struct chunkdesc
*temp
= read_chunk
;
1143 int pcmbuf_descs(void)
1145 return NUM_CHUNK_DESCS(pcmbuf_size
);
1148 #ifdef ROCKBOX_HAS_LOGF
1149 unsigned char *pcmbuf_get_meminfo(size_t *length
)
1151 *length
= pcmbuf_bufend
- pcmbuffer
;
1159 bool pcmbuf_is_lowdata(void)
1161 if (!pcm_is_playing() || pcm_is_paused()
1162 #ifdef HAVE_CROSSFADE
1163 || pcmbuf_is_crossfade_active()
1169 /* 1 seconds of buffer is low data */
1172 /* under watermark is low data */
1173 return (pcmbuf_unplayed_bytes
< pcmbuf_watermark
);
1177 void pcmbuf_set_low_latency(bool state
)
1179 low_latency_mode
= state
;
1182 unsigned long pcmbuf_get_latency(void)
1184 return (pcmbuf_unplayed_bytes
+ pcm_get_bytes_waiting()) * 1000 / BYTERATE
;
1187 #ifndef HAVE_HARDWARE_BEEP
1188 #define MINIBUF_SAMPLES (NATIVE_FREQUENCY / 1000 * KEYCLICK_DURATION)
1189 #define MINIBUF_SIZE (MINIBUF_SAMPLES*4)
1191 /* Generates a constant square wave sound with a given frequency
1192 in Hertz for a duration in milliseconds. */
1193 void pcmbuf_beep(unsigned int frequency
, size_t duration
, int amplitude
)
1195 unsigned int step
= 0xffffffffu
/ NATIVE_FREQUENCY
* frequency
;
1197 int16_t *bufptr
, *bufstart
, *bufend
;
1199 int nsamples
= NATIVE_FREQUENCY
/ 1000 * duration
;
1200 bool mix
= read_chunk
!= NULL
&& read_chunk
->link
!= NULL
;
1203 bufend
= SKIPBYTES((int16_t *)pcmbuffer
, pcmbuf_size
);
1205 /* Find the insertion point and set bufstart to the start of it */
1208 /* Get the currently playing chunk at the current position. */
1209 bufstart
= (int16_t *)pcm_play_dma_get_peak_buffer(&i
);
1211 /* If above isn't implemented or pcm is stopped, no beepeth. */
1212 if (!bufstart
|| !pcm_is_playing())
1215 /* Give 5ms clearance. */
1216 bufstart
+= BYTERATE
/ 200;
1218 #ifdef HAVE_PCM_DMA_ADDRESS
1219 /* Returned peak addresses are DMA addresses */
1220 bufend
= pcm_dma_addr(bufend
);
1223 /* Wrapped above? */
1224 if (bufstart
>= bufend
)
1225 bufstart
-= pcmbuf_size
;
1227 /* NOTE: On some targets using hardware DMA, cache range flushing may
1228 * be required or the writes may not be picked up by the controller.
1229 * An incremental flush should be done periodically during the mixdown. */
1231 else if (nsamples
<= MINIBUF_SAMPLES
)
1233 static int16_t minibuf
[MINIBUF_SAMPLES
*2] __attribute__((aligned(4)));
1234 /* Use mini buffer */
1236 bufend
= SKIPBYTES(bufstart
, MINIBUF_SIZE
);
1238 else if (!audio_buffer_state_trashed())
1241 bufstart
= (int16_t *)pcmbuffer
;
1251 /* Mix square wave into buffer */
1252 for (i
= 0; i
< nsamples
; ++i
)
1254 int32_t amp
= (phase
>> 31) ^ (int32_t)amplitude
;
1255 sample
= mix
? *bufptr
: 0;
1256 *bufptr
++ = clip_sample_16(sample
+ amp
);
1257 if (bufptr
>= bufend
)
1258 bufptr
= (int16_t *)pcmbuffer
;
1259 sample
= mix
? *bufptr
: 0;
1260 *bufptr
++ = clip_sample_16(sample
+ amp
);
1261 if (bufptr
>= bufend
)
1262 bufptr
= (int16_t *)pcmbuffer
;
1268 #ifdef HAVE_RECORDING
1272 /* Kick off playback if required and it won't interfere */
1273 if (!pcm_is_playing()
1274 #ifdef HAVE_RECORDING
1275 && !pcm_is_recording()
1279 pcm_play_data(NULL
, (unsigned char *)bufstart
, nsamples
* 4);
1283 #ifdef HAVE_RECORDING
1287 #endif /* HAVE_HARDWARE_BEEP */