RTL language enhancements by Tomers Shalev and I.
[kugel-rb.git] / apps / talk.c
blobc7a7eab50a0fac5dffb2e3754e74f176bf8e197a
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.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 #include "logf.h"
41 #include "bitswap.h"
42 #include "structec.h"
43 #include "debug.h"
46 /* Memory layout varies between targets because the
47 Archos (MASCODEC) devices cannot mix voice and audio playback
49 MASCODEC | MASCODEC | SWCODEC
50 (playing) | (stopped) |
51 audiobuf-----------+-----------+------------
52 audio | voice | thumbnail
53 |-----------|------------
54 | thumbnail | voice
55 | |------------
56 | | filebuf
57 | |------------
58 | | audio
59 audiobufend----------+-----------+------------
61 SWCODEC allocates dedicated buffers, MASCODEC reuses audiobuf. */
64 /***************** Constants *****************/
66 #define QUEUE_SIZE 64 /* must be a power of two */
67 #define QUEUE_MASK (QUEUE_SIZE-1)
68 const char* const dir_thumbnail_name = "_dirname.talk";
69 const char* const file_thumbnail_ext = ".talk";
71 /***************** Functional Macros *****************/
73 #define QUEUE_LEVEL ((queue_write - queue_read) & QUEUE_MASK)
75 #define LOADED_MASK 0x80000000 /* MSB */
77 #if CONFIG_CODEC == SWCODEC
78 #define MAX_THUMBNAIL_BUFSIZE 0x10000
79 #endif
81 /***************** Data types *****************/
83 struct clip_entry /* one entry of the index table */
85 int offset; /* offset from start of voicefile file */
86 int size; /* size of the clip */
89 struct voicefile /* file format of our voice file */
91 int version; /* version of the voicefile */
92 int target_id; /* the rockbox target the file was made for */
93 int table; /* offset to index table, (=header size) */
94 int id1_max; /* number of "normal" clips contained in above index */
95 int id2_max; /* number of "voice only" clips contained in above index */
96 struct clip_entry index[]; /* followed by the index tables */
97 /* and finally the mp3 clips, not visible here, bitswapped
98 for SH based players */
101 struct queue_entry /* one entry of the internal queue */
103 unsigned char* buf;
104 long len;
108 /***************** Globals *****************/
110 static unsigned char* p_thumbnail = NULL; /* buffer for thumbnails */
111 /* Multiple thumbnails can be loaded back-to-back in this buffer. */
112 static volatile int thumbnail_buf_used SHAREDBSS_ATTR; /* length of data in
113 thumbnail buffer */
114 static long size_for_thumbnail; /* total thumbnail buffer size */
115 static struct voicefile* p_voicefile; /* loaded voicefile */
116 static bool has_voicefile; /* a voicefile file is present */
117 static bool need_shutup; /* is there possibly any voice playing to be shutup */
118 static struct queue_entry queue[QUEUE_SIZE]; /* queue of scheduled clips */
119 static bool force_enqueue_next; /* enqueue next utterance even if enqueue is false */
120 static int queue_write; /* write index of queue, by application */
121 static int queue_read; /* read index of queue, by ISR context */
122 #if CONFIG_CODEC == SWCODEC
123 struct mutex queue_mutex SHAREDBSS_ATTR; /* protects queue_read, queue_write
124 and thumbnail_buf_used */
125 #define talk_queue_lock() ({ mutex_lock(&queue_mutex); })
126 #define talk_queue_unlock() ({ mutex_unlock(&queue_mutex); })
127 #else
128 #define talk_queue_lock() ({ })
129 #define talk_queue_unlock() ({ })
130 #endif /* CONFIG_CODEC */
131 static int sent; /* how many bytes handed over to playback, owned by ISR */
132 static unsigned char curr_hd[3]; /* current frame header, for re-sync */
133 static int filehandle = -1; /* global, so the MMC variant can keep the file open */
134 static unsigned char* p_silence; /* VOICE_PAUSE clip, used for termination */
135 static long silence_len; /* length of the VOICE_PAUSE clip */
136 static unsigned char* p_lastclip; /* address of latest clip, for silence add */
137 static unsigned long voicefile_size = 0; /* size of the loaded voice file */
138 static unsigned char last_lang[MAX_FILENAME+1]; /* name of last used lang file (in talk_init) */
139 static bool talk_initialized; /* true if talk_init has been called */
140 static int talk_temp_disable_count; /* if positive, temporarily disable voice UI (not saved) */
143 /***************** Private implementation *****************/
145 static int open_voicefile(void)
147 char buf[64];
148 char* p_lang = "english"; /* default */
150 if ( global_settings.lang_file[0] &&
151 global_settings.lang_file[0] != 0xff )
152 { /* try to open the voice file of the selected language */
153 p_lang = (char *)global_settings.lang_file;
156 snprintf(buf, sizeof(buf), LANG_DIR "/%s.voice", p_lang);
158 return open(buf, O_RDONLY);
162 /* fetch a clip from the voice file */
163 static unsigned char* get_clip(long id, long* p_size)
165 long clipsize;
166 unsigned char* clipbuf;
168 if (id > VOICEONLY_DELIMITER)
169 { /* voice-only entries use the second part of the table */
170 id -= VOICEONLY_DELIMITER + 1;
171 if (id >= p_voicefile->id2_max)
172 return NULL; /* must be newer than we have */
173 id += p_voicefile->id1_max; /* table 2 is behind table 1 */
175 else
176 { /* normal use of the first table */
177 if (id >= p_voicefile->id1_max)
178 return NULL; /* must be newer than we have */
181 clipsize = p_voicefile->index[id].size;
182 if (clipsize == 0) /* clip not included in voicefile */
183 return NULL;
184 clipbuf = (unsigned char *) p_voicefile + p_voicefile->index[id].offset;
186 #if (CONFIG_STORAGE & STORAGE_MMC) /* dynamic loading, on demand */
187 if (!(clipsize & LOADED_MASK))
188 { /* clip used for the first time, needs loading */
189 lseek(filehandle, p_voicefile->index[id].offset, SEEK_SET);
190 if (read(filehandle, clipbuf, clipsize) != clipsize)
191 return NULL; /* read error */
193 p_voicefile->index[id].size |= LOADED_MASK; /* mark as loaded */
195 else
196 { /* clip is in memory already */
197 clipsize &= ~LOADED_MASK; /* without the extra bit gives true size */
199 #endif
201 *p_size = clipsize;
202 return clipbuf;
206 /* load the voice file into the mp3 buffer */
207 static void load_voicefile(void)
209 int load_size;
210 int got_size;
211 int file_size;
212 #ifdef ROCKBOX_LITTLE_ENDIAN
213 int i;
214 #endif
216 filehandle = open_voicefile();
217 if (filehandle < 0) /* failed to open */
218 goto load_err;
220 file_size = filesize(filehandle);
221 if (file_size > audiobufend - audiobuf) /* won't fit? */
222 goto load_err;
224 #if (CONFIG_STORAGE & STORAGE_MMC) /* load only the header for now */
225 load_size = offsetof(struct voicefile, index);
226 #else /* load the full file */
227 load_size = file_size;
228 #endif
230 got_size = read(filehandle, audiobuf, load_size);
231 if (got_size != load_size /* failure */)
232 goto load_err;
234 #ifdef ROCKBOX_LITTLE_ENDIAN
235 logf("Byte swapping voice file");
236 structec_convert(audiobuf, "lllll", 1, true);
237 #endif
239 if (((struct voicefile*)audiobuf)->table /* format check */
240 == offsetof(struct voicefile, index))
242 p_voicefile = (struct voicefile*)audiobuf;
244 if (p_voicefile->version != VOICE_VERSION ||
245 p_voicefile->target_id != TARGET_ID)
247 logf("Incompatible voice file");
248 goto load_err;
250 #if CONFIG_CODEC != SWCODEC
251 /* MASCODEC: now use audiobuf for voice then thumbnail */
252 p_thumbnail = audiobuf + file_size;
253 p_thumbnail += (long)p_thumbnail % 2; /* 16-bit align */
254 size_for_thumbnail = audiobufend - p_thumbnail;
255 #endif
257 else
258 goto load_err;
260 #ifdef ROCKBOX_LITTLE_ENDIAN
261 for (i = 0; i < p_voicefile->id1_max + p_voicefile->id2_max; i++)
262 structec_convert(&p_voicefile->index[i], "ll", 1, true);
263 #endif
265 #if (CONFIG_STORAGE & STORAGE_MMC)
266 /* load the index table, now that we know its size from the header */
267 load_size = (p_voicefile->id1_max + p_voicefile->id2_max)
268 * sizeof(struct clip_entry);
269 got_size = read(filehandle,
270 (unsigned char *) p_voicefile + offsetof(struct voicefile, index), load_size);
271 if (got_size != load_size) /* read error */
272 goto load_err;
273 #else
274 close(filehandle); /* only the MMC variant leaves it open */
275 filehandle = -1;
276 #endif
278 /* make sure to have the silence clip, if available */
279 p_silence = get_clip(VOICE_PAUSE, &silence_len);
281 return;
283 load_err:
284 p_voicefile = NULL;
285 has_voicefile = false; /* don't try again */
286 if (filehandle >= 0)
288 close(filehandle);
289 filehandle = -1;
291 return;
295 /* called in ISR context if mp3 data got consumed */
296 static void mp3_callback(unsigned char** start, size_t* size)
298 queue[queue_read].len -= sent; /* we completed this */
299 queue[queue_read].buf += sent;
301 if (queue[queue_read].len > 0) /* current clip not finished? */
302 { /* feed the next 64K-1 chunk */
303 #if CONFIG_CODEC != SWCODEC
304 sent = MIN(queue[queue_read].len, 0xFFFF);
305 #else
306 sent = queue[queue_read].len;
307 #endif
308 *start = queue[queue_read].buf;
309 *size = sent;
310 return;
312 talk_queue_lock();
313 if(p_thumbnail
314 && queue[queue_read].buf == p_thumbnail +thumbnail_buf_used)
315 thumbnail_buf_used = 0;
316 if (sent > 0) /* go to next entry */
318 queue_read = (queue_read + 1) & QUEUE_MASK;
321 re_check:
323 if (QUEUE_LEVEL != 0) /* queue is not empty? */
324 { /* start next clip */
325 #if CONFIG_CODEC != SWCODEC
326 sent = MIN(queue[queue_read].len, 0xFFFF);
327 #else
328 sent = queue[queue_read].len;
329 #endif
330 *start = p_lastclip = queue[queue_read].buf;
331 *size = sent;
332 curr_hd[0] = p_lastclip[1];
333 curr_hd[1] = p_lastclip[2];
334 curr_hd[2] = p_lastclip[3];
336 else if (p_silence != NULL /* silence clip available */
337 && p_lastclip != p_silence /* previous clip wasn't silence */
338 && !(p_lastclip >= p_thumbnail /* ..or thumbnail */
339 && p_lastclip < p_thumbnail +size_for_thumbnail))
340 { /* add silence clip when queue runs empty playing a voice clip */
341 queue[queue_write].buf = p_silence;
342 queue[queue_write].len = silence_len;
343 queue_write = (queue_write + 1) & QUEUE_MASK;
345 goto re_check;
347 else
349 *size = 0; /* end of data */
351 talk_queue_unlock();
354 /***************** Public routines *****************/
356 /* stop the playback and the pending clips */
357 void talk_force_shutup(void)
359 /* Most of this is MAS only */
360 #if CONFIG_CODEC != SWCODEC
361 #ifdef SIMULATOR
362 return;
363 #endif
364 unsigned char* pos;
365 unsigned char* search;
366 unsigned char* end;
367 if (QUEUE_LEVEL == 0) /* has ended anyway */
368 return;
370 #if CONFIG_CPU == SH7034
371 CHCR3 &= ~0x0001; /* disable the DMA (and therefore the interrupt also) */
372 #endif /* CONFIG_CPU == SH7034 */
373 /* search next frame boundary and continue up to there */
374 pos = search = mp3_get_pos();
375 end = queue[queue_read].buf + queue[queue_read].len;
377 if (pos >= queue[queue_read].buf
378 && pos <= end) /* really our clip? */
379 { /* (for strange reasons this isn't nesessarily the case) */
380 /* find the next frame boundary */
381 while (search < end) /* search the remaining data */
383 if (*search++ != 0xFF) /* quick search for frame sync byte */
384 continue; /* (this does the majority of the job) */
386 /* look at the (bitswapped) rest of header candidate */
387 if (search[0] == curr_hd[0] /* do the quicker checks first */
388 && search[2] == curr_hd[2]
389 && (search[1] & 0x30) == (curr_hd[1] & 0x30)) /* sample rate */
391 search--; /* back to the sync byte */
392 break; /* From looking at it, this is our header. */
396 if (search-pos)
397 { /* play old data until the frame end, to keep the MAS in sync */
398 sent = search-pos;
400 queue_write = (queue_read + 1) & QUEUE_MASK; /* will be empty after next callback */
401 queue[queue_read].len = sent; /* current one ends after this */
403 #if CONFIG_CPU == SH7034
404 DTCR3 = sent; /* let the DMA finish this frame */
405 CHCR3 |= 0x0001; /* re-enable DMA */
406 #endif /* CONFIG_CPU == SH7034 */
407 thumbnail_buf_used = 0;
408 return;
411 #endif /* CONFIG_CODEC != SWCODEC */
413 /* Either SWCODEC, or MAS had nothing to do (was frame boundary or not our clip) */
414 mp3_play_stop();
415 talk_queue_lock();
416 queue_write = queue_read = 0; /* reset the queue */
417 thumbnail_buf_used = 0;
418 talk_queue_unlock();
419 need_shutup = false;
422 /* Shutup the voice, except if force_enqueue_next is set. */
423 void talk_shutup(void)
425 if (need_shutup && !force_enqueue_next)
426 talk_force_shutup();
429 /* schedule a clip, at the end or discard the existing queue */
430 static void queue_clip(unsigned char* buf, long size, bool enqueue)
432 int queue_level;
434 if (!enqueue)
435 talk_shutup(); /* cut off all the pending stuff */
436 /* Something is being enqueued, force_enqueue_next override is no
437 longer in effect. */
438 force_enqueue_next = false;
440 if (!size)
441 return; /* safety check */
442 #if CONFIG_CPU == SH7034
443 /* disable the DMA temporarily, to be safe of race condition */
444 CHCR3 &= ~0x0001;
445 #endif
446 talk_queue_lock();
447 queue_level = QUEUE_LEVEL; /* check old level */
449 if (queue_level < QUEUE_SIZE - 1) /* space left? */
451 queue[queue_write].buf = buf; /* populate an entry */
452 queue[queue_write].len = size;
453 queue_write = (queue_write + 1) & QUEUE_MASK;
455 talk_queue_unlock();
457 if (queue_level == 0)
458 { /* queue was empty, we have to do the initial start */
459 p_lastclip = buf;
460 #if CONFIG_CODEC != SWCODEC
461 sent = MIN(size, 0xFFFF); /* DMA can do no more */
462 #else
463 sent = size;
464 #endif
465 mp3_play_data(buf, sent, mp3_callback);
466 curr_hd[0] = buf[1];
467 curr_hd[1] = buf[2];
468 curr_hd[2] = buf[3];
469 mp3_play_pause(true); /* kickoff audio */
471 else
473 #if CONFIG_CPU == SH7034
474 CHCR3 |= 0x0001; /* re-enable DMA */
475 #endif
478 need_shutup = true;
480 return;
484 /* common code for talk_init() and talk_buffer_steal() */
485 static void reset_state(void)
487 queue_write = queue_read = 0; /* reset the queue */
488 p_voicefile = NULL; /* indicate no voicefile (trashed) */
489 #if CONFIG_CODEC == SWCODEC
490 /* Allocate a dedicated thumbnail buffer - once */
491 if (p_thumbnail == NULL)
493 size_for_thumbnail = audiobufend - audiobuf;
494 if (size_for_thumbnail > MAX_THUMBNAIL_BUFSIZE)
495 size_for_thumbnail = MAX_THUMBNAIL_BUFSIZE;
496 p_thumbnail = buffer_alloc(size_for_thumbnail);
498 #else
499 /* Just use the audiobuf, without allocating anything */
500 p_thumbnail = audiobuf;
501 size_for_thumbnail = audiobufend - audiobuf;
502 #endif
503 thumbnail_buf_used = 0;
504 p_silence = NULL; /* pause clip not accessible */
508 /***************** Public implementation *****************/
510 void talk_init(void)
512 talk_temp_disable_count = 0;
513 if (talk_initialized && !strcasecmp(last_lang, global_settings.lang_file))
515 /* not a new file, nothing to do */
516 return;
519 #if (CONFIG_STORAGE & STORAGE_MMC)
520 if (filehandle >= 0) /* MMC: An old voice file might still be open */
522 close(filehandle);
523 filehandle = -1;
525 #endif
527 #if CONFIG_CODEC == SWCODEC
528 if(!talk_initialized)
529 mutex_init(&queue_mutex);
530 #endif /* CONFIG_CODEC == SWCODEC */
532 talk_initialized = true;
533 strlcpy((char *)last_lang, (char *)global_settings.lang_file,
534 MAX_FILENAME);
536 #if CONFIG_CODEC == SWCODEC
537 audio_get_buffer(false, NULL); /* Must tell audio to reinitialize */
538 #endif
539 reset_state(); /* use this for most of our inits */
541 filehandle = open_voicefile();
542 has_voicefile = (filehandle >= 0); /* test if we can open it */
543 voicefile_size = 0;
545 if (has_voicefile)
547 voicefile_size = filesize(filehandle);
548 close(filehandle); /* close again, this was just to detect presence */
549 filehandle = -1;
554 #if CONFIG_CODEC == SWCODEC
555 /* return if a voice codec is required or not */
556 bool talk_voice_required(void)
558 return (voicefile_size != 0) /* Voice file is available */
559 || (global_settings.talk_dir_clip) /* Thumbnail clips are required */
560 || (global_settings.talk_file_clip);
562 #endif
564 /* return size of voice file */
565 int talk_get_bufsize(void)
567 return voicefile_size;
570 /* somebody else claims the mp3 buffer, e.g. for regular play/record */
571 void talk_buffer_steal(void)
573 #if CONFIG_CODEC != SWCODEC
574 mp3_play_stop();
575 #endif
576 #if (CONFIG_STORAGE & STORAGE_MMC)
577 if (filehandle >= 0) /* only relevant for MMC */
579 close(filehandle);
580 filehandle = -1;
582 #endif
583 reset_state();
587 /* play a voice ID from voicefile */
588 int talk_id(int32_t id, bool enqueue)
590 long clipsize;
591 unsigned char* clipbuf;
592 int32_t unit;
593 int decimals;
595 if (talk_temp_disable_count > 0)
596 return -1; /* talking has been disabled */
597 #if CONFIG_CODEC != SWCODEC
598 if (audio_status()) /* busy, buffer in use */
599 return -1;
600 #endif
602 if (p_voicefile == NULL && has_voicefile)
603 load_voicefile(); /* reload needed */
605 if (p_voicefile == NULL) /* still no voices? */
606 return -1;
608 if (id == -1) /* -1 is an indication for silence */
609 return -1;
611 decimals = (((uint32_t)id) >> DECIMAL_SHIFT) & 0x7;
613 /* check if this is a special ID, with a value */
614 unit = ((uint32_t)id) >> UNIT_SHIFT;
615 if (unit || decimals)
616 { /* sign-extend the value */
617 id = (uint32_t)id << (32-DECIMAL_SHIFT);
618 id >>= (32-DECIMAL_SHIFT);
620 talk_value_decimal(id, unit, decimals, enqueue); /* speak it */
621 return 0; /* and stop, end of special case */
624 clipbuf = get_clip(id, &clipsize);
625 if (clipbuf == NULL)
626 return -1; /* not present */
628 queue_clip(clipbuf, clipsize, enqueue);
630 return 0;
632 /* Speaks zero or more IDs (from an array). */
633 int talk_idarray(const long *ids, bool enqueue)
635 int r;
636 if(!ids)
637 return 0;
638 while(*ids != TALK_FINAL_ID)
640 if((r = talk_id(*ids++, enqueue)) <0)
641 return r;
642 enqueue = true;
644 return 0;
647 /* Make sure the current utterance is not interrupted by the next one. */
648 void talk_force_enqueue_next(void)
650 force_enqueue_next = true;
653 /* play a thumbnail from file */
654 /* Returns size of spoken thumbnail, so >0 means something is spoken,
655 <=0 means something went wrong. */
656 static int _talk_file(const char* filename,
657 const long *prefix_ids, bool enqueue)
659 int fd;
660 int size;
661 int thumb_used;
662 #if CONFIG_CODEC != SWCODEC
663 struct mp3entry info;
664 #endif
666 if (talk_temp_disable_count > 0)
667 return -1; /* talking has been disabled */
668 #if CONFIG_CODEC != SWCODEC
669 if (audio_status()) /* busy, buffer in use */
670 return -1;
671 #endif
673 if (p_thumbnail == NULL || size_for_thumbnail <= 0)
674 return -1;
676 #if CONFIG_CODEC != SWCODEC
677 if(mp3info(&info, filename)) /* use this to find real start */
679 return 0; /* failed to open, or invalid */
681 #endif
683 if (!enqueue)
684 /* shutup now to free the thumbnail buffer */
685 talk_shutup();
687 fd = open(filename, O_RDONLY);
688 if (fd < 0) /* failed to open */
690 return 0;
693 thumb_used = thumbnail_buf_used;
694 if(filesize(fd) > size_for_thumbnail -thumb_used)
695 { /* Don't play truncated clips */
696 close(fd);
697 return 0;
700 #if CONFIG_CODEC != SWCODEC
701 lseek(fd, info.first_frame_offset, SEEK_SET); /* behind ID data */
702 #endif
704 size = read(fd, p_thumbnail +thumb_used,
705 size_for_thumbnail -thumb_used);
706 close(fd);
708 /* ToDo: find audio, skip ID headers and trailers */
710 if (size > 0) /* Don't play missing clips */
712 #if CONFIG_CODEC != SWCODEC && !defined(SIMULATOR)
713 bitswap(p_thumbnail, size);
714 #endif
715 if(prefix_ids)
716 /* prefix thumbnail by speaking these ids, but only now
717 that we know there's actually a thumbnail to be
718 spoken. */
719 talk_idarray(prefix_ids, true);
720 talk_queue_lock();
721 thumbnail_buf_used = thumb_used +size;
722 talk_queue_unlock();
723 queue_clip(p_thumbnail +thumb_used, size, true);
726 return size;
729 int talk_file(const char *root, const char *dir, const char *file,
730 const char *ext, const long *prefix_ids, bool enqueue)
731 /* Play a thumbnail file */
733 char buf[MAX_PATH];
734 /* Does root end with a slash */
735 char *slash = (root && root[0]
736 && root[strlen(root)-1] != '/') ? "/" : "";
737 snprintf(buf, MAX_PATH, "%s%s%s%s%s%s",
738 root ? root : "", slash,
739 dir ? dir : "", dir ? "/" : "",
740 file ? file : "",
741 ext ? ext : "");
742 return _talk_file(buf, prefix_ids, enqueue);
745 static int talk_spell_basename(const char *path,
746 const long *prefix_ids, bool enqueue)
748 if(prefix_ids)
750 talk_idarray(prefix_ids, enqueue);
751 enqueue = true;
753 char buf[MAX_PATH];
754 /* Spell only the path component after the last slash */
755 strlcpy(buf, path, sizeof(buf));
756 if(strlen(buf) >1 && buf[strlen(buf)-1] == '/')
757 /* strip trailing slash */
758 buf[strlen(buf)-1] = '\0';
759 char *ptr = strrchr(buf, '/');
760 if(ptr && strlen(buf) >1)
761 ++ptr;
762 else ptr = buf;
763 return talk_spell(ptr, enqueue);
766 /* Play a file's .talk thumbnail, fallback to spelling the filename, or
767 go straight to spelling depending on settings. */
768 int talk_file_or_spell(const char *dirname, const char *filename,
769 const long *prefix_ids, bool enqueue)
771 if (global_settings.talk_file_clip)
772 { /* .talk clips enabled */
773 if(talk_file(dirname, NULL, filename, file_thumbnail_ext,
774 prefix_ids, enqueue) >0)
775 return 0;
777 if (global_settings.talk_file == 2)
778 /* Either .talk clips are disabled, or as a fallback */
779 return talk_spell_basename(filename, prefix_ids, enqueue);
780 return 0;
783 /* Play a directory's .talk thumbnail, fallback to spelling the filename, or
784 go straight to spelling depending on settings. */
785 int talk_dir_or_spell(const char* dirname,
786 const long *prefix_ids, bool enqueue)
788 if (global_settings.talk_dir_clip)
789 { /* .talk clips enabled */
790 if(talk_file(dirname, NULL, dir_thumbnail_name, NULL,
791 prefix_ids, enqueue) >0)
792 return 0;
794 if (global_settings.talk_dir == 2)
795 /* Either .talk clips disabled or as a fallback */
796 return talk_spell_basename(dirname, prefix_ids, enqueue);
797 return 0;
800 /* say a numeric value, this word ordering works for english,
801 but not necessarily for other languages (e.g. german) */
802 int talk_number(long n, bool enqueue)
804 int level = 2; /* mille count */
805 long mil = 1000000000; /* highest possible "-illion" */
807 if (talk_temp_disable_count > 0)
808 return -1; /* talking has been disabled */
809 #if CONFIG_CODEC != SWCODEC
810 if (audio_status()) /* busy, buffer in use */
811 return -1;
812 #endif
814 if (!enqueue)
815 talk_shutup(); /* cut off all the pending stuff */
817 if (n==0)
818 { /* special case */
819 talk_id(VOICE_ZERO, true);
820 return 0;
823 if (n<0)
825 talk_id(VOICE_MINUS, true);
826 n = -n;
829 while (n)
831 int segment = n / mil; /* extract in groups of 3 digits */
832 n -= segment * mil; /* remove the used digits from number */
833 mil /= 1000; /* digit place for next round */
835 if (segment)
837 int hundreds = segment / 100;
838 int ones = segment % 100;
840 if (hundreds)
842 talk_id(VOICE_ZERO + hundreds, true);
843 talk_id(VOICE_HUNDRED, true);
846 /* combination indexing */
847 if (ones > 20)
849 int tens = ones/10 + 18;
850 talk_id(VOICE_ZERO + tens, true);
851 ones %= 10;
854 /* direct indexing */
855 if (ones)
856 talk_id(VOICE_ZERO + ones, true);
858 /* add billion, million, thousand */
859 if (mil)
860 talk_id(VOICE_THOUSAND + level, true);
862 level--;
865 return 0;
868 /* Say time duration/interval. Input is time in seconds,
869 say hours,minutes,seconds. */
870 static int talk_time_unit(long secs, bool exact, bool enqueue)
872 int hours, mins;
873 if (!enqueue)
874 talk_shutup();
875 if((hours = secs/3600)) {
876 secs %= 3600;
877 talk_value(hours, UNIT_HOUR, true);
879 if((mins = secs/60)) {
880 secs %= 60;
881 if(exact || !hours)
882 talk_value(mins, UNIT_MIN, true);
883 else talk_number(mins, true); /* don't say "minutes" */
885 if((exact && secs) || (!hours && !mins))
886 talk_value(secs, UNIT_SEC, true);
887 else if(!hours && secs)
888 talk_number(secs, true);
889 return 0;
892 void talk_fractional(char *tbuf, int value, int unit)
894 int i;
895 /* strip trailing zeros from the fraction */
896 for (i = strlen(tbuf) - 1; (i >= 0) && (tbuf[i] == '0'); i--)
897 tbuf[i] = '\0';
899 talk_number(value, true);
900 if (tbuf[0] != 0)
902 talk_id(LANG_POINT, true);
903 talk_spell(tbuf, true);
905 talk_id(unit, true);
908 int talk_value(long n, int unit, bool enqueue)
910 return talk_value_decimal(n, unit, 0, enqueue);
913 /* singular/plural aware saying of a value */
914 int talk_value_decimal(long n, int unit, int decimals, bool enqueue)
916 int unit_id;
917 static const int unit_voiced[] =
918 { /* lookup table for the voice ID of the units */
919 [0 ... UNIT_LAST-1] = -1, /* regular ID, int, signed */
920 [UNIT_MS]
921 = VOICE_MILLISECONDS, /* here come the "real" units */
922 [UNIT_SEC]
923 = VOICE_SECONDS,
924 [UNIT_MIN]
925 = VOICE_MINUTES,
926 [UNIT_HOUR]
927 = VOICE_HOURS,
928 [UNIT_KHZ]
929 = VOICE_KHZ,
930 [UNIT_DB]
931 = VOICE_DB,
932 [UNIT_PERCENT]
933 = VOICE_PERCENT,
934 [UNIT_MAH]
935 = VOICE_MILLIAMPHOURS,
936 [UNIT_PIXEL]
937 = VOICE_PIXEL,
938 [UNIT_PER_SEC]
939 = VOICE_PER_SEC,
940 [UNIT_HERTZ]
941 = VOICE_HERTZ,
942 [UNIT_MB]
943 = LANG_MEGABYTE,
944 [UNIT_KBIT]
945 = VOICE_KBIT_PER_SEC,
946 [UNIT_PM_TICK]
947 = VOICE_PM_UNITS_PER_TICK,
950 static const int pow10[] = { /* 10^0 - 10^7 */
951 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000
954 char tbuf[8];
955 char fmt[] = "%0nd";
957 if (talk_temp_disable_count > 0)
958 return -1; /* talking has been disabled */
959 #if CONFIG_CODEC != SWCODEC
960 if (audio_status()) /* busy, buffer in use */
961 return -1;
962 #endif
964 /* special case for time duration */
965 if (unit == UNIT_TIME || unit == UNIT_TIME_EXACT)
966 return talk_time_unit(n, unit == UNIT_TIME_EXACT, enqueue);
968 if (unit < 0 || unit >= UNIT_LAST)
969 unit_id = -1;
970 else
971 unit_id = unit_voiced[unit];
973 if ((n==1 || n==-1) /* singular? */
974 && unit_id >= VOICE_SECONDS && unit_id <= VOICE_HOURS)
976 unit_id--; /* use the singular for those units which have */
979 /* special case with a "plus" before */
980 if (n > 0 && (unit == UNIT_SIGNED || unit == UNIT_DB))
982 talk_id(VOICE_PLUS, enqueue);
983 enqueue = true;
986 if (decimals)
988 /* needed for the "-0.5" corner case */
989 if (n < 0)
991 talk_id(VOICE_MINUS, enqueue);
992 n = -n;
995 fmt[2] = '0' + decimals;
997 snprintf(tbuf, sizeof(tbuf), fmt, n % pow10[decimals]);
998 talk_fractional(tbuf, n / pow10[decimals], unit_id);
1000 return 0;
1003 talk_number(n, enqueue); /* say the number */
1004 talk_id(unit_id, true); /* say the unit, if any */
1006 return 0;
1009 /* spell a string */
1010 int talk_spell(const char* spell, bool enqueue)
1012 char c; /* currently processed char */
1014 if (talk_temp_disable_count > 0)
1015 return -1; /* talking has been disabled */
1016 #if CONFIG_CODEC != SWCODEC
1017 if (audio_status()) /* busy, buffer in use */
1018 return -1;
1019 #endif
1021 if (!enqueue)
1022 talk_shutup(); /* cut off all the pending stuff */
1024 while ((c = *spell++) != '\0')
1026 /* if this grows into too many cases, I should use a table */
1027 if (c >= 'A' && c <= 'Z')
1028 talk_id(VOICE_CHAR_A + c - 'A', true);
1029 else if (c >= 'a' && c <= 'z')
1030 talk_id(VOICE_CHAR_A + c - 'a', true);
1031 else if (c >= '0' && c <= '9')
1032 talk_id(VOICE_ZERO + c - '0', true);
1033 else if (c == '-')
1034 talk_id(VOICE_MINUS, true);
1035 else if (c == '+')
1036 talk_id(VOICE_PLUS, true);
1037 else if (c == '.')
1038 talk_id(VOICE_DOT, true);
1039 else if (c == ' ')
1040 talk_id(VOICE_PAUSE, true);
1041 else if (c == '/')
1042 talk_id(VOICE_CHAR_SLASH, true);
1045 return 0;
1048 void talk_disable(bool disable)
1050 if (disable)
1051 talk_temp_disable_count++;
1052 else
1053 talk_temp_disable_count--;
1056 void talk_setting(const void *global_settings_variable)
1058 const struct settings_list *setting;
1059 if (!global_settings.talk_menu)
1060 return;
1061 setting = find_setting(global_settings_variable, NULL);
1062 if (setting == NULL)
1063 return;
1064 if (setting->lang_id)
1065 talk_id(setting->lang_id,false);
1069 #if CONFIG_RTC
1070 void talk_date(const struct tm *tm, bool enqueue)
1072 talk_id(LANG_MONTH_JANUARY + tm->tm_mon, enqueue);
1073 talk_number(tm->tm_mday, true);
1074 talk_number(1900 + tm->tm_year, true);
1077 void talk_time(const struct tm *tm, bool enqueue)
1079 if (global_settings.timeformat == 1)
1081 /* Voice the hour */
1082 long am_pm_id = VOICE_AM;
1083 int hour = tm->tm_hour;
1084 if (hour >= 12)
1086 am_pm_id = VOICE_PM;
1087 hour -= 12;
1089 if (hour == 0)
1090 hour = 12;
1091 talk_number(hour, enqueue);
1093 /* Voice the minutes */
1094 if (tm->tm_min == 0)
1096 /* Say o'clock if the minute is 0. */
1097 talk_id(VOICE_OCLOCK, true);
1099 else
1101 /* Pronounce the leading 0 */
1102 if(tm->tm_min < 10)
1103 talk_id(VOICE_OH, true);
1104 talk_number(tm->tm_min, true);
1106 talk_id(am_pm_id, true);
1108 else
1110 /* Voice the time in 24 hour format */
1111 talk_number(tm->tm_hour, enqueue);
1112 if (tm->tm_min == 0)
1114 talk_id(VOICE_HUNDRED, true);
1115 talk_id(VOICE_HOUR, true);
1117 else
1119 /* Pronounce the leading 0 */
1120 if(tm->tm_min < 10)
1121 talk_id(VOICE_OH, true);
1122 talk_number(tm->tm_min, true);
1127 #endif