Fix remaining problems.
[kugel-rb.git] / apps / talk.c
blobf32e1b6e0bf1bb56bf0a50551dfc0ce45fab7831
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2004 Jörg Hohensohn
12 * This module collects the Talkbox and voice UI functions.
13 * (Talkbox reads directory names from mp3 clips called thumbnails,
14 * the voice UI lets menus and screens "talk" from a voicefile in memory.
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * as published by the Free Software Foundation; either version 2
19 * of the License, or (at your option) any later version.
21 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
22 * KIND, either express or implied.
24 ****************************************************************************/
26 #include <stdio.h>
27 #include <stddef.h>
28 #include "string-extra.h"
29 #include "file.h"
30 #include "buffer.h"
31 #include "system.h"
32 #include "kernel.h"
33 #include "settings.h"
34 #include "settings_list.h"
35 #include "mp3_playback.h"
36 #include "audio.h"
37 #include "lang.h"
38 #include "talk.h"
39 #include "metadata.h"
40 /*#define LOGF_ENABLE*/
41 #include "logf.h"
42 #include "bitswap.h"
43 #include "structec.h"
44 #include "plugin.h" /* plugin_get_buffer() */
45 #include "debug.h"
48 /* Memory layout varies between targets because the
49 Archos (MASCODEC) devices cannot mix voice and audio playback
51 MASCODEC | MASCODEC | SWCODEC
52 (playing) | (stopped) |
53 voicebuf-----------+-----------+------------
54 audio | voice | thumbnail
55 |-----------|------------
56 | thumbnail | voice
57 | |------------
58 | | filebuf
59 | |------------
60 | | audio
61 voicebufend----------+-----------+------------
63 SWCODEC allocates dedicated buffers, MASCODEC reuses audiobuf. */
66 /***************** Constants *****************/
68 #define QUEUE_SIZE 64 /* must be a power of two */
69 #define QUEUE_MASK (QUEUE_SIZE-1)
70 const char* const dir_thumbnail_name = "_dirname.talk";
71 const char* const file_thumbnail_ext = ".talk";
73 /***************** Functional Macros *****************/
75 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
77 #define LOADED_MASK 0x80000000 /* MSB */
79 #if CONFIG_CODEC == SWCODEC
80 #define MAX_THUMBNAIL_BUFSIZE 0x10000
81 #endif
83 /***************** Data types *****************/
85 struct clip_entry /* one entry of the index table */
87 int offset; /* offset from start of voicefile file */
88 int size; /* size of the clip */
91 struct voicefile /* file format of our voice file */
93 int version; /* version of the voicefile */
94 int target_id; /* the rockbox target the file was made for */
95 int table; /* offset to index table, (=header size) */
96 int id1_max; /* number of "normal" clips contained in above index */
97 int id2_max; /* number of "voice only" clips contained in above index */
98 struct clip_entry index[]; /* followed by the index tables */
99 /* and finally the mp3 clips, not visible here, bitswapped
100 for SH based players */
103 struct queue_entry /* one entry of the internal queue */
105 unsigned char* buf;
106 long len;
110 /***************** Globals *****************/
112 #if CONFIG_STORAGE & STORAGE_MMC
113 /* The MMC storage on the Ondios is slow enough that we want to buffer the
114 * talk clips only when they are needed */
115 # define TALK_PROGRESSIVE_LOAD
116 #elif CONFIG_CODEC == SWCODEC && MEMORYSIZE <= 2
117 /* The entire voice file wouldn't fit in memory together with codecs, so we
118 * load clips each time they are accessed */
119 # define TALK_PARTIAL_LOAD
120 #endif
122 #ifdef TALK_PARTIAL_LOAD
123 static unsigned char *clip_buffer;
124 static long max_clipsize; /* size of the biggest clip */
125 static long buffered_id[QUEUE_SIZE]; /* IDs of the talk clips */
126 static uint8_t clip_age[QUEUE_SIZE];
127 #if QUEUE_SIZE > 255
128 # error clip_age[] type too small
129 #endif
130 #endif
132 static char* voicebuf; /* root pointer to our buffer */
133 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
134 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
135 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
136 thumbnail buffer */
137 static long size_for_thumbnail; /* total thumbnail buffer size */
138 static struct voicefile* p_voicefile; /* loaded voicefile */
139 static bool has_voicefile; /* a voicefile file is present */
140 static bool need_shutup; /* is there possibly any voice playing to be shutup */
141 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
142 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
143 static int queue_write; /* write index of queue, by application */
144 static int queue_read; /* read index of queue, by ISR context */
145 #if CONFIG_CODEC == SWCODEC
146 /* protects queue_read, queue_write and thumbnail_buf_used */
147 static struct mutex queue_mutex SHAREDBSS_ATTR;
148 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
149 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
150 #else
151 #define talk_queue_lock() ({ })
152 #define talk_queue_unlock() ({ })
153 #endif /* CONFIG_CODEC */
154 static int sent; /* how many bytes handed over to playback, owned by ISR */
155 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
156 static int filehandle = -1; /* global, so we can keep the file open if needed */
157 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
158 static long silence_len; /* length of the VOICE_PAUSE clip */
159 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
160 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
161 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
162 static bool talk_initialized; /* true if talk_init has been called */
163 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
166 /***************** Private implementation *****************/
168 static int open_voicefile(void)
170 char buf[64];
171 char* p_lang = "english"; /* default */
173 if ( global_settings.lang_file[0] &&
174 global_settings.lang_file[0] != 0xff )
175 { /* try to open the voice file of the selected language */
176 p_lang = (char *)global_settings.lang_file;
179 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
181 return open(buf, O_RDONLY);
185 /* fetch a clip from the voice file */
186 static unsigned char* get_clip(long id, long* p_size)
188 long clipsize;
189 unsigned char* clipbuf;
191 if (id > VOICEONLY_DELIMITER)
192 { /* voice-only entries use the second part of the table */
193 id -= VOICEONLY_DELIMITER + 1;
194 if (id >= p_voicefile->id2_max)
195 return NULL; /* must be newer than we have */
196 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
198 else
199 { /* normal use of the first table */
200 if (id >= p_voicefile->id1_max)
201 return NULL; /* must be newer than we have */
204 clipsize = p_voicefile->index[id].size;
205 if (clipsize == 0) /* clip not included in voicefile */
206 return NULL;
208 #ifndef TALK_PARTIAL_LOAD
209 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
210 #endif
212 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
213 if (!(clipsize & LOADED_MASK))
214 { /* clip needs loading */
215 #ifdef TALK_PARTIAL_LOAD
216 int idx = 0;
217 if (id == VOICE_PAUSE) {
218 idx = QUEUE_SIZE; /* we keep VOICE_PAUSE loaded */
219 } else {
220 int oldest = 0, i;
221 for(i=0; i<QUEUE_SIZE; i++) {
222 if (buffered_id[i] < 0) {
223 /* found a free entry, that means the buffer isn't
224 * full yet. */
225 idx = i;
226 break;
229 /* find the oldest clip */
230 if(clip_age[i] > oldest) {
231 idx = i;
232 oldest = clip_age[i];
235 /* increment age of each loaded clip */
236 clip_age[i]++;
238 clip_age[idx] = 0; /* reset clip's age */
240 clipbuf = clip_buffer + idx * max_clipsize;
241 #endif
243 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
244 if (read(filehandle, clipbuf, clipsize) != clipsize)
245 return NULL; /* read error */
247 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
249 #ifdef TALK_PARTIAL_LOAD
250 if (id != VOICE_PAUSE) {
251 if (buffered_id[idx] >= 0) {
252 /* mark previously loaded clip as unloaded */
253 p_voicefile->index[buffered_id[idx]].size &= ~LOADED_MASK;
255 buffered_id[idx] = id;
257 #endif
259 else
260 { /* clip is in memory already */
261 #ifdef TALK_PARTIAL_LOAD
262 /* Find where it was loaded */
263 clipbuf = clip_buffer;
264 if (id == VOICE_PAUSE) {
265 clipbuf += QUEUE_SIZE * max_clipsize;
266 } else {
267 int idx;
268 for (idx=0; idx<QUEUE_SIZE; idx++)
269 if (buffered_id[idx] == id) {
270 clipbuf += idx * max_clipsize;
271 clip_age[idx] = 0; /* reset clip's age */
272 break;
275 #endif
276 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
278 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
280 *p_size = clipsize;
281 return clipbuf;
285 /* load the voice file into the mp3 buffer */
286 static void load_voicefile(bool probe, char* buf, size_t bufsize)
288 union voicebuf {
289 unsigned char* buf;
290 struct voicefile* file;
292 union voicebuf voicebuf;
294 size_t load_size, alloc_size;
295 ssize_t got_size;
296 #ifndef TALK_PARTIAL_LOAD
297 size_t file_size;
298 #endif
299 #ifdef ROCKBOX_LITTLE_ENDIAN
300 int i;
301 #endif
303 if (!probe)
304 filehandle = open_voicefile();
305 if (filehandle < 0) /* failed to open */
306 goto load_err;
308 voicebuf.buf = buf;
309 if (!voicebuf.buf)
310 goto load_err;
312 #ifndef TALK_PARTIAL_LOAD
313 file_size = filesize(filehandle);
314 if (file_size > bufsize) /* won't fit? */
315 goto load_err;
316 #endif
318 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
319 /* load only the header for now */
320 load_size = sizeof(struct voicefile);
321 #else /* load the full file */
322 load_size = file_size;
323 #endif
325 #ifdef TALK_PARTIAL_LOAD
326 if (load_size > bufsize) /* won't fit? */
327 goto load_err;
328 #endif
330 got_size = read(filehandle, voicebuf.buf, load_size);
331 if (got_size != (ssize_t)load_size /* failure */)
332 goto load_err;
334 alloc_size = load_size;
336 #ifdef ROCKBOX_LITTLE_ENDIAN
337 logf("Byte swapping voice file");
338 structec_convert(voicebuf.buf, "lllll", 1, true);
339 #endif
341 /* format check */
342 if (voicebuf.file->table == sizeof(struct voicefile))
344 p_voicefile = voicebuf.file;
346 if (p_voicefile->version != VOICE_VERSION ||
347 p_voicefile->target_id != TARGET_ID)
349 logf("Incompatible voice file");
350 goto load_err;
352 #if CONFIG_CODEC != SWCODEC
353 /* MASCODEC: now use audiobuf for voice then thumbnail */
354 p_thumbnail = voicebuf.buf + file_size;
355 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
356 size_for_thumbnail = voicebuf.buf + bufsize - p_thumbnail;
357 #endif
359 else
360 goto load_err;
362 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
363 /* load the index table, now that we know its size from the header */
364 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
365 * sizeof(struct clip_entry);
367 #ifdef TALK_PARTIAL_LOAD
368 if (load_size > bufsize) /* won't fit? */
369 goto load_err;
370 #endif
372 got_size = read(filehandle, &p_voicefile->index[0], load_size);
373 if (got_size != (ssize_t)load_size) /* read error */
374 goto load_err;
376 alloc_size += load_size;
377 #else
378 close(filehandle);
379 filehandle = -1;
380 #endif /* defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD) */
382 #ifdef ROCKBOX_LITTLE_ENDIAN
383 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
384 structec_convert(&p_voicefile->index[i], "ll", 1, true);
385 #endif
387 #ifdef TALK_PARTIAL_LOAD
388 clip_buffer = (unsigned char *) p_voicefile + p_voicefile->table;
389 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
390 clip_buffer += clips * sizeof(struct clip_entry); /* skip index */
391 #endif
392 if (!probe) {
393 /* make sure to have the silence clip, if available */
394 p_silence = get_clip(VOICE_PAUSE, &silence_len);
397 #ifdef TALK_PARTIAL_LOAD
398 alloc_size += silence_len + QUEUE_SIZE;
399 #endif
400 if (alloc_size > bufsize)
401 goto load_err;
402 return;
404 load_err:
405 p_voicefile = NULL;
406 has_voicefile = false; /* don't try again */
407 if (filehandle >= 0)
409 close(filehandle);
410 filehandle = -1;
412 return;
416 /* called in ISR context if mp3 data got consumed */
417 static void mp3_callback(unsigned char** start, size_t* size)
419 queue[queue_read].len -= sent; /* we completed this */
420 queue[queue_read].buf += sent;
422 if (queue[queue_read].len > 0) /* current clip not finished? */
423 { /* feed the next 64K-1 chunk */
424 #if CONFIG_CODEC != SWCODEC
425 sent = MIN(queue[queue_read].len, 0xFFFF);
426 #else
427 sent = queue[queue_read].len;
428 #endif
429 *start = queue[queue_read].buf;
430 *size = sent;
431 return;
433 talk_queue_lock();
434 if(p_thumbnail
435 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
436 thumbnail_buf_used = 0;
437 if (sent > 0) /* go to next entry */
439 queue_read = (queue_read + 1) & QUEUE_MASK;
442 re_check:
444 if (QUEUE_LEVEL != 0) /* queue is not empty? */
445 { /* start next clip */
446 #if CONFIG_CODEC != SWCODEC
447 sent = MIN(queue[queue_read].len, 0xFFFF);
448 #else
449 sent = queue[queue_read].len;
450 #endif
451 *start = p_lastclip = queue[queue_read].buf;
452 *size = sent;
453 curr_hd[0] = p_lastclip[1];
454 curr_hd[1] = p_lastclip[2];
455 curr_hd[2] = p_lastclip[3];
457 else if (p_silence != NULL /* silence clip available */
458 && p_lastclip != p_silence /* previous clip wasn't silence */
459 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
460 && p_lastclip < p_thumbnail +size_for_thumbnail))
461 { /* add silence clip when queue runs empty playing a voice clip */
462 queue[queue_write].buf = p_silence;
463 queue[queue_write].len = silence_len;
464 queue_write = (queue_write + 1) & QUEUE_MASK;
466 goto re_check;
468 else
470 *size = 0; /* end of data */
472 talk_queue_unlock();
475 /***************** Public routines *****************/
477 /* stop the playback and the pending clips */
478 void talk_force_shutup(void)
480 /* Most of this is MAS only */
481 #if CONFIG_CODEC != SWCODEC
482 #ifdef SIMULATOR
483 return;
484 #endif
485 unsigned char* pos;
486 unsigned char* search;
487 unsigned char* end;
488 if (QUEUE_LEVEL == 0) /* has ended anyway */
489 return;
491 #if CONFIG_CPU == SH7034
492 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
493 #endif /* CONFIG_CPU == SH7034 */
494 /* search next frame boundary and continue up to there */
495 pos = search = mp3_get_pos();
496 end = queue[queue_read].buf + queue[queue_read].len;
498 if (pos >= queue[queue_read].buf
499 && pos <= end) /* really our clip? */
500 { /* (for strange reasons this isn't nesessarily the case) */
501 /* find the next frame boundary */
502 while (search < end) /* search the remaining data */
504 if (*search++ != 0xFF) /* quick search for frame sync byte */
505 continue; /* (this does the majority of the job) */
507 /* look at the (bitswapped) rest of header candidate */
508 if (search[0] == curr_hd[0] /* do the quicker checks first */
509 && search[2] == curr_hd[2]
510 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
512 search--; /* back to the sync byte */
513 break; /* From looking at it, this is our header. */
517 if (search-pos)
518 { /* play old data until the frame end, to keep the MAS in sync */
519 sent = search-pos;
521 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
522 queue[queue_read].len = sent; /* current one ends after this */
524 #if CONFIG_CPU == SH7034
525 DTCR3 = sent; /* let the DMA finish this frame */
526 CHCR3 |= 0x0001; /* re-enable DMA */
527 #endif /* CONFIG_CPU == SH7034 */
528 thumbnail_buf_used = 0;
529 return;
532 #endif /* CONFIG_CODEC != SWCODEC */
534 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
535 mp3_play_stop();
536 talk_queue_lock();
537 queue_write = queue_read = 0; /* reset the queue */
538 thumbnail_buf_used = 0;
539 talk_queue_unlock();
540 need_shutup = false;
543 /* Shutup the voice, except if force_enqueue_next is set. */
544 void talk_shutup(void)
546 if (need_shutup && !force_enqueue_next)
547 talk_force_shutup();
550 /* schedule a clip, at the end or discard the existing queue */
551 static void queue_clip(unsigned char* buf, long size, bool enqueue)
553 int queue_level;
555 if (!enqueue)
556 talk_shutup(); /* cut off all the pending stuff */
557 /* Something is being enqueued, force_enqueue_next override is no
558 longer in effect. */
559 force_enqueue_next = false;
561 if (!size)
562 return; /* safety check */
563 #if CONFIG_CPU == SH7034
564 /* disable the DMA temporarily, to be safe of race condition */
565 CHCR3 &= ~0x0001;
566 #endif
567 talk_queue_lock();
568 queue_level = QUEUE_LEVEL; /* check old level */
570 if (queue_level < QUEUE_SIZE - 1) /* space left? */
572 queue[queue_write].buf = buf; /* populate an entry */
573 queue[queue_write].len = size;
574 queue_write = (queue_write + 1) & QUEUE_MASK;
576 talk_queue_unlock();
578 if (queue_level == 0)
579 { /* queue was empty, we have to do the initial start */
580 p_lastclip = buf;
581 #if CONFIG_CODEC != SWCODEC
582 sent = MIN(size, 0xFFFF); /* DMA can do no more */
583 #else
584 sent = size;
585 #endif
586 mp3_play_data(buf, sent, mp3_callback);
587 curr_hd[0] = buf[1];
588 curr_hd[1] = buf[2];
589 curr_hd[2] = buf[3];
590 mp3_play_pause(true); /* kickoff audio */
592 else
594 #if CONFIG_CPU == SH7034
595 CHCR3 |= 0x0001; /* re-enable DMA */
596 #endif
599 need_shutup = true;
601 return;
605 static void alloc_thumbnail_buf(void)
607 #if CONFIG_CODEC == SWCODEC
608 /* Allocate a dedicated thumbnail buffer - once */
609 if (p_thumbnail == NULL)
611 size_for_thumbnail = buffer_available();
612 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
613 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
614 p_thumbnail = buffer_alloc(size_for_thumbnail);
616 #else
617 /* use the audio buffer now, need to release before loading a voice */
618 p_thumbnail = voicebuf;
619 #endif
620 thumbnail_buf_used = 0;
623 /* common code for talk_init() and talk_buffer_steal() */
624 static void reset_state(void)
626 queue_write = queue_read = 0; /* reset the queue */
627 p_voicefile = NULL; /* indicate no voicefile (trashed) */
628 #if CONFIG_CODEC != SWCODEC
629 p_thumbnail = NULL; /* don't leak buffer_alloc() for swcodec */
630 #endif
632 #ifdef TALK_PARTIAL_LOAD
633 int i;
634 for(i=0; i<QUEUE_SIZE; i++)
635 buffered_id[i] = -1;
636 #endif
638 p_silence = NULL; /* pause clip not accessible */
639 voicebuf = NULL;
643 /***************** Public implementation *****************/
645 void talk_init(void)
647 talk_temp_disable_count = 0;
648 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
650 /* not a new file, nothing to do */
651 return;
654 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
655 if (filehandle >= 0)
657 close(filehandle);
658 filehandle = -1;
660 #endif
662 #if CONFIG_CODEC == SWCODEC
663 if(!talk_initialized)
664 mutex_init(&queue_mutex);
665 #endif /* CONFIG_CODEC == SWCODEC */
667 talk_initialized = true;
668 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
669 MAX_FILENAME);
671 filehandle = open_voicefile();
672 if (filehandle < 0) {
673 has_voicefile = false;
674 voicefile_size = 0;
675 return;
678 voicefile_size = filesize(filehandle);
680 #if CONFIG_CODEC == SWCODEC
681 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
682 #endif
683 reset_state(); /* use this for most of our inits */
685 #ifdef TALK_PARTIAL_LOAD
686 size_t bufsize;
687 char* buf = plugin_get_buffer(&bufsize);
688 /* we won't load the full file, we only need the index */
689 load_voicefile(true, buf, bufsize);
690 if (!p_voicefile)
691 return;
693 unsigned clips = p_voicefile->id1_max + p_voicefile->id2_max;
694 unsigned i;
695 int silence_size = 0;
697 for(i=0; i<clips; i++) {
698 int size = p_voicefile->index[i].size;
699 if (size > max_clipsize)
700 max_clipsize = size;
701 if (i == VOICE_PAUSE)
702 silence_size = size;
705 voicefile_size = p_voicefile->table + clips * sizeof(struct clip_entry);
706 voicefile_size += max_clipsize * QUEUE_SIZE + silence_size;
707 p_voicefile = NULL; /* Don't pretend we can load talk clips just yet */
708 #endif
711 /* test if we can open and if it fits in the audiobuffer */
712 size_t audiobufsz = buffer_available();
713 if (voicefile_size <= audiobufsz) {
714 has_voicefile = true;
715 } else {
716 has_voicefile = false;
717 voicefile_size = 0;
720 alloc_thumbnail_buf();
721 close(filehandle); /* close again, this was just to detect presence */
722 filehandle = -1;
725 #if CONFIG_CODEC == SWCODEC
726 /* return if a voice codec is required or not */
727 bool talk_voice_required(void)
729 return (voicefile_size != 0) /* Voice file is available */
730 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
731 || (global_settings.talk_file_clip);
733 #endif
735 /* return size of voice file */
736 int talk_get_buffer(void)
738 return voicefile_size;
741 /* Sets the buffer for the voicefile and returns how many bytes of this
742 * buffer we will use for the voicefile */
743 size_t talkbuf_init(char *bufstart)
745 bool changed = voicebuf != bufstart;
747 if (bufstart)
748 voicebuf = bufstart;
749 if (changed) /* must reload voice file */
750 reset_state();
752 return voicefile_size;
755 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
756 void talk_buffer_steal(void)
758 #if CONFIG_CODEC != SWCODEC
759 mp3_play_stop();
760 #endif
761 #if defined(TALK_PROGRESSIVE_LOAD) || defined(TALK_PARTIAL_LOAD)
762 if (filehandle >= 0)
764 close(filehandle);
765 filehandle = -1;
767 #endif
768 reset_state();
772 /* play a voice ID from voicefile */
773 int talk_id(int32_t id, bool enqueue)
775 long clipsize;
776 unsigned char* clipbuf;
777 int32_t unit;
778 int decimals;
780 if (talk_temp_disable_count > 0)
781 return -1; /* talking has been disabled */
782 #if CONFIG_CODEC != SWCODEC
783 if (audio_status()) /* busy, buffer in use */
784 return -1;
785 #endif
787 if (p_voicefile == NULL && has_voicefile)
788 load_voicefile(false, voicebuf, voicefile_size); /* reload needed */
790 if (p_voicefile == NULL) /* still no voices? */
791 return -1;
793 if (id == -1) /* -1 is an indication for silence */
794 return -1;
796 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
798 /* check if this is a special ID, with a value */
799 unit = ((uint32_t)id) >> UNIT_SHIFT;
800 if (unit || decimals)
801 { /* sign-extend the value */
802 id = (uint32_t)id << (32-DECIMAL_SHIFT);
803 id >>= (32-DECIMAL_SHIFT);
805 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
806 return 0; /* and stop, end of special case */
809 clipbuf = get_clip(id, &clipsize);
810 if (clipbuf == NULL)
811 return -1; /* not present */
813 #ifdef LOGF_ENABLE
814 if (id > VOICEONLY_DELIMITER)
815 logf("\ntalk_id: Say voice clip 0x%x\n", id);
816 else
817 logf("\ntalk_id: Say '%s'\n", str(id));
818 #endif
820 queue_clip(clipbuf, clipsize, enqueue);
822 return 0;
824 /* Speaks zero or more IDs (from an array). */
825 int talk_idarray(const long *ids, bool enqueue)
827 int r;
828 if(!ids)
829 return 0;
830 while(*ids != TALK_FINAL_ID)
832 if((r = talk_id(*ids++, enqueue)) <0)
833 return r;
834 enqueue = true;
836 return 0;
839 /* Make sure the current utterance is not interrupted by the next one. */
840 void talk_force_enqueue_next(void)
842 force_enqueue_next = true;
845 /* play a thumbnail from file */
846 /* Returns size of spoken thumbnail, so >0 means something is spoken,
847 <=0 means something went wrong. */
848 static int _talk_file(const char* filename,
849 const long *prefix_ids, bool enqueue)
851 int fd;
852 int size;
853 int thumb_used;
854 #if CONFIG_CODEC != SWCODEC
855 struct mp3entry info;
856 #endif
858 if (talk_temp_disable_count > 0)
859 return -1; /* talking has been disabled */
860 #if CONFIG_CODEC != SWCODEC
861 if (audio_status()) /* busy, buffer in use */
862 return -1;
863 #endif
865 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
866 alloc_thumbnail_buf();
868 #if CONFIG_CODEC != SWCODEC
869 if(mp3info(&info, filename)) /* use this to find real start */
871 return 0; /* failed to open, or invalid */
873 #endif
875 if (!enqueue)
876 /* shutup now to free the thumbnail buffer */
877 talk_shutup();
879 fd = open(filename, O_RDONLY);
880 if (fd < 0) /* failed to open */
882 return 0;
885 thumb_used = thumbnail_buf_used;
886 if(filesize(fd) > size_for_thumbnail -thumb_used)
887 { /* Don't play truncated clips */
888 close(fd);
889 return 0;
892 #if CONFIG_CODEC != SWCODEC
893 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
894 #endif
896 size = read(fd, p_thumbnail +thumb_used,
897 size_for_thumbnail -thumb_used);
898 close(fd);
900 /* ToDo: find audio, skip ID headers and trailers */
902 if (size > 0) /* Don't play missing clips */
904 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
905 bitswap(p_thumbnail, size);
906 #endif
907 if(prefix_ids)
908 /* prefix thumbnail by speaking these ids, but only now
909 that we know there's actually a thumbnail to be
910 spoken. */
911 talk_idarray(prefix_ids, true);
912 talk_queue_lock();
913 thumbnail_buf_used = thumb_used +size;
914 talk_queue_unlock();
915 queue_clip(p_thumbnail +thumb_used, size, true);
918 return size;
921 int talk_file(const char *root, const char *dir, const char *file,
922 const char *ext, const long *prefix_ids, bool enqueue)
923 /* Play a thumbnail file */
925 char buf[MAX_PATH];
926 /* Does root end with a slash */
927 char *slash = (root && root[0]
928 && root[strlen(root)-1] != '/') ? "/" : "";
929 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
930 root ? root : "", slash,
931 dir ? dir : "", dir ? "/" : "",
932 file ? file : "",
933 ext ? ext : "");
934 return _talk_file(buf, prefix_ids, enqueue);
937 static int talk_spell_basename(const char *path,
938 const long *prefix_ids, bool enqueue)
940 if(prefix_ids)
942 talk_idarray(prefix_ids, enqueue);
943 enqueue = true;
945 char buf[MAX_PATH];
946 /* Spell only the path component after the last slash */
947 strlcpy(buf, path, sizeof(buf));
948 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
949 /* strip trailing slash */
950 buf[strlen(buf)-1] = '\0';
951 char *ptr = strrchr(buf, '/');
952 if(ptr && strlen(buf) >1)
953 ++ptr;
954 else ptr = buf;
955 return talk_spell(ptr, enqueue);
958 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
959 go straight to spelling depending on settings. */
960 int talk_file_or_spell(const char *dirname, const char *filename,
961 const long *prefix_ids, bool enqueue)
963 if (global_settings.talk_file_clip)
964 { /* .talk clips enabled */
965 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
966 prefix_ids, enqueue) >0)
967 return 0;
969 if (global_settings.talk_file == 2)
970 /* Either .talk clips are disabled, or as a fallback */
971 return talk_spell_basename(filename, prefix_ids, enqueue);
972 return 0;
975 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
976 go straight to spelling depending on settings. */
977 int talk_dir_or_spell(const char* dirname,
978 const long *prefix_ids, bool enqueue)
980 if (global_settings.talk_dir_clip)
981 { /* .talk clips enabled */
982 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
983 prefix_ids, enqueue) >0)
984 return 0;
986 if (global_settings.talk_dir == 2)
987 /* Either .talk clips disabled or as a fallback */
988 return talk_spell_basename(dirname, prefix_ids, enqueue);
989 return 0;
992 /* say a numeric value, this word ordering works for english,
993 but not necessarily for other languages (e.g. german) */
994 int talk_number(long n, bool enqueue)
996 int level = 2; /* mille count */
997 long mil = 1000000000; /* highest possible "-illion" */
999 if (talk_temp_disable_count > 0)
1000 return -1; /* talking has been disabled */
1001 #if CONFIG_CODEC != SWCODEC
1002 if (audio_status()) /* busy, buffer in use */
1003 return -1;
1004 #endif
1006 if (!enqueue)
1007 talk_shutup(); /* cut off all the pending stuff */
1009 if (n==0)
1010 { /* special case */
1011 talk_id(VOICE_ZERO, true);
1012 return 0;
1015 if (n<0)
1017 talk_id(VOICE_MINUS, true);
1018 n = -n;
1021 while (n)
1023 int segment = n / mil; /* extract in groups of 3 digits */
1024 n -= segment * mil; /* remove the used digits from number */
1025 mil /= 1000; /* digit place for next round */
1027 if (segment)
1029 int hundreds = segment / 100;
1030 int ones = segment % 100;
1032 if (hundreds)
1034 talk_id(VOICE_ZERO + hundreds, true);
1035 talk_id(VOICE_HUNDRED, true);
1038 /* combination indexing */
1039 if (ones > 20)
1041 int tens = ones/10 + 18;
1042 talk_id(VOICE_ZERO + tens, true);
1043 ones %= 10;
1046 /* direct indexing */
1047 if (ones)
1048 talk_id(VOICE_ZERO + ones, true);
1050 /* add billion, million, thousand */
1051 if (mil)
1052 talk_id(VOICE_THOUSAND + level, true);
1054 level--;
1057 return 0;
1060 /* Say time duration/interval. Input is time in seconds,
1061 say hours,minutes,seconds. */
1062 static int talk_time_unit(long secs, bool enqueue)
1064 int hours, mins;
1065 if (!enqueue)
1066 talk_shutup();
1067 if((hours = secs/3600)) {
1068 secs %= 3600;
1069 talk_value(hours, UNIT_HOUR, true);
1071 if((mins = secs/60)) {
1072 secs %= 60;
1073 talk_value(mins, UNIT_MIN, true);
1075 if((secs) || (!hours && !mins))
1076 talk_value(secs, UNIT_SEC, true);
1077 else if(!hours && secs)
1078 talk_number(secs, true);
1079 return 0;
1082 void talk_fractional(char *tbuf, int value, int unit)
1084 int i;
1085 /* strip trailing zeros from the fraction */
1086 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
1087 tbuf[i] = '\0';
1089 talk_number(value, true);
1090 if (tbuf[0] != 0)
1092 talk_id(LANG_POINT, true);
1093 talk_spell(tbuf, true);
1095 talk_id(unit, true);
1098 int talk_value(long n, int unit, bool enqueue)
1100 return talk_value_decimal(n, unit, 0, enqueue);
1103 /* singular/plural aware saying of a value */
1104 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
1106 int unit_id;
1107 static const int unit_voiced[] =
1108 { /* lookup table for the voice ID of the units */
1109 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
1110 [UNIT_MS]
1111 = VOICE_MILLISECONDS, /* here come the "real" units */
1112 [UNIT_SEC]
1113 = VOICE_SECONDS,
1114 [UNIT_MIN]
1115 = VOICE_MINUTES,
1116 [UNIT_HOUR]
1117 = VOICE_HOURS,
1118 [UNIT_KHZ]
1119 = VOICE_KHZ,
1120 [UNIT_DB]
1121 = VOICE_DB,
1122 [UNIT_PERCENT]
1123 = VOICE_PERCENT,
1124 [UNIT_MAH]
1125 = VOICE_MILLIAMPHOURS,
1126 [UNIT_PIXEL]
1127 = VOICE_PIXEL,
1128 [UNIT_PER_SEC]
1129 = VOICE_PER_SEC,
1130 [UNIT_HERTZ]
1131 = VOICE_HERTZ,
1132 [UNIT_MB]
1133 = LANG_MEGABYTE,
1134 [UNIT_KBIT]
1135 = VOICE_KBIT_PER_SEC,
1136 [UNIT_PM_TICK]
1137 = VOICE_PM_UNITS_PER_TICK,
1140 static const int pow10[] = { /* 10^0 - 10^7 */
1141 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
1144 char tbuf[8];
1145 char fmt[] = "%0nd";
1147 if (talk_temp_disable_count > 0)
1148 return -1; /* talking has been disabled */
1149 #if CONFIG_CODEC != SWCODEC
1150 if (audio_status()) /* busy, buffer in use */
1151 return -1;
1152 #endif
1154 /* special case for time duration */
1155 if (unit == UNIT_TIME)
1156 return talk_time_unit(n, enqueue);
1158 if (unit < 0 || unit >= UNIT_LAST)
1159 unit_id = -1;
1160 else
1161 unit_id = unit_voiced[unit];
1163 if ((n==1 || n==-1) /* singular? */
1164 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
1166 unit_id--; /* use the singular for those units which have */
1169 /* special case with a "plus" before */
1170 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
1172 talk_id(VOICE_PLUS, enqueue);
1173 enqueue = true;
1176 if (decimals)
1178 /* needed for the "-0.5" corner case */
1179 if (n < 0)
1181 talk_id(VOICE_MINUS, enqueue);
1182 n = -n;
1185 fmt[2] = '0' + decimals;
1187 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
1188 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1190 return 0;
1193 talk_number(n, enqueue); /* say the number */
1194 talk_id(unit_id, true); /* say the unit, if any */
1196 return 0;
1199 /* spell a string */
1200 int talk_spell(const char* spell, bool enqueue)
1202 char c; /* currently processed char */
1204 if (talk_temp_disable_count > 0)
1205 return -1; /* talking has been disabled */
1206 #if CONFIG_CODEC != SWCODEC
1207 if (audio_status()) /* busy, buffer in use */
1208 return -1;
1209 #endif
1211 if (!enqueue)
1212 talk_shutup(); /* cut off all the pending stuff */
1214 while ((c = *spell++) != '\0')
1216 /* if this grows into too many cases, I should use a table */
1217 if (c >= 'A' && c <= 'Z')
1218 talk_id(VOICE_CHAR_A + c - 'A', true);
1219 else if (c >= 'a' && c <= 'z')
1220 talk_id(VOICE_CHAR_A + c - 'a', true);
1221 else if (c >= '0' && c <= '9')
1222 talk_id(VOICE_ZERO + c - '0', true);
1223 else if (c == '-')
1224 talk_id(VOICE_MINUS, true);
1225 else if (c == '+')
1226 talk_id(VOICE_PLUS, true);
1227 else if (c == '.')
1228 talk_id(VOICE_DOT, true);
1229 else if (c == ' ')
1230 talk_id(VOICE_PAUSE, true);
1231 else if (c == '/')
1232 talk_id(VOICE_CHAR_SLASH, true);
1235 return 0;
1238 void talk_disable(bool disable)
1240 if (disable)
1241 talk_temp_disable_count++;
1242 else
1243 talk_temp_disable_count--;
1246 void talk_setting(const void *global_settings_variable)
1248 const struct settings_list *setting;
1249 if (!global_settings.talk_menu)
1250 return;
1251 setting = find_setting(global_settings_variable, NULL);
1252 if (setting == NULL)
1253 return;
1254 if (setting->lang_id)
1255 talk_id(setting->lang_id,false);
1259 #if CONFIG_RTC
1260 void talk_date(const struct tm *tm, bool enqueue)
1262 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1263 talk_number(tm->tm_mday, true);
1264 talk_number(1900 + tm->tm_year, true);
1267 void talk_time(const struct tm *tm, bool enqueue)
1269 if (global_settings.timeformat == 1)
1271 /* Voice the hour */
1272 long am_pm_id = VOICE_AM;
1273 int hour = tm->tm_hour;
1274 if (hour >= 12)
1276 am_pm_id = VOICE_PM;
1277 hour -= 12;
1279 if (hour == 0)
1280 hour = 12;
1281 talk_number(hour, enqueue);
1283 /* Voice the minutes */
1284 if (tm->tm_min == 0)
1286 /* Say o'clock if the minute is 0. */
1287 talk_id(VOICE_OCLOCK, true);
1289 else
1291 /* Pronounce the leading 0 */
1292 if(tm->tm_min < 10)
1293 talk_id(VOICE_OH, true);
1294 talk_number(tm->tm_min, true);
1296 talk_id(am_pm_id, true);
1298 else
1300 /* Voice the time in 24 hour format */
1301 talk_number(tm->tm_hour, enqueue);
1302 if (tm->tm_min == 0)
1304 talk_id(VOICE_HUNDRED, true);
1305 talk_id(VOICE_HOUR, true);
1307 else
1309 /* Pronounce the leading 0 */
1310 if(tm->tm_min < 10)
1311 talk_id(VOICE_OH, true);
1312 talk_number(tm->tm_min, true);
1317 #endif /* CONFIG_RTC */