skin_engine: fix scrolling lines with dynamic content
[maemo-rb.git] / apps / voice_thread.c
blob56d67a2284e1c39e6a27527fbb659eec10138e72
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2007 Michael Sevakis
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 <sys/types.h>
22 #include "system.h"
23 #include "thread.h"
24 #include "voice_thread.h"
25 #include "talk.h"
26 #include "dsp.h"
27 #include "audio.h"
28 #include "playback.h"
29 #include "pcmbuf.h"
30 #include "pcm.h"
31 #include "pcm_mixer.h"
32 #include "codecs/libspeex/speex/speex.h"
34 /* Define any of these as "1" and uncomment the LOGF_ENABLE line to log
35 regular and/or timeout messages */
36 #define VOICE_LOGQUEUES 0
37 #define VOICE_LOGQUEUES_SYS_TIMEOUT 0
39 /*#define LOGF_ENABLE*/
40 #include "logf.h"
42 #if VOICE_LOGQUEUES
43 #define LOGFQUEUE logf
44 #else
45 #define LOGFQUEUE(...)
46 #endif
48 #if VOICE_LOGQUEUES_SYS_TIMEOUT
49 #define LOGFQUEUE_SYS_TIMEOUT logf
50 #else
51 #define LOGFQUEUE_SYS_TIMEOUT(...)
52 #endif
54 #ifndef IBSS_ATTR_VOICE_STACK
55 #define IBSS_ATTR_VOICE_STACK IBSS_ATTR
56 #endif
58 /* Minimum priority needs to be a bit elevated since voice has fairly low
59 latency */
60 #define PRIORITY_VOICE (PRIORITY_PLAYBACK-4)
62 #define VOICE_FRAME_SIZE 320 /* Samples / frame */
63 #define VOICE_SAMPLE_RATE 16000 /* Sample rate in HZ */
64 #define VOICE_SAMPLE_DEPTH 16 /* Sample depth in bits */
66 /* Voice thread variables */
67 static unsigned int voice_thread_id = 0;
68 #ifdef CPU_COLDFIRE
69 /* ISR uses any available stack - need a bit more room */
70 #define VOICE_STACK_EXTRA 0x400
71 #else
72 #define VOICE_STACK_EXTRA 0x3c0
73 #endif
74 static long voice_stack[(DEFAULT_STACK_SIZE + VOICE_STACK_EXTRA)/sizeof(long)]
75 IBSS_ATTR_VOICE_STACK;
76 static const char voice_thread_name[] = "voice";
78 /* Voice thread synchronization objects */
79 static struct event_queue voice_queue SHAREDBSS_ATTR;
80 static struct queue_sender_list voice_queue_sender_list SHAREDBSS_ATTR;
81 static int quiet_counter SHAREDDATA_ATTR = 0;
83 /* Buffer for decoded samples */
84 static spx_int16_t voice_output_buf[VOICE_FRAME_SIZE] CACHEALIGN_ATTR;
86 #define VOICE_PCM_FRAME_COUNT ((NATIVE_FREQUENCY*VOICE_FRAME_SIZE + \
87 VOICE_SAMPLE_RATE) / VOICE_SAMPLE_RATE)
88 #define VOICE_PCM_FRAME_SIZE (VOICE_PCM_FRAME_COUNT*4)
90 /* Default number of native-frequency PCM frames to queue - adjust as
91 necessary per-target */
92 #define VOICE_FRAMES 3
94 /* Might have lookahead and be skipping samples, so size is needed */
95 static size_t voicebuf_sizes[VOICE_FRAMES];
96 static uint32_t (* voicebuf)[VOICE_PCM_FRAME_COUNT];
97 static unsigned int cur_buf_in, cur_buf_out;
99 /* Voice processing states */
100 enum voice_state
102 VOICE_STATE_MESSAGE = 0,
103 VOICE_STATE_DECODE,
104 VOICE_STATE_BUFFER_INSERT,
107 /* A delay to not bring audio back to normal level too soon */
108 #define QUIET_COUNT 3
110 enum voice_thread_messages
112 Q_VOICE_PLAY = 0, /* Play a clip */
113 Q_VOICE_STOP, /* Stop current clip */
116 /* Structure to store clip data callback info */
117 struct voice_info
119 /* Callback to get more clips */
120 mp3_play_callback_t get_more;
121 /* Start of clip */
122 const void *start;
123 /* Size of clip */
124 size_t size;
127 /* Private thread data for its current state that must be passed to its
128 * internal functions */
129 struct voice_thread_data
131 struct queue_event ev; /* Last queue event pulled from queue */
132 void *st; /* Decoder instance */
133 SpeexBits bits; /* Bit cursor */
134 struct dsp_config *dsp; /* DSP used for voice output */
135 struct voice_info vi; /* Copy of clip data */
136 const char *src[2]; /* Current output buffer pointers */
137 int lookahead; /* Number of samples to drop at start of clip */
138 int count; /* Count of samples remaining to send to PCM */
141 /* Functions called in their repective state that return the next state to
142 state machine loop - compiler may inline them at its discretion */
143 static enum voice_state voice_message(struct voice_thread_data *td);
144 static enum voice_state voice_decode(struct voice_thread_data *td);
145 static enum voice_state voice_buffer_insert(struct voice_thread_data *td);
147 /* Number of frames in queue */
148 static inline int voice_unplayed_frames(void)
150 return cur_buf_in - cur_buf_out;
153 /* Mixer channel callback */
154 static void voice_pcm_callback(const void **start, size_t *size)
156 if (voice_unplayed_frames() == 0)
157 return; /* Done! */
159 unsigned int i = ++cur_buf_out % VOICE_FRAMES;
161 *start = voicebuf[i];
162 *size = voicebuf_sizes[i];
165 /* Start playback of voice channel if not already playing */
166 static void voice_start_playback(void)
168 if (mixer_channel_status(PCM_MIXER_CHAN_VOICE) != CHANNEL_STOPPED)
169 return;
171 unsigned int i = cur_buf_out % VOICE_FRAMES;
172 mixer_channel_play_data(PCM_MIXER_CHAN_VOICE, voice_pcm_callback,
173 voicebuf[i], voicebuf_sizes[i]);
176 /* Stop the voice channel */
177 static void voice_stop_playback(void)
179 mixer_channel_stop(PCM_MIXER_CHAN_VOICE);
180 cur_buf_in = cur_buf_out = 0;
183 /* Grab a free PCM frame */
184 static uint32_t * voice_buf_get(void)
186 if (voice_unplayed_frames() >= VOICE_FRAMES)
188 /* Full */
189 voice_start_playback();
190 return NULL;
193 return voicebuf[cur_buf_in % VOICE_FRAMES];
196 /* Commit a frame returned by voice_buf_get and set the actual size */
197 static void voice_buf_commit(size_t size)
199 voicebuf_sizes[cur_buf_in++ % VOICE_FRAMES] = size;
202 /* Stop any current clip and start playing a new one */
203 void mp3_play_data(const void *start, size_t size,
204 mp3_play_callback_t get_more)
206 if (get_more != NULL && start != NULL && size > 0)
208 struct voice_info voice_clip =
210 .get_more = get_more,
211 .start = start,
212 .size = size,
215 LOGFQUEUE("mp3 >| voice Q_VOICE_PLAY");
216 queue_send(&voice_queue, Q_VOICE_PLAY, (intptr_t)&voice_clip);
220 /* Stop current voice clip from playing */
221 void mp3_play_stop(void)
223 LOGFQUEUE("mp3 >| voice Q_VOICE_STOP");
224 queue_send(&voice_queue, Q_VOICE_STOP, 0);
227 void mp3_play_pause(bool play)
229 /* a dummy */
230 (void)play;
233 /* Tell if voice is still in a playing state */
234 bool mp3_is_playing(void)
236 return quiet_counter != 0;
239 /* This function is meant to be used by the buffer request functions to
240 ensure the codec is no longer active */
241 void voice_stop(void)
243 /* Unqueue all future clips */
244 talk_force_shutup();
247 /* Wait for voice to finish speaking. */
248 void voice_wait(void)
250 /* NOTE: One problem here is that we can't tell if another thread started a
251 * new clip by the time we wait. This should be resolvable if conditions
252 * ever require knowing the very clip you requested has finished. */
254 while (quiet_counter != 0)
255 sleep(1);
258 /* Initialize voice thread data that must be valid upon starting and the
259 * setup the DSP parameters */
260 static void voice_data_init(struct voice_thread_data *td)
262 td->dsp = (struct dsp_config *)dsp_configure(NULL, DSP_MYDSP,
263 CODEC_IDX_VOICE);
265 dsp_configure(td->dsp, DSP_RESET, 0);
266 dsp_configure(td->dsp, DSP_SET_FREQUENCY, VOICE_SAMPLE_RATE);
267 dsp_configure(td->dsp, DSP_SET_SAMPLE_DEPTH, VOICE_SAMPLE_DEPTH);
268 dsp_configure(td->dsp, DSP_SET_STEREO_MODE, STEREO_MONO);
270 mixer_channel_set_amplitude(PCM_MIXER_CHAN_VOICE, MIX_AMP_UNITY);
273 /* Voice thread message processing */
274 static enum voice_state voice_message(struct voice_thread_data *td)
276 if (quiet_counter > 0)
277 queue_wait_w_tmo(&voice_queue, &td->ev, HZ/10);
278 else
279 queue_wait(&voice_queue, &td->ev);
281 switch (td->ev.id)
283 case Q_VOICE_PLAY:
284 LOGFQUEUE("voice < Q_VOICE_PLAY");
285 if (quiet_counter == 0)
287 /* Boost CPU now */
288 trigger_cpu_boost();
290 else
292 /* Stop any clip still playing */
293 voice_stop_playback();
296 quiet_counter = QUIET_COUNT;
298 /* Copy the clip info */
299 td->vi = *(struct voice_info *)td->ev.data;
301 /* Be sure audio buffer is initialized */
302 audio_restore_playback(AUDIO_WANT_VOICE);
304 /* We need nothing more from the sending thread - let it run */
305 queue_reply(&voice_queue, 1);
307 /* Make audio play more softly and set delay to return to normal
308 playback level */
309 pcmbuf_soft_mode(true);
311 /* Clean-start the decoder */
312 td->st = speex_decoder_init(&speex_wb_mode);
314 /* Make bit buffer use our own buffer */
315 speex_bits_set_bit_buffer(&td->bits, (void *)td->vi.start,
316 td->vi.size);
317 speex_decoder_ctl(td->st, SPEEX_GET_LOOKAHEAD, &td->lookahead);
319 return VOICE_STATE_DECODE;
321 case SYS_TIMEOUT:
322 if (voice_unplayed_frames())
324 /* Waiting for PCM to finish */
325 break;
328 /* Drop through and stop the first time after clip runs out */
329 if (quiet_counter-- != QUIET_COUNT)
331 if (quiet_counter <= 0)
332 pcmbuf_soft_mode(false);
334 break;
337 /* Fall-through */
338 case Q_VOICE_STOP:
339 LOGFQUEUE("voice < Q_VOICE_STOP");
340 cancel_cpu_boost();
341 voice_stop_playback();
342 break;
344 /* No default: no other message ids are sent */
347 return VOICE_STATE_MESSAGE;
350 /* Decode frames or stop if all have completed */
351 static enum voice_state voice_decode(struct voice_thread_data *td)
353 if (!queue_empty(&voice_queue))
354 return VOICE_STATE_MESSAGE;
356 /* Decode the data */
357 if (speex_decode_int(td->st, &td->bits, voice_output_buf) < 0)
359 /* End of stream or error - get next clip */
360 td->vi.size = 0;
362 if (td->vi.get_more != NULL)
363 td->vi.get_more(&td->vi.start, &td->vi.size);
365 if (td->vi.start != NULL && td->vi.size > 0)
367 /* Make bit buffer use our own buffer */
368 speex_bits_set_bit_buffer(&td->bits, (void *)td->vi.start,
369 td->vi.size);
370 /* Don't skip any samples when we're stringing clips together */
371 td->lookahead = 0;
373 else
375 /* If all clips are done and not playing, force pcm playback. */
376 voice_start_playback();
377 return VOICE_STATE_MESSAGE;
380 else
382 yield();
384 /* Output the decoded frame */
385 td->count = VOICE_FRAME_SIZE - td->lookahead;
386 td->src[0] = (const char *)&voice_output_buf[td->lookahead];
387 td->src[1] = NULL;
388 td->lookahead -= MIN(VOICE_FRAME_SIZE, td->lookahead);
390 if (td->count > 0)
391 return VOICE_STATE_BUFFER_INSERT;
394 return VOICE_STATE_DECODE;
397 /* Process the PCM samples in the DSP and send out for mixing */
398 static enum voice_state voice_buffer_insert(struct voice_thread_data *td)
400 if (!queue_empty(&voice_queue))
401 return VOICE_STATE_MESSAGE;
403 char *dest = (char *)voice_buf_get();
405 if (dest != NULL)
407 voice_buf_commit(dsp_process(td->dsp, dest, td->src, td->count)
408 * sizeof (int32_t));
409 return VOICE_STATE_DECODE;
412 sleep(0);
413 return VOICE_STATE_BUFFER_INSERT;
416 /* Voice thread entrypoint */
417 static void NORETURN_ATTR voice_thread(void)
419 struct voice_thread_data td;
420 enum voice_state state = VOICE_STATE_MESSAGE;
422 voice_data_init(&td);
424 while (1)
426 switch (state)
428 case VOICE_STATE_MESSAGE:
429 state = voice_message(&td);
430 break;
431 case VOICE_STATE_DECODE:
432 state = voice_decode(&td);
433 break;
434 case VOICE_STATE_BUFFER_INSERT:
435 state = voice_buffer_insert(&td);
436 break;
441 /* Initialize all synchronization objects create the thread */
442 void voice_thread_init(void)
444 logf("Starting voice thread");
445 queue_init(&voice_queue, false);
447 voice_thread_id = create_thread(voice_thread, voice_stack,
448 sizeof(voice_stack), 0, voice_thread_name
449 IF_PRIO(, PRIORITY_VOICE) IF_COP(, CPU));
451 queue_enable_queue_send(&voice_queue, &voice_queue_sender_list,
452 voice_thread_id);
455 #ifdef HAVE_PRIORITY_SCHEDULING
456 /* Set the voice thread priority */
457 void voice_thread_set_priority(int priority)
459 if (priority > PRIORITY_VOICE)
460 priority = PRIORITY_VOICE;
462 thread_set_priority(voice_thread_id, priority);
464 #endif
466 /* Initialize voice PCM buffer and return size, allocated from the end */
467 size_t voicebuf_init(unsigned char *bufend)
469 size_t size = VOICE_FRAMES * VOICE_PCM_FRAME_SIZE;
470 cur_buf_out = cur_buf_in = 0;
471 voicebuf = (uint32_t (*)[VOICE_PCM_FRAME_COUNT])(bufend - size);
472 return size;