Don't try to resolve an empty path.
[maemo-rb.git] / apps / voice_thread.c
blob1a86dc7cfa0a4a08d9a00eb652cbdb1e278815ab
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 "core_alloc.h"
24 #include "thread.h"
25 #include "voice_thread.h"
26 #include "talk.h"
27 #include "dsp_core.h"
28 #include "audio.h"
29 #include "playback.h"
30 #include "pcmbuf.h"
31 #include "pcm.h"
32 #include "pcm_mixer.h"
33 #include "codecs/libspeex/speex/speex.h"
35 /* Default number of native-frequency PCM frames to queue - adjust as
36 necessary per-target */
37 #define VOICE_FRAMES 4
39 /* Define any of these as "1" and uncomment the LOGF_ENABLE line to log
40 regular and/or timeout messages */
41 #define VOICE_LOGQUEUES 0
42 #define VOICE_LOGQUEUES_SYS_TIMEOUT 0
44 /*#define LOGF_ENABLE*/
45 #include "logf.h"
47 #if VOICE_LOGQUEUES
48 #define LOGFQUEUE logf
49 #else
50 #define LOGFQUEUE(...)
51 #endif
53 #if VOICE_LOGQUEUES_SYS_TIMEOUT
54 #define LOGFQUEUE_SYS_TIMEOUT logf
55 #else
56 #define LOGFQUEUE_SYS_TIMEOUT(...)
57 #endif
59 #ifndef IBSS_ATTR_VOICE_STACK
60 #define IBSS_ATTR_VOICE_STACK IBSS_ATTR
61 #endif
63 /* Minimum priority needs to be a bit elevated since voice has fairly low
64 latency */
65 #define PRIORITY_VOICE (PRIORITY_PLAYBACK-4)
67 #define VOICE_FRAME_COUNT 320 /* Samples / frame */
68 #define VOICE_SAMPLE_RATE 16000 /* Sample rate in HZ */
69 #define VOICE_SAMPLE_DEPTH 16 /* Sample depth in bits */
71 /* Voice thread variables */
72 static unsigned int voice_thread_id = 0;
73 #ifdef CPU_COLDFIRE
74 /* ISR uses any available stack - need a bit more room */
75 #define VOICE_STACK_EXTRA 0x400
76 #else
77 #define VOICE_STACK_EXTRA 0x3c0
78 #endif
79 static long voice_stack[(DEFAULT_STACK_SIZE + VOICE_STACK_EXTRA)/sizeof(long)]
80 IBSS_ATTR_VOICE_STACK;
81 static const char voice_thread_name[] = "voice";
83 /* Voice thread synchronization objects */
84 static struct event_queue voice_queue SHAREDBSS_ATTR;
85 static struct queue_sender_list voice_queue_sender_list SHAREDBSS_ATTR;
86 static int quiet_counter SHAREDDATA_ATTR = 0;
88 #define VOICE_PCM_FRAME_COUNT ((NATIVE_FREQUENCY*VOICE_FRAME_COUNT + \
89 VOICE_SAMPLE_RATE) / VOICE_SAMPLE_RATE)
90 #define VOICE_PCM_FRAME_SIZE (VOICE_PCM_FRAME_COUNT*2*sizeof (int16_t))
92 /* Voice processing states */
93 enum voice_state
95 VOICE_STATE_MESSAGE = 0,
96 VOICE_STATE_DECODE,
97 VOICE_STATE_BUFFER_INSERT,
100 /* A delay to not bring audio back to normal level too soon */
101 #define QUIET_COUNT 3
103 enum voice_thread_messages
105 Q_VOICE_PLAY = 0, /* Play a clip */
106 Q_VOICE_STOP, /* Stop current clip */
109 /* Structure to store clip data callback info */
110 struct voice_info
112 /* Callback to get more clips */
113 mp3_play_callback_t get_more;
114 /* Start of clip */
115 const void *start;
116 /* Size of clip */
117 size_t size;
120 /* Private thread data for its current state that must be passed to its
121 * internal functions */
122 struct voice_thread_data
124 struct queue_event ev; /* Last queue event pulled from queue */
125 void *st; /* Decoder instance */
126 SpeexBits bits; /* Bit cursor */
127 struct dsp_config *dsp; /* DSP used for voice output */
128 struct voice_info vi; /* Copy of clip data */
129 int lookahead; /* Number of samples to drop at start of clip */
130 struct dsp_buffer src; /* Speex output buffer/input to DSP */
131 struct dsp_buffer *dst; /* Pointer to DSP output buffer for PCM */
134 /* Functions called in their repective state that return the next state to
135 state machine loop - compiler may inline them at its discretion */
136 static enum voice_state voice_message(struct voice_thread_data *td);
137 static enum voice_state voice_decode(struct voice_thread_data *td);
138 static enum voice_state voice_buffer_insert(struct voice_thread_data *td);
140 /* Might have lookahead and be skipping samples, so size is needed */
141 static struct voice_buf
143 /* Buffer for decoded samples */
144 spx_int16_t spx_outbuf[VOICE_FRAME_COUNT];
145 /* Queue frame indexes */
146 unsigned int frame_in, frame_out;
147 /* For PCM pointer adjustment */
148 struct voice_thread_data *td;
149 /* Buffers for mixing voice */
150 struct voice_pcm_frame
152 size_t size;
153 int16_t pcm[2*VOICE_PCM_FRAME_COUNT];
154 } frames[VOICE_FRAMES];
155 } *voice_buf = NULL;
157 static int voice_buf_hid = 0;
159 static int move_callback(int handle, void *current, void *new)
161 /* Have to adjust the pointers that point into things in voice_buf */
162 off_t diff = new - current;
163 struct voice_thread_data *td = voice_buf->td;
164 td->src.p32[0] = SKIPBYTES(td->src.p32[0], diff);
165 td->src.p32[1] = SKIPBYTES(td->src.p32[1], diff);
166 if (td->dst != NULL) /* Only when calling dsp_process */
167 td->dst->p16out = SKIPBYTES(td->dst->p16out, diff);
168 mixer_adjust_channel_address(PCM_MIXER_CHAN_VOICE, diff);
169 voice_buf = new;
171 return BUFLIB_CB_OK;
172 (void)handle;
175 static void sync_callback(int handle, bool sync_on)
177 /* A move must not allow PCM to access the channel */
178 if (sync_on)
179 pcm_play_lock();
180 else
181 pcm_play_unlock();
183 (void)handle;
186 static struct buflib_callbacks ops =
188 .move_callback = move_callback,
189 .sync_callback = sync_callback,
192 /* Number of frames in queue */
193 static inline int voice_unplayed_frames(void)
195 return voice_buf->frame_in - voice_buf->frame_out;
198 /* Mixer channel callback */
199 static void voice_pcm_callback(const void **start, size_t *size)
201 if (voice_unplayed_frames() == 0)
202 return; /* Done! */
204 struct voice_pcm_frame *frame =
205 &voice_buf->frames[++voice_buf->frame_out % VOICE_FRAMES];
207 *start = frame->pcm;
208 *size = frame->size;
211 /* Start playback of voice channel if not already playing */
212 static void voice_start_playback(void)
214 if (mixer_channel_status(PCM_MIXER_CHAN_VOICE) != CHANNEL_STOPPED ||
215 voice_unplayed_frames() <= 0)
216 return;
218 struct voice_pcm_frame *frame =
219 &voice_buf->frames[voice_buf->frame_out % VOICE_FRAMES];
221 mixer_channel_play_data(PCM_MIXER_CHAN_VOICE, voice_pcm_callback,
222 frame->pcm, frame->size);
225 /* Stop the voice channel */
226 static void voice_stop_playback(void)
228 mixer_channel_stop(PCM_MIXER_CHAN_VOICE);
229 voice_buf->frame_in = voice_buf->frame_out = 0;
232 /* Grab a free PCM frame */
233 static int16_t * voice_buf_get(void)
235 if (voice_unplayed_frames() >= VOICE_FRAMES)
237 /* Full */
238 voice_start_playback();
239 return NULL;
242 return voice_buf->frames[voice_buf->frame_in % VOICE_FRAMES].pcm;
245 /* Commit a frame returned by voice_buf_get and set the actual size */
246 static void voice_buf_commit(int count)
248 if (count > 0)
250 voice_buf->frames[voice_buf->frame_in++ % VOICE_FRAMES].size =
251 count * 2 * sizeof (int16_t);
255 /* Stop any current clip and start playing a new one */
256 void mp3_play_data(const void *start, size_t size,
257 mp3_play_callback_t get_more)
259 if (voice_thread_id && start && size && get_more)
261 struct voice_info voice_clip =
263 .get_more = get_more,
264 .start = start,
265 .size = size,
268 LOGFQUEUE("mp3 >| voice Q_VOICE_PLAY");
269 queue_send(&voice_queue, Q_VOICE_PLAY, (intptr_t)&voice_clip);
273 /* Stop current voice clip from playing */
274 void mp3_play_stop(void)
276 if (voice_thread_id != 0)
278 LOGFQUEUE("mp3 >| voice Q_VOICE_STOP");
279 queue_send(&voice_queue, Q_VOICE_STOP, 0);
283 void mp3_play_pause(bool play)
285 /* a dummy */
286 (void)play;
289 /* Tell if voice is still in a playing state */
290 bool mp3_is_playing(void)
292 return quiet_counter != 0;
295 /* This function is meant to be used by the buffer request functions to
296 ensure the codec is no longer active */
297 void voice_stop(void)
299 /* Unqueue all future clips */
300 talk_force_shutup();
303 /* Wait for voice to finish speaking. */
304 void voice_wait(void)
306 /* NOTE: One problem here is that we can't tell if another thread started a
307 * new clip by the time we wait. This should be resolvable if conditions
308 * ever require knowing the very clip you requested has finished. */
310 while (quiet_counter != 0)
311 sleep(1);
314 /* Initialize voice thread data that must be valid upon starting and the
315 * setup the DSP parameters */
316 static void voice_data_init(struct voice_thread_data *td)
318 td->dsp = dsp_get_config(CODEC_IDX_VOICE);
319 dsp_configure(td->dsp, DSP_RESET, 0);
320 dsp_configure(td->dsp, DSP_SET_FREQUENCY, VOICE_SAMPLE_RATE);
321 dsp_configure(td->dsp, DSP_SET_SAMPLE_DEPTH, VOICE_SAMPLE_DEPTH);
322 dsp_configure(td->dsp, DSP_SET_STEREO_MODE, STEREO_MONO);
324 mixer_channel_set_amplitude(PCM_MIXER_CHAN_VOICE, MIX_AMP_UNITY);
326 voice_buf->frame_in = voice_buf->frame_out = 0;
327 voice_buf->td = td;
328 td->dst = NULL;
331 /* Voice thread message processing */
332 static enum voice_state voice_message(struct voice_thread_data *td)
334 if (quiet_counter > 0)
335 queue_wait_w_tmo(&voice_queue, &td->ev, HZ/10);
336 else
337 queue_wait(&voice_queue, &td->ev);
339 switch (td->ev.id)
341 case Q_VOICE_PLAY:
342 LOGFQUEUE("voice < Q_VOICE_PLAY");
343 if (quiet_counter == 0)
345 /* Boost CPU now */
346 trigger_cpu_boost();
348 else
350 /* Stop any clip still playing */
351 voice_stop_playback();
354 quiet_counter = QUIET_COUNT;
356 /* Copy the clip info */
357 td->vi = *(struct voice_info *)td->ev.data;
359 /* We need nothing more from the sending thread - let it run */
360 queue_reply(&voice_queue, 1);
362 /* Make audio play more softly and set delay to return to normal
363 playback level */
364 pcmbuf_soft_mode(true);
366 /* Clean-start the decoder */
367 td->st = speex_decoder_init(&speex_wb_mode);
369 /* Make bit buffer use our own buffer */
370 speex_bits_set_bit_buffer(&td->bits, (void *)td->vi.start,
371 td->vi.size);
372 speex_decoder_ctl(td->st, SPEEX_GET_LOOKAHEAD, &td->lookahead);
374 return VOICE_STATE_DECODE;
376 case SYS_TIMEOUT:
377 if (voice_unplayed_frames())
379 /* Waiting for PCM to finish */
380 break;
383 /* Drop through and stop the first time after clip runs out */
384 if (quiet_counter-- != QUIET_COUNT)
386 if (quiet_counter <= 0)
387 pcmbuf_soft_mode(false);
389 break;
392 /* Fall-through */
393 case Q_VOICE_STOP:
394 LOGFQUEUE("voice < Q_VOICE_STOP");
395 cancel_cpu_boost();
396 voice_stop_playback();
397 break;
399 /* No default: no other message ids are sent */
402 return VOICE_STATE_MESSAGE;
405 /* Decode frames or stop if all have completed */
406 static enum voice_state voice_decode(struct voice_thread_data *td)
408 if (!queue_empty(&voice_queue))
409 return VOICE_STATE_MESSAGE;
411 /* Decode the data */
412 if (speex_decode_int(td->st, &td->bits, voice_buf->spx_outbuf) < 0)
414 /* End of stream or error - get next clip */
415 td->vi.size = 0;
417 if (td->vi.get_more != NULL)
418 td->vi.get_more(&td->vi.start, &td->vi.size);
420 if (td->vi.start != NULL && td->vi.size > 0)
422 /* Make bit buffer use our own buffer */
423 speex_bits_set_bit_buffer(&td->bits, (void *)td->vi.start,
424 td->vi.size);
425 /* Don't skip any samples when we're stringing clips together */
426 td->lookahead = 0;
428 else
430 /* If all clips are done and not playing, force pcm playback. */
431 if (voice_unplayed_frames() > 0)
432 voice_start_playback();
433 return VOICE_STATE_MESSAGE;
436 else
438 yield();
440 /* Output the decoded frame */
441 td->src.remcount = VOICE_FRAME_COUNT - td->lookahead;
442 td->src.pin[0] = &voice_buf->spx_outbuf[td->lookahead];
443 td->src.pin[1] = NULL;
444 td->src.proc_mask = 0;
446 td->lookahead -= MIN(VOICE_FRAME_COUNT, td->lookahead);
448 if (td->src.remcount > 0)
449 return VOICE_STATE_BUFFER_INSERT;
452 return VOICE_STATE_DECODE;
455 /* Process the PCM samples in the DSP and send out for mixing */
456 static enum voice_state voice_buffer_insert(struct voice_thread_data *td)
458 if (!queue_empty(&voice_queue))
459 return VOICE_STATE_MESSAGE;
461 struct dsp_buffer dst;
463 if ((dst.p16out = voice_buf_get()) != NULL)
465 dst.remcount = 0;
466 dst.bufcount = VOICE_PCM_FRAME_COUNT;
468 td->dst = &dst;
469 dsp_process(td->dsp, &td->src, &dst);
470 td->dst = NULL;
472 voice_buf_commit(dst.remcount);
474 /* Unless other effects are introduced to voice that have delays,
475 all output should have been purged to dst in one call */
476 return td->src.remcount > 0 ?
477 VOICE_STATE_BUFFER_INSERT : VOICE_STATE_DECODE;
480 sleep(0);
481 return VOICE_STATE_BUFFER_INSERT;
484 /* Voice thread entrypoint */
485 static void NORETURN_ATTR voice_thread(void)
487 struct voice_thread_data td;
488 enum voice_state state = VOICE_STATE_MESSAGE;
490 voice_data_init(&td);
492 while (1)
494 switch (state)
496 case VOICE_STATE_MESSAGE:
497 state = voice_message(&td);
498 break;
499 case VOICE_STATE_DECODE:
500 state = voice_decode(&td);
501 break;
502 case VOICE_STATE_BUFFER_INSERT:
503 state = voice_buffer_insert(&td);
504 break;
509 /* Initialize buffers, all synchronization objects and create the thread */
510 void voice_thread_init(void)
512 if (voice_thread_id != 0)
513 return; /* Already did an init and succeeded at it */
515 if (!talk_voice_required())
517 logf("No voice required");
518 return;
521 voice_buf_hid = core_alloc_ex("voice buf", sizeof (*voice_buf), &ops);
523 if (voice_buf_hid <= 0)
525 logf("voice: core_alloc_ex failed");
526 return;
529 voice_buf = core_get_data(voice_buf_hid);
531 if (voice_buf == NULL)
533 logf("voice: core_get_data failed");
534 core_free(voice_buf_hid);
535 voice_buf_hid = 0;
536 return;
539 logf("Starting voice thread");
540 queue_init(&voice_queue, false);
542 voice_thread_id = create_thread(voice_thread, voice_stack,
543 sizeof(voice_stack), 0, voice_thread_name
544 IF_PRIO(, PRIORITY_VOICE) IF_COP(, CPU));
546 queue_enable_queue_send(&voice_queue, &voice_queue_sender_list,
547 voice_thread_id);
550 #ifdef HAVE_PRIORITY_SCHEDULING
551 /* Set the voice thread priority */
552 void voice_thread_set_priority(int priority)
554 if (voice_thread_id == 0)
555 return;
557 if (priority > PRIORITY_VOICE)
558 priority = PRIORITY_VOICE;
560 thread_set_priority(voice_thread_id, priority);
562 #endif